diff --git a/inferredbugs-0023/instruction.md b/inferredbugs-0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2236fcfc01503283f5c239f52f0975a6d310874 --- /dev/null +++ b/inferredbugs-0023/instruction.md @@ -0,0 +1,270 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** UABEA +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using AssetsTools.NET; +using AssetsTools.NET.Extra; +using Avalonia; +using Avalonia.Collections; +using Avalonia.Controls; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace UABEAvalonia +{ + public class AssetDataTreeView : TreeView + { + private AssetWorkspace workspace; + + private AvaloniaList ListItems => (AvaloniaList)Items; + + public void Init(AssetWorkspace workspace) + { + this.workspace = workspace; + Reset(); + } + + public void Reset() + { + Items = new AvaloniaList(); + } + + public void LoadComponent(AssetContainer container) + { + if (workspace == null) + return; + + AssetTypeValueField baseField = workspace.GetBaseField(container); + TreeViewItem baseItem = CreateTreeItem($"{baseField.GetFieldType()} {baseField.GetName()}"); + + TreeViewItem arrayIndexTreeItem = CreateTreeItem("Loading..."); + baseItem.Items = new AvaloniaList() { arrayIndexTreeItem }; + ListItems.Add(baseItem); + + SetTreeItemEvents(baseItem, container.FileInstance, container.PathId, baseField); + baseItem.IsExpanded = true; + } + + private TreeViewItem CreateTreeItem(string text) + { + return new TreeViewItem() { Header = text }; + } + + //lazy load tree items. avalonia is really slow to load if + //we just throw everything in the treeview at once + private void SetTreeItemEvents(TreeViewItem item, AssetsFileInstance fromFile, long fromPathId, AssetTypeValueField field) + { + item.Tag = new AssetDataTreeViewItem(fromFile, fromPathId); + //avalonia's treeviews have no Expanded event so this is all we can do + var expandObs = item.GetObservable(TreeViewItem.IsExpandedProperty); + expandObs.Subscribe(isExpanded => + { + AssetDataTreeViewItem itemInfo = (AssetDataTreeViewItem)item.Tag; + if (isExpanded && !itemInfo.loaded) + { + itemInfo.loaded = true; //don't load this again + TreeLoad(fromFile, field, fromPathId, item); + } + }); + } + + private void SetPPtrEvents(TreeViewItem item, AssetsFileInstance fromFile, long fromPathId, AssetContainer cont) + { + item.Tag = new AssetDataTreeViewItem(fromFile, fromPathId); + var expandObs = item.GetObservable(TreeViewItem.IsExpandedProperty); + expandObs.Subscribe(isExpanded => + { + AssetDataTreeViewItem itemInfo = (AssetDataTreeViewItem)item.Tag; + if (isExpanded && !itemInfo.loaded) + { + itemInfo.loaded = true; //don't load this again + + if (cont != null) + { + AssetTypeValueField baseField = workspace.GetBaseField(cont); + TreeViewItem baseItem = CreateTreeItem($"{baseField.GetFieldType()} {baseField.GetName()}"); + + TreeViewItem arrayIndexTreeItem = CreateTreeItem("Loading..."); + baseItem.Items = new List() { arrayIndexTreeItem }; + item.Items = new List() { baseItem }; + SetTreeItemEvents(baseItem, cont.FileInstance, fromPathId, baseField); + } + else + { + item.Items = new List() { CreateTreeItem("[null asset]") }; + } + } + }); + } + + private void TreeLoad(AssetsFileInstance fromFile, AssetTypeValueField assetField, long fromPathId, TreeViewItem treeItem) + { + if (assetField.childrenCount == 0) return; + + int arrayIdx = 0; + List items = new List(assetField.childrenCount + 1); + + AssetTypeTemplateField assetFieldTemplate = assetField.GetTemplateField(); + bool isArray = assetFieldTemplate.isArray; + + if (isArray) + { + int size = assetField.GetValue().AsArray().size; + AssetTypeTemplateField sizeTemplate = assetFieldTemplate.children[0]; + TreeViewItem arrayIndexTreeItem = CreateTreeItem($"{sizeTemplate.type} {sizeTemplate.name} = {size}"); + items.Add(arrayIndexTreeItem); + } + + foreach (AssetTypeValueField childField in assetField.children) + { + if (childField == null) return; + string value = ""; + if (childField.GetValue() != null) + { + EnumValueTypes evt = childField.GetValue().GetValueType(); + string quote = ""; + if (evt == EnumValueTypes.String) quote = "\""; + if (1 <= (int)evt && (int)evt <= 12) + { + value = $" = {quote}{childField.GetValue().AsString()}{quote}"; + } + if (evt == EnumValueTypes.Array || + evt == EnumValueTypes.ByteArray) + { + value = $" (size {childField.childrenCount})"; + } + } + + if (isArray) + { + TreeViewItem arrayIndexTreeItem = CreateTreeItem($"{arrayIdx}"); + items.Add(arrayIndexTreeItem); + + TreeViewItem childTreeItem = CreateTreeItem($"{childField.GetFieldType()} {childField.GetName()}{value}"); + arrayIndexTreeItem.Items = new List() { childTreeItem }; + + if (childField.childrenCount > 0) + { + TreeViewItem dummyItem = CreateTreeItem("Loading..."); + childTreeItem.Items = new List() { dummyItem }; + SetTreeItemEvents(childTreeItem, fromFile, fromPathId, childField); + } + + arrayIdx++; + } + else + { + TreeViewItem childTreeItem = CreateTreeItem($"{childField.GetFieldType()} {childField.GetName()}{value}"); + items.Add(childTreeItem); + + if (childField.childrenCount > 0) + { + TreeViewItem dummyItem = CreateTreeItem("Loading..."); + childTreeItem.Items = new List() { dummyItem }; + SetTreeItemEvents(childTreeItem, fromFile, fromPathId, childField); + } + } + } + + string templateFieldType = assetField.templateField.type; + if (templateFieldType.StartsWith("PPtr<") && templateFieldType.EndsWith(">")) + { + var fileIdField = assetField.Get("m_FileID"); + var pathIdField = assetField.Get("m_PathID"); + bool pptrValid = !fileIdField.IsDummy() && !pathIdField.IsDummy(); + + if (pptrValid) + { + int fileId = fileIdField.GetValue().AsInt(); + long pathId = pathIdField.GetValue().AsInt64(); + + AssetContainer cont = workspace.GetAssetContainer(fromFile, fileId, pathId, false); + + TreeViewItem childTreeItem = CreateTreeItem($"[view asset]"); + items.Add(childTreeItem); + + TreeViewItem dummyItem = CreateTreeItem("Loading..."); + childTreeItem.Items = new List() { dummyItem }; + SetPPtrEvents(childTreeItem, fromFile, pathId, cont); + } + } + + treeItem.Items = items; + } + } + + public class AssetDataTreeViewItem + { + public bool loaded; + public AssetsFileInstance fromFile; + public long fromPathId; + + public AssetDataTreeViewItem(AssetsFileInstance fromFile, long fromPathId) + { + this.loaded = false; + this.fromFile = fromFile; + this.fromPathId = fromPathId; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `baseField` last assigned on line 36 could be null and is dereferenced at line 38, column 13. + +### Severity: +ERROR + +### Procedure: +Void AssetDataTreeView.LoadComponent(AssetContainer) + +### File: +UABEAvalonia/AssetDataTreeView.cs + +### Key: +AssetDataTreeView.cs|LoadComponent|NULL_DEREFERENCE + +### Node Key: +0a2f2289efc1b4f27401d167fdf3ab36 + +### Hash: +ae3ba6ba176748ccddff32104e180bcf + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0024/instruction.md b/inferredbugs-0024/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7ca401d70f6ed9e3e9dcaf5a236ba5ea56f239d5 --- /dev/null +++ b/inferredbugs-0024/instruction.md @@ -0,0 +1,74 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** luban +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace Luban.Common.Utils +{ + public static class LogUtil + { + public static void InitSimpleNLogConfigure(NLog.LogLevel minConsoleLogLevel) + { + var logConfig = new NLog.Config.LoggingConfiguration(); + //var layout = NLog.Layouts.Layout.FromString("${longdate}|${level:uppercase=true}|${threadid}|${message}${onexception:${newline}${exception:format=tostring}${exception:format=StackTrace}}"); + var layout = NLog.Layouts.Layout.FromString("${longdate}|${message}${onexception:${newline}${exception:format=tostring}${exception:format=StackTrace}}"); + logConfig.AddTarget("console", new NLog.Targets.ColoredConsoleTarget() { Layout = layout }); + logConfig.AddRule(minConsoleLogLevel, NLog.LogLevel.Fatal, "console"); + NLog.LogManager.Configuration = logConfig; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of NLog.Targets.ColoredConsoleTarget::.ctor() at Line 10) of type NLog.Targets.ColoredConsoleTarget in method "Void LogUtil.InitSimpleNLogConfigure(LogLevel)". + +### Severity: +ERROR + +### Procedure: +Void LogUtil.InitSimpleNLogConfigure(LogLevel) + +### File: +src/Luban.Common/Source/Utils/LogUtil.cs + +### Key: +LogUtil.cs|InitSimpleNLogConfigure|DOTNET_RESOURCE_LEAK + +### Hash: +33fce8b9796d5ea4930c2b3942928fd5 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0102/instruction.md b/inferredbugs-0102/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..021da3c7549c18566363241ec0feccb35ddecbec --- /dev/null +++ b/inferredbugs-0102/instruction.md @@ -0,0 +1,210 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Mandrill-dotnet +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Mandrill.Requests; +using Mandrill.Utilities; +using System; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Xunit; + +namespace Mandrill.Tests.UnitTests +{ + public class PostTests : IDisposable + { + public PostTests() + { + var responseMessage = new HttpResponseMessage(); + var messageHandler = new FakeHttpMessageHandler(responseMessage); + httpClient = new HttpClient(messageHandler); + } + public void Dispose() { + httpClient?.Dispose(); + } + + private void RespondWith(MandrillApi api, HttpStatusCode statusCode, string content) + { + var responseMessage = new HttpResponseMessage(statusCode); + responseMessage.Content = new FakeHttpContent(content); + var messageHandler = new FakeHttpMessageHandler(responseMessage); + var httpClient = new HttpClient(messageHandler) + { + BaseAddress = new Uri(Configuration.BASE_SECURE_URL) + }; + api.SetHttpClient(httpClient); + } + + private HttpClient httpClient; + + private class SampleObject + { + public string Name { get; set; } + public int Id { get; set; } + } + + private class SamplePayload : RequestBase + { + } + + [Fact] + public async Task Should_Serialize_Response_When_Json_Content_Is_Recieved() + { + string responseString = @"{ + ""Name"": ""Shawn"", + ""Id"": 1 + }"; + var api = new MandrillApi(""); + RespondWith(api, HttpStatusCode.OK, responseString); + + SampleObject response = await api.Post("", new SamplePayload()); + + Assert.Equal("Shawn", response.Name); + Assert.Equal(1, response.Id); + } + + [Fact] + public async Task Should_Throw_Mandrill_Exception_When_Server_Error() + { + string responseString = @"{ + ""code"": ""501"", + ""message"": ""m1"", + ""name"": ""n1"", + ""status"": ""s1"" + }"; + + var api = new MandrillApi(""); + RespondWith(api, HttpStatusCode.InternalServerError, responseString); + + var ex = await Assert.ThrowsAsync(async () => await api.Post("", new SamplePayload())); + Assert.Equal(501, ex.Error.Code); + Assert.Equal("m1", ex.Error.Message); + Assert.Equal("n1", ex.Error.Name); + Assert.Equal("s1", ex.Error.Status); + } + + [Fact] + public async Task Should_Allow_Multiple_Requests_With_Single_HttpClient() + { + string responseString = @"{ + ""Name"": ""Shawn"", + ""Id"": 1 + }"; + var api = new MandrillApi(""); + RespondWith(api, HttpStatusCode.OK, responseString); + await api.Post("", new SamplePayload()); + await api.Post("", new SamplePayload()); + } + + [Fact] + public async Task Should_Throw_Mandrill_Exception_When_Serialization_Error() + { + string responseString = @""; + + var api = new MandrillApi(""); + RespondWith(api, HttpStatusCode.OK, responseString); + + var ex = await Assert.ThrowsAsync(async () => await api.Post("", new SamplePayload())); + var content = await ex.HttpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); + Assert.Equal(responseString, content); + } + public class FakeHttpMessageHandler : HttpMessageHandler + { + private HttpResponseMessage response; + + public FakeHttpMessageHandler(HttpResponseMessage response) + { + this.response = response; + } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var responseTask = new TaskCompletionSource(); + responseTask.SetResult(response); + + return responseTask.Task; + } + } + + public class FakeHttpContent : HttpContent + { + public string Content { get; set; } + + public FakeHttpContent(string content) + { + Content = content; + } + + protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) + { + byte[] byteArray = Encoding.ASCII.GetBytes(Content); + await stream.WriteAsync(byteArray, 0, Content.Length).ConfigureAwait(false); + } + + protected override bool TryComputeLength(out long length) + { + length = Content.Length; + return true; + } + } + + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource httpClient of type System.Net.Http.HttpClient, Leaked resource messageHandler of type Mandrill.Tests.UnitTests.PostTests$FakeHttpMessageHandler, Leaked resource responseMessage of type System.Net.Http.HttpResponseMessage, Leaked resource (output of Mandrill.Tests.UnitTests.PostTests$FakeHttpContent::.ctor() at Line 29) of type Mandrill.Tests.UnitTests.PostTests$FakeHttpContent in method "Void PostTests.RespondWith(MandrillApi,HttpStatusCode,String)". + +### Severity: +ERROR + +### Procedure: +Void PostTests.RespondWith(MandrillApi,HttpStatusCode,String) + +### File: +tests/Mandrill.Tests/UnitTests/PostTests.cs + +### Key: +PostTests.cs|RespondWith|DOTNET_RESOURCE_LEAK + +### Hash: +61c50933994f3a8d1b0e87779d82a058 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0105/instruction.md b/inferredbugs-0105/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..84a49d49fbb8875b5043f6d339f7b7c5d47bbb12 --- /dev/null +++ b/inferredbugs-0105/instruction.md @@ -0,0 +1,425 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** azure-functions-openapi-extension +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; + +using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Abstractions; +using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes; +using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Extensions; + +using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Models; + +using Newtonsoft.Json.Serialization; + +namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Visitors +{ + /// + /// This represents the visitor entity for type. This MUST be inherited. + /// + public abstract class TypeVisitor : IVisitor + { + /// + /// Initializes a new instance of the class. + /// + /// instance. + protected TypeVisitor(VisitorCollection visitorCollection) + { + this.VisitorCollection = visitorCollection.ThrowIfNullOrDefault(); + } + + /// + /// Gets the object. + /// + protected Type Type { get; private set; } + + /// + /// Gets the . + /// + protected VisitorCollection VisitorCollection { get; } + + /// + public virtual bool IsVisitable(Type type) + { + return false; + } + + /// + public virtual void Visit(IAcceptor acceptor, KeyValuePair type, NamingStrategy namingStrategy, params Attribute[] attributes) + { + return; + } + + /// + public virtual bool IsNavigatable(Type type) + { + return false; + } + + /// + public virtual bool IsParameterVisitable(Type type) + { + return false; + } + + /// + public virtual OpenApiSchema ParameterVisit(Type type, NamingStrategy namingStrategy) + { + return default; + } + + /// + public virtual bool IsPayloadVisitable(Type type) + { + return false; + } + + /// + public virtual OpenApiSchema PayloadVisit(Type type, NamingStrategy namingStrategy) + { + return default; + } + + /// + /// Checks whether the type is visitable or not. + /// + /// Type to check. + /// value. + /// Returns True, if the type is visitable; otherwise returns False. + protected bool IsVisitable(Type type, TypeCode code) + { + var @enum = Type.GetTypeCode(type); + var isVisitable = @enum == code; + + if (isVisitable) + { + this.Type = type; + } + + return isVisitable; + } + + /// + /// Checks whether the type can be referenced or not. + /// + /// Type to check. + /// Returns True, if the type can be referenced; otherwise returns False. + protected bool IsReferential(Type type) + { + var isReferential = type.IsReferentialType(); + + return isReferential; + } + + /// + /// Visits and processes the acceptor. + /// + /// instance. + /// Property name. + /// Type name. + /// Data type. + /// Data format. + /// List of attribute instances. + /// Returns the name as the schema key. + protected string Visit(IAcceptor acceptor, string name, string title, string dataType, string dataFormat, params Attribute[] attributes) + { + var instance = acceptor as OpenApiSchemaAcceptor; + if (instance.IsNullOrDefault()) + { + return null; + } + + if (instance.Schemas.ContainsKey(name)) + { + return null; + } + + var schema = new OpenApiSchema() + { + Title = title, + Type = dataType, + Format = dataFormat + }; + + // Adds the extra properties. + if (attributes.Any()) + { + schema.ApplyValidationAttributes(attributes.OfType()); + + Attribute attr = attributes.OfType().SingleOrDefault(); + if (!attr.IsNullOrDefault()) + { + if (dataType != "object") + { + schema.Nullable = this.GetOpenApiPropertyNullable(attr as OpenApiPropertyAttribute); + schema.Default = this.GetOpenApiPropertyDefault(attr as OpenApiPropertyAttribute); + } + schema.Description = this.GetOpenApiPropertyDescription(attr as OpenApiPropertyAttribute); + } + + attr = attributes.OfType().SingleOrDefault(); + if (!attr.IsNullOrDefault()) + { + var extension = new OpenApiString((attr as OpenApiSchemaVisibilityAttribute).Visibility.ToDisplayName()); + + schema.Extensions.Add("x-ms-visibility", extension); + } + } + + instance.Schemas.Add(name, schema); + + return name; + } + + /// + /// Visits and processes the for parameters. + /// + /// Data type. + /// Data format. + /// Returns instance. + protected OpenApiSchema ParameterVisit(string dataType, string dataFormat) + { + var schema = new OpenApiSchema() + { + Type = dataType, + Format = dataFormat + }; + + return schema; + } + + /// + /// Visits and processes the for payloads. + /// + /// Data type. + /// Data format. + /// Returns instance. + protected OpenApiSchema PayloadVisit(string dataType, string dataFormat) + { + var schema = new OpenApiSchema() + { + Type = dataType, + Format = dataFormat + }; + + return schema; + } + + /// + /// Gets the value indicating whether the property is nullable or not. + /// + /// instance. + /// Returns True, if nullable; otherwise returns False. + protected bool GetOpenApiPropertyNullable(OpenApiPropertyAttribute attr) + { + return attr.Nullable; + } + + /// + /// Gets the default value from the instance. + /// + /// instance. + /// Returns the default data. + protected IOpenApiAny GetOpenApiPropertyDefault(OpenApiPropertyAttribute attr) + { + var @default = attr.Default; + if (@default.IsNullOrDefault()) + { + return null; + } + + if (@default is bool) + { + return new OpenApiBoolean((bool) @default); + } + + if (@default is DateTime) + { + return new OpenApiDateTime((DateTime) @default); + } + + if (@default is DateTimeOffset) + { + return new OpenApiDateTime((DateTimeOffset) @default); + } + + if (@default is float) + { + return new OpenApiFloat((float) @default); + } + + if (@default is double) + { + return new OpenApiDouble((double) @default); + } + + if (@default is decimal) + { + return new OpenApiDouble(Convert.ToDouble(@default)); + } + + if (@default is short) + { + return new OpenApiInteger((short) @default); + } + + if (@default is int) + { + return new OpenApiInteger((int) @default); + } + + if (@default is long) + { + return new OpenApiLong((long) @default); + } + + if (@default is ushort) + { + return new OpenApiInteger(Convert.ToInt16(@default)); + } + + if (@default is uint) + { + return new OpenApiInteger(Convert.ToInt32(@default)); + } + + if (@default is ulong) + { + return new OpenApiLong(Convert.ToInt64(@default)); + } + + if (@default is Guid) + { + return new OpenApiString(Convert.ToString(@default)); + } + + return new OpenApiString((string) @default); + } + + /// + /// Gets the default value from the instance. + /// + /// Type to compare. + /// instance. + /// Returns the default data. + protected IOpenApiAny GetOpenApiPropertyDefault(OpenApiPropertyAttribute attr) + { + var @default = attr.Default; + if (@default.IsNullOrDefault()) + { + return null; + } + + if (typeof(T) == typeof(short)) + { + return new OpenApiInteger((short) @default); + } + + if (typeof(T) == typeof(int)) + { + return new OpenApiInteger((int) @default); + } + + if (typeof(T) == typeof(long)) + { + return new OpenApiLong((long) @default); + } + + if (@default is ushort) + { + return new OpenApiInteger(Convert.ToInt16(@default)); + } + + if (@default is uint) + { + return new OpenApiInteger(Convert.ToInt32(@default)); + } + + if (@default is ulong) + { + return new OpenApiLong(Convert.ToInt64(@default)); + } + + if (typeof(T) == typeof(string) && @default.GetType().IsEnumType()) + { + var @enum = (Enum)Convert.ChangeType(@default, typeof(Enum)); + + return new OpenApiString((string) EnumExtensions.ToDisplayName(@enum)); + } + + return new OpenApiString((string) @default); + } + + /// + /// Gets the property description. + /// + /// instance. + /// Returns the property description. + protected string GetOpenApiPropertyDescription(OpenApiPropertyAttribute attr) + { + return attr.Description; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `instance` last assigned on line 125 could be null and is dereferenced at line 131, column 13. + +### Severity: +ERROR + +### Procedure: +String TypeVisitor.Visit(IAcceptor,String,String,String,String,Attribute[]) + +### File: +src/Microsoft.Azure.WebJobs.Extensions.OpenApi.Core/Visitors/TypeVisitor.cs + +### Key: +TypeVisitor.cs|Visit|NULL_DEREFERENCE + +### Node Key: +cd898c0a5096d52146136ed94834c132 + +### Hash: +4f0543853d960e01f9c15cc682e178ad + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0133/instruction.md b/inferredbugs-0133/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a3475fbf674d8ecc279469bd60cafc16206f3062 --- /dev/null +++ b/inferredbugs-0133/instruction.md @@ -0,0 +1,142 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Rhisis +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; +using Rhisis.Core.Common; +using Rhisis.Core.DependencyInjection; +using Rhisis.Core.Helpers; +using Rhisis.Database.Context; +using System; + +namespace Rhisis.Database +{ + public sealed class DatabaseFactory : Singleton, IDesignTimeDbContextFactory + { + private const string MigrationConfigurationEnv = "DB_CONFIG"; + + public DatabaseConfiguration Configuration { get; private set; } + + /// + /// Initialize the and Data Access Layer assembly. + /// + public void Initialize() + { + DependencyContainer.Instance.Register(); + } + + /// + /// Initialize the . + /// + /// + public void Initialize(string databaseConfigurationPath) + => this.Initialize(ConfigurationHelper.Load(databaseConfigurationPath)); + + /// + /// Initialize the . + /// + /// Database configuration object + public void Initialize(DatabaseConfiguration configuration) + { + this.Configuration = configuration; + + using (var dbContext = this.CreateDbContext()) + { + dbContext.Migrate(); + if (!dbContext.DatabaseExists()) + throw new InvalidOperationException($"The database '{this.Configuration.Database}' doesn't exists."); + } + + this.Initialize(); + } + + /// + /// Creates a new . + /// + /// + public DatabaseContext CreateDbContext() => this.CreateDbContext(this.Configuration); + + /// + /// Creates a new with a specific configuration. + /// + /// + /// + public DatabaseContext CreateDbContext(DatabaseConfiguration configuration) => new DatabaseContext(configuration); + + /// + /// Creates a new by passing context options. + /// + /// + /// + public DatabaseContext CreateDbContext(DbContextOptions options) => new DatabaseContext(options); + + /// + public DatabaseContext CreateDbContext(string[] args) + { + var configurationPath = Environment.GetEnvironmentVariable(MigrationConfigurationEnv); + var configuration = ConfigurationHelper.Load(configurationPath); + var context = new DatabaseContext(configuration); + + if (!string.IsNullOrEmpty(configurationPath) && !context.DatabaseExists()) + throw new InvalidOperationException($"The database '{configuration.Database}' doesn't exists."); + + return context; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type Microsoft.EntityFrameworkCore.DbContext, Leaked resource context of type Microsoft.EntityFrameworkCore.DbContext in method "DatabaseContext DatabaseFactory.CreateDbContext(String[])". + +### Severity: +ERROR + +### Procedure: +DatabaseContext DatabaseFactory.CreateDbContext(String[]) + +### File: +src/Rhisis.Database/DatabaseFactory.cs + +### Key: +DatabaseFactory.cs|CreateDbContext|DOTNET_RESOURCE_LEAK + +### Hash: +a0b28d053da435d30dff346c03fbb819 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0134/instruction.md b/inferredbugs-0134/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d8b1a89d38bd3d2bb803b846c22b9544fa513a2f --- /dev/null +++ b/inferredbugs-0134/instruction.md @@ -0,0 +1,120 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Rhisis +**Bug ID:** 5 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.Extensions.DependencyInjection; +using Rhisis.Game.Abstractions.Entities; +using Rhisis.Game.Abstractions.Features; +using Rhisis.Game.Abstractions.Systems; +using Rhisis.Game.Common; +using Rhisis.Network; +using Rhisis.Network.Snapshots; +using System; + +namespace Rhisis.Game.Abstractions.Components +{ + public class Health : IHealth + { + private readonly IMover _mover; + private readonly Lazy _healthFormulas; + + public bool IsDead => Hp < 0; + + public int Hp { get; set; } + + public int Mp { get; set; } + + public int Fp { get; set; } + + public int MaxHp => _healthFormulas.Value.GetMaxHp(_mover); + + public int MaxMp => _healthFormulas.Value.GetMaxMp(_mover); + + public int MaxFp => _healthFormulas.Value.GetMaxFp(_mover); + + /// + /// Creates a new instance. + /// + /// Current player. + public Health(IMover mover) + { + _mover = mover; + _healthFormulas = new Lazy(() => mover.Systems.GetService()); + } + + public void RegenerateAll() + { + Hp = MaxHp; + Mp = MaxMp; + Fp = MaxFp; + + using var healthSnapshot = new FFSnapshot(); + healthSnapshot.Merge(new UpdateParamPointSnapshot(_mover, DefineAttributes.HP, Hp)); + healthSnapshot.Merge(new UpdateParamPointSnapshot(_mover, DefineAttributes.MP, Mp)); + healthSnapshot.Merge(new UpdateParamPointSnapshot(_mover, DefineAttributes.FP, Fp)); + + _mover.SendToVisible(healthSnapshot); + + if (_mover is IPlayer) + { + _mover.Send(healthSnapshot); + } + + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Rhisis.Network.Snapshots.UpdateParamPointSnapshot::.ctor() at Line 50) of type Sylver.Network.Data.NetPacketStream, Leaked resource (output of Rhisis.Network.Snapshots.UpdateParamPointSnapshot::.ctor() at Line 49) of type Sylver.Network.Data.NetPacketStream, Leaked resource (output of Rhisis.Network.Snapshots.UpdateParamPointSnapshot::.ctor() at Line 48) of type Sylver.Network.Data.NetPacketStream in method "Void Health.RegenerateAll()". + +### Severity: +ERROR + +### Procedure: +Void Health.RegenerateAll() + +### File: +src/Rhisis.Game/Features/Health.cs + +### Key: +Health.cs|RegenerateAll|DOTNET_RESOURCE_LEAK + +### Hash: +62a7a3edfca648cef7d92b28d56f8518 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0150/instruction.md b/inferredbugs-0150/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..79cd1ec20a83b62b40e0d8d98fa7a45fb259456f --- /dev/null +++ b/inferredbugs-0150/instruction.md @@ -0,0 +1,383 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Xabe.FFmpeg +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using Xabe.FFMpeg.Enums; + +namespace Xabe.FFMpeg +{ + /// + /// Information about media file + /// + public class VideoInfo : IDisposable + { + /// + /// _sourceFile info + /// + + public readonly string FilePath; + + /// + /// Return extension of file + /// + public string Extension => Path.GetExtension(FilePath); + + private FFMpeg _ffmpeg; + + /// + /// Fires when conversion progress changed + /// + public ConversionHandler OnConversionProgress; + + /// + /// Get VideoInfo from file + /// + /// _sourceFile + public VideoInfo(FileInfo sourceFileInfo) : this(sourceFileInfo.FullName) + { + } + + /// + /// Get VideoInfo from file + /// + /// FilePath to file + public VideoInfo(string filePath) + { + if(!File.Exists(filePath)) + { + throw new ArgumentException($"Input file {filePath} doesn't exists."); + } + FilePath = filePath; + new FFProbe().ProbeDetails(this); + } + + private FFMpeg FFmpeg + { + get + { + if(_ffmpeg != null && + _ffmpeg.IsRunning) + throw new InvalidOperationException( + "Operation on this file is in progress."); + + return _ffmpeg ?? (_ffmpeg = new FFMpeg()); + } + } + + /// + /// duration of video + /// + public TimeSpan Duration { get; internal set; } + + /// + /// Audio format + /// + public string AudioFormat { get; internal set; } + + /// + /// Video format + /// + public string VideoFormat { get; internal set; } + + /// + /// Screen ratio + /// + public string Ratio { get; internal set; } + + /// + /// Frame rate + /// + public double FrameRate { get; internal set; } + + /// + /// Height + /// + public int Height { get; internal set; } + + /// + /// Width + /// + public int Width { get; internal set; } + + /// + /// size + /// + public double Size { get; internal set; } + + /// + /// Get the ffmpeg process status + /// + public bool IsRunning => FFmpeg.IsRunning; + + /// + /// Create VideoInfo from file + /// + /// _sourceFile + /// VideoInfo + public static VideoInfo FromFile(FileInfo fileInfo) + { + return new VideoInfo(fileInfo); + } + + /// + /// Get formated info about video + /// + /// Formated info about vidoe + public override string ToString() + { + return "Video FilePath : " + FilePath + Environment.NewLine + + "Video Root : " + Path.GetDirectoryName(FilePath)+ Environment.NewLine + + "Video Name: " + Path.GetFileName(FilePath) + Environment.NewLine + + "Video Extension : " + Extension + Environment.NewLine + + "Video duration : " + Duration + Environment.NewLine + + "Audio format : " + AudioFormat + Environment.NewLine + + "Video format : " + VideoFormat + Environment.NewLine + + "Aspect Ratio : " + Ratio + Environment.NewLine + + "Framerate : " + FrameRate + "fps" + Environment.NewLine + + "Resolution : " + Width + "x" + Height + Environment.NewLine + + "Size : " + Size + " MB"; + } + + /// + /// Convert file to TS + /// + /// Destination file + /// Output VideoInfo + public VideoInfo ToTs(string outputPath) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToTs(this, outputPath); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Convert file to WebM + /// + /// Destination file + /// Dimension + /// Audio quality + /// Output VideoInfo + public VideoInfo ToWebM(string outputPath, VideoSize size = VideoSize.Original, AudioQuality audioQuality = AudioQuality.Normal) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToWebM(this, outputPath, size, audioQuality); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Convert file to OGV + /// + /// Destination file + /// Dimension + /// Audio quality + /// Use multithread + /// Output VideoInfo + public VideoInfo ToOgv(string outputPath, VideoSize size = VideoSize.Original, AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToOgv(this, outputPath, size, audioQuality, multithread); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Convert file to MP4 + /// + /// Destination file + /// Conversion speed + /// Dimension + /// Audio quality + /// Use multithread + /// Output VideoInfo + public VideoInfo ToMp4(string outputPath, Speed speed = Speed.SuperFast, + VideoSize size = VideoSize.Original, AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToMp4(this, outputPath, speed, size, audioQuality, multithread); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Extract video from file + /// + /// Output audio stream + /// Conversion result + public bool ExtractVideo(string output) + { + return FFmpeg.ExtractVideo(this, output); + } + + /// + /// Extract audio from file + /// + /// Output video stream + /// Conversion result + public bool ExtractAudio(string output) + { + return FFmpeg.ExtractAudio(this, output); + } + + /// + /// Add audio to file + /// + /// Audio file + /// Output file + /// Conversion result + public bool AddAudio(FileInfo audio, string output) + { + return FFmpeg.AddAudio(this, audio, output); + } + + /// + /// Get snapshot of video + /// + /// Dimension of snapshot + /// + /// Snapshot + public Bitmap Snapshot(Size? size = null, TimeSpan? captureTime = null) + { + var output = $"{Environment.TickCount}.png"; + + bool success = FFmpeg.Snapshot(this, output, size, captureTime); + + if(!success) + throw new OperationCanceledException("Could not take snapshot!"); + + Bitmap result; + + using(Image bmp = Image.FromFile(output)) + { + using(var ms = new MemoryStream()) + { + bmp.Save(ms, ImageFormat.Png); + + result = new Bitmap(ms); + } + } + + if(File.Exists(output)) + File.Delete(output); + + return result; + } + + /// + /// Saves snapshot of video + /// + /// Output file + /// Dimension of snapshot + /// + /// Snapshot + public Bitmap Snapshot(string output, Size? size = null, TimeSpan? captureTime = null) + { + bool success = FFmpeg.Snapshot(this, output, size, captureTime); + + if(!success) + throw new OperationCanceledException("Could not take snapshot!"); + + Bitmap result; + + + using(Image bmp = Image.FromFile(System.IO.Path.ChangeExtension(output, ".png"))) + { + result = (Bitmap) bmp.Clone(); + } + + return result; + } + + /// + /// Concat multiple videos + /// + /// Concatenated videos + /// Videos to add + /// Conversion result + public bool JoinWith(string output, params VideoInfo[] videos) + { + List queuedVideos = videos.ToList(); + + queuedVideos.Insert(0, this); + + return FFmpeg.Join(output, queuedVideos.ToArray()); + } + + /// + public void Dispose() + { + FFmpeg.Stop(); + _ffmpeg?.Dispose(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from Xabe.FFMpeg.FFMpeg Xabe.FFMpeg.VideoInfo::get_FFmpeg() at Line 286) of type Xabe.FFMpeg.FFMpeg in method "Bitmap VideoInfo.Snapshot(String,Nullable`1,Nullable`1)". + +### Severity: +ERROR + +### Procedure: +Bitmap VideoInfo.Snapshot(String,Nullable`1,Nullable`1) + +### File: +Xabe.FFMpeg/VideoInfo.cs + +### Key: +VideoInfo.cs|Snapshot|DOTNET_RESOURCE_LEAK + +### Hash: +92597941ea68210d8e69b13d90bd76c8 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0151/instruction.md b/inferredbugs-0151/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bc4b9d2294fc15698ec3e5ad3d9fb8561962d514 --- /dev/null +++ b/inferredbugs-0151/instruction.md @@ -0,0 +1,217 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Xabe.FFmpeg +**Bug ID:** 10 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Drawing; +using System.IO; +using Xabe.FFMpeg.Enums; +using Xunit; + +namespace Xabe.FFMpeg.Test +{ + public class VideoInfoTests + + { + private static readonly FileInfo SampleVideoWithAudio = new FileInfo(Path.Combine(Environment.CurrentDirectory, "Resources", "input.mp4")); + private static readonly FileInfo SampleAudio = new FileInfo(Path.Combine(Environment.CurrentDirectory, "Resources", "audio.mp3")); + private static readonly FileInfo SampleVideo = new FileInfo(Path.Combine(Environment.CurrentDirectory, "Resources", "mute.mp4")); + private static readonly FileInfo SampleMkvVideo = new FileInfo(Path.Combine(Environment.CurrentDirectory, "Resources", "sampleMkv.mkv")); + + + [Fact] + public void ToTs() + { + FileInfo fileInfo = SampleVideoWithAudio; + var output = Path.ChangeExtension(Path.GetTempFileName(), ".ts"); + + VideoInfo outputVideo = new VideoInfo(fileInfo).ToTs(output); + Assert.True(File.Exists(outputVideo.FilePath)); + Assert.Equal(TimeSpan.FromSeconds(13), outputVideo.Duration); + } + + [Fact] + public void ToWebM() + { + FileInfo fileInfo = SampleVideoWithAudio; + var output = Path.ChangeExtension(Path.GetTempFileName(), ".webm"); + + VideoInfo outputVideo = new VideoInfo(fileInfo).ToWebM(output); + Assert.True(File.Exists(outputVideo.FilePath)); + Assert.Equal(TimeSpan.FromSeconds(13), outputVideo.Duration); + } + + [Fact] + public void ToOGV() + { + FileInfo fileInfo = SampleVideoWithAudio; + var output = Path.ChangeExtension(Path.GetTempFileName(), ".ogv"); + + VideoInfo outputVideo = new VideoInfo(fileInfo).ToOgv(output); + Assert.True(File.Exists(outputVideo.FilePath)); + Assert.Equal(TimeSpan.FromSeconds(13), outputVideo.Duration); + } + + [Fact] + public void ToMp4() + { + FileInfo fileInfo = SampleMkvVideo; + var output = Path.ChangeExtension(Path.GetTempFileName(), ".mp4"); + + VideoInfo outputVideo = new VideoInfo(fileInfo).ToMp4(output); + Assert.True(File.Exists(outputVideo.FilePath)); + Assert.Equal(TimeSpan.FromSeconds(30), outputVideo.Duration); + } + + [Fact] + public void AddAudio() + { + var videoInfo = new VideoInfo(SampleVideo); + var output = Path.ChangeExtension(Path.GetTempFileName(), videoInfo.Extension); + + bool result = videoInfo.AddAudio(SampleAudio, output); + Assert.True(result); + Assert.Equal(videoInfo.Duration, new VideoInfo(output).Duration); + } + + [Fact] + public void ExtractAudio() + { + FileInfo fileInfo = SampleVideoWithAudio; + var output = Path.ChangeExtension(Path.GetTempFileName(), ".mp3"); + + bool result = new VideoInfo(fileInfo).ExtractAudio(output); + Assert.True(result); + } + + [Fact] + public void ExtractVideo() + { + FileInfo fileInfo = SampleVideoWithAudio; + var output = Path.ChangeExtension(Path.GetTempFileName(), fileInfo.Extension); + + bool result = new VideoInfo(fileInfo).ExtractVideo(output); + Assert.True(result); + } + + [Fact] + public void JoinWith() + { + var videoInfo = new VideoInfo(SampleVideoWithAudio); + var output = Path.ChangeExtension(Path.GetTempFileName(), videoInfo.Extension); + + bool result = videoInfo.JoinWith(output, new VideoInfo(SampleVideo)); + + Assert.True(result); + } + + [Fact] + public void MkvPropertiesTest() + { + var videoInfo = new VideoInfo(SampleMkvVideo); + + Assert.Equal("none", videoInfo.AudioFormat); + Assert.Equal(TimeSpan.FromSeconds(30), videoInfo.Duration); + Assert.True(File.Exists(videoInfo.FilePath)); + Assert.Equal(".mkv", videoInfo.Extension); + Assert.Equal(29.97, videoInfo.FrameRate); + Assert.Equal(1080, videoInfo.Height); + Assert.Equal(1920, videoInfo.Width); + Assert.Equal("sampleMkv.mkv", Path.GetFileName(videoInfo.FilePath)); + Assert.False(videoInfo.IsRunning); + Assert.Equal("16:9", videoInfo.Ratio); + } + + [Fact] + public void PropertiesTest() + { + var videoInfo = new VideoInfo(SampleVideoWithAudio); + + Assert.Equal("aac", videoInfo.AudioFormat); + Assert.Equal(TimeSpan.FromSeconds(13), videoInfo.Duration); + Assert.True(File.Exists(videoInfo.FilePath)); + Assert.Equal(".mp4", videoInfo.Extension); + Assert.Equal(25, videoInfo.FrameRate); + Assert.Equal(720, videoInfo.Height); + Assert.Equal(1280, videoInfo.Width); + Assert.Equal("input.mp4", Path.GetFileName(videoInfo.FilePath)); + Assert.False(videoInfo.IsRunning); + Assert.Equal("16:9", videoInfo.Ratio); + } + + [Fact] + public void Snapshot() + { + var videoInfo = new VideoInfo(SampleVideoWithAudio); + Image snapshot = videoInfo.Snapshot(); + + Assert.Equal(snapshot.Width, videoInfo.Width); + } + + [Fact] + public void SnapshotWithOutput() + { + var videoInfo = new VideoInfo(SampleVideoWithAudio); + var output = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + Extensions.Png); + Image snapshot = videoInfo.Snapshot(output); + + Assert.Equal(snapshot.Width, videoInfo.Width); + Assert.True(File.Exists(output)); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource outputVideo of type Xabe.FFMpeg.VideoInfo, Leaked resource (output of Xabe.FFMpeg.VideoInfo::.ctor() at Line 46) of type Xabe.FFMpeg.VideoInfo in method "Void VideoInfoTests.ToOGV()". + +### Severity: +ERROR + +### Procedure: +Void VideoInfoTests.ToOGV() + +### File: +Xabe.FFMpeg.Test/VideoInfoTests.cs + +### Key: +VideoInfoTests.cs|ToOGV|DOTNET_RESOURCE_LEAK + +### Hash: +9ad643a6d4c49516eccb2a12f7481a84 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0158/instruction.md b/inferredbugs-0158/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..507df19163d533b1f3258255686ded466c3f2b2c --- /dev/null +++ b/inferredbugs-0158/instruction.md @@ -0,0 +1,428 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Xabe.FFmpeg +**Bug ID:** 15 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using JetBrains.Annotations; +using Xabe.FFMpeg.Enums; + +namespace Xabe.FFMpeg +{ + /// + public class VideoInfo: IDisposable, IVideoInfo + { + private FFMpeg _ffmpeg; + + /// + public VideoInfo(FileInfo sourceFileInfo): this(sourceFileInfo.FullName) + { + } + + /// + /// Get VideoInfo from file + /// + /// FilePath to file + public VideoInfo(string filePath) + { + if(!File.Exists(filePath)) + throw new ArgumentException($"Input file {filePath} doesn't exists."); + FilePath = filePath; + new FFProbe().ProbeDetails(this); + } + + private FFMpeg FFmpeg + { + get + { + if(_ffmpeg != null && + _ffmpeg.IsRunning) + throw new InvalidOperationException( + "Operation on this file is in progress."); + + return _ffmpeg ?? (_ffmpeg = new FFMpeg()); + } + } + + /// + public void Dispose() + { + FFmpeg.Stop(); + _ffmpeg?.Dispose(); + } + + /// + public string FilePath { get; } + + /// + public ConversionHandler OnConversionProgress { get; set; } + + + /// + public string Extension => Path.GetExtension(FilePath); + + + /// + public TimeSpan Duration { get; internal set; } + + /// + public string AudioFormat { get; internal set; } + + + /// + public string VideoFormat { get; internal set; } + + + /// + public string Ratio { get; internal set; } + + /// + public double FrameRate { get; internal set; } + + /// + public int Height { get; internal set; } + + /// + public int Width { get; internal set; } + + /// + public double Size { get; internal set; } + + /// + public bool IsRunning => FFmpeg.IsRunning; + + + /// + public override string ToString() + { + return "Video FilePath : " + FilePath + Environment.NewLine + + "Video Root : " + Path.GetDirectoryName(FilePath) + Environment.NewLine + + "Video Name: " + Path.GetFileName(FilePath) + Environment.NewLine + + "Video Extension : " + Extension + Environment.NewLine + + "Video duration : " + Duration + Environment.NewLine + + "Audio format : " + AudioFormat + Environment.NewLine + + "Video format : " + VideoFormat + Environment.NewLine + + "Aspect Ratio : " + Ratio + Environment.NewLine + + "Framerate : " + FrameRate + "fps" + Environment.NewLine + + "Resolution : " + Width + "x" + Height + Environment.NewLine + + "Size : " + Size + " MB"; + } + + + /// + public bool ToTs(string outputPath) + { + return new Conversion() + .SetInput(FilePath) + .StreamCopy(Channel.Both) + .SetBitstreamFilter(Channel.Video, Filter.H264_Mp4ToAnnexB) + .SetCodec(VideoCodec.MpegTs) + .SetOutput(outputPath) + .Start(); + } + + + /// + public bool ToWebM(string outputPath, string size = "", AudioQuality audioQuality = AudioQuality.Normal) + { + return new Conversion() + .SetInput(FilePath) + .SetScale(size) + .SetVideo(VideoCodec.LibVpx, 2400) + .SetSpeed(16) + .SetAudio(AudioCodec.LibVorbis, audioQuality) + .SetOutput(outputPath) + .Start(); + } + + + /// + public bool ToOgv(string outputPath, string size = "", AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false) + { + return new Conversion() + .SetInput(FilePath) + .SetScale(size) + .SetVideo(VideoCodec.LibTheora, 2400) + .SetSpeed(16) + .SetAudio(AudioCodec.LibVorbis, audioQuality) + .SetOutput(outputPath) + .Start(); + } + + + /// + public bool ToMp4(string outputPath, Speed speed = Speed.SuperFast, + string size = "", AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false) + { + return new Conversion() + .SetInput(FilePath) + .UseMultiThread(multithread) + .SetScale(size) + .SetVideo(VideoCodec.LibX264, 2400) + .SetSpeed(speed) + .SetAudio(AudioCodec.Aac, audioQuality) + .SetOutput(outputPath) + .Start(); + } + + + /// + public bool ExtractVideo(string output) + { + return new Conversion().SetInput(this.FilePath) + .StreamCopy(Channel.Both) + .DisableChannel(Channel.Audio) + .SetOutput(output) + .Start(); + } + + /// + public bool ExtractAudio(string output) + { + return new Conversion().SetInput(FilePath) + .DisableChannel(Channel.Video) + .SetOutput(output) + .Start(); + } + + + /// + public bool AddAudio(FileInfo audio, string output) + { + return new Conversion().SetInput(new FileInfo(this.FilePath), audio) + .StreamCopy(Channel.Video) + .SetAudio(AudioCodec.Aac, AudioQuality.Hd) + .SetOutput(output) + .Start(); + } + + + /// + public Bitmap Snapshot(Size? size = null, TimeSpan? captureTime = null) + { + string output = $"{Environment.TickCount}.png"; + + bool success = this.Snapshot(this, output, size, captureTime); + + if(!success) + throw new OperationCanceledException("Could not take snapshot!"); + + Bitmap result; + + using(Image bmp = Image.FromFile(output)) + { + using(var ms = new MemoryStream()) + { + bmp.Save(ms, ImageFormat.Png); + + result = new Bitmap(ms); + } + } + + if(File.Exists(output)) + File.Delete(output); + + return result; + } + + + /// + public Bitmap Snapshot(string output, Size? size = null, TimeSpan? captureTime = null) + { + bool success = Snapshot(this, output, size, captureTime); + + if(!success) + throw new OperationCanceledException("Could not take snapshot!"); + + Bitmap result; + + + using(Image bmp = Image.FromFile(Path.ChangeExtension(output, ".png"))) + { + result = (Bitmap) bmp.Clone(); + } + + return result; + } + + /// + /// Saves snapshot of video + /// + /// Video + /// Output file + /// Dimension of snapshot + /// + /// Conversion result + [UsedImplicitly] + public bool Snapshot(VideoInfo source, string outputPath, Size? size = null, TimeSpan? captureTime = null) + { + if (captureTime == null) + captureTime = TimeSpan.FromSeconds(source.Duration.TotalSeconds / 3); + + size = GetSize(source, size); + + return new Conversion() + .SetInput(source.FilePath) + .SetVideo(VideoCodec.Png) + .SetOutputFramesCount(1) + .SetSeek(captureTime) + .SetSize(size) + .SetOutput(outputPath) + .Start(); + } + + private static Size? GetSize(VideoInfo source, Size? size) + { + if (size == null || + size.Value.Height == 0 && size.Value.Width == 0) + size = new Size(source.Width, source.Height); + + if (size.Value.Width != size.Value.Height) + { + if (size.Value.Width == 0) + { + double ratio = source.Width / (double)size.Value.Width; + + size = new Size((int)(source.Width * ratio), (int)(source.Height * ratio)); + } + + if (size.Value.Height == 0) + { + double ratio = source.Height / (double)size.Value.Height; + + size = new Size((int)(source.Width * ratio), (int)(source.Height * ratio)); + } + } + + return size; + } + + /// + /// Adds a poster image to an audio file. + /// + /// Source image file. + /// Source audio file. + /// Output video file. + /// Conversion result + public bool PosterWithAudio(FileInfo image, FileInfo audio, string outputPath) + { + return new Conversion() + .SetInput(image, audio) + .SetLoop(1) + .SetVideo(VideoCodec.LibX264, 2400) + .SetAudio(AudioCodec.Aac, AudioQuality.Normal) + .UseShortest(true) + .SetOutput(outputPath) + .Start(); + } + + /// + /// Records M3U8 streams to the specified output. + /// + /// URI to stream. + /// Output file + /// Conversion result + public bool SaveM3U8Stream(Uri uri, string outputPath) + { + if (uri.Scheme != "http" || + uri.Scheme != "https") + throw new ArgumentException($"Invalid uri {uri.AbsolutePath}"); + + return new Conversion().SetInput(uri) + .SetOutput(outputPath) + .Start(); + } + + /// + public bool JoinWith(string output, params VideoInfo[] videos) + { + List queuedVideos = videos.ToList(); + + queuedVideos.Insert(0, this); + + var pathList = new List(); + + foreach (VideoInfo video in videos) + { + string tempFileName = Path.ChangeExtension(Path.GetTempFileName(), Extensions.Ts); + pathList.Add(tempFileName); + video.ToTs(tempFileName); + } + + return new Conversion().Concat(pathList.ToArray()) + .StreamCopy(Channel.Both) + .SetBitstreamFilter(Channel.Audio, Filter.Aac_AdtstoAsc) + .SetOutput(output) + .Start(); + } + + /// + /// Create VideoInfo from file + /// + /// _sourceFile + /// VideoInfo + public static IVideoInfo FromFile(FileInfo fileInfo) + { + return new VideoInfo(fileInfo); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from Xabe.FFMpeg.FFMpeg Xabe.FFMpeg.VideoInfo::get_FFmpeg() at Line 50) of type Xabe.FFMpeg.FFMpeg in method "Void VideoInfo.Dispose()". + +### Severity: +ERROR + +### Procedure: +Void VideoInfo.Dispose() + +### File: +Xabe.FFMpeg/VideoInfo.cs + +### Key: +VideoInfo.cs|Dispose|DOTNET_RESOURCE_LEAK + +### Hash: +b18476885ed02cb73ce8888bd969aaed + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0159/instruction.md b/inferredbugs-0159/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..639264dd75904f101cd17e6f28415045491f2d08 --- /dev/null +++ b/inferredbugs-0159/instruction.md @@ -0,0 +1,383 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Xabe.FFmpeg +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using Xabe.FFMpeg.Enums; + +namespace Xabe.FFMpeg +{ + /// + /// Information about media file + /// + public class VideoInfo : IDisposable + { + /// + /// _sourceFile info + /// + + public readonly string FilePath; + + /// + /// Return extension of file + /// + public string Extension => Path.GetExtension(FilePath); + + private FFMpeg _ffmpeg; + + /// + /// Fires when conversion progress changed + /// + public ConversionHandler OnConversionProgress; + + /// + /// Get VideoInfo from file + /// + /// _sourceFile + public VideoInfo(FileInfo sourceFileInfo) : this(sourceFileInfo.FullName) + { + } + + /// + /// Get VideoInfo from file + /// + /// FilePath to file + public VideoInfo(string filePath) + { + if(!File.Exists(filePath)) + { + throw new ArgumentException($"Input file {filePath} doesn't exists."); + } + FilePath = filePath; + new FFProbe().ProbeDetails(this); + } + + private FFMpeg FFmpeg + { + get + { + if(_ffmpeg != null && + _ffmpeg.IsRunning) + throw new InvalidOperationException( + "Operation on this file is in progress."); + + return _ffmpeg ?? (_ffmpeg = new FFMpeg()); + } + } + + /// + /// duration of video + /// + public TimeSpan Duration { get; internal set; } + + /// + /// Audio format + /// + public string AudioFormat { get; internal set; } + + /// + /// Video format + /// + public string VideoFormat { get; internal set; } + + /// + /// Screen ratio + /// + public string Ratio { get; internal set; } + + /// + /// Frame rate + /// + public double FrameRate { get; internal set; } + + /// + /// Height + /// + public int Height { get; internal set; } + + /// + /// Width + /// + public int Width { get; internal set; } + + /// + /// size + /// + public double Size { get; internal set; } + + /// + /// Get the ffmpeg process status + /// + public bool IsRunning => FFmpeg.IsRunning; + + /// + /// Create VideoInfo from file + /// + /// _sourceFile + /// VideoInfo + public static VideoInfo FromFile(FileInfo fileInfo) + { + return new VideoInfo(fileInfo); + } + + /// + /// Get formated info about video + /// + /// Formated info about vidoe + public override string ToString() + { + return "Video FilePath : " + FilePath + Environment.NewLine + + "Video Root : " + Path.GetDirectoryName(FilePath)+ Environment.NewLine + + "Video Name: " + Path.GetFileName(FilePath) + Environment.NewLine + + "Video Extension : " + Extension + Environment.NewLine + + "Video duration : " + Duration + Environment.NewLine + + "Audio format : " + AudioFormat + Environment.NewLine + + "Video format : " + VideoFormat + Environment.NewLine + + "Aspect Ratio : " + Ratio + Environment.NewLine + + "Framerate : " + FrameRate + "fps" + Environment.NewLine + + "Resolution : " + Width + "x" + Height + Environment.NewLine + + "Size : " + Size + " MB"; + } + + /// + /// Convert file to TS + /// + /// Destination file + /// Output VideoInfo + public VideoInfo ToTs(string outputPath) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToTs(this, outputPath); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Convert file to WebM + /// + /// Destination file + /// Dimension + /// Audio quality + /// Output VideoInfo + public VideoInfo ToWebM(string outputPath, VideoSize size = VideoSize.Original, AudioQuality audioQuality = AudioQuality.Normal) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToWebM(this, outputPath, size, audioQuality); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Convert file to OGV + /// + /// Destination file + /// Dimension + /// Audio quality + /// Use multithread + /// Output VideoInfo + public VideoInfo ToOgv(string outputPath, VideoSize size = VideoSize.Original, AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToOgv(this, outputPath, size, audioQuality, multithread); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Convert file to MP4 + /// + /// Destination file + /// Conversion speed + /// Dimension + /// Audio quality + /// Use multithread + /// Output VideoInfo + public VideoInfo ToMp4(string outputPath, Speed speed = Speed.SuperFast, + VideoSize size = VideoSize.Original, AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToMp4(this, outputPath, speed, size, audioQuality, multithread); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Extract video from file + /// + /// Output audio stream + /// Conversion result + public bool ExtractVideo(string output) + { + return FFmpeg.ExtractVideo(this, output); + } + + /// + /// Extract audio from file + /// + /// Output video stream + /// Conversion result + public bool ExtractAudio(string output) + { + return FFmpeg.ExtractAudio(this, output); + } + + /// + /// Add audio to file + /// + /// Audio file + /// Output file + /// Conversion result + public bool AddAudio(FileInfo audio, string output) + { + return FFmpeg.AddAudio(this, audio, output); + } + + /// + /// Get snapshot of video + /// + /// Dimension of snapshot + /// + /// Snapshot + public Bitmap Snapshot(Size? size = null, TimeSpan? captureTime = null) + { + var output = $"{Environment.TickCount}.png"; + + bool success = FFmpeg.Snapshot(this, output, size, captureTime); + + if(!success) + throw new OperationCanceledException("Could not take snapshot!"); + + Bitmap result; + + using(Image bmp = Image.FromFile(output)) + { + using(var ms = new MemoryStream()) + { + bmp.Save(ms, ImageFormat.Png); + + result = new Bitmap(ms); + } + } + + if(File.Exists(output)) + File.Delete(output); + + return result; + } + + /// + /// Saves snapshot of video + /// + /// Output file + /// Dimension of snapshot + /// + /// Snapshot + public Bitmap Snapshot(string output, Size? size = null, TimeSpan? captureTime = null) + { + bool success = FFmpeg.Snapshot(this, output, size, captureTime); + + if(!success) + throw new OperationCanceledException("Could not take snapshot!"); + + Bitmap result; + + + using(Image bmp = Image.FromFile(System.IO.Path.ChangeExtension(output, ".png"))) + { + result = (Bitmap) bmp.Clone(); + } + + return result; + } + + /// + /// Concat multiple videos + /// + /// Concatenated videos + /// Videos to add + /// Conversion result + public bool JoinWith(string output, params VideoInfo[] videos) + { + List queuedVideos = videos.ToList(); + + queuedVideos.Insert(0, this); + + return FFmpeg.Join(output, queuedVideos.ToArray()); + } + + /// + public void Dispose() + { + FFmpeg.Stop(); + _ffmpeg?.Dispose(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type Xabe.FFMpeg.VideoInfo, Leaked resource (returned from Xabe.FFMpeg.FFMpeg Xabe.FFMpeg.VideoInfo::get_FFmpeg() at Line 189) of type Xabe.FFMpeg.FFMpeg, Leaked resource (returned from Xabe.FFMpeg.FFMpeg Xabe.FFMpeg.VideoInfo::get_FFmpeg() at Line 186) of type Xabe.FFMpeg.FFMpeg, Leaked resource (returned from Xabe.FFMpeg.FFMpeg Xabe.FFMpeg.VideoInfo::get_FFmpeg() at Line 185) of type Xabe.FFMpeg.FFMpeg in method "VideoInfo VideoInfo.ToOgv(String,VideoSize,AudioQuality,Boolean)". + +### Severity: +ERROR + +### Procedure: +VideoInfo VideoInfo.ToOgv(String,VideoSize,AudioQuality,Boolean) + +### File: +Xabe.FFMpeg/VideoInfo.cs + +### Key: +VideoInfo.cs|ToOgv|DOTNET_RESOURCE_LEAK + +### Hash: +e710ba6c9a1bdcbadbb5fff33803ba39 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0161/instruction.md b/inferredbugs-0161/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4482eeda4f3678b5c7e39c7eea98afe1ab235ff8 --- /dev/null +++ b/inferredbugs-0161/instruction.md @@ -0,0 +1,383 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Xabe.FFmpeg +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using Xabe.FFMpeg.Enums; + +namespace Xabe.FFMpeg +{ + /// + /// Information about media file + /// + public class VideoInfo : IDisposable + { + /// + /// _sourceFile info + /// + + public readonly string FilePath; + + /// + /// Return extension of file + /// + public string Extension => Path.GetExtension(FilePath); + + private FFMpeg _ffmpeg; + + /// + /// Fires when conversion progress changed + /// + public ConversionHandler OnConversionProgress; + + /// + /// Get VideoInfo from file + /// + /// _sourceFile + public VideoInfo(FileInfo sourceFileInfo) : this(sourceFileInfo.FullName) + { + } + + /// + /// Get VideoInfo from file + /// + /// FilePath to file + public VideoInfo(string filePath) + { + if(!File.Exists(filePath)) + { + throw new ArgumentException($"Input file {filePath} doesn't exists."); + } + FilePath = filePath; + new FFProbe().ProbeDetails(this); + } + + private FFMpeg FFmpeg + { + get + { + if(_ffmpeg != null && + _ffmpeg.IsRunning) + throw new InvalidOperationException( + "Operation on this file is in progress."); + + return _ffmpeg ?? (_ffmpeg = new FFMpeg()); + } + } + + /// + /// duration of video + /// + public TimeSpan Duration { get; internal set; } + + /// + /// Audio format + /// + public string AudioFormat { get; internal set; } + + /// + /// Video format + /// + public string VideoFormat { get; internal set; } + + /// + /// Screen ratio + /// + public string Ratio { get; internal set; } + + /// + /// Frame rate + /// + public double FrameRate { get; internal set; } + + /// + /// Height + /// + public int Height { get; internal set; } + + /// + /// Width + /// + public int Width { get; internal set; } + + /// + /// size + /// + public double Size { get; internal set; } + + /// + /// Get the ffmpeg process status + /// + public bool IsRunning => FFmpeg.IsRunning; + + /// + /// Create VideoInfo from file + /// + /// _sourceFile + /// VideoInfo + public static VideoInfo FromFile(FileInfo fileInfo) + { + return new VideoInfo(fileInfo); + } + + /// + /// Get formated info about video + /// + /// Formated info about vidoe + public override string ToString() + { + return "Video FilePath : " + FilePath + Environment.NewLine + + "Video Root : " + Path.GetDirectoryName(FilePath)+ Environment.NewLine + + "Video Name: " + Path.GetFileName(FilePath) + Environment.NewLine + + "Video Extension : " + Extension + Environment.NewLine + + "Video duration : " + Duration + Environment.NewLine + + "Audio format : " + AudioFormat + Environment.NewLine + + "Video format : " + VideoFormat + Environment.NewLine + + "Aspect Ratio : " + Ratio + Environment.NewLine + + "Framerate : " + FrameRate + "fps" + Environment.NewLine + + "Resolution : " + Width + "x" + Height + Environment.NewLine + + "Size : " + Size + " MB"; + } + + /// + /// Convert file to TS + /// + /// Destination file + /// Output VideoInfo + public VideoInfo ToTs(string outputPath) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToTs(this, outputPath); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Convert file to WebM + /// + /// Destination file + /// Dimension + /// Audio quality + /// Output VideoInfo + public VideoInfo ToWebM(string outputPath, VideoSize size = VideoSize.Original, AudioQuality audioQuality = AudioQuality.Normal) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToWebM(this, outputPath, size, audioQuality); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Convert file to OGV + /// + /// Destination file + /// Dimension + /// Audio quality + /// Use multithread + /// Output VideoInfo + public VideoInfo ToOgv(string outputPath, VideoSize size = VideoSize.Original, AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToOgv(this, outputPath, size, audioQuality, multithread); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Convert file to MP4 + /// + /// Destination file + /// Conversion speed + /// Dimension + /// Audio quality + /// Use multithread + /// Output VideoInfo + public VideoInfo ToMp4(string outputPath, Speed speed = Speed.SuperFast, + VideoSize size = VideoSize.Original, AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToMp4(this, outputPath, speed, size, audioQuality, multithread); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Extract video from file + /// + /// Output audio stream + /// Conversion result + public bool ExtractVideo(string output) + { + return FFmpeg.ExtractVideo(this, output); + } + + /// + /// Extract audio from file + /// + /// Output video stream + /// Conversion result + public bool ExtractAudio(string output) + { + return FFmpeg.ExtractAudio(this, output); + } + + /// + /// Add audio to file + /// + /// Audio file + /// Output file + /// Conversion result + public bool AddAudio(FileInfo audio, string output) + { + return FFmpeg.AddAudio(this, audio, output); + } + + /// + /// Get snapshot of video + /// + /// Dimension of snapshot + /// + /// Snapshot + public Bitmap Snapshot(Size? size = null, TimeSpan? captureTime = null) + { + var output = $"{Environment.TickCount}.png"; + + bool success = FFmpeg.Snapshot(this, output, size, captureTime); + + if(!success) + throw new OperationCanceledException("Could not take snapshot!"); + + Bitmap result; + + using(Image bmp = Image.FromFile(output)) + { + using(var ms = new MemoryStream()) + { + bmp.Save(ms, ImageFormat.Png); + + result = new Bitmap(ms); + } + } + + if(File.Exists(output)) + File.Delete(output); + + return result; + } + + /// + /// Saves snapshot of video + /// + /// Output file + /// Dimension of snapshot + /// + /// Snapshot + public Bitmap Snapshot(string output, Size? size = null, TimeSpan? captureTime = null) + { + bool success = FFmpeg.Snapshot(this, output, size, captureTime); + + if(!success) + throw new OperationCanceledException("Could not take snapshot!"); + + Bitmap result; + + + using(Image bmp = Image.FromFile(System.IO.Path.ChangeExtension(output, ".png"))) + { + result = (Bitmap) bmp.Clone(); + } + + return result; + } + + /// + /// Concat multiple videos + /// + /// Concatenated videos + /// Videos to add + /// Conversion result + public bool JoinWith(string output, params VideoInfo[] videos) + { + List queuedVideos = videos.ToList(); + + queuedVideos.Insert(0, this); + + return FFmpeg.Join(output, queuedVideos.ToArray()); + } + + /// + public void Dispose() + { + FFmpeg.Stop(); + _ffmpeg?.Dispose(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type Xabe.FFMpeg.VideoInfo, Leaked resource (returned from Xabe.FFMpeg.FFMpeg Xabe.FFMpeg.VideoInfo::get_FFmpeg() at Line 209) of type Xabe.FFMpeg.FFMpeg, Leaked resource (returned from Xabe.FFMpeg.FFMpeg Xabe.FFMpeg.VideoInfo::get_FFmpeg() at Line 206) of type Xabe.FFMpeg.FFMpeg, Leaked resource (returned from Xabe.FFMpeg.FFMpeg Xabe.FFMpeg.VideoInfo::get_FFmpeg() at Line 205) of type Xabe.FFMpeg.FFMpeg in method "VideoInfo VideoInfo.ToMp4(String,Speed,VideoSize,AudioQuality,Boolean)". + +### Severity: +ERROR + +### Procedure: +VideoInfo VideoInfo.ToMp4(String,Speed,VideoSize,AudioQuality,Boolean) + +### File: +Xabe.FFMpeg/VideoInfo.cs + +### Key: +VideoInfo.cs|ToMp4|DOTNET_RESOURCE_LEAK + +### Hash: +3a319136da2fb4c3103b2c2f1a2cd68c + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0166/instruction.md b/inferredbugs-0166/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9985383be1bffb8156d7f9e2ad2ad5cf4aaedc56 --- /dev/null +++ b/inferredbugs-0166/instruction.md @@ -0,0 +1,253 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Xabe.FFmpeg +**Bug ID:** 25 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.IO; +using JetBrains.Annotations; + +namespace Xabe.FFMpeg +{ + /// + public class VideoInfo: IVideoInfo + { + private TimeSpan _videoDuration; + private bool _wasInitalized; + private TimeSpan _duration; + private string _audioFormat; + private TimeSpan _audioDuration; + private string _videoFormat; + private string _ratio; + private long _size; + private int _width; + private int _height; + private double _frameRate; + + /// + public VideoInfo(FileInfo sourceFileInfo): this(sourceFileInfo.FullName) + { + } + + /// + /// Get VideoInfo from file + /// + /// FullName to file + [UsedImplicitly] + public VideoInfo(string fullName) + { + if(!File.Exists(fullName)) + throw new ArgumentException($"Input file {fullName} doesn't exists."); + FullName = fullName; + } + + /// + public string FullName { get; } + + /// + public TimeSpan VideoDuration + { + get + { + if(!_wasInitalized) + // ReSharper disable once ObjectCreationAsStatement + { _wasInitalized = true; new FFProbe(this); } + return _videoDuration; + } + internal set => _videoDuration = value; + } + + /// + public string Extension => Path.GetExtension(FullName); + + /// + public TimeSpan Duration + { + get + { + if (!_wasInitalized) + // ReSharper disable once ObjectCreationAsStatement + { _wasInitalized = true; new FFProbe(this); } + return _duration; + } + internal set => _duration = value; + } + /// + public string AudioFormat + { + get + { + if (!_wasInitalized) + // ReSharper disable once ObjectCreationAsStatement + { _wasInitalized = true; new FFProbe(this); } + return _audioFormat; + } + internal set => _audioFormat = value; + } + + /// + public TimeSpan AudioDuration + { + get + { + if (!_wasInitalized) + // ReSharper disable once ObjectCreationAsStatement + { _wasInitalized = true; new FFProbe(this); } + return _audioDuration; + } + internal set => _audioDuration = value; + } + + /// + public string VideoFormat + { + get + { + if (!_wasInitalized) + // ReSharper disable once ObjectCreationAsStatement + { _wasInitalized = true; new FFProbe(this); } + return _videoFormat; + } + internal set => _videoFormat = value; + } + + /// + public string Ratio + { + get + { + if (!_wasInitalized) + // ReSharper disable once ObjectCreationAsStatement + { _wasInitalized = true; new FFProbe(this); } + return _ratio; + } + internal set => _ratio = value; + } + + /// + public double FrameRate + { + get + { + if (!_wasInitalized) + // ReSharper disable once ObjectCreationAsStatement + { _wasInitalized = true; new FFProbe(this); } + return _frameRate; + } + internal set => _frameRate = value; + } + + /// + public int Height + { + get + { + if (!_wasInitalized) + // ReSharper disable once ObjectCreationAsStatement + { _wasInitalized = true; new FFProbe(this); } + return _height; + } + internal set => _height = value; + } + + /// + public int Width + { + get + { + if (!_wasInitalized) + // ReSharper disable once ObjectCreationAsStatement + { _wasInitalized = true; new FFProbe(this); } + return _width; + } + internal set => _width = value; + } + + /// + public long Size + { + get + { + if (!_wasInitalized) + // ReSharper disable once ObjectCreationAsStatement + { _wasInitalized = true; new FFProbe(this); } + return _size; + } + internal set => _size = value; + } + + /// + [UsedImplicitly] + public override string ToString() + { + if(!_wasInitalized) + { _wasInitalized = true; new FFProbe(this); } + return $"Video fullName : {FullName}{Environment.NewLine}" + + $"Video root : {Path.GetDirectoryName(FullName)}{Environment.NewLine}" + + $"Video name: {Path.GetFileName(FullName)}{Environment.NewLine}" + + $"Video extension : {Extension}{Environment.NewLine}" + + $"Video duration : {VideoDuration}{Environment.NewLine}" + + $"Video format : {VideoFormat}{Environment.NewLine}" + + $"Audio format : {AudioFormat}{Environment.NewLine}" + + $"Audio duration : {AudioDuration}{Environment.NewLine}" + + $"Aspect Ratio : {Ratio}{Environment.NewLine}" + + $"Framerate : {Ratio} fps{Environment.NewLine}" + + $"Resolution : {Width} x {Height}{Environment.NewLine}" + + $"Size : {Size} b"; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Xabe.FFMpeg.FFProbe::.ctor() at Line 179) of type Xabe.FFMpeg.FFProbe in method "String VideoInfo.ToString()". + +### Severity: +ERROR + +### Procedure: +String VideoInfo.ToString() + +### File: +Xabe.FFMpeg/VideoInfo.cs + +### Key: +VideoInfo.cs|ToString|DOTNET_RESOURCE_LEAK + +### Hash: +7b4ae160fba656dd8ed844d7481d02f8 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0167/instruction.md b/inferredbugs-0167/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b4eb3c4e69adfbd21b5ccceeb809677d70fab5f1 --- /dev/null +++ b/inferredbugs-0167/instruction.md @@ -0,0 +1,771 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Lockstep-Tutorial +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Lockstep.Logging; +using Lockstep.Math; +using Lockstep.Serialization; +using NetMsg.Common; +using Lockstep.Util; +using Random = System.Random; + +namespace Lockstep.FakeServer { + public class Game : BaseLogger { + private delegate void DealNetMsg(Player player, BaseMsg data); + + private delegate BaseMsg ParseNetMsg(Deserializer reader); + + + public const int MaxPlayerCount = 2; + + public int MapId { get; set; } + public string GameHash { get; set; } + + public IPEndInfo TcpEnd { get; set; } + public IPEndInfo UdpEnd { get; set; } + + public EGameState State = EGameState.Idle; + public int GameType { get; set; } + public int GameId { get; set; } + + public long[] UserIds => _userId2LocalId.Keys.ToArray(); + + public int CurPlayerCount { + get { + int count = 0; + foreach (var player in Players) { + if (player != null) { + count++; + } + } + + return count; + } + } + + + public bool IsRunning { get; private set; } + public string Name; + public float TimeSinceCreate; + public bool IsFinished = false; + + public Msg_G2C_GameStartInfo GameStartInfo { get; set; } + + + private Dictionary _userId2LocalId = new Dictionary(); + public Player[] Players { get; private set; } + + + //hashcode + public int Tick = 0; + private Dictionary _hashCodes = new Dictionary(); + + + private const int MaxMsgIdx = (short) EMsgSC.EnumCount; + private DealNetMsg[] allMsgDealFuncs = new DealNetMsg[MaxMsgIdx]; + private ParseNetMsg[] allMsgParsers = new ParseNetMsg[MaxMsgIdx]; + + + private float _timeSinceLoaded; + private float _firstFrameTimeStamp = 0; + private float _waitTimer = 0; + + //所有需要等待输入到来的Ids + private List _allNeedWaitInputPlayerIds; + private List _allHistoryFrames = new List(); //所有的历史帧 + + private byte[] _playerLoadingProgress; + public const int MaxRepMissFrameCountPerPack = 600; + + public int Seed { get; set; } + + public void OnRecvPlayerGameData(Player player){ + if (player == null || MaxPlayerCount <= player.LocalId || Players[player.LocalId] != player) { + return; + } + + bool hasRecvAll = true; + foreach (var user in Players) { + if (user != null && user.GameData == null) { + hasRecvAll = false; + break; + } + } + + var playerCount = MaxPlayerCount; + if (hasRecvAll) { + //TODO + for (int i = 0; i < playerCount; i++) { + var helloMsg = new Msg_G2C_Hello() { + LocalId = (byte) i + }; + Players[i].SendTcp(EMsgSC.G2C_Hello, helloMsg); + } + + var userInfos = new GameData[playerCount]; + for (int i = 0; i < playerCount; i++) { + userInfos[i] = Players[i]?.GameData; + } + + //all user data ready notify game start + SetStartInfo(new Msg_G2C_GameStartInfo() { + MapId = MapId, + RoomId = GameId, + Seed = Seed, + UserCount = MaxPlayerCount, + TcpEnd = TcpEnd, + UdpEnd = UdpEnd, + SimulationSpeed = 30, + UserInfos = userInfos + }); + } + } + + + public int GetUserLocalId(long userId){ + if (_userId2LocalId.TryGetValue(userId, out var id)) { + return id; + } + + return -1; + } + + + #region life cycle + + public void DoStart(int gameId, int gameType, int mapId, Player[] playerInfos, string gameHash){ + State = EGameState.Loading; + Seed = LRandom.Range(1, 100000); + Tick = 0; + _timeSinceLoaded = 0; + _firstFrameTimeStamp = 0; + RegisterMsgHandlers(); + Debug = new DebugInstance("Room" + GameId + ": "); + var count = playerInfos.Length; + GameType = gameType; + GameHash = gameHash; + GameId = gameId; + Name = gameId.ToString(); + MapId = mapId; + Players = playerInfos; + _userId2LocalId.Clear(); + TimeSinceCreate = LTime.timeSinceLevelLoad; + for (byte i = 0; i < count; i++) { + var player = Players[i]; + _userId2LocalId.Add(player.UserId, player.LocalId); + } + + //Temp code + for (byte i = 0; i < count; i++) { + var player = Players[i]; + player.GameData = new GameData(); + OnRecvPlayerGameData(player); + } + } + + public void DoUpdate(float deltaTime){ + _timeSinceLoaded += deltaTime; + _waitTimer += deltaTime; + if (State != EGameState.Playing) return; + while (Tick < _tickSinceGameStart) { + _CheckBorderServerFrame(true); + } + } + + public void DoDestroy(){ + Log($"Room {GameId} Destroy"); + DumpGameFrames(); + } + + Player CreatePlayer(GamePlayerInfo playerInfo, byte localId){ + var player = Pool.Get(); + player.UserId = playerInfo.UserId; + player.Account = playerInfo.Account; + player.LoginHash = playerInfo.LoginHash; + player.LocalId = localId; + player.Game = this; + return player; + } + + private bool _CheckBorderServerFrame(bool isForce = false){ + if (State != EGameState.Playing) return false; + var frame = GetOrCreateFrame(Tick); + var inputs = frame.Inputs; + //超时等待 移除超时玩家 + //if (_waitTimer > (NetworkDefine.MAX_DELAY_TIME_MS / 1000.0f)) { + // _waitTimer = 0; + // //移除还没有到来的帧的Player + // for (int i = 0; i < inputs.Length; i++) { + // if (inputs[i] == null) { + // if (Players[i] != null) { + // Log($"Overtime wait remove localId = {i}"); + // } +// + // _allNeedWaitInputPlayerIds.Remove((byte) i); + // } + // } + //} + + //if (!isForce) { + // //是否所有的输入 都已经等到 + // foreach (var id in _allNeedWaitInputPlayerIds) { + // if (inputs[id] == null) { + // return false; + // } + // } + //} + if (!isForce) { + //是否所有的输入 都已经等到 + for (int i = 0; i < inputs.Length; i++) { + if (inputs[i] == null) { + return false; + } + } + } + + //将所有未到的包 给予默认的输入 + for (int i = 0; i < inputs.Length; i++) { + if (inputs[i] == null) { + inputs[i] = new Msg_PlayerInput(Tick, (byte) i); + } + } + + //Debug.Log("Border input " + Tick); + var msg = new Msg_ServerFrames(); + int count = Tick < 2 ? Tick + 1 : 3; + var frames = new ServerFrame[count]; + for (int i = 0; i < count; i++) { + frames[count - i - 1] = _allHistoryFrames[Tick - i]; + } + + msg.startTick = frames[0].tick; + msg.frames = frames; + BorderUdp(EMsgSC.G2C_FrameData, msg); + if (_firstFrameTimeStamp <= 0) { + _firstFrameTimeStamp = _timeSinceLoaded; + } + + Tick++; + return true; + } + + + private void DumpGameFrames(){ + var msg = new Msg_RepMissFrame(); + int count = System.Math.Min((Tick - 1), _allHistoryFrames.Count); + if (count <= 0) return; + var writer = new Serializer(); + GameStartInfo.Serialize(writer); + var frames = new ServerFrame[count]; + for (int i = 0; i < count; i++) { + frames[i] = _allHistoryFrames[i]; + Logging.Debug.Assert(frames[i] != null, "!!!!!!!!!!!!!!!!!"); + } + + msg.startTick = frames[0].tick; + msg.frames = frames; + msg.Serialize(writer); + var bytes = Compressor.Compress(writer); + var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, + "../Record/" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + GameType + "_" + GameId + + ".record"); + var dir = Path.GetDirectoryName(path); + if (!Directory.Exists(dir)) { + Directory.CreateDirectory(dir); + } + + Log("Create Record " + path); + File.WriteAllBytes(path, bytes); + } + + #endregion + + #region net msg + + public void SetStartInfo(Msg_G2C_GameStartInfo info){ + Debug.Log("SetStartInfo"); + GameStartInfo = info; + BorderTcp(EMsgSC.G2C_GameStartInfo, GameStartInfo); + } + + public void OnRecvMsg(Player player, Deserializer reader){ + if (reader.IsEnd) { + DealMsgHandlerError(player, $"{player.UserId} send a Error:Net Msg"); + return; + } + + var msgType = reader.ReadInt16(); + if (msgType >= MaxMsgIdx) { + DealMsgHandlerError(player, $"{player.UserId} send a Error msgType out of range {msgType}"); + return; + } + + //Debug.Log($"OnDataReceived netID = {player.localId} type:{(EMsgCS) msgType}"); + { + var _func = allMsgDealFuncs[msgType]; + var _parser = allMsgParsers[msgType]; + if (_func != null && _parser != null) { + var data = _parser(reader); + if (data == null) { + DealMsgHandlerError(player, + $"ErrorMsg type :parser data error playerID = {player.UserId} msgType:{msgType}"); + return; + } + + _func(player, data); + } + else { + DealMsgHandlerError(player, + $" {player.UserId} ErrorMsg type :no msg handler or parser {msgType}"); + } + } + } + + void DealMsgHandlerError(Player player, string msg){ + LogError(msg); + TickOut(player, 0); + } + + public void TickOut(Player player, int reason){ + //_gameServer.TickOut(player, reason); + } + + private void RegisterMsgHandlers(){ + RegisterHandler(EMsgSC.C2G_PlayerInput, C2G_PlayerInput, + (reader) => { return ParseData(reader); }); + RegisterHandler(EMsgSC.C2G_HashCode, C2G_HashCode, + (reader) => { return ParseData(reader); }); + RegisterHandler(EMsgSC.C2G_LoadingProgress, C2G_LoadingProgress, + (reader) => { return ParseData(reader); }); + RegisterHandler(EMsgSC.C2G_ReqMissFrame, C2G_ReqMissFrame, + (reader) => { return ParseData(reader); }); + RegisterHandler(EMsgSC.C2G_RepMissFrameAck, C2G_RepMissFrameAck, + (reader) => { return ParseData(reader); }); + } + + private void RegisterHandler(EMsgSC type, DealNetMsg func, ParseNetMsg parseFunc){ + allMsgDealFuncs[(int) type] = func; + allMsgParsers[(int) type] = parseFunc; + } + + T ParseData(Deserializer reader) where T : BaseMsg, new(){ + T data = null; + try { + data = reader.Parse(); + if (!reader.IsEnd) { + data = null; + } + } + catch (Exception e) { + LogError("Parse Msg Error:" + e); + data = null; + } + + return data; + } + + public void BorderTcp(EMsgSC type, BaseMsg data){ + var bytes = data.ToBytes(); + foreach (var player in Players) { + player?.SendTcp(type, bytes); + } + } + + public void BorderUdp(EMsgSC type, byte[] data){ + foreach (var player in Players) { + SendUdp(player, type, data); + } + } + + public void BorderUdp(EMsgSC type, ISerializable body){ + var writer = new Serializer(); + body.Serialize(writer); + var bytes = writer.CopyData(); + foreach (var player in Players) { + player?.SendUdp(type, bytes); + } + } + + + public void SendUdp(Player player, EMsgSC type, byte[] data){ + player?.SendUdp(type, data); + } + + public void SendUdp(Player player, EMsgSC type, ISerializable body, bool isNeedDebugSize = false){ + var writer = new Serializer(); + body.Serialize(writer); + player?.SendUdp(type, writer.CopyData()); + } + + #endregion + + #region net status + + public void OnPlayerConnect(Player player){ + if (GameStartInfo != null) { + player.SendTcp(EMsgSC.G2C_GameStartInfo, GameStartInfo); + } + } + + //net status + public void OnPlayerReconnect(GamePlayerInfo playerInfo){ + var localId = _userId2LocalId[playerInfo.UserId]; + var player = CreatePlayer(playerInfo, localId); + Players[localId] = player; + } + + public void OnPlayerReconnect(Player player){ + player.LocalId = _userId2LocalId[player.UserId]; + Players[player.LocalId] = player; + } + + public void OnPlayerDisconnect(Player player){ + Log($"Player{player.UserId} OnDisconnect room {GameId}"); + RemovePlayer(player); + } + + public void OnPlayerLeave(long userId){ + if (_userId2LocalId.TryGetValue(userId, out var localId)) { + var player = Players[localId]; + if (player != null) { + OnPlayerLeave(player); + } + } + } + + public void OnPlayerLeave(Player player){ + RemovePlayer(player); + _userId2LocalId.Remove(player.UserId); //同时还需要彻底的移除记录 避免玩家重连 + Log($"Player{player.UserId} OnPlayerLeave room {GameId}"); + } + + void RemovePlayer(Player player){ + if (Players[player.LocalId] == null) return; + Players[player.LocalId] = null; + var peer = player.PeerTcp; + peer?.Dispose(); + + player.PeerTcp = null; + peer = player.PeerUdp; + peer?.Dispose(); + + player.PeerUdp = null; + + var curCount = CurPlayerCount; + if (curCount == 0) { + Log("All players left, stopping current simulation..."); + IsRunning = false; + State = EGameState.Idle; + //_gameServer.OnGameEmpty(this); + } + else { + Log(curCount + " players remaining."); + } + } + + #endregion + + #region game status + + public void StartGame(){ } + + public void FinishedGame(){ } + + #endregion + + #region IRecyclable + + //回收时候调用 + public void OnReuse(){ } + + public void OnRecycle(){ + _userId2LocalId.Clear(); + _hashCodes.Clear(); + Tick = 0; + GameId = -1; + if (Players == null) return; + foreach (var player in Players) { + Pool.Return(player); + } + + Players = null; + } + + #endregion + + #region Net msg handler + + public void OnNetMsg(Player player, ushort opcode, BaseMsg msg){ + var type = (EMsgSC) opcode; + switch (type) { + //login + //room + case EMsgSC.C2G_PlayerInput: + C2G_PlayerInput(player, msg); + break; + case EMsgSC.C2G_HashCode: + C2G_HashCode(player, msg); + break; + case EMsgSC.C2G_LoadingProgress: + C2G_LoadingProgress(player, msg); + break; + case EMsgSC.C2G_ReqMissFrame: + C2G_ReqMissFrame(player, msg); + break; + case EMsgSC.C2G_RepMissFrameAck: + C2G_RepMissFrameAck(player, msg); + break; + default: + Debug.Log("Unknow msg " + type); + break; + } + } + + public long _gameStartTimestampMs; + public int _ServerTickDealy = 2; + + public int _tickSinceGameStart => + (int) ((LTime.realtimeSinceStartupMS - _gameStartTimestampMs) / NetworkDefine.UPDATE_DELTATIME); + + void C2G_PlayerInput(Player player, BaseMsg data){ + if (State != EGameState.PartLoaded && State != EGameState.Playing) return; + if (State == EGameState.PartLoaded) { + Log("First input: game start playing"); + State = EGameState.Playing; + _gameStartTimestampMs = + LTime.realtimeSinceStartupMS + NetworkDefine.UPDATE_DELTATIME * _ServerTickDealy; + } + + var input = data as Msg_PlayerInput; +#if DEBUG_SHOW_INPUT + if (input.Commands.Length > 0) { + var cmd = input.Commands[0]; + var playerInput = new Deserializer(cmd.content).Parse(); + if (playerInput.inputUV != LVector2.zero) { + Debug.Log( $"curTick{Tick} isOutdate{input.Tick < Tick} RecvInput actorID:{input.ActorId} inputTick:{input.Tick} move:{playerInput.inputUV}"); + } + } +#endif + + //Debug.Log($"RecvInput actorID:{input.ActorId} inputTick:{input.Tick} Tick{Tick}"); + if (input.Tick < Tick) { + return; + } + + var frame = GetOrCreateFrame(input.Tick); + + var id = input.ActorId; + if (!_allNeedWaitInputPlayerIds.Contains(id)) { + _allNeedWaitInputPlayerIds.Add(id); + } + + frame.Inputs[id] = input; + + while (_CheckBorderServerFrame(false)) { } + } + + ServerFrame GetOrCreateFrame(int tick){ + //扩充帧队列 + var frameCount = _allHistoryFrames.Count; + if (frameCount <= tick) { + var count = tick - _allHistoryFrames.Count + 1; + for (int i = 0; i < count; i++) { + _allHistoryFrames.Add(null); + } + } + + if (_allHistoryFrames[tick] == null) { + _allHistoryFrames[tick] = new ServerFrame() {tick = tick}; + } + + var frame = _allHistoryFrames[tick]; + if (frame.Inputs == null || frame.Inputs.Length != MaxPlayerCount) { + frame.Inputs = new Msg_PlayerInput[MaxPlayerCount]; + } + + return frame; + } + + + void C2G_HashCode(Player player, BaseMsg data){ + var hashInfo = data as Msg_HashCode; + var id = player.LocalId; + for (int i = 0; i < hashInfo.HashCodes.Length; i++) { + var code = hashInfo.HashCodes[i]; + var tick = hashInfo.StartTick + i; + //Debug.Log($"tick: {tick} Hash {code}" ); + if (_hashCodes.TryGetValue(tick, out HashCodeMatcher matcher1)) { + if (matcher1 == null || matcher1.sendResult[id]) { + continue; + } + + if (matcher1.hashCode != code) { + OnHashMatchResult(tick, code, false); + } + + matcher1.count = matcher1.count + 1; + matcher1.sendResult[id] = true; + if (matcher1.IsMatchered) { + OnHashMatchResult(tick, code, true); + } + } + else { + var matcher2 = new HashCodeMatcher(MaxPlayerCount); + matcher2.count = 1; + matcher2.hashCode = code; + matcher2.sendResult[id] = true; + _hashCodes.Add(tick, matcher2); + if (matcher2.IsMatchered) { + OnHashMatchResult(tick, code, true); + } + } + } + } + + + void OnHashMatchResult(int tick, long hash, bool isMatched){ + if (isMatched) { + _hashCodes[tick] = null; + } + + if (!isMatched) { + Log($"!!!!!!!!!!!! Hash not match tick{tick} hash{hash} "); + } + } + + + void C2G_ReqMissFrame(Player player, BaseMsg data){ + var reqMsg = data as Msg_ReqMissFrame; + var nextCheckTick = reqMsg.StartTick; + Log($"C2G_ReqMissFrame nextCheckTick id:{player.LocalId}:{nextCheckTick}"); + int count = System.Math.Min(System.Math.Min((Tick - 1), _allHistoryFrames.Count) - nextCheckTick, + MaxRepMissFrameCountPerPack); + if (count <= 0) return; + var msg = new Msg_RepMissFrame(); + var frames = new ServerFrame[count]; + for (int i = 0; i < count; i++) { + frames[i] = _allHistoryFrames[nextCheckTick + i]; + Logging.Debug.Assert(frames[i] != null); + } + + msg.startTick = frames[0].tick; + msg.frames = frames; + SendUdp(player, EMsgSC.G2C_RepMissFrame, msg, true); + } + + void C2G_RepMissFrameAck(Player player, BaseMsg data){ + var msg = data as Msg_RepMissFrameAck; + Log($"C2G_RepMissFrameAck missFrameTick:{msg.MissFrameTick}"); + } + + + void C2G_LoadingProgress(Player player, BaseMsg data){ + if (State != EGameState.Loading) return; + var msg = data as Msg_C2G_LoadingProgress; + if (_playerLoadingProgress == null) { + _playerLoadingProgress = new byte[MaxPlayerCount]; + } + + _playerLoadingProgress[player.LocalId] = msg.Progress; + + //Log($"palyer{player.LocalId} Load {msg.Progress}"); + + BorderTcp(EMsgSC.G2C_LoadingProgress, new Msg_G2C_LoadingProgress() { + Progress = _playerLoadingProgress + }); + + if (msg.Progress < 100) return; + var isDone = true; + foreach (var progress in _playerLoadingProgress) { + if (progress < 100) { + isDone = false; + break; + } + } + + if (isDone) { + OnFinishedLoaded(); + } + } + + + void OnFinishedLoaded(){ + Log("All Load done"); + State = EGameState.PartLoaded; + for (int i = 0; i < _playerLoadingProgress.Length; i++) { + _playerLoadingProgress[i] = 0; + } + + _allNeedWaitInputPlayerIds = new List(); + foreach (var val in _userId2LocalId.Values) { + _allNeedWaitInputPlayerIds.Add(val); + } + + //BorderTcp(EMsgSC.G2C_GameStartInfo, GameStartInfo); + BorderTcp(EMsgSC.G2C_AllFinishedLoaded, new Msg_G2C_AllFinishedLoaded() { }); + } + + #endregion + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `input` last assigned on line 539 could be null and is dereferenced at line 551, column 13. + +### Severity: +ERROR + +### Procedure: +Void Game.C2G_PlayerInput(Player,BaseMsg) + +### File: +Server/Src/SimpleServer/Src/Server/Game.cs + +### Key: +Game.cs|C2G_PlayerInput|NULL_DEREFERENCE + +### Node Key: +09edcf2a75ac2f8cb6226ac52778403c + +### Hash: +290197c80f46558e40231c567b2f004d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0168/instruction.md b/inferredbugs-0168/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9f27d89a9118d32639b935c3ea3c230555fc9611 --- /dev/null +++ b/inferredbugs-0168/instruction.md @@ -0,0 +1,293 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ServiceStack.Text +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// +// https://github.com/ServiceStack/ServiceStack.Text +// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. +// +// Authors: +// Demis Bellot (demis.bellot@gmail.com) +// +// Copyright 2012 ServiceStack Ltd. +// +// Licensed under the same terms of ServiceStack: new BSD license. +// + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Threading; +using System.Linq; +using ServiceStack.Text.Json; + +namespace ServiceStack.Text.Common +{ + internal delegate void WriteMapDelegate( + TextWriter writer, + object oMap, + WriteObjectDelegate writeKeyFn, + WriteObjectDelegate writeValueFn); + + internal static class WriteDictionary + where TSerializer : ITypeSerializer + { + private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer(); + + internal class MapKey + { + internal Type KeyType; + internal Type ValueType; + + public MapKey(Type keyType, Type valueType) + { + KeyType = keyType; + ValueType = valueType; + } + + public bool Equals(MapKey other) + { + if (ReferenceEquals(null, other)) return false; + if (ReferenceEquals(this, other)) return true; + return Equals(other.KeyType, KeyType) && Equals(other.ValueType, ValueType); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + if (obj.GetType() != typeof(MapKey)) return false; + return Equals((MapKey)obj); + } + + public override int GetHashCode() + { + unchecked + { + return ((KeyType != null ? KeyType.GetHashCode() : 0) * 397) ^ (ValueType != null ? ValueType.GetHashCode() : 0); + } + } + } + + static Dictionary CacheFns = new Dictionary(); + + public static Action + GetWriteGenericDictionary(Type keyType, Type valueType) + { + WriteMapDelegate writeFn; + var mapKey = new MapKey(keyType, valueType); + if (CacheFns.TryGetValue(mapKey, out writeFn)) return writeFn.Invoke; + + var genericType = typeof(ToStringDictionaryMethods<,,>).MakeGenericType(keyType, valueType, typeof(TSerializer)); + var mi = genericType.GetPublicStaticMethod("WriteIDictionary"); + writeFn = (WriteMapDelegate)mi.MakeDelegate(typeof(WriteMapDelegate)); + + Dictionary snapshot, newCache; + do + { + snapshot = CacheFns; + newCache = new Dictionary(CacheFns); + newCache[mapKey] = writeFn; + + } while (!ReferenceEquals( + Interlocked.CompareExchange(ref CacheFns, newCache, snapshot), snapshot)); + + return writeFn.Invoke; + } + + public static void WriteIDictionary(TextWriter writer, object oMap) + { + WriteObjectDelegate writeKeyFn = null; + WriteObjectDelegate writeValueFn = null; + + writer.Write(JsWriter.MapStartChar); + var encodeMapKey = false; + + var map = (IDictionary)oMap; + var ranOnce = false; + foreach (var key in map.Keys) + { + var dictionaryValue = map[key]; + + var isNull = (dictionaryValue == null); + if (isNull && !Serializer.IncludeNullValues) continue; + + if (writeKeyFn == null) + { + var keyType = key.GetType(); + writeKeyFn = Serializer.GetWriteFn(keyType); + encodeMapKey = Serializer.GetTypeInfo(keyType).EncodeMapKey; + } + + if (writeValueFn == null) + writeValueFn = Serializer.GetWriteFn(dictionaryValue.GetType()); + + JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); + + JsState.WritingKeyCount++; + JsState.IsWritingValue = false; + + if (encodeMapKey) + { + JsState.IsWritingValue = true; //prevent ""null"" + writer.Write(JsWriter.QuoteChar); + writeKeyFn(writer, key); + writer.Write(JsWriter.QuoteChar); + } + else + { + writeKeyFn(writer, key); + } + + JsState.WritingKeyCount--; + + writer.Write(JsWriter.MapKeySeperator); + + if (isNull) + { + writer.Write(JsonUtils.Null); + } + else + { + JsState.IsWritingValue = true; + writeValueFn(writer, dictionaryValue); + JsState.IsWritingValue = false; + } + } + + writer.Write(JsWriter.MapEndChar); + } + } + + internal static class ToStringDictionaryMethods + where TSerializer : ITypeSerializer + { + private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer(); + + public static void WriteIDictionary( + TextWriter writer, + object oMap, + WriteObjectDelegate writeKeyFn, + WriteObjectDelegate writeValueFn) + { + if (writer == null) return; //AOT + WriteGenericIDictionary(writer, (IDictionary)oMap, writeKeyFn, writeValueFn); + } + + public static void WriteGenericIDictionary( + TextWriter writer, + IDictionary map, + WriteObjectDelegate writeKeyFn, + WriteObjectDelegate writeValueFn) + { + if (map == null) + { + writer.Write(JsonUtils.Null); + return; + } + writer.Write(JsWriter.MapStartChar); + + var encodeMapKey = Serializer.GetTypeInfo(typeof(TKey)).EncodeMapKey; + + var ranOnce = false; + foreach (var kvp in map) + { + var isNull = (kvp.Value == null); + if (isNull && !Serializer.IncludeNullValues) continue; + + JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); + + JsState.WritingKeyCount++; + JsState.IsWritingValue = false; + + if (encodeMapKey) + { + JsState.IsWritingValue = true; //prevent ""null"" + writer.Write(JsWriter.QuoteChar); + writeKeyFn(writer, kvp.Key); + writer.Write(JsWriter.QuoteChar); + } + else + { + writeKeyFn(writer, kvp.Key); + } + + JsState.WritingKeyCount--; + + writer.Write(JsWriter.MapKeySeperator); + + if (isNull) + { + writer.Write(JsonUtils.Null); + } + else + { + JsState.IsWritingValue = true; + writeValueFn(writer, kvp.Value); + JsState.IsWritingValue = false; + } + } + + writer.Write(JsWriter.MapEndChar); + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `dictionaryValue` last assigned on line 107 could be null and is dereferenced at line 120, column 6. + +### Severity: +ERROR + +### Procedure: +Void WriteDictionary`1.WriteIDictionary(TextWriter,Object) + +### File: +src/ServiceStack.Text/Common/WriteDictionary.cs + +### Key: +WriteDictionary.cs|WriteIDictionary|NULL_DEREFERENCE + +### Node Key: +277c5e4fc7793eba679254e42372b233 + +### Hash: +61e59a1bd1b57f50d7ea49062f87a00a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0169/instruction.md b/inferredbugs-0169/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..42b3136ed2ce74ca17e25abb896b581c82676711 --- /dev/null +++ b/inferredbugs-0169/instruction.md @@ -0,0 +1,300 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ServiceStack.Text +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// +// https://github.com/ServiceStack/ServiceStack.Text +// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. +// +// Authors: +// Demis Bellot (demis.bellot@gmail.com) +// +// Copyright 2012 Service Stack LLC. All Rights Reserved. +// +// Licensed under the same terms of ServiceStack. +// + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Threading; +using System.Linq; +using ServiceStack.Text.Json; + +namespace ServiceStack.Text.Common +{ + internal delegate void WriteMapDelegate( + TextWriter writer, + object oMap, + WriteObjectDelegate writeKeyFn, + WriteObjectDelegate writeValueFn); + + internal static class WriteDictionary + where TSerializer : ITypeSerializer + { + private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer(); + + internal class MapKey + { + internal Type KeyType; + internal Type ValueType; + + public MapKey(Type keyType, Type valueType) + { + KeyType = keyType; + ValueType = valueType; + } + + public bool Equals(MapKey other) + { + if (ReferenceEquals(null, other)) return false; + if (ReferenceEquals(this, other)) return true; + return Equals(other.KeyType, KeyType) && Equals(other.ValueType, ValueType); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + if (obj.GetType() != typeof(MapKey)) return false; + return Equals((MapKey)obj); + } + + public override int GetHashCode() + { + unchecked + { + return ((KeyType != null ? KeyType.GetHashCode() : 0) * 397) ^ (ValueType != null ? ValueType.GetHashCode() : 0); + } + } + } + + static Dictionary CacheFns = new Dictionary(); + + public static Action + GetWriteGenericDictionary(Type keyType, Type valueType) + { + WriteMapDelegate writeFn; + var mapKey = new MapKey(keyType, valueType); + if (CacheFns.TryGetValue(mapKey, out writeFn)) return writeFn.Invoke; + + var genericType = typeof(ToStringDictionaryMethods<,,>).MakeGenericType(keyType, valueType, typeof(TSerializer)); + var mi = genericType.GetStaticMethod("WriteIDictionary"); + writeFn = (WriteMapDelegate)mi.MakeDelegate(typeof(WriteMapDelegate)); + + Dictionary snapshot, newCache; + do + { + snapshot = CacheFns; + newCache = new Dictionary(CacheFns); + newCache[mapKey] = writeFn; + + } while (!ReferenceEquals( + Interlocked.CompareExchange(ref CacheFns, newCache, snapshot), snapshot)); + + return writeFn.Invoke; + } + + public static void WriteIDictionary(TextWriter writer, object oMap) + { + WriteObjectDelegate writeKeyFn = null; + WriteObjectDelegate writeValueFn = null; + + writer.Write(JsWriter.MapStartChar); + var encodeMapKey = false; + Type lastKeyType = null; + Type lastValueType = null; + + var map = (IDictionary)oMap; + var ranOnce = false; + foreach (var key in map.Keys) + { + var dictionaryValue = map[key]; + + var isNull = (dictionaryValue == null); + if (isNull && !Serializer.IncludeNullValues) continue; + + var keyType = key.GetType(); + if (writeKeyFn == null || lastKeyType != keyType) + { + lastKeyType = keyType; + writeKeyFn = Serializer.GetWriteFn(keyType); + encodeMapKey = Serializer.GetTypeInfo(keyType).EncodeMapKey; + } + + JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); + + JsState.WritingKeyCount++; + JsState.IsWritingValue = false; + + if (encodeMapKey) + { + JsState.IsWritingValue = true; //prevent ""null"" + writer.Write(JsWriter.QuoteChar); + writeKeyFn(writer, key); + writer.Write(JsWriter.QuoteChar); + } + else + { + writeKeyFn(writer, key); + } + + JsState.WritingKeyCount--; + + writer.Write(JsWriter.MapKeySeperator); + + if (isNull) + { + writer.Write(JsonUtils.Null); + } + else + { + var valueType = dictionaryValue.GetType(); + if (writeValueFn == null || lastValueType != valueType) + { + lastValueType = valueType; + writeValueFn = Serializer.GetWriteFn(valueType); + } + + JsState.IsWritingValue = true; + writeValueFn(writer, dictionaryValue); + JsState.IsWritingValue = false; + } + } + + writer.Write(JsWriter.MapEndChar); + } + } + + public static class ToStringDictionaryMethods + where TSerializer : ITypeSerializer + { + private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer(); + + public static void WriteIDictionary( + TextWriter writer, + object oMap, + WriteObjectDelegate writeKeyFn, + WriteObjectDelegate writeValueFn) + { + if (writer == null) return; //AOT + WriteGenericIDictionary(writer, (IDictionary)oMap, writeKeyFn, writeValueFn); + } + + public static void WriteGenericIDictionary( + TextWriter writer, + IDictionary map, + WriteObjectDelegate writeKeyFn, + WriteObjectDelegate writeValueFn) + { + if (map == null) + { + writer.Write(JsonUtils.Null); + return; + } + writer.Write(JsWriter.MapStartChar); + + var encodeMapKey = Serializer.GetTypeInfo(typeof(TKey)).EncodeMapKey; + + var ranOnce = false; + foreach (var kvp in map) + { + var isNull = (kvp.Value == null); + if (isNull && !Serializer.IncludeNullValues) continue; + + JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); + + JsState.WritingKeyCount++; + JsState.IsWritingValue = false; + + if (encodeMapKey) + { + JsState.IsWritingValue = true; //prevent ""null"" + writer.Write(JsWriter.QuoteChar); + writeKeyFn(writer, kvp.Key); + writer.Write(JsWriter.QuoteChar); + } + else + { + writeKeyFn(writer, kvp.Key); + } + + JsState.WritingKeyCount--; + + writer.Write(JsWriter.MapKeySeperator); + + if (isNull) + { + writer.Write(JsonUtils.Null); + } + else + { + JsState.IsWritingValue = true; + writeValueFn(writer, kvp.Value); + JsState.IsWritingValue = false; + } + } + + writer.Write(JsWriter.MapEndChar); + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `dictionaryValue` last assigned on line 107 could be null and is dereferenced at line 120, column 6. + +### Severity: +ERROR + +### Procedure: +Void WriteDictionary`1.WriteIDictionary(TextWriter,Object) + +### File: +src/ServiceStack.Text/Common/WriteDictionary.cs + +### Key: +WriteDictionary.cs|WriteIDictionary|NULL_DEREFERENCE + +### Node Key: +277c5e4fc7793eba679254e42372b233 + +### Hash: +61e59a1bd1b57f50d7ea49062f87a00a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0192/instruction.md b/inferredbugs-0192/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2aba50957ce3d007bdd078c3ef2eb6d8a0513ae2 --- /dev/null +++ b/inferredbugs-0192/instruction.md @@ -0,0 +1,146 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** NEventStore +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace EventStore +{ + using System; + using System.Collections.Generic; + using Dispatcher; + using Persistence; + + public class OptimisticEventStore : IStoreEvents, ICommitEvents + { + private readonly CommitTracker tracker = new CommitTracker(); + private readonly IPersistStreams persistence; + private readonly IDispatchCommits dispatcher; + + public OptimisticEventStore(IPersistStreams persistence, IDispatchCommits dispatcher) + { + this.persistence = persistence; + this.dispatcher = dispatcher; + } + + public virtual IEventStream CreateStream(Guid streamId) + { + return new OptimisticEventStream(streamId, this.persistence); + } + public virtual IEventStream OpenStream(Guid streamId, int minRevision, int maxRevision) + { + var commits = this.persistence.GetFrom(streamId, minRevision, maxRevision); + var stream = new OptimisticEventStream(streamId, this, minRevision, maxRevision, commits); + return stream.CommitSequence == 0 ? null : stream; + } + + public virtual IEnumerable GetFrom(Guid streamId, int minRevision, int maxRevision) + { + var commits = this.persistence.GetFrom(streamId, minRevision, maxRevision); + foreach (var commit in commits) + { + this.tracker.Track(commit); + yield return commit; + } + } + + public virtual void Commit(Commit attempt) + { + if (!attempt.IsValid() || attempt.IsEmpty()) + return; + + this.ThrowOnDuplicateOrConcurrentWrites(attempt); + this.PersistAndDispatch(attempt); + } + protected virtual void ThrowOnDuplicateOrConcurrentWrites(Commit attempt) + { + if (this.tracker.Contains(attempt)) + throw new DuplicateCommitException(); + + var head = this.tracker.GetStreamHead(attempt.StreamId); + if (head == null) + return; + + if (head.CommitSequence >= attempt.CommitSequence) + throw new ConcurrencyException(); + + if (head.StreamRevision >= attempt.StreamRevision) + throw new ConcurrencyException(); + + if (head.CommitSequence < attempt.CommitSequence) + throw new StorageException(); // beyond the end of the stream + + if (head.StreamRevision < attempt.StreamRevision - attempt.Events.Count) + throw new StorageException(); // beyond the end of the stream + } + protected virtual void PersistAndDispatch(Commit attempt) + { + this.persistence.Commit(attempt); + this.tracker.Track(attempt); + this.dispatcher.Dispatch(attempt); + } + + public virtual Snapshot GetSnapshot(Guid streamId, int maxRevision) + { + // TODO: cache + return this.persistence.GetSnapshot(streamId, maxRevision); + } + public virtual bool AddSnapshot(Snapshot snapshot) + { + // TODO: update cache + return this.persistence.AddSnapshot(snapshot); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type EventStore.OptimisticEventStream, Leaked resource stream of type EventStore.OptimisticEventStream in method "IEventStream OptimisticEventStore.OpenStream(Guid,Int32,Int32)". + +### Severity: +ERROR + +### Procedure: +IEventStream OptimisticEventStore.OpenStream(Guid,Int32,Int32) + +### File: +src/proj/EventStore.Core/OptimisticEventStore.cs + +### Key: +OptimisticEventStore.cs|OpenStream|DOTNET_RESOURCE_LEAK + +### Hash: +7662e6ac925bdc48f65917a14cae4b94 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0193/instruction.md b/inferredbugs-0193/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af5cbea5fa4104c227e1a52bb2b81e77c31d5c65 --- /dev/null +++ b/inferredbugs-0193/instruction.md @@ -0,0 +1,151 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** linq2db.EntityFrameworkCore +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using JetBrains.Annotations; +using LinqToDB.Linq; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; + +namespace LinqToDB.EntityFrameworkCore +{ + using Data; + + public static partial class LinqToDBForEFTools + { + #region BulkCopy + + /// + /// Performs bulk insert operation. + /// + /// Mapping type of inserted record. + /// Database context. + /// Operation options. + /// Records to insert. + /// Bulk insert operation status. + public static BulkCopyRowsCopied BulkCopy([NotNull] this DbContext context, BulkCopyOptions options, IEnumerable source) + { + if (context == null) throw new ArgumentNullException(nameof(context)); + + return context.CreateLinqToDbConnection().BulkCopy(options, source); + } + + /// + /// Performs bulk insert operation. + /// + /// Mapping type of inserted record. + /// Database context. + /// Number of rows in each batch. At the end of each batch, the rows in the batch are sent to the server. + /// Records to insert. + /// Bulk insert operation status. + public static BulkCopyRowsCopied BulkCopy([NotNull] this DbContext context, int maxBatchSize, IEnumerable source) + { + if (context == null) throw new ArgumentNullException(nameof(context)); + + var dataConnection = context.CreateLinqToDbConnection(); + + return dataConnection.DataProvider.BulkCopy( + dataConnection, + new BulkCopyOptions { MaxBatchSize = maxBatchSize }, + source); + } + + /// + /// Performs bulk insert operation. + /// + /// Mapping type of inserted record. + /// Database context. + /// Records to insert. + /// Bulk insert operation status. + public static BulkCopyRowsCopied BulkCopy([NotNull] this DbContext context, IEnumerable source) + { + if (context == null) throw new ArgumentNullException(nameof(context)); + + var dataConnection = context.CreateLinqToDbConnection(); + + return dataConnection.DataProvider.BulkCopy( + dataConnection, + new BulkCopyOptions(), + source); + } + + #endregion + + #region Value Insertable + + /// + /// Starts LINQ query definition for insert operation. + /// + /// Target table mapping class. + /// Database context. + /// Target table. + /// Insertable source query. + [LinqTunnel] + [Pure] + public static IValueInsertable Into([NotNull] this DbContext context, [NotNull] ITable target) + { + if (context == null) throw new ArgumentNullException(nameof(context)); + if (target == null) throw new ArgumentNullException(nameof(target)); + + return context.CreateLinqToDbConnection().Into(target); + } + + #endregion + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource dataConnection of type LinqToDB.Data.DataConnection in method "BulkCopyRowsCopied LinqToDBForEFTools.BulkCopy(DbContext,IEnumerable`1)". + +### Severity: +ERROR + +### Procedure: +BulkCopyRowsCopied LinqToDBForEFTools.BulkCopy(DbContext,IEnumerable`1) + +### File: +Source/LinqToDB.EntityFrameworkCore/LinqToDBForEFTools.ContextExtensions.cs + +### Key: +LinqToDBForEFTools.ContextExtensions.cs|BulkCopy|DOTNET_RESOURCE_LEAK + +### Hash: +75f64d3b817b09748a3500438eddf3d0 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0194/instruction.md b/inferredbugs-0194/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..71b9c6878456da622c70b94cf8c98437ed47c2a2 --- /dev/null +++ b/inferredbugs-0194/instruction.md @@ -0,0 +1,151 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** linq2db.EntityFrameworkCore +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using JetBrains.Annotations; +using LinqToDB.Linq; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; + +namespace LinqToDB.EntityFrameworkCore +{ + using Data; + + public static partial class LinqToDBForEFTools + { + #region BulkCopy + + /// + /// Performs bulk insert operation. + /// + /// Mapping type of inserted record. + /// Database context. + /// Operation options. + /// Records to insert. + /// Bulk insert operation status. + public static BulkCopyRowsCopied BulkCopy([NotNull] this DbContext context, BulkCopyOptions options, IEnumerable source) + { + if (context == null) throw new ArgumentNullException(nameof(context)); + + return context.CreateLinqToDbConnection().BulkCopy(options, source); + } + + /// + /// Performs bulk insert operation. + /// + /// Mapping type of inserted record. + /// Database context. + /// Number of rows in each batch. At the end of each batch, the rows in the batch are sent to the server. + /// Records to insert. + /// Bulk insert operation status. + public static BulkCopyRowsCopied BulkCopy([NotNull] this DbContext context, int maxBatchSize, IEnumerable source) + { + if (context == null) throw new ArgumentNullException(nameof(context)); + + var dataConnection = context.CreateLinqToDbConnection(); + + return dataConnection.DataProvider.BulkCopy( + dataConnection, + new BulkCopyOptions { MaxBatchSize = maxBatchSize }, + source); + } + + /// + /// Performs bulk insert operation. + /// + /// Mapping type of inserted record. + /// Database context. + /// Records to insert. + /// Bulk insert operation status. + public static BulkCopyRowsCopied BulkCopy([NotNull] this DbContext context, IEnumerable source) + { + if (context == null) throw new ArgumentNullException(nameof(context)); + + var dataConnection = context.CreateLinqToDbConnection(); + + return dataConnection.DataProvider.BulkCopy( + dataConnection, + new BulkCopyOptions(), + source); + } + + #endregion + + #region Value Insertable + + /// + /// Starts LINQ query definition for insert operation. + /// + /// Target table mapping class. + /// Database context. + /// Target table. + /// Insertable source query. + [LinqTunnel] + [Pure] + public static IValueInsertable Into([NotNull] this DbContext context, [NotNull] ITable target) + { + if (context == null) throw new ArgumentNullException(nameof(context)); + if (target == null) throw new ArgumentNullException(nameof(target)); + + return context.CreateLinqToDbConnection().Into(target); + } + + #endregion + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from LinqToDB.Data.DataConnection LinqToDB.EntityFrameworkCore.LinqToDBForEFTools::CreateLinqToDbConnection(Microsoft.EntityFrameworkCore.DbContext,Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction) at Line 27) of type LinqToDB.Data.DataConnection in method "BulkCopyRowsCopied LinqToDBForEFTools.BulkCopy(DbContext,BulkCopyOptions,IEnumerable`1)". + +### Severity: +ERROR + +### Procedure: +BulkCopyRowsCopied LinqToDBForEFTools.BulkCopy(DbContext,BulkCopyOptions,IEnumerable`1) + +### File: +Source/LinqToDB.EntityFrameworkCore/LinqToDBForEFTools.ContextExtensions.cs + +### Key: +LinqToDBForEFTools.ContextExtensions.cs|BulkCopy|DOTNET_RESOURCE_LEAK + +### Hash: +bdfaa036462ad9e1013f0709b6117e68 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0216/instruction.md b/inferredbugs-0216/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dbc93ad5b10c6d73cad481f3edff5d6619015e43 --- /dev/null +++ b/inferredbugs-0216/instruction.md @@ -0,0 +1,208 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** PluginCore +**Bug ID:** 8 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using PluginCore.Models; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Mvc.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.FileProviders; +using PluginCore.Authorization; +using PluginCore.AdminUI; +using PluginCore.Middlewares; + +namespace PluginCore.Extensions +{ + /// + /// + /// + public static class PluginCoreStartupExtensions + { + private static IWebHostEnvironment _webHostEnvironment; + + public static void AddPluginCore(this IServiceCollection services) + { + // 用于添加插件Controller 时,通知Controller.Action发生变化 + services.AddSingleton(PluginActionDescriptorChangeProvider.Instance); + services.AddSingleton(PluginActionDescriptorChangeProvider.Instance); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + using (var serviceProvider = services.BuildServiceProvider()) + { + using (var scope = serviceProvider.GetRequiredService().CreateScope()) + { + PluginManager pluginManager = scope.ServiceProvider.GetService(); + + // 初始化 PluginCore 相关目录 + PluginPathProvider.PluginsRootPath(); + + // 在程序启动时加载所有 已安装的插件 + + // 获取PluginConfigModel + #region 获取 获取PluginConfigModel + PluginConfigModel pluginConfigModel = PluginConfigModelFactory.Create(); + #endregion + + // 已启用的插件 + #region 加载 已启用插件的Assemblies + IList enabledPluginIds = pluginConfigModel.EnabledPlugins; + foreach (var pluginId in enabledPluginIds) + { + pluginManager.LoadPlugin(pluginId); + } + #endregion + + + + // 将本 Assembly 内的 Controller 添加 + var ass = Assembly.GetExecutingAssembly(); + PluginControllerManager pluginControllerManager = scope.ServiceProvider.GetService(); + pluginControllerManager.AddControllers(ass); + + + // IWebHostEnvironment + _webHostEnvironment = scope.ServiceProvider.GetService(); + } + } + + // 1. 先 Authentication (我是谁) 2. 再 Authorization (我能做什么) + + // fixed: https://github.com/yiyungent/PluginCore/issues/4 + // System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions). + #region 添加认证 Authentication + // 没通过 Authentication: 401 Unauthorized + services.AddAuthentication("PluginCore.Authentication") + .AddScheme("PluginCore.Authentication", "PluginCore.Authentication", + options => { }); + #endregion + + #region 添加授权策略-所有标记 [PluginCoreAdminAuthorize] 都需要权限检查 + services.AddSingleton(); + + services.AddAuthorization(options => + { + options.AddPolicy("PluginCoreAdmin", policy => + { + // 无法满足 下方任何一项:HTTP 403 错误 + // 3.需要 检查是否拥有当前请求资源的权限 + policy.Requirements.Add(new PluginCoreAdminRequirement()); + }); + }); + #endregion + + + // AccountManager + services.AddTransient(); + // HttpContext.Current + services.TryAddSingleton(); + //services.AddHttpContextAccessor(); + + } + + public static IApplicationBuilder UsePluginCore(this IApplicationBuilder app) + { + app.UsePluginCoreAdminUI(); + + // 由于没办法在运行时, 动态 UseStaticFiles(), 因此不再为每一个插件都 UseStaticFiles(), + // 而是统一在一个文件夹下, 插件启用时, 将插件的wwwroot复制到 Plugins_wwwroot/{PluginId}, 禁用时, 再删除 + string pluginwwwrootDir = PluginPathProvider.PluginsWwwRootDir(); + app.UseStaticFiles(new StaticFileOptions + { + FileProvider = new PhysicalFileProvider( + pluginwwwrootDir), + RequestPath = "/Plugins" + }); + + + // 发现 UseAuthentication 认证中间件重复添加, 也只会执行一次 认证 + // 但 UseAuthorization 重复添加2次, 则会执行 2次 授权 + app.UseAuthentication(); + app.UseAuthorization(); + + // Plugin Middleware + //app.UseMiddleware(); + + + + Config.PluginCoreConfig pluginCoreConfig = Config.PluginCoreConfigFactory.Create(); + + Utils.LogUtil.Info("启动成功:"); + Utils.LogUtil.Info($"前端模式: {pluginCoreConfig.FrontendMode}"); + Utils.LogUtil.Info($"注意: 更新前端模式 需要 重启站点"); + + return app; + } + + + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Microsoft.Extensions.FileProviders.PhysicalFileProvider::.ctor() at Line 120) of type Microsoft.Extensions.FileProviders.PhysicalFileProvider in method "IApplicationBuilder PluginCoreStartupExtensions.UsePluginCore(IApplicationBuilder)". + +### Severity: +ERROR + +### Procedure: +IApplicationBuilder PluginCoreStartupExtensions.UsePluginCore(IApplicationBuilder) + +### File: +src/PluginCore/Extensions/PluginCoreStartupExtensions.cs + +### Key: +PluginCoreStartupExtensions.cs|UsePluginCore|DOTNET_RESOURCE_LEAK + +### Hash: +8658203f92b8758367489a5309831f46 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0229/instruction.md b/inferredbugs-0229/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..106f3028c0ed2c965b5477b1795e1365fd325f17 --- /dev/null +++ b/inferredbugs-0229/instruction.md @@ -0,0 +1,237 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Jil +**Bug ID:** 5 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Jil.Deserialize +{ + static class NewtonsoftStyleTypeCache + { + static readonly object InitLock = new object(); + static Func Thunk; + public static Exception ExceptionDuringBuild; + + public static Func Get() + { + if (Thunk != null) return Thunk; + + lock (InitLock) + { + if (Thunk != null) return Thunk; + + Thunk = InlineDeserializerHelper.Build(typeof(NewtonsoftStyleTypeCache<>), DateTimeFormat.NewtonsoftStyleMillisecondsSinceUnixEpoch, allowHashing: true, exceptionDuringBuild: out ExceptionDuringBuild); + + return Thunk; + } + } + } + + static class NewtonsoftStyleNoHashingTypeCache + { + static readonly object InitLock = new object(); + static Func Thunk; + public static Exception ExceptionDuringBuild; + + public static Func Get() + { + if (Thunk != null) return Thunk; + + lock (InitLock) + { + if (Thunk != null) return Thunk; + + Thunk = InlineDeserializerHelper.Build(typeof(NewtonsoftStyleNoHashingTypeCache<>), DateTimeFormat.NewtonsoftStyleMillisecondsSinceUnixEpoch, allowHashing: false, exceptionDuringBuild: out ExceptionDuringBuild); + + return Thunk; + } + } + } + + static class MillisecondStyleTypeCache + { + static readonly object InitLock = new object(); + static Func Thunk; + public static Exception ExceptionDuringBuild; + + public static Func Get() + { + if (Thunk != null) return Thunk; + + lock (InitLock) + { + if (Thunk != null) return Thunk; + + Thunk = InlineDeserializerHelper.Build(typeof(MillisecondStyleTypeCache<>), DateTimeFormat.MillisecondsSinceUnixEpoch, allowHashing: true, exceptionDuringBuild: out ExceptionDuringBuild); + + return Thunk; + } + } + } + + static class MillisecondStyleNoHashingTypeCache + { + static readonly object InitLock = new object(); + static Func Thunk; + public static Exception ExceptionDuringBuild; + + public static Func Get() + { + if (Thunk != null) return Thunk; + + lock (InitLock) + { + if (Thunk != null) return Thunk; + + Thunk = InlineDeserializerHelper.Build(typeof(MillisecondStyleNoHashingTypeCache<>), DateTimeFormat.MillisecondsSinceUnixEpoch, allowHashing: false, exceptionDuringBuild: out ExceptionDuringBuild); + + return Thunk; + } + } + } + + static class SecondStyleTypeCache + { + static readonly object InitLock = new object(); + static Func Thunk; + public static Exception ExceptionDuringBuild; + + public static Func Get() + { + if (Thunk != null) return Thunk; + + lock (InitLock) + { + if (Thunk != null) return Thunk; + + Thunk = InlineDeserializerHelper.Build(typeof(SecondStyleTypeCache<>), DateTimeFormat.SecondsSinceUnixEpoch, allowHashing: true, exceptionDuringBuild: out ExceptionDuringBuild); + + return Thunk; + } + } + } + + static class SecondStyleNoHashingTypeCache + { + static readonly object InitLock = new object(); + static Func Thunk; + public static Exception ExceptionDuringBuild; + + public static Func Get() + { + if (Thunk != null) return Thunk; + + lock (InitLock) + { + if (Thunk != null) return Thunk; + + Thunk = InlineDeserializerHelper.Build(typeof(SecondStyleNoHashingTypeCache<>), DateTimeFormat.SecondsSinceUnixEpoch, allowHashing: false, exceptionDuringBuild: out ExceptionDuringBuild); + + return Thunk; + } + } + } + + static class ISO8601StyleTypeCache + { + static readonly object InitLock = new object(); + static Func Thunk; + public static Exception ExceptionDuringBuild; + + public static Func Get() + { + if (Thunk != null) return Thunk; + + lock (InitLock) + { + if (Thunk != null) return Thunk; + + Thunk = InlineDeserializerHelper.Build(typeof(ISO8601StyleTypeCache<>), DateTimeFormat.ISO8601, allowHashing: true, exceptionDuringBuild: out ExceptionDuringBuild); + + return Thunk; + } + } + } + + static class ISO8601StyleNoHashingTypeCache + { + static readonly object InitLock = new object(); + static Func Thunk; + public static Exception ExceptionDuringBuild; + + public static Func Get() + { + if (Thunk != null) return Thunk; + + lock (InitLock) + { + if (Thunk != null) return Thunk; + + Thunk = InlineDeserializerHelper.Build(typeof(ISO8601StyleNoHashingTypeCache<>), DateTimeFormat.ISO8601, allowHashing: false, exceptionDuringBuild: out ExceptionDuringBuild); + + return Thunk; + } + } + } +} + +``` + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `SecondStyleTypeCache`1.Get()` reads without synchronization from `Deserialize.SecondStyleTypeCache`1.Jil.Deserialize.SecondStyleTypeCache`1.Thunk`. Potentially races with write in method `SecondStyleTypeCache`1.Get()`. + Reporting because this access may occur on a background thread. + +### Severity: +WARNING + +### Procedure: +Func`2 SecondStyleTypeCache`1.Get() + +### File: +Jil/Deserialize/TypeCaches.cs + +### Key: +TypeCaches.cs|Get|THREAD_SAFETY_VIOLATION + +### Hash: +f742c4353ea14b92c475e8245b816487 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0301/instruction.md b/inferredbugs-0301/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b021a363853fefc05df3ea63f40cf489291b8e3e --- /dev/null +++ b/inferredbugs-0301/instruction.md @@ -0,0 +1,212 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** kiota +**Bug ID:** 9 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Linq; +using Xunit; + +namespace Kiota.Builder.Refiners.Tests { + public class RubyLanguageRefinerTests { + + private readonly CodeNamespace graphNS; + private readonly CodeClass parentClass; + private readonly CodeNamespace root = CodeNamespace.InitRootNamespace(); + public RubyLanguageRefinerTests() { + root = CodeNamespace.InitRootNamespace(); + graphNS = root.AddNamespace("graph"); + parentClass = new (graphNS) { + Name = "parentClass" + }; + graphNS.AddClass(parentClass); + } + #region CommonLanguageRefinerTests + [Fact] + public void AddsDefaultImports() { + var model = root.AddClass(new CodeClass (root) { + Name = "model", + ClassKind = CodeClassKind.Model + }).First(); + var requestBuilder = root.AddClass(new CodeClass(root) { + Name = "rb", + ClassKind = CodeClassKind.RequestBuilder, + }).First(); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.NotEmpty(model.StartBlock.Usings); + Assert.NotEmpty(requestBuilder.StartBlock.Usings); + } + [Fact] + public void ReplacesImportsSubNamespace() { + var rootNS = parentClass.Parent as CodeNamespace; + rootNS.RemoveChildElement(parentClass); + graphNS.AddClass(parentClass); + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var subNS = graphNS.AddNamespace($"{graphNS.Name}.messages"); + var messageClassDef = new CodeClass(subNS) { + Name = "Message", + }; + declaration.Usings.Add(new (parentClass) { + Name = "graph", + Declaration = new(parentClass) { + Name = "Message", + TypeDefinition = messageClassDef, + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.Equal("./messages/message", declaration.Usings.First().Declaration.Name); + } + [Fact] + public void ReplacesImportsParentNamespace() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var subNS = root.AddNamespace("messages"); + var messageClassDef = new CodeClass(subNS) { + Name = "Message", + }; + subNS.AddClass(messageClassDef); + declaration.Usings.Add(new (parentClass) { + Name = "messages", + Declaration = new(parentClass) { + Name = "Message", + TypeDefinition = messageClassDef, + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.Equal("../messages/message", declaration.Usings.First().Declaration.Name); + } + [Fact] + public void ReplacesImportsSameNamespace() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var messageClassDef = new CodeClass(graphNS) { + Name = "Message", + }; + declaration.Usings.Add(new (parentClass) { + Name = "graph", + Declaration = new(parentClass) { + Name = "Message", + TypeDefinition = messageClassDef, + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.Equal("./message", declaration.Usings.First().Declaration.Name); + } + #endregion + #region RubyLanguageRefinerTests + [Fact] + public void EscapesReservedKeywords() { + var model = root.AddClass(new CodeClass (root) { + Name = "break", + ClassKind = CodeClassKind.Model + }).First(); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.NotEqual("break", model.Name); + Assert.Contains("escaped", model.Name); + } + [Fact] + public void AddInheritedAndMethodTypesImports() { + var model = root.AddClass(new CodeClass (root) { + Name = "model", + ClassKind = CodeClassKind.Model + }).First(); + var declaration = model.StartBlock as CodeClass.Declaration; + declaration.Inherits = new (parentClass){ + Name = "someInterface" + }; + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.Equal("./someInterface", declaration.Usings.First().Declaration.Name); + } + [Fact] + public void FixInheritedEntityType() { + var model = root.AddClass(new CodeClass (root) { + Name = "model", + ClassKind = CodeClassKind.Model + }).First(); + var entity = graphNS.AddClass(new CodeClass (root) { + Name = "entity", + ClassKind = CodeClassKind.Model + }).First(); + var declaration = model.StartBlock as CodeClass.Declaration; + declaration.Inherits = new (entity){ + Name = "entity" + }; + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.Equal("Graph::Entity", declaration.Inherits.Name); + } + [Fact] + public void AddNamespaceModuleImports() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var subNS = graphNS.AddNamespace("messages"); + var messageClassDef = new CodeClass(subNS) { + Name = "Message", + }; + subNS.AddClass(messageClassDef); + declaration.Usings.Add(new (parentClass) { + Name = "messages", + Declaration = new(parentClass) { + Name = "Message", + TypeDefinition = messageClassDef, + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.Equal("../messages/message", declaration.Usings.First().Declaration.Name); + Assert.Equal("./graph", declaration.Usings.Last().Declaration.Name); + } + #endregion + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `declaration` last assigned on line 73 could be null and is dereferenced at line 77, column 13. + +### Severity: +ERROR + +### Procedure: +Void RubyLanguageRefinerTests.ReplacesImportsSameNamespace() + +### File: +tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs + +### Key: +RubyLanguageRefinerTests.cs|ReplacesImportsSameNamespace|NULL_DEREFERENCE + +### Node Key: +ef91c4941a914fb0bf4a21cb3664ec51 + +### Hash: +bf0015206a7c301c2dc7dd21293504ac + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0306/instruction.md b/inferredbugs-0306/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e266f14458efd738f8249ebb20c545296bf5b9ff --- /dev/null +++ b/inferredbugs-0306/instruction.md @@ -0,0 +1,238 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** kiota +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Linq; +using Xunit; + +namespace Kiota.Builder.Refiners.Tests { + public class TypeScriptLanguageRefinerTests { + private readonly CodeNamespace root; + private readonly CodeNamespace graphNS; + private readonly CodeClass parentClass; + public TypeScriptLanguageRefinerTests() { + root = CodeNamespace.InitRootNamespace(); + graphNS = root.AddNamespace("graph"); + parentClass = new (graphNS) { + Name = "parentClass" + }; + graphNS.AddClass(parentClass); + } +#region common + [Fact] + public void ReplacesImportsSubNamespace() { + var rootNS = parentClass.Parent as CodeNamespace; + rootNS.RemoveChildElement(parentClass); + graphNS.AddClass(parentClass); + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var subNS = graphNS.AddNamespace($"{graphNS.Name}.messages"); + var messageClassDef = new CodeClass(subNS) { + Name = "Message", + }; + declaration.Usings.Add(new (parentClass) { + Name = "graph", + Declaration = new(parentClass) { + Name = "Message", + TypeDefinition = messageClassDef, + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.TypeScript }, root); + Assert.Equal("./messages/message", declaration.Usings.First().Declaration.Name); + } + [Fact] + public void ReplacesImportsParentNamespace() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var subNS = root.AddNamespace("messages"); + var messageClassDef = new CodeClass(subNS) { + Name = "Message", + }; + subNS.AddClass(messageClassDef); + declaration.Usings.Add(new (parentClass) { + Name = "messages", + Declaration = new(parentClass) { + Name = "Message", + TypeDefinition = messageClassDef, + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.TypeScript }, root); + Assert.Equal("../messages/message", declaration.Usings.First().Declaration.Name); + } + [Fact] + public void ReplacesImportsSameNamespace() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var messageClassDef = new CodeClass(graphNS) { + Name = "Message", + }; + declaration.Usings.Add(new (parentClass) { + Name = "graph", + Declaration = new(parentClass) { + Name = "Message", + TypeDefinition = messageClassDef, + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.TypeScript }, root); + Assert.Equal("./message", declaration.Usings.First().Declaration.Name); + } +#endregion +#region typescript + private const string HttpCoreDefaultName = "IHttpCore"; + private const string FactoryDefaultName = "ISerializationWriterFactory"; + private const string DeserializeDefaultName = "IDictionary>"; + private const string DateTimeOffsetDefaultName = "DateTimeOffset"; + private const string AddiationalDataDefaultName = "new Dictionary()"; + private const string HandlerDefaultName = "IResponseHandler"; + [Fact] + public void EscapesReservedKeywords() { + var model = root.AddClass(new CodeClass (root) { + Name = "break", + ClassKind = CodeClassKind.Model + }).First(); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.TypeScript }, root); + Assert.NotEqual("break", model.Name); + Assert.Contains("escaped", model.Name); + } + [Fact] + public void CorrectsCoreType() { + + var model = root.AddClass(new CodeClass (root) { + Name = "model", + ClassKind = CodeClassKind.Model + }).First(); + model.AddProperty(new (model) { + Name = "core", + PropertyKind = CodePropertyKind.HttpCore, + Type = new CodeType(model) { + Name = HttpCoreDefaultName + } + }, new (model) { + Name = "someDate", + PropertyKind = CodePropertyKind.Custom, + Type = new CodeType(model) { + Name = DateTimeOffsetDefaultName, + } + }, new (model) { + Name = "additionalData", + PropertyKind = CodePropertyKind.AdditionalData, + Type = new CodeType(model) { + Name = AddiationalDataDefaultName + } + }); + var executorMethod = model.AddMethod(new CodeMethod(model) { + Name = "executor", + MethodKind = CodeMethodKind.RequestExecutor, + ReturnType = new CodeType(model) { + Name = "string" + } + }).First(); + executorMethod.AddParameter(new CodeParameter(executorMethod) { + Name = "handler", + ParameterKind = CodeParameterKind.ResponseHandler, + Type = new CodeType(executorMethod) { + Name = HandlerDefaultName, + } + }); + const string serializerDefaultName = "ISerializationWriter"; + var serializationMethod = model.AddMethod(new CodeMethod(model) { + Name = "seriailization", + MethodKind = CodeMethodKind.Serializer, + ReturnType = new CodeType(model) { + Name = "string" + } + }).First(); + serializationMethod.AddParameter(new CodeParameter(serializationMethod) { + Name = "handler", + ParameterKind = CodeParameterKind.Serializer, + Type = new CodeType(executorMethod) { + Name = serializerDefaultName, + } + }); + var responseHandlerMethod = model.AddMethod(new CodeMethod(model) { + Name = "defaultResponseHandler", + ReturnType = new CodeType(model) { + Name = "string" + } + }, new (model) { + Name = "deserializeFields", + ReturnType = new CodeType(model) { + Name = DeserializeDefaultName, + }, + MethodKind = CodeMethodKind.Deserializer + }).First(); + const string streamDefaultName = "Stream"; + responseHandlerMethod.AddParameter(new CodeParameter(responseHandlerMethod) { + Name = "param1", + Type = new CodeType(responseHandlerMethod) { + Name = streamDefaultName + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration{ Language = GenerationLanguage.TypeScript }, root); + Assert.Empty(model.GetChildElements(true).OfType().Where(x => HttpCoreDefaultName.Equals(x.Type.Name))); + Assert.Empty(model.GetChildElements(true).OfType().Where(x => FactoryDefaultName.Equals(x.Type.Name))); + Assert.Empty(model.GetChildElements(true).OfType().Where(x => DateTimeOffsetDefaultName.Equals(x.Type.Name))); + Assert.Empty(model.GetChildElements(true).OfType().Where(x => AddiationalDataDefaultName.Equals(x.Type.Name))); + Assert.Empty(model.GetChildElements(true).OfType().Where(x => DeserializeDefaultName.Equals(x.ReturnType.Name))); + Assert.Empty(model.GetChildElements(true).OfType().SelectMany(x => x.Parameters).Where(x => HandlerDefaultName.Equals(x.Type.Name))); + Assert.Empty(model.GetChildElements(true).OfType().SelectMany(x => x.Parameters).Where(x => serializerDefaultName.Equals(x.Type.Name))); + Assert.Empty(model.GetChildElements(true).OfType().SelectMany(x => x.Parameters).Where(x => streamDefaultName.Equals(x.Type.Name))); + } + } +#endregion +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `declaration` last assigned on line 40 could be null and is dereferenced at line 46, column 13. + +### Severity: +ERROR + +### Procedure: +Void TypeScriptLanguageRefinerTests.ReplacesImportsParentNamespace() + +### File: +tests/Kiota.Builder.Tests/Refiners/TypeScriptLanguageRefinerTests.cs + +### Key: +TypeScriptLanguageRefinerTests.cs|ReplacesImportsParentNamespace|NULL_DEREFERENCE + +### Node Key: +ef91c4941a914fb0bf4a21cb3664ec51 + +### Hash: +1a2a2ce11981f39b7bd8de91aa5b82a7 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0308/instruction.md b/inferredbugs-0308/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a6c271a69e84cf6be10fd4804e8b3b6463e3e1e1 --- /dev/null +++ b/inferredbugs-0308/instruction.md @@ -0,0 +1,157 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** kiota +**Bug ID:** 17 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.IO; +using System.Linq; +using Xunit; + +namespace Kiota.Builder.Writers.Ruby.Tests { + public class CodeClassDeclarationWriterTests : IDisposable + { + private const string DefaultPath = "./"; + private const string DefaultName = "name"; + private readonly StringWriter tw; + private readonly LanguageWriter writer; + private readonly CodeClassDeclarationWriter codeElementWriter; + private readonly CodeClass parentClass; + + public CodeClassDeclarationWriterTests() { + codeElementWriter = new CodeClassDeclarationWriter(new RubyConventionService(), "graph"); + writer = LanguageWriter.GetLanguageWriter(GenerationLanguage.Ruby, DefaultPath, DefaultName); + tw = new StringWriter(); + writer.SetTextWriter(tw); + var root = CodeNamespace.InitRootNamespace(); + parentClass = new () { + Name = "parentClass" + }; + root.AddClass(parentClass); + } + public void Dispose() { + tw?.Dispose(); + GC.SuppressFinalize(this); + } + [Fact] + public void WritesSimpleDeclaration() { + codeElementWriter.WriteCodeElement(parentClass.StartBlock as CodeClass.Declaration, writer); + var result = tw.ToString(); + Assert.Contains("class", result); + } + [Fact] + public void WritesImplementation() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + declaration.AddImplements(new CodeType { + Name = "someInterface" + }); + codeElementWriter.WriteCodeElement(declaration, writer); + var result = tw.ToString(); + Assert.Contains("include", result); + } + [Fact] + public void WritesInheritance() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + declaration.Inherits = new (){ + Name = "someInterface" + }; + codeElementWriter.WriteCodeElement(declaration, writer); + var result = tw.ToString(); + Assert.Contains("<", result); + } + [Fact] + public void WritesImports() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var messageClass = parentClass.GetImmediateParentOfType().AddClass( new CodeClass { + Name = "Message" + }).First(); + declaration.AddUsings(new () { + Name = "Objects", + Declaration = new() { + Name = "util", + IsExternal = true, + } + }, + new () { + Name = "project-graph", + Declaration = new() { + Name = "Message", + TypeDefinition = messageClass, + } + }); + codeElementWriter.WriteCodeElement(declaration, writer); + var result = tw.ToString(); + Assert.Contains("require_relative", result); + Assert.Contains("message", result); + Assert.Contains("require", result); + } + [Fact] + public void WritesMixins() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + declaration.AddImplements(new CodeType { + Name = "test" + }); + codeElementWriter.WriteCodeElement(declaration, writer); + var result = tw.ToString(); + Assert.Contains("include", result); + Assert.Contains("test", result); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `declaration` last assigned on line 85 could be null and is dereferenced at line 86, column 13. + +### Severity: +ERROR + +### Procedure: +Void CodeClassDeclarationWriterTests.WritesMixins() + +### File: +tests/Kiota.Builder.Tests/Writers/Ruby/CodeClassDeclarationWriterTests.cs + +### Key: +CodeClassDeclarationWriterTests.cs|WritesMixins|NULL_DEREFERENCE + +### Node Key: +9ff6f66912dc2a3a36e0c52dc18cdd65 + +### Hash: +6dd8b45918f24f343132fe00eb4b2afe + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0330/instruction.md b/inferredbugs-0330/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0335b46cb2a928f2aaecb21d0d189387e5a4b1c2 --- /dev/null +++ b/inferredbugs-0330/instruction.md @@ -0,0 +1,121 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** sentakki +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence. +// See the LICENCE file in the repository root for full licence text. + +using System.Collections.Generic; +using osu.Framework.Graphics; +using osu.Framework.Graphics.Sprites; +using osu.Framework.Graphics.Textures; +using osu.Framework.Input.Bindings; +using osu.Game.Beatmaps; +using osu.Game.Rulesets.Difficulty; +using osu.Game.Rulesets.Mods; +using osu.Game.Rulesets.maimai.Beatmaps; +using osu.Game.Rulesets.maimai.Mods; +using osu.Game.Rulesets.maimai.UI; +using osu.Game.Rulesets.UI; + +namespace osu.Game.Rulesets.maimai +{ + public class maimaiRuleset : Ruleset + { + public maimaiRuleset(RulesetInfo rulesetInfo = null) + : base(rulesetInfo) + { + } + + public override string Description => "Washing machine rhythm game."; + + public override DrawableRuleset CreateDrawableRulesetWith(IWorkingBeatmap beatmap, IReadOnlyList mods) => + new DrawablemaimaiRuleset(this, beatmap, mods); + + public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => + new maimaiBeatmapConverter(beatmap); + + public override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => + new maimaiDifficultyCalculator(this, beatmap); + + public override IEnumerable GetModsFor(ModType type) + { + switch (type) + { + case ModType.Automation: + return new[] { new maimaiModAutoplay() }; + + default: + return new Mod[] { null }; + } + } + + public override string ShortName => "maimai"; + + public override IEnumerable GetDefaultKeyBindings(int variant = 0) => new[] + { + new KeyBinding(InputKey.Z, maimaiAction.Button1), + new KeyBinding(InputKey.X, maimaiAction.Button2), + }; + + public override Drawable CreateIcon() => new Sprite + { + Texture = new TextureStore(new TextureLoaderStore(CreateResourceStore()), false).Get("Textures/coin"), + }; + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type osu.Framework.Graphics.Sprites.Sprite, Leaked resource (output of osu.Framework.Graphics.Textures.TextureStore::.ctor() at Line 57) of type osu.Framework.Graphics.Textures.TextureStore, Leaked resource (output of osu.Framework.Graphics.Textures.TextureLoaderStore::.ctor() at Line 57) of type osu.Framework.Graphics.Textures.TextureLoaderStore in method "Drawable maimaiRuleset.CreateIcon()". + +### Severity: +ERROR + +### Procedure: +Drawable maimaiRuleset.CreateIcon() + +### File: +osu.Game.Rulesets.maimai/maimaiRuleset.cs + +### Key: +maimaiRuleset.cs|CreateIcon|DOTNET_RESOURCE_LEAK + +### Hash: +853f1cc6cde2a880707d25406252392b + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0337/instruction.md b/inferredbugs-0337/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..31498c6e5efafbea9af5bba642916127b9d01217 --- /dev/null +++ b/inferredbugs-0337/instruction.md @@ -0,0 +1,132 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** FbxWriter +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Text; +using System.IO; + +namespace Fbx +{ + class Program + { + static void Encrypt(byte[] a, byte[] b) + { + byte c = 64; + for (int i = 0; i < 16; i++) + { + a[i] = (byte)(a[i] ^ (byte)(c ^ b[i])); + c = a[i]; + } + } + + static void PrintBytes(byte[] array) + { + foreach(var b in array) + Console.Write(b + " "); + Console.Write("\n"); + } + + private static readonly byte[] sourceId = { 0x58, 0xAB, 0xA9, 0xF0, 0x6C, 0xA2, 0xD8, 0x3F, 0x4D, 0x47, 0x49, 0xA3, 0xB4, 0xB2, 0xE7, 0x3D }; + private static readonly byte[] key = { 0xE2, 0x4F, 0x7B, 0x5F, 0xCD, 0xE4, 0xC8, 0x6D, 0xDB, 0xD8, 0xFB, 0xD7, 0x40, 0x58, 0xC6, 0x78 }; + + static void Main(string[] args) + { + Console.WriteLine("Start"); + var stream = new FileStream(args[0], FileMode.Open); + int version; + var node = (new FbxBinaryReader(stream)).Read(out version); + stream.Close(); + + stream = new FileStream(args[1], FileMode.Create); + (new FbxBinaryWriter(stream)).Write(node); + stream.Close(); + + /*var timestamp = node["FBXHeaderExtension"]["CreationTimeStamp"]; + + var year = (int)timestamp["Year"].Properties[0]; + var month = (int)timestamp["Month"].Properties[0]; + var day = (int)timestamp["Day"].Properties[0]; + var hour = (int)timestamp["Hour"].Properties[0]; + var minute = (int)timestamp["Minute"].Properties[0]; + var second = (int)timestamp["Second"].Properties[0]; + var millisecond = (int)timestamp["Millisecond"].Properties[0]; + + var mangledtime = $"{second:00}{month:00}{hour:00}{day:00}{(millisecond/10):00}{year:0000}{minute:00}"; + + Console.WriteLine(mangledtime); + + var mangledBytes = Encoding.ASCII.GetBytes(mangledtime); + + if(mangledBytes.Length != 16) + throw new Exception(); + + var str = (byte[])sourceId.Clone(); + Encrypt(str, mangledBytes); + Encrypt(str, key); + Encrypt(str, mangledBytes); + + PrintBytes(footer); + PrintBytes(str);*/ + + + //Console.ReadLine(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Fbx.FbxBinaryWriter::.ctor() at Line 39).Fbx.FbxBinaryWriter.stream of type System.IO.BinaryWriter, Leaked resource (output of Fbx.FbxBinaryWriter::.ctor() at Line 39).Fbx.FbxBinaryWriter.memory of type System.IO.MemoryStream, Leaked resource (output of Fbx.FbxBinaryReader::.ctor() at Line 35).Fbx.FbxBinaryReader.stream of type System.IO.BinaryReader in method "Void Program.Main(String[])". + +### Severity: +ERROR + +### Procedure: +Void Program.Main(String[]) + +### File: +Fbx/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +69e8c8694f3f8b3c8a01309ed06c58a6 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0339/instruction.md b/inferredbugs-0339/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..36c6963aa9f3015a88478fc80c25f3f49ce80f41 --- /dev/null +++ b/inferredbugs-0339/instruction.md @@ -0,0 +1,82 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** FbxWriter +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Text; +using System.IO; + +namespace Fbx +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("Start"); + var stream = new FileStream(args[0], FileMode.Open); + int version; + var node = (new FbxBinaryReader(stream)).Read(out version); + stream.Close(); + + stream = new FileStream(args[1], FileMode.Create); + (new FbxBinaryWriter(stream)).Write(node); + stream.Close(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Fbx.FbxBinaryWriter::.ctor() at Line 19).Fbx.FbxBinaryWriter.stream of type System.IO.BinaryWriter, Leaked resource (output of Fbx.FbxBinaryWriter::.ctor() at Line 19).Fbx.FbxBinaryWriter.memory of type System.IO.MemoryStream, Leaked resource (output of Fbx.FbxBinaryReader::.ctor() at Line 15).Fbx.FbxBinaryReader.stream of type System.IO.BinaryReader in method "Void Program.Main(String[])". + +### Severity: +ERROR + +### Procedure: +Void Program.Main(String[]) + +### File: +Fbx/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +aa3888919cadbb2bc15a4a3e1608853e + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0352/instruction.md b/inferredbugs-0352/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e2a1430fe3d4432c6b67bb4f5ea6e55310d802ca --- /dev/null +++ b/inferredbugs-0352/instruction.md @@ -0,0 +1,197 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** platyPS +**Bug ID:** 5 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using Markdown.MAML.Model; + +namespace Markdown.MAML.Transformer +{ + public class ModelTransformer + { + private DocumentNode _root; + private IEnumerator _rootEnumerator; + + private const int COMMAND_NAME_HEADING_LEVEL = 2; + private const int COMMAND_ENTRIES_HEADING_LEVEL = 3; + + private MarkdownNode GetCurrentNode() + { + return _rootEnumerator.Current; + } + + private MarkdownNode GetNextNode() + { + if (_rootEnumerator.MoveNext()) + { + return _rootEnumerator.Current; + } + + return null; + } + + private string GetSynopsis() + { + var node = GetNextNode(); + + // check for appropriate header + if (node.NodeType != MarkdownNodeType.Heading) + { + throw new HelpSchemaException("Expect ###SYNOPSIS"); + } + + var headingNode = node as HeadingNode; + if (headingNode.HeadingLevel != COMMAND_ENTRIES_HEADING_LEVEL) + { + throw new HelpSchemaException("Expect ###SYNOPSIS"); + } + + if (StringComparer.OrdinalIgnoreCase.Compare(headingNode.Text, "SYNOPSIS") != 0) + { + throw new HelpSchemaException("Expect ###SYNOPSIS"); + } + + node = GetNextNode(); + if (node.NodeType != MarkdownNodeType.Paragraph) + { + throw new HelpSchemaException("Expect SYNOPSIS text"); + } + + return (node as ParagraphNode).Text; + } + + private string GetDescription() + { + var node = GetNextNode(); + + if (node == null) + { + return null; + } + + // check for appropriate header + if (node.NodeType != MarkdownNodeType.Heading) + { + throw new HelpSchemaException("Expect ###DESCRIPTION"); + } + + var headingNode = node as HeadingNode; + if (headingNode.HeadingLevel != COMMAND_ENTRIES_HEADING_LEVEL) + { + throw new HelpSchemaException("Expect ###SYNOPSIS"); + } + + if (StringComparer.OrdinalIgnoreCase.Compare(headingNode.Text, "SYNOPSIS") != 0) + { + throw new HelpSchemaException("Expect ###SYNOPSIS"); + } + + node = GetNextNode(); + if (node.NodeType != MarkdownNodeType.Paragraph) + { + throw new HelpSchemaException("Expect SYNOPSIS text"); + } + + return ((node as ParagraphNode).Text); + } + + public IEnumerable NodeModelToMamlModel(DocumentNode node) + { + _root = node; + if (_root.Children == null) + { + // HACK: + _rootEnumerator = (new LinkedList()).GetEnumerator(); + } + else + { + _rootEnumerator = _root.Children.GetEnumerator(); + } + + List commands = new List(); + MarkdownNode markdownNode; + while ((markdownNode = GetNextNode()) != null) + { + if (markdownNode is HeadingNode) + { + var headingNode = markdownNode as HeadingNode; + switch (headingNode.HeadingLevel) + { + case COMMAND_NAME_HEADING_LEVEL: + { + MamlCommand command = new MamlCommand() + { + Name = headingNode.Text, + Synopsis = GetSynopsis(), + Description = GetDescription() + }; + commands.Add(command); + break; + } + default: throw new HelpSchemaException("Booo, I don't know what is the heading level " + headingNode.HeadingLevel); + } + } + } + return commands; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `headingNode` last assigned on line 75 could be null and is dereferenced at line 76, column 13. + +### Severity: +ERROR + +### Procedure: +String ModelTransformer.GetDescription() + +### File: +src/Markdown.MAML/Transformer/ModelTransformer.cs + +### Key: +ModelTransformer.cs|GetDescription|NULL_DEREFERENCE + +### Node Key: +90535029835413c6e5d1bdebbf52bdf9 + +### Hash: +294b0a0dd7f8cf7f922c909d0d662e2c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0353/instruction.md b/inferredbugs-0353/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e9841ae22663c240d5bbcccaa26d41afd31ac521 --- /dev/null +++ b/inferredbugs-0353/instruction.md @@ -0,0 +1,626 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** neo +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// Copyright (C) 2015-2022 The Neo Project. +// +// The neo is free software distributed under the MIT software license, +// see the accompanying file LICENSE in the main directory of the +// project or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +#pragma warning disable IDE0051 + +using Neo.Cryptography.ECC; +using Neo.IO; +using Neo.Persistence; +using Neo.SmartContract.Iterators; +using Neo.VM; +using Neo.VM.Types; +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; + +namespace Neo.SmartContract.Native +{ + /// + /// Represents the NEO token in the NEO system. + /// + public sealed class NeoToken : FungibleToken + { + public override string Symbol => "NEO"; + public override byte Decimals => 0; + + /// + /// Indicates the total amount of NEO. + /// + public BigInteger TotalAmount { get; } + + /// + /// Indicates the effective voting turnout in NEO. The voted candidates will only be effective when the voting turnout exceeds this value. + /// + public const decimal EffectiveVoterTurnout = 0.2M; + + private const byte Prefix_VotersCount = 1; + private const byte Prefix_Candidate = 33; + private const byte Prefix_Committee = 14; + private const byte Prefix_GasPerBlock = 29; + private const byte Prefix_RegisterPrice = 13; + private const byte Prefix_VoterRewardPerCommittee = 23; + + private const byte NeoHolderRewardRatio = 10; + private const byte CommitteeRewardRatio = 10; + private const byte VoterRewardRatio = 80; + + internal NeoToken() + { + this.TotalAmount = 100000000 * Factor; + } + + public override BigInteger TotalSupply(DataCache snapshot) + { + return TotalAmount; + } + + internal override void OnBalanceChanging(ApplicationEngine engine, UInt160 account, NeoAccountState state, BigInteger amount) + { + GasDistribution distribution = DistributeGas(engine, account, state); + if (distribution is not null) + { + var list = engine.CurrentContext.GetState>(); + list.Add(distribution); + } + if (amount.IsZero) return; + if (state.VoteTo is null) return; + engine.Snapshot.GetAndChange(CreateStorageKey(Prefix_VotersCount)).Add(amount); + StorageKey key = CreateStorageKey(Prefix_Candidate).Add(state.VoteTo); + CandidateState candidate = engine.Snapshot.GetAndChange(key).GetInteroperable(); + candidate.Votes += amount; + CheckCandidate(engine.Snapshot, state.VoteTo, candidate); + } + + private protected override async ContractTask PostTransfer(ApplicationEngine engine, UInt160 from, UInt160 to, BigInteger amount, StackItem data, bool callOnPayment) + { + await base.PostTransfer(engine, from, to, amount, data, callOnPayment); + var list = engine.CurrentContext.GetState>(); + foreach (var distribution in list) + await GAS.Mint(engine, distribution.Account, distribution.Amount, callOnPayment); + } + + private GasDistribution DistributeGas(ApplicationEngine engine, UInt160 account, NeoAccountState state) + { + // PersistingBlock is null when running under the debugger + if (engine.PersistingBlock is null) return null; + + BigInteger gas = CalculateBonus(engine.Snapshot, state.VoteTo, state.Balance, state.BalanceHeight, engine.PersistingBlock.Index); + state.BalanceHeight = engine.PersistingBlock.Index; + + if (gas == 0) return null; + return new GasDistribution + { + Account = account, + Amount = gas + }; + } + + private BigInteger CalculateBonus(DataCache snapshot, ECPoint vote, BigInteger value, uint start, uint end) + { + if (value.IsZero || start >= end) return BigInteger.Zero; + if (value.Sign < 0) throw new ArgumentOutOfRangeException(nameof(value)); + + BigInteger neoHolderReward = CalculateNeoHolderReward(snapshot, value, start, end); + if (vote is null) return neoHolderReward; + + byte[] border = CreateStorageKey(Prefix_VoterRewardPerCommittee).Add(vote).ToArray(); + byte[] keyStart = CreateStorageKey(Prefix_VoterRewardPerCommittee).Add(vote).AddBigEndian(start).ToArray(); + (_, var item) = snapshot.FindRange(keyStart, border, SeekDirection.Backward).FirstOrDefault(); + BigInteger startRewardPerNeo = item ?? BigInteger.Zero; + + byte[] keyEnd = CreateStorageKey(Prefix_VoterRewardPerCommittee).Add(vote).AddBigEndian(end).ToArray(); + (_, item) = snapshot.FindRange(keyEnd, border, SeekDirection.Backward).FirstOrDefault(); + BigInteger endRewardPerNeo = item ?? BigInteger.Zero; + + return neoHolderReward + value * (endRewardPerNeo - startRewardPerNeo) / 100000000L; + } + + private BigInteger CalculateNeoHolderReward(DataCache snapshot, BigInteger value, uint start, uint end) + { + BigInteger sum = 0; + foreach (var (index, gasPerBlock) in GetSortedGasRecords(snapshot, end - 1)) + { + if (index > start) + { + sum += gasPerBlock * (end - index); + end = index; + } + else + { + sum += gasPerBlock * (end - start); + break; + } + } + return value * sum * NeoHolderRewardRatio / 100 / TotalAmount; + } + + private void CheckCandidate(DataCache snapshot, ECPoint pubkey, CandidateState candidate) + { + if (!candidate.Registered && candidate.Votes.IsZero) + { + foreach (var (rewardKey, _) in snapshot.Find(CreateStorageKey(Prefix_VoterRewardPerCommittee).Add(pubkey).ToArray()).ToArray()) + snapshot.Delete(rewardKey); + snapshot.Delete(CreateStorageKey(Prefix_Candidate).Add(pubkey)); + } + } + + /// + /// Determine whether the votes should be recounted at the specified height. + /// + /// The height to be checked. + /// The number of committee members in the system. + /// if the votes should be recounted; otherwise, . + public static bool ShouldRefreshCommittee(uint height, int committeeMembersCount) => height % committeeMembersCount == 0; + + internal override ContractTask Initialize(ApplicationEngine engine) + { + var cachedCommittee = new CachedCommittee(engine.ProtocolSettings.StandbyCommittee.Select(p => (p, BigInteger.Zero))); + engine.Snapshot.Add(CreateStorageKey(Prefix_Committee), new StorageItem(cachedCommittee)); + engine.Snapshot.Add(CreateStorageKey(Prefix_VotersCount), new StorageItem(System.Array.Empty())); + engine.Snapshot.Add(CreateStorageKey(Prefix_GasPerBlock).AddBigEndian(0u), new StorageItem(5 * GAS.Factor)); + engine.Snapshot.Add(CreateStorageKey(Prefix_RegisterPrice), new StorageItem(1000 * GAS.Factor)); + return Mint(engine, Contract.GetBFTAddress(engine.ProtocolSettings.StandbyValidators), TotalAmount, false); + } + + internal override ContractTask OnPersist(ApplicationEngine engine) + { + // Set next committee + if (ShouldRefreshCommittee(engine.PersistingBlock.Index, engine.ProtocolSettings.CommitteeMembersCount)) + { + StorageItem storageItem = engine.Snapshot.GetAndChange(CreateStorageKey(Prefix_Committee)); + var cachedCommittee = storageItem.GetInteroperable(); + cachedCommittee.Clear(); + cachedCommittee.AddRange(ComputeCommitteeMembers(engine.Snapshot, engine.ProtocolSettings)); + } + return ContractTask.CompletedTask; + } + + internal override async ContractTask PostPersist(ApplicationEngine engine) + { + // Distribute GAS for committee + + int m = engine.ProtocolSettings.CommitteeMembersCount; + int n = engine.ProtocolSettings.ValidatorsCount; + int index = (int)(engine.PersistingBlock.Index % (uint)m); + var gasPerBlock = GetGasPerBlock(engine.Snapshot); + var committee = GetCommitteeFromCache(engine.Snapshot); + var pubkey = committee[index].PublicKey; + var account = Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash(); + await GAS.Mint(engine, account, gasPerBlock * CommitteeRewardRatio / 100, false); + + // Record the cumulative reward of the voters of committee + + if (ShouldRefreshCommittee(engine.PersistingBlock.Index, m)) + { + BigInteger voterRewardOfEachCommittee = gasPerBlock * VoterRewardRatio * 100000000L * m / (m + n) / 100; // Zoom in 100000000 times, and the final calculation should be divided 100000000L + for (index = 0; index < committee.Count; index++) + { + var member = committee[index]; + var factor = index < n ? 2 : 1; // The `voter` rewards of validator will double than other committee's + if (member.Votes > 0) + { + BigInteger voterSumRewardPerNEO = factor * voterRewardOfEachCommittee / member.Votes; + StorageKey voterRewardKey = CreateStorageKey(Prefix_VoterRewardPerCommittee).Add(member.PublicKey).AddBigEndian(engine.PersistingBlock.Index + 1); + byte[] border = CreateStorageKey(Prefix_VoterRewardPerCommittee).Add(member.PublicKey).ToArray(); + (_, var item) = engine.Snapshot.FindRange(voterRewardKey.ToArray(), border, SeekDirection.Backward).FirstOrDefault(); + voterSumRewardPerNEO += (item ?? BigInteger.Zero); + engine.Snapshot.Add(voterRewardKey, new StorageItem(voterSumRewardPerNEO)); + } + } + } + } + + [ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.States)] + private void SetGasPerBlock(ApplicationEngine engine, BigInteger gasPerBlock) + { + if (gasPerBlock < 0 || gasPerBlock > 10 * GAS.Factor) + throw new ArgumentOutOfRangeException(nameof(gasPerBlock)); + if (!CheckCommittee(engine)) throw new InvalidOperationException(); + + uint index = engine.PersistingBlock.Index + 1; + StorageItem entry = engine.Snapshot.GetAndChange(CreateStorageKey(Prefix_GasPerBlock).AddBigEndian(index), () => new StorageItem(gasPerBlock)); + entry.Set(gasPerBlock); + } + + /// + /// Gets the amount of GAS generated in each block. + /// + /// The snapshot used to read data. + /// The amount of GAS generated. + [ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)] + public BigInteger GetGasPerBlock(DataCache snapshot) + { + return GetSortedGasRecords(snapshot, Ledger.CurrentIndex(snapshot) + 1).First().GasPerBlock; + } + + [ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.States)] + private void SetRegisterPrice(ApplicationEngine engine, long registerPrice) + { + if (registerPrice <= 0) + throw new ArgumentOutOfRangeException(nameof(registerPrice)); + if (!CheckCommittee(engine)) throw new InvalidOperationException(); + engine.Snapshot.GetAndChange(CreateStorageKey(Prefix_RegisterPrice)).Set(registerPrice); + } + + /// + /// Gets the fees to be paid to register as a candidate. + /// + /// The snapshot used to read data. + /// The amount of the fees. + [ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)] + public long GetRegisterPrice(DataCache snapshot) + { + return (long)(BigInteger)snapshot[CreateStorageKey(Prefix_RegisterPrice)]; + } + + private IEnumerable<(uint Index, BigInteger GasPerBlock)> GetSortedGasRecords(DataCache snapshot, uint end) + { + byte[] key = CreateStorageKey(Prefix_GasPerBlock).AddBigEndian(end).ToArray(); + byte[] boundary = CreateStorageKey(Prefix_GasPerBlock).ToArray(); + return snapshot.FindRange(key, boundary, SeekDirection.Backward) + .Select(u => (BinaryPrimitives.ReadUInt32BigEndian(u.Key.Key.Span[^sizeof(uint)..]), (BigInteger)u.Value)); + } + + /// + /// Get the amount of unclaimed GAS in the specified account. + /// + /// The snapshot used to read data. + /// The account to check. + /// The block index used when calculating GAS. + /// The amount of unclaimed GAS. + [ContractMethod(CpuFee = 1 << 17, RequiredCallFlags = CallFlags.ReadStates)] + public BigInteger UnclaimedGas(DataCache snapshot, UInt160 account, uint end) + { + StorageItem storage = snapshot.TryGet(CreateStorageKey(Prefix_Account).Add(account)); + if (storage is null) return BigInteger.Zero; + NeoAccountState state = storage.GetInteroperable(); + return CalculateBonus(snapshot, state.VoteTo, state.Balance, state.BalanceHeight, end); + } + + [ContractMethod(RequiredCallFlags = CallFlags.States)] + private bool RegisterCandidate(ApplicationEngine engine, ECPoint pubkey) + { + if (!engine.CheckWitnessInternal(Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash())) + return false; + engine.AddGas(GetRegisterPrice(engine.Snapshot)); + StorageKey key = CreateStorageKey(Prefix_Candidate).Add(pubkey); + StorageItem item = engine.Snapshot.GetAndChange(key, () => new StorageItem(new CandidateState())); + CandidateState state = item.GetInteroperable(); + state.Registered = true; + return true; + } + + [ContractMethod(CpuFee = 1 << 16, RequiredCallFlags = CallFlags.States)] + private bool UnregisterCandidate(ApplicationEngine engine, ECPoint pubkey) + { + if (!engine.CheckWitnessInternal(Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash())) + return false; + StorageKey key = CreateStorageKey(Prefix_Candidate).Add(pubkey); + if (engine.Snapshot.TryGet(key) is null) return true; + StorageItem item = engine.Snapshot.GetAndChange(key); + CandidateState state = item.GetInteroperable(); + state.Registered = false; + CheckCandidate(engine.Snapshot, pubkey, state); + return true; + } + + [ContractMethod(CpuFee = 1 << 16, RequiredCallFlags = CallFlags.States)] + private async ContractTask Vote(ApplicationEngine engine, UInt160 account, ECPoint voteTo) + { + if (!engine.CheckWitnessInternal(account)) return false; + NeoAccountState state_account = engine.Snapshot.GetAndChange(CreateStorageKey(Prefix_Account).Add(account))?.GetInteroperable(); + if (state_account is null) return false; + CandidateState validator_new = null; + if (voteTo != null) + { + validator_new = engine.Snapshot.GetAndChange(CreateStorageKey(Prefix_Candidate).Add(voteTo))?.GetInteroperable(); + if (validator_new is null) return false; + if (!validator_new.Registered) return false; + } + if (state_account.VoteTo is null ^ voteTo is null) + { + StorageItem item = engine.Snapshot.GetAndChange(CreateStorageKey(Prefix_VotersCount)); + if (state_account.VoteTo is null) + item.Add(state_account.Balance); + else + item.Add(-state_account.Balance); + } + GasDistribution gasDistribution = DistributeGas(engine, account, state_account); + if (state_account.VoteTo != null) + { + StorageKey key = CreateStorageKey(Prefix_Candidate).Add(state_account.VoteTo); + StorageItem storage_validator = engine.Snapshot.GetAndChange(key); + CandidateState state_validator = storage_validator.GetInteroperable(); + state_validator.Votes -= state_account.Balance; + CheckCandidate(engine.Snapshot, state_account.VoteTo, state_validator); + } + state_account.VoteTo = voteTo; + if (validator_new != null) + { + validator_new.Votes += state_account.Balance; + } + if (gasDistribution is not null) + await GAS.Mint(engine, gasDistribution.Account, gasDistribution.Amount, true); + return true; + } + + /// + /// Gets the first 256 registered candidates. + /// + /// The snapshot used to read data. + /// All the registered candidates. + [ContractMethod(CpuFee = 1 << 22, RequiredCallFlags = CallFlags.ReadStates)] + private (ECPoint PublicKey, BigInteger Votes)[] GetCandidates(DataCache snapshot) + { + return GetCandidatesInternal(snapshot) + .Select(p => (p.PublicKey, p.State.Votes)) + .Take(256) + .ToArray(); + } + + /// + /// Gets the registered candidates iterator. + /// + /// The snapshot used to read data. + /// All the registered candidates. + [ContractMethod(CpuFee = 1 << 22, RequiredCallFlags = CallFlags.ReadStates)] + private IIterator GetAllCandidates(DataCache snapshot) + { + const FindOptions options = FindOptions.RemovePrefix | FindOptions.DeserializeValues | FindOptions.PickField1; + var enumerator = GetCandidatesInternal(snapshot) + .Select(p => (p.Key, p.Value)) + .GetEnumerator(); + return new StorageIterator(enumerator, 1, options); + } + + internal IEnumerable<(StorageKey Key, StorageItem Value, ECPoint PublicKey, CandidateState State)> GetCandidatesInternal(DataCache snapshot) + { + byte[] prefix_key = CreateStorageKey(Prefix_Candidate).ToArray(); + return snapshot.Find(prefix_key) + .Select(p => (p.Key, p.Value, PublicKey: p.Key.Key[1..].AsSerializable(), State: p.Value.GetInteroperable())) + .Where(p => p.State.Registered) + .Where(p => !Policy.IsBlocked(snapshot, Contract.CreateSignatureRedeemScript(p.PublicKey).ToScriptHash())); + } + + /// + /// Gets votes from specific candidate. + /// + /// The snapshot used to read data. + /// Specific public key + /// Votes or -1 if it was not found. + [ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)] + public BigInteger GetCandidateVote(DataCache snapshot, ECPoint pubKey) + { + StorageItem storage = snapshot.TryGet(CreateStorageKey(Prefix_Candidate).Add(pubKey)); + CandidateState state = storage?.GetInteroperable(); + return state?.Registered == true ? state.Votes : -1; + } + + /// + /// Gets all the members of the committee. + /// + /// The snapshot used to read data. + /// The public keys of the members. + [ContractMethod(CpuFee = 1 << 16, RequiredCallFlags = CallFlags.ReadStates)] + public ECPoint[] GetCommittee(DataCache snapshot) + { + return GetCommitteeFromCache(snapshot).Select(p => p.PublicKey).OrderBy(p => p).ToArray(); + } + + /// + /// Get account state. + /// + /// The snapshot used to read data. + /// account + /// The state of the account. + [ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)] + public NeoAccountState GetAccountState(DataCache snapshot, UInt160 account) + { + return snapshot.TryGet(CreateStorageKey(Prefix_Account).Add(account))?.GetInteroperable(); + } + + /// + /// Gets the address of the committee. + /// + /// The snapshot used to read data. + /// The address of the committee. + public UInt160 GetCommitteeAddress(DataCache snapshot) + { + ECPoint[] committees = GetCommittee(snapshot); + return Contract.CreateMultiSigRedeemScript(committees.Length - (committees.Length - 1) / 2, committees).ToScriptHash(); + } + + private CachedCommittee GetCommitteeFromCache(DataCache snapshot) + { + return snapshot[CreateStorageKey(Prefix_Committee)].GetInteroperable(); + } + + /// + /// Computes the validators of the next block. + /// + /// The snapshot used to read data. + /// The used during computing. + /// The public keys of the validators. + public ECPoint[] ComputeNextBlockValidators(DataCache snapshot, ProtocolSettings settings) + { + return ComputeCommitteeMembers(snapshot, settings).Select(p => p.PublicKey).Take(settings.ValidatorsCount).OrderBy(p => p).ToArray(); + } + + private IEnumerable<(ECPoint PublicKey, BigInteger Votes)> ComputeCommitteeMembers(DataCache snapshot, ProtocolSettings settings) + { + decimal votersCount = (decimal)(BigInteger)snapshot[CreateStorageKey(Prefix_VotersCount)]; + decimal voterTurnout = votersCount / (decimal)TotalAmount; + var candidates = GetCandidatesInternal(snapshot) + .Select(p => (p.PublicKey, p.State.Votes)) + .ToArray(); + if (voterTurnout < EffectiveVoterTurnout || candidates.Length < settings.CommitteeMembersCount) + return settings.StandbyCommittee.Select(p => (p, candidates.FirstOrDefault(k => k.PublicKey.Equals(p)).Votes)); + return candidates + .OrderByDescending(p => p.Votes) + .ThenBy(p => p.PublicKey) + .Take(settings.CommitteeMembersCount); + } + + [ContractMethod(CpuFee = 1 << 16, RequiredCallFlags = CallFlags.ReadStates)] + private ECPoint[] GetNextBlockValidators(ApplicationEngine engine) + { + return GetNextBlockValidators(engine.Snapshot, engine.ProtocolSettings.ValidatorsCount); + } + + /// + /// Gets the validators of the next block. + /// + /// The snapshot used to read data. + /// The number of validators in the system. + /// The public keys of the validators. + public ECPoint[] GetNextBlockValidators(DataCache snapshot, int validatorsCount) + { + return GetCommitteeFromCache(snapshot) + .Take(validatorsCount) + .Select(p => p.PublicKey) + .OrderBy(p => p) + .ToArray(); + } + + /// + /// Represents the account state of . + /// + public class NeoAccountState : AccountState + { + /// + /// The height of the block where the balance changed last time. + /// + public uint BalanceHeight; + + /// + /// The voting target of the account. This field can be . + /// + public ECPoint VoteTo; + + public override void FromStackItem(StackItem stackItem) + { + base.FromStackItem(stackItem); + Struct @struct = (Struct)stackItem; + BalanceHeight = (uint)@struct[1].GetInteger(); + VoteTo = @struct[2].IsNull ? null : ECPoint.DecodePoint(@struct[2].GetSpan(), ECCurve.Secp256r1); + } + + public override StackItem ToStackItem(ReferenceCounter referenceCounter) + { + Struct @struct = (Struct)base.ToStackItem(referenceCounter); + @struct.Add(BalanceHeight); + @struct.Add(VoteTo?.ToArray() ?? StackItem.Null); + return @struct; + } + } + + internal class CandidateState : IInteroperable + { + public bool Registered = true; + public BigInteger Votes; + + public void FromStackItem(StackItem stackItem) + { + Struct @struct = (Struct)stackItem; + Registered = @struct[0].GetBoolean(); + Votes = @struct[1].GetInteger(); + } + + public StackItem ToStackItem(ReferenceCounter referenceCounter) + { + return new Struct(referenceCounter) { Registered, Votes }; + } + } + + internal class CachedCommittee : InteroperableList<(ECPoint PublicKey, BigInteger Votes)> + { + public CachedCommittee() { } + public CachedCommittee(IEnumerable<(ECPoint, BigInteger)> collection) => AddRange(collection); + + protected override (ECPoint, BigInteger) ElementFromStackItem(StackItem item) + { + Struct @struct = (Struct)item; + return (ECPoint.DecodePoint(@struct[0].GetSpan(), ECCurve.Secp256r1), @struct[1].GetInteger()); + } + + protected override StackItem ElementToStackItem((ECPoint PublicKey, BigInteger Votes) element, ReferenceCounter referenceCounter) + { + return new Struct(referenceCounter) { element.PublicKey.ToArray(), element.Votes }; + } + } + + private record GasDistribution + { + public UInt160 Account { get; init; } + public BigInteger Amount { get; init; } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from Neo.SmartContract.KeyBuilder Neo.SmartContract.Native.NativeContract::CreateStorageKey(System.Byte) at Line 307).Neo.SmartContract.KeyBuilder.stream of type System.IO.MemoryStream in method "Boolean NeoToken.UnregisterCandidate(ApplicationEngine,ECPoint)". + +### Severity: +ERROR + +### Procedure: +Boolean NeoToken.UnregisterCandidate(ApplicationEngine,ECPoint) + +### File: +src/neo/SmartContract/Native/NeoToken.cs + +### Key: +NeoToken.cs|UnregisterCandidate|DOTNET_RESOURCE_LEAK + +### Hash: +7b137895cac6c99f6467ce6040b3e9d6 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0354/instruction.md b/inferredbugs-0354/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3b3b10f7687ca71e5cf261bf9acf8530d3c50c38 --- /dev/null +++ b/inferredbugs-0354/instruction.md @@ -0,0 +1,491 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** neo +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// Copyright (C) 2015-2022 The Neo Project. +// +// The neo is free software distributed under the MIT software license, +// see the accompanying file LICENSE in the main directory of the +// project or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + +using Akka.Actor; +using Neo.Cryptography; +using Neo.IO.Caching; +using Neo.Ledger; +using Neo.Network.P2P.Capabilities; +using Neo.Network.P2P.Payloads; +using Neo.Persistence; +using Neo.SmartContract.Native; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; + +namespace Neo.Network.P2P +{ + public delegate bool MessageReceivedHandler(NeoSystem system, Message message); + + partial class RemoteNode + { + private class Timer { } + private class PendingKnownHashesCollection : KeyedCollection + { + protected override UInt256 GetKeyForItem((UInt256, DateTime) item) + { + return item.Item1; + } + } + + public static event MessageReceivedHandler MessageReceived + { + add => handlers.Add(value); + remove => handlers.Remove(value); + } + + private static readonly List handlers = new(); + private readonly PendingKnownHashesCollection pendingKnownHashes = new(); + private readonly HashSetCache knownHashes; + private readonly HashSetCache sentHashes; + private bool verack = false; + private BloomFilter bloom_filter; + + private static readonly TimeSpan TimerInterval = TimeSpan.FromSeconds(30); + private readonly ICancelable timer = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(TimerInterval, TimerInterval, Context.Self, new Timer(), ActorRefs.NoSender); + + private void OnMessage(Message msg) + { + foreach (MessageReceivedHandler handler in handlers) + if (!handler(system, msg)) + return; + if (Version == null) + { + if (msg.Command != MessageCommand.Version) + throw new ProtocolViolationException(); + OnVersionMessageReceived((VersionPayload)msg.Payload); + return; + } + if (!verack) + { + if (msg.Command != MessageCommand.Verack) + throw new ProtocolViolationException(); + OnVerackMessageReceived(); + return; + } + switch (msg.Command) + { + case MessageCommand.Addr: + OnAddrMessageReceived((AddrPayload)msg.Payload); + break; + case MessageCommand.Block: + case MessageCommand.Extensible: + OnInventoryReceived((IInventory)msg.Payload); + break; + case MessageCommand.FilterAdd: + OnFilterAddMessageReceived((FilterAddPayload)msg.Payload); + break; + case MessageCommand.FilterClear: + OnFilterClearMessageReceived(); + break; + case MessageCommand.FilterLoad: + OnFilterLoadMessageReceived((FilterLoadPayload)msg.Payload); + break; + case MessageCommand.GetAddr: + OnGetAddrMessageReceived(); + break; + case MessageCommand.GetBlocks: + OnGetBlocksMessageReceived((GetBlocksPayload)msg.Payload); + break; + case MessageCommand.GetBlockByIndex: + OnGetBlockByIndexMessageReceived((GetBlockByIndexPayload)msg.Payload); + break; + case MessageCommand.GetData: + OnGetDataMessageReceived((InvPayload)msg.Payload); + break; + case MessageCommand.GetHeaders: + OnGetHeadersMessageReceived((GetBlockByIndexPayload)msg.Payload); + break; + case MessageCommand.Headers: + OnHeadersMessageReceived((HeadersPayload)msg.Payload); + break; + case MessageCommand.Inv: + OnInvMessageReceived((InvPayload)msg.Payload); + break; + case MessageCommand.Mempool: + OnMemPoolMessageReceived(); + break; + case MessageCommand.Ping: + OnPingMessageReceived((PingPayload)msg.Payload); + break; + case MessageCommand.Pong: + OnPongMessageReceived((PingPayload)msg.Payload); + break; + case MessageCommand.Transaction: + if (msg.Payload.Size <= Transaction.MaxTransactionSize) + OnInventoryReceived((Transaction)msg.Payload); + break; + case MessageCommand.Verack: + case MessageCommand.Version: + throw new ProtocolViolationException(); + case MessageCommand.Alert: + case MessageCommand.MerkleBlock: + case MessageCommand.NotFound: + case MessageCommand.Reject: + default: break; + } + } + + private void OnAddrMessageReceived(AddrPayload payload) + { + ref bool sent = ref sentCommands[(byte)MessageCommand.GetAddr]; + if (!sent) return; + sent = false; + system.LocalNode.Tell(new Peer.Peers + { + EndPoints = payload.AddressList.Select(p => p.EndPoint).Where(p => p.Port > 0) + }); + } + + private void OnFilterAddMessageReceived(FilterAddPayload payload) + { + bloom_filter?.Add(payload.Data); + } + + private void OnFilterClearMessageReceived() + { + bloom_filter = null; + } + + private void OnFilterLoadMessageReceived(FilterLoadPayload payload) + { + bloom_filter = new BloomFilter(payload.Filter.Length * 8, payload.K, payload.Tweak, payload.Filter); + } + + /// + /// Will be triggered when a MessageCommand.GetAddr message is received. + /// Randomly select nodes from the local RemoteNodes and tells to RemoteNode actors a MessageCommand.Addr message. + /// The message contains a list of networkAddresses from those selected random peers. + /// + private void OnGetAddrMessageReceived() + { + Random rand = new(); + IEnumerable peers = localNode.RemoteNodes.Values + .Where(p => p.ListenerTcpPort > 0) + .GroupBy(p => p.Remote.Address, (k, g) => g.First()) + .OrderBy(p => rand.Next()) + .Take(AddrPayload.MaxCountToSend); + NetworkAddressWithTime[] networkAddresses = peers.Select(p => NetworkAddressWithTime.Create(p.Listener.Address, p.Version.Timestamp, p.Version.Capabilities)).ToArray(); + if (networkAddresses.Length == 0) return; + EnqueueMessage(Message.Create(MessageCommand.Addr, AddrPayload.Create(networkAddresses))); + } + + /// + /// Will be triggered when a MessageCommand.GetBlocks message is received. + /// Tell the specified number of blocks' hashes starting with the requested HashStart until payload.Count or MaxHashesCount + /// Responses are sent to RemoteNode actor as MessageCommand.Inv Message. + /// + /// A GetBlocksPayload including start block Hash and number of blocks requested. + private void OnGetBlocksMessageReceived(GetBlocksPayload payload) + { + // The default value of payload.Count is -1 + int count = payload.Count < 0 || payload.Count > InvPayload.MaxHashesCount ? InvPayload.MaxHashesCount : payload.Count; + DataCache snapshot = system.StoreView; + UInt256 hash = payload.HashStart; + TrimmedBlock state = NativeContract.Ledger.GetTrimmedBlock(snapshot, hash); + if (state == null) return; + uint currentHeight = NativeContract.Ledger.CurrentIndex(snapshot); + List hashes = new(); + for (uint i = 1; i <= count; i++) + { + uint index = state.Index + i; + if (index > currentHeight) + break; + hash = NativeContract.Ledger.GetBlockHash(snapshot, index); + if (hash == null) break; + hashes.Add(hash); + } + if (hashes.Count == 0) return; + EnqueueMessage(Message.Create(MessageCommand.Inv, InvPayload.Create(InventoryType.Block, hashes.ToArray()))); + } + + private void OnGetBlockByIndexMessageReceived(GetBlockByIndexPayload payload) + { + uint count = payload.Count == -1 ? InvPayload.MaxHashesCount : Math.Min((uint)payload.Count, InvPayload.MaxHashesCount); + for (uint i = payload.IndexStart, max = payload.IndexStart + count; i < max; i++) + { + Block block = NativeContract.Ledger.GetBlock(system.StoreView, i); + if (block == null) + break; + + if (bloom_filter == null) + { + EnqueueMessage(Message.Create(MessageCommand.Block, block)); + } + else + { + BitArray flags = new(block.Transactions.Select(p => bloom_filter.Test(p)).ToArray()); + EnqueueMessage(Message.Create(MessageCommand.MerkleBlock, MerkleBlockPayload.Create(block, flags))); + } + } + } + + /// + /// Will be triggered when a MessageCommand.GetData message is received. + /// The payload includes an array of hash values. + /// For different payload.Type (Tx, Block, Consensus), + /// get the corresponding (Txs, Blocks, Consensus) and tell them to RemoteNode actor. + /// + /// The payload containing the requested information. + private void OnGetDataMessageReceived(InvPayload payload) + { + var notFound = new List(); + foreach (UInt256 hash in payload.Hashes.Where(p => sentHashes.Add(p))) + { + switch (payload.Type) + { + case InventoryType.TX: + if (system.MemPool.TryGetValue(hash, out Transaction tx)) + EnqueueMessage(Message.Create(MessageCommand.Transaction, tx)); + else + notFound.Add(hash); + break; + case InventoryType.Block: + Block block = NativeContract.Ledger.GetBlock(system.StoreView, hash); + if (block != null) + { + if (bloom_filter == null) + { + EnqueueMessage(Message.Create(MessageCommand.Block, block)); + } + else + { + BitArray flags = new(block.Transactions.Select(p => bloom_filter.Test(p)).ToArray()); + EnqueueMessage(Message.Create(MessageCommand.MerkleBlock, MerkleBlockPayload.Create(block, flags))); + } + } + else + { + notFound.Add(hash); + } + break; + default: + if (system.RelayCache.TryGet(hash, out IInventory inventory)) + EnqueueMessage(Message.Create((MessageCommand)payload.Type, inventory)); + break; + } + } + + if (notFound.Count > 0) + { + foreach (InvPayload entry in InvPayload.CreateGroup(payload.Type, notFound.ToArray())) + EnqueueMessage(Message.Create(MessageCommand.NotFound, entry)); + } + } + + /// + /// Will be triggered when a MessageCommand.GetHeaders message is received. + /// Tell the specified number of blocks' headers starting with the requested IndexStart to RemoteNode actor. + /// A limit set by HeadersPayload.MaxHeadersCount is also applied to the number of requested Headers, namely payload.Count. + /// + /// A GetBlockByIndexPayload including start block index and number of blocks' headers requested. + private void OnGetHeadersMessageReceived(GetBlockByIndexPayload payload) + { + DataCache snapshot = system.StoreView; + if (payload.IndexStart > NativeContract.Ledger.CurrentIndex(snapshot)) return; + List
headers = new(); + uint count = payload.Count == -1 ? HeadersPayload.MaxHeadersCount : (uint)payload.Count; + for (uint i = 0; i < count; i++) + { + var header = NativeContract.Ledger.GetHeader(snapshot, payload.IndexStart + i); + if (header == null) break; + headers.Add(header); + } + if (headers.Count == 0) return; + EnqueueMessage(Message.Create(MessageCommand.Headers, HeadersPayload.Create(headers.ToArray()))); + } + + private void OnHeadersMessageReceived(HeadersPayload payload) + { + UpdateLastBlockIndex(payload.Headers[^1].Index); + system.Blockchain.Tell(payload.Headers); + } + + private void OnInventoryReceived(IInventory inventory) + { + if (!knownHashes.Add(inventory.Hash)) return; + pendingKnownHashes.Remove(inventory.Hash); + system.TaskManager.Tell(inventory); + switch (inventory) + { + case Transaction transaction: + if (!system.ContainsTransaction(transaction.Hash)) + system.TxRouter.Tell(new TransactionRouter.Preverify(transaction, true)); + break; + case Block block: + UpdateLastBlockIndex(block.Index); + if (block.Index > NativeContract.Ledger.CurrentIndex(system.StoreView) + InvPayload.MaxHashesCount) return; + system.Blockchain.Tell(inventory); + break; + default: + system.Blockchain.Tell(inventory); + break; + } + } + + private void OnInvMessageReceived(InvPayload payload) + { + UInt256[] hashes = payload.Hashes.Where(p => !pendingKnownHashes.Contains(p) && !knownHashes.Contains(p) && !sentHashes.Contains(p)).ToArray(); + if (hashes.Length == 0) return; + switch (payload.Type) + { + case InventoryType.Block: + { + DataCache snapshot = system.StoreView; + hashes = hashes.Where(p => !NativeContract.Ledger.ContainsBlock(snapshot, p)).ToArray(); + } + break; + case InventoryType.TX: + { + DataCache snapshot = system.StoreView; + hashes = hashes.Where(p => !NativeContract.Ledger.ContainsTransaction(snapshot, p)).ToArray(); + } + break; + } + if (hashes.Length == 0) return; + foreach (UInt256 hash in hashes) + pendingKnownHashes.Add((hash, TimeProvider.Current.UtcNow)); + system.TaskManager.Tell(new TaskManager.NewTasks { Payload = InvPayload.Create(payload.Type, hashes) }); + } + + private void OnMemPoolMessageReceived() + { + foreach (InvPayload payload in InvPayload.CreateGroup(InventoryType.TX, system.MemPool.GetVerifiedTransactions().Select(p => p.Hash).ToArray())) + EnqueueMessage(Message.Create(MessageCommand.Inv, payload)); + } + + private void OnPingMessageReceived(PingPayload payload) + { + UpdateLastBlockIndex(payload.LastBlockIndex); + EnqueueMessage(Message.Create(MessageCommand.Pong, PingPayload.Create(NativeContract.Ledger.CurrentIndex(system.StoreView), payload.Nonce))); + } + + private void OnPongMessageReceived(PingPayload payload) + { + UpdateLastBlockIndex(payload.LastBlockIndex); + } + + private void OnVerackMessageReceived() + { + verack = true; + system.TaskManager.Tell(new TaskManager.Register { Version = Version }); + CheckMessageQueue(); + } + + private void OnVersionMessageReceived(VersionPayload payload) + { + Version = payload; + foreach (NodeCapability capability in payload.Capabilities) + { + switch (capability) + { + case FullNodeCapability fullNodeCapability: + IsFullNode = true; + LastBlockIndex = fullNodeCapability.StartHeight; + break; + case ServerCapability serverCapability: + if (serverCapability.Type == NodeCapabilityType.TcpServer) + ListenerTcpPort = serverCapability.Port; + break; + } + } + if (!localNode.AllowNewConnection(Self, this)) + { + Disconnect(true); + return; + } + SendMessage(Message.Create(MessageCommand.Verack)); + } + + private void OnTimer() + { + DateTime oneMinuteAgo = TimeProvider.Current.UtcNow.AddMinutes(-1); + while (pendingKnownHashes.Count > 0) + { + var (_, time) = pendingKnownHashes[0]; + if (oneMinuteAgo <= time) break; + pendingKnownHashes.RemoveAt(0); + } + if (oneMinuteAgo > lastSent) + EnqueueMessage(Message.Create(MessageCommand.Ping, PingPayload.Create(NativeContract.Ledger.CurrentIndex(system.StoreView)))); + } + + private void UpdateLastBlockIndex(uint lastBlockIndex) + { + if (lastBlockIndex > LastBlockIndex) + { + LastBlockIndex = lastBlockIndex; + system.TaskManager.Tell(new TaskManager.Update { LastBlockIndex = LastBlockIndex }); + } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from Neo.Persistence.DataCache Neo.NeoSystem::get_StoreView() at Line 420) of type Neo.Persistence.SnapshotCache in method "Void RemoteNode.OnTimer()". + +### Severity: +ERROR + +### Procedure: +Void RemoteNode.OnTimer() + +### File: +src/Neo/Network/P2P/RemoteNode.ProtocolHandler.cs + +### Key: +RemoteNode.ProtocolHandler.cs|OnTimer|DOTNET_RESOURCE_LEAK + +### Hash: +fcee7327e2b8c246be727213b4cb307d + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0355/instruction.md b/inferredbugs-0355/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b4fe1e6dcaa1041c1ba6a994cbb90646e4d48122 --- /dev/null +++ b/inferredbugs-0355/instruction.md @@ -0,0 +1,128 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** StackExchange.Metrics +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Diagnostics; +using System.Threading; +using BosunReporter; + +namespace Scratch +{ + class Program + { + static void Main(string[] args) + { + Debug.Listeners.Add(new TextWriterTraceListener(Console.Out)); + Debug.AutoFlush = true; + + var options = new BosunReporterOptions() + { + MetricsNamePrefix = "bret.", + BosunUrl = new Uri("http://192.168.59.104:8070/"), + ThrowOnPostFail = true, + ReportingInterval = 5 + }; + var reporter = new BosunReporter.BosunReporter(options); + var counter = reporter.GetMetric("my_counter"); + counter.Increment(); + counter.Increment(); + + var gauge = reporter.GetMetric("my_gauge"); + if (gauge != reporter.GetMetric("my_gauge")) + throw new Exception("WAT?"); + + //reporter.GetMetric("my_gauge_95"); // <- should throw an exception + + var rand = new Random(); + while (true) + { + gauge.Record(rand.NextDouble()); + Thread.Sleep(5); + } + } + } + + [GaugeAggregator(AggregateMode.Average)] + [GaugeAggregator(AggregateMode.Max)] + [GaugeAggregator(AggregateMode.Min)] + [GaugeAggregator(AggregateMode.Median)] + [GaugeAggregator(AggregateMode.Percentile, 0.95)] + [GaugeAggregator(AggregateMode.Percentile, 0.25)] + public class TestAggregateGauge : BosunAggregateGauge + { + [BosunTag("host")] + public readonly string Host; + + public TestAggregateGauge() + { + Host = "bret-host"; + } + } + + public class TestCounter : BosunCounter + { + [BosunTag("host")] + public readonly string Host; + + public TestCounter() + { + Host = "bret-host"; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of System.Diagnostics.TextWriterTraceListener::.ctor() at Line 12) of type System.Diagnostics.TextWriterTraceListener in method "Void Program.Main(String[])". + +### Severity: +ERROR + +### Procedure: +Void Program.Main(String[]) + +### File: +Scratch/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +8e58a18cae1bf1f6099a7800e0abb700 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0362/instruction.md b/inferredbugs-0362/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9e1f16b68bd93bcf442ce83aa981543fa5376eed --- /dev/null +++ b/inferredbugs-0362/instruction.md @@ -0,0 +1,429 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** kafka-streams-dotnet +**Bug ID:** 10 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Confluent.Kafka; +using NUnit.Framework; +using Streamiz.Kafka.Net.Errors; +using Streamiz.Kafka.Net.Mock; +using Streamiz.Kafka.Net.Mock.Kafka; +using Streamiz.Kafka.Net.Mock.Sync; +using Streamiz.Kafka.Net.Processors; +using Streamiz.Kafka.Net.Processors.Internal; +using Streamiz.Kafka.Net.SerDes; +using Streamiz.Kafka.Net.State.Internal; +using Streamiz.Kafka.Net.Table; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using Streamiz.Kafka.Net.Metrics; +using ThreadState = Streamiz.Kafka.Net.Processors.ThreadState; + +namespace Streamiz.Kafka.Net.Tests.Private +{ + public class StreamThreadTests + { + #region State Test + + [Test] + public void TestCreatedState() + { + var state = ThreadState.CREATED; + Assert.AreEqual(0, state.Ordinal); + Assert.AreEqual("CREATED", state.Name); + Assert.AreEqual(new HashSet {1, 5}, state.Transitions); + Assert.IsFalse(state.IsRunning()); + Assert.IsFalse(state.IsValidTransition(ThreadState.DEAD)); + Assert.IsTrue(state.IsValidTransition(ThreadState.STARTING)); + } + + [Test] + public void TestStartingState() + { + var state = ThreadState.STARTING; + Assert.AreEqual(1, state.Ordinal); + Assert.AreEqual("STARTING", state.Name); + Assert.AreEqual(new HashSet {2, 3, 5}, state.Transitions); + Assert.IsTrue(state.IsRunning()); + Assert.IsFalse(state.IsValidTransition(ThreadState.CREATED)); + Assert.IsTrue(state.IsValidTransition(ThreadState.PARTITIONS_ASSIGNED)); + } + + [Test] + public void TestPartitionsRevokedState() + { + var state = ThreadState.PARTITIONS_REVOKED; + Assert.AreEqual(2, state.Ordinal); + Assert.AreEqual("PARTITIONS_REVOKED", state.Name); + Assert.AreEqual(new HashSet {2, 3, 5}, state.Transitions); + Assert.IsTrue(state.IsRunning()); + Assert.IsFalse(state.IsValidTransition(ThreadState.DEAD)); + Assert.IsTrue(state.IsValidTransition(ThreadState.PARTITIONS_ASSIGNED)); + } + + [Test] + public void TestPartitionsAssignedState() + { + var state = ThreadState.PARTITIONS_ASSIGNED; + Assert.AreEqual(3, state.Ordinal); + Assert.AreEqual("PARTITIONS_ASSIGNED", state.Name); + Assert.AreEqual(new HashSet {2, 3, 4, 5}, state.Transitions); + Assert.IsTrue(state.IsRunning()); + Assert.IsFalse(state.IsValidTransition(ThreadState.DEAD)); + Assert.IsTrue(state.IsValidTransition(ThreadState.RUNNING)); + } + + [Test] + public void TestRunningState() + { + var state = ThreadState.RUNNING; + Assert.AreEqual(4, state.Ordinal); + Assert.AreEqual("RUNNING", state.Name); + Assert.AreEqual(new HashSet {2, 3, 4, 5}, state.Transitions); + Assert.IsTrue(state.IsRunning()); + Assert.IsFalse(state.IsValidTransition(ThreadState.CREATED)); + Assert.IsTrue(state.IsValidTransition(ThreadState.PARTITIONS_ASSIGNED)); + } + + [Test] + public void TestPendingShutdownState() + { + var state = ThreadState.PENDING_SHUTDOWN; + Assert.AreEqual(5, state.Ordinal); + Assert.AreEqual("PENDING_SHUTDOWN", state.Name); + Assert.AreEqual(new HashSet {6}, state.Transitions); + Assert.IsFalse(state.IsRunning()); + Assert.IsFalse(state.IsValidTransition(ThreadState.CREATED)); + Assert.IsTrue(state.IsValidTransition(ThreadState.DEAD)); + } + + [Test] + public void TestDeadState() + { + var state = ThreadState.DEAD; + Assert.AreEqual(6, state.Ordinal); + Assert.AreEqual("DEAD", state.Name); + Assert.AreEqual(new HashSet { }, state.Transitions); + Assert.IsFalse(state.IsRunning()); + Assert.IsFalse(state.IsValidTransition(ThreadState.CREATED)); + } + + #endregion + + #region StreamThread Id + + [Test] + public void GetConsumerClientIdTest() + { + var result = StreamThread.GetConsumerClientId("thread-client"); + Assert.AreEqual($"thread-client-consumer", result); + } + + [Test] + public void GetRestoreConsumerClientIdTest() + { + var result = StreamThread.GetRestoreConsumerClientId("thread-client"); + Assert.AreEqual($"thread-client-restore-consumer", result); + } + + [Test] + public void GetSharedAdminClientIdTest() + { + var result = StreamThread.GetSharedAdminClientId("thread-client"); + Assert.AreEqual($"thread-client-admin", result); + } + + [Test] + public void GetTaskProducerClientIdTest() + { + var taskId = new TaskId {Id = 0, Partition = 0}; + var result = StreamThread.GetTaskProducerClientId("thread-client", taskId); + Assert.AreEqual($"thread-client-0-0-producer", result); + } + + [Test] + public void GetThreadProducerClientIdTest() + { + var result = StreamThread.GetThreadProducerClientId("thread-client"); + Assert.AreEqual($"thread-client-producer", result); + } + + #endregion + + #region StreamThread Workflow + + [Test] + public void CreateStreamThread() + { + var config = new StreamConfig(); + config.ApplicationId = "test"; + + var builder = new StreamBuilder(); + builder.Stream("topic").To("topic2"); + + var topo = builder.Build(); + + var supplier = new SyncKafkaSupplier(); + var thread = StreamThread.Create( + "thread-0", "c0", + topo.Builder, new StreamMetricsRegistry(), config, + supplier, supplier.GetAdmin(config.ToAdminConfig("admin")), + 0) as StreamThread; + + Assert.AreEqual("thread-0", thread.Name); + } + + [Test] + public void StreamThreadNormalWorkflow() + { + List allStates = new List(); + var expectedStates = new List + { + ThreadState.CREATED, + ThreadState.STARTING, + ThreadState.PARTITIONS_ASSIGNED, + ThreadState.RUNNING, + ThreadState.PENDING_SHUTDOWN, + ThreadState.DEAD + }; + + var source = new System.Threading.CancellationTokenSource(); + var config = new StreamConfig(); + config.ApplicationId = "test"; + config.Guarantee = ProcessingGuarantee.AT_LEAST_ONCE; + config.PollMs = 1; + + var serdes = new StringSerDes(); + var builder = new StreamBuilder(); + builder.Stream("topic").To("topic2"); + + var topo = builder.Build(); + + var supplier = new SyncKafkaSupplier(); + var producer = supplier.GetProducer(config.ToProducerConfig()); + var consumer = supplier.GetConsumer(config.ToConsumerConfig("test-consum"), null); + consumer.Subscribe("topic2"); + var thread = StreamThread.Create( + "thread-0", "c0", + topo.Builder, new StreamMetricsRegistry(), config, + supplier, supplier.GetAdmin(config.ToAdminConfig("admin")), + 0) as StreamThread; + allStates.Add(thread.State); + thread.StateChanged += (t, o, n) => + { + Assert.IsInstanceOf(n); + allStates.Add(n as ThreadState); + }; + + thread.Start(source.Token); + producer.Produce("topic", new Confluent.Kafka.Message + { + Key = serdes.Serialize("key1", new SerializationContext()), + Value = serdes.Serialize("coucou", new SerializationContext()) + }); + //WAIT STREAMTHREAD PROCESS MESSAGE + System.Threading.Thread.Sleep(100); + var message = consumer.Consume(100); + + source.Cancel(); + thread.Dispose(); + + Assert.AreEqual("key1", serdes.Deserialize(message.Message.Key, new SerializationContext())); + Assert.AreEqual("coucou", serdes.Deserialize(message.Message.Value, new SerializationContext())); + Assert.AreEqual(expectedStates, allStates); + } + + [Test] + public void StreamThreadCommitIntervalWorkflow() + { + var source = new System.Threading.CancellationTokenSource(); + var config = new StreamConfig(); + config.ApplicationId = "test"; + config.Guarantee = ProcessingGuarantee.AT_LEAST_ONCE; + config.PollMs = 1; + config.CommitIntervalMs = 1; + + var serdes = new StringSerDes(); + var builder = new StreamBuilder(); + builder.Stream("topic").To("topic2"); + + var topo = builder.Build(); + + var supplier = new SyncKafkaSupplier(); + var producer = supplier.GetProducer(config.ToProducerConfig()); + var consumer = supplier.GetConsumer(config.ToConsumerConfig("test-consum"), null); + consumer.Subscribe("topic2"); + var thread = StreamThread.Create( + "thread-0", "c0", + topo.Builder, new StreamMetricsRegistry(), config, + supplier, supplier.GetAdmin(config.ToAdminConfig("admin")), + 0) as StreamThread; + + thread.Start(source.Token); + producer.Produce("topic", new Confluent.Kafka.Message + { + Key = serdes.Serialize("key1", new SerializationContext()), + Value = serdes.Serialize("coucou", new SerializationContext()) + }); + //WAIT STREAMTHREAD PROCESS MESSAGE + System.Threading.Thread.Sleep(100); + var message = consumer.Consume(100); + + Assert.AreEqual("key1", serdes.Deserialize(message.Message.Key, new SerializationContext())); + Assert.AreEqual("coucou", serdes.Deserialize(message.Message.Value, new SerializationContext())); + + var offsets = thread.GetCommittedOffsets(new List {new TopicPartition("topic", 0)}, + TimeSpan.FromSeconds(10)).ToList(); + Assert.AreEqual(1, offsets.Count); + Assert.AreEqual(1, offsets[0].Offset.Value); + Assert.AreEqual(0, offsets[0].TopicPartition.Partition.Value); + Assert.AreEqual("topic", offsets[0].Topic); + + source.Cancel(); + thread.Dispose(); + } + + #endregion + + #region StreamThread SetState + + [Test] + public void CheckIncorrectStateTransition() + { + var config = new StreamConfig(); + config.ApplicationId = "test"; + + var builder = new StreamBuilder(); + builder.Stream("topic").To("topic2"); + + var topo = builder.Build(); + + var supplier = new SyncKafkaSupplier(); + var thread = StreamThread.Create( + "thread-0", "c0", + topo.Builder, new StreamMetricsRegistry(), config, + supplier, supplier.GetAdmin(config.ToAdminConfig("admin")), + 0) as StreamThread; + + // MUST BE IN CREATED STATE + Assert.AreEqual(ThreadState.CREATED, thread.State); + Assert.Throws(() => thread.SetState(ThreadState.DEAD)); + } + + [Test] + public void CheckSetStateWithoutStateChangedHandler() + { + var config = new StreamConfig(); + config.ApplicationId = "test"; + + var builder = new StreamBuilder(); + builder.Stream("topic").To("topic2"); + + var topo = builder.Build(); + + var supplier = new SyncKafkaSupplier(); + var thread = StreamThread.Create( + "thread-0", "c0", + topo.Builder, new StreamMetricsRegistry(), config, + supplier, supplier.GetAdmin(config.ToAdminConfig("admin")), + 0) as StreamThread; + + // MUST BE IN CREATED STATE + Assert.AreEqual(ThreadState.CREATED, thread.State); + thread.SetState(ThreadState.STARTING); + Assert.AreEqual(ThreadState.STARTING, thread.State); + } + + + [Test] + public void CheckSetStateStartingWithDeadThread() + { + var config = new StreamConfig(); + config.ApplicationId = "test"; + + var builder = new StreamBuilder(); + builder.Stream("topic").To("topic2"); + + var topo = builder.Build(); + + var supplier = new SyncKafkaSupplier(); + var thread = StreamThread.Create( + "thread-0", "c0", + topo.Builder, new StreamMetricsRegistry(), config, + supplier, supplier.GetAdmin(config.ToAdminConfig("admin")), + 0) as StreamThread; + + // MUST BE IN CREATED STATE + Assert.AreEqual(ThreadState.CREATED, thread.State); + thread.SetState(ThreadState.STARTING); + thread.SetState(ThreadState.PENDING_SHUTDOWN); + thread.SetState(ThreadState.DEAD); + thread.Start(default); + Assert.IsFalse(thread.IsRunning); + } + + #endregion + + #region StreamThread Commit Requested TODO + + // TODO: + + #endregion + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource supplier.Streamiz.Kafka.Net.Mock.Sync.SyncKafkaSupplier.producer of type Streamiz.Kafka.Net.Mock.Sync.SyncProducer, Leaked resource supplier.Streamiz.Kafka.Net.Mock.Sync.SyncKafkaSupplier.admin of type Streamiz.Kafka.Net.Mock.Sync.SyncAdminClient, Leaked resource (returned from Streamiz.Kafka.Net.Processors.IThread Streamiz.Kafka.Net.Processors.StreamThread::Create(System.String,System.String,Streamiz.Kafka.Net.Processors.Internal.InternalTopologyBuilder,Streamiz.Kafka.Net.Metrics.StreamMetricsRegistry,Streamiz.Kafka.Net.IStreamConfig,Streamiz.Kafka.Net.Kafka.IKafkaSupplier,Confluent.Kafka.IAdminClient,System.Int32) at Line 165) of type Streamiz.Kafka.Net.Processors.StreamThread in method "Void StreamThreadTests.CreateStreamThread()". + +### Severity: +ERROR + +### Procedure: +Void StreamThreadTests.CreateStreamThread() + +### File: +test/Streamiz.Kafka.Net.Tests/Private/StreamThreadTests.cs + +### Key: +StreamThreadTests.cs|CreateStreamThread|DOTNET_RESOURCE_LEAK + +### Hash: +ecacf16cb461c62650234d878a6a2cf2 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0363/instruction.md b/inferredbugs-0363/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..57d743fad4852850da88357f660be8851b0f3a0d --- /dev/null +++ b/inferredbugs-0363/instruction.md @@ -0,0 +1,295 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** kafka-streams-dotnet +**Bug ID:** 8 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Confluent.Kafka; +using Moq; +using NUnit.Framework; +using Streamiz.Kafka.Net.Errors; +using Streamiz.Kafka.Net.Processors; +using Streamiz.Kafka.Net.Processors.Internal; +using Streamiz.Kafka.Net.State; +using Streamiz.Kafka.Net.Stream.Internal; +using System; +using System.Collections.Generic; +using System.Linq; +using Streamiz.Kafka.Net.Mock.Sync; + +namespace Streamiz.Kafka.Net.Tests.Private +{ + public class GlobalStateManagerTests + { + private GlobalStateManager stateManager; + private Mock> kvStoreMock; + private Mock> otherStoreMock; + private Mock adminClientMock; + private ProcessorTopology topology; + private Mock streamConfigMock; + private ProcessorContext context; + + private readonly string kvStoreName = "kv-store"; + private readonly string kvStoreTopic = "kv-store-topic"; + private readonly string otherStoreName = "other-store"; + private readonly string otherStoreTopic = "other-store-topic"; + + [SetUp] + public void SetUp() + { + var mockSupplier = new SyncKafkaSupplier(); + var consumerConfig = new ConsumerConfig(); + consumerConfig.GroupId = "global-consulmer"; + var globalConsumer = mockSupplier.GetConsumer(consumerConfig, null); + + streamConfigMock = new Mock(); + streamConfigMock.Setup(c => c.StateDir).Returns("."); + streamConfigMock.Setup(c => c.ApplicationId).Returns("app"); + + kvStoreMock = CreateMockStore>(kvStoreName); + otherStoreMock = CreateMockStore>(otherStoreName); + var globalStateStores = new Dictionary() { + { kvStoreMock.Object.Name, kvStoreMock.Object }, + { otherStoreMock.Object.Name, otherStoreMock.Object } + }; + var storesToTopics = new Dictionary() { + { kvStoreMock.Object.Name, kvStoreTopic }, + { otherStoreMock.Object.Name, otherStoreTopic } + }; + + topology = new ProcessorTopology( + null, + new Dictionary(), + new Dictionary(), + new Dictionary(), + new Dictionary(), + globalStateStores, + storesToTopics); + + adminClientMock = new Mock(); + RegisterPartitionInAdminClient(kvStoreTopic); + RegisterPartitionInAdminClient(otherStoreTopic); + + stateManager = new GlobalStateManager(globalConsumer, topology, + adminClientMock.Object, + streamConfigMock.Object + ); + + context = new GlobalProcessorContext( + streamConfigMock.Object, + stateManager); + + stateManager.SetGlobalProcessorContext(context); + } + + [Test] + public void ShouldInitializeStateStores() + { + stateManager.Initialize(); + + kvStoreMock.Verify(store => store.Init(It.IsAny(), It.IsAny()), Times.Once); + } + + [Test] + public void ShouldInitializeWithGlobalContext() + { + stateManager.Initialize(); + + kvStoreMock.Verify(store => store.Init(context, It.IsAny()), Times.Once); + } + + [Test] + public void ShouldReturnInitializedStoreNames() + { + ISet storeNames = stateManager.Initialize(); + + Assert.AreEqual(new HashSet() { kvStoreName, otherStoreName }, storeNames); + } + + [Test] + public void ShouldThrowIfSameStoreTwiceTwiceInTopology() + { + // this was already registered once + topology.GlobalStateStores.Add($"kvStoreMock.Object.Name{1}", kvStoreMock.Object); + + Assert.Throws(() => stateManager.Initialize()); + } + + [Test] + public void ShouldThrowIfNoPartitionsFoundForStore() + { + kvStoreMock + .Setup(s => s.Init(context, It.IsAny())) + .Callback((ProcessorContext c, IStateStore store) => + { + stateManager.Register(store, (k, v) => { }); + }); + + adminClientMock.Setup(client => client.GetMetadata(kvStoreTopic, It.IsAny())).Returns((Metadata)null); + Assert.Throws(() => stateManager.Initialize()); + } + + [Test] + public void ShouldSetChangelogOffsetToZero() + { + stateManager.Initialize(); + stateManager.Register(kvStoreMock.Object, null); + + Assert.AreEqual(-2, stateManager.ChangelogOffsets.Single(x => x.Key.Topic == kvStoreTopic).Value); + } + + [Test] + public void ShouldReturnStore() + { + stateManager.Initialize(); + stateManager.Register(kvStoreMock.Object, null); + + var result = stateManager.GetStore(kvStoreName); + + Assert.AreEqual(kvStoreMock.Object, result); + } + + [Test] + public void ShouldReturnNullIfNoStore() + { + stateManager.Initialize(); + + var result = stateManager.GetStore("some-store-name"); + + Assert.AreEqual(null, result); + } + + [Test] + public void ShouldFlushStateStores() + { + stateManager.Initialize(); + stateManager.Register(kvStoreMock.Object, null); + stateManager.Register(otherStoreMock.Object, null); + + stateManager.Flush(); + + kvStoreMock.Verify(x => x.Flush(), Times.Once); + otherStoreMock.Verify(x => x.Flush(), Times.Once); + } + + [Test] + public void ShouldCloseStateStores() + { + stateManager.Initialize(); + stateManager.Register(kvStoreMock.Object, null); + stateManager.Register(otherStoreMock.Object, null); + + stateManager.Close(); + + kvStoreMock.Verify(x => x.Close(), Times.Once); + otherStoreMock.Verify(x => x.Close(), Times.Once); + } + + [Test] + public void ShouldThrowIfStoreCloseFailed() + { + stateManager.Initialize(); + stateManager.Register(kvStoreMock.Object, null); + kvStoreMock.Setup(x => x.Close()).Throws(new ProcessorStateException("boom!")); + + Assert.Throws(() => stateManager.Close()); + } + + [Test] + public void ShouldAttemptToCloseAllStoresEvenWhenSomeException() + { + stateManager.Initialize(); + stateManager.Register(kvStoreMock.Object, null); + stateManager.Register(otherStoreMock.Object, null); + + kvStoreMock.Setup(x => x.Close()).Throws(new ProcessorStateException("boom!")); + + try + { + stateManager.Close(); + } + catch + { + // expected + } + + kvStoreMock.Verify(x => x.Close(), Times.Once); + otherStoreMock.Verify(x => x.Close(), Times.Once); + } + + private Mock CreateMockStore(string name, bool isOpen = true) where T : class, IStateStore + { + var store = new Mock(); + store.Setup(kvStore => kvStore.Name).Returns(name); + store.Setup(kvStore => kvStore.IsOpen).Returns(isOpen); + return store; + } + + private void RegisterPartitionInAdminClient(string topic) + { + adminClientMock.Setup(client => client.GetMetadata(topic, It.IsAny())).Returns( + new Metadata( + null, + new List() { + new TopicMetadata( + topic, + new List() { new PartitionMetadata(0, 0, new int[] { }, new int[] { }, null) }, + null) + }, 0, "") + ); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource globalConsumer of type Streamiz.Kafka.Net.Mock.Sync.SyncConsumer, Leaked resource mockSupplier.Streamiz.Kafka.Net.Mock.Sync.SyncKafkaSupplier.producer of type Streamiz.Kafka.Net.Mock.Sync.SyncProducer, Leaked resource mockSupplier.Streamiz.Kafka.Net.Mock.Sync.SyncKafkaSupplier.admin of type Streamiz.Kafka.Net.Mock.Sync.SyncAdminClient in method "Void GlobalStateManagerTests.SetUp()". + +### Severity: +ERROR + +### Procedure: +Void GlobalStateManagerTests.SetUp() + +### File: +test/Streamiz.Kafka.Net.Tests/Private/GlobalStateManagerTests.cs + +### Key: +GlobalStateManagerTests.cs|SetUp|DOTNET_RESOURCE_LEAK + +### Hash: +88eb5c046426ea67120ff60b06ab12a4 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0391/instruction.md b/inferredbugs-0391/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..beffc675a7fdd253a15a617d1ed354e56f737ad6 --- /dev/null +++ b/inferredbugs-0391/instruction.md @@ -0,0 +1,128 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** opengl4csharp +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; + +namespace OpenGL.Constructs +{ + public class Geometry + { + /// + /// Create a basic quad by storing two triangles into a VAO. + /// This quad includes UV co-ordinates from 0,0 to 1,1. + /// + /// The ShaderProgram assigned to this quad. + /// The location of the VAO (assigned to the vertices). + /// The size of the VAO (assigned to the vertices). + /// The VAO object representing this quad. + public static VAO CreateQuad(ShaderProgram program, Vector2 location, Vector2 size) + { + Vector3[] vertices = new Vector3[] { new Vector3(location.x, location.y, 0), new Vector3(location.x + size.x, location.y, 0), + new Vector3(location.x + size.x, location.y + size.y, 0), new Vector3(location.x, location.y + size.y, 0) }; + Vector2[] uvs = new Vector2[] { new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1) }; + int[] indices = new int[] { 0, 1, 2, 2, 3, 0 }; + + return new VAO(program, new VBO(vertices), new VBO(uvs), new VBO(indices, BufferTarget.ElementArrayBuffer, BufferUsageHint.StaticRead)); + } + + /// + /// Create a basic quad by storing two triangles into a VAO. + /// This quad includes UV co-ordinates from uvloc to uvloc+uvsize. + /// + /// The ShaderProgram assigned to this quad. + /// The location of the VAO (assigned to the vertices). + /// The size of the VAO (assigned to the vertices). + /// The origin of the UV co-ordinates. + /// The size of the UV co-ordinates. + /// The VAO object representing this quad. + public static VAO CreateQuad(ShaderProgram program, Vector2 location, Vector2 size, Vector2 uvloc, Vector2 uvsize) + { + Vector3[] vertices = new Vector3[] { new Vector3(location.x, location.y, 0), new Vector3(location.x + size.x, location.y, 0), + new Vector3(location.x + size.x, location.y + size.y, 0), new Vector3(location.x, location.y + size.y, 0) }; + Vector2[] uvs = new Vector2[] { uvloc, new Vector2(uvloc.x + uvsize.x, uvloc.y), new Vector2(uvloc.x + uvsize.x, uvloc.y + uvsize.y), new Vector2(uvloc.x, uvloc.y + uvsize.y) }; + int[] indices = new int[] { 0, 1, 2, 2, 3, 0 }; + + return new VAO(program, new VBO(vertices), new VBO(uvs), new VBO(indices, BufferTarget.ElementArrayBuffer, BufferUsageHint.StaticRead)); + } + + /// + /// Create a basic cube and store into a VAO. + /// This cube consists of 12 triangles and 6 faces. + /// + /// The ShaderProgram assigned to this cube. + /// The 3 minimum values of the cube (lower left back corner). + /// The 3 maximum values of the cube (top right front corner). + /// + public static VAO CreateCube(ShaderProgram program, Vector3 min, Vector3 max) + { + Vector3[] vertex = new Vector3[] { + new Vector3(min.x, min.y, min.z), + new Vector3(min.x, min.y, max.z), + new Vector3(min.x, max.y, min.z), + new Vector3(min.x, max.y, max.z), + new Vector3(max.x, min.y, min.z), + new Vector3(max.x, min.y, max.z), + new Vector3(max.x, max.y, min.z), + new Vector3(max.x, max.y, max.z) }; + int[] element = new int[] { 0, 1, 2, 1, 3, 2, 1, 5, 3, 5, 7, 3, 4, 0, 2, 4, 2, 6, 5, 4, 6, 5, 6, 7, 2, 3, 6, 6, 3, 7, 0, 1, 5, 5, 4, 0 }; + + return new VAO(program, new VBO(vertex), new VBO(element)); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type OpenGL.VAO, Leaked resource (output of OpenGL.VBO`1::.ctor() at Line 66) of type OpenGL.VBO`1, Leaked resource (output of OpenGL.VBO`1::.ctor() at Line 66) of type OpenGL.VBO`1 in method "VAO Geometry.CreateCube(ShaderProgram,Vector3,Vector3)". + +### Severity: +ERROR + +### Procedure: +VAO Geometry.CreateCube(ShaderProgram,Vector3,Vector3) + +### File: +OpenGL/Constructs/Geometry.cs + +### Key: +Geometry.cs|CreateCube|DOTNET_RESOURCE_LEAK + +### Hash: +447d4d4381cafcccacb11d5ef3478e2a + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0396/instruction.md b/inferredbugs-0396/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3f9a765179f6e3f7c3e590e98b9632ce7294c477 --- /dev/null +++ b/inferredbugs-0396/instruction.md @@ -0,0 +1,143 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Blazor-Hackathon +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Blazor.Components; +using Blazor.Runtime.Components; +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; + +namespace Blazor.Routing +{ + public static class Router + { + private static string _mountInElementSelector; + private static string _currentPageComponentPath; + private static Component _currentPageComponent; + public static IEnumerable ViewAssemblies; + private static BlazorContext _context; + + public static void MountInElement(string selector) + { + _mountInElementSelector = selector; + } + + internal static Component OnNavigation(string descriptor) + { + var parsed = MiniJSON.Json.Deserialize(descriptor) as Dictionary; + var url = (string)parsed["url"]; + var absoluteUrl = (string)parsed["absoluteUrl"]; + if (_context == null) + { + _context = new BlazorContext(absoluteUrl); + } + else + { + _context.AbsoluteUrl = absoluteUrl; + } + return MountPageFromUrl(url, _context); + } + + internal static Component MountPageFromUrl(string url, BlazorContext context) + { + // By holding the _currentPageComponent in a static property, we ensure that it doesn't + // get GCed while the user can still see and try to interact with it. + // TODO: Instead of just using "MountAsPage" which destroys the entire previous element content, + // somehow find the nearest common layout ancestor between the old and new page, and retain + // the DOM/vdom up to and including that layout, and just insert the new sequence of child + // layouts and the new page into it. + _currentPageComponentPath = UrlToComponentPath(url); + return _currentPageComponent = RazorComponent + .Instantiate(_currentPageComponentPath, context) + .MountAsPage(_mountInElementSelector); + } + + private static string UrlToComponentPath(string url) + { + if (url.Equals("/")) + { + url = url + "Index"; + } + if (url[url.Length - 1] == '/') + { + url = url.Substring(0, url.Length - 1); + } + var split = url.Split(new char[] { '/' }); + var id = split[split.Length - 1]; + int res; + if (int.TryParse(id, out res)) + { + // We have an int, remove id and continue + string temp = "/"; + for (int i =0; i < split.Length - 1; i++) + { + temp += split[i]; + } + Console.WriteLine(temp); + return $".{temp.Replace('/', Path.DirectorySeparatorChar)}.cshtml"; + } + + return $".{url.Replace('/', Path.DirectorySeparatorChar)}.cshtml"; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `parsed` last assigned on line 25 could be null and is dereferenced at line 26, column 13. + +### Severity: +ERROR + +### Procedure: +Component Router.OnNavigation(String) + +### File: +src/Blazor.Runtime/Routing/Router.cs + +### Key: +Router.cs|OnNavigation|NULL_DEREFERENCE + +### Node Key: +4c5a0b70536cd3f04e9da256c6c8ae68 + +### Hash: +7b039b3a86cbe7d9bf21bb6b15de9c32 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0398/instruction.md b/inferredbugs-0398/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4f6574b41e804efe6057fdab848b5cdc772bacde --- /dev/null +++ b/inferredbugs-0398/instruction.md @@ -0,0 +1,188 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** AspNetCoreCertificates +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using CertificateManager; +using CertificateManager.Models; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Text; +using Xunit; + +namespace CertificateManagerTests +{ + public class DistinguishedNameTests + { + + [Fact] + public void DnCompleteValid() + { + var serviceProvider = new ServiceCollection() + .AddCertificateManager() + .BuildServiceProvider(); + + var certManagerService = serviceProvider.GetService(); + + + var rootCaL1 = certManagerService.CreateRootCertificateForClientServerAuth( + new DistinguishedName { + CommonName = "root dev", + Country = "IT", + Locality = "DD", + Organisation="SS", + OrganisationUnit="unit", + StateProvince= "yes" + }, + new ValidityPeriod { ValidFrom = DateTime.UtcNow, ValidTo = DateTime.UtcNow.AddYears(10) }, + 3, "localhost"); + + Assert.Equal("CN=root dev, C=IT, O=SS, OU=unit, L=DD, S=yes", rootCaL1.Subject); + Assert.Equal("CN=root dev, C=IT, O=SS, OU=unit, L=DD, S=yes", rootCaL1.Issuer); + } + + [Fact] + public void DnHalfCompleteValid() + { + var serviceProvider = new ServiceCollection() + .AddCertificateManager() + .BuildServiceProvider(); + + var certManagerService = serviceProvider.GetService(); + + + var rootCaL1 = certManagerService.CreateRootCertificateForClientServerAuth( + new DistinguishedName + { + CommonName = "root dev", + Country = "IT", + Locality = "DD", + Organisation = "SS" + + }, + new ValidityPeriod { ValidFrom = DateTime.UtcNow, ValidTo = DateTime.UtcNow.AddYears(10) }, + 3, "localhost"); + + Assert.Equal("CN=root dev, C=IT, O=SS, L=DD", rootCaL1.Subject); + Assert.Equal("CN=root dev, C=IT, O=SS, L=DD", rootCaL1.Issuer); + } + + [Fact] + public void DnMissingCountry() + { + var serviceProvider = new ServiceCollection() + .AddCertificateManager() + .BuildServiceProvider(); + + var certManagerService = serviceProvider.GetService(); + + + certManagerService.CreateRootCertificateForClientServerAuth( + new DistinguishedName + { + CommonName = "root dev", + Locality = "DD", + Organisation = "SS", + OrganisationUnit = "unit", + StateProvince = "yes" + }, + new ValidityPeriod { ValidFrom = DateTime.UtcNow, ValidTo = DateTime.UtcNow.AddYears(10) }, + 3, "localhost"); + + } + + [Fact] + public void DnMissingCommonName() + { + var serviceProvider = new ServiceCollection() + .AddCertificateManager() + .BuildServiceProvider(); + + var certManagerService = serviceProvider.GetService(); + + + certManagerService.CreateRootCertificateForClientServerAuth( + new DistinguishedName + { + Country = "IT", + Locality = "DD", + Organisation = "SS", + OrganisationUnit = "unit", + StateProvince = "yes" + }, + new ValidityPeriod { ValidFrom = DateTime.UtcNow, ValidTo = DateTime.UtcNow.AddYears(10) }, + 3, "localhost"); + } + + [Fact] + public void DnNull() + { + var serviceProvider = new ServiceCollection() + .AddCertificateManager() + .BuildServiceProvider(); + + var certManagerService = serviceProvider.GetService(); + + + certManagerService.CreateRootCertificateForClientServerAuth( + null, + new ValidityPeriod { ValidFrom = DateTime.UtcNow, ValidTo = DateTime.UtcNow.AddYears(10) }, + 3, "localhost"); + } + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +null (last assigned on line 123) is dereferenced in call to `CertificateManagerService.CreateRootCertificateForClientServerAuth(...)`. + +### Severity: +ERROR + +### Procedure: +Void DistinguishedNameTests.DnNull() + +### File: +CertificatesCreation/CertificateManagerTests/DistinguishedNameTests.cs + +### Key: +DistinguishedNameTests.cs|DnNull|NULLPTR_DEREFERENCE + +### Hash: +95ce4460b8ee68a538110727a2fd7dba + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0399/instruction.md b/inferredbugs-0399/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5afac9b213a63f5ba12abcbaca306bf968c566ad --- /dev/null +++ b/inferredbugs-0399/instruction.md @@ -0,0 +1,69 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** design-patterns-explained-with-food +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace CreationalPatterns.Prototype.DiningRoomIcons.Chairs { + public class CafeChairIcon : IChairIcon { + public bool HasSeatCushions => false; + + public IDeepCloneable DeepClone() { + CafeChairIcon cafeChairIcon = null; + return cafeChairIcon.DeepClone(); + } + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`cafeChairIcon` could be null (last assigned on line 6) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +IDeepCloneable CafeChairIcon.DeepClone() + +### File: +CreationalPatterns/Prototype/DiningRoomIcons/Chairs/CafeChairIcon.cs + +### Key: +CafeChairIcon.cs|DeepClone|NULLPTR_DEREFERENCE + +### Hash: +505c395db673e44f4f391084e8de2943 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0440/instruction.md b/inferredbugs-0440/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6f3d09747710b037f665fe8fc00801572ad039cf --- /dev/null +++ b/inferredbugs-0440/instruction.md @@ -0,0 +1,637 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** apm-agent-dotnet +**Bug ID:** 19 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Threading; +using System.Threading.Tasks; +using Elastic.Apm.Api; +using Elastic.Apm.Model.Payload; +using Elastic.Apm.Tests.Mocks; +using Xunit; + +namespace Elastic.Apm.Tests.ApiTests +{ + /// + /// Tests the API for manual instrumentation. + /// Only tests scenarios when using the convenient API and only test transactions. + /// Spans are covered by . + /// Scenarios with manually calling , + /// , + /// are covered by + /// Very similar to . The test cases are the same, + /// but this one tests the CaptureTransaction method - including every single overload. + /// + public class ConvenientApiTransactionTests + { + private const string ExceptionMessage = "Foo"; + private const int SleepLength = 45; + private const string TransactionName = "ConvenientApiTest"; + private const string TransactionType = "Test"; + + /// + /// Tests the method. + /// It wraps a fake transaction (Thread.Sleep) into the CaptureTransaction method + /// and it makes sure that the transaction is captured by the agent. + /// + [Fact] + public void SimpleAction() => AssertWith1Transaction(agent => + { + agent.Tracer.CaptureTransaction(TransactionName, TransactionType, + () => { Thread.Sleep(SleepLength); }); + }); + + /// + /// Tests the method with an exception. + /// It wraps a fake transaction (Thread.Sleep) that throws an exception into the CaptureTransaction method + /// and it makes sure that the transaction and the exception are captured by the agent. + /// + [Fact] + public void SimpleActionWithException() => AssertWith1TransactionAnd1Error(agent => + { + Assert.Throws(() => + { + agent.Tracer.CaptureTransaction(TransactionName, TransactionType, new Action(() => + { + Thread.Sleep(SleepLength); + throw new InvalidOperationException(ExceptionMessage); + })); + }); + }); + + /// + /// Tests the method. + /// It wraps a fake transaction (Thread.Sleep) into the CaptureTransaction method with an + /// parameter + /// and it makes sure that the transaction is captured by the agent and the parameter + /// is not null + /// + [Fact] + public void SimpleActionWithParameter() => AssertWith1Transaction(agent => + { + agent.Tracer.CaptureTransaction(TransactionName, TransactionType, + t => + { + Assert.NotNull(t); + Thread.Sleep(SleepLength); + }); + }); + + /// + /// Tests the method with an exception. + /// It wraps a fake transaction (Thread.Sleep) that throws an exception into the CaptureTransaction method with an + /// parameter + /// and it makes sure that the transaction and the error are captured by the agent and the + /// parameter is not null + /// + [Fact] + public void SimpleActionWithExceptionAndParameter() => AssertWith1TransactionAnd1Error(agent => + { + Assert.Throws(() => + { + agent.Tracer.CaptureTransaction(TransactionName, TransactionType, new Action(t => + { + Assert.NotNull(t); + Thread.Sleep(SleepLength); + throw new InvalidOperationException(ExceptionMessage); + })); + }); + }); + + /// + /// Tests the method. + /// It wraps a fake transaction (Thread.Sleep) with a return value into the CaptureTransaction method + /// and it makes sure that the transaction is captured by the agent and the return value is correct. + /// + [Fact] + public void SimpleActionWithReturnType() => AssertWith1Transaction(agent => + { + var res = agent.Tracer.CaptureTransaction(TransactionName, TransactionType, () => + { + Thread.Sleep(SleepLength); + return 42; + }); + + Assert.Equal(42, res); + }); + + /// + /// Tests the method. + /// It wraps a fake transaction (Thread.Sleep) with a return value into the CaptureTransaction method with an + /// parameter + /// and it makes sure that the transaction is captured by the agent and the return value is correct and the + /// is not null. + /// + [Fact] + public void SimpleActionWithReturnTypeAndParameter() => AssertWith1Transaction(agent => + { + var res = agent.Tracer.CaptureTransaction(TransactionName, TransactionType, + t => + { + Assert.NotNull(t); + Thread.Sleep(SleepLength); + return 42; + }); + + Assert.Equal(42, res); + }); + + /// + /// Tests the method with an + /// exception. + /// It wraps a fake transaction (Thread.Sleep) with a return value that throws an exception into the CaptureTransaction + /// method with an parameter + /// and it makes sure that the transaction and the error are captured by the agent and the return value is correct and the + /// is not null. + /// + [Fact] + public void SimpleActionWithReturnTypeAndExceptionAndParameter() => AssertWith1TransactionAnd1Error(agent => + { + Assert.Throws(() => + { + var result = agent.Tracer.CaptureTransaction(TransactionName, TransactionType, t => + { + Assert.NotNull(t); + Thread.Sleep(SleepLength); + + if (new Random().Next(1) == 0) //avoid unreachable code warning. + throw new InvalidOperationException(ExceptionMessage); + + return 42; + }); + + Assert.True(false); //Should not be executed because the agent isn't allowed to catch an exception. + Assert.Equal(42, result); //But if it'd not throw it'd be 42. + }); + }); + + /// + /// Tests the method with an exception. + /// It wraps a fake transaction (Thread.Sleep) with a return value that throws an exception into the CaptureTransaction + /// method + /// and it makes sure that the transaction and the error are captured by the agent. + /// + [Fact] + public void SimpleActionWithReturnTypeAndException() => AssertWith1TransactionAnd1Error(agent => + { + Assert.Throws(() => + { + var result = agent.Tracer.CaptureTransaction(TransactionName, TransactionType, () => + { + Thread.Sleep(SleepLength); + + if (new Random().Next(1) == 0) //avoid unreachable code warning. + throw new InvalidOperationException(ExceptionMessage); + + return 42; + }); + + Assert.True(false); //Should not be executed because the agent isn't allowed to catch an exception. + Assert.Equal(42, result); //But if it'd not throw it'd be 42. + }); + }); + + /// + /// Tests the method. + /// It wraps a fake async transaction (Task.Delay) into the CaptureTransaction method + /// and it makes sure that the transaction is captured. + /// + [Fact] + public async Task AsyncTask() => await AssertWith1TransactionAsync(async agent => + { + await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, + async () => { await Task.Delay(SleepLength); }); + }); + + /// + /// Tests the method with an exception + /// It wraps a fake async transaction (Task.Delay) that throws an exception into the CaptureTransaction method + /// and it makes sure that the transaction and the error are captured. + /// + [Fact] + public async Task AsyncTaskWithException() => await AssertWith1TransactionAnd1ErrorAsync(async agent => + { + await Assert.ThrowsAsync(async () => + { + await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, async () => + { + await Task.Delay(SleepLength); + throw new InvalidOperationException(ExceptionMessage); + }); + }); + }); + + /// + /// Tests the method. + /// It wraps a fake async transaction (Task.Delay) into the CaptureTransaction method with an + /// parameter + /// and it makes sure that the transaction is captured and the parameter is not null. + /// + [Fact] + public async Task AsyncTaskWithParameter() => await AssertWith1TransactionAsync(async agent => + { + await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, + async t => + { + Assert.NotNull(t); + await Task.Delay(SleepLength); + }); + }); + + /// + /// Tests the method with an + /// exception. + /// It wraps a fake async transaction (Task.Delay) that throws an exception into the CaptureTransaction method with an + /// parameter + /// and it makes sure that the transaction and the error are captured and the parameter + /// is not null. + /// + [Fact] + public async Task AsyncTaskWithExceptionAndParameter() => await AssertWith1TransactionAnd1ErrorAsync(async agent => + { + await Assert.ThrowsAsync(async () => + { + await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, async t => + { + Assert.NotNull(t); + await Task.Delay(SleepLength); + throw new InvalidOperationException(ExceptionMessage); + }); + }); + }); + + /// + /// Tests the method. + /// It wraps a fake async transaction (Task.Delay) with a return value into the CaptureTransaction method + /// and it makes sure that the transaction is captured by the agent and the return value is correct. + /// + [Fact] + public async Task AsyncTaskWithReturnType() => await AssertWith1TransactionAsync(async agent => + { + var res = await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, async () => + { + await Task.Delay(SleepLength); + return 42; + }); + Assert.Equal(42, res); + }); + + /// + /// Tests the method. + /// It wraps a fake async transaction (Task.Delay) with a return value into the CaptureTransaction method with an + /// parameter + /// and it makes sure that the transaction is captured by the agent and the return value is correct and the + /// is not null. + /// + [Fact] + public async Task AsyncTaskWithReturnTypeAndParameter() => await AssertWith1TransactionAsync(async agent => + { + var res = await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, + async t => + { + Assert.NotNull(t); + await Task.Delay(SleepLength); + return 42; + }); + + Assert.Equal(42, res); + }); + + /// + /// Tests the method with an + /// exception. + /// It wraps a fake async transaction (Task.Delay) with a return value that throws an exception into the CaptureTransaction + /// method with an parameter + /// and it makes sure that the transaction and the error are captured by the agent and the return value is correct and the + /// is not null. + /// + [Fact] + public async Task AsyncTaskWithReturnTypeAndExceptionAndParameter() => await AssertWith1TransactionAnd1ErrorAsync(async agent => + { + await Assert.ThrowsAsync(async () => + { + var result = await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, async t => + { + Assert.NotNull(t); + await Task.Delay(SleepLength); + + if (new Random().Next(1) == 0) //avoid unreachable code warning. + throw new InvalidOperationException(ExceptionMessage); + + return 42; + }); + + Assert.True(false); //Should not be executed because the agent isn't allowed to catch an exception. + Assert.Equal(42, result); //But if it'd not throw it'd be 42. + }); + }); + + /// + /// Tests the method with an exception. + /// It wraps a fake async transaction (Task.Delay) with a return value that throws an exception into the CaptureTransaction + /// method + /// and it makes sure that the transaction and the error are captured by the agent. + /// + [Fact] + public async Task AsyncTaskWithReturnTypeAndException() => await AssertWith1TransactionAnd1ErrorAsync(async agent => + { + await Assert.ThrowsAsync(async () => + { + var result = await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, async () => + { + await Task.Delay(SleepLength); + + if (new Random().Next(1) == 0) //avoid unreachable code warning. + throw new InvalidOperationException(ExceptionMessage); + + return 42; + }); + + Assert.True(false); //Should not be executed because the agent isn't allowed to catch an exception. + Assert.Equal(42, result); //But if it'd not throw it'd be 42. + }); + }); + + /// + /// Wraps a cancelled task into the CaptureTransaction method and + /// makes sure that the cancelled task is captured by the agent. + /// + [Fact] + public async Task CancelledAsyncTask() + { + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender)); + + var cancellationTokenSource = new CancellationTokenSource(); + var token = cancellationTokenSource.Token; + cancellationTokenSource.Cancel(); + + await Assert.ThrowsAsync(async () => + { + await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, + async () => + { + // ReSharper disable once MethodSupportsCancellation, we want to delay before we throw the exception + await Task.Delay(SleepLength); + token.ThrowIfCancellationRequested(); + }); + }); + + Assert.NotEmpty(payloadSender.Payloads); + Assert.NotEmpty(payloadSender.Payloads[0].Transactions); + + Assert.Equal(TransactionName, payloadSender.Payloads[0].Transactions[0].Name); + Assert.Equal(TransactionType, payloadSender.Payloads[0].Transactions[0].Type); + + //`await Task.Delay` is inaccurate, so we enable 10% error in the test + var expectedTransactionLength = SleepLength - (SleepLength * 0.1); + var duration = payloadSender.Payloads[0].Transactions[0].Duration; + Assert.True(duration >= expectedTransactionLength, $"Expected {duration} to be greater or equal to: {expectedTransactionLength}"); + + Assert.NotEmpty(payloadSender.Errors); + Assert.NotEmpty(payloadSender.Errors[0].Errors); + + Assert.Equal("A task was canceled", payloadSender.Errors[0].Errors[0].Culprit); + Assert.Equal("Task canceled", payloadSender.Errors[0].Errors[0].Exception.Message); + } + + /// + /// Creates a custom transaction and adds a tag to it. + /// Makes sure that the tag is stored on Transaction.Context. + /// + [Fact] + public void TagsOnTransaction() + { + var payloadSender = AssertWith1Transaction( + t => + { + t.Tracer.CaptureTransaction(TransactionName, TransactionType, transaction => + { + Thread.Sleep(SleepLength); + transaction.Tags["foo"] = "bar"; + }); + }); + + //According to the Intake API tags are stored on the Context (and not on Transaction.Tags directly). + Assert.Equal("bar", payloadSender.FirstTransaction.Context.Tags["foo"]); + + //Also make sure the tag is visible directly on Transaction.Tags. + Assert.Equal("bar", payloadSender.Payloads[0].Transactions[0].Tags["foo"]); + } + + /// + /// Creates a custom async transaction and adds a tag to it. + /// Makes sure that the tag is stored on Transaction.Context. + /// + [Fact] + public async Task TagsOnTransactionAsync() + { + var payloadSender = await AssertWith1TransactionAsync( + async t => + { + await t.Tracer.CaptureTransaction(TransactionName, TransactionType, async transaction => + { + await Task.Delay(SleepLength); + transaction.Tags["foo"] = "bar"; + }); + }); + + //According to the Intake API tags are stored on the Context (and not on Transaction.Tags directly). + Assert.Equal("bar", payloadSender.FirstTransaction.Context.Tags["foo"]); + + //Also make sure the tag is visible directly on Transaction.Tags. + Assert.Equal("bar", payloadSender.Payloads[0].Transactions[0].Tags["foo"]); + } + + /// + /// Creates a custom async Transaction that ends with an error and adds a tag to it. + /// Makes sure that the tag is stored on Transaction.Context. + /// + [Fact] + public async Task TagsOnTransactionAsyncError() + { + var payloadSender = await AssertWith1TransactionAnd1ErrorAsync( + async t => + { + await Assert.ThrowsAsync(async () => + { + await t.Tracer.CaptureTransaction(TransactionName, TransactionType, async transaction => + { + await Task.Delay(SleepLength); + transaction.Tags["foo"] = "bar"; + + if (new Random().Next(1) == 0) //avoid unreachable code warning. + throw new InvalidOperationException(ExceptionMessage); + }); + }); + }); + + //According to the Intake API tags are stored on the Context (and not on Transaction.Tags directly). + Assert.Equal("bar", payloadSender.FirstTransaction.Context.Tags["foo"]); + + //Also make sure the tag is visible directly on Transaction.Tags. + Assert.Equal("bar", payloadSender.Payloads[0].Transactions[0].Tags["foo"]); + } + + /// + /// Asserts on 1 transaction with async code + /// + private async Task AssertWith1TransactionAsync(Func func) + { + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender)); + + await func(agent); + + Assert.NotEmpty(payloadSender.Payloads); + Assert.NotEmpty(payloadSender.Payloads[0].Transactions); + + Assert.Equal(TransactionName, payloadSender.Payloads[0].Transactions[0].Name); + Assert.Equal(TransactionType, payloadSender.Payloads[0].Transactions[0].Type); + + //`await Task.Delay` is inaccurate, so we enable 10% error in the test + var expectedTransactionLength = SleepLength - (SleepLength * 0.1); + var duration = payloadSender.Payloads[0].Transactions[0].Duration; + Assert.True(duration >= expectedTransactionLength, $"Expected {duration} to be greater or equal to: {expectedTransactionLength}"); + + return payloadSender; + } + + /// + /// Asserts on 1 async transaction and 1 error + /// + private async Task AssertWith1TransactionAnd1ErrorAsync(Func func) + { + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender)); + + await func(agent); + + Assert.NotEmpty(payloadSender.Payloads); + Assert.NotEmpty(payloadSender.Payloads[0].Transactions); + + Assert.Equal(TransactionName, payloadSender.Payloads[0].Transactions[0].Name); + Assert.Equal(TransactionType, payloadSender.Payloads[0].Transactions[0].Type); + + //`await Task.Delay` is inaccurate, so we enable 10% error in the test + var expectedTransactionLength = SleepLength - (SleepLength * 0.1); + var duration = payloadSender.Payloads[0].Transactions[0].Duration; + Assert.True(duration >= expectedTransactionLength, $"Expected {duration} to be greater or equal to: {expectedTransactionLength}"); + + Assert.NotEmpty(payloadSender.Errors); + Assert.NotEmpty(payloadSender.Errors[0].Errors); + + Assert.Equal(typeof(InvalidOperationException).FullName, payloadSender.Errors[0].Errors[0].Exception.Type); + Assert.Equal(ExceptionMessage, payloadSender.Errors[0].Errors[0].Exception.Message); + return payloadSender; + } + + /// + /// Asserts on 1 transaction + /// + private MockPayloadSender AssertWith1Transaction(Action action) + { + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender)); + + action(agent); + + Assert.NotEmpty(payloadSender.Payloads); + Assert.NotEmpty(payloadSender.Payloads[0].Transactions); + + Assert.Equal(TransactionName, payloadSender.Payloads[0].Transactions[0].Name); + Assert.Equal(TransactionType, payloadSender.Payloads[0].Transactions[0].Type); + + //`await Task.Delay` is inaccurate, so we enable 10% error in the test + var expectedTransactionLength = SleepLength - (SleepLength * 0.1); + var duration = payloadSender.Payloads[0].Transactions[0].Duration; + Assert.True(duration >= expectedTransactionLength, $"Expected {duration} to be greater or equal to: {expectedTransactionLength}"); + + return payloadSender; + } + + /// + /// Asserts on 1 transaction and 1 error + /// + private void AssertWith1TransactionAnd1Error(Action action) + { + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender)); + + action(agent); + + Assert.NotEmpty(payloadSender.Payloads); + Assert.NotEmpty(payloadSender.Payloads[0].Transactions); + + Assert.Equal(TransactionName, payloadSender.Payloads[0].Transactions[0].Name); + Assert.Equal(TransactionType, payloadSender.Payloads[0].Transactions[0].Type); + + + //`await Task.Delay` is inaccurate, so we enable 10% error in the test + var expectedTransactionLength = SleepLength - (SleepLength * 0.1); + var duration = payloadSender.Payloads[0].Transactions[0].Duration; + Assert.True(duration >= expectedTransactionLength, $"Expected {duration} to be greater or equal to: {expectedTransactionLength}"); + + Assert.NotEmpty(payloadSender.Errors); + Assert.NotEmpty(payloadSender.Errors[0].Errors); + + Assert.Equal(typeof(InvalidOperationException).FullName, payloadSender.Errors[0].Errors[0].Exception.Type); + Assert.Equal(ExceptionMessage, payloadSender.Errors[0].Errors[0].Exception.Message); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource agent of type Elastic.Apm.ApmAgent, Leaked resource (output of Elastic.Apm.Tests.Mocks.TestAgentComponents::.ctor() at Line 555) of type Elastic.Apm.AgentComponents in method "Void ConvenientApiTransactionTests.AssertWith1TransactionAnd1Error(Action`1)". + +### Severity: +ERROR + +### Procedure: +Void ConvenientApiTransactionTests.AssertWith1TransactionAnd1Error(Action`1) + +### File: +test/Elastic.Apm.Tests/ApiTests/ConvenientApiTransactionTests.cs + +### Key: +ConvenientApiTransactionTests.cs|AssertWith1TransactionAnd1Error|DOTNET_RESOURCE_LEAK + +### Hash: +801ec49d4a6bf7108ce39e00432b095f + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0447/instruction.md b/inferredbugs-0447/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8a9bf41509174adcb3125ce14552103989bc816e --- /dev/null +++ b/inferredbugs-0447/instruction.md @@ -0,0 +1,430 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** apm-agent-dotnet +**Bug ID:** 72 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Linq; +using System.Threading; +using Elastic.Apm.Config; +using Elastic.Apm.Logging; +using Elastic.Apm.Tests.Mocks; +using FluentAssertions; +using Xunit; + +namespace Elastic.Apm.Tests +{ + /// + /// Tests the configuration through environment variables + /// + public class EnvVarConfigTest : IDisposable + { + [Fact] + public void ServerUrlsSimpleTest() + { + var serverUrl = "http://myServer.com:1234"; + var agent = new ApmAgent(new TestAgentComponents(serverUrls: serverUrl)); + agent.ConfigurationReader.ServerUrls[0].OriginalString.Should().Be(serverUrl); + var rootedUrl = serverUrl + "/"; + rootedUrl.Should().BeEquivalentTo(agent.ConfigurationReader.ServerUrls[0].AbsoluteUri); + } + + [Fact] + public void ServerUrlsInvalidUrlTest() + { + var serverUrl = "InvalidUrl"; + var agent = new ApmAgent(new TestAgentComponents(serverUrls: serverUrl)); + agent.ConfigurationReader.ServerUrls[0].Should().Be(ConfigConsts.DefaultServerUri); + } + + [Fact] + public void ServerUrlInvalidUrlLogTest() + { + var serverUrl = "InvalidUrl"; + var logger = new TestLogger(); + var agent = new ApmAgent(new TestAgentComponents(logger, serverUrl)); + agent.ConfigurationReader.ServerUrls[0].Should().Be(ConfigConsts.DefaultServerUri); + + logger.Lines.Should().NotBeEmpty(); + logger.Lines[0] + .Should() + .ContainAll( + $"{{{nameof(TestAgentConfigurationReader)}}}", + "Failed parsing server URL from", + TestAgentConfigurationReader.Origin, + ConfigConsts.EnvVarNames.ServerUrls, + serverUrl + ); + } + + /// + /// Sets 2 servers and makes sure that they are all parsed + /// + [Fact] + public void ServerUrlsMultipleUrlsTest() + { + var serverUrl1 = "http://myServer1.com:1234"; + var serverUrl2 = "http://myServer2.com:1234"; + var serverUrls = $"{serverUrl1},{serverUrl2}"; + + var logger = new TestLogger(); + var agent = new ApmAgent(new TestAgentComponents(logger, serverUrls)); + + var parsedUrls = agent.ConfigurationReader.ServerUrls; + parsedUrls[0].OriginalString.Should().Be(serverUrl1); + parsedUrls[0].AbsoluteUri.Should().BeEquivalentTo($"{serverUrl1}/"); + + parsedUrls[1].OriginalString.Should().Be(serverUrl2); + parsedUrls[1].AbsoluteUri.Should().BeEquivalentTo($"{serverUrl2}/"); + } + + /// + /// Sets 3 server urls, 2 of them are valid, 1 is invalid + /// Makes sure that the 2 valid urls are parsed and there is a log line for the invalid server url + /// + [Fact] + public void ServerUrlsMultipleUrlsWith1InvalidUrlTest() + { + var serverUrl1 = "http://myServer1.com:1234"; + var serverUrl2 = "invalidUrl"; + var serverUrl3 = "http://myServer2.com:1234"; + var serverUrls = $"{serverUrl1},{serverUrl2},{serverUrl3}"; + var logger = new TestLogger(); + var agent = new ApmAgent(new TestAgentComponents(logger, serverUrls)); + + var parsedUrls = agent.ConfigurationReader.ServerUrls; + parsedUrls.Should().NotBeEmpty().And.HaveCount(2, "seeded 3 but one was invalid"); + parsedUrls[0].OriginalString.Should().Be(serverUrl1); + parsedUrls[0].AbsoluteUri.Should().BeEquivalentTo($"{serverUrl1}/"); + + parsedUrls[1].OriginalString.Should().Be(serverUrl3); + parsedUrls[1].AbsoluteUri.Should().BeEquivalentTo($"{serverUrl3}/"); + + logger.Lines.Should().NotBeEmpty(); + logger.Lines[0] + .Should() + .ContainAll( + $"{{{nameof(TestAgentConfigurationReader)}}}", + "Failed parsing server URL from", + TestAgentConfigurationReader.Origin, + ConfigConsts.EnvVarNames.ServerUrls, + serverUrl2 + ); + } + + [Fact] + public void SecretTokenSimpleTest() + { + var secretToken = "secretToken"; + var agent = new ApmAgent(new TestAgentComponents(secretToken: secretToken)); + agent.ConfigurationReader.SecretToken.Should().Be(secretToken); + } + + [Fact] + public void DefaultCaptureHeadersTest() => Agent.Config.CaptureHeaders.Should().Be(true); + + [Fact] + public void SetCaptureHeadersTest() + { + Environment.SetEnvironmentVariable(ConfigConsts.EnvVarNames.CaptureHeaders, "false"); + var config = new EnvironmentConfigurationReader(); + config.CaptureHeaders.Should().Be(false); + } + + [Fact] + public void DefaultTransactionSampleRateTest() => + Agent.Config.TransactionSampleRate.Should().Be(ConfigConsts.DefaultValues.TransactionSampleRate); + + [Fact] + public void SetTransactionSampleRateTest() + { + Environment.SetEnvironmentVariable(ConfigConsts.EnvVarNames.TransactionSampleRate, "0.789"); + var config = new EnvironmentConfigurationReader(); + config.TransactionSampleRate.Should().Be(0.789); + } + + [Fact] + public void TransactionSampleRateExpectsDotForFloatingPoint() + { + Environment.SetEnvironmentVariable(ConfigConsts.EnvVarNames.TransactionSampleRate, "0,789"); + var config = new EnvironmentConfigurationReader(); + // Since comma was used instead of dot then default value will be used + config.TransactionSampleRate.Should().Be(ConfigConsts.DefaultValues.TransactionSampleRate); + } + + [Fact] + public void DefaultLogLevelTest() => Agent.Config.LogLevel.Should().Be(LogLevel.Error); + + [Fact] + public void SetDebugLogLevelTest() + { + var agent = new ApmAgent(new TestAgentComponents("Debug")); + agent.ConfigurationReader.LogLevel.Should().Be(LogLevel.Debug); + agent.Logger.Level.Should().Be(LogLevel.Debug); + } + + [Fact] + public void SetErrorLogLevelTest() + { + var agent = new ApmAgent(new TestAgentComponents("Error")); + agent.ConfigurationReader.LogLevel.Should().Be(LogLevel.Error); + agent.Logger.Level.Should().Be(LogLevel.Error); + } + + [Fact] + public void SetInfoLogLevelTest() + { + var agent = new ApmAgent(new TestAgentComponents("Information")); + agent.ConfigurationReader.LogLevel.Should().Be(LogLevel.Information); + agent.Logger.Level.Should().Be(LogLevel.Information); + } + + [Fact] + public void SetWarningLogLevelTest() + { + var agent = new ApmAgent(new TestAgentComponents("Warning")); + agent.ConfigurationReader.LogLevel.Should().Be(LogLevel.Warning); + agent.Logger.Level.Should().Be(LogLevel.Warning); + } + + [Fact] + public void SetInvalidLogLevelTest() + { + var logLevelValue = "InvalidLogLevel"; + var agent = new ApmAgent(new TestAgentComponents(logLevelValue)); + var logger = agent.Logger as TestLogger; + + agent.ConfigurationReader.LogLevel.Should().Be(LogLevel.Error); + logger.Lines.Should().NotBeEmpty(); + logger.Lines[0] + .Should() + .ContainAll( + $"{{{nameof(TestAgentConfigurationReader)}}}", + "Failed parsing log level from", + TestAgentConfigurationReader.Origin, + ConfigConsts.EnvVarNames.LogLevel, + "Defaulting to " + ); + } + + /// + /// The server doesn't accept services with '.' in it. + /// This test makes sure we don't have '.' in the default service name. + /// + [Fact] + public void DefaultServiceNameTest() + { + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new AgentComponents(payloadSender: payloadSender)); + agent.Tracer.CaptureTransaction("TestTransactionName", "TestTransactionType", t => { Thread.Sleep(2); }); + + //By default XUnit uses 'testhost' as the entry assembly, and that is what the + //agent reports if we don't set it to anything: + var serviceName = agent.Service.Name; + serviceName.Should().NotBeNullOrWhiteSpace(); + serviceName.Should().NotContain("."); + } + + /// + /// Sets the ELASTIC_APM_SERVICE_NAME environment variable and makes sure that + /// when the agent sends data to the server it has the value from the + /// ELASTIC_APM_SERVICE_NAME environment variable as service name. + /// + [Fact] + public void ReadServiceNameViaEnvironmentVariable() + { + var serviceName = "MyService123"; + Environment.SetEnvironmentVariable(ConfigConsts.EnvVarNames.ServiceName, serviceName); + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new AgentComponents(payloadSender: payloadSender)); + agent.Tracer.CaptureTransaction("TestTransactionName", "TestTransactionType", t => { Thread.Sleep(2); }); + + agent.Service.Name.Should().Be(serviceName); + } + + /// + /// Sets the ELASTIC_APM_SERVICE_NAME environment variable to a value that contains a '.' + /// Makes sure that when the agent sends data to the server it has the value from the + /// ELASTIC_APM_SERVICE_NAME environment variable as service name and also makes sure that + /// the '.' is replaced. + /// + [Fact] + public void ReadServiceNameWithDotViaEnvironmentVariable() + { + var serviceName = "My.Service.Test"; + Environment.SetEnvironmentVariable(ConfigConsts.EnvVarNames.ServiceName, serviceName); + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new AgentComponents(payloadSender: payloadSender)); + agent.Tracer.CaptureTransaction("TestTransactionName", "TestTransactionType", t => { Thread.Sleep(2); }); + + + agent.Service.Name.Should().Be(serviceName.Replace('.', '_')); + agent.Service.Name.Should().NotContain("."); + } + + /// + /// In case the user does not provide us a service name we try to calculate it based on the callstack. + /// This test makes sure we recognize mscorlib and our own assemblies correctly in the + /// method. + /// + [Fact] + public void TestAbstractConfigurationReaderIsMsOrElastic() + { + var elasticToken = new byte[] { 174, 116, 0, 210, 193, 137, 207, 34 }; + var mscorlibToken = new byte[] { 183, 122, 92, 86, 25, 52, 224, 137 }; + + AbstractConfigurationReader.IsMsOrElastic(elasticToken).Should().BeTrue(); + + AbstractConfigurationReader.IsMsOrElastic(new byte[] { 0 }).Should().BeFalse(); + AbstractConfigurationReader.IsMsOrElastic(new byte[] { }).Should().BeFalse(); + + AbstractConfigurationReader + .IsMsOrElastic(new[] + { + elasticToken[0], mscorlibToken[1], elasticToken[2], + mscorlibToken[3], elasticToken[4], mscorlibToken[5], elasticToken[6], mscorlibToken[7] + }) + .Should() + .BeFalse(); + } + + /// + /// Makes sure that the logs + /// in case it reads an invalid URL. + /// + [Fact] + public void LoggerNotNull() + { + Environment.SetEnvironmentVariable(ConfigConsts.EnvVarNames.ServerUrls, "localhost"); //invalid, it should be "http://localhost" + var testLogger = new TestLogger(); + var config = new EnvironmentConfigurationReader(testLogger); + var serverUrl = config.ServerUrls.FirstOrDefault(); + + serverUrl.Should().NotBeNull(); + testLogger.Lines.Should().NotBeEmpty(); + } + + [Fact] + public void SetMetricsIntervalTo10S() + => MetricsInterValTestCommon("10s").Should().Be(10 * 1000); + + /// + /// Sets the metrics interval to '500ms' + /// Makes sure that 500ms defaults to 0, since the minimum is 1s + /// + [Fact] + public void SetMetricsInterValTo500Ms() + => MetricsInterValTestCommon("500ms").Should().Be(0); + + [Fact] + public void SetMetricsInterValTo1500Ms() + => MetricsInterValTestCommon("1500ms").Should().Be(1500); + + [Fact] + public void SetMetricsInterValTo1HourAs60minutes() + => MetricsInterValTestCommon("60m").Should().Be(60*60*1000); + + [Fact] + public void SetMetricsInterValTo1HourUsingUnsupportedUnits() + => MetricsInterValTestCommon("1h").Should().Be(ConfigConsts.DefaultValues.MetricsIntervalInMilliseconds); + + [Fact] + public void SetMetricsInterValTo1M() + => MetricsInterValTestCommon("1m").Should().Be(60 * 1000); + + /// + /// Sets the metrics interval to '10'. + /// Makes sure that '10' defaults to '10s' + /// + [Fact] + public void SetMetricsInterValTo10() + => MetricsInterValTestCommon("10").Should().Be(10 * 1000); + + /// + /// Any negative value should be treated as 0 + /// + [Fact] + public void SetMetricsInterValToNegative5() + => MetricsInterValTestCommon("-1").Should().Be(0); + + [Fact] + public void SetMetricsInterValToNegative5S() + => MetricsInterValTestCommon("-0.3s").Should().Be(0); + + [Fact] + public void SetMetricsInterValToNegative5M() + => MetricsInterValTestCommon("-5m").Should().Be(0); + + [Fact] + public void SetMetricsInterValToNegative5Ms() + => MetricsInterValTestCommon("-5ms").Should().Be(0); + + private static double MetricsInterValTestCommon(string configValue) + { + Environment.SetEnvironmentVariable(ConfigConsts.EnvVarNames.MetricsInterval, configValue); + var testLogger = new TestLogger(); + var config = new EnvironmentConfigurationReader(testLogger); + return config.MetricsIntervalInMillisecond; + } + + public void Dispose() + { + Environment.SetEnvironmentVariable(ConfigConsts.EnvVarNames.ServerUrls, null); + Environment.SetEnvironmentVariable(ConfigConsts.EnvVarNames.MetricsInterval, null); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource agent of type Elastic.Apm.ApmAgent, Leaked resource (output of Elastic.Apm.Tests.Mocks.TestAgentComponents::.ctor() at Line 40) of type Elastic.Apm.AgentComponents in method "Void EnvVarConfigTest.ServerUrlInvalidUrlLogTest()". + +### Severity: +ERROR + +### Procedure: +Void EnvVarConfigTest.ServerUrlInvalidUrlLogTest() + +### File: +test/Elastic.Apm.Tests/ConfigTest.cs + +### Key: +ConfigTest.cs|ServerUrlInvalidUrlLogTest|DOTNET_RESOURCE_LEAK + +### Hash: +f098404337617fd6f485df310805b8b2 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0478/instruction.md b/inferredbugs-0478/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3a6d19849bca05622d62a96e4e17f74ced42f926 --- /dev/null +++ b/inferredbugs-0478/instruction.md @@ -0,0 +1,141 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** apm-agent-dotnet +**Bug ID:** 23 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Text; +using Elastic.Apm.Model.Payload; +using Elastic.Apm.Report.Serialization; +using Elastic.Apm.Tests.Mocks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace Elastic.Apm.Tests +{ + /// + /// Contains tests related to json serialization. + /// + public class SerializationTests + { + /// + /// Tests the . It serializes a transaction with Transaction.Name.Length > 1024 + /// And makes sure that the Transaction.Name is truncated correctly. + /// + [Fact] + public void StringTruncationTest() + { + var sb = new StringBuilder(); + + for (var i = 0; i < 1200; i++) + { + sb.Append('a'); + } + + var transaction = new Transaction(new TestAgentComponents(), sb.ToString(), "test") { Duration = 1, Result = "fail" }; + + var settings = new JsonSerializerSettings { ContractResolver = new StringTruncationValueResolver() }; + var json = JsonConvert.SerializeObject(transaction, settings); + var deserializedTransaction = JsonConvert.DeserializeObject(json) as JObject; + + Assert.NotNull(deserializedTransaction); + + Assert.Equal(Consts.PropertyMaxLength, deserializedTransaction["name"]?.Value()?.Length); + Assert.Equal("...", deserializedTransaction["name"].Value().Substring(1021, 3)); + Assert.Equal("test", deserializedTransaction["type"].Value()); + Assert.Equal("fail", deserializedTransaction["result"].Value()); + } + + /// + /// Test . + /// It creates an instance of with a that has a string + /// which is longer than . + /// Makes sure that the serialized instance still contains the whole string (aka it was not trimmed), since + /// the property pointing to the string was marked with . + /// + [Fact] + public void NoTruncateAttributeTest() + { + var sb = new StringBuilder(); + + for (var i = 0; i < 1200; i++) + { + sb.Append('a'); + } + + var dummyInstance = new DummyType { IntProp = 42, StringProp = sb.ToString() }; + + var settings = new JsonSerializerSettings { ContractResolver = new StringTruncationValueResolver() }; + var json = JsonConvert.SerializeObject(dummyInstance, settings); + var deserializedDummyInstance = JsonConvert.DeserializeObject(json); + + Assert.NotNull(deserializedDummyInstance); + + Assert.Equal(sb.Length, deserializedDummyInstance.StringProp.Length); + Assert.Equal(sb.ToString(), deserializedDummyInstance.StringProp); + Assert.Equal(42, deserializedDummyInstance.IntProp); + } + + private class DummyType + { + [NoTruncationInJsonNet] + public string StringProp { get; set; } + + public int IntProp { get; set; } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Elastic.Apm.Tests.Mocks.TestAgentComponents::.ctor() at Line 30) of type Elastic.Apm.AgentComponents in method "Void SerializationTests.StringTruncationTest()". + +### Severity: +ERROR + +### Procedure: +Void SerializationTests.StringTruncationTest() + +### File: +test/Elastic.Apm.Tests/SerializationTests.cs + +### Key: +SerializationTests.cs|StringTruncationTest|DOTNET_RESOURCE_LEAK + +### Hash: +a73134bb83a168e73665407c757efa63 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0502/instruction.md b/inferredbugs-0502/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2a65beebce1f0f06d8f527cb2c7cc9a88f6d4824 --- /dev/null +++ b/inferredbugs-0502/instruction.md @@ -0,0 +1,956 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** R2API +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Mono.Cecil.Cil; +using MonoMod.Utils; + +namespace R2API.Utils { + public static class Reflection { + + private const BindingFlags AllFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | + BindingFlags.Instance | BindingFlags.DeclaredOnly; + + private delegate T GetDelegate(object instance); + + private delegate void SetDelegate(object instance, T value); + + //private delegate object CallDelegate(object instance, object[] arguments); + + private delegate void SetDelegateRef(ref TInstance instance, TValue value) where TInstance : struct; + + private delegate T GetDelegateRef(ref TInstance instance) where TInstance : struct; + + #region Caches + + // Field + private static readonly ConcurrentDictionary<(Type T, string name), FieldInfo> FieldCache = + new ConcurrentDictionary<(Type T, string name), FieldInfo>(); + + private static readonly ConcurrentDictionary FieldGetDelegateCache = + new ConcurrentDictionary(); + + private static readonly ConcurrentDictionary FieldSetDelegateCache = + new ConcurrentDictionary(); + + + // Property + private static readonly ConcurrentDictionary<(Type T, string name), PropertyInfo> PropertyCache = + new ConcurrentDictionary<(Type T, string name), PropertyInfo>(); + + private static readonly ConcurrentDictionary PropertyGetDelegateCache = + new ConcurrentDictionary(); + + private static readonly ConcurrentDictionary PropertySetDelegateCache = + new ConcurrentDictionary(); + + + // Method + private static readonly ConcurrentDictionary<(Type T, string name), MethodInfo> MethodCache = + new ConcurrentDictionary<(Type T, string name), MethodInfo>(); + + private static readonly ConcurrentDictionary<(Type T, string name, Type[] argumentTypes), MethodInfo> + OverloadedMethodCache = + new ConcurrentDictionary<(Type T, string name, Type[] argumentTypes), MethodInfo>(); + + private static readonly ConcurrentDictionary DelegateCache = + new ConcurrentDictionary(); + + + // Class + private static readonly ConcurrentDictionary<(Type T, Type[] argumentTypes), ConstructorInfo> ConstructorCache = + new ConcurrentDictionary<(Type T, Type[] argumentTypes), ConstructorInfo>(); + + private static readonly ConcurrentDictionary<(Type T, string name), Type> NestedTypeCache = + new ConcurrentDictionary<(Type T, string name), Type>(); + + + // Helper methods + private static TValue GetOrAddOnNull(this ConcurrentDictionary dict, TKey key, + Func factory) { + if (dict.TryGetValue(key, out var val) && val != null) + return val; + + return dict[key] = factory(key); + } + + #endregion + + #region Field + + /// + /// Gets the of the type by name and caches it + /// + /// The type to search + /// The name of the field to find + /// + public static FieldInfo GetFieldCached(string name) => + typeof(T).GetFieldCached(name); + + /// + /// Gets the of the type by name and caches it + /// + /// The type to search + /// The name of the field to find + /// + public static FieldInfo GetFieldCached(this Type T, string name) => + FieldCache.GetOrAddOnNull((T, name), x => x.T.GetFieldFull(x.name) + ?? throw new Exception($"Could not find {nameof(FieldInfo)} on {T.FullName} with the name {name}")); + + + /// + /// Gets the value of the field on the object + /// + /// The type of the return value + /// The name of the field to get the value of + /// The object to get the field's value from + /// + public static TReturn GetFieldValue(this object instance, string fieldName) => + instance.GetType() + .GetFieldCached(fieldName) + .GetFieldGetDelegate() + (instance); + + /// + /// Gets the value of the specified static field on the specified static type + /// + /// The return type + /// The name of the static field to get the value of + /// The type to get the specified static field's value on + /// + public static TReturn GetFieldValue(this Type staticType, string fieldName) => + staticType + .GetFieldCached(fieldName) + .GetFieldGetDelegate() + (null); + + /// + /// Sets the value of the specified field on the specified object; if the object is a struct use + /// instead + /// + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified field's value on + /// The value to set + /// + public static void SetFieldValue(this object instance, string fieldName, TValue value) => + instance.GetType() + .GetFieldCached(fieldName) + .GetFieldSetDelegate() + (instance, value); + + /// + /// Sets the value of the specified static field on the specified static type + /// + /// The type of the value to set + /// The name of the static field to set the value of + /// The type to set the specified static field's value on + /// The value to set + /// + public static void SetFieldValue(this Type staticType, string fieldName, TValue value) => + staticType + .GetFieldCached(fieldName) + .GetFieldSetDelegate() + (null, value); + + /// + /// Sets the value of the specified field on the specified struct + /// + /// The type of the instance of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified field's value on + /// The value to set the field to + /// + public static void SetStructFieldValue(this ref TInstance instance, string fieldName, TValue value) + where TInstance : struct => + typeof(TInstance) + .GetFieldCached(fieldName) + .GetFieldSetDelegateRef() + (ref instance, value); + + + /// + /// Gets the on the specified and searches base types if not found. + /// + /// The to search and get base types from + /// The name of the property to search for. + /// + private static FieldInfo GetFieldFull(this Type T, string name) { + while (T != null) { + var fieldInfo = T.GetField(name, AllFlags); + if (fieldInfo != null) { + return fieldInfo; + } + + T = T.BaseType; + } + + return null; + } + + private static T GetMemberFull(this Type type, string name) where T : MemberInfo { + while (type != null) { + var fieldInfo = type.GetMember(name, AllFlags); + if (fieldInfo != null) { + return (T)fieldInfo.First(); + } + + type = type.BaseType; + } + + return null; + } + + private static GetDelegate GetFieldGetDelegate(this FieldInfo field) => + FieldGetDelegateCache.GetOrAdd(field, x => x.CreateGetDelegate()) + .CastDelegate>(); + + private static SetDelegate GetFieldSetDelegate(this FieldInfo field) => + FieldSetDelegateCache.GetOrAdd(field, x => x.CreateSetDelegate()) + .CastDelegate>(); + + private static SetDelegateRef GetFieldSetDelegateRef(this FieldInfo field) where TInstance : struct => + FieldSetDelegateCache.GetOrAdd(field, x => x.CreateSetDelegateRef()) + .CastDelegate>(); + + #endregion + + #region Property + + /// + /// Gets the of the type by name + /// + /// The type on which to find the property + /// The name of the property to get + /// + public static PropertyInfo GetPropertyCached(string name) => + typeof(T).GetPropertyCached(name); + + /// + /// Gets the of the type by name + /// + /// The type to get the from + /// The name of the property to get + /// + public static PropertyInfo GetPropertyCached(this Type T, string name) => + PropertyCache.GetOrAddOnNull((T, name), x => x.T.GetProperty(x.name, AllFlags)); + + /// + /// Gets the value of the property on the specified object; if the object is a struct use + /// instead + /// + /// The type of the return value + /// The object to get the property's value from + /// The name of the field to get the value of + /// + public static TReturn GetPropertyValue(this object instance, string propName) => + instance.GetType() + .GetPropertyCached(propName) + .GetPropertyGetDelegate() + (instance); + + /// + /// Gets the value of the static property on the specified static type + /// + /// The return type + /// The name of the static field to get the value of + /// The type to get the specified static property's value on + /// + public static TReturn GetPropertyValue(this Type staticType, string propName) => + staticType + .GetPropertyCached(propName) + .GetPropertyGetDelegate() + (null); + + /// + /// Sets the value of the property on the specified class; if you're setting the property on a + /// struct use instead + /// + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// The value to set + /// + public static void SetPropertyValue(this object instance, string propName, TValue value) => + instance.GetType() + .GetPropertyCached(propName)? + .GetPropertySetDelegate() + (instance, value); + + /// + /// Sets the value of the static property on the specified static class + /// + /// The type of the value to set + /// The name of the static field to set the value of + /// The type to set the specified static property's value on + /// The value to set the property to + /// + public static void SetPropertyValue(this Type staticType, string propName, TValue value) => + staticType.GetPropertyCached(propName)? + .GetPropertySetDelegate() + (null, value); + + /// + /// Sets the value of the specified property on the specified struct + /// + /// The type of the instance of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// The value to set the property to + /// + public static void SetStructPropertyValue(this ref TInstance instance, string propName, + TValue value) + where TInstance : struct => + typeof(TInstance) + .GetPropertyCached(propName) + .GetPropertySetDelegateRef() + (ref instance, value); + + /// + /// Gets the value of the specified property on the specified struct + /// + /// The type of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// + public static TValue GetStructPropertyValue(this ref TInstance instance, string propName) + where TInstance : struct => + typeof(TInstance) + .GetPropertyCached(propName) + .GetPropertyGetDelegateRef() + (ref instance); + + private static GetDelegate GetPropertyGetDelegate(this PropertyInfo property) => + PropertyGetDelegateCache.GetOrAdd(property, prop => prop.CreateGetDelegate()) + .CastDelegate>(); + + private static GetDelegateRef GetPropertyGetDelegateRef(this PropertyInfo property) + where TInstance : struct => + PropertyGetDelegateCache.GetOrAdd(property, prop => prop.CreateGetDelegate()) + .CastDelegate>(); + + private static SetDelegate GetPropertySetDelegate(this PropertyInfo property) => + PropertySetDelegateCache.GetOrAdd(property, prop => prop.CreateSetDelegate()) + .CastDelegate>(); + + private static SetDelegateRef GetPropertySetDelegateRef( + this PropertyInfo property) + where TInstance : struct => + PropertySetDelegateCache.GetOrAdd(property, prop => prop.CreateSetDelegateRef()) + .CastDelegate>(); + + #endregion + + #region Method + + /// + /// Gets the method on the specified type and caches it + /// + /// The type to search + /// The name of the method to find + /// + public static MethodInfo GetMethodCached(string name) => + typeof(T).GetMethodCached(name); + + /// + /// Gets the method on the specified static type and caches it + /// + /// The type to search + /// The name of the method to find + /// + public static MethodInfo GetMethodCached(this Type T, string name) => + MethodCache.GetOrAddOnNull((T, name), x => x.T.GetMethod(x.name, AllFlags) + ?? throw new Exception($"Could not find {nameof(MethodInfo)} on {T.FullName} with the name {name}")); + + /// + /// Gets the method on the specified type and caches it. This overload is used when the method is ambiguous + /// + /// The type to search + /// The name of the method to find + /// The types of the argument + /// + public static MethodInfo GetMethodCached(string name, Type[] argumentTypes) => + typeof(T).GetMethodCached(name, argumentTypes); + + /// + /// Gets the method on the specified static type and caches it. This overload is used when the method is ambiguous + /// + /// The type to search + /// The name of the method to find + /// The types of the argument + public static MethodInfo GetMethodCached(this Type T, string name, Type[] argumentTypes) => + OverloadedMethodCache.GetOrAddOnNull((T, name, argumentTypes), + x => x.T.GetMethod(x.name, AllFlags, null, x.argumentTypes, null) + ?? throw new Exception($"Could not find {nameof(MethodInfo)} on {T.FullName} with the name {name} and arguments: " + + $"{string.Join(",", argumentTypes.Select(a => a.FullName))}")); + + /// + /// Invoke a method on the specified object by name + /// + /// The return type of the method + /// The object to invoke the method on + /// The name of the method to invoke + /// + public static TReturn InvokeMethod(this object instance, string methodName) => + instance.InvokeMethod(methodName, null); + + /// + /// Invoke a static method on the specified type by name + /// + /// The return type of the method + /// The static type to search + /// The name of the method to invoke + /// + public static TReturn InvokeMethod(this Type staticType, string methodName) => + staticType.InvokeMethod(methodName, null); + + /// + /// Invoke a method on the specified object by name + /// + /// The object to invoke the method on + /// The name of the method to invoke + public static void InvokeMethod(this object instance, string methodName) => + instance.InvokeMethod(methodName); + + /// + /// Invoke a static method on the specified type by name + /// + /// The static type to search + /// The name of the method to invoke + public static void InvokeMethod(this Type staticType, string methodName) => + staticType.InvokeMethod(methodName); + + /// + /// Invoke a method on the specified object by name with parameters + /// + /// The return type of the method + /// The object to invoke the method on + /// The name of the method to invoke + /// + /// + public static TReturn InvokeMethod(this object instance, string methodName, + params object[] methodParams) { + var methodInfo = (methodParams == null + ? instance.GetType() + .GetMethodCached(methodName) + : instance.GetType() + .GetMethodCached(methodName, methodParams.Select(x => x.GetType()).ToArray()) + ) ?? throw new Exception($"Could not find method on type {instance.GetType()} with the name of {methodName} with the arguments specified."); + + return (TReturn)methodInfo.GetMethodDelegateCached()(instance, methodParams); + } + + /// + /// Invoke a static method on the specified type by name with parameters + /// + /// The return type of the method + /// The static type to search + /// The name of the method to invoke + /// The method parameters + /// + public static TReturn InvokeMethod(this Type staticType, string methodName, + params object[] methodParams) { + var methodInfo = (methodParams == null + ? staticType + .GetMethodCached(methodName) + : staticType + .GetMethodCached(methodName, methodParams.Select(x => x.GetType()).ToArray())) + ?? throw new Exception($"Could not find method on type {staticType} with the name of {methodName} with the arguments specified."); + + return (TReturn)methodInfo.GetMethodDelegateCached()(null, methodParams); + } + + /// + /// Invoke a method on the specified object by name with parameters + /// + /// The object to invoke the method on + /// The name of the method to invoke + /// + public static void InvokeMethod(this object instance, string methodName, params object[] methodParams) => + instance.InvokeMethod(methodName, methodParams); + + /// + /// Invoke a static method on the specified type by name with parameters + /// + /// The static type to search + /// The name of the method to invoke + /// + public static void InvokeMethod(this Type staticType, string methodName, params object[] methodParams) => + staticType.InvokeMethod(methodName, methodParams); + + + private static FastReflectionDelegate GetMethodDelegateCached(this MethodInfo methodInfo) => + DelegateCache.GetOrAdd(methodInfo, method => method.CreateFastDelegate()); + + #endregion + + #region Class + + /// + /// Gets the constructor on the specified type with specified arguments and caches it + /// + /// The type to search + /// The types of the arguments on the constructor to find + /// + public static ConstructorInfo GetConstructorCached(Type[] argumentTypes) => + GetConstructorCached(typeof(T), argumentTypes); + + /// + /// Gets the constructor on the specified static type with specified arguments and caches it + /// + /// The type to search + /// The types of the arguments on the constructor to find + /// + public static ConstructorInfo GetConstructorCached(this Type T, Type[] argumentTypes) => + ConstructorCache.GetOrAddOnNull((T, argumentTypes), x => x.T.GetConstructor(x.argumentTypes) + ?? throw new Exception($"Could not find {nameof(ConstructorInfo)} on {T.FullName} with the arguments {string.Join(",", argumentTypes.Select(a => a.FullName))}")); + + /// + /// Gets the nested type on the specified type + /// + /// The type to search + /// The name of the nested type to find + /// + public static Type GetNestedType(string name) => + typeof(T).GetNestedTypeCached(name); + + /// + /// Gets the nested type on the specified type + /// + /// The type to search + /// The name of the nested type to find + /// + public static Type GetNestedTypeCached(string name) => + typeof(T).GetNestedTypeCached(name); + + /// + /// Gets the nested type on the specified static type + /// + /// The static type to search + /// The name of the nested type to find + /// + public static Type GetNestedTypeCached(this Type T, string name) => + NestedTypeCache.GetOrAddOnNull((T, name), x => x.T.GetNestedType(x.name, AllFlags) + ?? throw new Exception($"Could not find nested {nameof(Type)} on {T.FullName} with the name {name}")); + + /// + /// Instatiates the specified type + /// + /// The type to instantiate + /// + public static object Instantiate(this Type type) => + Activator.CreateInstance(type, true); + + /// + /// Instatiates the specified type with specified constructor arguments + /// + /// The type to instantiate + /// The constructor arguments + /// + public static object Instantiate(this Type type, params object[] constructorArguments) => + type.GetConstructorCached(constructorArguments.Select(x => x.GetType()).ToArray()) + .Invoke(constructorArguments); + + /// + /// Instantiates the specified generic type + /// + /// The type to instantiate + /// The type of the generic type argument + /// + public static object InstantiateGeneric(this Type typeArgument) => + typeof(TClass).MakeGenericType(typeArgument).Instantiate(); + + /// + /// Instantiates the specified generic types + /// + /// The type to instantiate + /// The types of the generic type arguments + /// + public static object InstantiateGeneric(this Type[] typeArgument) => + typeof(TClass).MakeGenericType(typeArgument).Instantiate(); + + /// + /// Instantiates a list of the specified generic type + /// + /// + /// + public static IList InstantiateList(this Type type) => + (IList)typeof(List<>).MakeGenericType(type).Instantiate(); + + #endregion + + #region Fast Reflection + + private static GetDelegate CreateGetDelegate(this FieldInfo field) { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (!typeof(TReturn).IsAssignableFrom(field.FieldType)) { + throw new Exception($"Field type {field.FieldType} does not match the requested type {typeof(TReturn)}."); + } + + + var method = new DynamicMethodDefinition($"{field} Getter", typeof(TReturn), new[] { typeof(object) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + if (field.DeclaringType.GetTypeInfo().IsValueType) { + il.Emit(OpCodes.Unbox_Any, field.DeclaringType); + } + } + + il.Emit(!field.IsStatic ? OpCodes.Ldfld : OpCodes.Ldsfld, field); + il.Emit(OpCodes.Ret); + + return (GetDelegate)method.Generate().CreateDelegate(typeof(GetDelegate)); + } + + private static SetDelegate CreateSetDelegate(this FieldInfo field) { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (!field.FieldType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {field.FieldType}."); + } + + var method = new DynamicMethodDefinition($"{field} Setter", typeof(void), + new[] { typeof(object), typeof(TValue) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(!field.IsStatic ? OpCodes.Stfld : OpCodes.Stsfld, field); + + il.Emit(OpCodes.Ret); + + return (SetDelegate)method.Generate().CreateDelegate(typeof(SetDelegate)); + } + + private static SetDelegateRef CreateSetDelegateRef(this FieldInfo field) where TInstance : struct { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (field.FieldType != typeof(TValue)) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {field.FieldType}."); + } + + var method = new DynamicMethodDefinition($"{field} SetterByRef", typeof(void), + new[] { typeof(TInstance).MakeByRefType(), typeof(TValue) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(!field.IsStatic ? OpCodes.Stfld : OpCodes.Stsfld, field); + il.Emit(OpCodes.Ret); + + return (SetDelegateRef)method.Generate().CreateDelegate(typeof(SetDelegateRef)); + } + + private static GetDelegate CreateGetDelegate(this PropertyInfo property) { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!typeof(TReturn).IsAssignableFrom(property.PropertyType)) { + throw new Exception($"Field type {property.PropertyType} does not match the requested type {typeof(TReturn)}."); + } + + var method = new DynamicMethodDefinition($"{property} Getter", typeof(TReturn), new[] { typeof(object) }); + var il = method.GetILProcessor(); + + var getMethod = property.GetGetMethod(nonPublic: true); + + if (!getMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Call, getMethod); + il.Emit(OpCodes.Ret); + + return (GetDelegate)method.Generate().CreateDelegate(typeof(GetDelegate)); + } + + private static GetDelegateRef CreateGetDelegate(this PropertyInfo property) where TInstance : struct { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!typeof(TReturn).IsAssignableFrom(property.PropertyType)) { + throw new Exception($"Field type {property.PropertyType} does not match the requested type {typeof(TReturn)}."); + } + + var method = new DynamicMethodDefinition($"{property} Getter", typeof(TReturn), new[] { typeof(TInstance).MakeByRefType() }); + var il = method.GetILProcessor(); + + // Cache this as well? + var getMethod = property.GetGetMethod(nonPublic: true); + + if (!getMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Call, getMethod); + il.Emit(OpCodes.Ret); + + return (GetDelegateRef)method.Generate().CreateDelegate(typeof(GetDelegateRef)); + } + + + private static SetDelegate CreateSetDelegate(this PropertyInfo property) { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!property.PropertyType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {property.PropertyType}."); + } + + var method = new DynamicMethodDefinition($"{property} Setter", typeof(void), + new[] { typeof(object), typeof(TValue) }); + var il = method.GetILProcessor(); + + var setMethod = property.GetSetMethod(true); + + if (!setMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Call, setMethod); + il.Emit(OpCodes.Ret); + + return (SetDelegate)method.Generate().CreateDelegate(typeof(SetDelegate)); + } + + private static SetDelegateRef CreateSetDelegateRef(this PropertyInfo property) where TInstance : struct { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!property.PropertyType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {property.PropertyType}."); + } + + var method = new DynamicMethodDefinition($"{property} SetterByRef", typeof(void), + new[] { typeof(TInstance).MakeByRefType(), typeof(TValue) }); + var il = method.GetILProcessor(); + + var setMethod = property.GetSetMethod(true); + + if (!setMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Call, setMethod); + il.Emit(OpCodes.Ret); + + return (SetDelegateRef)method.Generate().CreateDelegate(typeof(SetDelegateRef)); + } + + // Partial hack from https://github.com/0x0ade/MonoMod/blob/master/MonoMod.Utils/FastReflectionHelper.cs + // to get fast call delegates + //private static CallDelegate GenerateCallDelegate(this MethodInfo method) { + // if (method == null) { + // throw new ArgumentException("Method cannot be null.", nameof(method)); + // } + + // var dmd = new DynamicMethodDefinition( + // $"CallDelegate<{method.Name}>", typeof(object), new[] { typeof(object), typeof(object[]) }); + // var il = dmd.GetILProcessor(); + + // var args = method.GetParameters(); + + // if (!method.IsStatic) { + // il.Emit(OpCodes.Ldarg_0); + // if (method.DeclaringType.GetTypeInfo().IsValueType) { + // il.Emit(OpCodes.Unbox_Any, method.DeclaringType); + // } + // } + + // for (var i = 0; i < args.Length; i++) { + // var argType = args[i].ParameterType; + // var argIsByRef = argType.IsByRef; + // if (argIsByRef) + // argType = argType.GetElementType(); + // var argIsValueType = argType.GetTypeInfo().IsValueType; + + // if (argIsByRef && argIsValueType) { + // // Used later when storing back the reference to the new box in the array. + // il.Emit(OpCodes.Ldarg_1); + // il.EmitFast_Ldc_I4(i); + // } + + // il.Emit(OpCodes.Ldarg_1); + // il.EmitFast_Ldc_I4(i); + + // if (argIsByRef && !argIsValueType) { + // il.Emit(OpCodes.Ldelema, typeof(object)); + // } + // else { + // il.Emit(OpCodes.Ldelem_Ref); + // if (!argIsValueType) continue; + // il.Emit(!argIsByRef ? OpCodes.Unbox_Any : OpCodes.Unbox, argType); + // } + // } + + // if (method.IsFinal || !method.IsVirtual) { + // il.Emit(OpCodes.Call, method); + // } + // else { + // il.Emit(OpCodes.Callvirt, method); + // } + + // var returnType = method.IsConstructor ? method.DeclaringType : method.ReturnType; + // if (returnType != typeof(void)) { + // if (returnType.GetTypeInfo().IsValueType) { + // il.Emit(OpCodes.Box, returnType); + // } + // } + // else { + // il.Emit(OpCodes.Ldnull); + // } + + // il.Emit(OpCodes.Ret); + + // return (CallDelegate) dmd.Generate().CreateDelegate(typeof(CallDelegate)); + //} + + // https://github.com/0x0ade/MonoMod/blob/master/MonoMod.Utils/FastReflectionHelper.cs + public static void EmitFast_Ldc_I4(this ILProcessor il, int value) { + switch (value) { + case -1: + il.Emit(OpCodes.Ldc_I4_M1); + return; + case 0: + il.Emit(OpCodes.Ldc_I4_0); + return; + case 1: + il.Emit(OpCodes.Ldc_I4_1); + return; + case 2: + il.Emit(OpCodes.Ldc_I4_2); + return; + case 3: + il.Emit(OpCodes.Ldc_I4_3); + return; + case 4: + il.Emit(OpCodes.Ldc_I4_4); + return; + case 5: + il.Emit(OpCodes.Ldc_I4_5); + return; + case 6: + il.Emit(OpCodes.Ldc_I4_6); + return; + case 7: + il.Emit(OpCodes.Ldc_I4_7); + return; + case 8: + il.Emit(OpCodes.Ldc_I4_8); + return; + } + + if (value > -129 && value < 128) + il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); + else + il.Emit(OpCodes.Ldc_I4, value); + } + + public static byte ReadLocalIndex(OpCode opCode, object operand) { + if (opCode == OpCodes.Ldloc_0 || opCode == OpCodes.Stloc_0) { + return 0; + } + if (opCode == OpCodes.Ldloc_1 || opCode == OpCodes.Stloc_1) { + return 1; + } + if (opCode == OpCodes.Ldloc_2 || opCode == OpCodes.Stloc_2) { + return 2; + } + if (opCode == OpCodes.Ldloc_3 || opCode == OpCodes.Stloc_3) { + return 3; + } + if (opCode == OpCodes.Ldloc_S || opCode == OpCodes.Stloc_S) { + return (byte)operand; + } + + throw new Exception($"Could not read index for opcode and operand: {opCode} - {operand}"); + } + + #endregion + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource method of type MonoMod.Utils.DynamicMethodDefinition in method "Reflection$SetDelegate`1 Reflection.CreateSetDelegate(FieldInfo)". + +### Severity: +ERROR + +### Procedure: +Reflection$SetDelegate`1 Reflection.CreateSetDelegate(FieldInfo) + +### File: +R2API/Utils/Reflection.cs + +### Key: +Reflection.cs|CreateSetDelegate|DOTNET_RESOURCE_LEAK + +### Hash: +d76a985c5e6960c1e71552cad3ba809d + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0503/instruction.md b/inferredbugs-0503/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43281d2f672a2aa724803d178ff1a3fa14f9e606 --- /dev/null +++ b/inferredbugs-0503/instruction.md @@ -0,0 +1,956 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** R2API +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Mono.Cecil.Cil; +using MonoMod.Utils; + +namespace R2API.Utils { + public static class Reflection { + + private const BindingFlags AllFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | + BindingFlags.Instance | BindingFlags.DeclaredOnly; + + private delegate T GetDelegate(object instance); + + private delegate void SetDelegate(object instance, T value); + + //private delegate object CallDelegate(object instance, object[] arguments); + + private delegate void SetDelegateRef(ref TInstance instance, TValue value) where TInstance : struct; + + private delegate T GetDelegateRef(ref TInstance instance) where TInstance : struct; + + #region Caches + + // Field + private static readonly ConcurrentDictionary<(Type T, string name), FieldInfo> FieldCache = + new ConcurrentDictionary<(Type T, string name), FieldInfo>(); + + private static readonly ConcurrentDictionary FieldGetDelegateCache = + new ConcurrentDictionary(); + + private static readonly ConcurrentDictionary FieldSetDelegateCache = + new ConcurrentDictionary(); + + + // Property + private static readonly ConcurrentDictionary<(Type T, string name), PropertyInfo> PropertyCache = + new ConcurrentDictionary<(Type T, string name), PropertyInfo>(); + + private static readonly ConcurrentDictionary PropertyGetDelegateCache = + new ConcurrentDictionary(); + + private static readonly ConcurrentDictionary PropertySetDelegateCache = + new ConcurrentDictionary(); + + + // Method + private static readonly ConcurrentDictionary<(Type T, string name), MethodInfo> MethodCache = + new ConcurrentDictionary<(Type T, string name), MethodInfo>(); + + private static readonly ConcurrentDictionary<(Type T, string name, Type[] argumentTypes), MethodInfo> + OverloadedMethodCache = + new ConcurrentDictionary<(Type T, string name, Type[] argumentTypes), MethodInfo>(); + + private static readonly ConcurrentDictionary DelegateCache = + new ConcurrentDictionary(); + + + // Class + private static readonly ConcurrentDictionary<(Type T, Type[] argumentTypes), ConstructorInfo> ConstructorCache = + new ConcurrentDictionary<(Type T, Type[] argumentTypes), ConstructorInfo>(); + + private static readonly ConcurrentDictionary<(Type T, string name), Type> NestedTypeCache = + new ConcurrentDictionary<(Type T, string name), Type>(); + + + // Helper methods + private static TValue GetOrAddOnNull(this ConcurrentDictionary dict, TKey key, + Func factory) { + if (dict.TryGetValue(key, out var val) && val != null) + return val; + + return dict[key] = factory(key); + } + + #endregion + + #region Field + + /// + /// Gets the of the type by name and caches it + /// + /// The type to search + /// The name of the field to find + /// + public static FieldInfo GetFieldCached(string name) => + typeof(T).GetFieldCached(name); + + /// + /// Gets the of the type by name and caches it + /// + /// The type to search + /// The name of the field to find + /// + public static FieldInfo GetFieldCached(this Type T, string name) => + FieldCache.GetOrAddOnNull((T, name), x => x.T.GetFieldFull(x.name) + ?? throw new Exception($"Could not find {nameof(FieldInfo)} on {T.FullName} with the name {name}")); + + + /// + /// Gets the value of the field on the object + /// + /// The type of the return value + /// The name of the field to get the value of + /// The object to get the field's value from + /// + public static TReturn GetFieldValue(this object instance, string fieldName) => + instance.GetType() + .GetFieldCached(fieldName) + .GetFieldGetDelegate() + (instance); + + /// + /// Gets the value of the specified static field on the specified static type + /// + /// The return type + /// The name of the static field to get the value of + /// The type to get the specified static field's value on + /// + public static TReturn GetFieldValue(this Type staticType, string fieldName) => + staticType + .GetFieldCached(fieldName) + .GetFieldGetDelegate() + (null); + + /// + /// Sets the value of the specified field on the specified object; if the object is a struct use + /// instead + /// + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified field's value on + /// The value to set + /// + public static void SetFieldValue(this object instance, string fieldName, TValue value) => + instance.GetType() + .GetFieldCached(fieldName) + .GetFieldSetDelegate() + (instance, value); + + /// + /// Sets the value of the specified static field on the specified static type + /// + /// The type of the value to set + /// The name of the static field to set the value of + /// The type to set the specified static field's value on + /// The value to set + /// + public static void SetFieldValue(this Type staticType, string fieldName, TValue value) => + staticType + .GetFieldCached(fieldName) + .GetFieldSetDelegate() + (null, value); + + /// + /// Sets the value of the specified field on the specified struct + /// + /// The type of the instance of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified field's value on + /// The value to set the field to + /// + public static void SetStructFieldValue(this ref TInstance instance, string fieldName, TValue value) + where TInstance : struct => + typeof(TInstance) + .GetFieldCached(fieldName) + .GetFieldSetDelegateRef() + (ref instance, value); + + + /// + /// Gets the on the specified and searches base types if not found. + /// + /// The to search and get base types from + /// The name of the property to search for. + /// + private static FieldInfo GetFieldFull(this Type T, string name) { + while (T != null) { + var fieldInfo = T.GetField(name, AllFlags); + if (fieldInfo != null) { + return fieldInfo; + } + + T = T.BaseType; + } + + return null; + } + + private static T GetMemberFull(this Type type, string name) where T : MemberInfo { + while (type != null) { + var fieldInfo = type.GetMember(name, AllFlags); + if (fieldInfo != null) { + return (T)fieldInfo.First(); + } + + type = type.BaseType; + } + + return null; + } + + private static GetDelegate GetFieldGetDelegate(this FieldInfo field) => + FieldGetDelegateCache.GetOrAdd(field, x => x.CreateGetDelegate()) + .CastDelegate>(); + + private static SetDelegate GetFieldSetDelegate(this FieldInfo field) => + FieldSetDelegateCache.GetOrAdd(field, x => x.CreateSetDelegate()) + .CastDelegate>(); + + private static SetDelegateRef GetFieldSetDelegateRef(this FieldInfo field) where TInstance : struct => + FieldSetDelegateCache.GetOrAdd(field, x => x.CreateSetDelegateRef()) + .CastDelegate>(); + + #endregion + + #region Property + + /// + /// Gets the of the type by name + /// + /// The type on which to find the property + /// The name of the property to get + /// + public static PropertyInfo GetPropertyCached(string name) => + typeof(T).GetPropertyCached(name); + + /// + /// Gets the of the type by name + /// + /// The type to get the from + /// The name of the property to get + /// + public static PropertyInfo GetPropertyCached(this Type T, string name) => + PropertyCache.GetOrAddOnNull((T, name), x => x.T.GetProperty(x.name, AllFlags)); + + /// + /// Gets the value of the property on the specified object; if the object is a struct use + /// instead + /// + /// The type of the return value + /// The object to get the property's value from + /// The name of the field to get the value of + /// + public static TReturn GetPropertyValue(this object instance, string propName) => + instance.GetType() + .GetPropertyCached(propName) + .GetPropertyGetDelegate() + (instance); + + /// + /// Gets the value of the static property on the specified static type + /// + /// The return type + /// The name of the static field to get the value of + /// The type to get the specified static property's value on + /// + public static TReturn GetPropertyValue(this Type staticType, string propName) => + staticType + .GetPropertyCached(propName) + .GetPropertyGetDelegate() + (null); + + /// + /// Sets the value of the property on the specified class; if you're setting the property on a + /// struct use instead + /// + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// The value to set + /// + public static void SetPropertyValue(this object instance, string propName, TValue value) => + instance.GetType() + .GetPropertyCached(propName)? + .GetPropertySetDelegate() + (instance, value); + + /// + /// Sets the value of the static property on the specified static class + /// + /// The type of the value to set + /// The name of the static field to set the value of + /// The type to set the specified static property's value on + /// The value to set the property to + /// + public static void SetPropertyValue(this Type staticType, string propName, TValue value) => + staticType.GetPropertyCached(propName)? + .GetPropertySetDelegate() + (null, value); + + /// + /// Sets the value of the specified property on the specified struct + /// + /// The type of the instance of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// The value to set the property to + /// + public static void SetStructPropertyValue(this ref TInstance instance, string propName, + TValue value) + where TInstance : struct => + typeof(TInstance) + .GetPropertyCached(propName) + .GetPropertySetDelegateRef() + (ref instance, value); + + /// + /// Gets the value of the specified property on the specified struct + /// + /// The type of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// + public static TValue GetStructPropertyValue(this ref TInstance instance, string propName) + where TInstance : struct => + typeof(TInstance) + .GetPropertyCached(propName) + .GetPropertyGetDelegateRef() + (ref instance); + + private static GetDelegate GetPropertyGetDelegate(this PropertyInfo property) => + PropertyGetDelegateCache.GetOrAdd(property, prop => prop.CreateGetDelegate()) + .CastDelegate>(); + + private static GetDelegateRef GetPropertyGetDelegateRef(this PropertyInfo property) + where TInstance : struct => + PropertyGetDelegateCache.GetOrAdd(property, prop => prop.CreateGetDelegate()) + .CastDelegate>(); + + private static SetDelegate GetPropertySetDelegate(this PropertyInfo property) => + PropertySetDelegateCache.GetOrAdd(property, prop => prop.CreateSetDelegate()) + .CastDelegate>(); + + private static SetDelegateRef GetPropertySetDelegateRef( + this PropertyInfo property) + where TInstance : struct => + PropertySetDelegateCache.GetOrAdd(property, prop => prop.CreateSetDelegateRef()) + .CastDelegate>(); + + #endregion + + #region Method + + /// + /// Gets the method on the specified type and caches it + /// + /// The type to search + /// The name of the method to find + /// + public static MethodInfo GetMethodCached(string name) => + typeof(T).GetMethodCached(name); + + /// + /// Gets the method on the specified static type and caches it + /// + /// The type to search + /// The name of the method to find + /// + public static MethodInfo GetMethodCached(this Type T, string name) => + MethodCache.GetOrAddOnNull((T, name), x => x.T.GetMethod(x.name, AllFlags) + ?? throw new Exception($"Could not find {nameof(MethodInfo)} on {T.FullName} with the name {name}")); + + /// + /// Gets the method on the specified type and caches it. This overload is used when the method is ambiguous + /// + /// The type to search + /// The name of the method to find + /// The types of the argument + /// + public static MethodInfo GetMethodCached(string name, Type[] argumentTypes) => + typeof(T).GetMethodCached(name, argumentTypes); + + /// + /// Gets the method on the specified static type and caches it. This overload is used when the method is ambiguous + /// + /// The type to search + /// The name of the method to find + /// The types of the argument + public static MethodInfo GetMethodCached(this Type T, string name, Type[] argumentTypes) => + OverloadedMethodCache.GetOrAddOnNull((T, name, argumentTypes), + x => x.T.GetMethod(x.name, AllFlags, null, x.argumentTypes, null) + ?? throw new Exception($"Could not find {nameof(MethodInfo)} on {T.FullName} with the name {name} and arguments: " + + $"{string.Join(",", argumentTypes.Select(a => a.FullName))}")); + + /// + /// Invoke a method on the specified object by name + /// + /// The return type of the method + /// The object to invoke the method on + /// The name of the method to invoke + /// + public static TReturn InvokeMethod(this object instance, string methodName) => + instance.InvokeMethod(methodName, null); + + /// + /// Invoke a static method on the specified type by name + /// + /// The return type of the method + /// The static type to search + /// The name of the method to invoke + /// + public static TReturn InvokeMethod(this Type staticType, string methodName) => + staticType.InvokeMethod(methodName, null); + + /// + /// Invoke a method on the specified object by name + /// + /// The object to invoke the method on + /// The name of the method to invoke + public static void InvokeMethod(this object instance, string methodName) => + instance.InvokeMethod(methodName); + + /// + /// Invoke a static method on the specified type by name + /// + /// The static type to search + /// The name of the method to invoke + public static void InvokeMethod(this Type staticType, string methodName) => + staticType.InvokeMethod(methodName); + + /// + /// Invoke a method on the specified object by name with parameters + /// + /// The return type of the method + /// The object to invoke the method on + /// The name of the method to invoke + /// + /// + public static TReturn InvokeMethod(this object instance, string methodName, + params object[] methodParams) { + var methodInfo = (methodParams == null + ? instance.GetType() + .GetMethodCached(methodName) + : instance.GetType() + .GetMethodCached(methodName, methodParams.Select(x => x.GetType()).ToArray()) + ) ?? throw new Exception($"Could not find method on type {instance.GetType()} with the name of {methodName} with the arguments specified."); + + return (TReturn)methodInfo.GetMethodDelegateCached()(instance, methodParams); + } + + /// + /// Invoke a static method on the specified type by name with parameters + /// + /// The return type of the method + /// The static type to search + /// The name of the method to invoke + /// The method parameters + /// + public static TReturn InvokeMethod(this Type staticType, string methodName, + params object[] methodParams) { + var methodInfo = (methodParams == null + ? staticType + .GetMethodCached(methodName) + : staticType + .GetMethodCached(methodName, methodParams.Select(x => x.GetType()).ToArray())) + ?? throw new Exception($"Could not find method on type {staticType} with the name of {methodName} with the arguments specified."); + + return (TReturn)methodInfo.GetMethodDelegateCached()(null, methodParams); + } + + /// + /// Invoke a method on the specified object by name with parameters + /// + /// The object to invoke the method on + /// The name of the method to invoke + /// + public static void InvokeMethod(this object instance, string methodName, params object[] methodParams) => + instance.InvokeMethod(methodName, methodParams); + + /// + /// Invoke a static method on the specified type by name with parameters + /// + /// The static type to search + /// The name of the method to invoke + /// + public static void InvokeMethod(this Type staticType, string methodName, params object[] methodParams) => + staticType.InvokeMethod(methodName, methodParams); + + + private static FastReflectionDelegate GetMethodDelegateCached(this MethodInfo methodInfo) => + DelegateCache.GetOrAdd(methodInfo, method => method.CreateFastDelegate()); + + #endregion + + #region Class + + /// + /// Gets the constructor on the specified type with specified arguments and caches it + /// + /// The type to search + /// The types of the arguments on the constructor to find + /// + public static ConstructorInfo GetConstructorCached(Type[] argumentTypes) => + GetConstructorCached(typeof(T), argumentTypes); + + /// + /// Gets the constructor on the specified static type with specified arguments and caches it + /// + /// The type to search + /// The types of the arguments on the constructor to find + /// + public static ConstructorInfo GetConstructorCached(this Type T, Type[] argumentTypes) => + ConstructorCache.GetOrAddOnNull((T, argumentTypes), x => x.T.GetConstructor(x.argumentTypes) + ?? throw new Exception($"Could not find {nameof(ConstructorInfo)} on {T.FullName} with the arguments {string.Join(",", argumentTypes.Select(a => a.FullName))}")); + + /// + /// Gets the nested type on the specified type + /// + /// The type to search + /// The name of the nested type to find + /// + public static Type GetNestedType(string name) => + typeof(T).GetNestedTypeCached(name); + + /// + /// Gets the nested type on the specified type + /// + /// The type to search + /// The name of the nested type to find + /// + public static Type GetNestedTypeCached(string name) => + typeof(T).GetNestedTypeCached(name); + + /// + /// Gets the nested type on the specified static type + /// + /// The static type to search + /// The name of the nested type to find + /// + public static Type GetNestedTypeCached(this Type T, string name) => + NestedTypeCache.GetOrAddOnNull((T, name), x => x.T.GetNestedType(x.name, AllFlags) + ?? throw new Exception($"Could not find nested {nameof(Type)} on {T.FullName} with the name {name}")); + + /// + /// Instatiates the specified type + /// + /// The type to instantiate + /// + public static object Instantiate(this Type type) => + Activator.CreateInstance(type, true); + + /// + /// Instatiates the specified type with specified constructor arguments + /// + /// The type to instantiate + /// The constructor arguments + /// + public static object Instantiate(this Type type, params object[] constructorArguments) => + type.GetConstructorCached(constructorArguments.Select(x => x.GetType()).ToArray()) + .Invoke(constructorArguments); + + /// + /// Instantiates the specified generic type + /// + /// The type to instantiate + /// The type of the generic type argument + /// + public static object InstantiateGeneric(this Type typeArgument) => + typeof(TClass).MakeGenericType(typeArgument).Instantiate(); + + /// + /// Instantiates the specified generic types + /// + /// The type to instantiate + /// The types of the generic type arguments + /// + public static object InstantiateGeneric(this Type[] typeArgument) => + typeof(TClass).MakeGenericType(typeArgument).Instantiate(); + + /// + /// Instantiates a list of the specified generic type + /// + /// + /// + public static IList InstantiateList(this Type type) => + (IList)typeof(List<>).MakeGenericType(type).Instantiate(); + + #endregion + + #region Fast Reflection + + private static GetDelegate CreateGetDelegate(this FieldInfo field) { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (!typeof(TReturn).IsAssignableFrom(field.FieldType)) { + throw new Exception($"Field type {field.FieldType} does not match the requested type {typeof(TReturn)}."); + } + + + var method = new DynamicMethodDefinition($"{field} Getter", typeof(TReturn), new[] { typeof(object) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + if (field.DeclaringType.GetTypeInfo().IsValueType) { + il.Emit(OpCodes.Unbox_Any, field.DeclaringType); + } + } + + il.Emit(!field.IsStatic ? OpCodes.Ldfld : OpCodes.Ldsfld, field); + il.Emit(OpCodes.Ret); + + return (GetDelegate)method.Generate().CreateDelegate(typeof(GetDelegate)); + } + + private static SetDelegate CreateSetDelegate(this FieldInfo field) { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (!field.FieldType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {field.FieldType}."); + } + + var method = new DynamicMethodDefinition($"{field} Setter", typeof(void), + new[] { typeof(object), typeof(TValue) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(!field.IsStatic ? OpCodes.Stfld : OpCodes.Stsfld, field); + + il.Emit(OpCodes.Ret); + + return (SetDelegate)method.Generate().CreateDelegate(typeof(SetDelegate)); + } + + private static SetDelegateRef CreateSetDelegateRef(this FieldInfo field) where TInstance : struct { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (field.FieldType != typeof(TValue)) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {field.FieldType}."); + } + + var method = new DynamicMethodDefinition($"{field} SetterByRef", typeof(void), + new[] { typeof(TInstance).MakeByRefType(), typeof(TValue) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(!field.IsStatic ? OpCodes.Stfld : OpCodes.Stsfld, field); + il.Emit(OpCodes.Ret); + + return (SetDelegateRef)method.Generate().CreateDelegate(typeof(SetDelegateRef)); + } + + private static GetDelegate CreateGetDelegate(this PropertyInfo property) { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!typeof(TReturn).IsAssignableFrom(property.PropertyType)) { + throw new Exception($"Field type {property.PropertyType} does not match the requested type {typeof(TReturn)}."); + } + + var method = new DynamicMethodDefinition($"{property} Getter", typeof(TReturn), new[] { typeof(object) }); + var il = method.GetILProcessor(); + + var getMethod = property.GetGetMethod(nonPublic: true); + + if (!getMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Call, getMethod); + il.Emit(OpCodes.Ret); + + return (GetDelegate)method.Generate().CreateDelegate(typeof(GetDelegate)); + } + + private static GetDelegateRef CreateGetDelegate(this PropertyInfo property) where TInstance : struct { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!typeof(TReturn).IsAssignableFrom(property.PropertyType)) { + throw new Exception($"Field type {property.PropertyType} does not match the requested type {typeof(TReturn)}."); + } + + var method = new DynamicMethodDefinition($"{property} Getter", typeof(TReturn), new[] { typeof(TInstance).MakeByRefType() }); + var il = method.GetILProcessor(); + + // Cache this as well? + var getMethod = property.GetGetMethod(nonPublic: true); + + if (!getMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Call, getMethod); + il.Emit(OpCodes.Ret); + + return (GetDelegateRef)method.Generate().CreateDelegate(typeof(GetDelegateRef)); + } + + + private static SetDelegate CreateSetDelegate(this PropertyInfo property) { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!property.PropertyType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {property.PropertyType}."); + } + + var method = new DynamicMethodDefinition($"{property} Setter", typeof(void), + new[] { typeof(object), typeof(TValue) }); + var il = method.GetILProcessor(); + + var setMethod = property.GetSetMethod(true); + + if (!setMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Call, setMethod); + il.Emit(OpCodes.Ret); + + return (SetDelegate)method.Generate().CreateDelegate(typeof(SetDelegate)); + } + + private static SetDelegateRef CreateSetDelegateRef(this PropertyInfo property) where TInstance : struct { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!property.PropertyType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {property.PropertyType}."); + } + + var method = new DynamicMethodDefinition($"{property} SetterByRef", typeof(void), + new[] { typeof(TInstance).MakeByRefType(), typeof(TValue) }); + var il = method.GetILProcessor(); + + var setMethod = property.GetSetMethod(true); + + if (!setMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Call, setMethod); + il.Emit(OpCodes.Ret); + + return (SetDelegateRef)method.Generate().CreateDelegate(typeof(SetDelegateRef)); + } + + // Partial hack from https://github.com/0x0ade/MonoMod/blob/master/MonoMod.Utils/FastReflectionHelper.cs + // to get fast call delegates + //private static CallDelegate GenerateCallDelegate(this MethodInfo method) { + // if (method == null) { + // throw new ArgumentException("Method cannot be null.", nameof(method)); + // } + + // var dmd = new DynamicMethodDefinition( + // $"CallDelegate<{method.Name}>", typeof(object), new[] { typeof(object), typeof(object[]) }); + // var il = dmd.GetILProcessor(); + + // var args = method.GetParameters(); + + // if (!method.IsStatic) { + // il.Emit(OpCodes.Ldarg_0); + // if (method.DeclaringType.GetTypeInfo().IsValueType) { + // il.Emit(OpCodes.Unbox_Any, method.DeclaringType); + // } + // } + + // for (var i = 0; i < args.Length; i++) { + // var argType = args[i].ParameterType; + // var argIsByRef = argType.IsByRef; + // if (argIsByRef) + // argType = argType.GetElementType(); + // var argIsValueType = argType.GetTypeInfo().IsValueType; + + // if (argIsByRef && argIsValueType) { + // // Used later when storing back the reference to the new box in the array. + // il.Emit(OpCodes.Ldarg_1); + // il.EmitFast_Ldc_I4(i); + // } + + // il.Emit(OpCodes.Ldarg_1); + // il.EmitFast_Ldc_I4(i); + + // if (argIsByRef && !argIsValueType) { + // il.Emit(OpCodes.Ldelema, typeof(object)); + // } + // else { + // il.Emit(OpCodes.Ldelem_Ref); + // if (!argIsValueType) continue; + // il.Emit(!argIsByRef ? OpCodes.Unbox_Any : OpCodes.Unbox, argType); + // } + // } + + // if (method.IsFinal || !method.IsVirtual) { + // il.Emit(OpCodes.Call, method); + // } + // else { + // il.Emit(OpCodes.Callvirt, method); + // } + + // var returnType = method.IsConstructor ? method.DeclaringType : method.ReturnType; + // if (returnType != typeof(void)) { + // if (returnType.GetTypeInfo().IsValueType) { + // il.Emit(OpCodes.Box, returnType); + // } + // } + // else { + // il.Emit(OpCodes.Ldnull); + // } + + // il.Emit(OpCodes.Ret); + + // return (CallDelegate) dmd.Generate().CreateDelegate(typeof(CallDelegate)); + //} + + // https://github.com/0x0ade/MonoMod/blob/master/MonoMod.Utils/FastReflectionHelper.cs + public static void EmitFast_Ldc_I4(this ILProcessor il, int value) { + switch (value) { + case -1: + il.Emit(OpCodes.Ldc_I4_M1); + return; + case 0: + il.Emit(OpCodes.Ldc_I4_0); + return; + case 1: + il.Emit(OpCodes.Ldc_I4_1); + return; + case 2: + il.Emit(OpCodes.Ldc_I4_2); + return; + case 3: + il.Emit(OpCodes.Ldc_I4_3); + return; + case 4: + il.Emit(OpCodes.Ldc_I4_4); + return; + case 5: + il.Emit(OpCodes.Ldc_I4_5); + return; + case 6: + il.Emit(OpCodes.Ldc_I4_6); + return; + case 7: + il.Emit(OpCodes.Ldc_I4_7); + return; + case 8: + il.Emit(OpCodes.Ldc_I4_8); + return; + } + + if (value > -129 && value < 128) + il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); + else + il.Emit(OpCodes.Ldc_I4, value); + } + + public static byte ReadLocalIndex(OpCode opCode, object operand) { + if (opCode == OpCodes.Ldloc_0 || opCode == OpCodes.Stloc_0) { + return 0; + } + if (opCode == OpCodes.Ldloc_1 || opCode == OpCodes.Stloc_1) { + return 1; + } + if (opCode == OpCodes.Ldloc_2 || opCode == OpCodes.Stloc_2) { + return 2; + } + if (opCode == OpCodes.Ldloc_3 || opCode == OpCodes.Stloc_3) { + return 3; + } + if (opCode == OpCodes.Ldloc_S || opCode == OpCodes.Stloc_S) { + return (byte)operand; + } + + throw new Exception($"Could not read index for opcode and operand: {opCode} - {operand}"); + } + + #endregion + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource method of type MonoMod.Utils.DynamicMethodDefinition in method "Reflection$SetDelegateRef`2 Reflection.CreateSetDelegateRef(PropertyInfo)". + +### Severity: +ERROR + +### Procedure: +Reflection$SetDelegateRef`2 Reflection.CreateSetDelegateRef(PropertyInfo) + +### File: +R2API/Utils/Reflection.cs + +### Key: +Reflection.cs|CreateSetDelegateRef|DOTNET_RESOURCE_LEAK + +### Hash: +956d446b2799643ff693e066d4ac4a7b + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0504/instruction.md b/inferredbugs-0504/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3e8475a43ad7a6c142738b2a74d536b57bc4a0ac --- /dev/null +++ b/inferredbugs-0504/instruction.md @@ -0,0 +1,956 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** R2API +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Mono.Cecil.Cil; +using MonoMod.Utils; + +namespace R2API.Utils { + public static class Reflection { + + private const BindingFlags AllFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | + BindingFlags.Instance | BindingFlags.DeclaredOnly; + + private delegate T GetDelegate(object instance); + + private delegate void SetDelegate(object instance, T value); + + //private delegate object CallDelegate(object instance, object[] arguments); + + private delegate void SetDelegateRef(ref TInstance instance, TValue value) where TInstance : struct; + + private delegate T GetDelegateRef(ref TInstance instance) where TInstance : struct; + + #region Caches + + // Field + private static readonly ConcurrentDictionary<(Type T, string name), FieldInfo> FieldCache = + new ConcurrentDictionary<(Type T, string name), FieldInfo>(); + + private static readonly ConcurrentDictionary FieldGetDelegateCache = + new ConcurrentDictionary(); + + private static readonly ConcurrentDictionary FieldSetDelegateCache = + new ConcurrentDictionary(); + + + // Property + private static readonly ConcurrentDictionary<(Type T, string name), PropertyInfo> PropertyCache = + new ConcurrentDictionary<(Type T, string name), PropertyInfo>(); + + private static readonly ConcurrentDictionary PropertyGetDelegateCache = + new ConcurrentDictionary(); + + private static readonly ConcurrentDictionary PropertySetDelegateCache = + new ConcurrentDictionary(); + + + // Method + private static readonly ConcurrentDictionary<(Type T, string name), MethodInfo> MethodCache = + new ConcurrentDictionary<(Type T, string name), MethodInfo>(); + + private static readonly ConcurrentDictionary<(Type T, string name, Type[] argumentTypes), MethodInfo> + OverloadedMethodCache = + new ConcurrentDictionary<(Type T, string name, Type[] argumentTypes), MethodInfo>(); + + private static readonly ConcurrentDictionary DelegateCache = + new ConcurrentDictionary(); + + + // Class + private static readonly ConcurrentDictionary<(Type T, Type[] argumentTypes), ConstructorInfo> ConstructorCache = + new ConcurrentDictionary<(Type T, Type[] argumentTypes), ConstructorInfo>(); + + private static readonly ConcurrentDictionary<(Type T, string name), Type> NestedTypeCache = + new ConcurrentDictionary<(Type T, string name), Type>(); + + + // Helper methods + private static TValue GetOrAddOnNull(this ConcurrentDictionary dict, TKey key, + Func factory) { + if (dict.TryGetValue(key, out var val) && val != null) + return val; + + return dict[key] = factory(key); + } + + #endregion + + #region Field + + /// + /// Gets the of the type by name and caches it + /// + /// The type to search + /// The name of the field to find + /// + public static FieldInfo GetFieldCached(string name) => + typeof(T).GetFieldCached(name); + + /// + /// Gets the of the type by name and caches it + /// + /// The type to search + /// The name of the field to find + /// + public static FieldInfo GetFieldCached(this Type T, string name) => + FieldCache.GetOrAddOnNull((T, name), x => x.T.GetFieldFull(x.name) + ?? throw new Exception($"Could not find {nameof(FieldInfo)} on {T.FullName} with the name {name}")); + + + /// + /// Gets the value of the field on the object + /// + /// The type of the return value + /// The name of the field to get the value of + /// The object to get the field's value from + /// + public static TReturn GetFieldValue(this object instance, string fieldName) => + instance.GetType() + .GetFieldCached(fieldName) + .GetFieldGetDelegate() + (instance); + + /// + /// Gets the value of the specified static field on the specified static type + /// + /// The return type + /// The name of the static field to get the value of + /// The type to get the specified static field's value on + /// + public static TReturn GetFieldValue(this Type staticType, string fieldName) => + staticType + .GetFieldCached(fieldName) + .GetFieldGetDelegate() + (null); + + /// + /// Sets the value of the specified field on the specified object; if the object is a struct use + /// instead + /// + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified field's value on + /// The value to set + /// + public static void SetFieldValue(this object instance, string fieldName, TValue value) => + instance.GetType() + .GetFieldCached(fieldName) + .GetFieldSetDelegate() + (instance, value); + + /// + /// Sets the value of the specified static field on the specified static type + /// + /// The type of the value to set + /// The name of the static field to set the value of + /// The type to set the specified static field's value on + /// The value to set + /// + public static void SetFieldValue(this Type staticType, string fieldName, TValue value) => + staticType + .GetFieldCached(fieldName) + .GetFieldSetDelegate() + (null, value); + + /// + /// Sets the value of the specified field on the specified struct + /// + /// The type of the instance of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified field's value on + /// The value to set the field to + /// + public static void SetStructFieldValue(this ref TInstance instance, string fieldName, TValue value) + where TInstance : struct => + typeof(TInstance) + .GetFieldCached(fieldName) + .GetFieldSetDelegateRef() + (ref instance, value); + + + /// + /// Gets the on the specified and searches base types if not found. + /// + /// The to search and get base types from + /// The name of the property to search for. + /// + private static FieldInfo GetFieldFull(this Type T, string name) { + while (T != null) { + var fieldInfo = T.GetField(name, AllFlags); + if (fieldInfo != null) { + return fieldInfo; + } + + T = T.BaseType; + } + + return null; + } + + private static T GetMemberFull(this Type type, string name) where T : MemberInfo { + while (type != null) { + var fieldInfo = type.GetMember(name, AllFlags); + if (fieldInfo != null) { + return (T)fieldInfo.First(); + } + + type = type.BaseType; + } + + return null; + } + + private static GetDelegate GetFieldGetDelegate(this FieldInfo field) => + FieldGetDelegateCache.GetOrAdd(field, x => x.CreateGetDelegate()) + .CastDelegate>(); + + private static SetDelegate GetFieldSetDelegate(this FieldInfo field) => + FieldSetDelegateCache.GetOrAdd(field, x => x.CreateSetDelegate()) + .CastDelegate>(); + + private static SetDelegateRef GetFieldSetDelegateRef(this FieldInfo field) where TInstance : struct => + FieldSetDelegateCache.GetOrAdd(field, x => x.CreateSetDelegateRef()) + .CastDelegate>(); + + #endregion + + #region Property + + /// + /// Gets the of the type by name + /// + /// The type on which to find the property + /// The name of the property to get + /// + public static PropertyInfo GetPropertyCached(string name) => + typeof(T).GetPropertyCached(name); + + /// + /// Gets the of the type by name + /// + /// The type to get the from + /// The name of the property to get + /// + public static PropertyInfo GetPropertyCached(this Type T, string name) => + PropertyCache.GetOrAddOnNull((T, name), x => x.T.GetProperty(x.name, AllFlags)); + + /// + /// Gets the value of the property on the specified object; if the object is a struct use + /// instead + /// + /// The type of the return value + /// The object to get the property's value from + /// The name of the field to get the value of + /// + public static TReturn GetPropertyValue(this object instance, string propName) => + instance.GetType() + .GetPropertyCached(propName) + .GetPropertyGetDelegate() + (instance); + + /// + /// Gets the value of the static property on the specified static type + /// + /// The return type + /// The name of the static field to get the value of + /// The type to get the specified static property's value on + /// + public static TReturn GetPropertyValue(this Type staticType, string propName) => + staticType + .GetPropertyCached(propName) + .GetPropertyGetDelegate() + (null); + + /// + /// Sets the value of the property on the specified class; if you're setting the property on a + /// struct use instead + /// + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// The value to set + /// + public static void SetPropertyValue(this object instance, string propName, TValue value) => + instance.GetType() + .GetPropertyCached(propName)? + .GetPropertySetDelegate() + (instance, value); + + /// + /// Sets the value of the static property on the specified static class + /// + /// The type of the value to set + /// The name of the static field to set the value of + /// The type to set the specified static property's value on + /// The value to set the property to + /// + public static void SetPropertyValue(this Type staticType, string propName, TValue value) => + staticType.GetPropertyCached(propName)? + .GetPropertySetDelegate() + (null, value); + + /// + /// Sets the value of the specified property on the specified struct + /// + /// The type of the instance of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// The value to set the property to + /// + public static void SetStructPropertyValue(this ref TInstance instance, string propName, + TValue value) + where TInstance : struct => + typeof(TInstance) + .GetPropertyCached(propName) + .GetPropertySetDelegateRef() + (ref instance, value); + + /// + /// Gets the value of the specified property on the specified struct + /// + /// The type of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// + public static TValue GetStructPropertyValue(this ref TInstance instance, string propName) + where TInstance : struct => + typeof(TInstance) + .GetPropertyCached(propName) + .GetPropertyGetDelegateRef() + (ref instance); + + private static GetDelegate GetPropertyGetDelegate(this PropertyInfo property) => + PropertyGetDelegateCache.GetOrAdd(property, prop => prop.CreateGetDelegate()) + .CastDelegate>(); + + private static GetDelegateRef GetPropertyGetDelegateRef(this PropertyInfo property) + where TInstance : struct => + PropertyGetDelegateCache.GetOrAdd(property, prop => prop.CreateGetDelegate()) + .CastDelegate>(); + + private static SetDelegate GetPropertySetDelegate(this PropertyInfo property) => + PropertySetDelegateCache.GetOrAdd(property, prop => prop.CreateSetDelegate()) + .CastDelegate>(); + + private static SetDelegateRef GetPropertySetDelegateRef( + this PropertyInfo property) + where TInstance : struct => + PropertySetDelegateCache.GetOrAdd(property, prop => prop.CreateSetDelegateRef()) + .CastDelegate>(); + + #endregion + + #region Method + + /// + /// Gets the method on the specified type and caches it + /// + /// The type to search + /// The name of the method to find + /// + public static MethodInfo GetMethodCached(string name) => + typeof(T).GetMethodCached(name); + + /// + /// Gets the method on the specified static type and caches it + /// + /// The type to search + /// The name of the method to find + /// + public static MethodInfo GetMethodCached(this Type T, string name) => + MethodCache.GetOrAddOnNull((T, name), x => x.T.GetMethod(x.name, AllFlags) + ?? throw new Exception($"Could not find {nameof(MethodInfo)} on {T.FullName} with the name {name}")); + + /// + /// Gets the method on the specified type and caches it. This overload is used when the method is ambiguous + /// + /// The type to search + /// The name of the method to find + /// The types of the argument + /// + public static MethodInfo GetMethodCached(string name, Type[] argumentTypes) => + typeof(T).GetMethodCached(name, argumentTypes); + + /// + /// Gets the method on the specified static type and caches it. This overload is used when the method is ambiguous + /// + /// The type to search + /// The name of the method to find + /// The types of the argument + public static MethodInfo GetMethodCached(this Type T, string name, Type[] argumentTypes) => + OverloadedMethodCache.GetOrAddOnNull((T, name, argumentTypes), + x => x.T.GetMethod(x.name, AllFlags, null, x.argumentTypes, null) + ?? throw new Exception($"Could not find {nameof(MethodInfo)} on {T.FullName} with the name {name} and arguments: " + + $"{string.Join(",", argumentTypes.Select(a => a.FullName))}")); + + /// + /// Invoke a method on the specified object by name + /// + /// The return type of the method + /// The object to invoke the method on + /// The name of the method to invoke + /// + public static TReturn InvokeMethod(this object instance, string methodName) => + instance.InvokeMethod(methodName, null); + + /// + /// Invoke a static method on the specified type by name + /// + /// The return type of the method + /// The static type to search + /// The name of the method to invoke + /// + public static TReturn InvokeMethod(this Type staticType, string methodName) => + staticType.InvokeMethod(methodName, null); + + /// + /// Invoke a method on the specified object by name + /// + /// The object to invoke the method on + /// The name of the method to invoke + public static void InvokeMethod(this object instance, string methodName) => + instance.InvokeMethod(methodName); + + /// + /// Invoke a static method on the specified type by name + /// + /// The static type to search + /// The name of the method to invoke + public static void InvokeMethod(this Type staticType, string methodName) => + staticType.InvokeMethod(methodName); + + /// + /// Invoke a method on the specified object by name with parameters + /// + /// The return type of the method + /// The object to invoke the method on + /// The name of the method to invoke + /// + /// + public static TReturn InvokeMethod(this object instance, string methodName, + params object[] methodParams) { + var methodInfo = (methodParams == null + ? instance.GetType() + .GetMethodCached(methodName) + : instance.GetType() + .GetMethodCached(methodName, methodParams.Select(x => x.GetType()).ToArray()) + ) ?? throw new Exception($"Could not find method on type {instance.GetType()} with the name of {methodName} with the arguments specified."); + + return (TReturn)methodInfo.GetMethodDelegateCached()(instance, methodParams); + } + + /// + /// Invoke a static method on the specified type by name with parameters + /// + /// The return type of the method + /// The static type to search + /// The name of the method to invoke + /// The method parameters + /// + public static TReturn InvokeMethod(this Type staticType, string methodName, + params object[] methodParams) { + var methodInfo = (methodParams == null + ? staticType + .GetMethodCached(methodName) + : staticType + .GetMethodCached(methodName, methodParams.Select(x => x.GetType()).ToArray())) + ?? throw new Exception($"Could not find method on type {staticType} with the name of {methodName} with the arguments specified."); + + return (TReturn)methodInfo.GetMethodDelegateCached()(null, methodParams); + } + + /// + /// Invoke a method on the specified object by name with parameters + /// + /// The object to invoke the method on + /// The name of the method to invoke + /// + public static void InvokeMethod(this object instance, string methodName, params object[] methodParams) => + instance.InvokeMethod(methodName, methodParams); + + /// + /// Invoke a static method on the specified type by name with parameters + /// + /// The static type to search + /// The name of the method to invoke + /// + public static void InvokeMethod(this Type staticType, string methodName, params object[] methodParams) => + staticType.InvokeMethod(methodName, methodParams); + + + private static FastReflectionDelegate GetMethodDelegateCached(this MethodInfo methodInfo) => + DelegateCache.GetOrAdd(methodInfo, method => method.CreateFastDelegate()); + + #endregion + + #region Class + + /// + /// Gets the constructor on the specified type with specified arguments and caches it + /// + /// The type to search + /// The types of the arguments on the constructor to find + /// + public static ConstructorInfo GetConstructorCached(Type[] argumentTypes) => + GetConstructorCached(typeof(T), argumentTypes); + + /// + /// Gets the constructor on the specified static type with specified arguments and caches it + /// + /// The type to search + /// The types of the arguments on the constructor to find + /// + public static ConstructorInfo GetConstructorCached(this Type T, Type[] argumentTypes) => + ConstructorCache.GetOrAddOnNull((T, argumentTypes), x => x.T.GetConstructor(x.argumentTypes) + ?? throw new Exception($"Could not find {nameof(ConstructorInfo)} on {T.FullName} with the arguments {string.Join(",", argumentTypes.Select(a => a.FullName))}")); + + /// + /// Gets the nested type on the specified type + /// + /// The type to search + /// The name of the nested type to find + /// + public static Type GetNestedType(string name) => + typeof(T).GetNestedTypeCached(name); + + /// + /// Gets the nested type on the specified type + /// + /// The type to search + /// The name of the nested type to find + /// + public static Type GetNestedTypeCached(string name) => + typeof(T).GetNestedTypeCached(name); + + /// + /// Gets the nested type on the specified static type + /// + /// The static type to search + /// The name of the nested type to find + /// + public static Type GetNestedTypeCached(this Type T, string name) => + NestedTypeCache.GetOrAddOnNull((T, name), x => x.T.GetNestedType(x.name, AllFlags) + ?? throw new Exception($"Could not find nested {nameof(Type)} on {T.FullName} with the name {name}")); + + /// + /// Instatiates the specified type + /// + /// The type to instantiate + /// + public static object Instantiate(this Type type) => + Activator.CreateInstance(type, true); + + /// + /// Instatiates the specified type with specified constructor arguments + /// + /// The type to instantiate + /// The constructor arguments + /// + public static object Instantiate(this Type type, params object[] constructorArguments) => + type.GetConstructorCached(constructorArguments.Select(x => x.GetType()).ToArray()) + .Invoke(constructorArguments); + + /// + /// Instantiates the specified generic type + /// + /// The type to instantiate + /// The type of the generic type argument + /// + public static object InstantiateGeneric(this Type typeArgument) => + typeof(TClass).MakeGenericType(typeArgument).Instantiate(); + + /// + /// Instantiates the specified generic types + /// + /// The type to instantiate + /// The types of the generic type arguments + /// + public static object InstantiateGeneric(this Type[] typeArgument) => + typeof(TClass).MakeGenericType(typeArgument).Instantiate(); + + /// + /// Instantiates a list of the specified generic type + /// + /// + /// + public static IList InstantiateList(this Type type) => + (IList)typeof(List<>).MakeGenericType(type).Instantiate(); + + #endregion + + #region Fast Reflection + + private static GetDelegate CreateGetDelegate(this FieldInfo field) { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (!typeof(TReturn).IsAssignableFrom(field.FieldType)) { + throw new Exception($"Field type {field.FieldType} does not match the requested type {typeof(TReturn)}."); + } + + + var method = new DynamicMethodDefinition($"{field} Getter", typeof(TReturn), new[] { typeof(object) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + if (field.DeclaringType.GetTypeInfo().IsValueType) { + il.Emit(OpCodes.Unbox_Any, field.DeclaringType); + } + } + + il.Emit(!field.IsStatic ? OpCodes.Ldfld : OpCodes.Ldsfld, field); + il.Emit(OpCodes.Ret); + + return (GetDelegate)method.Generate().CreateDelegate(typeof(GetDelegate)); + } + + private static SetDelegate CreateSetDelegate(this FieldInfo field) { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (!field.FieldType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {field.FieldType}."); + } + + var method = new DynamicMethodDefinition($"{field} Setter", typeof(void), + new[] { typeof(object), typeof(TValue) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(!field.IsStatic ? OpCodes.Stfld : OpCodes.Stsfld, field); + + il.Emit(OpCodes.Ret); + + return (SetDelegate)method.Generate().CreateDelegate(typeof(SetDelegate)); + } + + private static SetDelegateRef CreateSetDelegateRef(this FieldInfo field) where TInstance : struct { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (field.FieldType != typeof(TValue)) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {field.FieldType}."); + } + + var method = new DynamicMethodDefinition($"{field} SetterByRef", typeof(void), + new[] { typeof(TInstance).MakeByRefType(), typeof(TValue) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(!field.IsStatic ? OpCodes.Stfld : OpCodes.Stsfld, field); + il.Emit(OpCodes.Ret); + + return (SetDelegateRef)method.Generate().CreateDelegate(typeof(SetDelegateRef)); + } + + private static GetDelegate CreateGetDelegate(this PropertyInfo property) { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!typeof(TReturn).IsAssignableFrom(property.PropertyType)) { + throw new Exception($"Field type {property.PropertyType} does not match the requested type {typeof(TReturn)}."); + } + + var method = new DynamicMethodDefinition($"{property} Getter", typeof(TReturn), new[] { typeof(object) }); + var il = method.GetILProcessor(); + + var getMethod = property.GetGetMethod(nonPublic: true); + + if (!getMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Call, getMethod); + il.Emit(OpCodes.Ret); + + return (GetDelegate)method.Generate().CreateDelegate(typeof(GetDelegate)); + } + + private static GetDelegateRef CreateGetDelegate(this PropertyInfo property) where TInstance : struct { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!typeof(TReturn).IsAssignableFrom(property.PropertyType)) { + throw new Exception($"Field type {property.PropertyType} does not match the requested type {typeof(TReturn)}."); + } + + var method = new DynamicMethodDefinition($"{property} Getter", typeof(TReturn), new[] { typeof(TInstance).MakeByRefType() }); + var il = method.GetILProcessor(); + + // Cache this as well? + var getMethod = property.GetGetMethod(nonPublic: true); + + if (!getMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Call, getMethod); + il.Emit(OpCodes.Ret); + + return (GetDelegateRef)method.Generate().CreateDelegate(typeof(GetDelegateRef)); + } + + + private static SetDelegate CreateSetDelegate(this PropertyInfo property) { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!property.PropertyType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {property.PropertyType}."); + } + + var method = new DynamicMethodDefinition($"{property} Setter", typeof(void), + new[] { typeof(object), typeof(TValue) }); + var il = method.GetILProcessor(); + + var setMethod = property.GetSetMethod(true); + + if (!setMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Call, setMethod); + il.Emit(OpCodes.Ret); + + return (SetDelegate)method.Generate().CreateDelegate(typeof(SetDelegate)); + } + + private static SetDelegateRef CreateSetDelegateRef(this PropertyInfo property) where TInstance : struct { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!property.PropertyType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {property.PropertyType}."); + } + + var method = new DynamicMethodDefinition($"{property} SetterByRef", typeof(void), + new[] { typeof(TInstance).MakeByRefType(), typeof(TValue) }); + var il = method.GetILProcessor(); + + var setMethod = property.GetSetMethod(true); + + if (!setMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Call, setMethod); + il.Emit(OpCodes.Ret); + + return (SetDelegateRef)method.Generate().CreateDelegate(typeof(SetDelegateRef)); + } + + // Partial hack from https://github.com/0x0ade/MonoMod/blob/master/MonoMod.Utils/FastReflectionHelper.cs + // to get fast call delegates + //private static CallDelegate GenerateCallDelegate(this MethodInfo method) { + // if (method == null) { + // throw new ArgumentException("Method cannot be null.", nameof(method)); + // } + + // var dmd = new DynamicMethodDefinition( + // $"CallDelegate<{method.Name}>", typeof(object), new[] { typeof(object), typeof(object[]) }); + // var il = dmd.GetILProcessor(); + + // var args = method.GetParameters(); + + // if (!method.IsStatic) { + // il.Emit(OpCodes.Ldarg_0); + // if (method.DeclaringType.GetTypeInfo().IsValueType) { + // il.Emit(OpCodes.Unbox_Any, method.DeclaringType); + // } + // } + + // for (var i = 0; i < args.Length; i++) { + // var argType = args[i].ParameterType; + // var argIsByRef = argType.IsByRef; + // if (argIsByRef) + // argType = argType.GetElementType(); + // var argIsValueType = argType.GetTypeInfo().IsValueType; + + // if (argIsByRef && argIsValueType) { + // // Used later when storing back the reference to the new box in the array. + // il.Emit(OpCodes.Ldarg_1); + // il.EmitFast_Ldc_I4(i); + // } + + // il.Emit(OpCodes.Ldarg_1); + // il.EmitFast_Ldc_I4(i); + + // if (argIsByRef && !argIsValueType) { + // il.Emit(OpCodes.Ldelema, typeof(object)); + // } + // else { + // il.Emit(OpCodes.Ldelem_Ref); + // if (!argIsValueType) continue; + // il.Emit(!argIsByRef ? OpCodes.Unbox_Any : OpCodes.Unbox, argType); + // } + // } + + // if (method.IsFinal || !method.IsVirtual) { + // il.Emit(OpCodes.Call, method); + // } + // else { + // il.Emit(OpCodes.Callvirt, method); + // } + + // var returnType = method.IsConstructor ? method.DeclaringType : method.ReturnType; + // if (returnType != typeof(void)) { + // if (returnType.GetTypeInfo().IsValueType) { + // il.Emit(OpCodes.Box, returnType); + // } + // } + // else { + // il.Emit(OpCodes.Ldnull); + // } + + // il.Emit(OpCodes.Ret); + + // return (CallDelegate) dmd.Generate().CreateDelegate(typeof(CallDelegate)); + //} + + // https://github.com/0x0ade/MonoMod/blob/master/MonoMod.Utils/FastReflectionHelper.cs + public static void EmitFast_Ldc_I4(this ILProcessor il, int value) { + switch (value) { + case -1: + il.Emit(OpCodes.Ldc_I4_M1); + return; + case 0: + il.Emit(OpCodes.Ldc_I4_0); + return; + case 1: + il.Emit(OpCodes.Ldc_I4_1); + return; + case 2: + il.Emit(OpCodes.Ldc_I4_2); + return; + case 3: + il.Emit(OpCodes.Ldc_I4_3); + return; + case 4: + il.Emit(OpCodes.Ldc_I4_4); + return; + case 5: + il.Emit(OpCodes.Ldc_I4_5); + return; + case 6: + il.Emit(OpCodes.Ldc_I4_6); + return; + case 7: + il.Emit(OpCodes.Ldc_I4_7); + return; + case 8: + il.Emit(OpCodes.Ldc_I4_8); + return; + } + + if (value > -129 && value < 128) + il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); + else + il.Emit(OpCodes.Ldc_I4, value); + } + + public static byte ReadLocalIndex(OpCode opCode, object operand) { + if (opCode == OpCodes.Ldloc_0 || opCode == OpCodes.Stloc_0) { + return 0; + } + if (opCode == OpCodes.Ldloc_1 || opCode == OpCodes.Stloc_1) { + return 1; + } + if (opCode == OpCodes.Ldloc_2 || opCode == OpCodes.Stloc_2) { + return 2; + } + if (opCode == OpCodes.Ldloc_3 || opCode == OpCodes.Stloc_3) { + return 3; + } + if (opCode == OpCodes.Ldloc_S || opCode == OpCodes.Stloc_S) { + return (byte)operand; + } + + throw new Exception($"Could not read index for opcode and operand: {opCode} - {operand}"); + } + + #endregion + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource method of type MonoMod.Utils.DynamicMethodDefinition in method "Reflection$GetDelegate`1 Reflection.CreateGetDelegate(PropertyInfo)". + +### Severity: +ERROR + +### Procedure: +Reflection$GetDelegate`1 Reflection.CreateGetDelegate(PropertyInfo) + +### File: +R2API/Utils/Reflection.cs + +### Key: +Reflection.cs|CreateGetDelegate|DOTNET_RESOURCE_LEAK + +### Hash: +39ac3bfb236bcca6a582621a0432a137 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0505/instruction.md b/inferredbugs-0505/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..97d4a371af3fbbb5501da71ba89c53d71348a655 --- /dev/null +++ b/inferredbugs-0505/instruction.md @@ -0,0 +1,956 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** R2API +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Mono.Cecil.Cil; +using MonoMod.Utils; + +namespace R2API.Utils { + public static class Reflection { + + private const BindingFlags AllFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | + BindingFlags.Instance | BindingFlags.DeclaredOnly; + + private delegate T GetDelegate(object instance); + + private delegate void SetDelegate(object instance, T value); + + //private delegate object CallDelegate(object instance, object[] arguments); + + private delegate void SetDelegateRef(ref TInstance instance, TValue value) where TInstance : struct; + + private delegate T GetDelegateRef(ref TInstance instance) where TInstance : struct; + + #region Caches + + // Field + private static readonly ConcurrentDictionary<(Type T, string name), FieldInfo> FieldCache = + new ConcurrentDictionary<(Type T, string name), FieldInfo>(); + + private static readonly ConcurrentDictionary FieldGetDelegateCache = + new ConcurrentDictionary(); + + private static readonly ConcurrentDictionary FieldSetDelegateCache = + new ConcurrentDictionary(); + + + // Property + private static readonly ConcurrentDictionary<(Type T, string name), PropertyInfo> PropertyCache = + new ConcurrentDictionary<(Type T, string name), PropertyInfo>(); + + private static readonly ConcurrentDictionary PropertyGetDelegateCache = + new ConcurrentDictionary(); + + private static readonly ConcurrentDictionary PropertySetDelegateCache = + new ConcurrentDictionary(); + + + // Method + private static readonly ConcurrentDictionary<(Type T, string name), MethodInfo> MethodCache = + new ConcurrentDictionary<(Type T, string name), MethodInfo>(); + + private static readonly ConcurrentDictionary<(Type T, string name, Type[] argumentTypes), MethodInfo> + OverloadedMethodCache = + new ConcurrentDictionary<(Type T, string name, Type[] argumentTypes), MethodInfo>(); + + private static readonly ConcurrentDictionary DelegateCache = + new ConcurrentDictionary(); + + + // Class + private static readonly ConcurrentDictionary<(Type T, Type[] argumentTypes), ConstructorInfo> ConstructorCache = + new ConcurrentDictionary<(Type T, Type[] argumentTypes), ConstructorInfo>(); + + private static readonly ConcurrentDictionary<(Type T, string name), Type> NestedTypeCache = + new ConcurrentDictionary<(Type T, string name), Type>(); + + + // Helper methods + private static TValue GetOrAddOnNull(this ConcurrentDictionary dict, TKey key, + Func factory) { + if (dict.TryGetValue(key, out var val) && val != null) + return val; + + return dict[key] = factory(key); + } + + #endregion + + #region Field + + /// + /// Gets the of the type by name and caches it + /// + /// The type to search + /// The name of the field to find + /// + public static FieldInfo GetFieldCached(string name) => + typeof(T).GetFieldCached(name); + + /// + /// Gets the of the type by name and caches it + /// + /// The type to search + /// The name of the field to find + /// + public static FieldInfo GetFieldCached(this Type T, string name) => + FieldCache.GetOrAddOnNull((T, name), x => x.T.GetFieldFull(x.name) + ?? throw new Exception($"Could not find {nameof(FieldInfo)} on {T.FullName} with the name {name}")); + + + /// + /// Gets the value of the field on the object + /// + /// The type of the return value + /// The name of the field to get the value of + /// The object to get the field's value from + /// + public static TReturn GetFieldValue(this object instance, string fieldName) => + instance.GetType() + .GetFieldCached(fieldName) + .GetFieldGetDelegate() + (instance); + + /// + /// Gets the value of the specified static field on the specified static type + /// + /// The return type + /// The name of the static field to get the value of + /// The type to get the specified static field's value on + /// + public static TReturn GetFieldValue(this Type staticType, string fieldName) => + staticType + .GetFieldCached(fieldName) + .GetFieldGetDelegate() + (null); + + /// + /// Sets the value of the specified field on the specified object; if the object is a struct use + /// instead + /// + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified field's value on + /// The value to set + /// + public static void SetFieldValue(this object instance, string fieldName, TValue value) => + instance.GetType() + .GetFieldCached(fieldName) + .GetFieldSetDelegate() + (instance, value); + + /// + /// Sets the value of the specified static field on the specified static type + /// + /// The type of the value to set + /// The name of the static field to set the value of + /// The type to set the specified static field's value on + /// The value to set + /// + public static void SetFieldValue(this Type staticType, string fieldName, TValue value) => + staticType + .GetFieldCached(fieldName) + .GetFieldSetDelegate() + (null, value); + + /// + /// Sets the value of the specified field on the specified struct + /// + /// The type of the instance of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified field's value on + /// The value to set the field to + /// + public static void SetStructFieldValue(this ref TInstance instance, string fieldName, TValue value) + where TInstance : struct => + typeof(TInstance) + .GetFieldCached(fieldName) + .GetFieldSetDelegateRef() + (ref instance, value); + + + /// + /// Gets the on the specified and searches base types if not found. + /// + /// The to search and get base types from + /// The name of the property to search for. + /// + private static FieldInfo GetFieldFull(this Type T, string name) { + while (T != null) { + var fieldInfo = T.GetField(name, AllFlags); + if (fieldInfo != null) { + return fieldInfo; + } + + T = T.BaseType; + } + + return null; + } + + private static T GetMemberFull(this Type type, string name) where T : MemberInfo { + while (type != null) { + var fieldInfo = type.GetMember(name, AllFlags); + if (fieldInfo != null) { + return (T)fieldInfo.First(); + } + + type = type.BaseType; + } + + return null; + } + + private static GetDelegate GetFieldGetDelegate(this FieldInfo field) => + FieldGetDelegateCache.GetOrAdd(field, x => x.CreateGetDelegate()) + .CastDelegate>(); + + private static SetDelegate GetFieldSetDelegate(this FieldInfo field) => + FieldSetDelegateCache.GetOrAdd(field, x => x.CreateSetDelegate()) + .CastDelegate>(); + + private static SetDelegateRef GetFieldSetDelegateRef(this FieldInfo field) where TInstance : struct => + FieldSetDelegateCache.GetOrAdd(field, x => x.CreateSetDelegateRef()) + .CastDelegate>(); + + #endregion + + #region Property + + /// + /// Gets the of the type by name + /// + /// The type on which to find the property + /// The name of the property to get + /// + public static PropertyInfo GetPropertyCached(string name) => + typeof(T).GetPropertyCached(name); + + /// + /// Gets the of the type by name + /// + /// The type to get the from + /// The name of the property to get + /// + public static PropertyInfo GetPropertyCached(this Type T, string name) => + PropertyCache.GetOrAddOnNull((T, name), x => x.T.GetProperty(x.name, AllFlags)); + + /// + /// Gets the value of the property on the specified object; if the object is a struct use + /// instead + /// + /// The type of the return value + /// The object to get the property's value from + /// The name of the field to get the value of + /// + public static TReturn GetPropertyValue(this object instance, string propName) => + instance.GetType() + .GetPropertyCached(propName) + .GetPropertyGetDelegate() + (instance); + + /// + /// Gets the value of the static property on the specified static type + /// + /// The return type + /// The name of the static field to get the value of + /// The type to get the specified static property's value on + /// + public static TReturn GetPropertyValue(this Type staticType, string propName) => + staticType + .GetPropertyCached(propName) + .GetPropertyGetDelegate() + (null); + + /// + /// Sets the value of the property on the specified class; if you're setting the property on a + /// struct use instead + /// + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// The value to set + /// + public static void SetPropertyValue(this object instance, string propName, TValue value) => + instance.GetType() + .GetPropertyCached(propName)? + .GetPropertySetDelegate() + (instance, value); + + /// + /// Sets the value of the static property on the specified static class + /// + /// The type of the value to set + /// The name of the static field to set the value of + /// The type to set the specified static property's value on + /// The value to set the property to + /// + public static void SetPropertyValue(this Type staticType, string propName, TValue value) => + staticType.GetPropertyCached(propName)? + .GetPropertySetDelegate() + (null, value); + + /// + /// Sets the value of the specified property on the specified struct + /// + /// The type of the instance of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// The value to set the property to + /// + public static void SetStructPropertyValue(this ref TInstance instance, string propName, + TValue value) + where TInstance : struct => + typeof(TInstance) + .GetPropertyCached(propName) + .GetPropertySetDelegateRef() + (ref instance, value); + + /// + /// Gets the value of the specified property on the specified struct + /// + /// The type of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// + public static TValue GetStructPropertyValue(this ref TInstance instance, string propName) + where TInstance : struct => + typeof(TInstance) + .GetPropertyCached(propName) + .GetPropertyGetDelegateRef() + (ref instance); + + private static GetDelegate GetPropertyGetDelegate(this PropertyInfo property) => + PropertyGetDelegateCache.GetOrAdd(property, prop => prop.CreateGetDelegate()) + .CastDelegate>(); + + private static GetDelegateRef GetPropertyGetDelegateRef(this PropertyInfo property) + where TInstance : struct => + PropertyGetDelegateCache.GetOrAdd(property, prop => prop.CreateGetDelegate()) + .CastDelegate>(); + + private static SetDelegate GetPropertySetDelegate(this PropertyInfo property) => + PropertySetDelegateCache.GetOrAdd(property, prop => prop.CreateSetDelegate()) + .CastDelegate>(); + + private static SetDelegateRef GetPropertySetDelegateRef( + this PropertyInfo property) + where TInstance : struct => + PropertySetDelegateCache.GetOrAdd(property, prop => prop.CreateSetDelegateRef()) + .CastDelegate>(); + + #endregion + + #region Method + + /// + /// Gets the method on the specified type and caches it + /// + /// The type to search + /// The name of the method to find + /// + public static MethodInfo GetMethodCached(string name) => + typeof(T).GetMethodCached(name); + + /// + /// Gets the method on the specified static type and caches it + /// + /// The type to search + /// The name of the method to find + /// + public static MethodInfo GetMethodCached(this Type T, string name) => + MethodCache.GetOrAddOnNull((T, name), x => x.T.GetMethod(x.name, AllFlags) + ?? throw new Exception($"Could not find {nameof(MethodInfo)} on {T.FullName} with the name {name}")); + + /// + /// Gets the method on the specified type and caches it. This overload is used when the method is ambiguous + /// + /// The type to search + /// The name of the method to find + /// The types of the argument + /// + public static MethodInfo GetMethodCached(string name, Type[] argumentTypes) => + typeof(T).GetMethodCached(name, argumentTypes); + + /// + /// Gets the method on the specified static type and caches it. This overload is used when the method is ambiguous + /// + /// The type to search + /// The name of the method to find + /// The types of the argument + public static MethodInfo GetMethodCached(this Type T, string name, Type[] argumentTypes) => + OverloadedMethodCache.GetOrAddOnNull((T, name, argumentTypes), + x => x.T.GetMethod(x.name, AllFlags, null, x.argumentTypes, null) + ?? throw new Exception($"Could not find {nameof(MethodInfo)} on {T.FullName} with the name {name} and arguments: " + + $"{string.Join(",", argumentTypes.Select(a => a.FullName))}")); + + /// + /// Invoke a method on the specified object by name + /// + /// The return type of the method + /// The object to invoke the method on + /// The name of the method to invoke + /// + public static TReturn InvokeMethod(this object instance, string methodName) => + instance.InvokeMethod(methodName, null); + + /// + /// Invoke a static method on the specified type by name + /// + /// The return type of the method + /// The static type to search + /// The name of the method to invoke + /// + public static TReturn InvokeMethod(this Type staticType, string methodName) => + staticType.InvokeMethod(methodName, null); + + /// + /// Invoke a method on the specified object by name + /// + /// The object to invoke the method on + /// The name of the method to invoke + public static void InvokeMethod(this object instance, string methodName) => + instance.InvokeMethod(methodName); + + /// + /// Invoke a static method on the specified type by name + /// + /// The static type to search + /// The name of the method to invoke + public static void InvokeMethod(this Type staticType, string methodName) => + staticType.InvokeMethod(methodName); + + /// + /// Invoke a method on the specified object by name with parameters + /// + /// The return type of the method + /// The object to invoke the method on + /// The name of the method to invoke + /// + /// + public static TReturn InvokeMethod(this object instance, string methodName, + params object[] methodParams) { + var methodInfo = (methodParams == null + ? instance.GetType() + .GetMethodCached(methodName) + : instance.GetType() + .GetMethodCached(methodName, methodParams.Select(x => x.GetType()).ToArray()) + ) ?? throw new Exception($"Could not find method on type {instance.GetType()} with the name of {methodName} with the arguments specified."); + + return (TReturn)methodInfo.GetMethodDelegateCached()(instance, methodParams); + } + + /// + /// Invoke a static method on the specified type by name with parameters + /// + /// The return type of the method + /// The static type to search + /// The name of the method to invoke + /// The method parameters + /// + public static TReturn InvokeMethod(this Type staticType, string methodName, + params object[] methodParams) { + var methodInfo = (methodParams == null + ? staticType + .GetMethodCached(methodName) + : staticType + .GetMethodCached(methodName, methodParams.Select(x => x.GetType()).ToArray())) + ?? throw new Exception($"Could not find method on type {staticType} with the name of {methodName} with the arguments specified."); + + return (TReturn)methodInfo.GetMethodDelegateCached()(null, methodParams); + } + + /// + /// Invoke a method on the specified object by name with parameters + /// + /// The object to invoke the method on + /// The name of the method to invoke + /// + public static void InvokeMethod(this object instance, string methodName, params object[] methodParams) => + instance.InvokeMethod(methodName, methodParams); + + /// + /// Invoke a static method on the specified type by name with parameters + /// + /// The static type to search + /// The name of the method to invoke + /// + public static void InvokeMethod(this Type staticType, string methodName, params object[] methodParams) => + staticType.InvokeMethod(methodName, methodParams); + + + private static FastReflectionDelegate GetMethodDelegateCached(this MethodInfo methodInfo) => + DelegateCache.GetOrAdd(methodInfo, method => method.CreateFastDelegate()); + + #endregion + + #region Class + + /// + /// Gets the constructor on the specified type with specified arguments and caches it + /// + /// The type to search + /// The types of the arguments on the constructor to find + /// + public static ConstructorInfo GetConstructorCached(Type[] argumentTypes) => + GetConstructorCached(typeof(T), argumentTypes); + + /// + /// Gets the constructor on the specified static type with specified arguments and caches it + /// + /// The type to search + /// The types of the arguments on the constructor to find + /// + public static ConstructorInfo GetConstructorCached(this Type T, Type[] argumentTypes) => + ConstructorCache.GetOrAddOnNull((T, argumentTypes), x => x.T.GetConstructor(x.argumentTypes) + ?? throw new Exception($"Could not find {nameof(ConstructorInfo)} on {T.FullName} with the arguments {string.Join(",", argumentTypes.Select(a => a.FullName))}")); + + /// + /// Gets the nested type on the specified type + /// + /// The type to search + /// The name of the nested type to find + /// + public static Type GetNestedType(string name) => + typeof(T).GetNestedTypeCached(name); + + /// + /// Gets the nested type on the specified type + /// + /// The type to search + /// The name of the nested type to find + /// + public static Type GetNestedTypeCached(string name) => + typeof(T).GetNestedTypeCached(name); + + /// + /// Gets the nested type on the specified static type + /// + /// The static type to search + /// The name of the nested type to find + /// + public static Type GetNestedTypeCached(this Type T, string name) => + NestedTypeCache.GetOrAddOnNull((T, name), x => x.T.GetNestedType(x.name, AllFlags) + ?? throw new Exception($"Could not find nested {nameof(Type)} on {T.FullName} with the name {name}")); + + /// + /// Instatiates the specified type + /// + /// The type to instantiate + /// + public static object Instantiate(this Type type) => + Activator.CreateInstance(type, true); + + /// + /// Instatiates the specified type with specified constructor arguments + /// + /// The type to instantiate + /// The constructor arguments + /// + public static object Instantiate(this Type type, params object[] constructorArguments) => + type.GetConstructorCached(constructorArguments.Select(x => x.GetType()).ToArray()) + .Invoke(constructorArguments); + + /// + /// Instantiates the specified generic type + /// + /// The type to instantiate + /// The type of the generic type argument + /// + public static object InstantiateGeneric(this Type typeArgument) => + typeof(TClass).MakeGenericType(typeArgument).Instantiate(); + + /// + /// Instantiates the specified generic types + /// + /// The type to instantiate + /// The types of the generic type arguments + /// + public static object InstantiateGeneric(this Type[] typeArgument) => + typeof(TClass).MakeGenericType(typeArgument).Instantiate(); + + /// + /// Instantiates a list of the specified generic type + /// + /// + /// + public static IList InstantiateList(this Type type) => + (IList)typeof(List<>).MakeGenericType(type).Instantiate(); + + #endregion + + #region Fast Reflection + + private static GetDelegate CreateGetDelegate(this FieldInfo field) { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (!typeof(TReturn).IsAssignableFrom(field.FieldType)) { + throw new Exception($"Field type {field.FieldType} does not match the requested type {typeof(TReturn)}."); + } + + + var method = new DynamicMethodDefinition($"{field} Getter", typeof(TReturn), new[] { typeof(object) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + if (field.DeclaringType.GetTypeInfo().IsValueType) { + il.Emit(OpCodes.Unbox_Any, field.DeclaringType); + } + } + + il.Emit(!field.IsStatic ? OpCodes.Ldfld : OpCodes.Ldsfld, field); + il.Emit(OpCodes.Ret); + + return (GetDelegate)method.Generate().CreateDelegate(typeof(GetDelegate)); + } + + private static SetDelegate CreateSetDelegate(this FieldInfo field) { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (!field.FieldType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {field.FieldType}."); + } + + var method = new DynamicMethodDefinition($"{field} Setter", typeof(void), + new[] { typeof(object), typeof(TValue) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(!field.IsStatic ? OpCodes.Stfld : OpCodes.Stsfld, field); + + il.Emit(OpCodes.Ret); + + return (SetDelegate)method.Generate().CreateDelegate(typeof(SetDelegate)); + } + + private static SetDelegateRef CreateSetDelegateRef(this FieldInfo field) where TInstance : struct { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (field.FieldType != typeof(TValue)) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {field.FieldType}."); + } + + var method = new DynamicMethodDefinition($"{field} SetterByRef", typeof(void), + new[] { typeof(TInstance).MakeByRefType(), typeof(TValue) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(!field.IsStatic ? OpCodes.Stfld : OpCodes.Stsfld, field); + il.Emit(OpCodes.Ret); + + return (SetDelegateRef)method.Generate().CreateDelegate(typeof(SetDelegateRef)); + } + + private static GetDelegate CreateGetDelegate(this PropertyInfo property) { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!typeof(TReturn).IsAssignableFrom(property.PropertyType)) { + throw new Exception($"Field type {property.PropertyType} does not match the requested type {typeof(TReturn)}."); + } + + var method = new DynamicMethodDefinition($"{property} Getter", typeof(TReturn), new[] { typeof(object) }); + var il = method.GetILProcessor(); + + var getMethod = property.GetGetMethod(nonPublic: true); + + if (!getMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Call, getMethod); + il.Emit(OpCodes.Ret); + + return (GetDelegate)method.Generate().CreateDelegate(typeof(GetDelegate)); + } + + private static GetDelegateRef CreateGetDelegate(this PropertyInfo property) where TInstance : struct { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!typeof(TReturn).IsAssignableFrom(property.PropertyType)) { + throw new Exception($"Field type {property.PropertyType} does not match the requested type {typeof(TReturn)}."); + } + + var method = new DynamicMethodDefinition($"{property} Getter", typeof(TReturn), new[] { typeof(TInstance).MakeByRefType() }); + var il = method.GetILProcessor(); + + // Cache this as well? + var getMethod = property.GetGetMethod(nonPublic: true); + + if (!getMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Call, getMethod); + il.Emit(OpCodes.Ret); + + return (GetDelegateRef)method.Generate().CreateDelegate(typeof(GetDelegateRef)); + } + + + private static SetDelegate CreateSetDelegate(this PropertyInfo property) { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!property.PropertyType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {property.PropertyType}."); + } + + var method = new DynamicMethodDefinition($"{property} Setter", typeof(void), + new[] { typeof(object), typeof(TValue) }); + var il = method.GetILProcessor(); + + var setMethod = property.GetSetMethod(true); + + if (!setMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Call, setMethod); + il.Emit(OpCodes.Ret); + + return (SetDelegate)method.Generate().CreateDelegate(typeof(SetDelegate)); + } + + private static SetDelegateRef CreateSetDelegateRef(this PropertyInfo property) where TInstance : struct { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!property.PropertyType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {property.PropertyType}."); + } + + var method = new DynamicMethodDefinition($"{property} SetterByRef", typeof(void), + new[] { typeof(TInstance).MakeByRefType(), typeof(TValue) }); + var il = method.GetILProcessor(); + + var setMethod = property.GetSetMethod(true); + + if (!setMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Call, setMethod); + il.Emit(OpCodes.Ret); + + return (SetDelegateRef)method.Generate().CreateDelegate(typeof(SetDelegateRef)); + } + + // Partial hack from https://github.com/0x0ade/MonoMod/blob/master/MonoMod.Utils/FastReflectionHelper.cs + // to get fast call delegates + //private static CallDelegate GenerateCallDelegate(this MethodInfo method) { + // if (method == null) { + // throw new ArgumentException("Method cannot be null.", nameof(method)); + // } + + // var dmd = new DynamicMethodDefinition( + // $"CallDelegate<{method.Name}>", typeof(object), new[] { typeof(object), typeof(object[]) }); + // var il = dmd.GetILProcessor(); + + // var args = method.GetParameters(); + + // if (!method.IsStatic) { + // il.Emit(OpCodes.Ldarg_0); + // if (method.DeclaringType.GetTypeInfo().IsValueType) { + // il.Emit(OpCodes.Unbox_Any, method.DeclaringType); + // } + // } + + // for (var i = 0; i < args.Length; i++) { + // var argType = args[i].ParameterType; + // var argIsByRef = argType.IsByRef; + // if (argIsByRef) + // argType = argType.GetElementType(); + // var argIsValueType = argType.GetTypeInfo().IsValueType; + + // if (argIsByRef && argIsValueType) { + // // Used later when storing back the reference to the new box in the array. + // il.Emit(OpCodes.Ldarg_1); + // il.EmitFast_Ldc_I4(i); + // } + + // il.Emit(OpCodes.Ldarg_1); + // il.EmitFast_Ldc_I4(i); + + // if (argIsByRef && !argIsValueType) { + // il.Emit(OpCodes.Ldelema, typeof(object)); + // } + // else { + // il.Emit(OpCodes.Ldelem_Ref); + // if (!argIsValueType) continue; + // il.Emit(!argIsByRef ? OpCodes.Unbox_Any : OpCodes.Unbox, argType); + // } + // } + + // if (method.IsFinal || !method.IsVirtual) { + // il.Emit(OpCodes.Call, method); + // } + // else { + // il.Emit(OpCodes.Callvirt, method); + // } + + // var returnType = method.IsConstructor ? method.DeclaringType : method.ReturnType; + // if (returnType != typeof(void)) { + // if (returnType.GetTypeInfo().IsValueType) { + // il.Emit(OpCodes.Box, returnType); + // } + // } + // else { + // il.Emit(OpCodes.Ldnull); + // } + + // il.Emit(OpCodes.Ret); + + // return (CallDelegate) dmd.Generate().CreateDelegate(typeof(CallDelegate)); + //} + + // https://github.com/0x0ade/MonoMod/blob/master/MonoMod.Utils/FastReflectionHelper.cs + public static void EmitFast_Ldc_I4(this ILProcessor il, int value) { + switch (value) { + case -1: + il.Emit(OpCodes.Ldc_I4_M1); + return; + case 0: + il.Emit(OpCodes.Ldc_I4_0); + return; + case 1: + il.Emit(OpCodes.Ldc_I4_1); + return; + case 2: + il.Emit(OpCodes.Ldc_I4_2); + return; + case 3: + il.Emit(OpCodes.Ldc_I4_3); + return; + case 4: + il.Emit(OpCodes.Ldc_I4_4); + return; + case 5: + il.Emit(OpCodes.Ldc_I4_5); + return; + case 6: + il.Emit(OpCodes.Ldc_I4_6); + return; + case 7: + il.Emit(OpCodes.Ldc_I4_7); + return; + case 8: + il.Emit(OpCodes.Ldc_I4_8); + return; + } + + if (value > -129 && value < 128) + il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); + else + il.Emit(OpCodes.Ldc_I4, value); + } + + public static byte ReadLocalIndex(OpCode opCode, object operand) { + if (opCode == OpCodes.Ldloc_0 || opCode == OpCodes.Stloc_0) { + return 0; + } + if (opCode == OpCodes.Ldloc_1 || opCode == OpCodes.Stloc_1) { + return 1; + } + if (opCode == OpCodes.Ldloc_2 || opCode == OpCodes.Stloc_2) { + return 2; + } + if (opCode == OpCodes.Ldloc_3 || opCode == OpCodes.Stloc_3) { + return 3; + } + if (opCode == OpCodes.Ldloc_S || opCode == OpCodes.Stloc_S) { + return (byte)operand; + } + + throw new Exception($"Could not read index for opcode and operand: {opCode} - {operand}"); + } + + #endregion + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource method of type MonoMod.Utils.DynamicMethodDefinition in method "Reflection$GetDelegateRef`2 Reflection.CreateGetDelegate(PropertyInfo)". + +### Severity: +ERROR + +### Procedure: +Reflection$GetDelegateRef`2 Reflection.CreateGetDelegate(PropertyInfo) + +### File: +R2API/Utils/Reflection.cs + +### Key: +Reflection.cs|CreateGetDelegate|DOTNET_RESOURCE_LEAK + +### Hash: +bfc0ebc68cc4be799f26f2fc387c8f4b + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0534/instruction.md b/inferredbugs-0534/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4acabaa5ac6bc10127126d94511e917a7eb19565 --- /dev/null +++ b/inferredbugs-0534/instruction.md @@ -0,0 +1,1068 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** USharp +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using UnrealEngine.Engine; + +namespace UnrealEngine.Runtime +{ + public partial class CodeGenerator + { + private Dictionary structInfos = new Dictionary(); + + // Helper for working with function info to determine function hierarchy (implemented interface functions, + // virtual functions, override functions, redeclared functions, etc) + class FunctionInfo + { + // The function we are working with + UFunction Function { get; set; } + + // The direct super function (used if this is an overridden function) + UFunction SuperFunction { get; set; } + + // The super-most function in a virtual/override chain + UFunction SupermostFunction { get; set; } + + // The original function in the class hierarchy (searched obtained by function name) + // - This can be different to SupermostFunction where the function chain is broken + UFunction OriginalFunction { get; set; } + + void callme() + { + Function.GetSuperFunction(); + } + } + + // Holds onto structure info (UClass, UScriptStruct) and info on if blittable and collapsed functions + class StructInfo + { + private CodeGenerator codeGenerator; + + public bool IsBlueprintType { get; private set; } + public UStruct Struct { get; private set; } + public UScriptStruct ScriptStruct { get; private set; } + public UClass Class { get; private set; } + public bool IsClass { get; private set; } + public bool IsStruct { get; private set; } + public bool IsInterface { get; private set; } + public bool IsBlittable { get; private set; } + + /// + /// This is a struct but it should be generated as a class. + /// + public bool StructAsClass { get; private set; } + + // + private Dictionary allProperties = new Dictionary(); + private Dictionary nonExportableProperties = new Dictionary(); + private Dictionary exportableProperties = new Dictionary(); + + private List allFunctions = new List(); + private List nonExportableFunctions = new List(); + private List exportableFunctions = new List(); + + private List collapsedMembers = new List(); + private Dictionary collapsedMembersByFunction = new Dictionary(); + private Dictionary collapsedMembersByProperty = new Dictionary(); + + private NameConflictInfo conflictInfo; + + public bool HasStaticFunction { get; private set; } + public bool HasStaticNonExportableFunction { get; set; } + + public bool HasContent + { + get { return exportableProperties.Count > 0 || exportableFunctions.Count > 0; } + } + + public StructInfo(CodeGenerator codeGenerator, UStruct unrealStruct, bool isBlueprintType) + { + this.codeGenerator = codeGenerator; + IsBlueprintType = isBlueprintType; + Struct = unrealStruct; + ScriptStruct = unrealStruct as UScriptStruct; + Class = unrealStruct as UClass; + IsClass = Class != null; + IsStruct = ScriptStruct != null; + IsInterface = unrealStruct.IsChildOf(); + + if (IsStruct) + { + // Start with a IsPlainOldData check for initial IsBlittable state. Is this enough? Or too verbose? + // - May need to take into account non-zero constructor / EForceInit constructor if IsBlittable state + // is used for construction. However since IsBlittable is only currently used to determine marshaling + // using FromNative / ToNative on existing memory the ctor check shouldn't be required. + // - The user can use StructDefault.Value if they want a new native default instance of a struct + // which will use the UScriptStruct.IsPODZeroInit check. + IsBlittable = ScriptStruct.StructFlags.HasFlag(EStructFlags.IsPlainOldData); + + if (codeGenerator.Settings.AlwaysGenerateStructsAsClasses) + { + StructAsClass = true; + } + else if (codeGenerator.Settings.StructsAsClassesByPath.Contains(unrealStruct.GetPathName().ToLower())) + { + StructAsClass = true; + } + + if (StructAsClass) + { + // Can't use blittable functions if the struct is being generated as a class + IsBlittable = false; + } + } + } + + /// + /// Post process the struct after adding all of the members + /// + public void PostProcess() + { + if (IsStruct && !StructAsClass) + { + if (IsBlittable) + { + if (codeGenerator.Settings.StructsAsClassesAtXProps_Blittable > 0 && + exportableProperties.Count >= codeGenerator.Settings.StructsAsClassesAtXProps_Blittable) + { + IsBlittable = false; + StructAsClass = true; + } + } + else + { + if (codeGenerator.Settings.StructsAsClassesAtXProps_NonBlittable > 0 && + exportableProperties.Count >= codeGenerator.Settings.StructsAsClassesAtXProps_NonBlittable) + { + StructAsClass = true; + } + } + + if (!StructAsClass) + { + ProjectDefinedType structureType; + if (projectDefinedTypes.TryGetValue(Struct.GetPathName(), out structureType)) + { + if (structureType == ProjectDefinedType.BlittableStruct) + { + IsBlittable = true; + } + else if (structureType == ProjectDefinedType.Struct) + { + IsBlittable = false; + } + } + } + } + } + + public IEnumerable GetProperties() + { + return exportableProperties.Keys; + } + + public IEnumerable GetFunctions() + { + return exportableFunctions; + } + + public IEnumerable GetCollapsedMembers() + { + return collapsedMembers; + } + + public bool IsCollapsedProperty(UProperty property) + { + return collapsedMembersByProperty.ContainsKey(property); + } + + public bool IsCollapsedFunction(UFunction function) + { + return collapsedMembersByFunction.ContainsKey(function); + } + + /// + /// Gets the custom property name (blueprint struct var names) + /// + public string GetPropertyName(UProperty property) + { + string propertyName; + exportableProperties.TryGetValue(property, out propertyName); + return propertyName; + } + + public void AddProperty(UProperty property, string bpVarName, bool exportable) + { + // If the ScriptName metadata is set use that for the property name instead + string scriptName = property.GetMetaData(MDProp.ScriptName); + if (!string.IsNullOrEmpty(scriptName)) + { + bpVarName = scriptName; + } + + allProperties.Add(property, bpVarName); + + if (exportable) + { + exportableProperties.Add(property, bpVarName); + if (IsBlittable && (!codeGenerator.IsBlittablePropertyType(property) || property.IsFixedSizeArray)) + { + IsBlittable = false; + } + } + else + { + nonExportableProperties.Add(property, bpVarName); + + // This property isn't being exported, our struct size wont match the real struct size + IsBlittable = false; + } + } + + public void AddFunction(UFunction function, bool exportable) + { + allFunctions.Add(function); + + if (exportable) + { + exportableFunctions.Add(function); + if (function.HasAnyFunctionFlags(EFunctionFlags.Static)) + { + HasStaticFunction = true; + } + } + else + { + nonExportableFunctions.Add(function); + if (function.HasAnyFunctionFlags(EFunctionFlags.Static)) + { + HasStaticNonExportableFunction = true; + } + } + } + + public void ResolveCollapsedMembers() + { + if (IsInterface || !codeGenerator.Settings.UseCollapsedMembers) + { + // Interface shouldn't have any C# properties, leave everything as functions + ResolveNameConflicts(); + return; + } + + collapsedMembers.Clear(); + collapsedMembersByFunction.Clear(); + collapsedMembersByProperty.Clear(); + + var getters = new Dictionary(); + var setters = new Dictionary(); + + // Conflicts aren't resolved at this point. May have multiple functions for a given name. + // - If there are conflicts avoid collapsing those functions. + Dictionary> gettersByName = new Dictionary>(); + Dictionary> settersByName = new Dictionary>(); + + foreach (UFunction function in exportableFunctions) + { + string functionName = codeGenerator.GetFunctionName(function, false); + + // 1 param either as return value or parameter and no return + if (function.NumParms == 1) + { + UProperty returnProperty = function.GetReturnProperty(); + if (returnProperty != null) + { + // Getter + foreach (var collapsedSetting in codeGenerator.Settings.CollapsedMembers) + { + if (!string.IsNullOrEmpty(collapsedSetting.GetPrefix) && + functionName.StartsWith(collapsedSetting.GetPrefix) && + (!collapsedSetting.RequiresBool || returnProperty.IsA())) + { + getters.Add(function, collapsedSetting); + + string trimmedName = functionName.Substring(collapsedSetting.GetPrefix.Length); + if (trimmedName.Length > 0) + { + List functions; + if (!gettersByName.TryGetValue(trimmedName, out functions)) + { + gettersByName.Add(trimmedName, functions = new List()); + } + functions.Add(function); + } + break; + } + } + } + else + { + // Setter + UProperty firstParam = function.GetFirstParam(); + if (firstParam != null) + { + foreach (var collapsedSetting in codeGenerator.Settings.CollapsedMembers) + { + if (!string.IsNullOrEmpty(collapsedSetting.SetPrefix) && + functionName.StartsWith(collapsedSetting.SetPrefix) && + (!collapsedSetting.RequiresBool || firstParam.IsA())) + { + setters.Add(function, collapsedSetting); + + string trimmedName = functionName.Substring(collapsedSetting.GetPrefix.Length); + if (trimmedName.Length > 0) + { + List functions; + if (!settersByName.TryGetValue(trimmedName, out functions)) + { + settersByName.Add(trimmedName, functions = new List()); + } + functions.Add(function); + } + break; + } + } + } + } + } + } + + for (int i = 0; i < 2; i++) + { + bool isGetter = i == 0; + Dictionary> collection = isGetter ? gettersByName : settersByName; + + foreach (KeyValuePair> funcs in collection) + { + if (funcs.Value.Count != 1) + { + continue; + } + + string name = funcs.Key; + UFunction getter = isGetter ? funcs.Value[0] : null; + UFunction setter = !isGetter ? funcs.Value[0] : null; + CodeGeneratorSettings.CollapsedMemberSettings settings = null; + UProperty paramOrRetValProperty = null; + + Dictionary> otherCollection = isGetter ? settersByName : gettersByName; + List otherFuncs; + if (otherCollection.TryGetValue(funcs.Key, out otherFuncs)) + { + if (otherFuncs.Count > 1) + { + // Other function has a conflict + continue; + } + + if (isGetter) + { + setter = otherFuncs[0]; + } + else + { + getter = otherFuncs[0]; + } + } + + if ((getter != null && collapsedMembersByFunction.ContainsKey(getter)) || + (setter != null && collapsedMembersByFunction.ContainsKey(setter))) + { + continue; + } + + if (getter != null && setter != null) + { + UProperty returnProperty = getter.GetReturnProperty(); + UProperty firstParam = setter.GetFirstParam(); + if (returnProperty != null && firstParam != null && !returnProperty.SameType(firstParam)) + { + // Property type mismatch on Get/Set functions + continue; + } + } + + if (getter != null) + { + paramOrRetValProperty = getter.GetReturnProperty(); + settings = getters[getter]; + } + else if (setter != null) + { + paramOrRetValProperty = setter.GetFirstParam(); + settings = setters[setter]; + } + + if (paramOrRetValProperty == null) + { + continue; + } + + UProperty backingProperty = null; + bool backingPropertyExportable = false; + + foreach (KeyValuePair property in exportableProperties) + { + if (name == codeGenerator.GetMemberName(property.Key, false, property.Value) && + property.Key.SameType(paramOrRetValProperty)) + { + if (backingProperty != null) + { + // Skip conflicts + continue; + } + backingProperty = property.Key; + backingPropertyExportable = true; + } + } + + if (backingProperty == null) + { + foreach (KeyValuePair property in nonExportableProperties) + { + if (name == codeGenerator.GetMemberName(property.Key, false, property.Value) && + property.Key.SameType(paramOrRetValProperty)) + { + if (backingProperty != null) + { + // Skip conflicts + continue; + } + backingProperty = property.Key; + backingPropertyExportable = false; + } + } + } + + if (getter == null && setter != null) + { + // SetXXX exists but there isn't a backing property or the backing property isn't + // exportable so there wouldn't be any way access the property. Leave the function + // as it is rather than creating a setter-only C# property unless the getter is injected. + if (backingProperty == null || (!backingPropertyExportable && !settings.InjectNonExportableProperty)) + { + continue; + } + if (settings.SetRequiresGet) + { + continue; + } + } + else if (getter != null && setter == null) + { + if (settings.GetRequiresSet) + { + continue; + } + } + + if ((getter != null && getter.HasAllFunctionFlags(EFunctionFlags.BlueprintEvent)) || + (setter != null && setter.HasAnyFunctionFlags(EFunctionFlags.BlueprintEvent))) + { + // Skip events as they need a normal method body + continue; + } + + string finalName = name; + if (!settings.StripPrefix && (getter == null || setter == null)) + { + if (getter != null) + { + finalName = settings.GetPrefix + finalName; + } + else if (setter != null) + { + finalName = settings.SetPrefix + finalName; + } + } + + if (backingProperty != null && backingProperty.HasAnyPropertyFlags(EPropertyFlags.BlueprintReadOnly) && + IsCollectionProperty(backingProperty) && setter != null) + { + // If there is a backing property which is a readonly collection and there is a setter method then + // there will be type conflicts. Don't collapse them. + continue; + } + + // Some validation on bool properties + { + UBoolProperty getterReturn = getter == null ? null : getter.GetReturnProperty() as UBoolProperty; + UBoolProperty setterParam = setter == null ? null : setter.GetFirstParam() as UBoolProperty; + + if (getterReturn != null && setterParam != null) + { + System.Diagnostics.Debug.Assert(getterReturn.ElementSize == setterParam.ElementSize, + "Get/Set use different bool size"); + } + + UBoolProperty backingBoolProperty = backingProperty as UBoolProperty; + if (backingBoolProperty != null) + { + if (getter != null) + { + System.Diagnostics.Debug.Assert(backingBoolProperty.ElementSize == getterReturn.ElementSize, + "BackingProperty/Get use different bool size"); + } + else if (setter != null) + { + System.Diagnostics.Debug.Assert(backingBoolProperty.ElementSize == setterParam.ElementSize, + "BackingProperty/Set use different bool size"); + } + } + } + + CollapsedMember collapsedMember = new CollapsedMember(settings); + collapsedMember.BackingProperty = backingProperty; + collapsedMember.IsBackingPropertyExportable = backingPropertyExportable; + collapsedMember.Getter = getter; + collapsedMember.Setter = setter; + collapsedMember.Name = finalName; + collapsedMember.Property = paramOrRetValProperty; + collapsedMembers.Add(collapsedMember); + if (getter != null) + { + collapsedMembersByFunction.Add(getter, collapsedMember); + } + if (setter != null) + { + collapsedMembersByFunction.Add(setter, collapsedMember); + } + if (backingPropertyExportable) + { + collapsedMembersByProperty.Add(backingProperty, collapsedMember); + } + } + } + + ResolveNameConflicts(); + } + + private void ResolveNameConflicts() + { + List baseConflictInfos = new List(); + + UStruct parentStruct = Struct.GetSuperStruct(); + if (parentStruct != null) + { + StructInfo parentInfo = codeGenerator.GetStructInfo(parentStruct); + if (parentInfo != null && parentInfo.conflictInfo != null) + { + baseConflictInfos.Add(parentInfo.conflictInfo); + } + } + + if (Class != null) + { + foreach (FImplementedInterface implementedInterface in Class.Interfaces) + { + UClass interfaceClass = implementedInterface.InterfaceClass; + if (interfaceClass != null) + { + StructInfo interfaceInfo = codeGenerator.GetStructInfo(interfaceClass); + if (interfaceInfo != null && interfaceInfo.conflictInfo != null) + { + baseConflictInfos.Add(interfaceInfo.conflictInfo); + } + } + } + } + + conflictInfo = new NameConflictInfo(this); + + foreach (KeyValuePair property in exportableProperties) + { + conflictInfo.AddMember(property.Key, codeGenerator.GetMemberName(property.Key, false, property.Value)); + } + + foreach (UFunction function in exportableFunctions) + { + // Functions are a special case. They can be redefined in the hierarchy but for name resolving + // we want them to have the same name throughout. Therefore only resolve the base-most function + // name (even if redefined later in the hierarchy). Then when we do a name conflict lookup find that + // base-most function and use that name for all of the functions in the hierarchy with that name. + // - This is lookup is done in ResolveNameConflict(). + if (codeGenerator.GetOriginalFunctionOwner(function) == Class) + { + conflictInfo.AddMember(function, codeGenerator.GetFunctionName(function, false)); + } + } + + foreach (NameConflictInfo baseConflictInfo in baseConflictInfos) + { + foreach (KeyValuePair baseMembersByName in baseConflictInfo.MembersByName) + { + NameConflictFieldInfo baseMembers; + if (!conflictInfo.BaseMembersByName.TryGetValue(baseMembersByName.Key, out baseMembers)) + { + conflictInfo.BaseMembersByName.Add(baseMembersByName.Key, + baseMembers = new NameConflictFieldInfo(baseMembersByName.Key)); + } + + foreach (KeyValuePair baseMember in baseMembersByName.Value.Fields) + { + baseMembers.AddField(baseMember.Key, baseMember.Value); + } + } + + foreach (KeyValuePair baseBaseMembersByName in baseConflictInfo.BaseMembersByName) + { + NameConflictFieldInfo baseBaseMembers; + if (!conflictInfo.BaseMembersByName.TryGetValue(baseBaseMembersByName.Key, out baseBaseMembers)) + { + conflictInfo.BaseMembersByName.Add(baseBaseMembersByName.Key, + baseBaseMembers = new NameConflictFieldInfo(baseBaseMembersByName.Key)); + } + + foreach (KeyValuePair baseBaseMember in baseBaseMembersByName.Value.Fields) + { + baseBaseMembers.AddField(baseBaseMember.Key, baseBaseMember.Value); + } + } + } + + var tempMembersByName = new Dictionary(conflictInfo.MembersByName); + + foreach (KeyValuePair membersByName in tempMembersByName) + { + // What about overridden functions? where do they appear? + if (membersByName.Value.HasConflict() || conflictInfo.BaseMembersByName.ContainsKey(membersByName.Key)) + { + foreach (KeyValuePair field in membersByName.Value.Fields) + { + if (field.Value == null) + { + string hashedName = membersByName.Key + "_" + field.Key.GetPathName().GetHashCode().ToString("X8"); + NameConflictResolved(field.Key, hashedName); + } + } + + foreach (KeyValuePair> collapsedMember in membersByName.Value.FieldsByCollapsedMember) + { + UField field = null; + if (collapsedMember.Key.Getter != null) + { + field = collapsedMember.Key.Getter; + } + else if (collapsedMember.Key.Setter != null) + { + field = collapsedMember.Key.Setter; + } + else if (collapsedMember.Key.BackingProperty != null) + { + field = collapsedMember.Key.BackingProperty; + } + + string hashedName = membersByName.Key + "_" + field.GetPathName().GetHashCode().ToString("X8"); + if (collapsedMember.Key.Getter != null) + { + NameConflictResolved(collapsedMember.Key.Getter, hashedName); + } + if (collapsedMember.Key.Setter != null) + { + NameConflictResolved(collapsedMember.Key.Setter, hashedName); + } + if (collapsedMember.Key.BackingProperty != null) + { + NameConflictResolved(collapsedMember.Key.BackingProperty, hashedName); + } + } + + // All fields with this name should have been renamed. Remove the old name. + conflictInfo.MembersByName.Remove(membersByName.Key); + } + } + } + + private void NameConflictResolved(UField field, string resolvedName) + { + int conflictIndex = -1; + string baseResolvedName = null; + while (conflictInfo.MembersByName.ContainsKey(resolvedName) || conflictInfo.BaseMembersByName.ContainsKey(resolvedName)) + { + // The resolved name has as a conflict (double conflict) - rename until no more conflicts + if (conflictIndex == -1) + { + conflictIndex = 1; + baseResolvedName = resolvedName; + } + + resolvedName = baseResolvedName + "_" + conflictIndex; + conflictIndex++; + } + + conflictInfo.AddResolvedMember(field, resolvedName); + conflictInfo.ResolvedName[field] = resolvedName; + } + + public string ResolveNameConflict(UField field, string name) + { + UFunction function = field as UFunction; + if (function != null) + { + // Functions are a special case and must use the base-most function for name resolving. + // See above for more info on this. + UFunction originalFunction; + UClass originalOwner = codeGenerator.GetOriginalFunctionOwner(function, out originalFunction); + if (originalOwner != Class) + { + StructInfo originalOwnerStructInfo = codeGenerator.GetStructInfo(originalOwner); + return originalOwnerStructInfo.ResolveNameConflict(originalFunction, name); + } + } + + string resolvedName; + if (conflictInfo.ResolvedName.TryGetValue(field, out resolvedName)) + { + return resolvedName; + } + + return name; + } + + class NameConflictInfo + { + private StructInfo structInfo; + + // MembersByName names are updated where there are name conflicts + // BaseMembersByName is set to base types MembersByName (chained to all base types) + public Dictionary BaseMembersByName { get; private set; }// + public Dictionary MembersByName { get; private set; }// + public Dictionary ResolvedName { get; private set; }// + + public NameConflictInfo(StructInfo structInfo) + { + this.structInfo = structInfo; + BaseMembersByName = new Dictionary(); + MembersByName = new Dictionary(); + ResolvedName = new Dictionary(); + } + + public void AddMember(UField field, string name) + { + AddMember(field, name, false); + } + + public void AddResolvedMember(UField field, string name) + { + AddMember(field, name, true); + } + + private void AddMember(UField field, string name, bool isResolvedName) + { + CollapsedMember collapsedMember = null; + + UProperty property = field as UProperty; + if (property != null) + { + structInfo.collapsedMembersByProperty.TryGetValue(property, out collapsedMember); + } + + UFunction function = field as UFunction; + if (function != null) + { + structInfo.collapsedMembersByFunction.TryGetValue(function, out collapsedMember); + } + + if (collapsedMember != null) + { + if (isResolvedName) + { + collapsedMember.ResolvedName = name; + } + else + { + name = collapsedMember.Name; + } + } + + NameConflictFieldInfo fieldInfo; + if (!MembersByName.TryGetValue(name, out fieldInfo)) + { + MembersByName.Add(name, fieldInfo = new NameConflictFieldInfo(name)); + } + fieldInfo.AddField(field, collapsedMember); + } + } + + class NameConflictFieldInfo + { + public string Name { get; set; } + public Dictionary Fields { get; private set; } + public Dictionary> FieldsByCollapsedMember { get; private set; } + + public NameConflictFieldInfo(string name) + { + Name = name; + Fields = new Dictionary(); + FieldsByCollapsedMember = new Dictionary>(); + } + + public IEnumerable GetFields() + { + return Fields.Keys; + } + + public bool IsCollapsed(UField field) + { + CollapsedMember collapsed; + return Fields.TryGetValue(field, out collapsed) && collapsed != null; + } + + public void AddField(UField field, CollapsedMember collapsedMember) + { + Fields[field] = collapsedMember; + if (collapsedMember != null) + { + List fields; + if (!FieldsByCollapsedMember.TryGetValue(collapsedMember, out fields)) + { + FieldsByCollapsedMember.Add(collapsedMember, fields = new List()); + } + fields.Add(field); + } + } + + public bool HasConflict() + { + if (Fields.Count == 1) + { + return false; + } + + if (FieldsByCollapsedMember.Count == 1 && FieldsByCollapsedMember.First().Value.Count == Fields.Count) + { + return false; + } + + return true; + } + } + } + + class CollapsedMember + { + /// + /// The property/field which this targets (null if no property with same name as function) + /// + public UProperty BackingProperty { get; set; } + public bool HasBackingProperty + { + get { return BackingProperty != null; } + } + public bool IsBackingPropertyExportable { get; set; } + + public UFunction Getter { get; set; } + public UFunction Setter { get; set; } + public string Name { get; set; } + + /// + /// If there is a name conflict this will hold the resolved name + /// + public string ResolvedName { get; set; } + + /// + /// Either the return of the Get or the parameter of the Set + /// + public UProperty Property { get; set; } + + public CodeGeneratorSettings.CollapsedMemberSettings Settings { get; private set; } + + public CollapsedMember(CodeGeneratorSettings.CollapsedMemberSettings settings) + { + Settings = settings; + } + } + + private bool IsBlittablePropertyType(UProperty property) + { + return property.IsBlittableType || + (property.IsA() && Settings.UObjectAsBlittableType) || + (property.IsA() && IsBlittableStructProperty(property as UStructProperty)); + } + + private bool IsBlittableStructProperty(UStructProperty property) + { + if (property == null) + { + return false; + } + UStruct unrealStruct = property.Struct; + if (unrealStruct != null) + { + StructInfo structInfo; + if (structInfos.TryGetValue(unrealStruct, out structInfo)) + { + return structInfo.IsBlittable; + } + + structInfo = GetStructInfo(unrealStruct); + return structInfo.IsBlittable; + } + return false; + } + + private string GetBlittablePropertyTypeName(UProperty property) + { + return GetBlittablePropertyTypeName(property, null); + } + + private string GetBlittablePropertyTypeName(UProperty property, List namespaces) + { + if (!IsBlittablePropertyType(property)) + { + return null; + } + + switch (property.PropertyType) + { + case EPropertyType.Name: return Names.FName; + case EPropertyType.Int8: return "sbyte"; + case EPropertyType.Byte: return "byte"; + case EPropertyType.Int16: return "short"; + case EPropertyType.UInt16: return "ushort"; + case EPropertyType.Int: return "int"; + case EPropertyType.UInt32: return "uint"; + case EPropertyType.Int64: return "long"; + case EPropertyType.UInt64: return "ulong"; + case EPropertyType.Float: return "float"; + case EPropertyType.Double: return "double"; + case EPropertyType.Struct: return GetTypeName(property, namespaces); + default: return null; + } + } + + private StructInfo GetStructInfo(UStruct unrealStruct) + { + bool isBlueprintType = unrealStruct.IsA() || unrealStruct.IsA(); + return GetStructInfo(unrealStruct, isBlueprintType); + } + + private StructInfo GetStructInfo(UStruct unrealStruct, bool isBlueprintType) + { + StructInfo structInfo; + if (structInfos.TryGetValue(unrealStruct, out structInfo)) + { + return structInfo; + } + + structInfo = new StructInfo(this, unrealStruct, isBlueprintType); + foreach (UFunction function in unrealStruct.GetFields(false, true, true)) + { + structInfo.AddFunction(function, CanExportFunction(function, isBlueprintType)); + } + + if (isBlueprintType) + { + UUserDefinedStruct userDefinedStruct = unrealStruct as UUserDefinedStruct; + if (userDefinedStruct != null) + { + Dictionary variableNames = GetStructBPVariableNames(userDefinedStruct); + + foreach (UProperty property in unrealStruct.GetFields(false)) + { + structInfo.AddProperty(property, variableNames[property], CanExportProperty(property, unrealStruct, isBlueprintType)); + } + } + else + { + foreach (UProperty property in unrealStruct.GetProperties(false)) + { + structInfo.AddProperty(property, null, CanExportProperty(property, unrealStruct, isBlueprintType)); + } + } + } + else + { + foreach (UProperty property in unrealStruct.GetFields(false)) + { + structInfo.AddProperty(property, null, CanExportProperty(property, unrealStruct, isBlueprintType)); + } + } + + structInfo.ResolveCollapsedMembers(); + structInfo.PostProcess(); + + structInfos.Add(unrealStruct, structInfo); + return structInfo; + } + + private string ResolveNameConflict(UField field, string name) + { + UStruct unrealStruct = field.GetOwnerStruct(); + if ((field as UFunction) != null) + { + // GetOwnerStruct will return itself if it is a UStruct (which is true for UFunction) + unrealStruct = field.GetOwnerClass(); + } + + if (unrealStruct != null) + { + StructInfo structInfo = GetStructInfo(unrealStruct); + if (structInfo != null) + { + return structInfo.ResolveNameConflict(field, name); + } + } + return name; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from UnrealEngine.Runtime.TFieldIterator`1 UnrealEngine.Runtime.UStruct::GetFields(System.Boolean,System.Boolean,System.Boolean) at Line 961) of type UnrealEngine.Runtime.TFieldIterator`1, Leaked resource (returned from UnrealEngine.Runtime.TFieldIterator`1 UnrealEngine.Runtime.UStruct::GetProperties(System.Boolean,System.Boolean,System.Boolean) at Line 968) of type UnrealEngine.Runtime.TFieldIterator`1, Leaked resource (returned from UnrealEngine.Runtime.TFieldIterator`1 UnrealEngine.Runtime.UStruct::GetFields(System.Boolean,System.Boolean,System.Boolean) at Line 976) of type UnrealEngine.Runtime.TFieldIterator`1, Leaked resource (returned from UnrealEngine.Runtime.TFieldIterator`1 UnrealEngine.Runtime.UStruct::GetFields(System.Boolean,System.Boolean,System.Boolean) at Line 949) of type UnrealEngine.Runtime.TFieldIterator`1 in method "CodeGenerator$StructInfo CodeGenerator.GetStructInfo(UStruct,Boolean)". + +### Severity: +ERROR + +### Procedure: +CodeGenerator$StructInfo CodeGenerator.GetStructInfo(UStruct,Boolean) + +### File: +Managed/UnrealEngine.Runtime/UnrealEngine.Runtime/Internal/CodeGenerator/CodeGenerator.StructInfo.cs + +### Key: +CodeGenerator.StructInfo.cs|GetStructInfo|DOTNET_RESOURCE_LEAK + +### Hash: +93a75f6ab85223500d15b871bd44fa11 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0535/instruction.md b/inferredbugs-0535/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4168abea78a347d9e137af645de2fc7300531572 --- /dev/null +++ b/inferredbugs-0535/instruction.md @@ -0,0 +1,190 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** USharp +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace UnrealEngine.Runtime +{ + public partial class CodeGenerator + { + private void AppendAttribute(CSharpTextBuilder builder, UField field, UnrealModuleInfo module, StructInfo structInfo) + { + AppendAttribute(builder, field, module); + //if (field.IsA() && structInfo.StructAsClass) + //{ + // builder.AppendLine("[" + Names.UStructAsClassAttributeShort + "]"); + //} + } + + private void AppendAttribute(CSharpTextBuilder builder, UField field, UnrealModuleInfo module) + { + UnrealModuleType moduleType; + UnrealModuleType moduleAssetType; + string moduleName = GetModuleName(field, out moduleType, out moduleAssetType); + if (string.IsNullOrEmpty(moduleName)) + { + moduleName = module.Name; + } + + List attributes = new List(); + + // TODO: Combine all of this into EPropertyType (add some TypeCode into UField?) + bool isInterface = false; + UEnum unrealEnum = field as UEnum; + UClass unrealClass = field as UClass; + UScriptStruct unrealStruct = field as UScriptStruct; + + UFunction unrealFunction = field as UFunction; + if (unrealFunction != null) + { + attributes.Add("UFunction(Flags=0x" + ((uint)unrealFunction.FunctionFlags).ToString("X8") + ")"); + } + + UProperty unrealProperty = field as UProperty; + if (unrealProperty != null) + { + attributes.Add("UProperty(Flags=(PropFlags)0x" + ((ulong)unrealProperty.PropertyFlags).ToString("X16") + ")"); + } + + if (unrealStruct != null) + { + attributes.Add("UStruct(Flags=0x" + ((uint)unrealStruct.StructFlags).ToString("X8") + ")"); + } + else if (unrealClass != null) + { + // Abstract isn't really required but might help with code browsing to know what is abstract + // and what isn't. Therefore put it at the start of the attributes list. + if (unrealClass.HasAnyClassFlags(EClassFlags.Abstract)) + { + attributes.Add("Abstract"); + } + + isInterface = unrealClass.IsChildOf(); + if (isInterface) + { + attributes.Add("UInterface(Flags=0x" + ((uint)unrealClass.ClassFlags).ToString("X8") + ")"); + } + else + { + // Should we skip "inherit" config name? + string configNameStr = string.Empty; + if (unrealClass.ClassConfigName != FName.None && + !unrealClass.ClassConfigName.ToString().Equals("inherit", StringComparison.InvariantCultureIgnoreCase)) + { + configNameStr = ", Config=\"" + unrealClass.ClassConfigName + "\""; + } + + attributes.Add("UClass(Flags=(ClassFlags)0x" + ((uint)unrealClass.ClassFlags).ToString("X8") + + configNameStr + ")"); + } + } + + if (unrealEnum != null) + { + attributes.Add("UEnum"); + } + + if (unrealEnum != null || unrealClass != null || unrealStruct != null) + { + bool blueprintType = false; + bool blueprintable = false; + if (unrealEnum != null) + { + blueprintType = field.GetBoolMetaData(MDClass.BlueprintType); + } + else + { + GetBlueprintability(field as UStruct, out blueprintType, out blueprintable); + } + if (blueprintType) + { + attributes.Add(UMeta.GetKey(MDClass.BlueprintType)); + } + if (blueprintable) + { + attributes.Add(UMeta.GetKey(MDClass.Blueprintable)); + } + + if (isInterface) + { + } + + attributes.Add("UMetaPath(\"" + field.GetPathName() + "\", \"" + moduleName + + "\", UnrealModuleType." + GetUnrealModuleTypeString(moduleType, moduleAssetType) + + (isInterface ? ", InterfaceImpl=typeof(" + GetTypeName(unrealClass) + "Impl" + ")" : string.Empty) + ")"); + + } + else + { + attributes.Add("UMetaPath(\"" + field.GetPathName() + "\")"); + } + + if (attributes.Count > 0) + { + builder.AppendLine("[" + string.Join(", ", attributes) + "]"); + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `null` is dereferenced by call to `GetPathName(...)` at line 136, column 17. + +### Severity: +ERROR + +### Procedure: +Void CodeGenerator.AppendAttribute(CSharpTextBuilder,UField,CodeGenerator$UnrealModuleInfo,Boolean) + +### File: +Managed/UnrealEngine.Runtime/UnrealEngine.Runtime/Internal/CodeGenerator/CodeGenerator.Attributes.cs + +### Key: +CodeGenerator.Attributes.cs|AppendAttribute|NULL_DEREFERENCE + +### Node Key: +a3c356fd9293cbe0aa600beb1ca2d657 + +### Hash: +c698cc1f6c94a76b74ab8dfce284dd93 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0557/instruction.md b/inferredbugs-0557/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3fc7a5b69e86ceb78b0e7c0a42ee42b2cf2f6aa8 --- /dev/null +++ b/inferredbugs-0557/instruction.md @@ -0,0 +1,391 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Riz.XFramework +**Bug ID:** 7 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp + +using System; +using System.Data; +using System.Linq; +using System.Linq.Expressions; +using System.Collections.Generic; + +namespace TZM.XFramework +{ + /// + /// 扩展帮助类 + /// + public static class XFrameworkExtensions + { + #region 表达式树 + + private static readonly string _anonymousName = "<>h__TransparentIdentifier"; + private static Func _isGrouping = t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IGrouping<,>); + private static Func _isAnonymous = name => !string.IsNullOrEmpty(name) && name.StartsWith(_anonymousName, StringComparison.Ordinal); + + /// + /// 返回真表达式 + /// + public static Expression> True() + where T : class + { + return f => true; + } + + /// + /// 返回假表达式 + /// + public static Expression> False() + where T : class + { + return f => false; + } + + /// + /// 拼接真表达式 + /// + public static Expression> AndAlso(this Expression> TExp1, + Expression> TExp2) where T : class + { + if (TExp1 == null) return TExp2; + if (TExp2 == null) return TExp1; + + var invokeExp = System.Linq.Expressions.Expression.Invoke(TExp2, TExp1.Parameters.Cast()); + return System.Linq.Expressions.Expression.Lambda> + (System.Linq.Expressions.Expression.AndAlso(TExp1.Body, invokeExp), TExp1.Parameters); + } + + /// + /// 拼接假表达式 + /// + public static Expression> OrElse(this Expression> TExp1, + Expression> TExp2) where T : class + { + if (TExp1 == null) return TExp2; + if (TExp2 == null) return TExp1; + + var invokeExp = System.Linq.Expressions.Expression.Invoke(TExp2, TExp1.Parameters.Cast()); + return System.Linq.Expressions.Expression.Lambda> + (System.Linq.Expressions.Expression.OrElse(TExp1.Body, invokeExp), TExp1.Parameters); + } + + /// + /// 去掉一元表达式的操作符 + /// + /// + public static Expression ReduceUnary(this Expression exp) + { + UnaryExpression unaryExpression = exp as UnaryExpression; + return unaryExpression != null + ? unaryExpression.Operand.ReduceUnary() + : exp; + } + + /// + /// 判断表达式链是否能通过动态计算,计算出它的值 + /// + public static bool CanEvaluate(this Expression node) + { + // => 5 + // => a.ActiveDate == DateTime.Now + // => a.State == (byte)state + + if (node == null) return false; + if (node.NodeType == ExpressionType.Constant) return true; + if (node.NodeType == ExpressionType.ArrayIndex) return true; + if (node.NodeType == ExpressionType.Call) + { + // List{0}[] + MethodCallExpression methodCallExpression = node as MethodCallExpression; + Expression expression = methodCallExpression.Object; + //if (expression != null && expression.Type.IsGenericType && expression.Type.GetGenericTypeDefinition() == typeof(List<>) && methodCallExpression.Method.Name == "get_Item") + if (expression != null && Data.TypeUtils.IsCollectionType(expression.Type) && methodCallExpression.Method.Name == "get_Item") + { + return true; + } + } + + var member = node as MemberExpression; + if (member == null) return false; + if (member.Expression == null) return true; + if (member.Expression.NodeType == ExpressionType.Constant) return true; + + return member.Expression.CanEvaluate(); + } + + /// + /// 计算表达式的值 + /// + public static ConstantExpression Evaluate(this Expression e) + { + ConstantExpression node = null; + if (e.NodeType == ExpressionType.Constant) + { + node = e as ConstantExpression; + } + else + { + LambdaExpression lambda = e is LambdaExpression ? Expression.Lambda(((LambdaExpression)e).Body) : Expression.Lambda(e); + Delegate fn = lambda.Compile(); + + node = Expression.Constant(fn.DynamicInvoke(null), e is LambdaExpression ? ((LambdaExpression)e).Body.Type : e.Type); + } + + // 枚举要转成 INT + if (node.Type.IsEnum) node = Expression.Constant(Convert.ToInt32(node.Value)); + + // 返回最终处理的常量表达式s + return node; + } + + /// + /// 判断属性访问表达式是否有系统动态生成前缀 + /// + /// h__TransparentIdentifier.a.CompanyName + /// + /// + public static bool IsAnonymous(this Expression node) + { + // <>h__TransparentIdentifier => h__TransparentIdentifier.a.CompanyName + Expression exp = node; + ParameterExpression paramExp = exp.NodeType == ExpressionType.Lambda + ? (node as LambdaExpression).Parameters[0] + : exp as ParameterExpression; + if (paramExp != null) return _isAnonymous(paramExp.Name); + + if (exp.NodeType == ExpressionType.MemberAccess) // <>h__TransparentIdentifier.a.CompanyName + { + MemberExpression memExp = exp as MemberExpression; + if (_isAnonymous(memExp.Member.Name)) return true; + + return IsAnonymous(memExp.Expression); + } + + return false; + } + + /// + /// 判断是否是分组表达式 + /// + public static bool IsGrouping(this Expression node) + { + //g.Key + //g.Key.CompanyName + //g.Max() + //g=>g.xxx + //g.Key.CompanyId.Length + //g.Key.Length + + // g | g=>g.xx + Expression exp = node; + ParameterExpression paramExp = exp.NodeType == ExpressionType.Lambda + ? (node as LambdaExpression).Parameters[0] + : exp as ParameterExpression; + if (paramExp != null) return _isGrouping(paramExp.Type); + + // g.Max + MethodCallExpression callExp = exp as MethodCallExpression; + if (callExp != null) return _isGrouping(callExp.Arguments[0].Type); + + + MemberExpression memExp = exp as MemberExpression; + if (memExp != null) + { + // g.Key + var g1 = memExp.Member.Name == "Key" && _isGrouping(memExp.Expression.Type); + if (g1) return g1; + + // g.Key.Length | g.Key.Company | g.Key.CompanyId.Length + memExp = memExp.Expression as MemberExpression; + if (memExp != null) + { + g1 = memExp.Member.Name == "Key" && _isGrouping(memExp.Expression.Type) && memExp.Type.Namespace == null; //匿名类没有命令空间 + if (g1) return g1; + } + } + + return false; + } + + /// + /// 在递归访问 MemberAccess 表达式时,判定节点是否能够被继续递归访问 + /// + public static bool Acceptable(this Expression node) + { + // a + // <>h__TransparentIdentifier.a + // <>h__TransparentIdentifier0.<>h__TransparentIdentifier1.a + + if (node.NodeType == ExpressionType.Parameter) return false; + + if (node.NodeType == ExpressionType.MemberAccess) + { + MemberExpression m = node as MemberExpression; + if (m.Expression.NodeType == ExpressionType.Parameter) + { + string name = (m.Expression as ParameterExpression).Name; + if (_isAnonymous(name)) return false; + } + + if (m.Expression.NodeType == ExpressionType.MemberAccess) + { + string name = (m.Expression as MemberExpression).Member.Name; + if (_isAnonymous(name)) return false; + } + } + + return true; + } + + /// + /// 取剔除掉系统动态生成前缀后的表达式 + /// + public static string GetKeyWidthoutAnonymous(this MemberExpression node, bool isDesciptor = false) + { + List segs = new List(); + segs.Add(node.Member.Name); + + Expression expression = node.Expression; + while (expression.Acceptable()) + { + MemberExpression memberExpression = null; + if (expression.NodeType == ExpressionType.MemberAccess) memberExpression = (MemberExpression)expression; + else if (expression.NodeType == ExpressionType.Call) memberExpression = (expression as MethodCallExpression).Object as MemberExpression; + + segs.Add(memberExpression.Member.Name); + expression = memberExpression.Expression; + } + + // 如果读取 + if (expression.NodeType == ExpressionType.Parameter) segs.Add(isDesciptor ? expression.Type.Name : (expression as ParameterExpression).Name); + if (expression.NodeType == ExpressionType.MemberAccess) segs.Add((expression as MemberExpression).Member.Name); + + segs.Reverse(); + string result = string.Join(".", segs); + return result; + } + + #endregion + + #region 列表扩展 + + /// + /// 取指定列表中符合条件的元素索引 + /// + public static int IndexOf(this IEnumerable collection, Func predicate) + { + int i = -1; + foreach (T value in collection) + { + i++; + if (predicate(value)) return i; + } + + return -1; + } + + /// + /// 创建一个集合 + /// + public static List ToList(this IEnumerable collection, Func selector) + { + return collection.Select(selector).ToList(); + } + + /// + /// 列表转换扩展 + /// + public static List ToList(this IEnumerable source, Func selector, Func predicate = null) + { + if (predicate != null) source = source.Where(predicate); + return source.Select(selector).ToList(); + } + + /// + /// 根据页长计算总页码 + /// + /// 数据集合 + /// 页码 + /// + public static int Page(this IEnumerable collection, int pageSize) + { + int count = 0; + if ((collection as ICollection) != null) count = (collection as ICollection).Count; + else if ((collection as T[]) != null) count = (collection as T[]).Length; + else count = collection.Count(); + + int page = (count + pageSize - 1) / pageSize; + return page; + } + + /// + /// 批量添加命令参数 + /// + public static void AddRange(this IDataParameterCollection source, IEnumerable parameters) + { + if (parameters != null) + { + foreach (var p in parameters) source.Add(p); + } + } + + #endregion + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `methodCallExpression` last assigned on line 94 could be null and is dereferenced at line 95, column 17. + +### Severity: +ERROR + +### Procedure: +Boolean XFrameworkExtensions.CanEvaluate(Expression) + +### File: +net45/TZM.XFramework/Common/XFrameworkExtensions.cs + +### Key: +XFrameworkExtensions.cs|CanEvaluate|NULL_DEREFERENCE + +### Node Key: +90535029835413c6e5d1bdebbf52bdf9 + +### Hash: +d37146aef0c1f61eb7f3bdca4b334d37 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0559/instruction.md b/inferredbugs-0559/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..69f58371ca34faa4b5888ed1ea4f2fe9b99edf86 --- /dev/null +++ b/inferredbugs-0559/instruction.md @@ -0,0 +1,139 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Riz.XFramework +**Bug ID:** 16 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Linq.Expressions; + +namespace TZM.XFramework.Data +{ + /// + /// UPDATE 表达式解析器 + /// + public class UpdateExpressionVisitor : ExpressionVisitorBase + { + private IDbQueryProvider _provider = null; + private TableAliasCache _aliases = null; + + /// + /// 初始化 类的新实例 + /// + public UpdateExpressionVisitor(IDbQueryProvider provider, TableAliasCache aliases, Expression exp) + : base(provider, aliases, exp) + { + _provider = provider; + _aliases = aliases; + } + + //{new App() {Id = p.Id}} + protected override Expression VisitMemberInit(MemberInitExpression node) + { + if (node.Bindings == null || node.Bindings.Count == 0) + throw new XFrameworkException("Update at least update one member."); + + for (int index = 0; index < node.Bindings.Count; ++index) + { + MemberAssignment member = node.Bindings[index] as MemberAssignment; + _builder.AppendMember("t0", member.Member.Name); + _builder.Append(" = "); + + if (member.Expression.CanEvaluate()) + _builder.Append(member.Expression.Evaluate().Value, member.Member, node.Type); + //base.VisitConstant(member.Expression.Evaluate(), member.Member); + else + base.Visit(member.Expression); + + if (index < node.Bindings.Count - 1) + { + _builder.Append(","); + _builder.AppendNewLine(); + } + } + return node; + } + + protected override Expression VisitNew(NewExpression node) + { + // 匿名类的New + if (node == null) return node; + if (node.Arguments == null || node.Arguments.Count == 0) + throw new XFrameworkException("Update at least update one member."); + + for (int index = 0; index < node.Arguments.Count; index++) + { + var member = node.Members[index]; + _builder.AppendMember("t0", member.Name); + _builder.Append(" = "); + + if (node.Arguments[index].CanEvaluate()) + _builder.Append(node.Arguments[index].Evaluate().Value, member, node.Type); + else + base.Visit(node.Arguments[index]); + + if (index < node.Arguments.Count - 1) + { + _builder.Append(","); + _builder.AppendNewLine(); + } + } + + return node; + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `member` last assigned on line 32 could be null and is dereferenced at line 33, column 17. + +### Severity: +ERROR + +### Procedure: +Expression UpdateExpressionVisitor.VisitMemberInit(MemberInitExpression) + +### File: +net45/TZM.XFramework/Data/ExpressionVisitor/UpdateExpressionVisitor.cs + +### Key: +UpdateExpressionVisitor.cs|VisitMemberInit|NULL_DEREFERENCE + +### Node Key: +91b8c216590cdce695b1f86e7c48e6c5 + +### Hash: +ca68bae44360dc2f736535b6624c50e9 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0561/instruction.md b/inferredbugs-0561/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b25b25484c975688fc45f0512bb1a60d87cb487b --- /dev/null +++ b/inferredbugs-0561/instruction.md @@ -0,0 +1,278 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Riz.XFramework +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Linq; +using System.Collections.Generic; +using System.Linq.Expressions; + +namespace TZM.XFramework.Data +{ + /// + /// DELETE 或者 UPDATE 语法中的 JOIN 解析成 EXISTS + /// + public class OracleExistsExpressionVisitor : ExpressionVisitorBase + { + private IDbQueryProvider _provider = null; + private List _qJoin = null; + private TableAliasCache _aliases = null; + private DbExpression _where = null; + + /// + /// 初始化 类的新实例 + /// + public OracleExistsExpressionVisitor(IDbQueryProvider provider, TableAliasCache aliases, List qJoin, DbExpression qWhere) + : base(provider, aliases, null, false) + { + _provider = provider; + _qJoin = qJoin; + _aliases = aliases; + _where = qWhere; + } + + /// + /// 将表达式所表示的SQL片断写入SQL构造器 + /// + public void Write(OracleSelectInfoCommand cmd) + { + ISqlBuilder jf = cmd.JoinFragment; + ISqlBuilder on = cmd.OnPhrase; + ISqlBuilder wf = cmd.WhereFragment; + + if (_qJoin != null && _qJoin.Count > 0) + { + for (int i = 0; i < _qJoin.Count; i++) + { + DbExpression qj = _qJoin[i]; + if (qj.DbExpressionType == DbExpressionType.GroupJoin || qj.DbExpressionType == DbExpressionType.Join) + this.AppendLfInJoin(jf, wf, on, qj, _aliases); + else if (qj.DbExpressionType == DbExpressionType.SelectMany) + this.AppendCrossJoin(jf, qj, _aliases); + } + } + } + + // LEFT OR INNER JOIN + private void AppendLfInJoin(ISqlBuilder jf, ISqlBuilder wf, ISqlBuilder on, DbExpression exp, TableAliasCache aliases) + { + bool useExists = false; + LambdaExpression left = exp.Expressions[1] as LambdaExpression; + LambdaExpression right = exp.Expressions[2] as LambdaExpression; + NewExpression body1 = left.Body as NewExpression; + NewExpression body2 = right.Body as NewExpression; + + // t0(t1) + string alias = body1 == null + ? aliases.GetTableAlias(exp.Expressions[2]) + : aliases.GetTableAlias(right.Parameters[0]);//(body2.Arguments[0]); + + IDbQueryable sQuery = (IDbQueryable)((exp.Expressions[0] as ConstantExpression).Value); + if (sQuery.DbExpressions.Count == 1 && sQuery.DbExpressions[0].DbExpressionType == DbExpressionType.GetTable) + { + useExists = true; + if ((wf != null && wf.Length > 0) || (on != null && on.Length > 0)) + { + wf.AppendNewLine(); + if (wf != null && wf.Length > 0) wf.Append("AND "); + } + + wf.Append("EXISTS("); + wf.Indent += 1; + wf.AppendNewLine(); + wf.Append("SELECT 1 FROM "); + + Type type = exp.Expressions[0].Type.GetGenericArguments()[0]; + var typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(type); + wf.AppendMember(typeRuntime.TableName, !typeRuntime.IsTemporary); + wf.Append(' '); + wf.Append(alias); + + wf.AppendNewLine(); + wf.Append("WHERE "); + } + else + { + useExists = true; + if ((wf != null && wf.Length > 0) || (on != null && on.Length > 0)) + { + wf.AppendNewLine(); + if (wf != null && wf.Length > 0) wf.Append("AND "); + } + + wf.Append("EXISTS("); + wf.Indent += 1; + wf.AppendNewLine(); + wf.Append("SELECT 1 FROM("); + var cmd2 = sQuery.Resolve(wf.Indent + 1, false, wf.Parameter); + wf.Append(cmd2.CommandText); + wf.AppendNewLine(); + wf.Append(')'); + wf.Append(' '); + wf.Append(alias); + wf.Append(" WHERE "); + } + + ISqlBuilder builder = useExists ? wf : on; + if (body1 == null) + { + builder.AppendMember(aliases, left.Body.ReduceUnary()); + builder.Append(" = "); + builder.AppendMember(aliases, right.Body.ReduceUnary()); + } + else + { + for (int index = 0; index < body1.Arguments.Count; ++index) + { + builder.AppendMember(aliases, body1.Arguments[index]); + builder.Append(" = "); + builder.AppendMember(aliases, body2.Arguments[index]); + if (index < body1.Arguments.Count - 1) builder.Append(" AND "); + } + } + + //if (_where != null && _where.Expressions != null) this.AppendWhere(builder, right); + + if (useExists) + { + wf.Indent -= 1; + wf.AppendNewLine(); + wf.Append(')'); + } + } + + private void AppendWhere(ISqlBuilder builder, LambdaExpression lambda) + { + ParameterExpression parameter = lambda.Parameters[0]; + Expression expression = _where.Expressions[0]; + List predicates = new List(); + List others = new List(); + + while (expression != null && (expression is BinaryExpression)) + { + bool ignore = false; + BinaryExpression source = expression as BinaryExpression; + + // 找出对应的表别名 + BinaryExpression rightBinary = source.Right as BinaryExpression; + BinaryExpression binary = rightBinary != null ? rightBinary : source; + + Expression right = binary.Left.CanEvaluate() ? binary.Right : binary.Left; + while (right != null && right.Acceptable()) + { + MemberExpression m = right as MemberExpression; + if (m != null) right = m.Expression; + else right = null; + } + if (right != null && right.NodeType == ExpressionType.MemberAccess) + { + MemberExpression m = right as MemberExpression; + if (m.Member.Name == parameter.Name) + { + predicates.Add(binary); + ignore = true; + } + } + + expression = source.Left; + others.Add(new SegExpression + { + Ignore = ignore, + NodeType = source.NodeType, + Expression = binary + }); + } + + if (predicates.Count > 0) + { + Expression body = predicates[0]; + for (int i = 1; i < predicates.Count; i++) + { + if (predicates[i] != null) body = Expression.And(body, predicates[i]); + } + + OracleWhereExpressionVisitor visitor = new OracleWhereExpressionVisitor(_provider, _aliases, new DbExpression(DbExpressionType.Where, body)); + visitor.Write(builder); + } + + //if (others.Any(x => x.Ignore)) + //{ + // Expression body = null; + // for(int ) + //} + } + + // Cross Join + private void AppendCrossJoin(ISqlBuilder jf, DbExpression exp, TableAliasCache aliases) + { + throw new NotSupportedException("Oracle not support."); + } + + class SegExpression + { + public bool Ignore { get; set; } + + public ExpressionType NodeType { get; set; } + + public Expression Expression { get; set; } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `left` last assigned on line 56 could be null and is dereferenced at line 58, column 13. + +### Severity: +ERROR + +### Procedure: +Void OracleExistsExpressionVisitor.AppendLfInJoin(ISqlBuilder,ISqlBuilder,ISqlBuilder,DbExpression,TableAliasCache) + +### File: +net45/TZM.XFramework.Oracle/Data/ExpressionVisitor/OracleExistsExpressionVisitor.cs + +### Key: +OracleExistsExpressionVisitor.cs|AppendLfInJoin|NULL_DEREFERENCE + +### Node Key: +4c5a0b70536cd3f04e9da256c6c8ae68 + +### Hash: +c0c15c996196ad3d069f9f39b112a221 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0566/instruction.md b/inferredbugs-0566/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f20fb273180e319b9ad8f2592bc1671829a2d087 --- /dev/null +++ b/inferredbugs-0566/instruction.md @@ -0,0 +1,629 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Riz.XFramework +**Bug ID:** 19 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Data; +using System.Linq.Expressions; +using System.Collections.Generic; + +namespace TZM.XFramework.Data +{ + /// + /// 选择列表达式解析器 + /// + public class ColumnExpressionVisitor : ExpressionVisitorBase + { + private static IDictionary _statisMethods = null; + private IDbQueryProvider _provider = null; + private TableAliasCache _aliases = null; + private IDbQueryableInfo_Select _qQuery = null; + private DbExpression _groupBy = null; + private List _include = null; + + private ColumnCollection _pickColumns = null; + private NavigationCollection _navigations = null; + private List _navChainHopper = null; + private int _startLength = 0; + private string _pickColumnText = null; + + /// + /// 选中字段,Column 对应实体的原始属性 + /// + public ColumnCollection PickColumns + { + get { return _pickColumns; } + } + + /// + /// 选中字段的文本,给 Contains 表达式用 + /// + public string PickColumnText + { + get + { + if (_pickColumnText == null) + { + int count = _builder.Length - _startLength; + if (count > 0) + { + char[] chars = new char[count]; + _builder.CopyTo(_startLength, chars, 0, count); + _pickColumnText = new String(chars); + } + } + + return _pickColumnText; + } + } + + /// + /// 导航属性描述信息 + /// + /// 从 到实体的映射需要使用这些信息来给导航属性赋值 + /// + /// + public NavigationCollection Navigations + { + get { return _navigations; } + } + + static ColumnExpressionVisitor() + { + _statisMethods = new Dictionary + { + { DbExpressionType.Count,"COUNT" }, + { DbExpressionType.Max,"MAX" }, + { DbExpressionType.Min,"MIN" }, + { DbExpressionType.Average,"AVG" }, + { DbExpressionType.Sum,"SUM" } + }; + } + + /// + /// 初始化 类的新实例 + /// + public ColumnExpressionVisitor(IDbQueryProvider provider, TableAliasCache aliases, IDbQueryableInfo_Select qQuery) + : base(provider, aliases, qQuery.SelectExpression.Expressions != null ? qQuery.SelectExpression.Expressions[0] : null) + { + _provider = provider; + _aliases = aliases; + _qQuery = qQuery; + _groupBy = qQuery.GroupByExpression; + _include = qQuery.Includes; + + if (_pickColumns == null) _pickColumns = new ColumnCollection(); + _navigations = new NavigationCollection(); + _navChainHopper = new List(10); + } + + /// + /// 将表达式所表示的SQL片断写入SQL构造器 + /// + public override void Write(ISqlBuilder builder) + { + if (base.Expression != null) + { + base._builder = builder; + _builder.AppendNewLine(); + _startLength = _builder.Length; + if (base._methodVisitor == null) base._methodVisitor = _provider.CreateMethodVisitor(this); + + // SELECT 表达式解析 + if (base.Expression.NodeType != ExpressionType.Constant) base.Write(builder); + else + { + // if have no select syntax + Type type = (base.Expression as ConstantExpression).Value as Type; + this.VisitAllMember(type, "t0"); + } + // Include 表达式解析<导航属性> + this.VisitInclude(); + // 去掉空白字符 + _builder.TrimEnd(' ', ','); + } + } + + // p=>p p=>p.t p=>p.Id + protected override Expression VisitLambda(Expression node) + { + LambdaExpression lambda = node as LambdaExpression; + if (lambda.Body.NodeType == ExpressionType.Parameter) + { + // 例: a=> a + Type type = lambda.Body.Type; + string alias = _aliases.GetTableAlias(lambda); + this.VisitAllMember(type, alias); + return node; + } + else if (lambda.Body.CanEvaluate()) + { + // 例:a=>1 + base.Visit(lambda.Body.Evaluate()); + + // 选择字段 + string newName = _pickColumns.Add(Constant.CONSTANTNAME); + // 添加字段别名 + _builder.AppendAs(newName); + return node; + } + else if (lambda.Body.NodeType == ExpressionType.MemberAccess) + { + // 例: t=> t.a + // => SELECT a.ClientId + Type type = lambda.Body.Type; + if (!TypeUtils.IsPrimitiveType(type)) return this.VisitAllMember(type, _aliases.GetTableAlias(lambda.Body), node); + else + { + var newNode = this.VisitWithoutRemark(x => base.VisitLambda(node)); + string newName = _pickColumns.Add((lambda.Body as MemberExpression).Member.Name); + return newNode; + } + } + else + { + return base.VisitLambda(node); + } + } + + // => new App() {Id = p.Id}} + protected override Expression VisitMemberInit(MemberInitExpression node) + {// 如果有一对多的导航属性会产生嵌套的SQL,这时需要强制主表选择的列里面必须包含导航外键 + // TODO #对 Bindings 进行排序,保证导航属性的赋值一定要最后面# + // 未实现,在书写表达式时人工保证 ## + + if (node.NewExpression != null) this.VisitNewImpl(node.NewExpression); + if (_navChainHopper.Count == 0) _navChainHopper.Add(node.Type.Name); + + for (int i = 0; i < node.Bindings.Count; i++) + { + MemberAssignment binding = node.Bindings[i] as MemberAssignment; + if (binding == null) throw new XFrameworkException("Only 'MemberAssignment' binding supported."); + + Type propertyType = (node.Bindings[i].Member as System.Reflection.PropertyInfo).PropertyType; + bool isNavigation = !TypeUtils.IsPrimitiveType(propertyType); + + #region 一般属性 + + // 非导航属性 + if (!isNavigation) + { + if (binding.Expression.CanEvaluate()) + _builder.Append(binding.Expression.Evaluate().Value, binding.Member, node.Type); + else + this.VisitWithoutRemark(x => this.VisitMemberBinding(binding)); + + // 选择字段 + string newName = _pickColumns.Add(binding.Member.Name); + // 添加字段别名 + _builder.AppendAs(newName); + _builder.Append(','); + _builder.AppendNewLine(); + } + + #endregion 一般属性 + + #region 导航属性 + + else + { + // 非显式指定的导航属性需要有 ForeignKeyAttribute + if (binding.Expression.NodeType == ExpressionType.MemberAccess && binding.Expression.Acceptable()) + { + var typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(binding.Member.DeclaringType); + var attribute = typeRuntime.GetInvokerAttribute(binding.Member.Name); + if (attribute == null) throw new XFrameworkException("Complex property {{{0}}} must mark 'ForeignKeyAttribute' ", binding.Member.Name); + } + + // 生成导航属性描述集合,以类名.属性名做为键值 + int n = _navChainHopper.Count; + string keyName = _navChainHopper.Count > 0 ? _navChainHopper[_navChainHopper.Count - 1] : string.Empty; + keyName = !string.IsNullOrEmpty(keyName) ? keyName + "." + binding.Member.Name : binding.Member.Name; + Navigation nav = new Navigation(keyName, binding.Member); + if (!_navigations.ContainsKey(keyName)) + { + // fix issue# XC 列占一个位 + nav.Start = _pickColumns.Count; + nav.FieldCount = GetFieldCount(binding.Expression) + (binding.Expression.NodeType == ExpressionType.MemberAccess && binding.Expression.Acceptable() ? 1 : 0); + _navigations.Add(keyName, nav); + _navChainHopper.Add(keyName); + } + + // 1.不显式指定导航属性,例:a.Client.ClientList + // 2.表达式里显式指定导航属性,例:b + if (binding.Expression.NodeType == ExpressionType.MemberAccess) this.VisitNavigation(binding.Expression as MemberExpression, binding.Expression.Acceptable()); + else if (binding.Expression.NodeType == ExpressionType.New) this.VisitNewImpl(binding.Expression as NewExpression); + else if (binding.Expression.NodeType == ExpressionType.MemberInit) this.VisitMemberInit(binding.Expression as MemberInitExpression); + + // 恢复访问链 + // 在访问导航属性时可能是 Client.CloudServer,这时要恢复为 Client,以保证能访问 Client 的下一个导航属性 + if (_navChainHopper.Count != n) _navChainHopper.RemoveAt(_navChainHopper.Count - 1); + } + + #endregion 导航属性 + } + + return node; + } + + // => Client = a.Client.CloudServer + private Expression VisitNavigation(MemberExpression node, bool visitNavigation) + { + string alias = string.Empty; + Type type = node.Type; + + if (node.Acceptable()) + { + // 例: Client = a.Client.CloudServer + // fix issue# Join 表达式显式指定导航属性时时,alias 为空 + // fix issue# 多个导航属性时 AppendNullColumn 只解析当前表达式的 + int index = 0; + int num = this.NavMembers != null ? this.NavMembers.Count : 0; + alias = this.VisitNavMember(node); + + if (num != this.NavMembers.Count) + { + foreach (var kvp in NavMembers) + { + index += 1; + if (index < NavMembers.Count && index > num) alias = _aliases.GetNavigationTableAlias(kvp.Key); + else + { + alias = _aliases.GetNavigationTableAlias(kvp.Key); + type = kvp.Value.Type; + } + } + } + else + { + } + } + else + { + // 例: Client = b + alias = _aliases.GetTableAlias(node); + type = node.Type; + } + + if (type.IsGenericType) type = type.GetGenericArguments()[0]; + this.VisitAllMember(type, alias); + if (visitNavigation) AddSplitOnColumn(node.Member, alias); + + return node; + } + + // => new {Id = p.Id} + protected override Expression VisitNew(NewExpression node) + { + // TODO 未支持匿名类的导航属性 + // MemberInit的New + // 匿名类的New + if (node == null) return node; + if (node.Arguments == null || node.Arguments.Count == 0) + throw new XFrameworkException("'NewExpression' do not have any argument."); + + this.VisitNewImpl(node); + + return node; + } + + // 遍历New表达式的参数集 + private Expression VisitNewImpl(NewExpression node) + { + for (int i = 0; i < node.Arguments.Count; i++) + { + Expression expression = node.Arguments[i]; + Type type = expression.Type; + int visitedQty = _visitedMark.Count; + + if (expression.NodeType == ExpressionType.Parameter) + { + //例: new Client(a) + string alias = _aliases.GetTableAlias(expression); + this.VisitAllMember(type, alias); + } + else if (expression.CanEvaluate()) + { + //例: DateTime.Now + _builder.Append(expression.Evaluate().Value, node.Members[i], node.Type); + this.VisitNewImpl_AddNewName(node.Members != null ? node.Members[i].Name : (expression as MemberExpression).Member.Name); + } + else if (expression.NodeType == ExpressionType.MemberAccess || expression.NodeType == ExpressionType.Call) + { + bool isNavigation = !type.IsEnum && !TypeUtils.IsPrimitiveType(type); + if (isNavigation) this.VisitNavigation(expression as MemberExpression, false); + else + { + // new Client(a.ClientId) + this.Visit(expression); + this.VisitNewImpl_AddNewName(node.Members != null ? node.Members[i].Name : (expression as MemberExpression).Member.Name); + } + } + else + { + base.Visit(expression); + this.VisitNewImpl_AddNewName(node.Members != null ? node.Members[i].Name : (expression as MemberExpression).Member.Name); + } + + // 删除本次访问的成员痕迹 + if (_visitedMark.Count != visitedQty) _visitedMark.Remove(_visitedMark.Count - visitedQty); + } + + return node; + } + + private void VisitNewImpl_AddNewName(string memberName) + { + string newName = _pickColumns.Add(memberName); + _builder.AppendAs(newName); + _builder.Append(','); + _builder.AppendNewLine(); + } + + // g.Key.CompanyName & g.Max(a) + protected override Expression VisitMember(MemberExpression node) + { + if (node == null) return node; + else if (_groupBy == null || !node.IsGrouping()) return base.VisitMember(node); + else + { + // Group By 解析 CompanyName = g.Key.Name + LambdaExpression keySelector = _groupBy.Expressions[0] as LambdaExpression; + Expression exp = null; + Expression body = keySelector.Body; + + if (body.NodeType == ExpressionType.MemberAccess) + { + // group xx by a.CompanyName + exp = body; + + // + // + // + // + } + else if (body.NodeType == ExpressionType.New) + { + // group xx by new { Name = a.CompanyName } + + string memberName = node.Member.Name; + NewExpression newExp = body as NewExpression; + int index = newExp.Members.IndexOf(x => x.Name == memberName); + exp = newExp.Arguments[index]; + } + + return this.Visit(exp); + } + } + + // 选择所有的字段 + private Expression VisitAllMember(Type type, string alias, Expression node = null) + { + if (_groupBy != null && node != null && node.IsGrouping()) + { + // select g.Key + LambdaExpression keySelector = _groupBy.Expressions[0] as LambdaExpression; + return this.Visit(keySelector.Body); + } + else + { + TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(type); + MemberInvokerCollection invokers = typeRuntime.Invokers; + + foreach (var invoker in invokers) + { + if (invoker != null && invoker.Column != null && invoker.Column.NoMapped) continue; + if (invoker != null && invoker.ForeignKey != null) continue; // 不加载导航属性 + if (invoker.Member.MemberType == System.Reflection.MemberTypes.Method) continue; + + _builder.AppendMember(alias, invoker.Member.Name); + + // 选择字段 + string newName = _pickColumns.Add(invoker.Member.Name); + _builder.AppendAs(newName); + _builder.Append(","); + _builder.AppendNewLine(); + } + } + + return node; + } + + // g.Max(a=>a.Level) + protected override Expression VisitMethodCall(MethodCallExpression node) + { + if (_groupBy != null && node.IsGrouping()) + { + DbExpressionType dbExpressionType = DbExpressionType.None; + Enum.TryParse(node.Method.Name, out dbExpressionType); + Expression exp = dbExpressionType == DbExpressionType.Count + ? Expression.Constant(1) + : (node.Arguments.Count == 1 ? null : node.Arguments[1]); + if (exp.NodeType == ExpressionType.Lambda) exp = (exp as LambdaExpression).Body; + + // 如果是 a=> a 这种表达式,那么一定会指定 elementSelector + if (exp.NodeType == ExpressionType.Parameter) exp = _groupBy.Expressions[1]; + + _builder.Append(_statisMethods[dbExpressionType]); + _builder.Append("("); + this.Visit(exp); + _builder.Append(")"); + + return node; + } + + return base.VisitMethodCall(node); + } + + // 遍历 Include 包含的导航属性 + private void VisitInclude() + { + if (_include == null || _include.Count == 0) return; + + foreach (var dbExpression in _include) + { + Expression exp = dbExpression.Expressions[0]; + if (exp == null) continue; + + if (exp.NodeType == ExpressionType.Lambda) exp = (exp as LambdaExpression).Body; + MemberExpression memberExpression = exp as MemberExpression; + if (memberExpression == null) throw new XFrameworkException("Include expression body must be 'MemberExpression'."); + + // 例:Include(a => a.Client.AccountList[0].Client) + // 解析导航属性链 + List chain = new List(); + while (memberExpression != null) + { + // a.Client 要求 必须标明 ForeignKeyAttribute + TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(memberExpression.Expression.Type); + ForeignKeyAttribute attribute = typeRuntime.GetInvokerAttribute(memberExpression.Member.Name); + if (attribute == null) throw new XFrameworkException("Include member {{{0}}} must mark 'ForeignKeyAttribute'.", memberExpression); + + MemberExpression m = null; + chain.Add(memberExpression); + if (memberExpression.Expression.NodeType == ExpressionType.MemberAccess) m = (MemberExpression)memberExpression.Expression; + else if (memberExpression.Expression.NodeType == ExpressionType.Call) m = (memberExpression.Expression as MethodCallExpression).Object as MemberExpression; + + //var m = memberExpression.Expression as MemberExpression; + if (m == null) chain.Add(memberExpression.Expression); + memberExpression = m; + } + + // 生成导航属性描述信息 + string keyName = string.Empty; + for (int i = chain.Count - 1; i >= 0; i--) + { + Expression expression = chain[i]; + memberExpression = expression as MemberExpression; + if (memberExpression == null) continue; + + keyName = memberExpression.GetKeyWidthoutAnonymous(true); + if (!_navigations.ContainsKey(keyName)) + { + // fix issue# XC 列占一个位 + Navigation descriptor = new Navigation(keyName, memberExpression.Member); + descriptor.Start = i == 0 ? _pickColumns.Count : -1;//_columns.Count; + descriptor.FieldCount = i == 0 ? (GetFieldCount(exp) + 1) : -1; //i == 0 ? (GetFieldCount(exp) + 1) : 1;//-1; + _navigations.Add(keyName, descriptor); + } + } + + this.VisitNavigation(memberExpression, true); + } + } + + // 添加额外列,用来判断整个(左)连接记录是否为空 + private void AddSplitOnColumn(System.Reflection.MemberInfo member, string alias) + { + TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(member.DeclaringType); + var foreignKey = typeRuntime.GetInvokerAttribute(member.Name); + string keyName = foreignKey.OuterKeys[0]; + + _builder.Append("CASE WHEN "); + _builder.AppendMember(alias, keyName); + _builder.Append(" IS NULL THEN NULL ELSE "); + _builder.AppendMember(alias, keyName); + _builder.Append(" END"); + + // 选择字段 + string newName = _pickColumns.Add(Constant.NAVIGATIONSPLITONNAME); + //_builder.Append(caseWhen); + _builder.AppendAs(newName); + _builder.Append(','); + _builder.AppendNewLine(); + } + + // 计算数据库字段数量 + private static int GetFieldCount(Expression node) + { + int num = 0; + + switch (node.NodeType) + { + case ExpressionType.MemberInit: + MemberInitExpression m = node as MemberInitExpression; + foreach (var exp in m.NewExpression.Arguments) num += _typeFieldAggregator(exp); + foreach (MemberAssignment ma in m.Bindings) num += _primitiveAggregator((ma.Member as System.Reflection.PropertyInfo).PropertyType); + + break; + + case ExpressionType.MemberAccess: + MemberExpression m1 = node as MemberExpression; + num += _typeFieldAggregator(m1); + + break; + + case ExpressionType.New: + NewExpression m2 = node as NewExpression; + foreach (var exp in m2.Arguments) num += _typeFieldAggregator(exp); + if (m2.Members != null) foreach (var member in m2.Members) num += _primitiveAggregator((member as System.Reflection.PropertyInfo).PropertyType); + + break; + } + + return num; + } + + private static Func _typeFieldAggregator = exp => + exp.NodeType == ExpressionType.MemberAccess && TypeUtils.IsPrimitiveType(exp.Type) ? 1 : TypeRuntimeInfoCache.GetRuntimeInfo(exp.Type.IsGenericType ? exp.Type.GetGenericArguments()[0] : exp.Type).DataFieldCount; + + private static Func _primitiveAggregator = type => TypeUtils.IsPrimitiveType(type) ? 1 : 0; + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `m` last assigned on line 551 could be null and is dereferenced at line 552, column 41. + +### Severity: +ERROR + +### Procedure: +Int32 ColumnExpressionVisitor.GetFieldCount(Expression) + +### File: +net45/TZM.XFramework/Data/ExpressionVisitor/ColumnExpressionVisitor.cs + +### Key: +ColumnExpressionVisitor.cs|GetFieldCount|NULL_DEREFERENCE + +### Node Key: +5f6bc9a45b87a0bd98569135266c4d99 + +### Hash: +08416c86aa4443e21270e63dcd70c65c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0568/instruction.md b/inferredbugs-0568/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bd5a31767ce1c69baee71b336cd0e6db849177ec --- /dev/null +++ b/inferredbugs-0568/instruction.md @@ -0,0 +1,390 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Riz.XFramework +**Bug ID:** 8 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp + +using System; +using System.Data; +using System.Linq; +using System.Linq.Expressions; +using System.Collections.Generic; + +namespace TZM.XFramework +{ + /// + /// 扩展帮助类 + /// + public static class XFrameworkExtensions + { + #region 表达式树 + + private static readonly string _anonymousName = "<>h__TransparentIdentifier"; + private static Func _isGrouping = t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IGrouping<,>); + private static Func _isAnonymous = name => !string.IsNullOrEmpty(name) && name.StartsWith(_anonymousName, StringComparison.Ordinal); + + /// + /// 返回真表达式 + /// + public static Expression> True() + where T : class + { + return f => true; + } + + /// + /// 返回假表达式 + /// + public static Expression> False() + where T : class + { + return f => false; + } + + /// + /// 拼接真表达式 + /// + public static Expression> AndAlso(this Expression> TExp1, + Expression> TExp2) where T : class + { + if (TExp1 == null) return TExp2; + if (TExp2 == null) return TExp1; + + var invokeExp = System.Linq.Expressions.Expression.Invoke(TExp2, TExp1.Parameters.Cast()); + return System.Linq.Expressions.Expression.Lambda> + (System.Linq.Expressions.Expression.AndAlso(TExp1.Body, invokeExp), TExp1.Parameters); + } + + /// + /// 拼接假表达式 + /// + public static Expression> OrElse(this Expression> TExp1, + Expression> TExp2) where T : class + { + if (TExp1 == null) return TExp2; + if (TExp2 == null) return TExp1; + + var invokeExp = System.Linq.Expressions.Expression.Invoke(TExp2, TExp1.Parameters.Cast()); + return System.Linq.Expressions.Expression.Lambda> + (System.Linq.Expressions.Expression.OrElse(TExp1.Body, invokeExp), TExp1.Parameters); + } + + /// + /// 去掉一元表达式的操作符 + /// + /// + public static Expression ReduceUnary(this Expression exp) + { + UnaryExpression unaryExpression = exp as UnaryExpression; + return unaryExpression != null + ? unaryExpression.Operand.ReduceUnary() + : exp; + } + + /// + /// 判断表达式链是否能通过动态计算,计算出它的值 + /// + public static bool CanEvaluate(this Expression node) + { + // => 5 + // => a.ActiveDate == DateTime.Now + // => a.State == (byte)state + + if (node == null) return false; + if (node.NodeType == ExpressionType.Constant) return true; + if (node.NodeType == ExpressionType.ArrayIndex) return true; + if (node.NodeType == ExpressionType.Call) + { + // List{0}[] + MethodCallExpression methodCallExpression = node as MethodCallExpression; + Expression expression = methodCallExpression.Object; + if (expression != null && Data.TypeUtils.IsCollectionType(expression.Type) && methodCallExpression.Method.Name == "get_Item") + { + return true; + } + } + + var member = node as MemberExpression; + if (member == null) return false; + if (member.Expression == null) return true; + if (member.Expression.NodeType == ExpressionType.Constant) return true; + + return member.Expression.CanEvaluate(); + } + + /// + /// 计算表达式的值 + /// + public static ConstantExpression Evaluate(this Expression e) + { + ConstantExpression node = null; + if (e.NodeType == ExpressionType.Constant) + { + node = e as ConstantExpression; + } + else + { + LambdaExpression lambda = e is LambdaExpression ? Expression.Lambda(((LambdaExpression)e).Body) : Expression.Lambda(e); + Delegate fn = lambda.Compile(); + + node = Expression.Constant(fn.DynamicInvoke(null), e is LambdaExpression ? ((LambdaExpression)e).Body.Type : e.Type); + } + + // 枚举要转成 INT + if (node.Type.IsEnum) node = Expression.Constant(Convert.ToInt32(node.Value)); + + // 返回最终处理的常量表达式s + return node; + } + + /// + /// 判断属性访问表达式是否有系统动态生成前缀 + /// + /// h__TransparentIdentifier.a.CompanyName + /// + /// + public static bool IsAnonymous(this Expression node) + { + // <>h__TransparentIdentifier => h__TransparentIdentifier.a.CompanyName + Expression exp = node; + ParameterExpression paramExp = exp.NodeType == ExpressionType.Lambda + ? (node as LambdaExpression).Parameters[0] + : exp as ParameterExpression; + if (paramExp != null) return _isAnonymous(paramExp.Name); + + if (exp.NodeType == ExpressionType.MemberAccess) // <>h__TransparentIdentifier.a.CompanyName + { + MemberExpression memExp = exp as MemberExpression; + if (_isAnonymous(memExp.Member.Name)) return true; + + return IsAnonymous(memExp.Expression); + } + + return false; + } + + /// + /// 判断是否是分组表达式 + /// + public static bool IsGrouping(this Expression node) + { + //g.Key + //g.Key.CompanyName + //g.Max() + //g=>g.xxx + //g.Key.CompanyId.Length + //g.Key.Length + + // g | g=>g.xx + Expression exp = node; + ParameterExpression paramExp = exp.NodeType == ExpressionType.Lambda + ? (node as LambdaExpression).Parameters[0] + : exp as ParameterExpression; + if (paramExp != null) return _isGrouping(paramExp.Type); + + // g.Max + MethodCallExpression callExp = exp as MethodCallExpression; + if (callExp != null) return _isGrouping(callExp.Arguments[0].Type); + + + MemberExpression memExp = exp as MemberExpression; + if (memExp != null) + { + // g.Key + var g1 = memExp.Member.Name == "Key" && _isGrouping(memExp.Expression.Type); + if (g1) return g1; + + // g.Key.Length | g.Key.Company | g.Key.CompanyId.Length + memExp = memExp.Expression as MemberExpression; + if (memExp != null) + { + g1 = memExp.Member.Name == "Key" && _isGrouping(memExp.Expression.Type) && memExp.Type.Namespace == null; //匿名类没有命令空间 + if (g1) return g1; + } + } + + return false; + } + + /// + /// 在递归访问 MemberAccess 表达式时,判定节点是否能够被继续递归访问 + /// + public static bool Acceptable(this Expression node) + { + // a + // <>h__TransparentIdentifier.a + // <>h__TransparentIdentifier0.<>h__TransparentIdentifier1.a + + if (node.NodeType == ExpressionType.Parameter) return false; + + if (node.NodeType == ExpressionType.MemberAccess) + { + MemberExpression m = node as MemberExpression; + if (m.Expression.NodeType == ExpressionType.Parameter) + { + string name = (m.Expression as ParameterExpression).Name; + if (_isAnonymous(name)) return false; + } + + if (m.Expression.NodeType == ExpressionType.MemberAccess) + { + string name = (m.Expression as MemberExpression).Member.Name; + if (_isAnonymous(name)) return false; + } + } + + return true; + } + + /// + /// 取剔除掉系统动态生成前缀后的表达式 + /// + public static string GetKeyWidthoutAnonymous(this MemberExpression node, bool isDesciptor = false) + { + List segs = new List(); + segs.Add(node.Member.Name); + + Expression expression = node.Expression; + while (expression.Acceptable()) + { + MemberExpression memberExpression = null; + if (expression.NodeType == ExpressionType.MemberAccess) memberExpression = (MemberExpression)expression; + else if (expression.NodeType == ExpressionType.Call) memberExpression = (expression as MethodCallExpression).Object as MemberExpression; + + segs.Add(memberExpression.Member.Name); + expression = memberExpression.Expression; + } + + // 如果读取 + if (expression.NodeType == ExpressionType.Parameter) segs.Add(isDesciptor ? expression.Type.Name : (expression as ParameterExpression).Name); + if (expression.NodeType == ExpressionType.MemberAccess) segs.Add((expression as MemberExpression).Member.Name); + + segs.Reverse(); + string result = string.Join(".", segs); + return result; + } + + #endregion + + #region 列表扩展 + + /// + /// 取指定列表中符合条件的元素索引 + /// + public static int IndexOf(this IEnumerable collection, Func predicate) + { + int i = -1; + foreach (T value in collection) + { + i++; + if (predicate(value)) return i; + } + + return -1; + } + + /// + /// 创建一个集合 + /// + public static List ToList(this IEnumerable collection, Func selector) + { + return collection.Select(selector).ToList(); + } + + /// + /// 列表转换扩展 + /// + public static List ToList(this IEnumerable source, Func selector, Func predicate = null) + { + if (predicate != null) source = source.Where(predicate); + return source.Select(selector).ToList(); + } + + /// + /// 根据页长计算总页码 + /// + /// 数据集合 + /// 页码 + /// + public static int Page(this IEnumerable collection, int pageSize) + { + int count = 0; + if ((collection as ICollection) != null) count = (collection as ICollection).Count; + else if ((collection as T[]) != null) count = (collection as T[]).Length; + else count = collection.Count(); + + int page = (count + pageSize - 1) / pageSize; + return page; + } + + /// + /// 批量添加命令参数 + /// + public static void AddRange(this IDataParameterCollection source, IEnumerable parameters) + { + if (parameters != null) + { + foreach (var p in parameters) source.Add(p); + } + } + + #endregion + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `methodCallExpression` last assigned on line 94 could be null and is dereferenced at line 95, column 17. + +### Severity: +ERROR + +### Procedure: +Boolean XFrameworkExtensions.CanEvaluate(Expression) + +### File: +net45/TZM.XFramework/Common/XFrameworkExtensions.cs + +### Key: +XFrameworkExtensions.cs|CanEvaluate|NULL_DEREFERENCE + +### Node Key: +90535029835413c6e5d1bdebbf52bdf9 + +### Hash: +d37146aef0c1f61eb7f3bdca4b334d37 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0592/instruction.md b/inferredbugs-0592/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3c8ed7a6bbca640b28ce79f9459e469242493b31 --- /dev/null +++ b/inferredbugs-0592/instruction.md @@ -0,0 +1,331 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** socket.io-client-csharp +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; +using SocketIOClient.Messages; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; + +namespace SocketIOClient.UnitTest.ConverterTests +{ + [TestClass] + public class ConverterReadTest + { + [TestMethod] + public void Opened() + { + var msg = MessageFactory.CreateMessage("0{\"sid\":\"6lV4Ef7YOyGF-5dCBvKy\",\"upgrades\":[],\"pingInterval\":10000,\"pingTimeout\":5000}"); + Assert.AreEqual(MessageType.Opened, msg.Type); + + var openedMsg = msg as OpenedMessage; + + Assert.AreEqual("6lV4Ef7YOyGF-5dCBvKy", openedMsg.Sid); + Assert.AreEqual(10000, openedMsg.PingInterval); + Assert.AreEqual(5000, openedMsg.PingTimeout); + } + + [TestMethod] + public void Ping() + { + var msg = MessageFactory.CreateMessage("2"); + Assert.AreEqual(MessageType.Ping, msg.Type); + } + + [TestMethod] + public void Pong() + { + var msg = MessageFactory.CreateMessage("3"); + Assert.AreEqual(MessageType.Pong, msg.Type); + } + + [TestMethod] + public void Eio4Connected() + { + var msg = MessageFactory.CreateMessage("40{\"sid\":\"aMA_EmVTuzpgR16PAc4w\"}"); + Assert.AreEqual(MessageType.Connected, msg.Type); + + var connectedMsg = msg as ConnectedMessage; + + Assert.AreEqual(string.Empty, connectedMsg.Namespace); + Assert.AreEqual("aMA_EmVTuzpgR16PAc4w", connectedMsg.Sid); + } + + [TestMethod] + public void Eio4NamespaceConnected() + { + var msg = MessageFactory.CreateMessage("40/nsp,{\"sid\":\"xO_jp2_xrGtXUveLAc4y\"}"); + Assert.AreEqual(MessageType.Connected, msg.Type); + + var connectedMsg = msg as ConnectedMessage; + + Assert.AreEqual("/nsp", connectedMsg.Namespace); + Assert.AreEqual("xO_jp2_xrGtXUveLAc4y", connectedMsg.Sid); + } + + [TestMethod] + public void Disconnected() + { + var msg = MessageFactory.CreateMessage("41"); + Assert.AreEqual(MessageType.Disconnected, msg.Type); + + var realMsg = msg as DisconnectedMessage; + + Assert.AreEqual(string.Empty, realMsg.Namespace); + } + + [TestMethod] + public void NamespaceDisconnected() + { + var msg = MessageFactory.CreateMessage("41/github,"); + Assert.AreEqual(MessageType.Disconnected, msg.Type); + + var realMsg = msg as DisconnectedMessage; + + Assert.AreEqual("/github", realMsg.Namespace); + } + + [TestMethod] + public void Event0Param() + { + var msg = MessageFactory.CreateMessage("42[\"hi\"]"); + Assert.AreEqual(MessageType.EventMessage, msg.Type); + + var realMsg = msg as EventMessage; + + Assert.IsTrue(string.IsNullOrEmpty(realMsg.Namespace)); + + Assert.AreEqual("hi", realMsg.Event); + Assert.AreEqual(0, realMsg.JsonElements.Count); + } + + [TestMethod] + public void Event1Param() + { + var msg = MessageFactory.CreateMessage("42[\"hi\",\"V3: onAny\"]"); + Assert.AreEqual(MessageType.EventMessage, msg.Type); + + var realMsg = msg as EventMessage; + + Assert.IsTrue(string.IsNullOrEmpty(realMsg.Namespace)); + + Assert.AreEqual("hi", realMsg.Event); + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual("V3: onAny", realMsg.JsonElements[0].GetString()); + } + + [TestMethod] + public void NamespaceEvent0Param() + { + var msg = MessageFactory.CreateMessage("42/nsp,[\"234\"]"); + Assert.AreEqual(MessageType.EventMessage, msg.Type); + + var realMsg = msg as EventMessage; + + Assert.AreEqual("/nsp", realMsg.Namespace); + + Assert.AreEqual("234", realMsg.Event); + Assert.AreEqual(0, realMsg.JsonElements.Count); + } + + [TestMethod] + public void NamespaceEvent1Param() + { + var msg = MessageFactory.CreateMessage("42/nsp,[\"qww\",true]"); + Assert.AreEqual(MessageType.EventMessage, msg.Type); + + var realMsg = msg as EventMessage; + + Assert.AreEqual("/nsp", realMsg.Namespace); + + Assert.AreEqual("qww", realMsg.Event); + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.IsTrue(realMsg.JsonElements[0].GetBoolean()); + } + + [TestMethod] + public void Ack() + { + var msg = MessageFactory.CreateMessage("431[\"doghappy\"]"); + Assert.AreEqual(MessageType.AckMessage, msg.Type); + + var realMsg = msg as ClientAckMessage; + + Assert.IsTrue(string.IsNullOrEmpty(realMsg.Namespace)); + Assert.AreEqual(1, realMsg.Id); + + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual("doghappy", realMsg.JsonElements[0].GetString()); + } + + [TestMethod] + public void NamespaceAck() + { + var msg = MessageFactory.CreateMessage("43/google,15[\"doghappy\"]"); + Assert.AreEqual(MessageType.AckMessage, msg.Type); + + var realMsg = msg as ClientAckMessage; + + Assert.AreEqual("/google", realMsg.Namespace); + Assert.AreEqual(15, realMsg.Id); + + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual("doghappy", realMsg.JsonElements[0].GetString()); + } + + [TestMethod] + public void Error() + { + var msg = MessageFactory.CreateMessage("44{\"message\":\"Authentication error2\"}"); + Assert.AreEqual(MessageType.ErrorMessage, msg.Type); + + var result = msg as ErrorMessage; + + Assert.AreEqual("Authentication error2", result.Message); + } + + [TestMethod] + public void Binary() + { + var msg = MessageFactory.CreateMessage("451-[\"1 params\",{\"_placeholder\":true,\"num\":0}]"); + Assert.AreEqual(MessageType.BinaryMessage, msg.Type); + + var realMsg = msg as BinaryMessage; + + Assert.IsTrue(string.IsNullOrEmpty(realMsg.Namespace)); + Assert.AreEqual(1, realMsg.BinaryCount); + + Assert.AreEqual("1 params", realMsg.Event); + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual(JsonValueKind.Object, realMsg.JsonElements[0].ValueKind); + } + + [TestMethod] + public void NamespaceBinary() + { + var msg = MessageFactory.CreateMessage("451-/why-ve,[\"1 params\",{\"_placeholder\":true,\"num\":0}]"); + Assert.AreEqual(MessageType.BinaryMessage, msg.Type); + + var realMsg = msg as BinaryMessage; + + Assert.AreEqual("/why-ve", realMsg.Namespace); + Assert.AreEqual(1, realMsg.BinaryCount); + + Assert.AreEqual("1 params", realMsg.Event); + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual(JsonValueKind.Object, realMsg.JsonElements[0].ValueKind); + } + + [TestMethod] + public void NamespaceBinaryWithId() + { + var msg = MessageFactory.CreateMessage("451-/why-ve,30[\"1 params\",{\"_placeholder\":true,\"num\":0}]"); + Assert.AreEqual(MessageType.BinaryMessage, msg.Type); + + var realMsg = msg as BinaryMessage; + + Assert.AreEqual("/why-ve", realMsg.Namespace); + Assert.AreEqual(1, realMsg.BinaryCount); + Assert.AreEqual(30, realMsg.Id); + + Assert.AreEqual("1 params", realMsg.Event); + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual(JsonValueKind.Object, realMsg.JsonElements[0].ValueKind); + } + + [TestMethod] + public void BinaryAck() + { + var msg = MessageFactory.CreateMessage("461-6[{\"_placeholder\":true,\"num\":0}]"); + Assert.AreEqual(MessageType.BinaryAckMessage, msg.Type); + + var realMsg = msg as ServerBinaryAckMessage; + + Assert.IsNull(realMsg.Namespace); + Assert.AreEqual(1, realMsg.BinaryCount); + Assert.AreEqual(6, realMsg.Id); + + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual(JsonValueKind.Object, realMsg.JsonElements[0].ValueKind); + } + + [TestMethod] + public void NamespaceBinaryAck() + { + var msg = MessageFactory.CreateMessage("461-/name-space,6[{\"_placeholder\":true,\"num\":0}]"); + Assert.AreEqual(MessageType.BinaryAckMessage, msg.Type); + + var realMsg = msg as ServerBinaryAckMessage; + + Assert.AreEqual("/name-space", realMsg.Namespace); + Assert.AreEqual(1, realMsg.BinaryCount); + Assert.AreEqual(6, realMsg.Id); + + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual(JsonValueKind.Object, realMsg.JsonElements[0].ValueKind); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `realMsg` last assigned on line 243 could be null and is dereferenced at line 245, column 13. + +### Severity: +ERROR + +### Procedure: +Void ConverterReadTest.BinaryAck() + +### File: +src/SocketIOClient.UnitTest/ConverterTests/ConverterReadTest.cs + +### Key: +ConverterReadTest.cs|BinaryAck|NULL_DEREFERENCE + +### Node Key: +a35c6d97ccef7486c04c7fb208054b5b + +### Hash: +dc2fb48bc0c2474b89513759fbf78d33 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0595/instruction.md b/inferredbugs-0595/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c6d12410c876ed9a887cd003e81acb9886474c1b --- /dev/null +++ b/inferredbugs-0595/instruction.md @@ -0,0 +1,255 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ExpressiveAnnotations +**Bug ID:** 9 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; + +namespace ExpressiveAnnotations.Analysis +{ + /* EBNF GRAMMAR: + * + * expression => or-exp + * or-exp => and-exp [ "||" or-exp ] + * and-exp => not-exp [ "&&" and-exp ] + * not-exp => [ "!" ] rel-exp + * rel-exp => val [ rel-op val ] + * rel-op => "==" | "!=" | ">" | ">=" | "<" | "<=" + * val => "null" | int | float | bool | string | prop | "(" or-exp ")" + */ + + /// + /// Performs syntactic analysis of provided logical expression within given context. + /// + public sealed class Parser + { + private Stack Tokens { get; set; } + private Type ContextType { get; set; } + private Expression ContextExpression { get; set; } + + /// + /// Parses the specified logical expression into expression tree within given object context. + /// + /// The type identifier of the context within which the expression is interpreted. + /// The logical expression. + /// A delegate containing the compiled version of the lambda expression described by created expression tree. + public Func Parse(string expression) + { + ContextType = typeof(Context); + var param = Expression.Parameter(typeof(Context)); + ContextExpression = param; + InitTokenizer(expression); + var expressionTree = ParseExpression(); + var lambda = Expression.Lambda>(expressionTree, param); + return lambda.Compile(); + } + + /// + /// Parses the specified logical expression and builds expression tree. + /// + /// The type instance of the context within which the expression is interpreted. + /// The logical expression. + /// A delegate containing the compiled version of the lambda expression described by produced expression tree. + public Func Parse(Type context, string expression) + { + ContextType = context; + var param = Expression.Parameter(typeof(object)); + ContextExpression = Expression.Convert(param, context); + InitTokenizer(expression); + var expressionTree = ParseExpression(); + var lambda = Expression.Lambda>(expressionTree, param); + return lambda.Compile(); + } + + private void InitTokenizer(string expression) + { + var lexer = new Lexer(); + Tokens = new Stack(lexer.Analyze(expression).Reverse()); + } + + private bool PeekToken(out Token token) + { + token = Tokens.Any() ? Tokens.Peek() : null; + return token != null; + } + + private void CrushToken() + { + Tokens.Pop(); + } + + private Expression ParseExpression() + { + return ParseOrExp(); + } + + private Expression ParseOrExp() + { + var arg1 = ParseAndExp(); + Token token; + if (!PeekToken(out token) || token.Id != TokenId.OR) + return arg1; + CrushToken(); + var arg2 = ParseOrExp(); + return Expression.Or(arg1, arg2); + } + + private Expression ParseAndExp() + { + var arg1 = ParseNotExp(); + Token token; + if (!PeekToken(out token) || token.Id != TokenId.AND) + return arg1; + CrushToken(); + var arg2 = ParseAndExp(); + return Expression.And(arg1, arg2); + } + + private Expression ParseNotExp() + { + Token token; + if (!PeekToken(out token) || token.Id != TokenId.NOT) + return ParseRelExp(); + CrushToken(); + return Expression.Not(ParseRelExp()); + } + + private Expression ParseRelExp() + { + var arg1 = ParseVal(); + Token token; + if (!PeekToken(out token) || !new[] { TokenId.LT, TokenId.LE, TokenId.GT, TokenId.GE, TokenId.EQ, TokenId.NEQ }.Contains(token.Id)) + return arg1; + CrushToken(); + var arg2 = ParseVal(); + + Helper.MakeTypesCompatible(arg1, arg2, out arg1, out arg2); + switch (token.Id) + { + case TokenId.LT: + return Expression.LessThan(arg1, arg2); + case TokenId.LE: + return Expression.LessThanOrEqual(arg1, arg2); + case TokenId.GT: + return Expression.GreaterThan(arg1, arg2); + case TokenId.GE: + return Expression.GreaterThanOrEqual(arg1, arg2); + case TokenId.EQ: + return Expression.Equal(arg1, arg2); + case TokenId.NEQ: + return Expression.NotEqual(arg1, arg2); + default: + throw new InvalidOperationException(); + } + } + + private Expression ParseVal() + { + Token token; + if (!PeekToken(out token)) + throw new InvalidOperationException(); + + if (token.Id == TokenId.LEFT_BRACKET) + { + CrushToken(); + var arg = ParseOrExp(); + if (!PeekToken(out token) || token.Id != TokenId.RIGHT_BRACKET) + throw new InvalidOperationException(); + CrushToken(); + return arg; + } + + CrushToken(); + switch (token.Id) + { + case TokenId.NULL: + return Expression.Constant(null); + case TokenId.INT: + return Expression.Constant(token.Value, typeof(int)); + case TokenId.FLOAT: + return Expression.Constant(token.Value, typeof(float)); + case TokenId.BOOL: + return Expression.Constant(token.Value, typeof(bool)); + case TokenId.STRING: + return Expression.Constant(token.Value, typeof(string)); + case TokenId.PROPERTY: + return ExtractProperty(token.Value.ToString()); + default: + throw new InvalidOperationException(); + } + } + + private Expression ExtractProperty(string name) + { + var props = name.Split('.'); + var type = ContextType; + var expr = ContextExpression; + foreach (var prop in props) + { + var pi = type.GetProperty(prop); + if (pi == null) + throw new ArgumentException(string.Format("Dynamic extraction interrupted. Field {0} not found.", prop), name); + expr = Expression.Property(expr, pi); + type = pi.PropertyType; + } + return expr; + } + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`token` could be null (from the call to `Parser.PeekToken(...)` on line 88) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +Expression Parser.ParseOrExp() + +### File: +src/ExpressiveAnnotations/Analysis/Parser.cs + +### Key: +Parser.cs|ParseOrExp|NULLPTR_DEREFERENCE + +### Hash: +188da5288d55deb1f31c276187a8db33 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0672/instruction.md b/inferredbugs-0672/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d60470b6e75a502eeaf4c38490b8da09f705dc04 --- /dev/null +++ b/inferredbugs-0672/instruction.md @@ -0,0 +1,560 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** azure-storage-net-data-movement +**Bug ID:** 7 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation +// +//------------------------------------------------------------------------------ + +namespace Microsoft.Azure.Storage.DataMovement +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Runtime.Serialization; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Azure.Storage.Blob; + using Microsoft.Azure.Storage.DataMovement.TransferEnumerators; + using Microsoft.Azure.Storage.File; + + /// + /// Represents a sub-directory transfer under a hierarchy directory transfer. + /// +#if BINARY_SERIALIZATION + [Serializable] +#else + [DataContract] +#endif // BINARY_SERIALIZATION + class SubDirectoryTransfer : JournalItem +#if BINARY_SERIALIZATION + , ISerializable +#endif // BINARY_SERIALIZATION + { + private const string SubDirListContinuationTokenName = "SubDirListContinuationToken"; + private const string SubDirRelativePathName = "SubDirRelativePath"; + + /// + /// Base instance which this instance belongs to. + /// instance returns its listed directories and files to with callbacks. + /// + private HierarchyDirectoryTransfer baseDirectoryTransfer = null; + private ITransferEnumerator transferEnumerator = null; + +#if !BINARY_SERIALIZATION + [DataMember] +#endif + private string relativePath = null; + +#if !BINARY_SERIALIZATION + [DataMember] +#endif + private SerializableListContinuationToken enumerateContinuationToken = null; + + private TransferLocation source; + private TransferLocation dest; + + public SubDirectoryTransfer( + HierarchyDirectoryTransfer baseDirectoryTransfer, + string relativePath) + { + this.enumerateContinuationToken = new SerializableListContinuationToken(null); + this.baseDirectoryTransfer = baseDirectoryTransfer; + this.relativePath = relativePath; + this.baseDirectoryTransfer.GetSubDirLocation(this.relativePath, out this.source, out this.dest); + this.InitializeEnumerator(); + } + + public SubDirectoryTransfer(SubDirectoryTransfer other) + { + this.relativePath = other.relativePath; + this.enumerateContinuationToken = other.enumerateContinuationToken; + } + +#if BINARY_SERIALIZATION + /// + /// Initializes a new instance of the class. + /// + /// Serialization information. + /// Streaming context. + protected SubDirectoryTransfer(SerializationInfo info, StreamingContext context) + { + this.relativePath = info.GetString(SubDirRelativePathName); + + if (!(context.Context is StreamJournal)) + { + this.enumerateContinuationToken = (SerializableListContinuationToken)info.GetValue(SubDirListContinuationTokenName, typeof(SerializableListContinuationToken)); + } + } + + /// + /// Serializes the object. + /// + /// Serialization info object. + /// Streaming context. + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + if (info == null) + { + throw new ArgumentNullException("info"); + } + + info.AddValue(SubDirRelativePathName, this.relativePath, typeof(string)); + + if (!(context.Context is StreamJournal)) + { + // serialize continuation token + info.AddValue(SubDirListContinuationTokenName, this.enumerateContinuationToken, typeof(SerializableListContinuationToken)); + } + } +#endif // BINARY_SERIALIZATION + + public SerializableListContinuationToken ListContinuationToken + { + get + { + return this.enumerateContinuationToken; + } + + set + { + this.enumerateContinuationToken = value; + } + } + + public async Task ExecuteAsync(CancellationToken cancellationToken) + { + await Task.Yield(); + + this.CreateDestinationDirectory(cancellationToken); + + var enumerator = this.transferEnumerator.EnumerateLocation(cancellationToken).GetEnumerator(); + + while (true) + { + if (!enumerator.MoveNext()) + { + break; + } + + TransferEntry entry = enumerator.Current; + ErrorEntry errorEntry = entry as ErrorEntry; + if (errorEntry != null) + { + TransferException exception = errorEntry.Exception as TransferException; + if (null != exception) + { + throw exception; + } + else + { + throw new TransferException( + TransferErrorCode.FailToEnumerateDirectory, + errorEntry.Exception.GetExceptionMessage(), + errorEntry.Exception); + } + } + + if (entry.IsDirectory) + { + this.baseDirectoryTransfer.AddSubDir(entry.RelativePath, () => + { + var currentContinuationToken = new SerializableListContinuationToken(entry.ContinuationToken); + currentContinuationToken.Journal = this.enumerateContinuationToken.Journal; + currentContinuationToken.StreamJournalOffset = this.enumerateContinuationToken.StreamJournalOffset; + this.enumerateContinuationToken = currentContinuationToken; + return this.enumerateContinuationToken; + }); + } + else + { + SingleObjectTransfer transferItem = this.baseDirectoryTransfer.CreateTransfer(entry); +#if DEBUG + Utils.HandleFaultInjection(entry.RelativePath, transferItem); +#endif + + this.CreateDestinationParentDirectoryRecursively(transferItem); + + this.baseDirectoryTransfer.AddSingleObjectTransfer(transferItem, () => + { + var currentContinuationToken = new SerializableListContinuationToken(entry.ContinuationToken); + currentContinuationToken.Journal = this.enumerateContinuationToken.Journal; + currentContinuationToken.StreamJournalOffset = this.enumerateContinuationToken.StreamJournalOffset; + this.enumerateContinuationToken = currentContinuationToken; + return this.enumerateContinuationToken; + }); + } + } + } + + public void Update(HierarchyDirectoryTransfer baseDirectoryTransferInstance) + { + this.baseDirectoryTransfer = baseDirectoryTransferInstance; + this.baseDirectoryTransfer.GetSubDirLocation(this.relativePath, out this.source, out this.dest); + this.InitializeEnumerator(); + } + + public void CreateDestinationParentDirectoryRecursively(SingleObjectTransfer transferItem) + { + switch (transferItem.Destination.Type) + { + case TransferLocationType.FilePath: + var filePath = (transferItem.Destination as FileLocation).FilePath; + Utils.ValidateDestinationPath(transferItem.Source.Instance.ConvertToString(), filePath); + Utils.CreateParentDirectoryIfNotExists(filePath); + break; + case TransferLocationType.AzureFile: + var parent = (transferItem.Destination as AzureFileLocation).AzureFile.Parent; + CloudFileDirectory destDirectory = this.dest.Instance as CloudFileDirectory; + + if (!string.Equals(parent.SnapshotQualifiedUri.AbsolutePath, destDirectory.SnapshotQualifiedUri.AbsolutePath)) + { + if (this.baseDirectoryTransfer.IsForceOverwrite || !parent.ExistsAsync(Transfer_RequestOptions.DefaultFileRequestOptions, null).Result) + { + Utils.CreateCloudFileDirectoryRecursively(parent); + } + } + break; + default: + break; + } + } + + private void InitializeEnumerator() + { + if (this.source.Type == TransferLocationType.AzureFileDirectory) + { + var fileEnumerator = new AzureFileHierarchyEnumerator(this.source as AzureFileDirectoryLocation, this.baseDirectoryTransfer.Source.Instance as CloudFileDirectory); + fileEnumerator.EnumerateContinuationToken = this.enumerateContinuationToken.ListContinuationToken; + fileEnumerator.SearchPattern = this.baseDirectoryTransfer.SearchPattern; + fileEnumerator.Recursive = this.baseDirectoryTransfer.Recursive; + + this.transferEnumerator = fileEnumerator; + } + else if (this.source.Type == TransferLocationType.LocalDirectory) + { + var fileEnumerator = new FileHierarchyEnumerator(this.source as DirectoryLocation, this.baseDirectoryTransfer.Source.Instance as string, this.baseDirectoryTransfer.FollowSymblink); + fileEnumerator.EnumerateContinuationToken = this.enumerateContinuationToken.ListContinuationToken; + fileEnumerator.SearchPattern = this.baseDirectoryTransfer.SearchPattern; + fileEnumerator.Recursive = this.baseDirectoryTransfer.Recursive; + + this.transferEnumerator = fileEnumerator; + } + else + { + throw new NotSupportedException(); + } + } + + private void CreateDestinationDirectory(CancellationToken cancellationToken) + { + if (this.dest.Type == TransferLocationType.AzureBlobDirectory) + { + // No physical destination directory needed. + return; + } + + if ((this.dest.Type == TransferLocationType.AzureFileDirectory) + && (null == (this.dest as AzureFileDirectoryLocation).FileDirectory.Parent)) + { + //Root Azure File directory, no need to create. + return; + } + + CloudFileNtfsAttributes? fileAttributes = null; + DateTimeOffset? creationTime = null; + DateTimeOffset? lastWriteTime = null; + IDictionary metadata = null; + + if (this.source.Type == TransferLocationType.LocalDirectory) + { + if (this.baseDirectoryTransfer.PreserveSMBAttributes) + { + var sourceLocalDirLocation = this.source as DirectoryLocation; + + FileAttributes? localFileAttributes = null; + + string longDirectoryPath = sourceLocalDirLocation.DirectoryPath; + + if (Interop.CrossPlatformHelpers.IsWindows) + { + longDirectoryPath = LongPath.ToUncPath(longDirectoryPath); + } + +#if DOTNET5_4 + LongPathFile.GetFileProperties(longDirectoryPath, out creationTime, out lastWriteTime, out localFileAttributes, true); +#else + LongPathFile.GetFileProperties(longDirectoryPath, out creationTime, out lastWriteTime, out localFileAttributes); +#endif + fileAttributes = Utils.LocalAttributesToAzureFileNtfsAttributes(localFileAttributes.Value); + } + } + else if (this.source.Type == TransferLocationType.AzureFileDirectory) + { + if (this.baseDirectoryTransfer.PreserveSMBAttributes || this.dest.Type == TransferLocationType.AzureFileDirectory) + { + AzureFileDirectoryLocation sourceFileDirLocation = this.source as AzureFileDirectoryLocation; + + var sourceFileDirectory = sourceFileDirLocation.FileDirectory; + sourceFileDirectory.FetchAttributesAsync( + null, + Utils.GenerateFileRequestOptions(sourceFileDirLocation.FileRequestOptions), + Utils.GenerateOperationContext(this.baseDirectoryTransfer.Context), + cancellationToken).GetAwaiter().GetResult(); + + if (this.baseDirectoryTransfer.PreserveSMBAttributes) + { + fileAttributes = sourceFileDirectory.Properties.NtfsAttributes; + creationTime = sourceFileDirectory.Properties.CreationTime; + lastWriteTime = sourceFileDirectory.Properties.LastWriteTime; + } + + metadata = sourceFileDirectory.Metadata; + } + } + + if (this.dest.Type == TransferLocationType.LocalDirectory) + { + var localFileDestLocation = this.dest as DirectoryLocation; + if (!LongPathDirectory.Exists(localFileDestLocation.DirectoryPath)) + { + LongPathDirectory.CreateDirectory(localFileDestLocation.DirectoryPath); + } + + if (fileAttributes.HasValue) + { + string longDirectoryPath = localFileDestLocation.DirectoryPath; + + if (Interop.CrossPlatformHelpers.IsWindows) + { + longDirectoryPath = LongPath.ToUncPath(longDirectoryPath); + } + + LongPathFile.SetFileTime(longDirectoryPath, creationTime.Value, lastWriteTime.Value, true); + LongPathFile.SetAttributes(longDirectoryPath, Utils.AzureFileNtfsAttributesToLocalAttributes(fileAttributes.Value)); + } + } + else if (this.dest.Type == TransferLocationType.AzureFileDirectory) + { + AzureFileDirectoryLocation fileDirLocation = this.dest as AzureFileDirectoryLocation; + + var fileDirectory = fileDirLocation.FileDirectory; + + if (string.Equals(fileDirectory.SnapshotQualifiedUri.AbsolutePath, fileDirectory.Share.SnapshotQualifiedUri.AbsolutePath)) + { + return; + } + + try + { + CreateCloudFileDestinationDirectory(fileDirectory, + fileAttributes, + creationTime, + lastWriteTime, + metadata, + cancellationToken); + } + catch (StorageException storageException) + { + throw new TransferException(TransferErrorCode.FailToVadlidateDestination, + string.Format(CultureInfo.CurrentCulture, + Resources.FailedToValidateDestinationException, + storageException.ToErrorDetail()), + storageException); + } + } + } + + private static void CreateCloudFileDestinationDirectory(CloudFileDirectory fileDirectory, + CloudFileNtfsAttributes? fileAttributes, + DateTimeOffset? creationTime, + DateTimeOffset? lastWriteTime, + IDictionary metadata, + CancellationToken cancellationToken) + { + bool parentNotExist = false; + + if (fileAttributes.HasValue) + { + fileDirectory.Properties.NtfsAttributes = fileAttributes.Value; + fileDirectory.Properties.CreationTime = creationTime; + fileDirectory.Properties.LastWriteTime = lastWriteTime; + } + + if (null != metadata) + { + fileDirectory.Metadata.Clear(); + foreach (var keyValuePair in metadata) + { + fileDirectory.Metadata.Add(keyValuePair); + } + } + + bool needToSetProperties = false; + + try + { + fileDirectory.CreateAsync(Transfer_RequestOptions.DefaultFileRequestOptions, null, cancellationToken).GetAwaiter().GetResult(); + return; + } + catch (StorageException ex) + { + if (null != ex.RequestInformation) + { + if (string.Equals("ParentNotFound", ex.RequestInformation.ErrorCode)) + { + parentNotExist = true; + } + else if (string.Equals("ResourceAlreadyExists", ex.RequestInformation.ErrorCode)) + { + needToSetProperties = true; + } + else + { + throw; + } + } + else + { + throw; + } + } + + if (parentNotExist) + { + Utils.CreateCloudFileDirectoryRecursively(fileDirectory.Parent); + try + { + fileDirectory.CreateAsync(Transfer_RequestOptions.DefaultFileRequestOptions, null, cancellationToken).GetAwaiter().GetResult(); + } + catch (StorageException ex) + { + if (null != ex.RequestInformation) + { + if (string.Equals("ResourceAlreadyExists", ex.RequestInformation.ErrorCode)) + { + needToSetProperties = true; + } + else + { + throw; + } + } + else + { + throw; + } + } + } + + if (needToSetProperties) + { + SetAzureFileDirectoryAttributes(fileDirectory, fileAttributes, creationTime, lastWriteTime, metadata, cancellationToken); + } + } + + private static void SetAzureFileDirectoryAttributes( + CloudFileDirectory fileDirectory, + CloudFileNtfsAttributes? fileAttributes, + DateTimeOffset? creationTime, + DateTimeOffset? lastWriteTime, + IDictionary metadata, + CancellationToken cancellationToken) + { + if (fileAttributes.HasValue || null != metadata) + { + fileDirectory.FetchAttributesAsync(null, Transfer_RequestOptions.DefaultFileRequestOptions, null, cancellationToken).GetAwaiter().GetResult(); + + if (fileAttributes.HasValue) + { + if (fileDirectory.Properties.NtfsAttributes != fileAttributes.Value + || fileDirectory.Properties.CreationTime != creationTime.Value + || fileDirectory.Properties.LastWriteTime != lastWriteTime.Value) + { + fileDirectory.Properties.NtfsAttributes = fileAttributes.Value; + fileDirectory.Properties.CreationTime = creationTime; + fileDirectory.Properties.LastWriteTime = lastWriteTime; + fileDirectory.SetPropertiesAsync(Transfer_RequestOptions.DefaultFileRequestOptions, null, cancellationToken).GetAwaiter().GetResult(); + } + } + + if (null != metadata) + { + if (!metadata.DictionaryEquals(fileDirectory.Metadata)) + { + fileDirectory.Metadata.Clear(); + foreach (var keyValuePair in metadata) + { + fileDirectory.Metadata.Add(keyValuePair); + } + + fileDirectory.SetMetadataAsync(null, Transfer_RequestOptions.DefaultFileRequestOptions, null, cancellationToken).GetAwaiter().GetResult(); + } + } + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `localFileDestLocation` last assigned on line 319 could be null and is dereferenced at line 320, column 17. + +### Severity: +ERROR + +### Procedure: +Void SubDirectoryTransfer.CreateDestinationDirectory(CancellationToken) + +### File: +lib/TransferJobs/SubDirectoryTransfer.cs + +### Key: +SubDirectoryTransfer.cs|CreateDestinationDirectory|NULL_DEREFERENCE + +### Node Key: +93735850e46a76bf26a8e51627647824 + +### Hash: +53fd18a21ca7242d78a4123978850d6c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0675/instruction.md b/inferredbugs-0675/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e1e51d5b9555b29df9b7d75cb7247e08b5f6f1b --- /dev/null +++ b/inferredbugs-0675/instruction.md @@ -0,0 +1,553 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** azure-storage-net-data-movement +**Bug ID:** 10 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +//------------------------------------------------------------------------------ +// +// Copyright (c) Microsoft Corporation +// +//------------------------------------------------------------------------------ + +namespace Microsoft.Azure.Storage.DataMovement +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Runtime.Serialization; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Azure.Storage.Blob; + using Microsoft.Azure.Storage.DataMovement.TransferEnumerators; + using Microsoft.Azure.Storage.File; + + /// + /// Represents a sub-directory transfer under a hierarchy directory transfer. + /// +#if BINARY_SERIALIZATION + [Serializable] +#else + [DataContract] +#endif // BINARY_SERIALIZATION + class SubDirectoryTransfer : JournalItem +#if BINARY_SERIALIZATION + , ISerializable +#endif // BINARY_SERIALIZATION + { + private const string SubDirListContinuationTokenName = "SubDirListContinuationToken"; + private const string SubDirRelativePathName = "SubDirRelativePath"; + + /// + /// Base instance which this instance belongs to. + /// instance returns its listed directories and files to with callbacks. + /// + private HierarchyDirectoryTransfer baseDirectoryTransfer = null; + private ITransferEnumerator transferEnumerator = null; + +#if !BINARY_SERIALIZATION + [DataMember] +#endif + private string relativePath = null; + +#if !BINARY_SERIALIZATION + [DataMember] +#endif + private SerializableListContinuationToken enumerateContinuationToken = null; + + private TransferLocation source; + private TransferLocation dest; + + public SubDirectoryTransfer( + HierarchyDirectoryTransfer baseDirectoryTransfer, + string relativePath) + { + this.enumerateContinuationToken = new SerializableListContinuationToken(null); + this.baseDirectoryTransfer = baseDirectoryTransfer; + this.relativePath = relativePath; + this.baseDirectoryTransfer.GetSubDirLocation(this.relativePath, out this.source, out this.dest); + this.InitializeEnumerator(); + } + + public SubDirectoryTransfer(SubDirectoryTransfer other) + { + this.relativePath = other.relativePath; + this.enumerateContinuationToken = other.enumerateContinuationToken; + } + +#if BINARY_SERIALIZATION + /// + /// Initializes a new instance of the class. + /// + /// Serialization information. + /// Streaming context. + protected SubDirectoryTransfer(SerializationInfo info, StreamingContext context) + { + this.relativePath = info.GetString(SubDirRelativePathName); + + if (!(context.Context is StreamJournal)) + { + this.enumerateContinuationToken = (SerializableListContinuationToken)info.GetValue(SubDirListContinuationTokenName, typeof(SerializableListContinuationToken)); + } + } + + /// + /// Serializes the object. + /// + /// Serialization info object. + /// Streaming context. + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + if (info == null) + { + throw new ArgumentNullException("info"); + } + + info.AddValue(SubDirRelativePathName, this.relativePath, typeof(string)); + + if (!(context.Context is StreamJournal)) + { + // serialize continuation token + info.AddValue(SubDirListContinuationTokenName, this.enumerateContinuationToken, typeof(SerializableListContinuationToken)); + } + } +#endif // BINARY_SERIALIZATION + + public SerializableListContinuationToken ListContinuationToken + { + get + { + return this.enumerateContinuationToken; + } + + set + { + this.enumerateContinuationToken = value; + } + } + + public async Task ExecuteAsync(CancellationToken cancellationToken) + { + await Task.Yield(); + + this.CreateDestinationDirectory(cancellationToken); + + var enumerator = this.transferEnumerator.EnumerateLocation(cancellationToken).GetEnumerator(); + + while (true) + { + if (!enumerator.MoveNext()) + { + break; + } + + TransferEntry entry = enumerator.Current; + ErrorEntry errorEntry = entry as ErrorEntry; + if (errorEntry != null) + { + TransferException exception = errorEntry.Exception as TransferException; + if (null != exception) + { + throw exception; + } + else + { + throw new TransferException( + TransferErrorCode.FailToEnumerateDirectory, + errorEntry.Exception.GetExceptionMessage(), + errorEntry.Exception); + } + } + + if (entry.IsDirectory) + { + this.baseDirectoryTransfer.AddSubDir(entry.RelativePath, () => + { + var currentContinuationToken = new SerializableListContinuationToken(entry.ContinuationToken); + currentContinuationToken.Journal = this.enumerateContinuationToken.Journal; + currentContinuationToken.StreamJournalOffset = this.enumerateContinuationToken.StreamJournalOffset; + this.enumerateContinuationToken = currentContinuationToken; + return this.enumerateContinuationToken; + }); + } + else + { + SingleObjectTransfer transferItem = this.baseDirectoryTransfer.CreateTransfer(entry); +#if DEBUG + Utils.HandleFaultInjection(entry.RelativePath, transferItem); +#endif + + this.CreateDestinationParentDirectoryRecursively(transferItem); + + this.baseDirectoryTransfer.AddSingleObjectTransfer(transferItem, () => + { + var currentContinuationToken = new SerializableListContinuationToken(entry.ContinuationToken); + currentContinuationToken.Journal = this.enumerateContinuationToken.Journal; + currentContinuationToken.StreamJournalOffset = this.enumerateContinuationToken.StreamJournalOffset; + this.enumerateContinuationToken = currentContinuationToken; + return this.enumerateContinuationToken; + }); + } + } + } + + public void Update(HierarchyDirectoryTransfer baseDirectoryTransferInstance) + { + this.baseDirectoryTransfer = baseDirectoryTransferInstance; + this.baseDirectoryTransfer.GetSubDirLocation(this.relativePath, out this.source, out this.dest); + this.InitializeEnumerator(); + } + + public void CreateDestinationParentDirectoryRecursively(SingleObjectTransfer transferItem) + { + switch (transferItem.Destination.Type) + { + case TransferLocationType.FilePath: + var filePath = (transferItem.Destination as FileLocation).FilePath; + Utils.ValidateDestinationPath(transferItem.Source.Instance.ConvertToString(), filePath); + Utils.CreateParentDirectoryIfNotExists(filePath); + break; + case TransferLocationType.AzureFile: + var parent = (transferItem.Destination as AzureFileLocation).AzureFile.Parent; + CloudFileDirectory destDirectory = this.dest.Instance as CloudFileDirectory; + + if (!string.Equals(parent.SnapshotQualifiedUri.AbsolutePath, destDirectory.SnapshotQualifiedUri.AbsolutePath)) + { + if (this.baseDirectoryTransfer.IsForceOverwrite || !parent.ExistsAsync(Transfer_RequestOptions.DefaultFileRequestOptions, null).Result) + { + Utils.CreateCloudFileDirectoryRecursively(parent); + } + } + break; + default: + break; + } + } + + private void InitializeEnumerator() + { + if (this.source.Type == TransferLocationType.AzureFileDirectory) + { + var fileEnumerator = new AzureFileHierarchyEnumerator(this.source as AzureFileDirectoryLocation, this.baseDirectoryTransfer.Source.Instance as CloudFileDirectory); + fileEnumerator.EnumerateContinuationToken = this.enumerateContinuationToken.ListContinuationToken; + fileEnumerator.SearchPattern = this.baseDirectoryTransfer.SearchPattern; + fileEnumerator.Recursive = this.baseDirectoryTransfer.Recursive; + + this.transferEnumerator = fileEnumerator; + } + else if (this.source.Type == TransferLocationType.LocalDirectory) + { + var fileEnumerator = new FileHierarchyEnumerator(this.source as DirectoryLocation, this.baseDirectoryTransfer.Source.Instance as string, this.baseDirectoryTransfer.FollowSymblink); + fileEnumerator.EnumerateContinuationToken = this.enumerateContinuationToken.ListContinuationToken; + fileEnumerator.SearchPattern = this.baseDirectoryTransfer.SearchPattern; + fileEnumerator.Recursive = this.baseDirectoryTransfer.Recursive; + + this.transferEnumerator = fileEnumerator; + } + else + { + throw new NotSupportedException(); + } + } + + private void CreateDestinationDirectory(CancellationToken cancellationToken) + { + if (this.dest.Type == TransferLocationType.AzureBlobDirectory) + { + // No physical destination directory needed. + return; + } + + if ((this.dest.Type == TransferLocationType.AzureFileDirectory) + && (null == (this.dest as AzureFileDirectoryLocation).FileDirectory.Parent)) + { + //Root Azure File directory, no need to create. + return; + } + + CloudFileNtfsAttributes? fileAttributes = null; + DateTimeOffset? creationTime = null; + DateTimeOffset? lastWriteTime = null; + IDictionary metadata = null; + + if (this.source.Type == TransferLocationType.LocalDirectory) + { + if (this.baseDirectoryTransfer.PreserveSMBAttributes) + { + var sourceLocalDirLocation = this.source as DirectoryLocation; + + FileAttributes? localFileAttributes = null; + + string longDirectoryPath = sourceLocalDirLocation.DirectoryPath; + + if (Interop.CrossPlatformHelpers.IsWindows) + { + longDirectoryPath = LongPath.ToUncPath(longDirectoryPath); + } + +#if DOTNET5_4 + LongPathFile.GetFileProperties(longDirectoryPath, out creationTime, out lastWriteTime, out localFileAttributes, true); +#else + LongPathFile.GetFileProperties(longDirectoryPath, out creationTime, out lastWriteTime, out localFileAttributes); +#endif + fileAttributes = Utils.LocalAttributesToAzureFileNtfsAttributes(localFileAttributes.Value); + } + } + else if (this.source.Type == TransferLocationType.AzureFileDirectory) + { + if (this.baseDirectoryTransfer.PreserveSMBAttributes || this.dest.Type == TransferLocationType.AzureFileDirectory) + { + AzureFileDirectoryLocation sourceFileDirLocation = this.source as AzureFileDirectoryLocation; + + var sourceFileDirectory = sourceFileDirLocation.FileDirectory; + sourceFileDirectory.FetchAttributesAsync( + null, + Utils.GenerateFileRequestOptions(sourceFileDirLocation.FileRequestOptions), + Utils.GenerateOperationContext(this.baseDirectoryTransfer.Context), + cancellationToken).GetAwaiter().GetResult(); + + if (this.baseDirectoryTransfer.PreserveSMBAttributes) + { + fileAttributes = sourceFileDirectory.Properties.NtfsAttributes; + creationTime = sourceFileDirectory.Properties.CreationTime; + lastWriteTime = sourceFileDirectory.Properties.LastWriteTime; + } + + metadata = sourceFileDirectory.Metadata; + } + } + + if (this.dest.Type == TransferLocationType.LocalDirectory) + { + var localFileDestLocation = this.dest as DirectoryLocation; + if (!LongPathDirectory.Exists(localFileDestLocation.DirectoryPath)) + { + LongPathDirectory.CreateDirectory(localFileDestLocation.DirectoryPath); + } + + if (fileAttributes.HasValue) + { + LongPathFile.SetFileTime(localFileDestLocation.DirectoryPath, creationTime.Value, lastWriteTime.Value, true); + LongPathFile.SetAttributes(localFileDestLocation.DirectoryPath, Utils.AzureFileNtfsAttributesToLocalAttributes(fileAttributes.Value)); + } + } + else if (this.dest.Type == TransferLocationType.AzureFileDirectory) + { + AzureFileDirectoryLocation fileDirLocation = this.dest as AzureFileDirectoryLocation; + + var fileDirectory = fileDirLocation.FileDirectory; + + if (string.Equals(fileDirectory.SnapshotQualifiedUri.AbsolutePath, fileDirectory.Share.SnapshotQualifiedUri.AbsolutePath)) + { + return; + } + + try + { + CreateCloudFileDestinationDirectory(fileDirectory, + fileAttributes, + creationTime, + lastWriteTime, + metadata, + cancellationToken); + } + catch (StorageException storageException) + { + throw new TransferException(TransferErrorCode.FailToVadlidateDestination, + string.Format(CultureInfo.CurrentCulture, + Resources.FailedToValidateDestinationException, + storageException.ToErrorDetail()), + storageException); + } + } + } + + private static void CreateCloudFileDestinationDirectory(CloudFileDirectory fileDirectory, + CloudFileNtfsAttributes? fileAttributes, + DateTimeOffset? creationTime, + DateTimeOffset? lastWriteTime, + IDictionary metadata, + CancellationToken cancellationToken) + { + bool parentNotExist = false; + + if (fileAttributes.HasValue) + { + fileDirectory.Properties.NtfsAttributes = fileAttributes.Value; + fileDirectory.Properties.CreationTime = creationTime; + fileDirectory.Properties.LastWriteTime = lastWriteTime; + } + + if (null != metadata) + { + fileDirectory.Metadata.Clear(); + foreach (var keyValuePair in metadata) + { + fileDirectory.Metadata.Add(keyValuePair); + } + } + + bool needToSetProperties = false; + + try + { + fileDirectory.CreateAsync(Transfer_RequestOptions.DefaultFileRequestOptions, null, cancellationToken).GetAwaiter().GetResult(); + return; + } + catch (StorageException ex) + { + if (null != ex.RequestInformation) + { + if (string.Equals("ParentNotFound", ex.RequestInformation.ErrorCode)) + { + parentNotExist = true; + } + else if (string.Equals("ResourceAlreadyExists", ex.RequestInformation.ErrorCode)) + { + needToSetProperties = true; + } + else + { + throw; + } + } + else + { + throw; + } + } + + if (parentNotExist) + { + Utils.CreateCloudFileDirectoryRecursively(fileDirectory.Parent); + try + { + fileDirectory.CreateAsync(Transfer_RequestOptions.DefaultFileRequestOptions, null, cancellationToken).GetAwaiter().GetResult(); + } + catch (StorageException ex) + { + if (null != ex.RequestInformation) + { + if (string.Equals("ResourceAlreadyExists", ex.RequestInformation.ErrorCode)) + { + needToSetProperties = true; + } + else + { + throw; + } + } + else + { + throw; + } + } + } + + if (needToSetProperties) + { + SetAzureFileDirectoryAttributes(fileDirectory, fileAttributes, creationTime, lastWriteTime, metadata, cancellationToken); + } + } + + private static void SetAzureFileDirectoryAttributes( + CloudFileDirectory fileDirectory, + CloudFileNtfsAttributes? fileAttributes, + DateTimeOffset? creationTime, + DateTimeOffset? lastWriteTime, + IDictionary metadata, + CancellationToken cancellationToken) + { + if (fileAttributes.HasValue || null != metadata) + { + fileDirectory.FetchAttributesAsync(null, Transfer_RequestOptions.DefaultFileRequestOptions, null, cancellationToken).GetAwaiter().GetResult(); + + if (fileAttributes.HasValue) + { + if (fileDirectory.Properties.NtfsAttributes != fileAttributes.Value + || fileDirectory.Properties.CreationTime != creationTime.Value + || fileDirectory.Properties.LastWriteTime != lastWriteTime.Value) + { + fileDirectory.Properties.NtfsAttributes = fileAttributes.Value; + fileDirectory.Properties.CreationTime = creationTime; + fileDirectory.Properties.LastWriteTime = lastWriteTime; + fileDirectory.SetPropertiesAsync(Transfer_RequestOptions.DefaultFileRequestOptions, null, cancellationToken).GetAwaiter().GetResult(); + } + } + + if (null != metadata) + { + if (!metadata.DictionaryEquals(fileDirectory.Metadata)) + { + fileDirectory.Metadata.Clear(); + foreach (var keyValuePair in metadata) + { + fileDirectory.Metadata.Add(keyValuePair); + } + + fileDirectory.SetMetadataAsync(null, Transfer_RequestOptions.DefaultFileRequestOptions, null, cancellationToken).GetAwaiter().GetResult(); + } + } + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `sourceFileDirLocation` last assigned on line 297 could be null and is dereferenced at line 299, column 21. + +### Severity: +ERROR + +### Procedure: +Void SubDirectoryTransfer.CreateDestinationDirectory(CancellationToken) + +### File: +lib/TransferJobs/SubDirectoryTransfer.cs + +### Key: +SubDirectoryTransfer.cs|CreateDestinationDirectory|NULL_DEREFERENCE + +### Node Key: +2ecce4273ada11ad161ca44c6f340c1e + +### Hash: +d20328e69f66af499f952e3609e8afc3 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0681/instruction.md b/inferredbugs-0681/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..273ff10337bf7996c239c42490d9dd67764dde8b --- /dev/null +++ b/inferredbugs-0681/instruction.md @@ -0,0 +1,197 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** dnlib +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using dot10.IO; +using dot10.PE; + +namespace dot10.dotNET { + /// + /// + /// + public sealed class DotNetFile : IDisposable { + IMetaData metaData; + + enum MetaDataType { + Unknown, + Compressed, // #~ (normal) + ENC, // #- (edit and continue) + } + + /// + /// Create a instance + /// + /// The file to load + /// A new instance + public static DotNetFile Load(string fileName) { + return Load(new PEImage(fileName)); + } + + /// + /// Create a instance + /// + /// The .NET file data + /// A new instance + public static DotNetFile Load(byte[] data) { + return Load(new PEImage(data)); + } + + /// + /// Create a instance + /// + /// Address of a .NET file in memory + /// A new instance + public static DotNetFile Load(IntPtr addr) { + return Load(new PEImage(addr)); + } + + /// + /// Create a instance + /// + /// The PE image + /// A new instance + public static DotNetFile Load(IPEImage peImage) { + return Load(peImage, true); + } + + /// + /// Create a instance + /// + /// The PE image + /// true if we should verify that it's a .NET PE file + /// A new instance + public static DotNetFile Load(IPEImage peImage, bool verify) { + IImageStream cor20HeaderStream = null, mdHeaderStream = null; + MetaData md = null; + try { + var dotNetDir = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[14]; + if (dotNetDir.VirtualAddress == RVA.Zero) + throw new BadImageFormatException(".NET data directory RVA is 0"); + if (dotNetDir.Size < 0x48) + throw new BadImageFormatException(".NET data directory size < 0x48"); + var cor20Header = new ImageCor20Header(cor20HeaderStream = peImage.CreateStream(dotNetDir.VirtualAddress, 0x48), verify); + if (cor20Header.HasNativeHeader) + throw new BadImageFormatException(".NET native header isn't supported"); //TODO: Fix this + if (cor20Header.MetaData.VirtualAddress == RVA.Zero) + throw new BadImageFormatException(".NET MetaData RVA is 0"); + if (cor20Header.MetaData.Size < 16) + throw new BadImageFormatException(".NET MetaData size is too small"); + var mdSize = cor20Header.MetaData.Size; + var mdRva = cor20Header.MetaData.VirtualAddress; + var mdHeader = new MetaDataHeader(mdHeaderStream = peImage.CreateStream(mdRva, mdSize), verify); + if (verify) { + foreach (var sh in mdHeader.StreamHeaders) { + if (sh.Offset + sh.StreamSize < sh.Offset || sh.Offset + sh.StreamSize > mdSize) + throw new BadImageFormatException("Invalid stream header"); + } + } + + switch (GetMetaDataType(mdHeader.StreamHeaders)) { + case MetaDataType.Compressed: + md = new CompressedMetaData(peImage, cor20Header, mdHeader); + break; + + case MetaDataType.ENC: + md = new ENCMetaData(peImage, cor20Header, mdHeader); + break; + + default: + throw new BadImageFormatException("No #~ or #- stream found"); + } + md.Initialize(); + + return new DotNetFile(md); + } + catch { + if (md != null) + md.Dispose(); + throw; + } + finally { + if (cor20HeaderStream != null) + cor20HeaderStream.Dispose(); + if (mdHeaderStream != null) + mdHeaderStream.Dispose(); + } + } + + DotNetFile(IMetaData metaData) { + this.metaData = metaData; + } + + static MetaDataType GetMetaDataType(IList streamHeaders) { + foreach (var sh in streamHeaders) { + if (sh.Name == "#~") + return MetaDataType.Compressed; + if (sh.Name == "#-") + return MetaDataType.ENC; + } + return MetaDataType.Unknown; + } + + /// + public void Dispose() { + if (metaData != null) + metaData.Dispose(); + metaData = null; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of dot10.PE.PEImage::.ctor() at Line 26) of type dot10.PE.PEImage in method "DotNetFile DotNetFile.Load(String)". + +### Severity: +ERROR + +### Procedure: +DotNetFile DotNetFile.Load(String) + +### File: +dot10/dotNET/DotNetFile.cs + +### Key: +DotNetFile.cs|Load|DOTNET_RESOURCE_LEAK + +### Hash: +bb9ef1fafa1ea955f4d762bbd9f19f03 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0686/instruction.md b/inferredbugs-0686/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2e00f1cb55ddc1c8cad5cd98707285d70a9f2e4b --- /dev/null +++ b/inferredbugs-0686/instruction.md @@ -0,0 +1,197 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** dnlib +**Bug ID:** 5 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using dot10.IO; +using dot10.PE; + +namespace dot10.dotNET { + /// + /// + /// + public sealed class DotNetFile : IDisposable { + IMetaData metaData; + + enum MetaDataType { + Unknown, + Compressed, // #~ (normal) + ENC, // #- (edit and continue) + } + + /// + /// Create a instance + /// + /// The file to load + /// A new instance + public static DotNetFile Load(string fileName) { + return Load(new PEImage(fileName)); + } + + /// + /// Create a instance + /// + /// The .NET file data + /// A new instance + public static DotNetFile Load(byte[] data) { + return Load(new PEImage(data)); + } + + /// + /// Create a instance + /// + /// Address of a .NET file in memory + /// A new instance + public static DotNetFile Load(IntPtr addr) { + return Load(new PEImage(addr)); + } + + /// + /// Create a instance + /// + /// The PE image + /// A new instance + public static DotNetFile Load(IPEImage peImage) { + return Load(peImage, true); + } + + /// + /// Create a instance + /// + /// The PE image + /// true if we should verify that it's a .NET PE file + /// A new instance + public static DotNetFile Load(IPEImage peImage, bool verify) { + IImageStream cor20HeaderStream = null, mdHeaderStream = null; + MetaData md = null; + try { + var dotNetDir = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[14]; + if (dotNetDir.VirtualAddress == RVA.Zero) + throw new BadImageFormatException(".NET data directory RVA is 0"); + if (dotNetDir.Size < 0x48) + throw new BadImageFormatException(".NET data directory size < 0x48"); + var cor20Header = new ImageCor20Header(cor20HeaderStream = peImage.CreateStream(dotNetDir.VirtualAddress, 0x48), verify); + if (cor20Header.HasNativeHeader) + throw new BadImageFormatException(".NET native header isn't supported"); //TODO: Fix this + if (cor20Header.MetaData.VirtualAddress == RVA.Zero) + throw new BadImageFormatException(".NET MetaData RVA is 0"); + if (cor20Header.MetaData.Size < 16) + throw new BadImageFormatException(".NET MetaData size is too small"); + var mdSize = cor20Header.MetaData.Size; + var mdRva = cor20Header.MetaData.VirtualAddress; + var mdHeader = new MetaDataHeader(mdHeaderStream = peImage.CreateStream(mdRva, mdSize), verify); + if (verify) { + foreach (var sh in mdHeader.StreamHeaders) { + if (sh.Offset + sh.StreamSize < sh.Offset || sh.Offset + sh.StreamSize > mdSize) + throw new BadImageFormatException("Invalid stream header"); + } + } + + switch (GetMetaDataType(mdHeader.StreamHeaders)) { + case MetaDataType.Compressed: + md = new CompressedMetaData(peImage, cor20Header, mdHeader); + break; + + case MetaDataType.ENC: + md = new ENCMetaData(peImage, cor20Header, mdHeader); + break; + + default: + throw new BadImageFormatException("No #~ or #- stream found"); + } + md.Initialize(); + + return new DotNetFile(md); + } + catch { + if (md != null) + md.Dispose(); + throw; + } + finally { + if (cor20HeaderStream != null) + cor20HeaderStream.Dispose(); + if (mdHeaderStream != null) + mdHeaderStream.Dispose(); + } + } + + DotNetFile(IMetaData metaData) { + this.metaData = metaData; + } + + static MetaDataType GetMetaDataType(IList streamHeaders) { + foreach (var sh in streamHeaders) { + if (sh.Name == "#~") + return MetaDataType.Compressed; + if (sh.Name == "#-") + return MetaDataType.ENC; + } + return MetaDataType.Unknown; + } + + /// + public void Dispose() { + if (metaData != null) + metaData.Dispose(); + metaData = null; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of dot10.PE.PEImage::.ctor() at Line 35) of type dot10.PE.PEImage in method "DotNetFile DotNetFile.Load(Byte[])". + +### Severity: +ERROR + +### Procedure: +DotNetFile DotNetFile.Load(Byte[]) + +### File: +dot10/dotNET/DotNetFile.cs + +### Key: +DotNetFile.cs|Load|DOTNET_RESOURCE_LEAK + +### Hash: +0696b59a1212c798a72f6c904e9bd9a0 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0688/instruction.md b/inferredbugs-0688/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4ab87d06b9e0e9b9619cb26b2dda80ed4240c5e2 --- /dev/null +++ b/inferredbugs-0688/instruction.md @@ -0,0 +1,96 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Soulseek.NET +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace Soulseek.NET.Tests.Unit +{ + using Xunit; + + public class SoulseekClientTests + { + [Trait("Category", "Instantiation")] + [Fact(DisplayName = "Uses defaults for minimal constructor")] + public void Uses_Defaults_For_Minimal_Constructor() + { + var s = new SoulseekClient(); + + var defaultServer = s.GetField("DefaultAddress"); + var defaultPort = s.GetField("DefaultPort"); + var defaultOptions = new SoulseekClientOptions(); + + Assert.Equal(defaultServer, s.Address); + Assert.Equal(defaultPort, s.Port); + Assert.Equal(defaultOptions, s.Options); + } + + [Trait("Category", "Instantiation")] + [Fact(DisplayName = "Instantiates without exception")] + public void Instantiates_Without_Exception() + { + SoulseekClient s = null; + + var ex = Record.Exception(() => s = new SoulseekClient()); + + Assert.Null(ex); + Assert.NotNull(s); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `null` is dereferenced by call to `SoulseekClient(...)` at line 11, column 13. + +### Severity: +ERROR + +### Procedure: +Void SoulseekClientTests.Uses_Defaults_For_Minimal_Constructor() + +### File: +tests/Soulseek.NET.Tests.Unit/SoulseekClientTests.cs + +### Key: +SoulseekClientTests.cs|Uses_Defaults_For_Minimal_Constructor|NULL_DEREFERENCE + +### Node Key: +af4afc3f16bbd4d47126044f9dac65e9 + +### Hash: +c67ac206061fa372d312d36c509c15aa + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0706/instruction.md b/inferredbugs-0706/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b45d62c7dcb9bafae2dbc979e40f6402036cc263 --- /dev/null +++ b/inferredbugs-0706/instruction.md @@ -0,0 +1,273 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** python-language-server +**Bug ID:** 8 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// Copyright(c) Microsoft Corporation +// All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the License); you may not use +// this file except in compliance with the License. You may obtain a copy of the +// License at http://www.apache.org/licenses/LICENSE-2.0 +// +// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS +// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY +// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +// MERCHANTABILITY OR NON-INFRINGEMENT. +// +// See the Apache Version 2.0 License for specific language governing +// permissions and limitations under the License. + +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.Python.Analysis.Analyzer.Evaluation; +using Microsoft.Python.Analysis.Documents; +using Microsoft.Python.Analysis.Specializations.Typing; +using Microsoft.Python.Analysis.Values; +using Microsoft.Python.Core; +using Microsoft.Python.Parsing.Ast; + +namespace Microsoft.Python.Analysis.Types { + /// + /// Delegate that is invoked to determine function return type dynamically. + /// Can be used in specializations or when return type depends on actual arguments. + /// + /// Module making the call. + /// Function overload the return value is requested for. + /// Call arguments. + /// + public delegate IMember ReturnValueProvider( + IPythonModule declaringModule, + IPythonFunctionOverload overload, + IArgumentSet args); + + internal sealed class PythonFunctionOverload : LocatedMember, IPythonFunctionOverload { + private readonly string _returnDocumentation; + + // Allow dynamic function specialization, such as defining return types for builtin + // functions that are impossible to scrape and that are missing from stubs. + // Parameters: declaring module, overload for the return value, list of arguments. + private ReturnValueProvider _returnValueProvider; + + // Return value can be an instance or a type info. Consider type(C()) returning + // type info of C vs. return C() that returns an instance of C. + private Func _documentationProvider; + private bool _fromAnnotation; + + public PythonFunctionOverload(FunctionDefinition fd, IPythonClassMember classMember, Location location) + : this(fd.Name, location) { + FunctionDefinition = fd; + ClassMember = classMember; + var ast = (location.Module as IDocument)?.Analysis.Ast; + _returnDocumentation = ast != null ? fd.ReturnAnnotation?.ToCodeString(ast) : null; + } + + public PythonFunctionOverload(string name, Location location) : base(location) { + Name = name ?? throw new ArgumentNullException(nameof(name)); + } + + #region ILocatedMember + + public override PythonMemberType MemberType => PythonMemberType.Function; + + #endregion + + internal void SetParameters(IReadOnlyList parameters) => Parameters = parameters; + + internal void SetDocumentationProvider(Func documentationProvider) + => _documentationProvider = _documentationProvider ?? documentationProvider; + + internal void AddReturnValue(IMember value) { + if (value.IsUnknown()) { + return; // Don't add useless values. + } + + if (StaticReturnValue.IsUnknown()) { + SetReturnValue(value, false); + return; + } + + // If return value is set from annotation, it should not be changing. + var currentType = StaticReturnValue.GetPythonType(); + var valueType = value.GetPythonType(); + if (!_fromAnnotation && !currentType.Equals(valueType)) { + var type = PythonUnionType.Combine(currentType, valueType); + // Track instance vs type info. + StaticReturnValue = value is IPythonInstance ? new PythonInstance(type) : (IMember)type; + } + } + + internal void SetReturnValue(IMember value, bool fromAnnotation) { + StaticReturnValue = value; + _fromAnnotation = fromAnnotation; + } + + internal void SetReturnValueProvider(ReturnValueProvider provider) + => _returnValueProvider = provider; + + #region IPythonFunctionOverload + + public FunctionDefinition FunctionDefinition { get; } + public IPythonClassMember ClassMember { get; } + public string Name { get; } + + public string Documentation { + get { + var s = _documentationProvider?.Invoke(Name); + if (string.IsNullOrEmpty(s)) { + s = FunctionDefinition.GetDocumentation(); + } + + return s ?? string.Empty; + } + } + + public string GetReturnDocumentation(IPythonType self = null) { + if (self != null) { + var returnType = GetSpecificReturnType(self as IPythonClassType, null); + if (!returnType.IsUnknown()) { + return returnType.GetPythonType().Name; + } + } + + return _returnDocumentation; + } + + public IReadOnlyList Parameters { get; private set; } = Array.Empty(); + public IMember StaticReturnValue { get; private set; } + + public IMember Call(IArgumentSet args, IPythonType self, Node callLocation = null) { + if (!_fromAnnotation) { + // First try supplied specialization callback. + var rt = _returnValueProvider?.Invoke(DeclaringModule, this, args); + if (!rt.IsUnknown()) { + return rt; + } + } + + return GetSpecificReturnType(self as IPythonClassType, args); + } + + #endregion + + private IMember GetSpecificReturnType(IPythonClassType selfClassType, IArgumentSet args) { + var returnType = StaticReturnValue.GetPythonType(); + switch (returnType) { + case PythonClassType cls when cls.IsGeneric(): + return CreateSpecificReturnFromClassType(selfClassType, cls, args); // -> A[_T1, _T2, ...] + + case IGenericTypeDefinition gtd1 when selfClassType != null: + return CreateSpecificReturnFromTypeVar(selfClassType, gtd1); // -> _T + + case IGenericTypeDefinition gtd2 when args != null: // -> T on standalone function. + return args.Arguments.FirstOrDefault(a => gtd2.Equals(a.Type))?.Value as IMember; + + case IGenericType gt when args != null: // -> CLASS[T] on standalone function (i.e. -> List[T]). + var typeArgs = ExpressionEval.GetTypeArgumentsFromParameters(this, args); + return gt.CreateSpecificType(typeArgs); + } + + return null; + } + + private IMember CreateSpecificReturnFromClassType(IPythonClassType selfClassType, PythonClassType returnClassType, IArgumentSet args) { + // -> A[_T1, _T2, ...] + // Match arguments + IReadOnlyList typeArgs = null; + var classGenericParameters = selfClassType?.GenericParameters.Keys.ToArray() ?? Array.Empty(); + if (classGenericParameters.Length > 0 && selfClassType != null) { + // Declaring class is specific and provides definitions of generic parameters + typeArgs = classGenericParameters + .Select(n => selfClassType.GenericParameters.TryGetValue(n, out var t) ? t : null) + .ExcludeDefault() + .ToArray(); + } else if (args != null) { + typeArgs = ExpressionEval.GetTypeArgumentsFromParameters(this, args); + } + + if (typeArgs != null) { + var specificReturnValue = returnClassType.CreateSpecificType(new ArgumentSet(typeArgs)); + return new PythonInstance(specificReturnValue); + } + + return null; + } + + private IMember CreateSpecificReturnFromTypeVar(IPythonClassType selfClassType, IGenericTypeDefinition returnType) { + if (selfClassType.GenericParameters.TryGetValue(returnType.Name, out var specificType)) { + return new PythonInstance(specificType); + } + + // Try returning the constraint + // TODO: improve this, the heuristic is pretty basic and tailored to simple func(_T) -> _T + var name = StaticReturnValue.GetPythonType()?.Name; + var typeDefVar = DeclaringModule.Analysis.GlobalScope.Variables[name]; + if (typeDefVar?.Value is IGenericTypeDefinition gtp2) { + // See if the instance (self) type satisfies one of the constraints. + return selfClassType.Mro.Any(b => gtp2.Constraints.Any(c => c.Equals(b))) + ? selfClassType + : gtp2.Constraints.FirstOrDefault(); + } + + return null; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `currentType` last assigned on line 87 could be null and is dereferenced at line 94, column 9. + +### Severity: +ERROR + +### Procedure: +Void PythonFunctionOverload.AddReturnValue(IMember) + +### File: +src/Analysis/Ast/Impl/Types/PythonFunctionOverload.cs + +### Key: +PythonFunctionOverload.cs|AddReturnValue|NULL_DEREFERENCE + +### Node Key: +552d43ca4ba53a966acfd00b187c48fd + +### Hash: +b1d31969d51948d6f0e7276d06e50f2a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0707/instruction.md b/inferredbugs-0707/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..092f7d70483daeeb3e219edfdadd801e70e9b14a --- /dev/null +++ b/inferredbugs-0707/instruction.md @@ -0,0 +1,271 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** python-language-server +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// Copyright(c) Microsoft Corporation +// All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the License); you may not use +// this file except in compliance with the License. You may obtain a copy of the +// License at http://www.apache.org/licenses/LICENSE-2.0 +// +// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS +// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY +// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +// MERCHANTABILITY OR NON-INFRINGEMENT. +// +// See the Apache Version 2.0 License for specific language governing +// permissions and limitations under the License. + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Python.Analysis.Analyzer; +using Microsoft.Python.Analysis.Core.DependencyResolution; +using Microsoft.Python.Analysis.Core.Interpreter; +using Microsoft.Python.Analysis.Documents; +using Microsoft.Python.Analysis.Types; +using Microsoft.Python.Core; +using Microsoft.Python.Core.Diagnostics; +using Microsoft.Python.Core.IO; + +namespace Microsoft.Python.Analysis.Modules.Resolution { + internal sealed class MainModuleResolution : ModuleResolutionBase, IModuleManagement { + private readonly ConcurrentDictionary _specialized = new ConcurrentDictionary(); + private IReadOnlyList _searchPaths; + + public MainModuleResolution(string root, IServiceContainer services) + : base(root, services) { } + + internal async Task InitializeAsync(CancellationToken cancellationToken = default) { + // Add names from search paths + await ReloadAsync(cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + + // Initialize built-in + var moduleName = BuiltinTypeId.Unknown.GetModuleName(_interpreter.LanguageVersion); + var modulePath = ModuleCache.GetCacheFilePath(_interpreter.Configuration.InterpreterPath); + + var b = new BuiltinsPythonModule(moduleName, modulePath, _services); + BuiltinsModule = b; + _modules[BuiltinModuleName] = new ModuleRef(b); + } + + public async Task> GetSearchPathsAsync(CancellationToken cancellationToken = default) { + if (_searchPaths != null) { + return _searchPaths; + } + + _searchPaths = await GetInterpreterSearchPathsAsync(cancellationToken); + Debug.Assert(_searchPaths != null, "Should have search paths"); + _searchPaths = _searchPaths != null + ? Configuration.SearchPaths != null + ? _searchPaths.Concat(Configuration.SearchPaths).ToArray() + : _searchPaths + : Array.Empty(); + + _log?.Log(TraceEventType.Information, "SearchPaths:"); + foreach (var s in _searchPaths) { + _log?.Log(TraceEventType.Information, $" {s}"); + } + return _searchPaths; + } + + protected override IPythonModule CreateModule(string name) { + var moduleImport = CurrentPathResolver.GetModuleImportFromModuleName(name); + if (moduleImport == null) { + _log?.Log(TraceEventType.Verbose, "Import not found: ", name); + return null; + } + + var rdt = _services.GetService(); + IPythonModule module; + if (!string.IsNullOrEmpty(moduleImport.ModulePath) && Uri.TryCreate(moduleImport.ModulePath, UriKind.Absolute, out var uri)) { + module = rdt.GetDocument(uri); + if (module != null) { + return module; + } + } + + // If there is a stub, make sure it is loaded and attached + // First check stub next to the module. + if (!TryCreateModuleStub(name, moduleImport.ModulePath, out var stub)) { + // If nothing found, try Typeshed. + stub = _interpreter.TypeshedResolution.GetOrLoadModule(moduleImport.IsBuiltin ? name : moduleImport.FullName); + } + + // If stub is created and its path equals to module, return that stub as module + if (stub != null && stub.FilePath.PathEquals(moduleImport.ModulePath)) { + return stub; + } + + if (moduleImport.IsBuiltin) { + _log?.Log(TraceEventType.Verbose, "Create built-in compiled (scraped) module: ", name, Configuration.InterpreterPath); + module = new CompiledBuiltinPythonModule(name, stub, _services); + } else if (moduleImport.IsCompiled) { + _log?.Log(TraceEventType.Verbose, "Create compiled (scraped): ", moduleImport.FullName, moduleImport.ModulePath, moduleImport.RootPath); + module = new CompiledPythonModule(moduleImport.FullName, ModuleType.Compiled, moduleImport.ModulePath, stub, _services); + } else { + _log?.Log(TraceEventType.Verbose, "Import: ", moduleImport.FullName, moduleImport.ModulePath); + // Module inside workspace == user code. + + var mco = new ModuleCreationOptions { + ModuleName = moduleImport.FullName, + ModuleType = moduleImport.IsLibrary ? ModuleType.Library : ModuleType.User, + FilePath = moduleImport.ModulePath, + Stub = stub + }; + module = rdt.AddModule(mco); + } + + return module; + } + + private async Task> GetInterpreterSearchPathsAsync(CancellationToken cancellationToken = default) { + if (!_fs.FileExists(Configuration.InterpreterPath)) { + return Array.Empty(); + } + + _log?.Log(TraceEventType.Information, "GetCurrentSearchPaths", Configuration.InterpreterPath); + try { + var paths = await PythonLibraryPath.GetSearchPathsAsync(Configuration); + cancellationToken.ThrowIfCancellationRequested(); + return paths.MaybeEnumerate().Select(p => p.Path).ToArray(); + } catch (InvalidOperationException) { + return Array.Empty(); + } + } + + /// + /// Provides ability to specialize module by replacing module import by + /// implementation in code. Real module + /// content is loaded and analyzed only for class/functions definitions + /// so the original documentation can be extracted. + /// + /// Module to specialize. + /// Specialized module constructor. + /// Original (library) module loaded as stub. + public IPythonModule SpecializeModule(string name, Func specializationConstructor) { + var import = CurrentPathResolver.GetModuleImportFromModuleName(name); + var module = specializationConstructor(import?.ModulePath); + _specialized[name] = module; + return module; + } + + /// + /// Returns specialized module, if any. + /// + public IPythonModule GetSpecializedModule(string name) + => _specialized.TryGetValue(name, out var module) ? module : null; + + internal async Task LoadBuiltinTypesAsync(CancellationToken cancellationToken = default) { + await BuiltinsModule.LoadAndAnalyzeAsync(cancellationToken); + + Check.InvalidOperation(!(BuiltinsModule.Analysis is EmptyAnalysis), "After await"); + + // Add built-in module names + var builtinModuleNamesMember = BuiltinsModule.GetAnyMember("__builtin_module_names__"); + if (builtinModuleNamesMember.TryGetConstant(out var s)) { + var builtinModuleNames = s.Split(',').Select(n => n.Trim()); + PathResolver.SetBuiltins(builtinModuleNames); + } + } + + public async Task ReloadAsync(CancellationToken cancellationToken = default) { + ModuleCache = new ModuleCache(_interpreter, _services); + PathResolver = new PathResolver(_interpreter.LanguageVersion); + + var addedRoots = new HashSet(); + addedRoots.UnionWith(PathResolver.SetRoot(_root)); + + var interpreterPaths = await GetSearchPathsAsync(cancellationToken); + addedRoots.UnionWith(PathResolver.SetInterpreterSearchPaths(interpreterPaths)); + + addedRoots.UnionWith(SetUserSearchPaths(_interpreter.Configuration.SearchPaths)); + ReloadModulePaths(addedRoots); + } + + public IEnumerable SetUserSearchPaths(in IEnumerable searchPaths) + => PathResolver.SetUserSearchPaths(searchPaths); + + // For tests + internal void AddUnimportableModule(string moduleName) + => _modules[moduleName] = new ModuleRef(new SentinelModule(moduleName, _services)); + + private bool TryCreateModuleStub(string name, string modulePath, out IPythonModule module) { + // First check stub next to the module. + if (!string.IsNullOrEmpty(modulePath)) { + var pyiPath = Path.ChangeExtension(modulePath, "pyi"); + if (_fs.FileExists(pyiPath)) { + module = new StubPythonModule(name, pyiPath, false, _services); + return true; + } + } + + // Try location of stubs that are in a separate folder next to the package. + var stubPath = CurrentPathResolver.GetPossibleModuleStubPaths(name).FirstOrDefault(p => _fs.FileExists(p)); + module = !string.IsNullOrEmpty(stubPath) ? new StubPythonModule(name, stubPath, false, _services) : null; + return module != null; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Microsoft.Python.Analysis.Modules.SentinelModule::.ctor() at Line 194) of type Microsoft.Python.Analysis.Modules.SentinelModule in method "Void MainModuleResolution.AddUnimportableModule(String)". + +### Severity: +ERROR + +### Procedure: +Void MainModuleResolution.AddUnimportableModule(String) + +### File: +src/Analysis/Ast/Impl/Modules/Resolution/MainModuleResolution.cs + +### Key: +MainModuleResolution.cs|AddUnimportableModule|DOTNET_RESOURCE_LEAK + +### Hash: +87fddb7ba2cdca64a7e3a1fd26dbfc98 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0708/instruction.md b/inferredbugs-0708/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f619442c27bf4792f823c538af68cd33c048e2d3 --- /dev/null +++ b/inferredbugs-0708/instruction.md @@ -0,0 +1,515 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** python-language-server +**Bug ID:** 15 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// Copyright(c) Microsoft Corporation +// All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the License); you may not use +// this file except in compliance with the License. You may obtain a copy of the +// License at http://www.apache.org/licenses/LICENSE-2.0 +// +// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS +// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY +// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +// MERCHANTABILITY OR NON-INFRINGEMENT. +// +// See the Apache Version 2.0 License for specific language governing +// permissions and limitations under the License. + +using Microsoft.Python.Analysis.Diagnostics; +using Microsoft.Python.Analysis.Modules; +using Microsoft.Python.Analysis.Types; +using Microsoft.Python.Analysis.Types.Collections; +using Microsoft.Python.Analysis.Values; +using Microsoft.Python.Core; +using Microsoft.Python.Parsing; +using Microsoft.Python.Parsing.Ast; +using ErrorCodes = Microsoft.Python.Analysis.Diagnostics.ErrorCodes; + +namespace Microsoft.Python.Analysis.Analyzer.Evaluation { + internal sealed partial class ExpressionEval { + private IMember GetValueFromUnaryOp(UnaryExpression expr) { + switch (expr.Op) { + case PythonOperator.Not: + case PythonOperator.Is: + case PythonOperator.IsNot: + // Assume all of these return True/False + return Interpreter.GetBuiltinType(BuiltinTypeId.Bool); + + case PythonOperator.Invert: + return GetValueFromUnaryOp(expr, "__invert__"); + case PythonOperator.Negate: + return GetValueFromUnaryOp(expr, "__neg__"); + case PythonOperator.Pos: + return GetValueFromUnaryOp(expr, "__pos__"); + } + return UnknownType; + } + + private IMember GetValueFromUnaryOp(UnaryExpression expr, string op) { + var target = GetValueFromExpression(expr.Expression); + if (target is IPythonInstance instance) { + var fn = instance.GetPythonType()?.GetMember(op); + // Process functions declared in code modules. Scraped/compiled/stub modules do not actually perform any operations. + if (fn?.DeclaringModule != null && (fn.DeclaringModule.ModuleType == ModuleType.User || fn.DeclaringModule.ModuleType == ModuleType.Library)) { + var result = fn.Call(instance, op, ArgumentSet.Empty(expr, this)); + if (!result.IsUnknown()) { + return result; + } + } + return instance is IPythonConstant c && instance.TryGetConstant(out var value) + ? new PythonConstant(-value, c.Type) + : instance; + } + return UnknownType; + } + + private IMember GetValueFromBinaryOp(Expression expr) { + if (expr is AndExpression a) { + GetValueFromExpression(a.Left); + GetValueFromExpression(a.Right); + return Interpreter.GetBuiltinType(BuiltinTypeId.Bool); + } + + if (expr is OrExpression orexp) { + // Consider 'self.__params = types.MappingProxyType(params or {})' + var leftSide = GetValueFromExpression(orexp.Left); + if (!leftSide.IsUnknown()) { + return leftSide; + } + var rightSide = GetValueFromExpression(orexp.Right); + return rightSide.IsUnknown() ? Interpreter.GetBuiltinType(BuiltinTypeId.Bool) : rightSide; + } + + if (!(expr is BinaryExpression binop) || binop.Left == null) { + return null; + } + + var op = binop.Operator; + + var left = GetValueFromExpression(binop.Left) ?? UnknownType; + var right = GetValueFromExpression(binop.Right) ?? UnknownType; + + if (left.IsUnknown() && right.IsUnknown()) { + // Fast path for when nothing below will give any results. + if (op.IsComparison()) { + return Interpreter.GetBuiltinType(BuiltinTypeId.Bool); + } + + return UnknownType; + } + + var leftType = left.GetPythonType(); + var rightType = right.GetPythonType(); + + var leftTypeId = leftType.TypeId; + var rightTypeId = rightType.TypeId; + + if (op == PythonOperator.Add + && leftTypeId == rightTypeId + && left is IPythonCollection lc && right is IPythonCollection rc) { + + switch (leftTypeId) { + case BuiltinTypeId.List: + return PythonCollectionType.CreateConcatenatedList(Module.Interpreter, lc, rc); + case BuiltinTypeId.Tuple: + return PythonCollectionType.CreateConcatenatedTuple(Module.Interpreter, lc, rc); + } + } + + // Mod-style string formatting; don't bother looking at the right side. + if (op == PythonOperator.Mod && (leftTypeId == BuiltinTypeId.Str || leftTypeId == BuiltinTypeId.Unicode)) { + return Interpreter.GetBuiltinType(leftTypeId); + } + + var leftIsSupported = IsSupportedBinopBuiltin(leftTypeId); + var rightIsSupported = IsSupportedBinopBuiltin(rightTypeId); + + if (leftIsSupported && rightIsSupported) { + if (TryGetValueFromBuiltinBinaryOp(op, leftTypeId, rightTypeId, Interpreter.LanguageVersion.Is3x(), out var member)) { + if (member.IsUnknown()) { + ReportOperatorDiagnostics(expr, leftType, rightType, op); + } + return member; + } + } + + if (leftIsSupported) { + IMember ret; + + if (op.IsComparison()) { + // If the op is a comparison, and the thing on the left is the builtin, + // flip the operation and call it instead. + ret = CallOperator(op.InvertComparison(), right, rightType, left, leftType, expr, tryRight: false); + } else { + ret = CallOperator(op, left, leftType, right, rightType, expr, tryLeft: false); + } + + if (!ret.IsUnknown()) { + return ret; + } + + return op.IsComparison() ? Interpreter.GetBuiltinType(BuiltinTypeId.Bool) : left; + } + + if (rightIsSupported) { + // Try calling the function on the left side, otherwise just return right. + var ret = CallOperator(op, left, leftType, right, rightType, expr, tryRight: false); + + if (!ret.IsUnknown()) { + return ret; + } + + return op.IsComparison() ? Interpreter.GetBuiltinType(BuiltinTypeId.Bool) : right; + } + + var callRet = CallOperator(op, left, leftType, right, rightType, expr); + if (!callRet.IsUnknown()) { + return callRet; + } + + if (op.IsComparison()) { + callRet = CallOperator(op.InvertComparison(), right, rightType, left, leftType, expr); + + if (!callRet.IsUnknown()) { + return callRet; + } + } + + // TODO: Specific parsing + // TODO: warn about incompatible types like 'str' + 1 + switch (op) { + case PythonOperator.Equal: + case PythonOperator.GreaterThan: + case PythonOperator.GreaterThanOrEqual: + case PythonOperator.In: + case PythonOperator.Is: + case PythonOperator.IsNot: + case PythonOperator.LessThan: + case PythonOperator.LessThanOrEqual: + case PythonOperator.Not: + case PythonOperator.NotEqual: + case PythonOperator.NotIn: + // Assume all of these return True/False + return Interpreter.GetBuiltinType(BuiltinTypeId.Bool); + + case PythonOperator.Divide: + case PythonOperator.TrueDivide: + if (Interpreter.LanguageVersion.Is3x()) { + return Interpreter.GetBuiltinType(BuiltinTypeId.Float); + } + + break; + } + + return left.IsUnknown() ? right : left; + } + + private IMember CallOperator(PythonOperator op, IMember left, IPythonType leftType, IMember right, IPythonType rightType, Expression expr, bool tryLeft = true, bool tryRight = true) { + var (funcName, swappedFuncName) = OpMethodName(op); + + if (tryLeft && funcName != null && left is IPythonInstance lpi) { + var ret = leftType.Call(lpi, funcName, new ArgumentSet(new[] { right }, expr, this)); + if (!ret.IsUnknown()) { + return ret; + } + } + + if (tryRight && swappedFuncName != null && right is IPythonInstance rpi) { + var ret = rightType.Call(rpi, swappedFuncName, new ArgumentSet(new[] { left }, expr, this)); + if (!ret.IsUnknown()) { + return ret; + } + } + + return null; + } + + /// + /// Try to get the result of a binary operation on builtin types. This does not actually do the operation, but maybe should. + /// + /// The operation being done. + /// The left side's type ID. + /// The right side's type ID. + /// True if the Python version is 3.x. + /// The resulting member. + /// True, if member is correct and no further checks should be done. + private bool TryGetValueFromBuiltinBinaryOp(PythonOperator op, BuiltinTypeId left, BuiltinTypeId right, bool is3x, out IMember member) { + if (op.IsComparison()) { + // All builtins compare to bool. + member = Interpreter.GetBuiltinType(BuiltinTypeId.Bool); + return true; + } + + member = UnknownType; + + switch (op) { + case PythonOperator.MatMultiply: + // No builtins implement this operator. + return true; + + case PythonOperator.BitwiseAnd: + case PythonOperator.BitwiseOr: + case PythonOperator.Xor: + switch (left) { + case BuiltinTypeId.Bool when right == BuiltinTypeId.Bool: + member = Interpreter.GetBuiltinType(BuiltinTypeId.Bool); + return true; + + case BuiltinTypeId.Bool when right == BuiltinTypeId.Int: + case BuiltinTypeId.Int when right == BuiltinTypeId.Bool: + case BuiltinTypeId.Int when right == BuiltinTypeId.Int: + member = Interpreter.GetBuiltinType(BuiltinTypeId.Int); + return true; + + case BuiltinTypeId.Long when right == BuiltinTypeId.Long: + case BuiltinTypeId.Long when right == BuiltinTypeId.Int: + case BuiltinTypeId.Long when right == BuiltinTypeId.Bool: + case BuiltinTypeId.Bool when right == BuiltinTypeId.Long: + case BuiltinTypeId.Int when right == BuiltinTypeId.Long: + member = Interpreter.GetBuiltinType(BuiltinTypeId.Long); + return true; + } + + // All other combinations of these bitwise operaton on builtin types fail. + return true; + } + + // At this point, @ & | ^ are all handled and do not need to be considered. + + if (CoalesceComplex(left, right)) { + switch (op) { + case PythonOperator.Add: + case PythonOperator.Multiply: + case PythonOperator.Power: + case PythonOperator.Subtract: + case PythonOperator.Divide: + case PythonOperator.TrueDivide: + case PythonOperator.FloorDivide when !is3x: + member = Interpreter.GetBuiltinType(BuiltinTypeId.Complex); + return true; + + case PythonOperator.FloorDivide when is3x: + // Complex numbers cannot be floordiv'd in Python 3. + return true; + } + } + + if (IsStringLike(left)) { + member = HandleStringLike(op, left, right); + return true; + } + + if (IsStringLike(right)) { + member = HandleStringLike(op, right, left); + return true; + } + + // All string-like cases have been handled. + + // If a complex value made it to here, then it wasn't coalesced or used in a string format; bail. + if (left == BuiltinTypeId.Complex || right == BuiltinTypeId.Complex) { + return true; + } + + switch (op) { + case PythonOperator.TrueDivide: + member = Interpreter.GetBuiltinType(BuiltinTypeId.Float); + return true; + + case PythonOperator.LeftShift: + case PythonOperator.RightShift: + if (IsIntegerLike(left) && IsIntegerLike(right)) { + if (left == BuiltinTypeId.Long || right == BuiltinTypeId.Long) { + member = Interpreter.GetBuiltinType(BuiltinTypeId.Long); + } else { + member = Interpreter.GetBuiltinType(BuiltinTypeId.Int); + } + return true; + } + + // If they aren't integer-like, then they can't be shifted. + return true; + + case PythonOperator.Add: + case PythonOperator.Divide: + case PythonOperator.FloorDivide: + case PythonOperator.Mod: + case PythonOperator.Power: + case PythonOperator.Subtract: + if (IsIntegerLike(left) && IsIntegerLike(right)) { + if (left == BuiltinTypeId.Long || right == BuiltinTypeId.Long) { + member = Interpreter.GetBuiltinType(BuiltinTypeId.Long); + } else { + member = Interpreter.GetBuiltinType(BuiltinTypeId.Int); + } + return true; + } else if (left == BuiltinTypeId.Float || right == BuiltinTypeId.Float) { + member = Interpreter.GetBuiltinType(BuiltinTypeId.Float); + return true; + } + break; + } + + return false; + } + + private static bool IsSupportedBinopBuiltin(BuiltinTypeId id) { + switch (id) { + case BuiltinTypeId.Bool: + case BuiltinTypeId.Int: + case BuiltinTypeId.Long: + case BuiltinTypeId.Float: + case BuiltinTypeId.Complex: + case BuiltinTypeId.Str: + case BuiltinTypeId.Bytes: + case BuiltinTypeId.Unicode: + return true; + } + + return false; + } + + private static bool IsIntegerLike(BuiltinTypeId id) => id == BuiltinTypeId.Bool || id == BuiltinTypeId.Int || id == BuiltinTypeId.Long; + + private bool CoalesceComplex(BuiltinTypeId a, BuiltinTypeId b) { + if (a != BuiltinTypeId.Complex && b == BuiltinTypeId.Complex) { + var tmp = a; + a = b; + b = tmp; + } + + if (a == BuiltinTypeId.Complex) { + switch (b) { + case BuiltinTypeId.Bool: + case BuiltinTypeId.Long: + case BuiltinTypeId.Int: + case BuiltinTypeId.Float: + case BuiltinTypeId.Complex: + return true; + } + } + + return false; + } + + private bool IsStringLike(BuiltinTypeId id) => id == BuiltinTypeId.Str || id == BuiltinTypeId.Bytes || id == BuiltinTypeId.Unicode; + + private IMember HandleStringLike(PythonOperator op, BuiltinTypeId str, BuiltinTypeId other) { + switch (op) { + case PythonOperator.Multiply when other == BuiltinTypeId.Bool || other == BuiltinTypeId.Int || other == BuiltinTypeId.Long: + case PythonOperator.Add when str == other: + return Interpreter.GetBuiltinType(str); + + case PythonOperator.Add when str == BuiltinTypeId.Unicode || other == BuiltinTypeId.Unicode: + return Interpreter.GetBuiltinType(BuiltinTypeId.Unicode); + } + + return UnknownType; + } + + private static (string name, string swappedName) OpMethodName(PythonOperator op) { + switch (op) { + // Unary operators + // Not cannot be overridden, there is no method for it. + case PythonOperator.Pos: return ("__pos__", null); + case PythonOperator.Invert: return ("__invert__", null); + case PythonOperator.Negate: return ("__neg__", null); + + // Numeric operators, can be swapped + case PythonOperator.Add: return ("__add__", "__radd__"); + case PythonOperator.Subtract: return ("__sub__", "__rsub__"); + case PythonOperator.Multiply: return ("__mul__", "__rmul__"); + case PythonOperator.MatMultiply: return ("__matmul__", "__rmatmul__"); + case PythonOperator.Divide: return ("__div__", "__rdiv__"); // The parser has already chosen the correct operator here; no need to check versions. + case PythonOperator.TrueDivide: return ("__truediv__", "__rtruediv__"); + case PythonOperator.Mod: return ("__mod__", "__rmod__"); + case PythonOperator.BitwiseAnd: return ("__and__", "__rand__"); + case PythonOperator.BitwiseOr: return ("__or__", "__ror__"); + case PythonOperator.Xor: return ("__xor__", "__rxor__"); + case PythonOperator.LeftShift: return ("__lshift__", "__rlshift__"); + case PythonOperator.RightShift: return ("__rshift__", "__rrshift__"); + case PythonOperator.Power: return ("__pow__", "__rpow__"); + case PythonOperator.FloorDivide: return ("__floordiv__", "__rfloordiv__"); + + // Comparison operators + case PythonOperator.LessThan: return ("__lt__", null); + case PythonOperator.LessThanOrEqual: return ("__le__", null); + case PythonOperator.GreaterThan: return ("__gt__", null); + case PythonOperator.GreaterThanOrEqual: return ("__ge__", null); + case PythonOperator.Equal: return ("__eq__", null); + case PythonOperator.NotEqual: return ("__ne__", null); + } + + return (null, null); + } + private void ReportOperatorDiagnostics(Expression expr, IPythonType leftType, IPythonType rightType, PythonOperator op) { + ReportDiagnostics(Module.Uri, new DiagnosticsEntry( + Resources.UnsupporedOperandType.FormatInvariant(op.ToCodeString(), leftType.Name, rightType.Name), + GetLocation(expr).Span, + ErrorCodes.UnsupportedOperandType, + Severity.Error, + DiagnosticSource.Analysis)); + } + + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `rightType` last assigned on line 100 could be null and is dereferenced at line 103, column 13. + +### Severity: +ERROR + +### Procedure: +IMember ExpressionEval.GetValueFromBinaryOp(Expression) + +### File: +src/Analysis/Ast/Impl/Analyzer/Evaluation/ExpressionEval.Operators.cs + +### Key: +ExpressionEval.Operators.cs|GetValueFromBinaryOp|NULL_DEREFERENCE + +### Node Key: +90535029835413c6e5d1bdebbf52bdf9 + +### Hash: +fb762a9879302b69e9ac474890a20fa8 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0709/instruction.md b/inferredbugs-0709/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a3680f5583f070db90df73a7a83ffb566176afc1 --- /dev/null +++ b/inferredbugs-0709/instruction.md @@ -0,0 +1,291 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** python-language-server +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// Python Tools for Visual Studio +// Copyright(c) Microsoft Corporation +// All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the License); you may not use +// this file except in compliance with the License. You may obtain a copy of the +// License at http://www.apache.org/licenses/LICENSE-2.0 +// +// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS +// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY +// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +// MERCHANTABILITY OR NON-INFRINGEMENT. +// +// See the Apache Version 2.0 License for specific language governing +// permissions and limitations under the License. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Python.LanguageServer; +using Microsoft.Python.LanguageServer.Implementation; +using Microsoft.PythonTools.Interpreter; +using Microsoft.PythonTools.Interpreter.Ast; +using TestUtilities; + +namespace Microsoft.PythonTools.Analysis { + internal static class ServerExtensions { + public static async Task InitializeAsync(this Server server, InterpreterConfiguration configuration, Uri rootUri = null, IEnumerable searchPaths = null) { + configuration.AssertInstalled(); + + server.OnLogMessage += Server_OnLogMessage; + var properties = new InterpreterFactoryCreationOptions { + TraceLevel = System.Diagnostics.TraceLevel.Verbose, + DatabasePath = TestData.GetAstAnalysisCachePath(configuration.Version) + }.ToDictionary(); + + configuration.WriteToDictionary(properties); + + await server.Initialize(new InitializeParams { + rootUri = rootUri, + initializationOptions = new PythonInitializationOptions { + interpreter = new PythonInitializationOptions.Interpreter { + assembly = typeof(AstPythonInterpreterFactory).Assembly.Location, + typeName = typeof(AstPythonInterpreterFactory).FullName, + properties = properties + }, + analysisUpdates = true, + searchPaths = searchPaths?.ToArray() ?? Array.Empty(), + traceLogging = true, + }, + capabilities = new ClientCapabilities { + python = new PythonClientCapabilities { + liveLinting = true, + } + } + }, CancellationToken.None); + + return server; + } + + public static Task GetAnalysisAsync(this Server server, Uri uri, int waitingTimeout = -1, int failAfter = 30000) + => ((ProjectEntry)server.ProjectFiles.GetEntry(uri)).GetAnalysisAsync(waitingTimeout, new CancellationTokenSource(failAfter).Token); + + public static Task EnqueueItemAsync(this Server server, Uri uri) + => server.EnqueueItemAsync((IDocument)server.ProjectFiles.GetEntry(uri)); + + public static async Task EnqueueItemsAsync(this Server server, CancellationToken cancellationToken, params IDocument[] projectEntries) { + foreach (var document in projectEntries) { + await server.EnqueueItemAsync(document); + } + } + + // TODO: Replace usages of AddModuleWithContent with OpenDefaultDocumentAndGetUriAsync + public static async Task AddModuleWithContentAsync(this Server server, string moduleName, string relativePath, string content) { + var entry = (ProjectEntry)server.Analyzer.AddModule(moduleName, TestData.GetTestSpecificPath(relativePath)); + entry.ResetDocument(0, content); + await server.EnqueueItemAsync(entry); + return entry; + } + + public static Task SendCompletion(this Server server, Uri uri, int line, int character) { + return server.Completion(new CompletionParams { + textDocument = new TextDocumentIdentifier { + uri = uri + }, + position = new Position { + line = line, + character = character + } + }, CancellationToken.None); + } + + public static Task SendHover(this Server server, Uri uri, int line, int character) { + return server.Hover(new TextDocumentPositionParams() { + textDocument = new TextDocumentIdentifier { + uri = uri + }, + position = new Position { + line = line, + character = character + } + }, CancellationToken.None); + } + + public static Task SendSignatureHelp(this Server server, Uri uri, int line, int character) { + return server.SignatureHelp(new TextDocumentPositionParams { + textDocument = uri, + position = new Position { + line = line, + character = character + } + }, CancellationToken.None); + } + + public static Task SendFindReferences(this Server server, Uri uri, int line, int character, bool includeDeclaration = true) { + return server.FindReferences(new ReferencesParams { + textDocument = uri, + position = new Position { + line = line, + character = character + }, + context = new ReferenceContext { + includeDeclaration = includeDeclaration, + _includeValues = true // For compatibility with PTVS + } + }, CancellationToken.None); + } + + public static async Task OpenDefaultDocumentAndGetUriAsync(this Server server, string content) { + var uri = TestData.GetDefaultModuleUri(); + await server.SendDidOpenTextDocument(uri, content); + return uri; + } + + public static async Task OpenNextDocumentAndGetUriAsync(this Server server, string content) { + var uri = TestData.GetNextModuleUri(); + await server.SendDidOpenTextDocument(uri, content); + return uri; + } + + public static async Task OpenDocumentAndGetUriAsync(this Server server, string relativePath, string content) { + var uri = TestData.GetTestSpecificUri(relativePath); + await server.SendDidOpenTextDocument(uri, content); + return uri; + } + + public static async Task SendDidOpenTextDocument(this Server server, Uri uri, string content, string languageId = null) { + await server.DidOpenTextDocument(new DidOpenTextDocumentParams { + textDocument = new TextDocumentItem { + uri = uri, + text = content, + languageId = languageId ?? "python" + } + }, CancellationToken.None); + } + + public static async Task OpenDefaultDocumentAndGetAnalysisAsync(this Server server, string content, int failAfter = 30000, string languageId = null) { + var cancellationToken = new CancellationTokenSource(failAfter).Token; + await server.SendDidOpenTextDocument(TestData.GetDefaultModuleUri(), content, languageId); + cancellationToken.ThrowIfCancellationRequested(); + var projectEntry = (ProjectEntry) server.ProjectFiles.Single(); + return await projectEntry.GetAnalysisAsync(cancellationToken: cancellationToken); + } + + public static Task SendDidChangeTextDocumentAsync(this Server server, Uri uri, string text) { + return server.DidChangeTextDocument(new DidChangeTextDocumentParams { + textDocument = new VersionedTextDocumentIdentifier { + uri = uri + }, + contentChanges = new [] { + new TextDocumentContentChangedEvent { + text = text, + }, + } + }, CancellationToken.None); + } + + public static Task SendDocumentOnTypeFormatting(this Server server, TextDocumentIdentifier textDocument, Position position, string ch) { + return server.DocumentOnTypeFormatting(new DocumentOnTypeFormattingParams { + textDocument = textDocument, + position = position, + ch = ch, + }, CancellationToken.None); + } + + public static Task SendDidChangeConfiguration(this Server server, ServerSettings.PythonCompletionOptions pythonCompletionOptions, int failAfter = 30000) { + var currentSettings = server.Settings; + var settings = new LanguageServerSettings(); + + settings.completion.showAdvancedMembers = pythonCompletionOptions.showAdvancedMembers; + settings.completion.addBrackets = pythonCompletionOptions.addBrackets; + + settings.analysis.openFilesOnly = currentSettings.analysis.openFilesOnly; + if (currentSettings is LanguageServerSettings languageServerSettings) { + settings.diagnosticPublishDelay = languageServerSettings.diagnosticPublishDelay; + settings.symbolsHierarchyDepthLimit = languageServerSettings.symbolsHierarchyDepthLimit; + } + + var errors = currentSettings.analysis.errors; + var warnings = currentSettings.analysis.warnings; + var information = currentSettings.analysis.information; + var disabled = currentSettings.analysis.disabled; + settings.analysis.SetErrorSeverityOptions(errors, warnings, information, disabled); + + return server.SendDidChangeConfiguration(settings, failAfter); + } + + public static Task SendDidChangeConfiguration(this Server server, ServerSettings settings, int failAfter = 30000) + => server.DidChangeConfiguration(new DidChangeConfigurationParams { settings = settings }, new CancellationTokenSource(failAfter).Token); + + public static async Task ChangeDefaultDocumentAndGetAnalysisAsync(this Server server, string text, int failAfter = 30000) { + var projectEntry = (ProjectEntry) server.ProjectFiles.Single(); + await server.SendDidChangeTextDocumentAsync(projectEntry.DocumentUri, text); + return await projectEntry.GetAnalysisAsync(cancellationToken: new CancellationTokenSource(failAfter).Token); + } + + public static string[] GetBuiltinTypeMemberNames(this Server server, BuiltinTypeId typeId) + => server.Analyzer.Types[typeId].GetMemberNames((IModuleContext)server.Analyzer.Interpreter).ToArray(); + + private static void Server_OnLogMessage(object sender, LogMessageEventArgs e) { + switch (e.type) { + case MessageType.Error: Trace.TraceError($"[{TestEnvironmentImpl.Elapsed()}]: {e.message}"); break; + case MessageType.Warning: Trace.TraceWarning($"[{TestEnvironmentImpl.Elapsed()}]: {e.message}"); break; + case MessageType.Info: Trace.TraceInformation($"[{TestEnvironmentImpl.Elapsed()}]: {e.message}"); break; + case MessageType.Log: Trace.TraceInformation($"[{TestEnvironmentImpl.Elapsed()}] LOG: {e.message}"); break; + } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of System.Threading.CancellationTokenSource::.ctor() at Line 65) of type System.Threading.CancellationTokenSource in method "Task`1 ServerExtensions.GetAnalysisAsync(Server,Uri,Int32,Int32)". + +### Severity: +ERROR + +### Procedure: +Task`1 ServerExtensions.GetAnalysisAsync(Server,Uri,Int32,Int32) + +### File: +src/Analysis/Engine/Test/ServerExtensions.cs + +### Key: +ServerExtensions.cs|GetAnalysisAsync|DOTNET_RESOURCE_LEAK + +### Hash: +6b07bdae1bb3a467d2e8f04b19515b01 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0730/instruction.md b/inferredbugs-0730/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..294e34ce5b19dad2e84eb19f453e41b23808b5cb --- /dev/null +++ b/inferredbugs-0730/instruction.md @@ -0,0 +1,338 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** lightlib-lms +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Collections.Generic; +using System.Linq; +using FluentAssertions; +using Library.Data; +using Library.Data.Models; +using Library.Web.Controllers; +using Library.Web.Models.Catalog; +using Microsoft.AspNetCore.Mvc; +using Moq; +using NUnit.Framework; + +namespace Library.Tests.Controllers +{ + [TestFixture] + public class CatalogControllerShould + { + [Test] + public void Return_Catalog_Index_View() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + + mockLibraryAssetService.Setup(r => r.GetAll()).Returns(GetAllAssets()); + + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = controller.Index(); + var viewResult = result.Should().BeOfType(); + var viewModel = viewResult.Subject.ViewData.Model.Should().BeAssignableTo(); + viewModel.Subject.Assets.Count().Should().Be(2); + } + + [Test] + public void Return_AssetIndexListingModel() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + + mockLibraryAssetService.Setup(r => r.GetAll()).Returns(GetAllAssets()); + + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = controller.Index(); + var viewResult = result.Should().BeOfType(); + viewResult.Subject.Model.Should().BeOfType(); + } + + [Test] + public void Return_Branch_Detail_View() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + mockLibraryAssetService.Setup(r => r.GetCurrentLocation(24)).Returns(new LibraryBranch + { + Name = "Main St. Library" + }); + + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = controller.Detail(24); + + var viewResult = result.Should().BeOfType(); + var viewModel = viewResult.Subject.ViewData.Model.Should().BeAssignableTo(); + + viewModel.Subject.Title.Should().Be("Orlando"); + } + + [Test] + public void Return_BranchDetailModel() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + mockLibraryAssetService.Setup(r => r.GetCurrentLocation(24)).Returns(new LibraryBranch + { + Name = "Main St. Library" + }); + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + var result = controller.Detail(24); + var viewResult = result.Should().BeOfType(); + + viewResult.Subject.Model.Should().BeOfType(); + } + + [Test] + public void Return_CheckIn_View() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + mockLibraryAssetService.Setup(r => r.GetCurrentLocation(24)).Returns(new LibraryBranch + { + Name = "Main St. Library" + }); + + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = controller.Detail(24); + + var viewResult = result.Should().BeOfType(); + var viewModel = viewResult.Subject.ViewData.Model.Should().BeAssignableTo(); + + viewModel.Subject.Title.Should().Be("Orlando"); + } + + [Test] + public void Call_CheckInItem_In_Service_When_CheckIn_Called() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + controller.CheckIn(24); + + mockCheckoutService.Verify(s => s.CheckInItem(24), Times.Once()); + } + + [Test] + public void Return_DetailView_When_CheckIn_Called() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = controller.CheckIn(24); + var redirectResult = result.Should().BeOfType(); + + redirectResult.Subject.ActionName.Should().Be("Detail"); + } + + [Test] + public void Call_MarkLost_In_Service_When_MarkLost_Called() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + controller.MarkLost(24); + + mockCheckoutService.Verify(s => s.MarkLost(24), Times.Once()); + } + + [Test] + public void Return_DetailView_When_MarkLost_Called() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = controller.MarkLost(24); + var redirectResult = result.Should().BeOfType(); + + redirectResult.Subject.ActionName.Should().Be("Detail"); + } + + [Test] + public void Call_MarkFound_In_Service_When_MarkFound_Called() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + controller.MarkFound(24); + + mockCheckoutService.Verify(s => s.MarkFound(24), Times.Once()); + } + + [Test] + public void Return_DetailView_When_MarkFound_Called() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + var sut = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = sut.MarkFound(24); + var redirectResult = result.Should().BeOfType(); + + redirectResult.Subject.ActionName.Should().Be("Detail"); + } + + [Test] + public void Return_CheckOut_View() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + mockLibraryAssetService.Setup(r => r.GetCurrentLocation(24)).Returns(new LibraryBranch + { + Name = "Main St. Library" + }); + + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = controller.Detail(24); + + var viewResult = result.Should().BeOfType(); + var viewModel = viewResult.Subject.ViewData.Model.Should().BeAssignableTo(); + + viewModel.Subject.Title.Should().Be("Orlando"); + } + + [Test] + public void Return_CheckOutModel() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + mockLibraryAssetService.Setup(r => r.GetCurrentLocation(24)).Returns(new LibraryBranch + { + Name = "Main St. Library" + }); + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + var result = controller.Detail(24); + var viewResult = result.Should().BeOfType(); + + viewResult.Subject.Model.Should().BeOfType(); + } + + private static IEnumerable GetAllAssets() + { + return new List + { + new Book + { + Title = "Orlando", + Author = "Virginia Woolf", + Status = new Status() + { + Name = "Checked In", + Id = 1, + }, + }, + + new Video + { + Title = "Happy People", + Director = "Werner Herzog", + ImageUrl = "images/sample.jpg", + Status = new Status() + { + Name = "Lost", + Id = 3, + }, + } + }; + } + + private static Book GetAsset() + { + return new Book + { + Title = "Orlando", + Author = "Virginia Woolf", + Status = new Status() + { + Name = "Checked In", + Id = 1, + }, + Location = new LibraryBranch() + { + Id = -99, + Name = "Hawkins" + } + }; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource controller of type Microsoft.AspNetCore.Mvc.Controller in method "Void CatalogControllerShould.Return_Branch_Detail_View()". + +### Severity: +ERROR + +### Procedure: +Void CatalogControllerShould.Return_Branch_Detail_View() + +### File: +Library.Tests/Controllers/CatalogControllerShould.cs + +### Key: +CatalogControllerShould.cs|Return_Branch_Detail_View|DOTNET_RESOURCE_LEAK + +### Hash: +13cab1d332956c51494da141cb0f903a + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0731/instruction.md b/inferredbugs-0731/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f6d57510c44873007310676c0beaef8500ab136 --- /dev/null +++ b/inferredbugs-0731/instruction.md @@ -0,0 +1,338 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** lightlib-lms +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Collections.Generic; +using System.Linq; +using FluentAssertions; +using Library.Data; +using Library.Data.Models; +using Library.Web.Controllers; +using Library.Web.Models.Catalog; +using Microsoft.AspNetCore.Mvc; +using Moq; +using NUnit.Framework; + +namespace Library.Tests.Controllers +{ + [TestFixture] + public class CatalogControllerShould + { + [Test] + public void Return_Catalog_Index_View() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + + mockLibraryAssetService.Setup(r => r.GetAll()).Returns(GetAllAssets()); + + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = controller.Index(); + var viewResult = result.Should().BeOfType(); + var viewModel = viewResult.Subject.ViewData.Model.Should().BeAssignableTo(); + viewModel.Subject.Assets.Count().Should().Be(2); + } + + [Test] + public void Return_AssetIndexListingModel() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + + mockLibraryAssetService.Setup(r => r.GetAll()).Returns(GetAllAssets()); + + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = controller.Index(); + var viewResult = result.Should().BeOfType(); + viewResult.Subject.Model.Should().BeOfType(); + } + + [Test] + public void Return_Branch_Detail_View() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + mockLibraryAssetService.Setup(r => r.GetCurrentLocation(24)).Returns(new LibraryBranch + { + Name = "Main St. Library" + }); + + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = controller.Detail(24); + + var viewResult = result.Should().BeOfType(); + var viewModel = viewResult.Subject.ViewData.Model.Should().BeAssignableTo(); + + viewModel.Subject.Title.Should().Be("Orlando"); + } + + [Test] + public void Return_BranchDetailModel() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + mockLibraryAssetService.Setup(r => r.GetCurrentLocation(24)).Returns(new LibraryBranch + { + Name = "Main St. Library" + }); + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + var result = controller.Detail(24); + var viewResult = result.Should().BeOfType(); + + viewResult.Subject.Model.Should().BeOfType(); + } + + [Test] + public void Return_CheckIn_View() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + mockLibraryAssetService.Setup(r => r.GetCurrentLocation(24)).Returns(new LibraryBranch + { + Name = "Main St. Library" + }); + + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = controller.Detail(24); + + var viewResult = result.Should().BeOfType(); + var viewModel = viewResult.Subject.ViewData.Model.Should().BeAssignableTo(); + + viewModel.Subject.Title.Should().Be("Orlando"); + } + + [Test] + public void Call_CheckInItem_In_Service_When_CheckIn_Called() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + controller.CheckIn(24); + + mockCheckoutService.Verify(s => s.CheckInItem(24), Times.Once()); + } + + [Test] + public void Return_DetailView_When_CheckIn_Called() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = controller.CheckIn(24); + var redirectResult = result.Should().BeOfType(); + + redirectResult.Subject.ActionName.Should().Be("Detail"); + } + + [Test] + public void Call_MarkLost_In_Service_When_MarkLost_Called() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + controller.MarkLost(24); + + mockCheckoutService.Verify(s => s.MarkLost(24), Times.Once()); + } + + [Test] + public void Return_DetailView_When_MarkLost_Called() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = controller.MarkLost(24); + var redirectResult = result.Should().BeOfType(); + + redirectResult.Subject.ActionName.Should().Be("Detail"); + } + + [Test] + public void Call_MarkFound_In_Service_When_MarkFound_Called() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + controller.MarkFound(24); + + mockCheckoutService.Verify(s => s.MarkFound(24), Times.Once()); + } + + [Test] + public void Return_DetailView_When_MarkFound_Called() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + var sut = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = sut.MarkFound(24); + var redirectResult = result.Should().BeOfType(); + + redirectResult.Subject.ActionName.Should().Be("Detail"); + } + + [Test] + public void Return_CheckOut_View() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + mockLibraryAssetService.Setup(r => r.GetCurrentLocation(24)).Returns(new LibraryBranch + { + Name = "Main St. Library" + }); + + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + + var result = controller.Detail(24); + + var viewResult = result.Should().BeOfType(); + var viewModel = viewResult.Subject.ViewData.Model.Should().BeAssignableTo(); + + viewModel.Subject.Title.Should().Be("Orlando"); + } + + [Test] + public void Return_CheckOutModel() + { + var mockLibraryAssetService = new Mock(); + var mockCheckoutService = new Mock(); + + mockLibraryAssetService.Setup(r => r.Get(24)).Returns(GetAsset()); + mockLibraryAssetService.Setup(r => r.GetCurrentLocation(24)).Returns(new LibraryBranch + { + Name = "Main St. Library" + }); + var controller = new CatalogController(mockLibraryAssetService.Object, mockCheckoutService.Object); + var result = controller.Detail(24); + var viewResult = result.Should().BeOfType(); + + viewResult.Subject.Model.Should().BeOfType(); + } + + private static IEnumerable GetAllAssets() + { + return new List + { + new Book + { + Title = "Orlando", + Author = "Virginia Woolf", + Status = new Status() + { + Name = "Checked In", + Id = 1, + }, + }, + + new Video + { + Title = "Happy People", + Director = "Werner Herzog", + ImageUrl = "images/sample.jpg", + Status = new Status() + { + Name = "Lost", + Id = 3, + }, + } + }; + } + + private static Book GetAsset() + { + return new Book + { + Title = "Orlando", + Author = "Virginia Woolf", + Status = new Status() + { + Name = "Checked In", + Id = 1, + }, + Location = new LibraryBranch() + { + Id = -99, + Name = "Hawkins" + } + }; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource controller of type Microsoft.AspNetCore.Mvc.Controller in method "Void CatalogControllerShould.Return_CheckOut_View()". + +### Severity: +ERROR + +### Procedure: +Void CatalogControllerShould.Return_CheckOut_View() + +### File: +Library.Tests/Controllers/CatalogControllerShould.cs + +### Key: +CatalogControllerShould.cs|Return_CheckOut_View|DOTNET_RESOURCE_LEAK + +### Hash: +2cb37722a4ca45d7ba414fff597e1b82 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0736/instruction.md b/inferredbugs-0736/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3043785c8b262a6cac4537c1d8f8ae5d78434bd7 --- /dev/null +++ b/inferredbugs-0736/instruction.md @@ -0,0 +1,572 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Shielded +**Bug ID:** 8 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Linq; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading; + +namespace Shielded +{ + /// + /// A transactional dictionary - adding, removing, replacing items are transactional, + /// but anything done to the items is not unless they are Shielded themselves. The 'Nc' stands + /// for 'no count' - you cannot find out how many items it has, unless you enumerate. + /// WARNING: Enumerating transactions will not conflict with parallel transactions which + /// add new items to the dictionary. This is OK for read-only transactions, but writers + /// might successfully commit some result even though they did not see all items. + /// For fully safe enumerating, please use . + /// + public class ShieldedDictNc : IShielded, IEnumerable> + { + private class ItemKeeper + { + public long Version; + public TItem Value; + public bool Empty; + public ItemKeeper Older; + } + + private class LocalDict + { + public Dictionary Items = new Dictionary(); + public bool HasChanges; + public bool Locked; + } + + private readonly ConcurrentDictionary _dict; + private readonly ConcurrentDictionary _writeStamps = + new ConcurrentDictionary(); + private readonly TransactionalStorage _localDict = new TransactionalStorage(); + private readonly object _owner; + + /// + /// Initializes a new instance with the given initial contents. + /// + /// Initial items. + /// If this is given, then in WhenCommitting subscriptions + /// this shielded will report its owner instead of itself. + public ShieldedDictNc(IEnumerable> items = null, object owner = null) + { + _dict = items == null ? new ConcurrentDictionary() : + new ConcurrentDictionary( + items.Select(kvp => + new KeyValuePair(kvp.Key, new ItemKeeper() { Value = kvp.Value }))); + _owner = owner ?? this; + } + + internal ShieldedDictNc(IEnumerable> items, object owner, out int count) + : this(items, owner) + { + count = _dict.Count; + } + + private void CheckLockAndEnlist(TKey key, bool write) + { + var locals = _localDict.HasValue ? _localDict.Value : null; + if (locals != null && locals.Locked) + { + CheckLockedAccess(key, write); + return; // because the check above is much stricter than anything + } + if (!Shield.Enlist(this, locals != null, write) && locals.Items.ContainsKey(key)) + return; + + WriteStamp w; + if (_writeStamps.TryGetValue(key, out w) && w.Locked) w.Wait(); + } + + /// + /// Since the dictionary is just one field to the Shield class, we internally check, if + /// the access is happening while locked, whether the access is safe. + /// + void CheckLockedAccess(TKey key, bool write) + { + var locals = _localDict.Value; + ItemKeeper item; + if (!locals.Items.TryGetValue(key, out item)) + throw new InvalidOperationException("No new key access in this context."); + if (item == null && write) + throw new InvalidOperationException("No new writes in this context."); + } + + private ItemKeeper CurrentTransactionOldValue(TKey key) + { + ItemKeeper point; + _dict.TryGetValue(key, out point); + while (point != null && point.Version > Shield.ReadStamp) + point = point.Older; + return point; + } + + private LocalDict PrepareLocals() + { + LocalDict locals; + if (_localDict.HasValue) + locals = _localDict.Value; + else + _localDict.Value = locals = new LocalDict(); + return locals; + } + + /// + /// Returns an existing local entry, if any. + /// + private ItemKeeper PrepareWrite(TKey key) + { + CheckLockAndEnlist(key, true); + var locals = PrepareLocals(); + ItemKeeper existing; + if (locals.Items.TryGetValue(key, out existing)) + return existing; + return null; + } + + private ItemKeeper Read(TKey key) + { + CheckLockAndEnlist(key, false); + ItemKeeper v, curr; + var locals = PrepareLocals(); + bool hasLocal; + if (!(hasLocal = locals.Items.TryGetValue(key, out v)) || v == null) + { + if (!hasLocal) + locals.Items.Add(key, null); + v = CurrentTransactionOldValue(key); + } + else if (_dict.TryGetValue(key, out curr) && curr.Version > Shield.ReadStamp) + throw new TransException("Writable read collision."); + return v; + } + + /// + /// Gets or sets the value under the specified key. + /// + public TItem this [TKey key] + { + get + { + ItemKeeper v; + if (!Shield.IsInTransaction) + { + if (!_dict.TryGetValue(key, out v) || v.Empty) + throw new KeyNotFoundException(); + return v.Value; + } + + v = Read(key); + if (v == null || v.Empty) + throw new KeyNotFoundException(); + return v.Value; + } + set + { + ItemKeeper local = PrepareWrite(key); + ItemKeeper curr; + if (_dict.TryGetValue(key, out curr) && curr.Version > Shield.ReadStamp) + throw new TransException("Write collision."); + + if (local == null) + { + var locals = _localDict.Value; + locals.Items[key] = new ItemKeeper() { Value = value }; + locals.HasChanges = true; + } + else + { + local.Empty = false; + local.Value = value; + } + } + } + + /// + /// An enumerable of keys for which the current transaction made changes in the dictionary. + /// Safely accessible from subscriptions. NB that + /// this also includes keys which were removed from the dictionary. + /// + public IEnumerable Changes + { + get + { + if (Shield.IsInTransaction && _localDict.HasValue && _localDict.Value.HasChanges) + { + return _localDict.Value.Items + .Where(kvp => kvp.Value != null) + .Select(kvp => kvp.Key); + } + return Enumerable.Empty(); + } + } + + /// + /// An enumerable of keys which the current transaction read or wrote into. + /// Safely accessible from subscriptions. NB that + /// this also includes keys which were removed from the dictionary. + /// + public IEnumerable Reads + { + get + { + if (Shield.IsInTransaction && _localDict.HasValue) + return _localDict.Value.Items.Keys; + return Enumerable.Empty(); + } + } + + bool IShielded.HasChanges + { + get + { + return _localDict.HasValue && _localDict.Value.HasChanges; + } + } + + object IShielded.Owner + { + get + { + return _owner; + } + } + + bool IShielded.CanCommit(WriteStamp writeStamp) + { + var locals = _localDict.Value; + locals.Locked = true; + // locals were prepared when we enlisted. + if (locals.Items.Any(kvp => + { + ItemKeeper v; + return _writeStamps.ContainsKey(kvp.Key) || + (_dict.TryGetValue(kvp.Key, out v) && v.Version > Shield.ReadStamp); + })) + return false; + else + { + // touch only the ones we plan to change + if (locals.HasChanges) + foreach (var kvp in locals.Items) + if (kvp.Value != null) + _writeStamps[kvp.Key] = writeStamp; + return true; + } + } + + private ConcurrentQueue>> _copies = + new ConcurrentQueue>>(); + + void IShielded.Commit() + { + var locals = _localDict.Value; + if (locals.HasChanges) + { + long? version = null; + var copyList = new List(); + foreach (var kvp in _localDict.Value.Items) + { + if (kvp.Value == null) + continue; + if (version == null) + version = _writeStamps[kvp.Key].Version; + + ItemKeeper v = null; + if (_dict.TryGetValue(kvp.Key, out v)) + copyList.Add(kvp.Key); + + var newCurrent = kvp.Value; + newCurrent.Version = (long)version; + newCurrent.Older = v; + lock (_dict) + _dict[kvp.Key] = newCurrent; + + WriteStamp ws; + _writeStamps.TryRemove(kvp.Key, out ws); + } + if (version.HasValue) + _copies.Enqueue(Tuple.Create((long)version, copyList)); + } + _localDict.Release(); + } + + void IShielded.Rollback() + { + if (!_localDict.HasValue) + return; + var locals = _localDict.Value; + if (locals.HasChanges) + { + WriteStamp ws; + var ctx = Shield.Context; + foreach (var kvp in locals.Items) + { + if (kvp.Value != null && + _writeStamps.TryGetValue(kvp.Key, out ws) && ws.Locker == ctx) + { + _writeStamps.TryRemove(kvp.Key, out ws); + } + } + } + _localDict.Release(); + } + + void IShielded.TrimCopies(long smallestOpenTransactionId) + { + // NB the "smallest transaction" and others can freely read while + // we're doing this. + Tuple> item; + while (_copies.TryPeek(out item) && item.Item1 < smallestOpenTransactionId) + { + _copies.TryDequeue(out item); + foreach (var key in item.Item2) + { + ItemKeeper point; + if (!_dict.TryGetValue(key, out point)) + continue; + ItemKeeper pointNewer = null; + while (point != null && point.Version > smallestOpenTransactionId) + { + pointNewer = point; + point = point.Older; + } + if (point != null) + { + // point is the last accessible - his Older is not needed. + point.Older = null; + if (point.Empty) + { + if (pointNewer != null) + pointNewer.Older = null; + else + { + //((ICollection>)_dict) + // .Remove(new KeyValuePair(key, point)); + lock (_dict) + { + ItemKeeper k; + if (_dict.TryGetValue(key, out k) && k == point) + _dict.TryRemove(key, out k); + } + } + } + } + } + } + } + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return ((IEnumerable>)this).GetEnumerator(); + } + + /// + /// Get an enumerator for the dictionary contents. Iterating over this dictionary + /// does not conflict with other transactions that are adding new items, so it + /// is not fully safe. For read-only transactions, however, no problem. + /// + public IEnumerator> GetEnumerator() + { + Shield.AssertInTransaction(); + var keys = _localDict.HasValue ? + _dict.Keys.Union(_localDict.Value.Items.Keys) : _dict.Keys; + foreach (var key in keys) + { + var v = Read(key); + if (v == null || v.Empty) continue; + yield return new KeyValuePair(key, v.Value); + } + } + + /// + /// Removes all items, but one by one. + /// + public void Clear() + { + foreach (var key in Keys) + Remove(key); + } + + /// + /// Copy the dictionary contents to an array. Involves enumerating, might not get all + /// items which should have been visible at the time of your commit. This does not + /// affect read-only transactions, or those writers that do not logically depend on + /// seeing all items. + /// + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + Shield.InTransaction(() => { + foreach (KeyValuePair kvp in this) + array[arrayIndex++] = kvp; + }); + } + + /// + /// Add the specified key and value to the dictionary. + /// + /// Thrown if the key is already present in the dictionary. + public void Add(TKey key, TItem value) + { + Shield.AssertInTransaction(); + if (ContainsKey(key)) + throw new ArgumentException("The given key is already present in the dictionary."); + this[key] = value; + } + + /// + /// Check if the dictionary contains the given key. + /// + public bool ContainsKey(TKey key) + { + ItemKeeper v; + if (!Shield.IsInTransaction) + return _dict.TryGetValue(key, out v) && v != null && !v.Empty; + + v = Read(key); + return v != null && !v.Empty; + } + + /// + /// Remove the specified key from the collection. + /// + public bool Remove(TKey key) + { + Shield.AssertInTransaction(); + var keeper = PrepareWrite(key); + if (keeper != null) + { + var res = !keeper.Empty; + keeper.Empty = true; + return res; + } + var old = CurrentTransactionOldValue(key); + if (old == null || old.Empty) + return false; + var locals = _localDict.Value; + locals.Items[key] = new ItemKeeper { Empty = true }; + locals.HasChanges = true; + return true; + } + + /// + /// Safe read based on the key - returns true if the key is present, and + /// then also returns the value stored under that key through the out parameter. + /// + public bool TryGetValue(TKey key, out TItem value) + { + ItemKeeper v; + if (!Shield.IsInTransaction) + { + if (_dict.TryGetValue(key, out v) && !v.Empty) + { + value = v.Value; + return true; + } + value = default(TItem); + return false; + } + + v = Read(key); + if (v != null && !v.Empty) + { + value = v.Value; + return true; + } + value = default(TItem); + return false; + } + + /// + /// Get a collection of all the keys in the dictionary. Can be used out of transactions. + /// The result is a copy, it will not be updated if the dictionary is later changed. + /// Like all enumerating operations on this type, it is not completely safe, unless + /// your transaction is read-only. + /// + public ICollection Keys + { + get + { + return Shield.InTransaction( + () => ((IEnumerable>)this) + .Select(kvp => kvp.Key) + .ToList()); + } + } + + /// + /// Get a collection of all the values in the dictionary. Can be used out of transactions. + /// The result is a copy, it will not be updated if the dictionary is later changed. + /// Like all enumerating operations on this type, it is not completely safe, unless + /// your transaction is read-only. + /// + public ICollection Values + { + get + { + return Shield.InTransaction( + () => ((IEnumerable>)this) + .Select(kvp => kvp.Value) + .ToList()); + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `locals` last assigned on line 74 could be null and is dereferenced at line 75, column 9. + +### Severity: +ERROR + +### Procedure: +Void ShieldedDictNc`2.CheckLockAndEnlist(TKey,Boolean) + +### File: +Shielded/ShieldedDictNc.cs + +### Key: +ShieldedDictNc.cs|CheckLockAndEnlist|NULL_DEREFERENCE + +### Node Key: +cff514ccb90de40f899d1a804c0d1f8c + +### Hash: +e03a9634a87a6f635c3f2b1ffb9df529 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0737/instruction.md b/inferredbugs-0737/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a148ce48efaf07b1e3f37050456af79dae3e1faf --- /dev/null +++ b/inferredbugs-0737/instruction.md @@ -0,0 +1,245 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Shielded +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Microsoft.CSharp; +using System.CodeDom.Compiler; +using System.CodeDom; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using System.ComponentModel; +using System.Collections.Concurrent; +using Shielded; + +namespace Shielded.ProxyGen +{ + static class ProxyGen + { + static ConcurrentDictionary proxies = new ConcurrentDictionary(); + private const string ShieldedFieldName = "_data"; + private const string ShieldedValueProperty = "Value"; + + public static Type GetFor(Type t) + { + return proxies.GetOrAdd(t, CreateFor); + } + + private static Type CreateFor(Type t) + { + var provider = new CSharpCodeProvider(); + CompilerParameters cp = new CompilerParameters(); + cp.GenerateInMemory = true; + CodeCompileUnit cu = new CodeCompileUnit(); + AddAssemblyReference(cu, t); + cu.Namespaces.Add(CreateNamespace(t)); + +#if DEBUG + StringWriter sw = new StringWriter(); + provider.GenerateCodeFromCompileUnit(cu,sw , new CodeGeneratorOptions() { BracingStyle="C" }); + var s = sw.GetStringBuilder().ToString(); + Trace.WriteLine(s); +#endif + + CompilerResults cr = provider.CompileAssemblyFromDom(cp,cu); + if (cr.Errors.Count > 0) + { + ThrowErrors(cr.Errors); + } + return cr.CompiledAssembly.GetTypes()[0]; + } + + private static void AddAssemblyReference(CodeCompileUnit cu, Type t) + { + cu.ReferencedAssemblies.Add(t.Assembly.Location); + cu.ReferencedAssemblies.Add("Shielded.dll"); + } + + private static void ThrowErrors(CompilerErrorCollection compilerErrorCollection) + { + StringBuilder sb = new StringBuilder(); + foreach( CompilerError e in compilerErrorCollection) + { + sb.AppendLine(e.ErrorText); + } + throw new ProxyGenerationException("Compiler errors:\n" + sb.ToString()); + } + + private static CodeNamespace CreateNamespace(Type t) + { + var nsp = new CodeNamespace(t.Namespace); + var decl = new CodeTypeDeclaration(); + decl.Name = GetNameForDerivedClass(t); + decl.TypeAttributes = TypeAttributes.NotPublic; + decl.Attributes = MemberAttributes.Private; + decl.BaseTypes.Add(t); + + var theStruct = new CodeTypeDeclaration(); + theStruct.Name = GetNameForSupportingStruct(t); + theStruct.TypeAttributes = TypeAttributes.NestedPrivate; + theStruct.Attributes = MemberAttributes.Private; + theStruct.IsStruct = true; + + var theShieldedType = new CodeTypeReference("Shielded.Shielded", + new CodeTypeReference(theStruct.Name)); + var theShieldedField = new CodeMemberField(theShieldedType, "_data") { + Attributes = MemberAttributes.Private + }; + theShieldedField.InitExpression = new CodeObjectCreateExpression(theShieldedType); + decl.Members.Add(theShieldedField); + + foreach (PropertyInfo pi in t.GetProperties().Where(IsInteresting)) + { + theStruct.Members.Add(CreateStructField(pi)); + decl.Members.Add(CreatePropertyOverride(theStruct.Name, pi)); + } + + MethodInfo commMethod; + if ((commMethod = t.GetMethod("Commute")) != null && + commMethod.IsVirtual) + { + var commOverride = new CodeMemberMethod() { + Attributes = MemberAttributes.Override | MemberAttributes.Public, + Name = "Commute", + }; + commOverride.Parameters.Add(new CodeParameterDeclarationExpression( + new CodeTypeReference(typeof(Action)), + "a")); + commOverride.ReturnType = new CodeTypeReference(typeof(void)); + commOverride.Statements.Add(new CodeMethodInvokeExpression( + new CodeFieldReferenceExpression( + new CodeThisReferenceExpression(), + "_data"), + "Commute", + new CodeArgumentReferenceExpression("a"))); + decl.Members.Add(commOverride); + } + + decl.Members.Add(theStruct); + + nsp.Types.Add(decl); + return nsp; + } + + internal static bool IsInteresting(PropertyInfo pi) + { + MethodInfo getter, setter; + return pi.CanRead && (getter = pi.GetGetMethod()) != null && getter.IsVirtual && + pi.CanWrite && (setter = pi.GetSetMethod()) != null && setter.IsVirtual; + } + + private static CodeTypeMember CreateStructField(PropertyInfo pi) + { + CodeMemberField field = new CodeMemberField(); + field.Name = pi.Name; + field.Attributes = MemberAttributes.Public; + field.Type = new CodeTypeReference(pi.PropertyType); + return field; + } + + private static CodeMemberProperty CreatePropertyOverride(string structType, PropertyInfo pi) + { + CodeMemberProperty mp = new CodeMemberProperty(); + mp.Name = pi.Name; + mp.Attributes = MemberAttributes.Override | MemberAttributes.Public; + mp.Type = new CodeTypeReference(pi.PropertyType); + mp.HasGet = mp.HasSet = true; + + mp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression() { + TargetObject = new CodePropertyReferenceExpression() { + TargetObject = new CodeFieldReferenceExpression() { + TargetObject = new CodeThisReferenceExpression(), + FieldName = ShieldedFieldName, + }, + PropertyName = ShieldedValueProperty, + }, + FieldName = pi.Name, + })); + + // call base setter first, so they can see the old value (using getter) and new (using value) + mp.SetStatements.Add(new CodeAssignStatement( + new CodePropertyReferenceExpression() { + TargetObject = new CodeBaseReferenceExpression(), + PropertyName = pi.Name, + }, new CodePropertySetValueReferenceExpression())); + // using Modify has a huge advantage - if a class is big, we don't want to be passing + // copies of the underlying struct around. + mp.SetStatements.Add(new CodeSnippetStatement( + string.Format("{0}.Modify((ref {1} a) => a.{2} = value);", + ShieldedFieldName, structType, pi.Name))); + + return mp; + } + + + + private static string GetNameForDerivedClass(Type t) + { + return string.Concat("__shielded", t.Name); + } + + private static string GetNameForSupportingStruct(Type t) + { + return string.Concat("__struct", t.Name); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource sw of type System.IO.StringWriter, Leaked resource provider of type Microsoft.CSharp.CSharpCodeProvider in method "Type ProxyGen.CreateFor(Type)". + +### Severity: +ERROR + +### Procedure: +Type ProxyGen.CreateFor(Type) + +### File: +Shielded.ProxyGen/ProxyGen.cs + +### Key: +ProxyGen.cs|CreateFor|DOTNET_RESOURCE_LEAK + +### Hash: +59d9482719c6f3d584a4637ad2755d09 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0739/instruction.md b/inferredbugs-0739/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..58c0f398a65eb6a61ec03b2b1b5ef6574e812784 --- /dev/null +++ b/inferredbugs-0739/instruction.md @@ -0,0 +1,841 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Shielded +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Concurrent; +using System.Linq; +using System.Threading; +using System.Diagnostics; +using System.Threading.Tasks; +using Shielded; + +namespace ConsoleTests +{ + class MainClass + { + private static Stopwatch _timer; + + public static long mtTest(string name, int taskCount, Func task) + { + if (_timer == null) + _timer = Stopwatch.StartNew(); + + long time; + Console.Write("Test - {0}...", name); + time = _timer.ElapsedMilliseconds; + Task.WaitAll( + Enumerable.Range(0, taskCount) + .Select(task) + .ToArray()); + time = _timer.ElapsedMilliseconds - time; + return time; + } + + public static void TimeTests() + { + var randomizr = new Random(); + int transactionCounter; + int sleepTime = 1; + int taskCount = 1000; + + foreach (var i in Enumerable.Repeat(0, 5)) + { + var x = new int[100]; + transactionCounter = 0; + var time = mtTest("dirty write", taskCount, _ => + { + var rnd = randomizr.Next(100); + return Task.Factory.StartNew(() => + { + Interlocked.Increment(ref transactionCounter); + int v = x[rnd]; + if (sleepTime > 0) Thread.Sleep(sleepTime); + x[rnd] = v + 1; + }, + sleepTime > 0 ? TaskCreationOptions.LongRunning : TaskCreationOptions.None + ); + }); + var correct = x.Sum() == taskCount; + Console.WriteLine(" {0} ms with {1} iterations and is {2}.", + time, transactionCounter, correct ? "correct" : "incorrect"); + } + + var lockCount = 10; + foreach (var i in Enumerable.Repeat(0, 5)) + { + var x = new int[100]; + transactionCounter = 0; + var l = Enumerable.Repeat(0, lockCount).Select(_ => new object()).ToArray(); + var time = mtTest(string.Format("{0} lock write", lockCount), taskCount, _ => + { + var rnd = randomizr.Next(100); + return Task.Factory.StartNew(() => + { + lock (l[rnd % lockCount]) + { + Interlocked.Increment(ref transactionCounter); + int v = x[rnd]; + if (sleepTime > 0) Thread.Sleep(sleepTime); + x[rnd] = v + 1; + } + }, + sleepTime > 0 ? TaskCreationOptions.LongRunning : TaskCreationOptions.None + ); + }); + var correct = x.Sum() == taskCount; + Console.WriteLine(" {0} ms with {1} iterations and is {2}.", + time, transactionCounter, correct ? "correct" : "incorrect"); + } + + foreach (var i in Enumerable.Repeat(0, 5)) + { + var shx = Enumerable.Repeat(0, 100).Select(n => new Shielded(n)).ToArray(); + transactionCounter = 0; + var time = mtTest("shielded2 write", taskCount, _ => + { + var rnd = randomizr.Next(100); + return Task.Factory.StartNew(() => + { + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCounter); + int v = shx[rnd]; + if (sleepTime > 0) Thread.Sleep(sleepTime); + shx[rnd].Modify((ref int a) => a = v + 1); + }); + }, + sleepTime > 0 ? TaskCreationOptions.LongRunning : TaskCreationOptions.None + ); + }); + var correct = shx.Sum(s => s.Read) == taskCount; + Console.WriteLine(" {0} ms with {1} iterations and is {2}.", + time, transactionCounter, correct ? "correct" : "incorrect"); + } + } + + static void OneTransaction() + { + Shielded sh = new Shielded(); + Shield.InTransaction(() => + { + int x = sh; + Console.WriteLine("Read: {0}", x); + sh.Modify((ref int a) => a = x + 1); + Console.WriteLine("Read after increment: {0}", sh.Read); + }); + } + + + struct Account + { + public int Id; + public decimal Balance; + // beware - copies of this struct share this reference! + public List Transfers; + } + + struct Transfer + { + public int OtherId; + public decimal AmountReceived; + } + + static void ControlledRace() + { + var acc1 = new Shielded(new Account() + { + Id = 1, + Balance = 1000M, + Transfers = new List() + }); + var acc2 = new Shielded(new Account() + { + Id = 2, + Balance = 1000M, + Transfers = new List() + }); + int transactionCount = 0; + + mtTest("controlled race", 20, n => + { + if (n % 2 == 0) + return Task.Factory.StartNew(() => + { + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCount); + Shield.SideEffect(() => Console.WriteLine("Transferred 100.00 .. acc1 -> acc2"), + () => Console.WriteLine("Task 1 rollback!")); + acc1.Modify((ref Account a) => + { + a.Balance = a.Balance - 100M; + var list = a.Transfers; + Shield.SideEffect(() => list.Add( + new Transfer() { OtherId = acc2.Read.Id, AmountReceived = -100M })); + }); + Thread.Sleep(100); + acc2.Modify((ref Account a) => + { + a.Balance = a.Balance + 100M; + var list = a.Transfers; + Shield.SideEffect(() => list.Add( + new Transfer() { OtherId = acc1.Read.Id, AmountReceived = 100M })); + }); + }); + }, TaskCreationOptions.LongRunning); + else + return Task.Factory.StartNew(() => + { + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCount); + Shield.SideEffect(() => Console.WriteLine("Transferred 200.00 .. acc1 <- acc2"), + () => Console.WriteLine("Task 2 rollback!")); + acc2.Modify((ref Account a) => + { + a.Balance = a.Balance - 200M; + var list = a.Transfers; + Shield.SideEffect(() => list.Add( + new Transfer() { OtherId = acc1.Read.Id, AmountReceived = -200M })); + }); + Thread.Sleep(250); + acc1.Modify((ref Account a) => + { + a.Balance = a.Balance + 200M; + var list = a.Transfers; + Shield.SideEffect(() => list.Add( + new Transfer() { OtherId = acc2.Read.Id, AmountReceived = 200M })); + }); + }); + }, TaskCreationOptions.LongRunning); + }); + Console.WriteLine("\nCompleted 20 transactions in {0} total attempts.", transactionCount); + Console.WriteLine("Account 1 balance: {0}", acc1.Read.Balance); + foreach (var t in acc1.Read.Transfers) + { + Console.WriteLine(" {0:####,00}", t.AmountReceived); + } + Console.WriteLine("\nAccount 2 balance: {0}", acc2.Read.Balance); + foreach (var t in acc2.Read.Transfers) + { + Console.WriteLine(" {0:####,00}", t.AmountReceived); + } + } + + private static void DictionaryTest() + { + ShieldedDict> dict = new ShieldedDict>(); + var randomizr = new Random(); + foreach (var _ in Enumerable.Repeat(0, 10)) + { + var transactionCounter = 0; + var time = mtTest("dictionary", 10000, i => + { + var rnd = randomizr.Next(10); + if (i % 2 == 0) + // adder task - 500 of these + return Task.Factory.StartNew(() => + { + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCounter); + var v = dict.ContainsKey(rnd) ? dict[rnd] : null; + int? num = v != null ? (int?)v.Read : null; + Thread.Sleep(1); + if (v == null) + dict[rnd] = new Shielded(1); + else if (v.Read == -1) + dict.Remove(rnd); + else + v.Modify((ref int a) => a = num.Value + 1); + } + ); + }, + TaskCreationOptions.LongRunning + ); + else + // subtractor task - 500 of these + return Task.Factory.StartNew(() => + { + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCounter); + var v = dict.ContainsKey(rnd) ? dict[rnd] : null; + int? num = v != null ? (int?)v.Read : null; + Thread.Sleep(1); + if (v == null) + dict[rnd] = new Shielded(-1); + else if (v.Read == 1) + dict.Remove(rnd); + else + v.Modify((ref int a) => a = num.Value - 1); + } + ); + }, + TaskCreationOptions.LongRunning + ); + }); + var sum = Enumerable.Range(0, 10).Sum(n => dict.ContainsKey(n) ? dict[n] : 0); + Console.WriteLine(" {0} ms with {1} iterations and sum {2}.", + time, transactionCounter, sum); + } + } + + /// + /// Creates a BetShop, and tries to buy a large number of random tickets. Afterwards it + /// checks that the rule limiting same ticket winnings is not violated. + /// + public static void BetShopTest() + { + int numEvents = 100; + var betShop = new BetShop(numEvents); + var randomizr = new Random(); + int reportEvery = 1000; + //Shielded nextReport = new Shielded(reportEvery); + + //Shield.Conditional(() => betShop.TicketCount >= nextReport, () => + //{ + // nextReport.Modify((ref int n) => n += reportEvery); + // Shield.SideEffect(() => + // { + // Console.Write(" {0}..", betShop.TicketCount); + // }); + // return true; + //}); + Shielded lastReport = new Shielded(0); + Shielded lastTime = new Shielded(DateTime.UtcNow); + + var reportingCond = Shield.Conditional(() => betShop.Tickets.Count >= lastReport + reportEvery, () => + { + DateTime newNow = DateTime.UtcNow; + int count = betShop.Tickets.Count; + int speed = (count - lastReport) * 1000 / (int)newNow.Subtract(lastTime).TotalMilliseconds; + lastTime.Assign(newNow); + lastReport.Modify((ref int n) => n += reportEvery); + Shield.SideEffect(() => + { + Console.Write("\n{0} at {1} item/s", count, speed); + }); + return true; + }); + + + var time = mtTest("bet shop w/ " + numEvents, 50000, i => + { + decimal payIn = (randomizr.Next(10) + 1m) * 1; + int event1Id = randomizr.Next(numEvents) + 1; + int event2Id = randomizr.Next(numEvents) + 1; + int event3Id = randomizr.Next(numEvents) + 1; + int offer1Ind = randomizr.Next(3); + int offer2Ind = randomizr.Next(3); + int offer3Ind = randomizr.Next(3); + return Task.Factory.StartNew(() => Shield.InTransaction(() => + { + var offer1 = betShop.Events[event1Id].Read.BetOffers[offer1Ind]; + var offer2 = betShop.Events[event2Id].Read.BetOffers[offer2Ind]; + var offer3 = betShop.Events[event3Id].Read.BetOffers[offer3Ind]; + betShop.BuyTicket(payIn, offer1, offer2, offer3); + })); + }); + + Shield.CancelConditional(reportingCond); + + var totalCorrect = betShop.VerifyTickets(); + Console.WriteLine(" {0} ms with {1} tickets paid in and is {2}.", + time, betShop.Tickets.Count, totalCorrect ? "correct" : "incorrect"); + } + + public static void BetShopPoolTest() + { + int numThreads = 3; + int numTickets = 200000; + int numEvents = 100; + var barrier = new Barrier(2); + var betShop = new BetShop(numEvents); + var randomizr = new Random(); + int reportEvery = 10000; + //Shielded nextReport = new Shielded(reportEvery); + + //Shield.Conditional(() => betShop.TicketCount >= nextReport, () => + //{ + // nextReport.Modify((ref int n) => n += reportEvery); + // Shield.SideEffect(() => + // { + // Console.Write(" {0}..", betShop.TicketCount); + // }); + // return true; + //}); + Shielded lastReport = new Shielded(0); + Shielded lastTime = new Shielded(DateTime.UtcNow); + + Shield.Conditional(() => betShop.Tickets.Count >= lastReport + reportEvery, () => + { + DateTime newNow = DateTime.UtcNow; + int count = betShop.Tickets.Count; + int speed = (count - lastReport) * 1000 / (int)newNow.Subtract(lastTime).TotalMilliseconds; + lastTime.Assign(newNow); + lastReport.Modify((ref int n) => n += reportEvery); + Shield.SideEffect(() => + { + Console.Write("\n{0} at {1} item/s", count, speed); + }); + return true; + }); + + + var bags = new List[numThreads]; + var threads = new Thread[numThreads]; + for (int i = 0; i < numThreads; i++) + { + var bag = bags[i] = new List(); + threads[i] = new Thread(() => { + foreach (var a in bag) + a(); + }); + } + + var complete = new Shielded(); + Shield.Conditional(() => complete == numTickets, () => { + barrier.SignalAndWait(); + return false; + }); + foreach (var i in Enumerable.Range(0, numTickets)) + { + decimal payIn = (randomizr.Next(10) + 1m) * 1; + int event1Id = randomizr.Next(numEvents) + 1; + int event2Id = randomizr.Next(numEvents) + 1; + int event3Id = randomizr.Next(numEvents) + 1; + int offer1Ind = randomizr.Next(3); + int offer2Ind = randomizr.Next(3); + int offer3Ind = randomizr.Next(3); + bags[i % numThreads].Add(() => Shield.InTransaction(() => + { + var offer1 = betShop.Events[event1Id].Read.BetOffers[offer1Ind]; + var offer2 = betShop.Events[event2Id].Read.BetOffers[offer2Ind]; + var offer3 = betShop.Events[event3Id].Read.BetOffers[offer3Ind]; + betShop.BuyTicket(payIn, offer1, offer2, offer3); + complete.Commute((ref int n) => n++); + })); + } + _timer = new Stopwatch(); + _timer.Start(); + for (int i = 0; i < numThreads; i++) + threads[i].Start(); + + barrier.SignalAndWait(); + var time = _timer.ElapsedMilliseconds; + var totalCorrect = betShop.VerifyTickets(); + Console.WriteLine(" {0} ms with {1} tickets paid in and is {2}.", + time, betShop.Tickets.Count, totalCorrect ? "correct" : "incorrect"); + } + + class TreeItem + { + public Guid Id = Guid.NewGuid(); + } + + public static void TreePoolTest() + { + int numThreads = 3; + int numItems = 100000; + // for some reason, if this is replaced with ShieldedDict, KeyAlreadyPresent + // exception is thrown. under one key you can then find an entity which does + // not have that key. complete mystery. + var tree = new ShieldedTree(); + var barrier = new Barrier(numThreads + 1); + int reportEvery = 10000; + Shielded lastReport = new Shielded(0); + Shielded lastTime = new Shielded(DateTime.UtcNow); + + Shield.Conditional(() => tree.Count >= lastReport + reportEvery, () => + { + DateTime newNow = DateTime.UtcNow; + int count = tree.Count; + int speed = (count - lastReport) * 1000 / (int)newNow.Subtract(lastTime).TotalMilliseconds; + lastTime.Assign(newNow); + lastReport.Modify((ref int n) => n += reportEvery); + Shield.SideEffect(() => + { + Console.Write("\n{0} at {1} item/s", count, speed); + }); + return true; + }); + + + TreeItem x = new TreeItem(); + + _timer = new Stopwatch(); + _timer.Start(); + var time = _timer.ElapsedMilliseconds; + foreach (var k in Enumerable.Repeat(1, numItems)) + Shield.InTransaction(() => x.Id = x.Id); + time = _timer.ElapsedMilliseconds - time; + Console.WriteLine("Empty transactions in {0} ms.", time); + + var bags = new List[numThreads]; + var threads = new Thread[numThreads]; + for (int i = 0; i < numThreads; i++) + { + var bag = bags[i] = new List(); + threads[i] = new Thread(() => { + foreach (var a in bag) + a(); + barrier.SignalAndWait(); + }); + } + + foreach (var i in Enumerable.Range(0, numItems)) + { + var item1 = new TreeItem(); + bags[i % numThreads].Add(() => Shield.InTransaction(() => + { + tree.Add(item1.Id, item1); + })); + } + for (int i = 0; i < numThreads; i++) + threads[i].Start(); + + barrier.SignalAndWait(); + time = _timer.ElapsedMilliseconds; + Console.WriteLine(" {0} ms.", time); + + Console.WriteLine("\nReading sequentially..."); + time = _timer.ElapsedMilliseconds; + var keys = Shield.InTransaction(() => tree.Keys); + time = _timer.ElapsedMilliseconds - time; + Console.WriteLine("Keys read in {0} ms.", time); + + time = _timer.ElapsedMilliseconds; + Shield.InTransaction(() => { + foreach (var kvp in tree) + x = kvp.Value; + }); + time = _timer.ElapsedMilliseconds - time; + Console.WriteLine("Items read by enumerator in {0} ms.", time); + + time = _timer.ElapsedMilliseconds; + Shield.InTransaction(() => { + foreach (var k in keys) + x = tree[k]; + }); + time = _timer.ElapsedMilliseconds - time; + Console.WriteLine("Items read by key in one trans in {0} ms.", time); + + time = _timer.ElapsedMilliseconds; + foreach (var k in keys) + x = tree[k]; + time = _timer.ElapsedMilliseconds - time; + Console.WriteLine("Items read by key separately in {0} ms.", time); + + time = _timer.ElapsedMilliseconds; + foreach (var k in Enumerable.Repeat(1, numItems)) + Shield.InTransaction(() => x.Id = x.Id); + time = _timer.ElapsedMilliseconds - time; + Console.WriteLine("Empty transactions in {0} ms.", time); + } + + public static void TreeTest() + { + int numTasks = 100000; + int reportEvery = 1000; + + ShieldedTree tree = new ShieldedTree(); + int transactionCount = 0; + Shielded lastReport = new Shielded(0); + Shielded countComplete = new Shielded(0); +// Shielded lastTime = new Shielded(DateTime.UtcNow); +// +// Shield.Conditional(() => countComplete >= lastReport + reportEvery, () => +// { +// DateTime newNow = DateTime.UtcNow; +// int speed = (countComplete - lastReport) * 1000 / (int)newNow.Subtract(lastTime).TotalMilliseconds; +// lastTime.Assign(newNow); +// lastReport.Modify((ref int n) => n += reportEvery); +// int count = countComplete; +// Shield.SideEffect(() => +// { +// Console.Write("\n{0} at {1} item/s", count, speed); +// } +// ); +// return true; +// } +// ); + + if (true) + { + var treeTime = mtTest("tree", numTasks, i => + { + return Task.Factory.StartNew(() => + { + var item1 = new TreeItem(); + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCount); + tree.Add(item1.Id, item1); +// countComplete.Commute((ref int c) => c++); + } + ); + } + ); + } + ); + Guid? previous = null; + bool correct = true; + Shield.InTransaction(() => + { + int count = 0; + foreach (var item in tree) + { + count++; + if (previous != null && previous.Value.CompareTo(item.Key) > 0) + { + correct = false; + break; + } + previous = item.Key; + } + correct = correct && (count == numTasks); + } + ); + Console.WriteLine("\n -- {0} ms with {1} iterations and is {2}.", + treeTime, transactionCount, correct ? "correct" : "incorrect"); + } + + if (true) + { + ShieldedDict dict = new ShieldedDict(); + transactionCount = 0; + Shield.InTransaction(() => + { + countComplete.Assign(0); + lastReport.Assign(0); + } + ); + + var time = mtTest("dictionary", numTasks, i => + { + return Task.Factory.StartNew(() => + { + var item1 = new TreeItem(); + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCount); + dict[item1.Id] = item1; +// countComplete.Commute((ref int c) => c++); + } + ); + } + ); + } + ); + Console.WriteLine("\n -- {0} ms with {1} iterations. Not sorted.", + time, transactionCount); + } + + if (true) + { + ConcurrentDictionary dict = new ConcurrentDictionary(); + + var time = mtTest("ConcurrentDictionary", numTasks, i => + { + return Task.Factory.StartNew(() => + { + var item1 = new TreeItem(); + dict[item1.Id] = item1; + } + ); + } + ); + Console.WriteLine("\n -- {0} ms with {1} iterations. Not sorted.", + time, numTasks); + } + } + + public static void SkewTest() + { + var numTasks = 1000; + var numFields = 10; + var transactionCount = 0; + var randomizr = new Random(); + var shA = Enumerable.Repeat(0, numFields).Select(_ => new Shielded(100)).ToArray(); + var shB = Enumerable.Repeat(0, numFields).Select(_ => new Shielded(100)).ToArray(); + + var time = mtTest("skew write", numTasks, i => + { + int index = randomizr.Next(numFields << 1); + int amount = randomizr.Next(10) + 1; + return Task.Factory.StartNew(() => + { + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCount); + // take one from one of the arrays, but only if it does not take sum under 100 + var sum = shA[index >> 1] + shB[index >> 1]; + if (sum - amount >= 100) + { + //Thread.Sleep(10); + if ((index & 1) == 0) + shA[index >> 1].Modify((ref int n) => n = n - amount); + else + shB[index >> 1].Modify((ref int n) => n = n - amount); + } + } + ); + }, + TaskCreationOptions.LongRunning + ); + } + ); + // it's correct if no sum is smaller than 100 + var correct = true; + for (int j = 0; j < numFields; j++) + if (shA[j] + shB[j] < 100) + { + correct = false; + break; + } + Console.WriteLine("\n -- {0} ms with {1} iterations and is {2}.", + time, transactionCount, correct ? "correct" : "incorrect"); + } + + private class Dummy + { + public int Value; + } + + public static void SimpleTreeTest() + { + ShieldedTree tree = new ShieldedTree(); + Shield.InTransaction(() => + { + foreach (int i in Enumerable.Range(1, 2000)) + { + tree.Add(1000 - i, new Dummy() { Value = 1000 - i }); + tree.Add(1000 - i, new Dummy() { Value = 1000 - i }); + } + }); + Shield.InTransaction(() => + { + foreach (int i in Enumerable.Range(1, 1000).Select(x => x << 1)) + { + tree.Remove(1000 - i); + } + }); + Shield.InTransaction(() => + { + foreach (var kvp in tree.Range(505, 525)) + Console.WriteLine("Item: {0}", kvp.Key); + }); + } + + public static void SimpleCommuteTest() + { + var a = new Shielded(); + + Shield.InTransaction(() => a.Commute((ref int n) => n++)); + Console.WriteLine(a); + + Shield.InTransaction(() => + { + Console.WriteLine(a); + a.Commute((ref int n) => n++); + Console.WriteLine(a); + }); + Console.WriteLine(a); + + Shield.InTransaction(() => + { + a.Commute((ref int n) => n++); + Console.WriteLine(a); + }); + Console.WriteLine(a); + } + + public static void Main(string[] args) + { + //TimeTests(); + + //OneTransaction(); + + //ControlledRace(); + + //DictionaryTest(); + + //BetShopTest(); + + //BetShopPoolTest(); + + //TreeTest(); + + //TreePoolTest(); + + //SkewTest(); + + //SimpleTreeTest(); + + //SimpleCommuteTest(); + + new Queue().Run(); + + //SequentialTests.Run(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of ConsoleTests.Queue::.ctor() at Line 777).ConsoleTests.Queue._barrier of type System.Threading.Barrier in method "Void MainClass.Main(String[])". + +### Severity: +ERROR + +### Procedure: +Void MainClass.Main(String[]) + +### File: +ConsoleTests/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +6460e7d7a41dcf13adadf040c43c1890 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0754/instruction.md b/inferredbugs-0754/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2e1d836375287940ee76f0857100f4bd1dc89a15 --- /dev/null +++ b/inferredbugs-0754/instruction.md @@ -0,0 +1,118 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Dora +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Dora.DynamicProxy; +using Dora.Interception; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Reflection; +using System.Threading.Tasks; + +namespace App +{ + public class Program + { + public static void Main(string[] args) + { + var clock1 = new ServiceCollection() + .AddMemoryCache() + .AddSingleton() + .AddInterception() + .BuildServiceProvider() + .GetRequiredService>() + .Proxy; + + var method = typeof(ISystomClock).GetMethod("GetCurrentTime"); + var field = clock1.GetType().GetField("_interceptors", BindingFlags.NonPublic | BindingFlags.Instance); + var decoration = field.GetValue(clock1) as InterceptorDecoration; + var interceptor = decoration.GetInterceptor(method); + + for (int i = 0; i < 5; i++) + { + Console.WriteLine($"Current time: {clock1.GetCurrentTime(DateTimeKind.Local)}"); + Task.Delay(1000).Wait(); + } + + for (int i = 0; i < 5; i++) + { + Console.WriteLine($"Current time: {clock1.GetCurrentTime(DateTimeKind.Utc)}"); + Task.Delay(1000).Wait(); + } + + + var clock2 = new ServiceCollection() + .AddMemoryCache() + .AddSingleton() + .BuilderInterceptableServiceProvider() + .GetRequiredService(); + + for (int i = 0; i < 5; i++) + { + Console.WriteLine($"Current time: {clock2.GetCurrentTime(DateTimeKind.Local)}"); + Task.Delay(1000).Wait(); + } + + for (int i = 0; i < 5; i++) + { + Console.WriteLine($"Current time: {clock2.GetCurrentTime(DateTimeKind.Utc)}"); + Task.Delay(1000).Wait(); + } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from System.IServiceProvider Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions::BuilderInterceptableServiceProvider(Microsoft.Extensions.DependencyInjection.IServiceCollection,System.Action`1) at Line 40) of type Microsoft.Extensions.DependencyInjection.ServiceProvider2 in method "Void Program.Main(String[])". + +### Severity: +ERROR + +### Procedure: +Void Program.Main(String[]) + +### File: +demo/Interception/App1/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +f62bd97cd6c6c1bf5b8414cf228442ac + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0762/instruction.md b/inferredbugs-0762/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eab6d84aa3f5f3f9badccfe5a5c7d97a82d70ade --- /dev/null +++ b/inferredbugs-0762/instruction.md @@ -0,0 +1,92 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** silky +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Silky.Core.Rpc; +using Silky.Rpc.Endpoint; + +namespace Silky.Rpc.Transport.Messages +{ + public static class RemoteInvokeMessageExtensions + { + public static void SetRpcAttachments(this RemoteInvokeMessage message, bool isGateway = false) + { + foreach (var messageAttachment in message.Attachments) + { + if (messageAttachment.Key.Equals(AttachmentKeys.SelectedServerEndpoint) + || messageAttachment.Key.Equals(AttachmentKeys.SelectedServerHost) + || messageAttachment.Key.Equals(AttachmentKeys.SelectedServerPort) + || messageAttachment.Key.Equals(AttachmentKeys.SelectedServerServiceProtocol) + ) + { + continue; + } + + RpcContext.Context.SetAttachment(messageAttachment.Key, messageAttachment.Value); + } + + var localRpcEndpoint = RpcEndpointHelper.GetLocalRpcEndpointDescriptor(); + RpcContext.Context.SetAttachment(AttachmentKeys.LocalAddress, localRpcEndpoint.Host); + RpcContext.Context.SetAttachment(AttachmentKeys.LocalPort, localRpcEndpoint.Port); + RpcContext.Context.SetAttachment(AttachmentKeys.LocalServiceProtocol, localRpcEndpoint.ServiceProtocol); + RpcContext.Context.SetAttachment(AttachmentKeys.IsGateway, isGateway); + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `localRpcEndpoint` last assigned on line 24 could be null and is dereferenced at line 25, column 13. + +### Severity: +ERROR + +### Procedure: +Void RemoteInvokeMessageExtensions.SetRpcAttachments(RemoteInvokeMessage,Boolean) + +### File: +framework/src/Silky.Rpc/Transport/Messages/RemoteInvokeMessageExtensions.cs + +### Key: +RemoteInvokeMessageExtensions.cs|SetRpcAttachments|NULL_DEREFERENCE + +### Node Key: +2cefdf467be5b2a12ba8e1652fa299d8 + +### Hash: +b756acb1f8b0d04e2b47e7c2df0ada53 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0765/instruction.md b/inferredbugs-0765/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09c1f516915a3424a338164f036658edcf05928e --- /dev/null +++ b/inferredbugs-0765/instruction.md @@ -0,0 +1,3833 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Tizen-CSharp-Samples +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/** Copyright (c) 2017 Samsung Electronics Co., Ltd. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Diagnostics; +using Tizen.NUI; +using Tizen.NUI.BaseComponents; + +namespace Tizen.NUI +{ + /// + /// A view that shows items in two-dimension grid, which can scroll horizontally or vertically. + /// The items in the grid come from the GirdBridge associated with this view. + /// + public class GridView : View + { + /// + /// GridView event types + /// + public enum GridEventType + { + /// + /// Event triggered when focus change + /// + FocusChange, + /// + /// Event triggered when item scroll in + /// + ItemScrolledIn, + /// + /// Event triggered when item scroll out + /// + ItemScrolledOut, + } + + /// + /// GridView orientation types + /// + public enum GridType + { + /// + /// Items laid horizontal + /// + Horizontal = 0, + /// + /// Items laid vertical + /// + Vertical + } + + /// + /// GridView event args at event call back, user can get information + /// + public class GridEventArgs : EventArgs + { + /// + /// GridView event type + /// + public GridEventType EventType + { + get; + set; + } + + /// + /// GridView event data + /// + public int[] param = new int[4]; + } + + /// + /// Construct GridView. + /// + public GridView() + { + Initialize(); + + // register event handler for relayout + Relayout += OnRelayoutUpdate; + + FocusGained += ControlFocusGained; + FocusLost += ControlFocusLost; + } + + /// + /// Get/Set list type. + /// + public GridType Type + { + get { return gridType; } + set { gridType = value; } + } + + /// + /// Get/Set list spaces around items. + /// + public new Vector4 Margin + { + get { return margin; } + set { margin = value; } + } + + /// + /// Get/Set space between columns + /// + public int ColumnSpace + { + get { return columnSpace; } + set { columnSpace = value; } + } + + /// + /// Get/Set space between rows + /// + public int RowSpace + { + get { return rowSpace; } + set { rowSpace = value; } + } + + /// + /// Get/Set space between groups + /// + public int GroupSpace + { + get { return groupSpace; } + set { groupSpace = value; } + } + + /// + /// Get/Set space for title + /// + public int TitleSpace + { + get { return titleSpace; } + set { titleSpace = value; } + } + + /// + /// Get/Set enable flag of whether support straight path focus move. + /// + public bool StateStraightPathEnable + { + get; + set; + } + /// + /// Get/Set enable flag of right circulation of GridView. + /// + public bool StateRightCircularEnable + { + get; + set; + } + + /// + /// Get/Set enable flag of left circulation of GridView. + /// + public bool StateLeftCircularEnable + { + get; + set; + } + + /// + /// Get/Set focus move animation duration of GridView. + /// + public int FocusMoveDuration + { + get + { + return focusMoveAniDuration; + } + + set + { + focusMoveAniDuration = value; + //focusMoveAni.Duration = value; + //scaleAni.Duration = value; + } + } + + /// + /// Get/Set scroll bar fade out time + /// + public int ScrollBarFadeOutDuration + { + get; + set; + } + + + /// + /// Preload item buffer size at front + /// + public int PreloadFrontColumnSize + { + get { return preloadFrontColumnSize; } + set { preloadFrontColumnSize = value ; } + } + + /// + /// Preload item buffer size at back + /// + public int PreloadBackColumnSize + { + get { return preloadBackColumnSize; } + set { preloadBackColumnSize = value; } + } + + /// + /// Focus in scale factor + /// + public float FocusInScaleFactor + { + get { return focusInScaleFactor; } + set { focusInScaleFactor = value; } + } + + /// + /// Focus in scale animation duration + /// + public AnimationAttributes FocusInScaleAnimationAttrs + { + get { return focusInScaleAnimationAttrs; } + set { focusInScaleAnimationAttrs = value; } + } + + /// + /// Focus out scale animation duration + /// + public AnimationAttributes FocusOutScaleAnimationAttrs + { + get { return focusOutScaleAnimationAttrs; } + set { focusOutScaleAnimationAttrs = value; } + } + /// + /// Sets the data behind this GridView. + /// + /// The GridBridge which is responsible for maintaining the data + /// backing this grid and for producing a view to represent an item in the data set. + public void SetBridge(GridBridge bridge) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Set bridge for GridView")); + Debug.Assert(bridge != null); + + if (gridBridge != null) + { + return; + } + + gridBridge = bridge; + + gridBridge.DataChangeEvent += OnDataChange; + + for (int i = 0; i < groupList.Count; i++) + { + View groupTitle = gridBridge.GetGroupTitleView(i); + if (groupTitle != null) + { + groupList[i].title = groupTitle; + + if (GridType.Horizontal == gridType) + { + groupTitle.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + groupTitle.PivotPoint = Tizen.NUI.PivotPoint.BottomLeft; + groupTitle.PositionUsesPivotPoint = true; + groupTitle.PositionX = groupList[i].startPos; + groupTitle.PositionY = -titleSpace; + Tizen.Log.Fatal("NUI", "titleView.PositionX: " + groupTitle.PositionX + ", titleView.PositionY: " + groupTitle.PositionY); + } + else + { + groupTitle.PositionX = 0; + groupTitle.PositionY = groupList[i].startPos - titleSpace; + } + + itemGroup.Add(groupTitle); + } + } + + SetViewTypeCount(gridBridge.GetItemTypeCount()); + + + if (groupList.Count > 0) + { + Load(); + if (HasFocus() == true && curInMemoryItemSet.Count != 0) + { + SetFocus(focusGroupIndex, focusItemIndex); + } + } + } + /// + /// Add groups to GridView. + /// + /// The count of groups to add. + public void AddGroup(int groupCount) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add Group Number{0}", groupCount)); + int prevCount = groupList.Count; + for (int i = prevCount; i < groupCount + prevCount; i++) + { + Group newGroup = new Group(); + newGroup.index = i; + newGroup.columnList = new List(); + newGroup.itemList = new List(); + newGroup.itemIndexToCell = new Dictionary(); + + if (GridType.Horizontal == gridType) + { + newGroup.startPos = newGroup.endPos = (i == 0 ? 0 : groupSpace + groupList.ElementAt(i - 1).endPos); + } + else + { + newGroup.startPos = newGroup.endPos = (i == 0 ? 0 : groupSpace + groupList.ElementAt(i - 1).endPos + titleSpace); + } + + if (gridBridge != null) + { + View groupTitle = gridBridge.GetGroupTitleView(i); + if (groupTitle != null) + { + newGroup.title = groupTitle; + if (GridType.Horizontal == gridType) + { + groupTitle.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + groupTitle.PivotPoint = Tizen.NUI.PivotPoint.BottomLeft; + groupTitle.PositionUsesPivotPoint = true; + groupTitle.PositionX = newGroup.startPos; + groupTitle.PositionY = -titleSpace; + Tizen.Log.Fatal("NUI", "titleView.PositionX: " + groupTitle.PositionX + ", titleView.PositionY: " + groupTitle.PositionY); + } + else + { + groupTitle.PositionX = 0; + groupTitle.PositionY = newGroup.startPos - titleSpace; + } + + itemGroup.Add(groupTitle); + } + } + + groupList.Add(newGroup); + } + } + + internal void ResetGroup(int groupCount) + { + Tizen.Log.Fatal("NUI", "...." + groupCount); + if (groupList.Count < groupCount) + { + AddGroup(groupCount - groupList.Count); + } + else if (groupList.Count > groupCount) + { + int removeCount = groupList.Count - groupCount; + for (int i = groupCount; i < groupList.Count; i++) + { + if (groupList.ElementAt(i).title != null) + { + itemGroup.Remove(groupList.ElementAt(i).title); + gridBridge.RemoveGroupTitleView(i, groupList.ElementAt(i).title); + } + + Clear(i); + } + + groupList.RemoveRange(groupCount, removeCount); + } + } + + // Add column to GridView. + internal void AddColumn(int columnWidth, int groupIndex = 0) + { + if (groupList.Count == 0) + { + Group newGroup = new Group(); + newGroup.index = 0; + newGroup.columnList = new List(); + newGroup.itemList = new List(); + newGroup.itemIndexToCell = new Dictionary(); + newGroup.startPos = newGroup.endPos = 0; + groupList.Add(newGroup); + } + + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add column columnWidth {0} to group {1}",columnWidth, groupIndex)); + + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + Column newColumn = new Column(); + newColumn.groupIndex = groupIndex; + newColumn.index = curGroup.columnList.Count; + newColumn.space = columnWidth; + + if (newColumn.index == 0) + { + newColumn.startPos = curGroup.startPos; + } + else + { + newColumn.startPos = curGroup.columnList.ElementAt(newColumn.index - 1).endPos + columnSpace; + } + + newColumn.endPos = newColumn.startPos + columnWidth; + + if (newColumn.cellList == null) + { + newColumn.cellList = new List(); + } + + curGroup.columnList.Add(newColumn); + + float posOffset = (0 == newColumn.index) ? columnWidth : columnWidth + columnSpace; + curGroup.endPos += posOffset; + + for (int i = groupIndex + 1; i < (int)groupList.Count; i++) + { + if (GridType.Horizontal == gridType && groupList.ElementAt(i).title != null) + { + groupList.ElementAt(i).title.PositionX += posOffset; + } + + groupList.ElementAt(i).ResetPosition(posOffset); + } + + Tizen.Log.Fatal("NUI", "..."); + return; + } + /// + /// Add row to the column in GridView. + /// + /// The column index; + /// The row space. + /// The group index. + public void AddRowToColumn(int columnIndex, int rowHeight, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add row rowHeight {0} to column {1} of group {2}", rowHeight, columnIndex, groupIndex)); + if (!IsColumnIndexValid(groupIndex, columnIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid column index")); + return; + } + + Group curGroup = groupList.ElementAt(groupIndex); + Column curColumn = curGroup.columnList.ElementAt(columnIndex); + + int curRowNumInCol = curColumn.cellList.Count; + + Cell newCell = new Cell(); + + Cell lastCell = (curRowNumInCol == 0 ? null : curColumn.cellList.ElementAt(curRowNumInCol - 1)); + + if (GridType.Horizontal == gridType) + { + newCell.rect.X = curColumn.startPos; + newCell.rect.Y = (curRowNumInCol == 0 ? 0 : lastCell.rect.Bottom() + rowSpace); + newCell.rect.Height = rowHeight; + newCell.rect.Width = curColumn.space; + } + else + { + newCell.rect.X = (curRowNumInCol == 0) ? 0 : lastCell.rect.Right() + columnSpace; + newCell.rect.Y = curColumn.startPos; + newCell.rect.Height = rowHeight; + newCell.rect.Width = curColumn.space; + } + + newCell.columnIndex = columnIndex; + newCell.rowIndex = curRowNumInCol; + newCell.index = curRowNumInCol; + if (curRowNumInCol == 0) + { + if (columnIndex == 0) + { + newCell.itemIndex = 0; + } + else + { + newCell.itemIndex = curGroup.columnList.ElementAt(columnIndex - 1).endItemIndex + 1; + } + } + else + { + newCell.itemIndex = lastCell.itemIndex + 1; + } + + Tizen.Log.Fatal("NUI", " >>>>>>> newCell.itemIndex: " + newCell.itemIndex + " newCell.rect[" + newCell.rect.X + ", " + newCell.rect.Y + ", " + newCell.rect.Width + ", " + newCell.rect.Height + "]"); + + curColumn.cellList.Add(newCell); + Tizen.Log.Fatal("NUI", "..."); + + if (curRowNumInCol == 0) + { + curColumn.startItemIndex = newCell.itemIndex; + } + + curColumn.endItemIndex = newCell.itemIndex; + Tizen.Log.Fatal("NUI", " >>>>>>> curColumn.startItemIndex: " + curColumn.startItemIndex + " curColumn.endItemIndex: " + curColumn.endItemIndex); + + curGroup.itemIndexToCell.Add(newCell.itemIndex, newCell); + curGroup.realCellCount++; + + Tizen.Log.Fatal("NUI", "Group: " + groupIndex + ", Column: " + columnIndex + " Cell.rowIndex: " + newCell.rowIndex + " Cell.columnIndex: " + newCell.columnIndex + " Cell.itemIndex: " + newCell.itemIndex + " curGroup.realCellCount:" + curGroup.realCellCount); + } + + // Add row to the all column in same group of GridView. + internal void AddRowToAllColumn(int rowHeight, int groupIndex) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add row rowHeight {0} to to all column of group {1}", rowHeight, groupIndex)); + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + int columnCount = groupList.ElementAt(groupIndex).columnList.Count; + for (int i = 0; i < columnCount; i++) + { + AddRowToColumn(i, rowHeight, groupIndex); + } + } + /// + /// Quickly add an regular grid by pass column/row number and cell size. + /// + /// The columns count. + /// The rows count. + /// The column width. + /// The row height. + /// The groupIndex, default value is -1, means all the groups will use the same regular grid. + public void AddRegularGrid(int columnCount, int rowCount, int columnWidth, int rowHeight, int groupIndex = -1) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add row x column : ({0} x {1}) rowHeight: {2} , columnWidth: {3} to group {4}", rowCount, columnCount, rowHeight, columnWidth, groupIndex)); + + if (groupIndex != -1) + { + if (groupList.Count == 0) + { + Group newGroup = new Group(); + newGroup.index = 0; + newGroup.columnList = new List(); + newGroup.itemList = new List(); + newGroup.itemIndexToCell = new Dictionary(); + newGroup.startPos = newGroup.endPos = 0; + groupList.Add(newGroup); + } + else if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + } + + if (gridType == GridType.Vertical) + { + int temp = rowCount; + rowCount = columnCount; + columnCount = temp; + } + + this.rowCnt = rowCount; + this.colCnt = columnCount; + this.rowH = rowHeight; + this.colW = columnWidth; + + if (columnCount == -1) + { + return; + } + + if (groupIndex == -1) + { + for (int k = 0; k < groupList.Count; k++) + { + for (int i = 0; i < columnCount; i++) + { + AddColumn(columnWidth, groupIndex); + + for (int j = 0; j < rowCount; j++) + { + AddRowToColumn(i, rowHeight, groupIndex); + } + } + } + } + else + { + for (int i = 0; i < columnCount; i++) + { + AddColumn(columnWidth, groupIndex); + + for (int j = 0; j < rowCount; j++) + { + AddRowToColumn(i, rowHeight, groupIndex); + } + } + } + } + + /// + /// Attach title to the group. + /// + /// The title view. + /// The group index. + public void AttachGroupTitle(View titleView, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Attach group title to {0}", groupIndex)); + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + Group curGroup = groupList.ElementAt(groupIndex); + if (GridType.Horizontal == gridType) + { + titleView.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + titleView.PivotPoint = Tizen.NUI.PivotPoint.BottomLeft; + titleView.PositionUsesPivotPoint = true; + titleView.PositionX = curGroup.startPos; + titleView.PositionY = -titleSpace; + } + else + { + titleView.PositionX = 0; + titleView.PositionY = curGroup.startPos - titleSpace; + } + + curGroup.title = titleView; + itemGroup.Add(titleView); + } + + /// + /// Get group title of specified group index. + /// + /// Group index of GridIndex view. + /// Title view of specified group index. + public View GetGroupTitle(int groupIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return null; + } + + return groupList[groupIndex].title; + } + + /// + /// Set focus group index and item index of GridView. + /// + /// focus item index + /// focus group index + public void SetFoucsItemIndex(int itemIndex, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Set Focus to item {0} of group {1}", itemIndex, groupIndex)); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid item index")); + return; + } + + if (groupIndex == focusGroupIndex && itemIndex == focusItemIndex) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Already focused")); + return; + } + //if (IsFocused == true) + //{ + // SetFocus(groupIndex, itemIndex); + //} + if (HasFocus() == true) + { + SetFocus(groupIndex, itemIndex); + } + else + { + focusGroupIndex = groupIndex; + focusItemIndex = itemIndex; + focusTagGroupIndex = focusGroupIndex; + focusTagItemIndex = focusItemIndex; + } + } + + /// + /// Get focus group index and item index of GridView. + /// + /// focus group index + /// focus item index + public void GetFocusItemIndex(out int groupIndex, out int itemIndex) + { + groupIndex = focusGroupIndex; + itemIndex = focusItemIndex; + } + + /// + /// Get loaded item view in GridView. + /// + /// Specified group index + /// Specified item index + /// Return the ItemView, if the item is unloaded, returns null. + public object GetLoadedItemView(int groupIndex, int itemIndex) + { + GridItem item = null; + if (IsGroupIndexValid(groupIndex) == true && IsItemIndexValid(groupIndex, itemIndex)) + { + item = groupList.ElementAt(groupIndex).itemList.ElementAt(itemIndex); + } + + return item?.itemView; + } + + /// + /// User to do the page move. + /// + /// Used to control whether support animation. + public void MoveNextPage(bool bAni = true) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Move to next page")); + PageMove(false, bAni); + } + + /// + /// User to do the page move. + /// + /// Used to control whether support animation. + public void MovePrevPage(bool bAni = true) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Move to previous page")); + PageMove(true, bAni); + } + + /// + /// Update an item. + /// + /// The itemIndex. + /// The groupIndex. + public void UpdateItem(int itemIndex, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Update item {0} of group {1}", itemIndex, groupIndex)); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + Cell curCell = GetCellByItemIndex(groupIndex, itemIndex); + int columnIndex = curCell.columnIndex; + + if ((groupIndex > onScreenRange.startGroupIndex && groupIndex < onScreenRange.endGroupIndex) + || (groupIndex == onScreenRange.startGroupIndex && columnIndex >= onScreenRange.startColumnIndex) + || (groupIndex == onScreenRange.endGroupIndex && columnIndex <= onScreenRange.endColumnIndex)) + { + gridBridge.UpdateItem(groupIndex, itemIndex, groupList.ElementAt(groupIndex).itemList.ElementAt(itemIndex).itemView); + } + } + /// + /// Update all items on screen. + /// + public void UpdateAllItems() + { + foreach (GridItem item in curInMemoryItemSet) + { + gridBridge.UpdateItem(item.groupIndex, item.index, item.itemView); + } + } + /// + /// Get group number of GridView. + /// + /// Groups count + public int GetGroupCount() + { + return groupList.Count; + } + /// + /// Get column count of specified group. + /// + /// The group index. + /// Columns count + public int GetColumnCount(int groupIndex) + { + Tizen.Log.Fatal("NUI", "... groupIndex = " + groupIndex); + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return INVALID_COUNT; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + if (curGroup.columnList == null) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid column list")); + return INVALID_COUNT; + } + + Tizen.Log.Fatal("NUI", "... curGroup.columnList.Count = " + curGroup.columnList.Count); + return curGroup.columnList.Count; + } + /// + /// Get cell count of specified column of specified group. + /// + /// The group index. + /// The column index. + /// Cells count + public int GetCellCount(int groupIndex, int columnIndex) + { + if (!IsColumnIndexValid(groupIndex, columnIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return INVALID_COUNT; + } + + Column curColumn = groupList.ElementAt(groupIndex).columnList.ElementAt(columnIndex); + + if (curColumn.cellList == null) + { + return INVALID_COUNT; + } + + return curColumn.cellList.Count; + } + + + /// + /// Get item count of a group. + /// + /// The group index. + /// Items count + public int GetItemCount(int groupIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return INVALID_COUNT; + } + + Group curGroup = groupList.ElementAt(groupIndex); + return curGroup.itemList.Count; + } + /// + /// Get the GridBridge of GridView. + /// + /// The GridBridge of GridView. + public GridBridge GetBridge() + { + return gridBridge; + } + /// + /// Get on screen item range. + /// + /// The group index of start range. + /// The item index of start range. + /// The group index of end range. + /// The item index of end range. + public void GetOnscreenRange(out int startGroupIndex, out int startItemIndex, out int endGroupIndex, out int endItemIndex) + { + startGroupIndex = onScreenRange.startGroupInScrn; + startItemIndex = onScreenRange.startItemIndexInScrn; + endGroupIndex = onScreenRange.endGroupInScrn; + endItemIndex = onScreenRange.endItemIndexInScrn; + } + + /// + /// Move focus according to parameter direction + /// + /// Focus move direction, can be "Left", "Right", "Up" or "Down" + public void Move(string direction) + { + MoveFocus(direction); + } + + /// + /// Get screen position of specified item. + /// + /// Group index of linear view. + /// Item index of group. + /// + /// Thrown when groupIndex or item index is invalid. + /// + /// Screen position of specified item. + public Position2D GetItemScreenPosition(int groupIndex, int itemIndex) + { + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + throw new ArgumentException("Group index or item index is invalid"); + } + + GridItem curItem = groupList.ElementAt(groupIndex).itemList.ElementAt(itemIndex); + return curItem?.itemView?.ScreenPosition; + } + + /// + /// Dispose of GridView. + /// + /// Dispose caused type + protected override void Dispose(DisposeTypes type) + { + if (disposed) + { + return; + } + + if (type == DisposeTypes.Explicit) + { + //Called by User + //Release your own managed resources here. + //You should release all of your own disposable objects here. + + Tizen.Log.Fatal("NUI", string.Format("[GridView]Dispose")); + focusMoveAni?.Stop(); + focusMoveAni?.Dispose(); + focusMoveAni = null; + + ClearRecycleBin(); + ResetGroup(0); + } + + //Release your own unmanaged resources here. + //You should not access any managed member here except static instance. + //because the execution order of Finalizes is non-deterministic. + //Unreference this from if a static instance refer to this. + + //You must call base.Dispose(type) just before exit. + base.Dispose(type); + } + + /// + /// GridView event handler + /// + public event EventHandler GridEvent + { + add + { + gridEventHandlers += value; + } + + remove + { + gridEventHandlers -= value; + } + } + /// + /// Update when GridView attributes changed. + /// + /// the object + /// the args of the event + protected void OnRelayoutUpdate(object sender, EventArgs e) + { + gridWidth = this.SizeWidth; + gridHeight = this.SizeHeight; + Tizen.Log.Fatal("NUI", "...OnRelayoutUpdateOnRelayoutUpdateOnRelayoutUpdateOnRelayoutUpdate..."); + if (gridBridge != null) + { + Load(); + + if (HasFocus() == true && curInMemoryItemSet.Count != 0) + { + SetFocus(focusGroupIndex, focusItemIndex); + } + } + } + + private void OnListEvent(GridEventArgs e) + { + if (gridEventHandlers != null) + { + gridEventHandlers(this, e); + } + } + + private void Initialize() + { + ClippingMode = ClippingModeType.ClipChildren; + + + groupList = new List(); + itemGroup = new View(); + itemGroup.Name = "ItemGroup"; + itemGroup.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + itemGroup.PivotPoint = Tizen.NUI.PivotPoint.TopLeft; + this.Add(itemGroup); + + itemGroupRect = new Rect(0, 0, 0, 0); + + curInMemoryItemSet = new HashSet(); + nextInMemoryItemSet = new HashSet(); + + lastVisibleArea = new Rect(0, 0, 0, 0); + onScreenRange = new Range(-1, -1, -1, -1); + + refXForFocusMove = -1; + refYForFocusMove = -1; + + focusGroupIndex = 0; + focusItemIndex = 0; + + focusTagGroupIndex = 0; + focusTagItemIndex = 0; + + StateRightCircularEnable = false; + StateLeftCircularEnable = false; + + + focusMoveAni = new LinkerAnimation(itemGroup, 100, 100, 0); + focusMoveAni.ViaEvent += OnFocusMoveViaEvent; + + ScrollBarFadeOutDuration = 1000; + } + + private void Load() + { + Tizen.Log.Fatal("NUI", "...lOAD..."); + int groupCount = groupList.Count; + if (groupCount == 0) + { + return; + } + + for (int i = 0; i < groupCount; i++) + { + Group curGroup = groupList.ElementAt(i); + int dataCount = gridBridge.GetItemCount(i); + + int finalCount = curGroup.realCellCount < dataCount ? curGroup.realCellCount : dataCount; + + int bindedItemCount = curGroup.itemList.Count; + + for (int j = 0; j < finalCount; j++) + { + GridItem newItem; + if (j < bindedItemCount) + { + newItem = curGroup.itemList.ElementAt(j); + } + else + { + Cell curCell = curGroup.itemIndexToCell[j]; + newItem = new GridItem(); + newItem.groupIndex = i; + newItem.index = j; + newItem.rect = curCell.rect; + curGroup.itemList.Add(newItem); + } + } + + //add for right move between group when not all columns filled + if (finalCount >= 1) + { + Cell lastItemCell = GetCellByItemIndex(i, finalCount - 1); + curGroup.lastFilledColumnIndex = lastItemCell.columnIndex; + } + } + + UpdateItemGroupSize(); + + InitItemGroupPosition(); + UpdateInMemoryItems(); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + } + + private void UpdateInMemoryItems() + { + Rect windowRect = new Rect(-itemGroupRect.X, -itemGroupRect.Y, gridWidth, gridHeight); + + List loadItemList = new List(); + List unloadItemList = new List(); + + GetChangedItems(lastVisibleArea, windowRect, ref loadItemList, ref unloadItemList); + Tizen.Log.Fatal("NUI", ">>>>>>>>> loadItemList.Count: " + loadItemList.Count + " unloadItemList.Count: " + unloadItemList.Count); + lastVisibleArea.X = windowRect.X; + lastVisibleArea.Y = windowRect.Y; + lastVisibleArea.Width = windowRect.Width; + lastVisibleArea.Height = windowRect.Height; + + foreach (GridItem item in unloadItemList) + { + UnloadItem(item); + } + + foreach (GridItem item in loadItemList) + { + LoadItem(item); + } + + } + + private void UpdateInMemoryItems(Position itemGroupPos) + { + Rect windowRect = new Rect(-itemGroupPos.X, -itemGroupPos.Y, gridWidth, gridHeight); + + List loadItemList = new List(); + List unloadItemList = new List(); + + GetChangedItems(lastVisibleArea, windowRect, ref loadItemList, ref unloadItemList); + lastVisibleArea.X = windowRect.X; + lastVisibleArea.Y = windowRect.Y; + lastVisibleArea.Width = windowRect.Width; + lastVisibleArea.Height = windowRect.Height; + + foreach (GridItem item in unloadItemList) + { + UnloadItem(item); + } + + foreach (GridItem item in loadItemList) + { + LoadItem(item); + } + + } + + private void UnloadItem(GridItem item, bool bDirectly = false) + { + Tizen.Log.Fatal("NUI", "item: " + item + " bDirectly: " + bDirectly); + itemGroup.Remove(item.itemView); + + if (bDirectly) + { + gridBridge.UnloadItem(item.groupIndex, item.index, item.itemView); + } + else + { + AddRecycleView(item.groupIndex, item.index, item.itemView); + } + + item.itemView = null; + + curInMemoryItemSet.Remove(item); + } + + private void LoadItem(GridItem item) + { + curInMemoryItemSet.Add(item); + + if (item.itemView != null) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]LoadItem item view is null")); + return; + } + + View temp = GetRecycleView(item.groupIndex,item.index); + Tizen.Log.Fatal("NUI", " temp: " + temp); + if (temp != null) + { + item.itemView = temp; + gridBridge.UpdateItem(item.groupIndex, item.index, item.itemView); + } + else + { + item.itemView = gridBridge.GetItemView(item.groupIndex, item.index); + + item.itemView.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + item.itemView.PivotPoint = Tizen.NUI.PivotPoint.Center; + item.itemView.PositionUsesPivotPoint = false; + } + + Tizen.Log.Fatal("NUI", "item.index: " + item.index + " item.rect.X: " + item.rect.X + " item.rect.Y: " + item.rect.Y); + item.itemView.Position = new Position(item.rect.X, item.rect.Y, 0.0f); + item.itemView.Size2D = new Size2D((int)item.rect.Width, (int)item.rect.Height); + + itemGroup.Add(item.itemView); + } + + private void SetViewTypeCount(int typeCount) + { + if (typeCount < 1) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]SetViewTypeCount type count less than 1")); + return; + } + + viewTypeCount = typeCount; + List[] viewListArray = new List[viewTypeCount]; + + for (int i = 0; i < viewTypeCount; i++) + { + viewListArray[i] = new List(); + } + + recycledViews = viewListArray; + } + + private void AddRecycleView(int groupIndex, int itemIndex, View view) + { + int viewType = gridBridge.GetItemType(groupIndex, itemIndex); + + if (viewType >= viewTypeCount) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]AddRecycleView viewType larger than viewTypeCount")); + return; + } + + if (view != null) + { + view.Hide(); + view.Scale = new Vector3(1, 1, 1); + } + + recycledViews[viewType].Add(view); + } + + private View GetRecycleView(int groupIndex, int itemIndex) + { + int viewType = gridBridge.GetItemType(groupIndex, itemIndex); + Tizen.Log.Fatal("NUI", " viewType:" + viewType + " viewTypeCount:" + viewTypeCount); + + if (viewType >= viewTypeCount) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]AddRecycleView viewType larger than viewTypeCount")); + return null; + } + + View obj = null; + int viewCount = recycledViews[viewType].Count; + if (viewCount != 0) + { + obj = recycledViews[viewType][viewCount - 1]; + recycledViews[viewType].Remove(obj); + } + + if (obj != null) + { + obj.Show(); + } + + return obj; + } + + private void ClearRecycleBin() + { + for (int i = 0; i < viewTypeCount; i++) + { + for (int j = 0; j < recycledViews[i].Count; j++) + { + UnloadRecycledView(i, recycledViews[i][j]); + } + + recycledViews[i].Clear(); + } + } + + private void UnloadRecycledView(int viewType, View view) + { + itemGroup.Remove(view); + gridBridge.UnloadItemByViewType(viewType, view); + } + + private void GetChangedItems(Rect aLastVisibleArea, Rect curVisibleArea, ref List loadItem, ref List unloadItem) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> aLastVisibleArea.X: " + aLastVisibleArea.X + " aLastVisibleArea.Y: " + aLastVisibleArea.Y + " aLastVisibleArea.Width: " + aLastVisibleArea.Width + " aLastVisibleArea.Height: " + aLastVisibleArea.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> curVisibleArea.X: " + curVisibleArea.X + " curVisibleArea.Y: " + curVisibleArea.Y + " curVisibleArea.Width: " + curVisibleArea.Width + " curVisibleArea.Height: " + curVisibleArea.Height); + GetOnscreenRange(curVisibleArea, ref onScreenRange); + + //Adjust the new start column: if the start column has items which are merge_hidden, + //find the item's smalllest start column as the new start column. + Column startColumn = groupList.ElementAt(onScreenRange.startGroupIndex).columnList.ElementAt(onScreenRange.startColumnIndex); + int cellCount = startColumn.cellList.Count; + + //save new range items to list + nextInMemoryItemSet.Clear(); + GetItemsInRange(onScreenRange, ref nextInMemoryItemSet); + + loadItem = nextInMemoryItemSet.Except(curInMemoryItemSet).ToList(); + unloadItem = curInMemoryItemSet.Except(nextInMemoryItemSet).ToList(); + } + + private void GetOnscreenRange(Rect visibleArea, ref Range range, bool bAllInArea = false) + { + Cell focusedCell = GetCellByItemIndex(focusGroupIndex, focusItemIndex); + + int focusColumnIndex = focusedCell.columnIndex; + + float areaStartPos, areaEndPos, focusedCellStart, focusedCellEnd; + if (GridType.Horizontal == gridType) + { + areaStartPos = visibleArea.X; + areaEndPos = visibleArea.X + visibleArea.Width; + focusedCellStart = focusedCell.rect.X; + focusedCellEnd = focusedCell.rect.X + focusedCell.rect.Width; + } + else + { + areaStartPos = visibleArea.Y; + areaEndPos = visibleArea.Y + visibleArea.Height; + focusedCellStart = focusedCell.rect.Y; + focusedCellEnd = focusedCell.rect.Y + focusedCell.rect.Height; + } + + bool bStartFound = false, bEndFound = false; + + int groupCount = groupList.Count; + //find start range + if ((bAllInArea == true && focusedCellStart < areaStartPos) + || (bAllInArea == false && focusedCellEnd < areaStartPos)) + { + for (int i = focusGroupIndex; i < groupCount && bStartFound == false; i++) + { + Group curGroup = groupList.ElementAt(i); + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : 0; + int columnCount = curGroup.columnList.Count; + for (int j = startColumnIndex; j < columnCount; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (true == bAllInArea) + { + if (curColumn.startPos >= areaStartPos) + { + range.startGroupIndex = i; + range.startColumnIndex = j; + bStartFound = true; + break; + } + } + else + { + if (curColumn.endPos > areaStartPos) + { + range.startGroupIndex = i; + range.startColumnIndex = j; + bStartFound = true; + break; + } + } + } + } + } + else + { + for (int i = focusGroupIndex; i >= 0 && bStartFound == false; i--) + { + Group curGroup = groupList.ElementAt(i); + int columnCount = curGroup.columnList.Count; + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : columnCount - 1; + for (int j = startColumnIndex; j >= 0; j--) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (curColumn.startPos <= areaStartPos) + { + if (bAllInArea == true) + { + if (j == columnCount - 1) + { + range.startGroupIndex = i + 1; + range.startColumnIndex = 0; + } + else + { + range.startGroupIndex = i; + range.startColumnIndex = j + 1; + } + + bStartFound = true; + break; + } + else + { + if (curColumn.endPos > areaStartPos) + { + range.startGroupIndex = i; + range.startColumnIndex = j; + } + else + { + if (j == columnCount - 1) + { + range.startGroupIndex = i + 1; + range.startColumnIndex = 0; + } + else + { + range.startGroupIndex = i; + range.startColumnIndex = j + 1; + } + } + + bStartFound = true; + break; + } + } + } + } + } + + if (bStartFound == false) + { + range.startGroupIndex = 0; + range.startColumnIndex = 0; + } + + //find end range + if ((bAllInArea == true && focusedCellEnd >= areaEndPos) + || (bAllInArea == false && focusedCellStart >= areaEndPos)) + { + for (int i = focusGroupIndex; i >= 0 && bEndFound == false; i--) + { + Group curGroup = groupList.ElementAt(i); + int columnCount = curGroup.columnList.Count; + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : columnCount - 1; + for (int j = startColumnIndex; j >= 0; j--) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (bAllInArea == true) + { + if (curColumn.endPos <= areaEndPos) + { + range.endGroupIndex = i; + range.endColumnIndex = j; + bEndFound = true; + break; + } + } + else + { + if (curColumn.startPos <= areaEndPos) + { + range.endGroupIndex = i; + range.endColumnIndex = j; + bEndFound = true; + break; + } + } + } + } + } + else + { + for (int i = focusGroupIndex; i < groupCount && bEndFound == false; i++) + { + Group curGroup = groupList.ElementAt(i); + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : 0; + int columnCount = curGroup.columnList.Count; + for (int j = startColumnIndex; j < columnCount; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (curColumn.endPos >= areaEndPos) + { + if (curColumn.startPos < areaEndPos) + { + range.endGroupIndex = i; + range.endColumnIndex = j; + } + else + { + if (j == 0) + { + range.endGroupIndex = i - 1; + range.endColumnIndex = groupList.ElementAt(i - 1).columnList.Count - 1; + } + else + { + range.endGroupIndex = i; + range.endColumnIndex = j - 1; + } + } + + bEndFound = true; + break; + } + } + } + } + + if (bEndFound == false) + { + range.endGroupIndex = groupCount - 1; + range.endColumnIndex = groupList.ElementAt(range.endGroupIndex).columnList.Count - 1; + } + + range.startGroupInScrn = range.startGroupIndex; + range.startColumnInScrn = range.startColumnIndex; + range.endGroupInScrn = range.endGroupIndex; + range.endColumnInScrn = range.endColumnIndex; + + //get on screen start and end item index + Group startGroup = groupList.ElementAt(range.startGroupInScrn); + Column startColumn = startGroup.columnList.ElementAt(range.startColumnInScrn); + Cell startCell = startColumn.cellList.ElementAt(0); + range.startItemIndexInScrn = startCell.itemIndex; + if (range.startItemIndexInScrn >= startGroup.itemList.Count) + { + range.startItemIndexInScrn = startGroup.itemList.Count - 1; + } + + Group endGroup = groupList.ElementAt(range.endGroupInScrn); + Column endColumn = endGroup.columnList.ElementAt(range.endColumnInScrn); + Cell endCell = endColumn.cellList.ElementAt(endColumn.cellList.Count - 1); + range.endItemIndexInScrn = endCell.itemIndex; + if (range.endItemIndexInScrn >= endGroup.itemList.Count) + { + range.endItemIndexInScrn = endGroup.itemList.Count - 1; + } + + //add buffer columns + int frontBufferCount = preloadFrontColumnSize; + while (frontBufferCount-- > 0) + { + if (range.startColumnIndex > 0) + { + range.startColumnIndex--; + } + else + { + if (range.startGroupIndex > 0) + { + range.startGroupIndex--; + range.startColumnIndex = groupList.ElementAt(range.startGroupIndex).columnList.Count - 1; + } + else + { + break; + } + } + } + + int backBufferCount = preloadBackColumnSize; + while (backBufferCount-- > 0) + { + if (range.endColumnIndex < groupList.ElementAt(range.endGroupIndex).columnList.Count - 1) + { + range.endColumnIndex++; + } + else + { + if (range.endGroupIndex < groupList.Count - 1) + { + range.endGroupIndex++; + range.endColumnIndex = 0; + } + else + { + break; + } + } + } + } + + private void GetItemsInRange(Range range, ref HashSet itemSet) + { + for (int i = range.startGroupIndex; i <= range.endGroupIndex; i++) + { + Group curGroup = groupList.ElementAt(i); + int startColumnIndex = (i == range.startGroupIndex) ? range.startColumnIndex : 0; + int endColumnIndex = (i == range.endGroupIndex) ? range.endColumnIndex : curGroup.columnList.Count - 1; + + for (int j = startColumnIndex; j <= endColumnIndex; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + + for (int k = 0; k < curColumn.cellList.Count; k++) + { + Cell curCell = curColumn.cellList.ElementAt(k); + if (curCell.itemIndex < curGroup.itemList.Count) + { + itemSet.Add(curGroup.itemList.ElementAt(curCell.itemIndex)); + } + } + } + } + } + + private void MoveFocus(string direction) + { + string logicalDirection = GetLogicalDirection(direction); + MoveFocus(logicalDirection, focusTagGroupIndex, focusTagItemIndex); + } + + // Get the specific groupIndex,itemIndex neighbor item according to direction + private GridItem GetItemByDirection(string direction, int fromGroupIndex, int fromItemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> direction: " + direction + " fromGroupIndex: " + fromGroupIndex + " fromItemIndex: " + fromItemIndex); + Cell currentCell = GetCellByItemIndex(fromGroupIndex, fromItemIndex); + + //adjust focused column index based on reference line + Group currentGroup = groupList.ElementAt(fromGroupIndex); + int currentColumnIndex = currentCell.columnIndex; + Column currentColumn = currentGroup.columnList.ElementAt(currentColumnIndex); + + int destFocusGroupIndex = -2, destFocusItemIndex = -2; + int destFocusColumnIndex = -1; + switch (direction) + { + case "Up": + destFocusGroupIndex = fromGroupIndex; + if (currentCell.rowIndex == 0) + { + destFocusItemIndex = -1; + } + else + { + Cell nextCell = currentColumn.cellList.ElementAt(currentCell.rowIndex - 1); + destFocusItemIndex = nextCell.itemIndex; + } + + break; + case "Down": + destFocusGroupIndex = fromGroupIndex; + if (currentCell.rowIndex >= currentColumn.cellList.Count - 1) + { + destFocusItemIndex = -1; + } + else if (fromItemIndex == currentGroup.itemList.Count - 1) + { + destFocusColumnIndex = currentColumnIndex - 1; + Column nextColumn = currentGroup.columnList.ElementAt(destFocusColumnIndex); + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex + 1); + destFocusItemIndex = nextCell.itemIndex; + } + else + { + Cell nextCell = currentColumn.cellList.ElementAt(currentCell.rowIndex + 1); + destFocusItemIndex = nextCell.itemIndex; + } + + break; + case "Left": + if (currentCell.columnIndex == 0) + { + if (fromGroupIndex == 0) + { + destFocusItemIndex = -1; + } + else + { + destFocusGroupIndex = fromGroupIndex - 1; + Group nextGroup = groupList.ElementAt(destFocusGroupIndex); + destFocusColumnIndex = nextGroup.columnList.Count - 1; + + Column nextColumn = nextGroup.columnList.ElementAt(destFocusColumnIndex); + if (currentCell.rowIndex >= nextColumn.cellList.Count) + { + Cell nextCell = nextColumn.cellList.ElementAt(nextColumn.cellList.Count - 1); + destFocusItemIndex = nextCell.itemIndex; + } + else + { + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + } + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = currentCell.columnIndex - 1; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex + " currentCell.rowIndex: " + currentCell.rowIndex); + Column nextColumn = currentGroup.columnList.ElementAt(destFocusColumnIndex); + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex); + } + + break; + case "Right": + if (currentColumnIndex == currentGroup.columnList.Count - 1) + { + if (fromGroupIndex == groupList.Count - 1) + { + destFocusItemIndex = -1; + } + else + { + destFocusGroupIndex = fromGroupIndex + 1; + destFocusColumnIndex = 0; + Group nextGroup = groupList.ElementAt(destFocusGroupIndex); + Column nextColumn = nextGroup.columnList.ElementAt(destFocusColumnIndex); + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = currentColumnIndex + 1; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex + " currentCell.rowIndex: " + currentCell.rowIndex); + Column nextColumn = currentGroup.columnList.ElementAt(destFocusColumnIndex); + if (currentCell.rowIndex >= nextColumn.cellList.Count) + { + + Cell nextCell = nextColumn.cellList.ElementAt(nextColumn.cellList.Count - 1); + destFocusItemIndex = nextCell.itemIndex; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex + " currentCell.rowIndex: " + currentCell.rowIndex + " nextColumn.cellList.Count: " + nextColumn.cellList.Count); + } + else + { + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex + " currentCell.rowIndex: " + currentCell.rowIndex + " nextColumn.cellList.Count: " + nextColumn.cellList.Count); + } + } + + break; + default: + break; + } + + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex + " destFocusItemIndex: " + destFocusItemIndex); + GridItem item = null; + if (IsGroupIndexValid(destFocusGroupIndex) == true && IsItemIndexValid(destFocusGroupIndex, destFocusItemIndex)) + { + item = groupList.ElementAt(destFocusGroupIndex).itemList.ElementAt(destFocusItemIndex); + } + + return item; + } + + private void MoveFocus(string direction, int fromGroupIndex, int fromItemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> direction: " + direction + " fromGroupIndex: " + fromGroupIndex + " fromItemIndex: " + fromItemIndex); + Cell curFocusedCell = GetCellByItemIndex(fromGroupIndex, fromItemIndex); + //change reference line of focus move + if (refXForFocusMove == -1) + { + refXForFocusMove = curFocusedCell.rect.X; + } + + if (refYForFocusMove == -1) + { + refYForFocusMove = curFocusedCell.rect.Y; + } + + //adjust focused column index based on reference line + Group focusedGroup = groupList.ElementAt(fromGroupIndex); + int focusedColumnIndex = curFocusedCell.columnIndex; + + Column focusedColumn = focusedGroup.columnList.ElementAt(focusedColumnIndex); + + int destFocusGroupIndex = -2, destFocusItemIndex = -2; + int destFocusColumnIndex = -1; + switch (direction) + { + case "Up": + destFocusGroupIndex = fromGroupIndex; + if (curFocusedCell.index == 0) + { + destFocusItemIndex = -1; + } + else + { + Cell nextCell = focusedColumn.cellList.ElementAt(curFocusedCell.index - 1); + { + destFocusItemIndex = nextCell.itemIndex; + if (destFocusItemIndex >= 0 && destFocusItemIndex < groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + if (GridType.Horizontal == gridType) + { + refYForFocusMove = nextCell.rect.Y; + } + else + { + refXForFocusMove = nextCell.rect.X; + } + } + } + } + + break; + case "Down": + destFocusGroupIndex = fromGroupIndex; + int destCellIndex = curFocusedCell.index + 1; + if (destCellIndex >= focusedColumn.cellList.Count || fromItemIndex == focusedGroup.itemList.Count - 1) + { + destFocusItemIndex = -1; + if (fromItemIndex == focusedGroup.itemList.Count - 1) + { + destFocusColumnIndex = focusedColumnIndex - 1; + Cell cellBelow = FindCellBelow(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex); + if (cellBelow != null) + { + destFocusItemIndex = cellBelow.itemIndex; + refXForFocusMove = cellBelow.rect.X; + refYForFocusMove = cellBelow.rect.Y; + } + } + } + else + { + Cell nextCell = null; + for (; destCellIndex < focusedColumn.cellList.Count; destCellIndex++) + { + nextCell = focusedColumn.cellList.ElementAt(destCellIndex); + { + break; + } + } + + if (destCellIndex >= focusedColumn.cellList.Count) + { + destFocusItemIndex = -1; + } + else + { + destFocusItemIndex = nextCell.itemIndex; + if (destFocusItemIndex >= 0 && destFocusItemIndex < groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + if (GridType.Horizontal == gridType) + { + refYForFocusMove = nextCell.rect.Y; + } + else + { + refXForFocusMove = nextCell.rect.X; + } + } + } + } + + break; + case "Left": + if (curFocusedCell.columnIndex == 0) + { + if (fromGroupIndex == 0) + { + if (StateLeftCircularEnable && true/*check whether allow to loop*/) + { + destFocusGroupIndex = groupList.Count - 1; + destFocusColumnIndex = groupList.ElementAt(destFocusGroupIndex).columnList.Count - 1; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + int itemCount = groupList.ElementAt(destFocusGroupIndex).itemList.Count; + while (destFocusItemIndex >= itemCount) + { + destFocusColumnIndex--; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + + bool bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + while (bEnabled == false) + { + destFocusColumnIndex--; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + } + + /*ToDo Left Circular*/ + SetFocus(destFocusGroupIndex, destFocusItemIndex); + return; + } + else + { + destFocusItemIndex = -1; + } + + } + else + { + destFocusGroupIndex = fromGroupIndex - 1; + destFocusColumnIndex = groupList.ElementAt(destFocusGroupIndex).columnList.Count - 1; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + int itemCount = groupList.ElementAt(destFocusGroupIndex).itemList.Count; + while (destFocusItemIndex >= itemCount) + { + destFocusColumnIndex--; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = curFocusedCell.columnIndex - 1; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + + break; + case "Right": + { + focusedColumnIndex = curFocusedCell.columnIndex; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusedColumnIndex: " + focusedColumnIndex); + if (focusedColumnIndex == focusedGroup.columnList.Count - 1 || focusedColumnIndex == focusedGroup.lastFilledColumnIndex) + { + if (fromGroupIndex == groupList.Count - 1) + { + if (StateRightCircularEnable && true/*check whether allow right circular*/) + { + destFocusGroupIndex = 0; + destFocusColumnIndex = 0; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + + bool bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + while (bEnabled == false && destFocusColumnIndex < focusedGroup.columnList.Count - 1) + { + destFocusColumnIndex++; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + + refXForFocusMove = refYForFocusMove = -1; + } + + /*ToDo Left Circular*/ + SetFocus(destFocusGroupIndex, destFocusItemIndex); + return; + } + else + { + destFocusItemIndex = -1; + } + } + else + { + destFocusGroupIndex = fromGroupIndex + 1; + destFocusColumnIndex = 0; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = focusedColumnIndex + 1; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex); + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex); + + if (StateRightCircularEnable) + { + if (destFocusItemIndex >= groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + MoveFocus(direction, destFocusGroupIndex, destFocusItemIndex); + return; + } + } + } + + break; + default: + break; + } + + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex); + if (destFocusGroupIndex >= 0 && destFocusItemIndex >= groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + destFocusItemIndex = -1; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex); + if (destFocusItemIndex == -1) + { + //notify event focus move out + return; + } + + if (gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex) == false) + { + MoveFocus(direction, destFocusGroupIndex, destFocusItemIndex); + } + else + { + PushFocus(destFocusGroupIndex, destFocusItemIndex); + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> "); + } + + + private void GetNearestItem(Cell focusedCell, int destGroupIndex, int destColumnIndex, ref int destItemIndex, bool bDirectMove = false) + { + Group destGroup = groupList.ElementAt(destGroupIndex); + Column destColumn = destGroup.columnList.ElementAt(destColumnIndex); + + Cell nextCell = destColumn.cellList.ElementAt(0); + int cellCount = destColumn.cellList.Count; + + bool bNotAllItemDisabled = false; + for (int i = 0; i < cellCount; i++) + { + Cell curCell = destColumn.cellList.ElementAt(i); + if (curCell.itemIndex >= 0 && curCell.itemIndex < destGroup.itemList.Count) + { + if (gridBridge.IsItemEnabled(destGroupIndex, curCell.itemIndex)) + { + bNotAllItemDisabled = true; + break; + } + } + } + + float yDis = gridHeight + 1; + bool bFound = false; + for (int i = 0; i < cellCount; i++) + { + Cell curCell = destColumn.cellList.ElementAt(i); + if (curCell.itemIndex >= destGroup.itemList.Count) + { + break; + } + + if (curCell.itemIndex >= 0 && bNotAllItemDisabled) + { + if (gridBridge.IsItemEnabled(destGroupIndex, curCell.itemIndex) == false) + { + continue; + } + } + + if (curCell.itemIndex < 0) + { + Column realColumn = destGroup.columnList.ElementAt(curCell.columnIndex); + Cell realCell = realColumn.cellList.ElementAt(curCell.rowIndex); + if (realCell.itemIndex >= destGroup.itemList.Count || gridBridge.IsItemEnabled(destGroupIndex, realCell.itemIndex) == false) + { + continue; + } + } + + if (GridType.Vertical == gridType) + { + float tempXDis; + if (StateStraightPathEnable) + { + tempXDis = Math.Abs(curCell.rect.X - refXForFocusMove); + } + else + { + tempXDis = Math.Abs(curCell.rect.X - focusedCell.rect.X); + } + + if (tempXDis < yDis) + { + bFound = true; + yDis = tempXDis; + nextCell = curCell; + if (yDis == 0) + { + break; + } + } + } + else + { + float tempYDis; + if (StateStraightPathEnable) + { + tempYDis = Math.Abs(curCell.rect.Y - refYForFocusMove); + } + else + { + tempYDis = Math.Abs(curCell.rect.Y - focusedCell.rect.Y); + } + + if (tempYDis < yDis) + { + bFound = true; + yDis = tempYDis; + nextCell = curCell; + if (yDis == 0) + { + break; + } + } + } + + } + + { + destItemIndex = nextCell.itemIndex; + if (bFound) + { + refXForFocusMove = nextCell.rect.X; + if (bDirectMove == false) + { + refYForFocusMove = nextCell.rect.Y; + } + } + } + } + + private string GetLogicalDirection(string direction) + { + string logicalDirection = direction; + + if (GridType.Vertical == gridType) + { + if ("Left" == direction) + { + logicalDirection = "Up"; + } + else if ("Right" == direction) + { + logicalDirection = "Down"; + } + else if ("Down" == direction) + { + logicalDirection = "Right"; + } + else if ("Up" == direction) + { + logicalDirection = "Left"; + } + } + + return logicalDirection; + } + + private Cell FindCellBelow(Cell fromCell, int destGroupIndex, int destColumnIndex) + { + Group destGroup = groupList.ElementAt(destGroupIndex); + + if (destColumnIndex < 0 || destColumnIndex >= destGroup.columnList.Count) + { + return null; + } + + Column destColumn = destGroup.columnList.ElementAt(destColumnIndex); + + for (int i = 0; i < destColumn.cellList.Count; i++) + { + Cell destCell = destColumn.cellList.ElementAt(i); + + if (destCell.rect.Y > fromCell.rect.Y && destCell.rect.Y + destCell.rect.Height > fromCell.rect.Y + fromCell.rect.Height) + { + { + return destCell; + } + } + } + + return null; + } + + private void SetFocus(int groupIndex, int itemIndex, bool bAnimation = false, Position newItemGroupPos = null) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> groupIndex: " + groupIndex + " itemIndex: " + itemIndex); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + return; + } + + bool bNeedScroll = false; + + if (newItemGroupPos == null) + { + Position itemGroupPos = new Position(0, 0, 0); + bNeedScroll = GetItemGroupPosByFocusItem(groupIndex, itemIndex, itemGroupPos); + + itemGroupRect.X = itemGroupPos.X; + itemGroupRect.Y = itemGroupPos.Y; + } + else + { + if (GridType.Horizontal == gridType && itemGroupRect.X != newItemGroupPos.X + || GridType.Vertical == gridType && itemGroupRect.Y != newItemGroupPos.Y) + { + bNeedScroll = true; + } + + itemGroupRect.X = newItemGroupPos.X; + itemGroupRect.Y = newItemGroupPos.Y; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> bNeedScroll: " + bNeedScroll + " itemGroupRect.X: " + itemGroupRect.X + " itemGroupRect.Y: " + itemGroupRect.Y); + ResetItemGroupRectPos(); + + Tizen.Log.Fatal("NUI", ">>>>>>>>> bNeedScroll: " + bNeedScroll + " itemGroupRect.X: " + itemGroupRect.X + " itemGroupRect.Y: " + itemGroupRect.Y); + if (bNeedScroll) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> bAnimation: " + bAnimation); + if (bAnimation == true) + { + FocusMoveViaObject obj = new FocusMoveViaObject(); + obj.toGroupIndex = groupIndex; + obj.toItemIndex = itemIndex; + focusMoveViaQ.Enqueue(obj); + + if (gridType == GridType.Horizontal) + { + focusMoveAni.SetDestination("PositionX", itemGroupRect.X); + } + else + { + focusMoveAni.SetDestination("PositionY", itemGroupRect.Y); + } + + focusMoveAni.Play(); + } + else + { + UpdateInMemoryItems(); + itemGroup.PositionX = itemGroupRect.X; + itemGroup.PositionY = itemGroupRect.Y; + NotifyFocusChange(focusGroupIndex, focusItemIndex, groupIndex, itemIndex); + } + } + else + { + NotifyFocusChange(focusGroupIndex, focusItemIndex, groupIndex, itemIndex); + } + + focusTagGroupIndex = groupIndex; + focusTagItemIndex = itemIndex; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + } + + + private void PushFocus(int groupIndex, int itemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> groupIndex: " + groupIndex + " itemIndex:" + itemIndex); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + return; + } + + Position itemGroupPos = new Position(0, 0, 0); + bool bNeedScroll = GetItemGroupPosByFocusItem(groupIndex, itemIndex, itemGroupPos); + + itemGroupRect.X = itemGroupPos.X; + itemGroupRect.Y = itemGroupPos.Y; + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect.X: " + itemGroupRect.X + " itemGroupRect.Y:" + itemGroupRect.Y); + + ResetItemGroupRectPos(); + + //focusTag keep move, but real focus will set when focusMoveVia trigger, + //so remember context of focus move, include from and to, and itemGroupPos information + focusTagGroupIndex = groupIndex; + focusTagItemIndex = itemIndex; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> bNeedScroll: " + bNeedScroll + " itemGroupRect.X:" + itemGroupRect.X + " itemGroupRect.Y:" + itemGroupRect.Y); + if (bNeedScroll) + { + if (gridType == GridType.Horizontal) + { + focusMoveAni.SetDestination("PositionX", itemGroupRect.X); + } + else + { + focusMoveAni.SetDestination("PositionY", itemGroupRect.Y); + } + + FocusMoveViaObject obj = new FocusMoveViaObject(); + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusMoveViaQ.Count: " + focusMoveViaQ.Count); + Tizen.Log.Fatal("NUI", "::::: " + focusGroupIndex + ", " + focusItemIndex); + + obj.toGroupIndex = groupIndex; + obj.toItemIndex = itemIndex; + focusMoveViaQ.Enqueue(obj); + focusMoveAni.Play(); + } + else + { + if (focusMoveAni.IsPlaying() == false) + { + Tizen.Log.Fatal("NUI", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ " + groupIndex + " " + itemIndex + " ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); + NotifyFocusChange(focusGroupIndex, focusItemIndex, groupIndex, itemIndex); + } + } + //To keep focusBar on the top of + + Tizen.Log.Fatal("NUI", ">>>>>>>>> "); + } + + private bool GetItemGroupPosByFocusItem(int aFocusGroupIndex, int aFocusItemIndex, Position itemGroupPos) + { + bool bNeedScroll = false; + if (!IsItemIndexValid(aFocusGroupIndex, aFocusItemIndex)) + { + return false; + } + + Group focusedGroup = groupList.ElementAt(aFocusGroupIndex); + GridItem focusedItem = focusedGroup.itemList.ElementAt(aFocusItemIndex); + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusedItem.rect: " + focusedItem.rect.X + ", " + focusedItem.rect.Y + ", " + focusedItem.rect.Width + ", " + focusedItem.rect.Height); + + Rect focusBarRectBaseOnList = new Rect(focusedItem.rect.X, focusedItem.rect.Y, focusedItem.rect.Width, focusedItem.rect.Height); + focusBarRectBaseOnList.X += itemGroupRect.X; + focusBarRectBaseOnList.Y += itemGroupRect.Y; + + itemGroupPos.X = itemGroupRect.X; + itemGroupPos.Y = itemGroupRect.Y; + + float startFocusRange; + float endFocusRange; + + if (GridType.Horizontal == gridType) + { + if (0 == focusedItem.rect.X) + { + startFocusRange = margin[0]; + } + else + { + Tizen.Log.Fatal("NUI", "Left aFocusItemIndex:: " + aFocusGroupIndex + ", aFocusItemIndex:: " + aFocusItemIndex); + GridItem prevItem = GetItemByDirection("Left", aFocusGroupIndex, aFocusItemIndex); + //Tizen.Log.Fatal("NUI", "startFocusRange :: " + margin[0]); + startFocusRange = prevItem != null ? prevItem.rect.Width / 2 : margin[0]; + } + + if (itemGroupRect.Width == focusedItem.rect.Right()) + { + endFocusRange = gridWidth - margin[2]; + } + else + { + GridItem nextItem = GetItemByDirection("Right", aFocusGroupIndex, aFocusItemIndex); + //Tizen.Log.Fatal("NUI", "gridWidth::" + gridWidth + " gridWidth - margin[2] :: " + (gridWidth - margin[2])); + //Tizen.Log.Fatal("NUI", "gridWidth - nextItem.rect.Width / 2 :: " + (gridWidth - nextItem.rect.Width / 2)); + endFocusRange = nextItem != null ? gridWidth - nextItem.rect.Width / 2 : gridWidth - margin[2]; + Tizen.Log.Fatal("NUI", "endFocusRange :: " + endFocusRange); + } + + if (focusBarRectBaseOnList.X < startFocusRange) + { + Tizen.Log.Fatal("NUI", "focusBarRectBaseOnList.X :: " + focusBarRectBaseOnList.X + " startFocusRange :: " + startFocusRange); + itemGroupPos.X += startFocusRange - focusBarRectBaseOnList.X; + bNeedScroll = true; + } + else if (focusBarRectBaseOnList.Right() > endFocusRange) + { + Tizen.Log.Fatal("NUI", "focusBarRectBaseOnList.Right() :: " + focusBarRectBaseOnList.Right() + " endFocusRange :: " + endFocusRange); + itemGroupPos.X += endFocusRange - focusBarRectBaseOnList.Right(); + bNeedScroll = true; + } + } + else + { + if (0 == focusedItem.rect.Y) + { + startFocusRange = margin[1]; + } + else + { + GridItem prevItem = GetItemByDirection("Left", aFocusGroupIndex, aFocusItemIndex); + startFocusRange = prevItem != null ? prevItem.rect.Height / 2 : margin[1]; + } + + if (itemGroupRect.Height == focusedItem.rect.Bottom()) + { + endFocusRange = gridHeight - margin[3]; + } + else + { + GridItem nextItem = GetItemByDirection("Right", aFocusGroupIndex, aFocusItemIndex); + endFocusRange = nextItem != null ? gridHeight - nextItem.rect.Height / 2 : gridHeight - margin[3]; + } + + if (focusBarRectBaseOnList.Y < startFocusRange) + { + itemGroupPos.Y += startFocusRange - focusBarRectBaseOnList.Y; + bNeedScroll = true; + } + else if (focusBarRectBaseOnList.Bottom() > endFocusRange) + { + itemGroupPos.Y += endFocusRange - focusBarRectBaseOnList.Bottom(); + bNeedScroll = true; + } + } + + return bNeedScroll; + } + + private void NotifyFocusChange(int fromGroupIndex,int fromItemIndex,int toGroupIndex,int toItemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> fromGroupIndex: " + fromGroupIndex + " fromItemIndex: " + fromItemIndex + " toGroupIndex: " + toGroupIndex + " toItemIndex: " + toItemIndex); + + if (IsItemIndexValid(fromGroupIndex, fromItemIndex) && (fromGroupIndex != toGroupIndex || fromItemIndex != toItemIndex)) + { + Group preGroup = groupList.ElementAt(fromGroupIndex); + GridItem preItem = preGroup.itemList.ElementAt(fromItemIndex); + + ScaleDownItem(preItem); + if (preItem.itemView != null) + { + gridBridge.FocusChange(fromGroupIndex, fromItemIndex, preItem.itemView, false); + } + } + + if (IsItemIndexValid(toGroupIndex, toItemIndex)) + { + Group curGroup = groupList.ElementAt(toGroupIndex); + GridItem item = curGroup.itemList.ElementAt(toItemIndex); + + ScaleUpItem(item); + if (item.itemView != null) + { + Tizen.Log.Fatal("NUI", "Call GridBridge.FocusChange to set focus"); + gridBridge.FocusChange(toGroupIndex, toItemIndex, item.itemView, true); + } + } + + //notify user focus change + GridEventArgs evtArgs = new GridEventArgs(); + evtArgs.EventType = GridEventType.FocusChange; + evtArgs.param[0] = fromGroupIndex; + evtArgs.param[1] = fromItemIndex; + evtArgs.param[2] = toGroupIndex; + evtArgs.param[3] = toItemIndex; + OnListEvent(evtArgs); + + if (toGroupIndex != -1 && toItemIndex != -1) + { + focusGroupIndex = toGroupIndex; + focusItemIndex = toItemIndex; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusGroupIndex: " + focusGroupIndex + " focusItemIndex: " + focusItemIndex); + } + + private void ScaleUpItem(GridItem item) + { + if (item.itemView == null) + { + return; + } + + item.itemView.RaiseToTop(); + item.ScaleItem(new Vector3(focusInScaleFactor, focusInScaleFactor, 1.0f), focusInScaleAnimationAttrs); + } + + private void ScaleDownItem(GridItem item) + { + if (item.itemView == null) + { + return; + } + + item.ScaleItem(new Vector3(1.0f, 1.0f, 1.0f), focusOutScaleAnimationAttrs); + } + + private void UpdateItemGroupSize() + { + if (groupList.Count == 0) + { + return; + } + + Group lastGroup = groupList.ElementAt(groupList.Count - 1); + + int lastItemIndex = lastGroup.itemList.Count - 1; + if (lastItemIndex < 0) + { + return; + } + + Cell lastFilledCell = GetCellByItemIndex(groupList.Count - 1 ,lastItemIndex); + int lastFilledColumnIndex = lastFilledCell.columnIndex; + Column lastFilledColumn = lastGroup.columnList.ElementAt(lastFilledColumnIndex); + + int cellCount = lastFilledColumn.cellList.Count; + for (int i = 0; i < cellCount; i++) + { + Cell curCell = lastFilledColumn.cellList.ElementAt(i); + if (curCell.columnIndex > lastFilledColumnIndex) + { + lastFilledColumnIndex = lastFilledColumn.cellList.ElementAt(i).columnIndex; + } + } + + lastFilledColumn = lastGroup.columnList.ElementAt(lastFilledColumnIndex); + + float width, height; + + if (GridType.Horizontal == gridType) + { + width = lastFilledColumn.endPos; + height = gridHeight - (margin[1] + margin[3]); + } + else + { + width = gridWidth - (margin[0] + margin[2]); + height = lastFilledColumn.endPos; + } + + itemGroupRect.Width = width; + itemGroupRect.Height = height; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + itemGroup.SizeWidth = itemGroupRect.Width; + itemGroup.SizeHeight = itemGroupRect.Height; + } + + private void InitItemGroupPosition() + { + if (GridType.Horizontal == gridType) + { + if (itemGroupRect.X > margin[0]) + { + itemGroupRect.X = margin[0]; + } + else if (itemGroupRect.Right() < gridWidth) + { + if (itemGroupRect.X >= gridWidth) + { + itemGroupRect.X = gridWidth - itemGroupRect.Width; + } + else + { + itemGroupRect.X = 0; + } + } + + itemGroupRect.Y = margin[1]; + } + else + { + itemGroupRect.X = margin[0]; + if (itemGroupRect.Y > margin[1]) + { + itemGroupRect.Y = margin[1]; + } + else if (itemGroupRect.Y + itemGroupRect.Height < gridHeight) + { + if (itemGroupRect.Y >= gridHeight) + { + itemGroupRect.Y = gridHeight - itemGroupRect.Height; + } + else + { + itemGroupRect.Y = 0; + } + } + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + ResetItemGroupRectPos(); + + itemGroup.PositionX = itemGroupRect.X; + itemGroup.PositionY = itemGroupRect.Y; + } + + private void ResetItemGroupRectPos() + { + //adjust item Group pos, to add margin when item group scroll to Head or Tail + if (GridType.Horizontal == gridType) + { + if (itemGroupRect.X == 0) + { + itemGroupRect.X += margin[0]; + } + else if (itemGroupRect.Right() == gridWidth) + { + itemGroupRect.X -= margin[2]; + } + } + else + { + if (itemGroupRect.Y == 0) + { + itemGroupRect.Y += margin[1]; + } + else if (itemGroupRect.Bottom() == gridHeight) + { + itemGroupRect.Y -= margin[3]; + } + } + } + + private Cell GetCellByItemIndex(int groupIndex, int itemIndex) + { + Cell curCell = null; + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return null; + } + + Group curGroup = groupList.ElementAt(groupIndex); + if (curGroup.itemIndexToCell.ContainsKey(itemIndex)) + { + curCell = curGroup.itemIndexToCell[itemIndex]; + } + + return curCell; + } + + private bool IsGroupIndexValid(int groupIndex) + { + return (groupIndex >= 0 && groupList != null && groupIndex < groupList.Count); + } + + private bool IsItemIndexValid(int groupIndex, int itemIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return false; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + return (itemIndex >= 0 && curGroup.itemList != null && itemIndex < curGroup.itemList.Count); + } + + private bool IsColumnIndexValid(int groupIndex, int columnIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return false; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + return (columnIndex >= 0 && curGroup.columnList != null && columnIndex < curGroup.columnList.Count); + } + + private bool IsCellIndexValid(int groupIndex, int columnIndex, int cellIndex) + { + if (!IsColumnIndexValid(groupIndex, columnIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid column index")); + return false; + } + + Column curColumn = groupList.ElementAt(groupIndex).columnList.ElementAt(columnIndex); + + return (cellIndex >= 0 && curColumn.cellList != null && cellIndex < curColumn.cellList.Count); + } + + /// + /// Called when the control gain key input focus. + /// + /// the object + /// the args of the event + public void ControlFocusGained(object sender, EventArgs e) + { + OnFocusGained(); + } + + public void OnFocusGained() + { + Tizen.Log.Fatal("NUI", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "); + SetFocus(focusGroupIndex, focusItemIndex); + } + + /// + /// Called when the control loses key input focus. + /// + /// the object + /// the args of the event + public void ControlFocusLost(object sender, EventArgs e) + { + OnFocusLost(); + } + + public void OnFocusLost() + { + Tizen.Log.Fatal("NUI", "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); + NotifyFocusChange(focusGroupIndex, focusItemIndex, -1, -1); + } + + private void OnFocusMoveViaEvent(object o, EventArgs e) + { + Tizen.Log.Fatal("NUI", "--------------------- " + focusMoveViaQ.Count + " -------------------------------"); + if (focusMoveViaQ.Count > 0) + { + { + FocusMoveViaObject obj = focusMoveViaQ.Dequeue(); + { + UpdateInMemoryItems(itemGroup.Position); + } + + { + //common focus notify focus change at destination of every via + NotifyFocusChange(focusGroupIndex, focusItemIndex, obj.toGroupIndex, obj.toItemIndex); + } + } + + //viaMap1.Remove(args.ViaNode); + } + } + + private void OnDataChange(object o, GridBridge.DataChangeEventArgs e) + { + switch (e.ChangeType) + { + case GridBridge.DataChangeEventType.Add: + AddItem(e.param[0]); + break; + case GridBridge.DataChangeEventType.Remove: + DeleteItem(e.param[0], e.param[1], e.param[2]); + break; + case GridBridge.DataChangeEventType.Insert: + InsertItem(e.param[0], e.param[1]); + break; + case GridBridge.DataChangeEventType.Clear: + Clear(); + break; + case GridBridge.DataChangeEventType.Reset: + ResetByData(); + break; + case GridBridge.DataChangeEventType.Load: + Load(); + Group curGroup = groupList.ElementAt(e.param[0]); + for (int i = e.param[1]; i < gridBridge.GetItemCount(e.param[0]); i++) + { + if (i < curGroup.itemList.Count) + { + gridBridge.UpdateItem(e.param[0], i, curGroup.itemList.ElementAt(i).itemView); + } + } + + if (focusItemIndex >= e.param[1] && focusItemIndex <= e.param[1] + e.param[2] - 1) + { + if (e.param[1] > 0) + { + SetFoucsItemIndex(e.param[1] - 1, focusGroupIndex); + } + else if (e.param[1] + e.param[2] < curGroup.itemList.Count) + { + SetFoucsItemIndex(e.param[1] + e.param[2], focusGroupIndex); + } + } + else if (focusItemIndex >= e.param[1] + e.param[2]) + { + SetFoucsItemIndex(focusItemIndex - e.param[2], focusGroupIndex); + } + + break; + default: + + break; + } + + refXForFocusMove = refYForFocusMove = -1; + } + + private void AddItem(int groupIndex) + { + int dataCount = gridBridge.GetItemCount(groupIndex); + if (dataCount > groupList.ElementAt(groupIndex).realCellCount) + { + AddColumn(colW, groupIndex); + int columnIndex = groupList.ElementAt(groupIndex).columnList.Count - 1; + for (int i = 0; i < rowCnt; i++) + { + AddRowToColumn(columnIndex, rowH, groupIndex); + } + } + + Load(); + } + + private void AddAll(int groupIndex, int count) + { + Load(); + } + + + private void DeleteItem(int groupIndex, int fromItemIndex, int deleteItemNum) + { + Group curGroup = groupList.ElementAt(groupIndex); + + GridItem item = null; + + int toItemIndex = fromItemIndex + deleteItemNum - 1; + + int count = 0; + + for (int i = fromItemIndex; i < curGroup.itemList.Count; i++) + { + item = curGroup.itemList.ElementAt(i); + if (curInMemoryItemSet.Contains(item)) + { + UnloadItem(item, true); + count++; + } + } + + for (int i = 0; i < count; i++) + { + curGroup.itemList.Remove(curGroup.itemList.ElementAt(curGroup.itemList.Count - 1)); + } + } + + private void InsertItem(int groupIndex, int itemIndex) + { + Load(); + + Group curGroup = groupList.ElementAt(groupIndex); + for (int i = itemIndex; i < gridBridge.GetItemCount(groupIndex); i++) + { + if (i < curGroup.itemList.Count) + { + gridBridge.UpdateItem(groupIndex, i, curGroup.itemList.ElementAt(i).itemView); + } + } + } + + private void Clear() + { + for (int i = 0; i < groupList.Count; i++) + { + Clear(i); + } + + ClearRecycleBin(); + } + + private void Clear(int groupIndex) + { + Tizen.Log.Fatal("NUI", "--------------------- " + groupIndex + " -------------------------------"); + Group curGroup = groupList.ElementAt(groupIndex); + for (int i = 0; i < curGroup.itemList.Count; i++) + { + GridItem item = curGroup.itemList.ElementAt(i); + if (curInMemoryItemSet.Contains(item)) + { + UnloadItem(item, false); + } + } + + curGroup.itemList.Clear(); + } + + private void ResetByData() + { + Tizen.Log.Fatal("NUI", "...."); + int groupCount = gridBridge.GetGroupCount(); + ResetGroup(groupCount); + for (int i = 0; i < groupCount; i++) + { + Tizen.Log.Fatal("NUI", ".... group: " + i); + int dataCount = gridBridge.GetItemCount(i); + Tizen.Log.Fatal("NUI", ".... dataCount: " + dataCount + " rowCnt: " + rowCnt); + int columnCount = (dataCount + rowCnt - 1) / rowCnt; + Group group = groupList.ElementAt(i); + Tizen.Log.Fatal("NUI", ".... columnCount: " + columnCount + " group.columnList.Count: " + group.columnList.Count + " group.itemIndexToCell.Count: " + group.itemIndexToCell.Count); + if (columnCount > group.columnList.Count) + { + for (int c = group.columnList.Count; c < columnCount; c++) + { + AddColumn(colW, i); + for (int r = 0; r < rowCnt; r++) + { + AddRowToColumn(c, rowH, i); + } + } + } + else if (columnCount < group.columnList.Count) + { + float posOffset = -(group.columnList.Count - columnCount) * (colW + columnSpace) + ColumnSpace; + + for (int c = columnCount; c < group.columnList.Count; c++) + { + for (int r = 0; r < rowCnt; r++) + { + int itemIndex = c * rowCnt + r; + group.itemIndexToCell.Remove(itemIndex); + group.realCellCount--; + Tizen.Log.Fatal("NUI", ".... itemIndexToCell.Remove: " + itemIndex); + } + } + + group.columnList.RemoveRange(columnCount, group.columnList.Count - columnCount); + group.endPos = group.columnList.ElementAt(columnCount - 1).endPos; + for (int j = i + 1; j < groupList.Count; j++) + { + if (GridType.Horizontal == gridType && groupList.ElementAt(j).title != null) + { + groupList.ElementAt(j).title.PositionX += posOffset; + } + + groupList.ElementAt(j).ResetPosition(posOffset); + } + + } + + Tizen.Log.Fatal("NUI", ".... group.columnList.Count: " + group.columnList.Count); + } + + focusGroupIndex = 0; + focusItemIndex = 0; + Tizen.Log.Fatal("NUI", "...."); + Load(); + if (HasFocus() == true && curInMemoryItemSet.Count != 0) + { + SetFocus(0, 0); + } + } + + /*page length set to grid length*/ + private void PageMove(bool bPrev, bool bAni) + { + Rect visibleAreaOfItemGroup = new Rect(-itemGroupRect.X, -itemGroupRect.Y, gridWidth, gridHeight); + + if (GridType.Horizontal == gridType) + { + if (bPrev) + { + visibleAreaOfItemGroup.X -= gridWidth; + if (0 > visibleAreaOfItemGroup.X) + { + visibleAreaOfItemGroup.X = 0; + } + } + else + { + visibleAreaOfItemGroup.X += gridWidth; + if (-visibleAreaOfItemGroup.X + itemGroupRect.Width < gridWidth) + { + visibleAreaOfItemGroup.X = itemGroupRect.Width - gridWidth; + } + } + + if (-itemGroupRect.X == visibleAreaOfItemGroup.X) + { + return; + } + } + else + { + if (bPrev) + { + visibleAreaOfItemGroup.Y -= gridHeight; + if (0 > visibleAreaOfItemGroup.Y) + { + visibleAreaOfItemGroup.Y = 0; + } + } + else + { + visibleAreaOfItemGroup.Y += gridHeight; + if (-visibleAreaOfItemGroup.Y + itemGroupRect.Height < gridHeight) + { + visibleAreaOfItemGroup.Y = itemGroupRect.Height - gridHeight; + } + } + + if (-itemGroupRect.Y == visibleAreaOfItemGroup.Y) + { + return; + } + } + + Range newRange = new Range(0, 0, 0, 0); + GetOnscreenRange(visibleAreaOfItemGroup, ref newRange, true); + + Group curFocusedGroup = groupList.ElementAt(focusGroupIndex); + Cell curFocusedCell = GetCellByItemIndex(focusGroupIndex, focusItemIndex); + Column curFocusedColumn = curFocusedGroup.columnList.ElementAt(curFocusedCell.columnIndex); + + float focusStartLine = curFocusedColumn.startPos; + float focusEndLine = curFocusedColumn.endPos; + float focusMiddleLine = 0; + + if (newRange.startGroupInScrn >= 0 && newRange.endGroupInScrn >= 0) + { + if (GridType.Horizontal == gridType) + { + focusStartLine = focusStartLine + itemGroupRect.X + visibleAreaOfItemGroup.X; + focusEndLine = focusEndLine + itemGroupRect.X + visibleAreaOfItemGroup.X; + } + else + { + focusStartLine = focusStartLine + itemGroupRect.Y + visibleAreaOfItemGroup.Y; + focusEndLine = focusEndLine + itemGroupRect.Y + visibleAreaOfItemGroup.Y; + } + + focusMiddleLine = focusStartLine + (focusEndLine - focusStartLine) / 2; + + int nextFocusGroup = -1; int nextFocusColumn = -1; + bool bFound = false; + for (int i = newRange.startGroupInScrn; i <= newRange.endGroupInScrn && bFound == false; i++) + { + Group curGroup = groupList.ElementAt(i); + + int startColumnIndex = (i == newRange.startGroupInScrn) ? newRange.startColumnInScrn : 0; + int endColumnIndex = (i == newRange.endGroupInScrn) ? newRange.endColumnInScrn : curGroup.columnList.Count - 1; + + for (int j = startColumnIndex; j <= endColumnIndex; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (curColumn.startPos <= focusMiddleLine && curColumn.endPos >= focusMiddleLine) + { + nextFocusGroup = i; + nextFocusColumn = j; + bFound = true; + break; + } + } + + if (bFound == false && i == newRange.startGroupInScrn && focusMiddleLine < curGroup.columnList.ElementAt(startColumnIndex).startPos) + { + nextFocusGroup = i; + nextFocusColumn = startColumnIndex; + break; + } + + else if (bFound == false && i == newRange.endGroupInScrn && focusMiddleLine > curGroup.columnList.ElementAt(endColumnIndex).endPos) + { + nextFocusGroup = i; + nextFocusColumn = endColumnIndex; + break; + } + } + + if (nextFocusGroup >= 0 && nextFocusColumn >= 0) + { + int nextFocusItem = -1; + GetNearestItem(curFocusedCell, nextFocusGroup, nextFocusColumn, ref nextFocusItem); + + if (nextFocusItem >= 0) + { + while (gridBridge.IsItemEnabled(nextFocusGroup, nextFocusItem) == false) + { + nextFocusItem = GetNextColumnIndex(bPrev, nextFocusColumn, ref nextFocusGroup); + } + + if (nextFocusItem >= 0) + { + Position newItemGroupPos = new Position(-visibleAreaOfItemGroup.X, -visibleAreaOfItemGroup.Y, 0); + SetFocus(nextFocusGroup, nextFocusItem, bAni, newItemGroupPos); + } + } + } + } + } + + private int GetNextColumnIndex(bool bPrev, int curColumnIndex, ref int curGroupIndex) + { + if (bPrev == true) + { + if (curColumnIndex == 0) + { + if (curGroupIndex == 0) + { + return -1; + } + else + { + curGroupIndex--; + return groupList.ElementAt(curGroupIndex).columnList.Count - 1; + } + } + else + { + return curColumnIndex - 1; + } + } + else + { + Group curGroup = groupList.ElementAt(curGroupIndex); + if (curGroup.columnList.Count - 1 == curColumnIndex) + { + if (groupList.Count - 1 == curGroupIndex) + { + return -1; + } + else + { + curGroupIndex++; + return 0; + } + } + else + { + return curColumnIndex + 1; + } + } + } + + private class GridItem + { + public void ScaleItem(Vector3 scaleFactor, AnimationAttributes aniAttrs) + { + if (itemView == null || scaleFactor == null || aniAttrs == null) + { + return; + } + + if (scaleAni == null) + { + scaleAni = new Animation(); + } + + if (scaleAni.State == Animation.States.Playing) + { + scaleAni.Stop(Animation.EndActions.StopFinal); + } + + scaleAni.Clear(); + scaleAni.AnimateTo(itemView, "Scale", scaleFactor, 0, aniAttrs.Duration, new AlphaFunction(aniAttrs.BezierPoint1, aniAttrs.BezierPoint2)); + scaleAni.Play(); + } + + public int groupIndex; + public int index; + + public View itemView; + public Rect rect; + + private Animation scaleAni = null; + } + + private class Cell + { + public int columnIndex; + public int index; + public int itemIndex; + public int rowIndex; + + public Rect rect; + public Cell() + { + rect = new Rect(0, 0, 0, 0); + } + } + + private class Column + { + public int groupIndex; + public int index; + + public float space; + public float startPos; + public float endPos; + + public int startItemIndex; + public int endItemIndex; + + public List cellList; + } + + private class Group + { + public int index; + + public float startPos; + public float endPos; + + public int realCellCount; + public int lastFilledColumnIndex; + + public List columnList; + public List itemList; + public Dictionary itemIndexToCell; + + public void ResetPosition(float posOffset) + { + startPos += posOffset; + endPos += posOffset; + + int count = columnList.Count; + for (int i = 0; i < count; i++) + { + Column column = columnList.ElementAt(i); + column.startPos += posOffset; + column.endPos += posOffset; + + int cellCount = column.cellList.Count; + for (int j = 0; j < cellCount; j++) + { + column.cellList.ElementAt(j).rect.X += posOffset; + } + } + } + + public View title; + } + + private class Range + { + public int startGroupIndex; + public int startColumnIndex; + + public int endGroupIndex; + public int endColumnIndex; + + public int startGroupInScrn; + public int startColumnInScrn; + + public int endGroupInScrn; + public int endColumnInScrn; + + public int startItemIndexInScrn; + public int endItemIndexInScrn; + + public Range() + { + startGroupIndex = 0; + startColumnIndex = 0; + endGroupIndex = 0; + endColumnIndex = 0; + } + + public Range(int a, int b, int c, int d) + { + startGroupIndex = a; + startColumnIndex = b; + endGroupIndex = c; + endColumnIndex = d; + } + } + + private class FocusMoveViaObject + { + public int toGroupIndex; + public int toItemIndex; + } + + const int INVALID_COUNT = -1; + + private List groupList; + private GridBridge gridBridge; + + private View itemGroup; + private Rect itemGroupRect; + + private Vector4 margin = Vector4.Zero; + + private float gridWidth; + private float gridHeight; + + private int preloadFrontColumnSize = 1; + private int preloadBackColumnSize = 1; + + //layout attributes + private GridType gridType = GridType.Horizontal; + private int groupSpace = 0; + private int columnSpace = 0; + private int rowSpace = 0; + private int titleSpace = 0; + + private int rowCnt = 0; + private int colCnt = 0; + private int colW = 0; + private int rowH = 0; + + //focus + private int focusGroupIndex; + private int focusItemIndex; + + private float refXForFocusMove; + private float refYForFocusMove; + + private int focusTagGroupIndex; + private int focusTagItemIndex; + //animation + LinkerAnimation focusMoveAni; + + private float focusInScaleFactor; + + private AnimationAttributes focusInScaleAnimationAttrs; + + private AnimationAttributes focusOutScaleAnimationAttrs; + + private int focusMoveAniDuration; + + private Queue focusMoveViaQ = new Queue(); + + //for load + private HashSet curInMemoryItemSet; + private HashSet nextInMemoryItemSet; + + private Rect lastVisibleArea; + + private Range onScreenRange; + + //reuse + private List[] recycledViews; + private int viewTypeCount; + + private EventHandler gridEventHandlers; + } + + /// + /// The attributes of Animation. + /// + /// + /// AnimationAttributes attrs = new AnimationAttributes(); + /// attrs.BezierPoint1 = new Vector2(0.21f, 2); + /// attrs.BezierPoint2 = new Vector2(0.14f, 1); + /// attrs.Duration = 1000; + /// + public class AnimationAttributes + { + /// V1 on bezier curve + public Vector2 BezierPoint1; + /// V2 on bezier curve + public Vector2 BezierPoint2; + /// Animation duration + public int Duration; + + /// + /// Constructs a AnimationAttributes.. + /// + public AnimationAttributes() + { + } + + /// + /// Constructs a AnimationAttributes with curve style.. + /// + /// curve + public AnimationAttributes(string curve) + { + } + + /// + /// Constructs a AnimationAttributes that is a copy of attrs.. + /// + /// Construct Attributes + public AnimationAttributes(AnimationAttributes attrs = null) + { + if (attrs == null) + { + return; + } + + if (attrs.BezierPoint1 != null) + { + BezierPoint1 = new Vector2(attrs.BezierPoint1[0], attrs.BezierPoint1[1]); + } + + if (attrs.BezierPoint2 != null) + { + BezierPoint2 = new Vector2(attrs.BezierPoint2[0], attrs.BezierPoint2[1]); + } + + Duration = attrs.Duration; + } + + /// Clone a AnimationAttributes + /// The AnimationAttributes copy + public AnimationAttributes Clone() + { + return new AnimationAttributes(this); + } + } + + /// + /// A GridBridge object acts as a pipeline between an BridgeView and the + /// underlying data for that view. The Bridge provides access to the data items. + /// The Bridge is also responsible for making a View for each item in the data set. + /// + public abstract class GridBridge + { + /// + /// Event type of data change. + /// + public enum DataChangeEventType + { + Add, + Remove, + Insert, + Clear, + Load, + Reset + } + + /// + /// Data change event args at event call back, + /// user can get information about data change. + /// + /// + ///private void OnDataChange(object o, GridBridge.DataChangeEventArgs e) + ///{ + ///} + /// + public class DataChangeEventArgs : EventArgs + { + /// + /// Data changed event type. + /// + public DataChangeEventType ChangeType + { + get { return m_ChangeType; } + set { m_ChangeType = value; } + } + + /// + /// Changed data. + /// + public object data; + /// + /// Data change event parameters. + /// + public int[] param = new int[4]; + + private DataChangeEventType m_ChangeType; + } + + /// + /// Event handler of data change event. + /// + /// The object who sends the event. + /// The event arguments. + public delegate void EventHandler(object sender, DataChangeEventArgs e); + + /// + /// Data change event handler, user can add/remove. + /// + public event EventHandler DataChangeEvent + { + add + { + dataChangeEventHandlers += value; + } + + remove + { + dataChangeEventHandlers -= value; + } + } + + /// + /// Constructor to create a grid view bridge with multi-groups. + /// + /// Data list of differet groups. + public GridBridge(List> objects) + { + gridData = objects; + } + + /// + /// Simple constructor to create a grid view bridge with one group. + /// + /// Data list of grid view. + public GridBridge(List objects) + { + gridData = new List>(); + gridData.Add(objects); + } + + /// + /// Create item View. + /// + /// Group index of item in grid view. + /// Item index of specified group of grid view. + /// View of specified item. + public abstract View GetItemView(int groupIndex, int itemIndex); + + /// + /// Create group title of specified group, need to be overrided. + /// + /// Group index of grid view. + /// Group title view. + public virtual View GetGroupTitleView(int groupIndex) + { + return null; + } + + /// + /// Remove group title of specified group, need to be overrided. + /// + /// Group index of grid view. + /// Group title view. + public virtual void RemoveGroupTitleView(int groupIndex, View groupTitle) + { + + } + + /// + /// Update View that displays the data at the specified index in the data set when data change. + /// + /// The group index. + /// The item index. + /// A View that displays the data at the specified index in the data set. + public abstract void UpdateItem(int groupIndex, int itemIndex, View view); + + /// + /// Update View that displays the data at the specified index in the data set when focus change. + /// + /// The group index. + /// The item index. + /// Item view of specified item. + /// Focus in or focus out + /// LinearView item selected or not. + public abstract void FocusChange(int groupIndex, int itemIndex, View view, bool FlagFocused, bool bSelected = false); + + /// + /// Unload view at the specified index when item scroll out or deleted. + /// + /// The group index. + /// The item index. + /// Item view of specified item. + public abstract void UnloadItem(int groupIndex, int itemIndex, View view); + + /// + /// Unload view according to the specified viewType. + /// + /// Item type set by users. + /// A View that displays the data at the specified index in the data set. + public abstract void UnloadItemByViewType(int viewType, View view); + + /// + /// Get the type of View that will be created by GetView for the specified item. + /// + /// The group index. + /// The item index. + /// Integers must be in the range 0 to GetItemTypeCount() - 1. + /// Item type. + public virtual int GetItemType(int groupIndex, int itemIndex) + { + return 0; + } + + /// + /// Get the number of view types. + /// + /// The count of view type. + public virtual int GetItemTypeCount() + { + return 1; + } + + /// + /// Check whether item is enable or not. + /// + /// The group index. + /// The item index. + /// Item is enabled or disabled. + public virtual bool IsItemEnabled(int groupIndex, int itemIndex) + { + return true; + } + + /// + /// Get the data at the specified index. + /// + /// The item index. + /// The group index. + /// The data at the specified index. + public object GetData(int itemIndex, int groupIndex = 0) + { + object data = null; + if (gridData != null && gridData.ElementAt(groupIndex) != null && itemIndex >= 0 && itemIndex < gridData.ElementAt(groupIndex).Count) + { + data = gridData.ElementAt(groupIndex).ElementAt(itemIndex); + } + + return data; + } + + /// + /// Get data group count of the bridge. + /// + /// Group count of the data set. + public int GetGroupCount() + { + int count = 0; + if (gridData != null) + { + count = gridData.Count; + } + + return count; + } + + /// + /// How many items are in the data set of specified group. + /// + /// The data group index. + /// Count of items of specified group. + public int GetItemCount(int groupIndex = 0) + { + int count = 0; + if (gridData != null && gridData.ElementAtOrDefault(groupIndex) != null) + { + count = gridData.ElementAt(groupIndex).Count; + } + + return count; + } + + /// + /// How many items are in the data set of whole data list. + /// + /// Count of total items + public int GetTotalCount() + { + int count = 0; + if (gridData != null) + { + foreach (List group in gridData) + { + count += group.Count; + } + } + + return count; + } + + /// + /// Adds the specified data at the end of the List of specified group. + /// + /// The data to add at the end of the List. + /// The group index which need to add data. + /// Notify list to remove item or not. + public void Add(object data, int groupIndex = 0, bool sendEvent = true) + { + Debug.Assert(groupIndex < gridData.Count); + + gridData[groupIndex].Add(data); + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Add; + e.param[0] = groupIndex; + e.data = data; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Removes the specified data from the List of specified group. + /// + /// The from index of data to remove from the list. + /// The remove number of data to remove from the list. + /// The group index which need to add data. + /// Remove with animation or not. + /// Notify list to remove item or not. + + public void RemoveItems(int fromIndex, int removeNum, int groupIndex = 0, bool withAni = false, bool sendEvent = true) + { + Debug.Assert(groupIndex < gridData.Count); + + if (fromIndex + removeNum > gridData[groupIndex].Count) + { + return; + } + + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Remove; + e.param[0] = groupIndex; + e.param[1] = fromIndex; + e.param[2] = removeNum; + e.param[3] = withAni ? 1 : 0; + OnDataChangeEvent(this, e, sendEvent); + gridData[groupIndex].RemoveRange(fromIndex, removeNum); + e.ChangeType = DataChangeEventType.Load; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Removes the specified data from the List of specified group. + /// + /// The from index of data to remove from the list. + /// The group index which need to add data. + /// Remove with animation or not. + /// Notify list to remove item or not. + public void Remove(int itemIndex, int groupIndex = 0, bool withAni = false, bool sendEvent = true) + { + if (itemIndex < 0 || itemIndex >= GetItemCount(groupIndex)) + { + Tizen.Log.Fatal("NUI", "Error!! item index is invalid"); + return; + } + + RemoveItems(itemIndex, 1, groupIndex, withAni, sendEvent); + } + + /// + /// Inserts the specified data at the specified index in the List of specified group. + /// + /// The index at which the data must be inserted. + /// The data to insert into the list. + /// The group index which need to insert data. + /// Notify list to remove item or not. + public void Insert(int index, object data, int groupIndex = 0, bool sendEvent = true) + { + Debug.Assert(groupIndex < gridData.Count); + + gridData[groupIndex].Insert(index, data); + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Insert; + e.data = data; + e.param[0] = groupIndex; + e.param[1] = index; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Remove all elements from the list. + /// + /// Notify list to remove item or not. + public void Clear(bool sendEvent = true) + { + if (gridData != null) + { + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Clear; + OnDataChangeEvent(this, e, sendEvent); + gridData.Clear(); + } + } + + /// + /// Reset bridge, and Update LinearView with new bridge data. + /// + /// Data list of differet groups. + /// Notify list to remove item or not. + public void Reset(List> objects, bool sendEvent = true) + { + Clear(); + gridData = objects; + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Reset; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Reset bridge, and Update LinearView with new bridge data. + /// + /// Data list of grid view. + /// Notify list to remove item or not. + public void Reset(List objects, bool sendEvent = true) + { + Clear(); + gridData = new List>(); + gridData.Add(objects); + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Reset; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Swap data of specified group. + /// + /// The group index which need to insert data. + /// First item index of the group. + /// Second item index of the group. + public void SwapGroupData(int groupIndex, int from, int to) + { + List groupDataList = gridData.ElementAt(groupIndex); + object fromData = groupDataList.ElementAt(from); + groupDataList[from] = groupDataList[to]; + groupDataList[to] = fromData; + } + + private void OnDataChangeEvent(object sender, DataChangeEventArgs e, bool sendEvent = true) + { + if (!sendEvent) + { + return; + } + + if (dataChangeEventHandlers != null) + { + dataChangeEventHandlers(sender, e); + } + } + + private List> gridData; + private EventHandler dataChangeEventHandlers; + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `focusedCell` last assigned on line 1293 could be null and is dereferenced at line 1295, column 13. + +### Severity: +ERROR + +### Procedure: +Void GridView.GetOnscreenRange(Rect,GridView$Range&,Boolean) + +### File: +TV/MediaHubSample/MediaHubSample/src/View/GridView/Grid.cs + +### Key: +Grid.cs|GetOnscreenRange|NULL_DEREFERENCE + +### Node Key: +1466417a2c6e07913ac313df0b77f760 + +### Hash: +3d7fc4fb42aaff3ee4e22bca635375a9 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0791/instruction.md b/inferredbugs-0791/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..deea579413c1a00ee01506d78d60d4b914c96f52 --- /dev/null +++ b/inferredbugs-0791/instruction.md @@ -0,0 +1,331 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** CoreHook +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.Win32.SafeHandles; +using System; +using System.Text; +using System.IO; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Diagnostics; + +namespace CoreHook.Memory +{ + public static partial class ThreadHelper + { + public static SafeWaitHandle CreateRemoteThread( + SafeProcessHandle processHandle, + IntPtr startAddress, + IntPtr parameter) + { + return Interop.Kernel32.CreateRemoteThread( + processHandle, + IntPtr.Zero, + UIntPtr.Zero, + startAddress, + parameter, + 0, + IntPtr.Zero); + } + + public static IntPtr GetProcAddress(SafeProcessHandle processHandle, string module, string function) + { + var moduleHandle = GetModuleHandle(processHandle, module); + + if(moduleHandle == IntPtr.Zero) + { + throw new Win32Exception($"Failed to get the {module} handle."); + } + + return GetModuleFunctionAddress(processHandle, moduleHandle, function); + } + + private static IntPtr GetModuleFunctionAddress(SafeProcessHandle processHandle, + IntPtr moduleHandle, string functionName) + { + Interop.Kernel32.NtModuleInfo moduleInfo = GetModuleInfo(processHandle, moduleHandle); + + DataDirectory exportDirectory = ReadExportDataDirectory(ReadPage(processHandle, moduleInfo.BaseOfDll), 0); + + var exportTable = new byte[exportDirectory.Size]; + var exportTableAddress = moduleInfo.BaseOfDll + (int)exportDirectory.Rva; + if (!Interop.Kernel32.ReadProcessMemory( + processHandle, + exportTableAddress, + exportTable, + new UIntPtr((uint)exportTable.Length), + out UIntPtr bytesRead) || bytesRead.ToUInt32() != exportTable.Length) + { + throw new Win32Exception($"Cannot read export table at {exportTableAddress.ToInt64()}"); + } + + return new IntPtr(moduleInfo.BaseOfDll.ToInt64() + + GetAddressFromExportTable(exportTable, exportDirectory.Rva, functionName).ToInt64()); + } + + private static byte[] ReadPage(SafeProcessHandle processHandle, IntPtr pageAddress) + { + var page = new byte[Environment.SystemPageSize]; + if(!Interop.Kernel32.ReadProcessMemory( + processHandle, + pageAddress, + page, + new UIntPtr((uint)page.Length), + out UIntPtr bytesRead) || bytesRead.ToUInt32() != page.Length) + { + throw new Win32Exception( + $"Failed to read process memory page: {pageAddress.ToInt64():X16}."); + } + return page; + } + + private static Interop.Kernel32.NtModuleInfo GetModuleInfo(SafeProcessHandle processHandle, IntPtr moduleHandle) + { + if(!Interop.Kernel32.GetModuleInformation( + processHandle, + moduleHandle, + out Interop.Kernel32.NtModuleInfo moduleInfo)) + { + throw new Win32Exception("Failed to get process module information"); + } + return moduleInfo; + } + + private static IntPtr GetModuleHandle(SafeProcessHandle processHandle, string moduleName) + { + IntPtr[] moduleHandles = GetProcessModuleHandles(processHandle); + char[] chars = new char[1024]; + + foreach (IntPtr moduleHandle in moduleHandles) + { + int length = Interop.Kernel32.GetModuleFileNameEx(processHandle, moduleHandle, chars, chars.Length); + if (length == 0) + { + continue; + } + + var moduleFileName = (length >= 4 && chars[0] == '\\' && chars[1] == '\\' && chars[2] == '?' && chars[3] == '\\') ? + new string(chars, 4, length - 4) : + new string(chars, 0, length); + + if (length == moduleName.Length) + { + if (moduleName.Equals(moduleFileName, StringComparison.OrdinalIgnoreCase)) + { + return moduleHandle; + } + } + } + + return IntPtr.Zero; + } + + private static IntPtr[] GetProcessModuleHandles(SafeProcessHandle processHandle) + { + IntPtr[] moduleHandles = new IntPtr[64]; + GCHandle moduleHandlesArrayHandle = new GCHandle(); + int moduleCount = 0; + for (; ;) + { + bool enumResult = false; + try + { + moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned); + enumResult = Interop.Psapi.EnumProcessModulesEx(processHandle, + moduleHandlesArrayHandle.AddrOfPinnedObject(), + (uint)(moduleHandles.Length * IntPtr.Size), + ref moduleCount, + Interop.Psapi.ModuleFilterFlags.All); + } + finally + { + moduleHandlesArrayHandle.Free(); + } + + if (!enumResult) + { + throw new Win32Exception("Failed to retrieve process modules."); + } + + moduleCount /= IntPtr.Size; + if (moduleCount <= moduleHandles.Length) + break; + + moduleHandles = new IntPtr[moduleHandles.Length * 2]; + } + return moduleHandles; + } + + private static DataDirectory ReadExportDataDirectory(byte[] programHeader, int index) + { + using (var reader = new BinaryReader(new MemoryStream(programHeader))) + { + const uint portableExecutableMagic = 0x00004550; + reader.BaseStream.Position = 0x3c; + + reader.BaseStream.Position = reader.ReadInt32(); + + if(reader.ReadUInt32() != portableExecutableMagic) + { + throw new Win32Exception( + $"Invalid portable executable header {portableExecutableMagic}."); + } + + reader.BaseStream.Position += 0x14; + + switch(reader.ReadUInt16()) + { + case 0x10b: + reader.BaseStream.Position += 0x5E; + break; + case 0x20b: + reader.BaseStream.Position += 0x6E; + break; + + default: + throw new InvalidOperationException("Portable executable header not supported"); + } + + reader.BaseStream.Position += (index * 8); + + var rva = reader.ReadUInt32(); + var size = reader.ReadUInt32(); + + reader.Close(); + + return new DataDirectory(rva, size); + } + } + + private static IntPtr GetAddressFromExportTable(byte[] exportTable, uint exportTableRva, string functionName) + { + using (var reader = new BinaryReader(new MemoryStream(exportTable))) + { + reader.BaseStream.Position = 0x10; + + var ordinalBase = reader.ReadInt32(); + var addressTableEntryCount = reader.ReadUInt32(); + var namePointerTableEntryCount = reader.ReadUInt32(); + var exportAddressTableRva = reader.ReadUInt32() - exportTableRva; + var exportNamePointerTableRva = reader.ReadUInt32() - exportTableRva; + var ordinalTableRva = reader.ReadUInt32() - exportTableRva; + + reader.BaseStream.Position = exportNamePointerTableRva; + + var functionAddress = IntPtr.Zero; + + for(int x = 0; x < namePointerTableEntryCount; ++x) + { + reader.BaseStream.Position = exportNamePointerTableRva + (x * 4); + + var nameRva = reader.ReadUInt32(); + + if(nameRva == 0) + { + continue; + } + + reader.BaseStream.Position = nameRva - exportTableRva; + + if(functionName == ReadAsciiString(reader)) + { + reader.BaseStream.Position = ordinalTableRva + (x * 2); + var ordinal = reader.ReadUInt16(); + + if(ordinal >= addressTableEntryCount) + { + throw new Win32Exception("Invalid function export table"); + } + + reader.BaseStream.Position = exportAddressTableRva + (ordinal * 4); + + functionAddress = new IntPtr(reader.ReadUInt32()); + } + } + + return functionAddress; + } + + } + private static string ReadAsciiString(BinaryReader reader) + { + var stringBuilder = new StringBuilder(); + + char character = '\0'; + while((character = reader.ReadChar()) != '\0') + { + stringBuilder.Append(character); + } + + return stringBuilder.ToString(); + } + + internal struct DataDirectory + { + internal readonly uint Rva; + internal readonly uint Size; + + internal DataDirectory(uint rva, uint size) + { + Rva = rva; + Size = size; + } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource reader of type System.IO.BinaryReader, Leaked resource (output of System.IO.MemoryStream::.ctor() at Line 199) of type System.IO.MemoryStream in method "IntPtr ThreadHelper.GetAddressFromExportTable(Byte[],UInt32,String)". + +### Severity: +ERROR + +### Procedure: +IntPtr ThreadHelper.GetAddressFromExportTable(Byte[],UInt32,String) + +### File: +src/CoreHook.Memory/ThreadHelper.Windows.cs + +### Key: +ThreadHelper.Windows.cs|GetAddressFromExportTable|DOTNET_RESOURCE_LEAK + +### Hash: +55e54628e8e5947aad7fcb9c0209dac3 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0798/instruction.md b/inferredbugs-0798/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ac55cef89f08d165b7a143df85d8910211b3b020 --- /dev/null +++ b/inferredbugs-0798/instruction.md @@ -0,0 +1,193 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** EntityFrameworkCore.Taos +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using ConsoleTableExt; +using Maikebing.Data.Taos; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Linq; +using System.Threading; + +namespace TaosADODemo +{ + class Program + { + static void Main(string[] args) + { + System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); + DbProviderFactories.RegisterFactory("TDengine", TaosFactory .Instance); + ///Specify the name of the database + string database = "db_" + DateTime.Now.ToString("yyyyMMddHHmmss"); + var builder = new TaosConnectionStringBuilder() + { + DataSource = "taos", + DataBase = database, + Username = "root", + Password = "taosdata", + Port = 6030 + + }; + //Example for ADO.Net + using (var connection = new TaosConnection(builder.ConnectionString)) + { + connection.Open(); + Console.WriteLine("ServerVersion:{0}", connection.ServerVersion); + Console.WriteLine("create {0} {1}", database, connection.CreateCommand($"create database {database};").ExecuteNonQuery()); + Console.WriteLine("create table t {0} {1}", database, connection.CreateCommand($"create table {database}.t (ts timestamp, cdata int);").ExecuteNonQuery()); + Console.WriteLine("insert into t values {0} ", connection.CreateCommand($"insert into {database}.t values ({(long)(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds)}, 10);").ExecuteNonQuery()); + var pmcmd = connection.CreateCommand($"insert into {database}.t values (@t, @c);"); + Thread.Sleep(TimeSpan.FromSeconds(1)); + pmcmd.Parameters.AddWithValue("@t", (long)(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds)); + pmcmd.Parameters.AddWithValue("@c", 1111); + pmcmd.ExecuteNonQuery(); + Console.WriteLine("insert into t values {0} ", connection.CreateCommand($"insert into {database}.t values ({(long)(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds)}, 10);").ExecuteNonQuery()); + + //Console.WriteLine("insert into t values {0} ", connection.CreateCommand($"insert into {database}.t values ({(long)(DateTime.Now.AddMonths(1).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds)}, 20);").ExecuteNonQuery()); + var cmd_select = connection.CreateCommand(); + cmd_select.CommandText = $"select * from {database}.t;"; + var reader = cmd_select.ExecuteReader(); + + int index =reader.GetOrdinal("cdata"); + if (reader.Read()) + { + var ts = reader.GetDateTime("ts"); + } + Console.WriteLine($"cdata index at {index}"); + Console.WriteLine(cmd_select.CommandText); + Console.WriteLine(""); + ConsoleTableBuilder.From(reader.ToDataTable()).WithFormat(ConsoleTableBuilderFormat.MarkDown).ExportAndWriteLine(); + + + Console.WriteLine(""); + connection.CreateCommand($"CREATE TABLE datas ('reportTime' timestamp, type int, 'bufferedEnd' bool, address nchar(64), parameter nchar(64), value nchar(64)) TAGS ('boxCode' nchar(64), 'machineId' int);").ExecuteNonQuery(); + connection.CreateCommand($"INSERT INTO data_history_67 USING datas TAGS (mongo, 67) values ( 1608173534840 2 false 'Channel1.窑.烟囱温度' '烟囱温度' '122.00' );").ExecuteNonQuery(); + var cmd_datas = connection.CreateCommand(); + cmd_datas.CommandText = $"SELECT reportTime,type,bufferedEnd,address,parameter,value FROM {database}.data_history_67 LIMIT 100"; + var readerdatas = cmd_datas.ExecuteReader(); + Console.WriteLine(cmd_datas.CommandText); + Console.WriteLine(""); + ConsoleTableBuilder.From(readerdatas.ToDataTable()).WithFormat(ConsoleTableBuilderFormat.Default).ExportAndWriteLine(); + Console.WriteLine(""); + + Console.WriteLine("CREATE TABLE meters ", connection.CreateCommand($"CREATE TABLE meters (ts timestamp, current float, voltage int, phase float) TAGS (location binary(64), groupdId int);").ExecuteNonQuery()); + Console.WriteLine("CREATE TABLE d1001 ", connection.CreateCommand($"CREATE TABLE d1001 USING meters TAGS (\"Beijing.Chaoyang\", 2);").ExecuteNonQuery()); + Console.WriteLine("INSERT INTO d1001 ", connection.CreateCommand($"INSERT INTO d1001 USING METERS TAGS(\"Beijng.Chaoyang\", 2) VALUES(now, 10.2, 219, 0.32);").ExecuteNonQuery()); + Console.WriteLine("DROP TABLE {0} {1}", database, connection.CreateCommand($"DROP TABLE {database}.t;").ExecuteNonQuery()); + Console.WriteLine("DROP DATABASE {0} {1}", database, connection.CreateCommand($"DROP DATABASE {database};").ExecuteNonQuery()); + connection.CreateCommand("DROP DATABASE IF EXISTS IoTSharp").ExecuteNonQuery(); + connection.CreateCommand("CREATE DATABASE IoTSharp KEEP 365 DAYS 10 BLOCKS 4;").ExecuteNonQuery(); + connection.ChangeDatabase("IoTSharp"); + connection.CreateCommand("CREATE STABLE IF NOT EXISTS telemetrydata (ts timestamp,value_type tinyint, value_boolean bool, value_string binary(10240), value_long bigint,value_datetime timestamp,value_double double) TAGS (deviceid binary(32),keyname binary(64));").ExecuteNonQuery(); + //connection.CreateCommand($"CREATE TABLE dev_Thermometer USING telemetrydata TAGS (\"Temperature\")").ExecuteNonQuery(); + var devid = $"{Guid.NewGuid():N}"; + UploadTelemetryData(connection, devid, "Temperature", 999); + UploadTelemetryData(connection,devid, "Humidity", 888); + var devid2 = $"{Guid.NewGuid():N}"; + UploadTelemetryData(connection, devid2, "Temperature", 777); + UploadTelemetryData(connection, devid2, "Humidity", 666); + var reader2 = connection.CreateCommand("select last_row(*) from telemetrydata group by deviceid,keyname ;").ExecuteReader(); + ConsoleTableBuilder.From(reader2.ToDataTable()).WithFormat(ConsoleTableBuilderFormat.Default).ExportAndWriteLine(); + + Console.WriteLine("DROP DATABASE IoTSharp", database, connection.CreateCommand($"DROP DATABASE IoTSharp;").ExecuteNonQuery()); + + connection.Close(); + + + } + //Example for Entity Framework Core + using (var context = new TaosContext(new DbContextOptionsBuilder() + .UseTaos(builder.ConnectionString).Options)) + { + Console.WriteLine("EnsureCreated"); + context.Database.EnsureCreated(); + for (int i = 0; i < 10; i++) + { + var rd = new Random(); + context.sensor.Add(new sensor() { ts = DateTime.Now.AddMilliseconds(i + 10), degree = rd.NextDouble(), pm25 = rd.Next(0, 1000) }); + Thread.Sleep(10); + } + Console.WriteLine("Saveing"); + context.SaveChanges(); + Console.WriteLine(""); + Console.WriteLine("from s in context.sensor where s.pm25 > 0 select s "); + Console.WriteLine(""); + var f = from s in context.sensor where s.pm25 > 0 select s; + var ary = f.ToArray(); + if (ary.Any()) + { + ConsoleTableBuilder.From(ary.ToList()).WithFormat(ConsoleTableBuilderFormat.MarkDown).ExportAndWriteLine(); + } + context.Database.EnsureDeleted(); + } + + + } + + static void UploadTelemetryData( TaosConnection connection, string devid, string keyname, int count) + { + for (int i = 0; i < count; i++) + { + connection.CreateCommand($"INSERT INTO device_{devid}_{keyname} USING telemetrydata TAGS(\"{devid}\",\"{keyname}\") values (now,2,true,'{i}',{i},now,{i});").ExecuteNonQuery(); + } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource pmcmd of type Maikebing.Data.Taos.TaosCommand, Leaked resource cmd_select of type Maikebing.Data.Taos.TaosCommand, Leaked resource cmd_datas of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 91) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from System.Data.DataTable Maikebing.Data.Taos.DataReaderExtensions::ToDataTable(System.Data.IDataReader) at Line 89) of type System.Data.DataTable, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 88) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 80) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 78) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 77) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 76) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 75) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 74) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 73) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 72) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from System.Data.DataTable Maikebing.Data.Taos.DataReaderExtensions::ToDataTable(System.Data.IDataReader) at Line 69) of type System.Data.DataTable, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 63) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 62) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from System.Data.DataTable Maikebing.Data.Taos.DataReaderExtensions::ToDataTable(System.Data.IDataReader) at Line 58) of type System.Data.DataTable, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 43) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 37) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 36) of type Maikebing.Data.Taos.TaosCommand, Leaked resource (returned from Maikebing.Data.Taos.TaosCommand Maikebing.Data.Taos.TaosConnection::CreateCommand(System.String) at Line 35) of type Maikebing.Data.Taos.TaosCommand in method "Void Program.Main(String[])". + +### Severity: +ERROR + +### Procedure: +Void Program.Main(String[]) + +### File: +src/Example/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +51d21d60492b1eb992c100a2cfa85e63 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0818/instruction.md b/inferredbugs-0818/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c8721fe63a79747b78a85a67b3b29b8609a3fd32 --- /dev/null +++ b/inferredbugs-0818/instruction.md @@ -0,0 +1,97 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** rush +**Bug ID:** 5 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// Copyright (c) Shane Woolcock. Licensed under the MIT Licence. +// See the LICENCE file in the repository root for full licence text. + +using osu.Framework.Allocation; +using osu.Framework.Graphics; +using osu.Game.Overlays.Settings; +using osu.Game.Rulesets.Rush.Configuration; + +namespace osu.Game.Rulesets.Rush.UI +{ + public class RushSettingsSubsection : RulesetSettingsSubsection + { + private readonly Ruleset ruleset; + + protected override string Header => ruleset.Description; + + public RushSettingsSubsection(Ruleset ruleset) + : base(ruleset) + { + this.ruleset = ruleset; + } + + [BackgroundDependencyLoader] + private void load() + { + var config = (RushRulesetConfigManager)Config; + + Children = new Drawable[] + { + new SettingsCheckbox + { + LabelText = "Automatic Fever activation", + Current = config.GetBindable(RushRulesetSettings.AutomaticFever) + }, + }; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource n$4.[_] of type osu.Game.Overlays.Settings.SettingsCheckbox in method "Void RushSettingsSubsection.load()". + +### Severity: +ERROR + +### Procedure: +Void RushSettingsSubsection.load() + +### File: +osu.Game.Rulesets.Rush/UI/RushSettingsSubsection.cs + +### Key: +RushSettingsSubsection.cs|load|DOTNET_RESOURCE_LEAK + +### Hash: +814bd62c0a5e82f01ab8db79cfc2dfda + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0820/instruction.md b/inferredbugs-0820/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1f78b48f05ae4fe43a68ceee8aa9248e288ef169 --- /dev/null +++ b/inferredbugs-0820/instruction.md @@ -0,0 +1,792 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Reflexil +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// +// Mono.CSharp.Debugger/MonoSymbolFile.cs +// +// Author: +// Martin Baulig (martin@ximian.com) +// +// (C) 2003 Ximian, Inc. http://www.ximian.com +// + +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +using System; +using System.Reflection; +using SRE = System.Reflection.Emit; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.IO; + +namespace Mono.CompilerServices.SymbolWriter +{ + public class MonoSymbolFileException : Exception + { + public MonoSymbolFileException () + : base () + { } + + public MonoSymbolFileException (string message, params object[] args) + : base (String.Format (message, args)) + { } + } + + internal class MyBinaryWriter : BinaryWriter + { + public MyBinaryWriter (Stream stream) + : base (stream) + { } + + public void WriteLeb128 (int value) + { + base.Write7BitEncodedInt (value); + } + } + + internal class MyBinaryReader : BinaryReader + { + public MyBinaryReader (Stream stream) + : base (stream) + { } + + public int ReadLeb128 () + { + return base.Read7BitEncodedInt (); + } + + public string ReadString (int offset) + { + long old_pos = BaseStream.Position; + BaseStream.Position = offset; + + string text = ReadString (); + + BaseStream.Position = old_pos; + return text; + } + } + + public interface ISourceFile + { + SourceFileEntry Entry { + get; + } + } + + public interface ICompileUnit + { + CompileUnitEntry Entry { + get; + } + } + + public interface IMethodDef + { + string Name { + get; + } + + int Token { + get; + } + } + +#if !CECIL + internal class MonoDebuggerSupport + { + static GetMethodTokenFunc get_method_token; + static GetGuidFunc get_guid; + static GetLocalIndexFunc get_local_index; + + delegate int GetMethodTokenFunc (MethodBase method); + delegate Guid GetGuidFunc (Module module); + delegate int GetLocalIndexFunc (SRE.LocalBuilder local); + + static Delegate create_delegate (Type type, Type delegate_type, string name) + { + MethodInfo mi = type.GetMethod (name, BindingFlags.Static | + BindingFlags.NonPublic); + if (mi == null) + throw new Exception ("Can't find " + name); + + return Delegate.CreateDelegate (delegate_type, mi); + } + + static MonoDebuggerSupport () + { + get_method_token = (GetMethodTokenFunc) create_delegate ( + typeof (Assembly), typeof (GetMethodTokenFunc), + "MonoDebugger_GetMethodToken"); + + get_guid = (GetGuidFunc) create_delegate ( + typeof (Module), typeof (GetGuidFunc), "Mono_GetGuid"); + + get_local_index = (GetLocalIndexFunc) create_delegate ( + typeof (SRE.LocalBuilder), typeof (GetLocalIndexFunc), + "Mono_GetLocalIndex"); + } + + public static int GetMethodToken (MethodBase method) + { + return get_method_token (method); + } + + public static Guid GetGuid (Module module) + { + return get_guid (module); + } + + public static int GetLocalIndex (SRE.LocalBuilder local) + { + return get_local_index (local); + } + } +#endif + + public class MonoSymbolFile : IDisposable + { + List methods = new List (); + List sources = new List (); + List comp_units = new List (); + Dictionary type_hash = new Dictionary (); + Dictionary anonymous_scopes; + + OffsetTable ot; + int last_type_index; + int last_method_index; + int last_namespace_index; + + public readonly string FileName = ""; + public readonly int MajorVersion = OffsetTable.MajorVersion; + public readonly int MinorVersion = OffsetTable.MinorVersion; + + public int NumLineNumbers; + + internal MonoSymbolFile () + { + ot = new OffsetTable (); + } + + internal int AddSource (SourceFileEntry source) + { + sources.Add (source); + return sources.Count; + } + + internal int AddCompileUnit (CompileUnitEntry entry) + { + comp_units.Add (entry); + return comp_units.Count; + } + + internal int DefineType (Type type) + { + int index; + if (type_hash.TryGetValue (type, out index)) + return index; + + index = ++last_type_index; + type_hash.Add (type, index); + return index; + } + + internal void AddMethod (MethodEntry entry) + { + methods.Add (entry); + } + + public MethodEntry DefineMethod (CompileUnitEntry comp_unit, int token, + ScopeVariable[] scope_vars, LocalVariableEntry[] locals, + LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, + string real_name, MethodEntry.Flags flags, + int namespace_id) + { + if (reader != null) + throw new InvalidOperationException (); + + MethodEntry method = new MethodEntry ( + this, comp_unit, token, scope_vars, locals, lines, code_blocks, + real_name, flags, namespace_id); + AddMethod (method); + return method; + } + + internal void DefineAnonymousScope (int id) + { + if (reader != null) + throw new InvalidOperationException (); + + if (anonymous_scopes == null) + anonymous_scopes = new Dictionary (); + + anonymous_scopes.Add (id, new AnonymousScopeEntry (id)); + } + + internal void DefineCapturedVariable (int scope_id, string name, string captured_name, + CapturedVariable.CapturedKind kind) + { + if (reader != null) + throw new InvalidOperationException (); + + AnonymousScopeEntry scope = anonymous_scopes [scope_id]; + scope.AddCapturedVariable (name, captured_name, kind); + } + + internal void DefineCapturedScope (int scope_id, int id, string captured_name) + { + if (reader != null) + throw new InvalidOperationException (); + + AnonymousScopeEntry scope = anonymous_scopes [scope_id]; + scope.AddCapturedScope (id, captured_name); + } + + internal int GetNextTypeIndex () + { + return ++last_type_index; + } + + internal int GetNextMethodIndex () + { + return ++last_method_index; + } + + internal int GetNextNamespaceIndex () + { + return ++last_namespace_index; + } + + void Write (MyBinaryWriter bw, Guid guid) + { + // Magic number and file version. + bw.Write (OffsetTable.Magic); + bw.Write (MajorVersion); + bw.Write (MinorVersion); + + bw.Write (guid.ToByteArray ()); + + // + // Offsets of file sections; we must write this after we're done + // writing the whole file, so we just reserve the space for it here. + // + long offset_table_offset = bw.BaseStream.Position; + ot.Write (bw, MajorVersion, MinorVersion); + + // + // Sort the methods according to their tokens and update their index. + // + methods.Sort (); + for (int i = 0; i < methods.Count; i++) + ((MethodEntry) methods [i]).Index = i + 1; + + // + // Write data sections. + // + ot.DataSectionOffset = (int) bw.BaseStream.Position; + foreach (SourceFileEntry source in sources) + source.WriteData (bw); + foreach (CompileUnitEntry comp_unit in comp_units) + comp_unit.WriteData (bw); + foreach (MethodEntry method in methods) + method.WriteData (this, bw); + ot.DataSectionSize = (int) bw.BaseStream.Position - ot.DataSectionOffset; + + // + // Write the method index table. + // + ot.MethodTableOffset = (int) bw.BaseStream.Position; + for (int i = 0; i < methods.Count; i++) { + MethodEntry entry = (MethodEntry) methods [i]; + entry.Write (bw); + } + ot.MethodTableSize = (int) bw.BaseStream.Position - ot.MethodTableOffset; + + // + // Write source table. + // + ot.SourceTableOffset = (int) bw.BaseStream.Position; + for (int i = 0; i < sources.Count; i++) { + SourceFileEntry source = (SourceFileEntry) sources [i]; + source.Write (bw); + } + ot.SourceTableSize = (int) bw.BaseStream.Position - ot.SourceTableOffset; + + // + // Write compilation unit table. + // + ot.CompileUnitTableOffset = (int) bw.BaseStream.Position; + for (int i = 0; i < comp_units.Count; i++) { + CompileUnitEntry unit = (CompileUnitEntry) comp_units [i]; + unit.Write (bw); + } + ot.CompileUnitTableSize = (int) bw.BaseStream.Position - ot.CompileUnitTableOffset; + + // + // Write anonymous scope table. + // + ot.AnonymousScopeCount = anonymous_scopes != null ? anonymous_scopes.Count : 0; + ot.AnonymousScopeTableOffset = (int) bw.BaseStream.Position; + if (anonymous_scopes != null) { + foreach (AnonymousScopeEntry scope in anonymous_scopes.Values) + scope.Write (bw); + } + ot.AnonymousScopeTableSize = (int) bw.BaseStream.Position - ot.AnonymousScopeTableOffset; + + // + // Fixup offset table. + // + ot.TypeCount = last_type_index; + ot.MethodCount = methods.Count; + ot.SourceCount = sources.Count; + ot.CompileUnitCount = comp_units.Count; + + // + // Write offset table. + // + ot.TotalFileSize = (int) bw.BaseStream.Position; + bw.Seek ((int) offset_table_offset, SeekOrigin.Begin); + ot.Write (bw, MajorVersion, MinorVersion); + bw.Seek (0, SeekOrigin.End); + +#if false + Console.WriteLine ("TOTAL: {0} line numbes, {1} bytes, extended {2} bytes, " + + "{3} methods.", NumLineNumbers, LineNumberSize, + ExtendedLineNumberSize, methods.Count); +#endif + } + + public void CreateSymbolFile (Guid guid, FileStream fs) + { + if (reader != null) + throw new InvalidOperationException (); + + Write (new MyBinaryWriter (fs), guid); + } + + MyBinaryReader reader; + Dictionary source_file_hash; + Dictionary compile_unit_hash; + + List method_list; + Dictionary method_token_hash; + Dictionary source_name_hash; + + Guid guid; + + MonoSymbolFile (string filename) + { + this.FileName = filename; + FileStream stream = new FileStream (filename, FileMode.Open, FileAccess.Read); + reader = new MyBinaryReader (stream); + + try { + long magic = reader.ReadInt64 (); + int major_version = reader.ReadInt32 (); + int minor_version = reader.ReadInt32 (); + + if (magic != OffsetTable.Magic) + throw new MonoSymbolFileException ( + "Symbol file `{0}' is not a valid " + + "Mono symbol file", filename); + if (major_version != OffsetTable.MajorVersion) + throw new MonoSymbolFileException ( + "Symbol file `{0}' has version {1}, " + + "but expected {2}", filename, major_version, + OffsetTable.MajorVersion); + if (minor_version != OffsetTable.MinorVersion) + throw new MonoSymbolFileException ( + "Symbol file `{0}' has version {1}.{2}, " + + "but expected {3}.{4}", filename, major_version, + minor_version, OffsetTable.MajorVersion, + OffsetTable.MinorVersion); + + MajorVersion = major_version; + MinorVersion = minor_version; + guid = new Guid (reader.ReadBytes (16)); + + ot = new OffsetTable (reader, major_version, minor_version); + } catch { + throw new MonoSymbolFileException ( + "Cannot read symbol file `{0}'", filename); + } + + source_file_hash = new Dictionary (); + compile_unit_hash = new Dictionary (); + } + + void CheckGuidMatch (Guid other, string filename, string assembly) + { + if (other == guid) + return; + + throw new MonoSymbolFileException ( + "Symbol file `{0}' does not match assembly `{1}'", + filename, assembly); + } + +#if CECIL + protected MonoSymbolFile (string filename, Mono.Cecil.ModuleDefinition module) + : this (filename) + { + CheckGuidMatch (module.Mvid, filename, module.FullyQualifiedName); + } + + public static MonoSymbolFile ReadSymbolFile (Mono.Cecil.ModuleDefinition module) + { + return ReadSymbolFile (module, module.FullyQualifiedName); + } + + public static MonoSymbolFile ReadSymbolFile (Mono.Cecil.ModuleDefinition module, string filename) + { + string name = filename + ".mdb"; + + return new MonoSymbolFile (name, module); + } +#else + protected MonoSymbolFile (string filename, Assembly assembly) : this (filename) + { + // Check that the MDB file matches the assembly, if we have been + // passed an assembly. + if (assembly == null) + return; + + Module[] modules = assembly.GetModules (); + Guid assembly_guid = MonoDebuggerSupport.GetGuid (modules [0]); + + CheckGuidMatch (assembly_guid, filename, assembly.Location); + } + + public static MonoSymbolFile ReadSymbolFile (Assembly assembly) + { + string filename = assembly.Location; + string name = filename + ".mdb"; + + return new MonoSymbolFile (name, assembly); + } +#endif + + public static MonoSymbolFile ReadSymbolFile (string mdbFilename) + { + return new MonoSymbolFile (mdbFilename, null); + } + + public int CompileUnitCount { + get { return ot.CompileUnitCount; } + } + + public int SourceCount { + get { return ot.SourceCount; } + } + + public int MethodCount { + get { return ot.MethodCount; } + } + + public int TypeCount { + get { return ot.TypeCount; } + } + + public int AnonymousScopeCount { + get { return ot.AnonymousScopeCount; } + } + + public int NamespaceCount { + get { return last_namespace_index; } + } + + public Guid Guid { + get { return guid; } + } + + public OffsetTable OffsetTable { + get { return ot; } + } + + internal int LineNumberCount = 0; + internal int LocalCount = 0; + internal int StringSize = 0; + + internal int LineNumberSize = 0; + internal int ExtendedLineNumberSize = 0; + + public SourceFileEntry GetSourceFile (int index) + { + if ((index < 1) || (index > ot.SourceCount)) + throw new ArgumentException (); + if (reader == null) + throw new InvalidOperationException (); + + lock (this) { + SourceFileEntry source; + if (source_file_hash.TryGetValue (index, out source)) + return source; + + long old_pos = reader.BaseStream.Position; + + reader.BaseStream.Position = ot.SourceTableOffset + + SourceFileEntry.Size * (index - 1); + source = new SourceFileEntry (this, reader); + source_file_hash.Add (index, source); + + reader.BaseStream.Position = old_pos; + return source; + } + } + + public SourceFileEntry[] Sources { + get { + if (reader == null) + throw new InvalidOperationException (); + + SourceFileEntry[] retval = new SourceFileEntry [SourceCount]; + for (int i = 0; i < SourceCount; i++) + retval [i] = GetSourceFile (i + 1); + return retval; + } + } + + public CompileUnitEntry GetCompileUnit (int index) + { + if ((index < 1) || (index > ot.CompileUnitCount)) + throw new ArgumentException (); + if (reader == null) + throw new InvalidOperationException (); + + lock (this) { + CompileUnitEntry unit; + if (compile_unit_hash.TryGetValue (index, out unit)) + return unit; + + long old_pos = reader.BaseStream.Position; + + reader.BaseStream.Position = ot.CompileUnitTableOffset + + CompileUnitEntry.Size * (index - 1); + unit = new CompileUnitEntry (this, reader); + compile_unit_hash.Add (index, unit); + + reader.BaseStream.Position = old_pos; + return unit; + } + } + + public CompileUnitEntry[] CompileUnits { + get { + if (reader == null) + throw new InvalidOperationException (); + + CompileUnitEntry[] retval = new CompileUnitEntry [CompileUnitCount]; + for (int i = 0; i < CompileUnitCount; i++) + retval [i] = GetCompileUnit (i + 1); + return retval; + } + } + + void read_methods () + { + lock (this) { + if (method_token_hash != null) + return; + + method_token_hash = new Dictionary (); + method_list = new List (); + + long old_pos = reader.BaseStream.Position; + reader.BaseStream.Position = ot.MethodTableOffset; + + for (int i = 0; i < MethodCount; i++) { + MethodEntry entry = new MethodEntry (this, reader, i + 1); + method_token_hash.Add (entry.Token, entry); + method_list.Add (entry); + } + + reader.BaseStream.Position = old_pos; + } + } + + public MethodEntry GetMethodByToken (int token) + { + if (reader == null) + throw new InvalidOperationException (); + + lock (this) { + read_methods (); + MethodEntry me; + method_token_hash.TryGetValue (token, out me); + return me; + } + } + + public MethodEntry GetMethod (int index) + { + if ((index < 1) || (index > ot.MethodCount)) + throw new ArgumentException (); + if (reader == null) + throw new InvalidOperationException (); + + lock (this) { + read_methods (); + return (MethodEntry) method_list [index - 1]; + } + } + + public MethodEntry[] Methods { + get { + if (reader == null) + throw new InvalidOperationException (); + + lock (this) { + read_methods (); + MethodEntry[] retval = new MethodEntry [MethodCount]; + method_list.CopyTo (retval, 0); + return retval; + } + } + } + + public int FindSource (string file_name) + { + if (reader == null) + throw new InvalidOperationException (); + + lock (this) { + if (source_name_hash == null) { + source_name_hash = new Dictionary (); + + for (int i = 0; i < ot.SourceCount; i++) { + SourceFileEntry source = GetSourceFile (i + 1); + source_name_hash.Add (source.FileName, i); + } + } + + int value; + if (!source_name_hash.TryGetValue (file_name, out value)) + return -1; + return value; + } + } + + public AnonymousScopeEntry GetAnonymousScope (int id) + { + if (reader == null) + throw new InvalidOperationException (); + + AnonymousScopeEntry scope; + lock (this) { + if (anonymous_scopes != null) { + anonymous_scopes.TryGetValue (id, out scope); + return scope; + } + + anonymous_scopes = new Dictionary (); + reader.BaseStream.Position = ot.AnonymousScopeTableOffset; + for (int i = 0; i < ot.AnonymousScopeCount; i++) { + scope = new AnonymousScopeEntry (reader); + anonymous_scopes.Add (scope.ID, scope); + } + + return anonymous_scopes [id]; + } + } + + internal MyBinaryReader BinaryReader { + get { + if (reader == null) + throw new InvalidOperationException (); + + return reader; + } + } + + public void Dispose () + { + Dispose (true); + } + + protected virtual void Dispose (bool disposing) + { + if (disposing) { + if (reader != null) { + reader.Close (); + reader = null; + } + } + } + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +null (last assigned on line 488) is dereferenced in call to `MonoSymbolFile(...)`. + +### Severity: +ERROR + +### Procedure: +MonoSymbolFile MonoSymbolFile.ReadSymbolFile(String) + +### File: +Libs/Sources/Mono.Cecil.Mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolFile.cs + +### Key: +MonoSymbolFile.cs|ReadSymbolFile|NULLPTR_DEREFERENCE + +### Hash: +44e552d6dbc8718851ad00e0ec6c5089 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0827/instruction.md b/inferredbugs-0827/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ceca15f6628712c0f9cf53a50df1862b1cf25512 --- /dev/null +++ b/inferredbugs-0827/instruction.md @@ -0,0 +1,86 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** DotnetCrawler +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using DotnetCrawler.Core; +using DotnetCrawler.Data.Models; +using DotnetCrawler.Downloader; +using DotnetCrawler.Pipeline; +using DotnetCrawler.Processor; +using DotnetCrawler.Request; +using System; +using System.Linq; + +namespace DotnetCrawler.Sample +{ + class Program + { + static void Main(string[] args) + { + const string CrawleUrl = "https://www.ebay.com/b/Apple-iPhone/9355/bn_319682"; + + var crawler = new DotnetCrawler() + .AddRequest(new DotnetCrawlerRequest { Url = CrawleUrl, Regex = @".*itm/.+", TimeOut = 5000 }) + .AddDownloader(new DotnetCrawlerDownloader { DownloderType = DotnetCrawlerDownloaderType.FromMemory, DownloadPath = @"C:\DotnetCrawlercrawler\" }) + .AddProcessor(new DotnetCrawlerProcessor { }) + .AddPipeline(new DotnetCrawlerPipeline { }); + + await crawler.Crawle(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource context of type Microsoft.EntityFrameworkCore.DbContext in method "Void Program.Main(String[])". + +### Severity: +ERROR + +### Procedure: +Void Program.Main(String[]) + +### File: +DotnetCrawler.Sample/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +0bf5eb4ad68956c42c8ed298d20462a6 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0901/instruction.md b/inferredbugs-0901/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..880dbb747ce405b4c144f537fb74f4c7407af399 --- /dev/null +++ b/inferredbugs-0901/instruction.md @@ -0,0 +1,992 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** VirusTotalNet +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Sockets; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using VirusTotalNET.Exceptions; +using VirusTotalNET.Results; + +namespace VirusTotalNET +{ + public class VirusTotal + { + private readonly HttpClient _client; + private bool _useTls; + private readonly HttpClientHandler _httpClientHandler; + private readonly Dictionary _defaultValues; + private readonly JsonSerializer _serializer; + + /// + /// Public constructor for VirusTotal. + /// + /// The API key you got from Virus Total + /// + public VirusTotal(string apiKey) + { + if (string.IsNullOrEmpty(apiKey) || apiKey.Length < 64) + throw new ArgumentException("You have to set an API key.", nameof(apiKey)); + + _defaultValues = new Dictionary(); + _defaultValues.Add("apikey", apiKey); + + _httpClientHandler = new HttpClientHandler(); + _httpClientHandler.AllowAutoRedirect = false; + + _serializer = JsonSerializer.Create(); + + _client = new HttpClient(_httpClientHandler); + + ApiUrl = "www.virustotal.com/vtapi/v2/"; + + FileSizeLimit = 33553369; //32 MB - 1063 = 33553369 it is the effective limit by virus total + RestrictSizeLimits = true; + RestrictNumberOfResources = true; + DumpRawJSON = false; + DumpFolder = "%TEMP%"; + } + + internal VirusTotal(string apiKey, JsonSerializerSettings settings) : this(apiKey) + { + _serializer = JsonSerializer.Create(settings); + } + + /// + /// Dumps the raw JSON from VirusTotal into the folder specified in "DumpFolder". For debug purposes only. + /// Defaults to false. + /// + public bool DumpRawJSON { get; set; } + + /// + /// When DumpRawJSON is set to true, it dumps the raw JSON files to this folder. The files are named [DateTimeInUTC]-[RandomGUID].json + /// Defaults to %TEMP% + /// + public string DumpFolder { get; set; } + + /// + /// When true, we check the file size before uploading it to Virus Total. The file size restrictions are based on the Virusl Total public API 2.0 documentation. + /// + public bool RestrictSizeLimits { get; set; } + + /// + /// When true, we check the number of resources that are submitted to Virus Total. The limits are according to Virus Total public API 2.0 documentation. + /// + public bool RestrictNumberOfResources { get; set; } + + /// + /// The maximum file size (in bytes) that the Virus Total public API 2.0 supports. + /// + public long FileSizeLimit { get; set; } + + /// + /// Set to false to use HTTP instead of HTTPS. HTTPS is used by default. + /// + public bool UseTLS + { + get { return _useTls; } + set + { + _useTls = value; + + string oldUrl = ApiUrl; + + if (string.IsNullOrWhiteSpace(oldUrl)) + return; + + if (oldUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + oldUrl = oldUrl.Substring(8); + else if (oldUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) + oldUrl = oldUrl.Substring(7); + + _client.BaseAddress = _useTls ? new Uri("https://" + oldUrl) : new Uri("http://" + oldUrl); + } + } + + public string UserAgent { get { return _client.DefaultRequestHeaders.UserAgent.ToString(); } set { _client.DefaultRequestHeaders.Add("User-Agent", value); } } + + /// + /// Get or set the proxy. + /// + public IWebProxy Proxy { get { return _httpClientHandler.Proxy; } set { _httpClientHandler.Proxy = value; } } + + /// + /// Get or set the timeout. + /// + public TimeSpan Timeout { get { return _client.Timeout; } set { _client.Timeout = value; } } + + /// + /// The URL which the Virus Total service listens on. IF you don't set the scheme to http:// or https:// it will default to https. + /// + public string ApiUrl + { + get { return _client.BaseAddress.ToString(); } + set + { + string newUrl = value.Trim(); + + if (string.IsNullOrWhiteSpace(newUrl)) + return; + + if (newUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + { + _useTls = true; + newUrl = newUrl.Substring(8); + } + else if (newUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) + { + _useTls = false; + newUrl = newUrl.Substring(7); + } + else + _useTls = true; + + _client.BaseAddress = _useTls ? new Uri("https://" + newUrl) : new Uri("http://" + newUrl); + } + } + + /// + /// Scan a file. + /// Note: It is highly encouraged to get the report of the file before scanning, in case it has already been scanned before. + /// + /// The file to scan + /// The scan results. + public Task ScanFile(FileInfo file) + { + if (!file.Exists) + throw new FileNotFoundException("The file was not found.", file.Name); + + return ScanFile(file.OpenRead(), file.Name); + } + + /// + /// Scan a file. + /// Note: It is highly encouraged to get the report of the file before scanning, in case it has already been scanned before. + /// Note: You are also strongly encouraged to provide the filename as it is rich metadata for the Virus Total database. + /// + /// The file to scan + /// The filename of the file + /// The scan results. + public Task ScanFile(byte[] file, string filename) + { + return ScanFile(new MemoryStream(file), filename); + } + + /// + /// Scan a file. + /// Note: It is highly encouraged to get the report of the file before scanning, in case it has already been scanned before. + /// Note: You are also strongly encouraged to provide the filename as it is rich metadata for the Virus Total database. + /// + /// The file to scan + /// The filename of the file + /// The scan results. + public Task ScanFile(Stream fileStream, string filename) + { + if (fileStream == null || fileStream.Length <= 0) + throw new ArgumentException("You must provide a file", nameof(fileStream)); + + if (RestrictSizeLimits && fileStream.Length > FileSizeLimit) + throw new SizeLimitException(string.Format("The filesize limit on VirusTotal is {0} KB. Your file is {1} KB", FileSizeLimit / 1024, fileStream.Length / 1024)); + + if (string.IsNullOrWhiteSpace(filename)) + throw new ArgumentException("You must provide a filename. Preferably the original filename."); + + MultipartFormDataContent multi = new MultipartFormDataContent(); + multi.Add(CreateApiPart()); + multi.Add(CreateFileContent(fileStream, filename, "application/octet-stream")); + + //https://www.virustotal.com/vtapi/v2/file/scan + return GetResult("file/scan", HttpMethod.Post, multi); + } + + /// + /// Scan multiple files. + /// Note: It is highly encouraged to get the report of the files before scanning, in case it they already been scanned before. + /// Note: You are also strongly encouraged to provide the filename as it is rich metadata for the Virus Total database. + /// + /// The files you wish to scan. They are a tuple of file content and filename. + /// The scan results. + public IEnumerable> ScanFiles(IEnumerable> files) + { + foreach (Tuple fileInfo in files) + { + yield return ScanFile(fileInfo.Item1, fileInfo.Item2); + } + } + + /// + /// Scan multiple files. + /// Note: It is highly encouraged to get the report of the files before scanning, in case it they already been scanned before. + /// Note: You are also strongly encouraged to provide the filename as it is rich metadata for the Virus Total database. + /// + /// The streams you wish to scan. They are a tuple of stream and filename. + /// The scan results. + public IEnumerable> ScanFiles(IEnumerable> streams) + { + foreach (Tuple stream in streams) + { + yield return ScanFile(stream.Item1, stream.Item2); + } + } + + /// + /// Scan multiple files. + /// Note: It is highly encouraged to get the report of the files before scanning, in case it they already been scanned before. + /// + /// The files you wish to scan. + /// The scan results. + public IEnumerable> ScanFiles(IEnumerable files) + { + foreach (FileInfo fileInfo in files) + { + yield return ScanFile(fileInfo); + } + } + + /// + /// Tell VirusTotal to rescan a file without sending the actual file to VirusTotal. + /// Note: Before requesting a rescan you should retrieve the latest report on the file. + /// + /// The scan results. + public Task RescanFile(FileInfo file) + { + return RescanFile(GetResourcesFromFiles(file).First()); + } + + /// + /// Tell VirusTotal to rescan a file without sending the actual file to VirusTotal. + /// Note: Before requesting a rescan you should retrieve the latest report on the file. + /// + /// The scan results. + public Task RescanFile(byte[] file) + { + return RescanFile(GetResourcesFromFiles(file).First()); + } + + /// + /// Tell VirusTotal to rescan a file. + /// Note: This does not send the files to VirusTotal. It hashes the file and sends that instead. + /// Note: Before requesting a rescan you should retrieve the latest report on the files. + /// + /// The scan results. + public Task> RescanFiles(IEnumerable files) + { + return RescanFiles(GetResourcesFromFiles(files.ToArray())); + } + + /// + /// Tell VirusTotal to rescan a file. + /// Note: This does not send the files to VirusTotal. It hashes the file and sends that instead. + /// Note: Before requesting a rescan you should retrieve the latest report on the files. + /// + /// The scan results. + public Task> RescanFiles(IEnumerable files) + { + return RescanFiles(GetResourcesFromFiles(files.ToArray())); + } + + /// + /// Tell VirusTotal to rescan a file. + /// Note: This does not send the content of the streams to VirusTotal. It hashes the content and sends that instead. + /// Note: Before requesting a rescan you should retrieve the latest report on the files. + /// + /// The scan results. + public Task> RescanFiles(IEnumerable streams) + { + return RescanFiles(GetResourcesFromFiles(streams.ToArray())); + } + + /// + /// Tell VirusTotal to rescan a file. + /// Note: This does not send the files to VirusTotal. It hashes the file and sends that instead. + /// Note: Before requesting a rescan you should retrieve the latest report on the files. + /// Note: You can use MD5, SHA1 or SHA256 and even mix them. + /// Note: You can only request a maximum of 25 rescans. + /// + /// a MD5, SHA1 or SHA256 of the files. You can also specify list made up of a combination of any of the three allowed hashes (up to 25 items), this allows you to perform a batch request with one single call. + /// Note: that the files must already be present in the files store. + /// + /// The scan results. + public Task> RescanFiles(IEnumerable resourceList) + { + string[] hashes = resourceList as string[] ?? resourceList.ToArray(); + + if (!hashes.Any()) + throw new ArgumentException("You have to supply a resource.", nameof(resourceList)); + + if (RestrictNumberOfResources && hashes.Length > 25) + throw new ResourceLimitException("Too many hashes. There is a maximum of 25 hashes."); + + for (int i = 0; i < hashes.Length; i++) + { + ValidateResource(hashes[i]); + } + + //Required + Dictionary values = new Dictionary(); + values.Add("resource", string.Join(",", hashes)); + + //https://www.virustotal.com/vtapi/v2/file/rescan + return GetResults("file/rescan", HttpMethod.Post, CreateContent(values)); + } + + /// + /// Tell VirusTotal to rescan a file without sending the actual file to VirusTotal. + /// Note: Before requesting a rescan you should retrieve the latest report on the file. + /// + /// A hash of the file. It can be an MD5, SHA1 or SHA256 + /// The scan results. + public Task RescanFile(string resource) + { + if (string.IsNullOrWhiteSpace(resource)) + throw new ArgumentException("You have to supply a resource.", nameof(resource)); + + ValidateResource(resource); + + //Required + Dictionary values = new Dictionary(); + values.Add("resource", resource); + + //https://www.virustotal.com/vtapi/v2/file/rescan + return GetResult("file/rescan", HttpMethod.Post, CreateContent(values)); + } + + /// + /// Gets the report of the file. + /// Note: This does not send the files to VirusTotal. It hashes the file and sends that instead. + /// + /// The file you wish to get a report on. + public Task GetFileReport(byte[] file) + { + return GetFileReport(HashHelper.GetSHA256(file)); + } + + /// + /// Gets the report of the file. + /// Note: This does not send the files to VirusTotal. It hashes the file and sends that instead. + /// + /// The file you wish to get a report on. + public Task GetFileReport(FileInfo file) + { + return GetFileReport(HashHelper.GetSHA256(file)); + } + + /// + /// Gets a list of reports of the files. + /// Note: This does not send the files to VirusTotal. It hashes the files and sends them instead. + /// + /// The files you wish to get reports on. + public Task> GetFileReports(IEnumerable files) + { + return GetFileReports(GetResourcesFromFiles(files.ToArray())); + } + + /// + /// Gets a list of reports of the files. + /// Note: This does not send the files to VirusTotal. It hashes the files and sends them instead. + /// + /// The files you wish to get reports on. + public Task> GetFileReports(IEnumerable files) + { + return GetFileReports(GetResourcesFromFiles(files.ToArray())); + } + + /// + /// Gets a list of reports of the files. + /// Note: This does not send the content of the streams to VirusTotal. It hashes the content of the stream and sends that instead. + /// + /// The streams you wish to get reports on. + public Task> GetFileReports(IEnumerable streams) + { + return GetFileReports(GetResourcesFromFiles(streams.ToArray())); + } + + /// + /// Gets the report of the file represented by its hash or scan ID. + /// Keep in mind that URLs sent using the API have the lowest scanning priority, depending on VirusTotal's load, it may take several hours before the file is scanned, + /// so query the report at regular intervals until the result shows up and do not keep submitting the file over and over again. + /// + /// SHA1, MD5 or SHA256 of the file. It can also be a scan ID of a previous scan. + /// + public Task> GetFileReports(IEnumerable resourceList) + { + string[] hashes = resourceList as string[] ?? resourceList.ToArray(); + + if (!hashes.Any()) + throw new ArgumentException("You have to supply a resource.", nameof(resourceList)); + + if (RestrictNumberOfResources && hashes.Length > 4) + throw new ResourceLimitException("Too many hashes. There is a maximum of 4 hashes at the same time."); + + for (int i = 0; i < hashes.Length; i++) + { + ValidateResource(hashes[i]); + } + + //Required + Dictionary values = new Dictionary(); + values.Add("resource", string.Join(",", hashes)); + + //https://www.virustotal.com/vtapi/v2/file/report + return GetResults("file/report", HttpMethod.Post, CreateContent(values)); + } + + /// + /// Gets the report of the file. + /// Note: This does not send the files to VirusTotal. It hashes the file and sends that instead. + /// + /// The resource (MD5, SHA1 or SHA256) you wish to get a report on. + public Task GetFileReport(string resource) + { + if (string.IsNullOrWhiteSpace(resource)) + throw new ArgumentException("You have to supply a resource.", nameof(resource)); + + ValidateResource(resource); + + //Required + Dictionary values = new Dictionary(); + values.Add("resource", resource); + + //https://www.virustotal.com/vtapi/v2/file/report + return GetResult("file/report", HttpMethod.Post, CreateContent(values)); + } + + /// + /// Scan the given URL. The URL will be downloaded by VirusTotal and processed. + /// Note: Before performing your submission, you should retrieve the latest report on the URL. + /// + /// The url to process. + /// The scan results. + public Task ScanUrl(string url) + { + return ScanUrl(UrlToUri(new[] { url }).First()); + } + + /// + /// Scan the given URLs. The URLs will be downloaded by VirusTotal and processed. + /// Note: Before performing your submission, you should retrieve the latest reports on the URLs. + /// + /// The urls to process. + /// The scan results. + public Task> ScanUrls(IEnumerable urlList) + { + return ScanUrls(UrlToUri(urlList)); + } + + /// + /// Scan the given URLs. The URLs will be downloaded by VirusTotal and processed. + /// Note: Before performing your submission, you should retrieve the latest reports on the URLs. + /// + /// The urls to process. + /// The scan results. + public Task> ScanUrls(IEnumerable urlList) + { + IEnumerable urls = urlList as Uri[] ?? urlList.ToArray(); + + if (!urls.Any()) + throw new ArgumentException("You have to supply an URL.", nameof(urlList)); + + if (RestrictNumberOfResources && urls.Count() > 25) + throw new ResourceLimitException("Too many URLs. There is a maximum of 25 URLs at the same time."); + + //Required + Dictionary values = new Dictionary(); + values.Add("url", string.Join(Environment.NewLine, urls)); + + //https://www.virustotal.com/vtapi/v2/url/scan + return GetResults("url/scan", HttpMethod.Post, CreateContent(values)); + } + + /// + /// Scan the given URL. The URL will be downloaded by VirusTotal and processed. + /// Note: Before performing your submission, you should retrieve the latest report on the URL. + /// + /// The url to process. + /// The scan results. + public Task ScanUrl(Uri url) + { + if (url == null) + throw new ArgumentNullException(nameof(url), "You have to supply an URL."); + + //Required + Dictionary values = new Dictionary(); + values.Add("url", url.ToString()); + + //https://www.virustotal.com/vtapi/v2/url/scan + return GetResult("url/scan", HttpMethod.Post, CreateContent(values)); + } + + /// + /// Gets a scan report from an URL + /// + /// The URL you wish to get the report on. + /// Set to true if you wish VirusTotal to scan the URL if it is not present in the database. + /// A list of reports + public Task GetUrlReport(string url, bool scanIfNoReport = false) + { + return GetUrlReport(UrlToUri(new[] { url }).First(), scanIfNoReport); + } + + /// + /// Gets a scan report from a list of URLs + /// + /// The URLs you wish to get the reports on. + /// Set to true if you wish VirusTotal to scan the URLs if it is not present in the database. + /// A list of reports + public Task> GetUrlReports(IEnumerable urlList, bool scanIfNoReport = false) + { + return GetUrlReports(UrlToUri(urlList), scanIfNoReport); + } + + /// + /// Gets a scan report from a list of URLs + /// + /// The URLs you wish to get the reports on. + /// Set to true if you wish VirusTotal to scan the URLs if it is not present in the database. + /// A list of reports + public Task> GetUrlReports(IEnumerable urlList, bool scanIfNoReport = false) + { + IEnumerable urls = urlList as Uri[] ?? urlList.ToArray(); + + if (!urls.Any()) + throw new ArgumentException("You have to supply an URL.", nameof(urlList)); + + if (RestrictNumberOfResources && urls.Count() > 4) + throw new ResourceLimitException("Too many URLs. There is a maximum of 4 urls at the time."); + + //Required + Dictionary values = new Dictionary(); + values.Add("resource", string.Join(Environment.NewLine, urls)); + + //Optional + if (scanIfNoReport) + values.Add("scan", "1"); + + //Output + return GetResults("url/report", HttpMethod.Post, CreateContent(values)); + } + + /// + /// Gets a scan report from an URL + /// + /// The URL you wish to get the report on. + /// Set to true if you wish VirusTotal to scan the URL if it is not present in the database. + /// A list of reports + public Task GetUrlReport(Uri url, bool scanIfNoReport = false) + { + if (url == null) + throw new ArgumentNullException(nameof(url), "You have to supply an URL."); + + //Required + Dictionary values = new Dictionary(); + values.Add("resource", url.ToString()); + + //Optional + if (scanIfNoReport) + values.Add("scan", "1"); + + //Output + return GetResult("url/report", HttpMethod.Post, CreateContent(values)); + } + + /// + /// Gets a scan report from an list of IP addreses + /// IMPORTANT: This method actually does a query pr. item, which can quickly result in you getting over your request limit. + /// + /// The IPs you wish to get a report for. + /// A list of reports + public IEnumerable> GetIPReports(IEnumerable ips) + { + foreach (IPAddress ip in ips) + { + yield return GetIPReport(ip); + } + } + + /// + /// Gets a scan report from an list of IP addreses + /// IMPORTANT: This method actually does a query pr. item, which can quickly result in you getting over your request limit. + /// + /// The IPs you wish to get a report for. + /// A list of reports + public IEnumerable> GetIPReports(IEnumerable ips) + { + foreach (string ip in ips) + { + yield return GetIPReport(ip); + } + } + + /// + /// Gets a scan report from an IP + /// + /// The IP you wish to get the report on. + /// A report + public Task GetIPReport(string ip) + { + return GetIPReport(IPAddress.Parse(ip)); + } + + /// + /// Gets a scan report from an IP + /// + /// The IP you wish to get the report on. + /// A report + public Task GetIPReport(IPAddress ip) + { + if (ip == null) + throw new ArgumentNullException(nameof(ip), "You have to supply an IP."); + + if (ip.AddressFamily != AddressFamily.InterNetwork) + throw new ArgumentException("Only IPv4 addresses are supported", nameof(ip)); + + //Hack because VT thought it was a good idea to have this API call as GET + return GetResult("ip-address/report?apikey=" + _defaultValues["apikey"] + "&ip=" + ip, HttpMethod.Get, null); + } + + /// + /// Gets a scan report from a list of domains + /// IMPORTANT: This method actually does a query pr. item, which can quickly result in you getting over your request limit. + /// + /// The list of domains you wish to get reports for. + /// A list of reports + public IEnumerable> GetDomainReports(IEnumerable domains) + { + foreach (string domain in domains) + { + yield return GetDomainReport(domain); + } + } + + /// + /// Gets a scan report from a domain + /// + /// The domain you wish to get the report on. + /// A report + public Task GetDomainReport(string domain) + { + if (string.IsNullOrWhiteSpace(domain)) + throw new ArgumentException("You have to supply a domain.", nameof(domain)); + + //Required + Dictionary values = new Dictionary(); + values.Add("domain", domain); + + //Hack because VT thought it was a good idea to have this API call as GET + return GetResult("domain/report?apikey=" + _defaultValues["apikey"] + "&domain=" + domain, HttpMethod.Get, null); + } + + /// + /// Creates a comment on a file denoted by its hash and/or scan ID. + /// + /// The file you wish to create a comment on + /// The comment you wish to add. + /// A ScanResult object containing information about the resource. + public Task CreateComment(byte[] file, string comment) + { + return CreateComment(HashHelper.GetSHA256(file), comment); + } + + /// + /// Creates a comment on a file denoted by its hash and/or scan ID. + /// + /// The file you wish to create a comment on + /// The comment you wish to add. + /// A ScanResult object containing information about the resource. + public Task CreateComment(FileInfo file, string comment) + { + return CreateComment(HashHelper.GetSHA256(file), comment); + } + + /// + /// Creates a comment on a file denoted by its hash and/or scan ID. + /// + /// The SHA256 hash or scan ID of the resource. + /// The comment you wish to add. + /// A ScanResult object containing information about the resource. + public Task CreateComment(string resource, string comment) + { + ValidateResource(resource); + + if (string.IsNullOrWhiteSpace(comment)) + throw new ArgumentException("Comment must not be null or whitespace", nameof(comment)); + + //Required + Dictionary values = new Dictionary(); + values.Add("resource", resource); + values.Add("comment", comment); + + //https://www.virustotal.com/vtapi/v2/comments/put + return GetResult("comments/put", HttpMethod.Post, CreateContent(values)); + } + + private FormUrlEncodedContent CreateContent(Dictionary values) + { + return new FormUrlEncodedContent(_defaultValues.Concat(values)); + } + + /// + /// Gives you a link to a file analysis based on its hash. + /// + /// A link to VirusTotal that contains the report + public string GetPublicFileScanLink(string resource) + { + ValidateResource(resource); + + return string.Format("{0}://www.virustotal.com/file/{1}/analysis/", UseTLS ? "https" : "http", resource); + } + + /// + /// Gives you a link to a file analysis based on its hash. + /// + /// A link to VirusTotal that contains the report + public string GetPublicFileScanLink(FileInfo file) + { + return GetPublicFileScanLink(HashHelper.GetSHA256(file)); + } + + /// + /// Gives you a link to a URL analysis. + /// + /// A link to VirusTotal that contains the report + public string GetPublicUrlScanLink(string url) + { + return string.Format("{0}://www.virustotal.com/url/{1}/analysis/", UseTLS ? "https" : "http", HashHelper.GetSHA256(NormalizeUrl(url))); + } + + private async Task> GetResults(string url, HttpMethod method, HttpContent content) + { + HttpResponseMessage response = await SendRequest(url, method, content); + + using (Stream responseStream = await response.Content.ReadAsStreamAsync()) + using (StreamReader sr = new StreamReader(responseStream, Encoding.UTF8)) + using (JsonTextReader jsonTextReader = new JsonTextReader(sr)) + { + jsonTextReader.CloseInput = false; + + JToken token = JToken.Load(jsonTextReader); + + if (token.Type == JTokenType.Array) + return token.ToObject>(_serializer); + + List list = new List { token.ToObject(_serializer) }; + + DumpJSONIfDebug(responseStream); + + return list; + } + } + + private async Task GetResult(string url, HttpMethod method, HttpContent content) + { + HttpResponseMessage response = await SendRequest(url, method, content); + + using (Stream responseStream = await response.Content.ReadAsStreamAsync()) + using (StreamReader sr = new StreamReader(responseStream, Encoding.UTF8)) + using (JsonTextReader jsonTextReader = new JsonTextReader(sr)) + { + jsonTextReader.CloseInput = false; + + T obj = _serializer.Deserialize(jsonTextReader); + + DumpJSONIfDebug(responseStream); + + return obj; + } + } + + private void DumpJSONIfDebug(Stream stream) + { + if (!DumpRawJSON) + return; + + stream.Position = 0; + string path = Environment.ExpandEnvironmentVariables(DumpFolder); + + if (!Directory.Exists(path)) + Directory.CreateDirectory(path); + + string filename = DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss") + "-" + Guid.NewGuid() + ".json"; + string filePath = Path.Combine(path, filename); + + using (FileStream fs = File.OpenWrite(filePath)) + stream.CopyTo(fs); + } + + private async Task SendRequest(string url, HttpMethod method, HttpContent content) + { + HttpRequestMessage request = new HttpRequestMessage(method, url); + request.Content = content; + + HttpResponseMessage response = await _client.SendAsync(request); + + if (response.StatusCode == HttpStatusCode.NoContent) + throw new RateLimitException("You have reached the 4 requests pr. min. limit of VirusTotal"); + + if (response.StatusCode == HttpStatusCode.Forbidden) + throw new AccessDeniedException("You don't have access to the service. Make sure your API key is working correctly."); + + if (response.StatusCode != HttpStatusCode.OK) + throw new Exception("API gave error code " + response.StatusCode); + + if (string.IsNullOrWhiteSpace(response.Content.ToString())) + throw new Exception("There were no content in the response."); + + return response; + } + + private string NormalizeUrl(string url) + { + Uri uri = CreateUri(url); + return uri.ToString(); + } + + private IEnumerable GetResourcesFromFiles(params FileInfo[] files) + { + foreach (FileInfo fileInfo in files) + { + yield return HashHelper.GetSHA256(fileInfo); + } + } + + private IEnumerable GetResourcesFromFiles(params byte[][] files) + { + foreach (byte[] fileBytes in files) + { + yield return HashHelper.GetSHA256(fileBytes); + } + } + + private IEnumerable GetResourcesFromFiles(params Stream[] streams) + { + foreach (Stream stream in streams) + { + yield return HashHelper.GetSHA256(stream); + } + } + + private IEnumerable UrlToUri(IEnumerable urls) + { + foreach (string url in urls) + { + Uri uri; + try + { + uri = CreateUri(url); + } + catch (Exception ex) + { + throw new Exception("There was an error converting " + url + " to an uri. See InnerException for details.", ex); + } + + yield return uri; + } + } + + private Uri CreateUri(string url) + { + string tempUri = url.Trim(); + string lowered = tempUri.ToLower(); + + if (!lowered.StartsWith("http://") && !lowered.StartsWith("https://")) + tempUri = "http://" + tempUri; + + return new Uri(tempUri); + } + + private void ValidateResource(string resource) + { + if (string.IsNullOrWhiteSpace(resource)) + throw new ArgumentException("Resource must not be null or whitespace", nameof(resource)); + + if (resource.Length != 32 && resource.Length != 40 && resource.Length != 64 && resource.Length != 75) + throw new InvalidResourceException("Resource " + resource + " has to be either a MD5, SHA1, SHA256 or scan id"); + } + + private HttpContent CreateApiPart() + { + HttpContent content = new StringContent(_defaultValues["apikey"]); + content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") + { + Name = "\"apikey\"" + }; + + return content; + } + + private StreamContent CreateFileContent(Stream stream, string fileName, string contentType) + { + var fileContent = new StreamContent(stream); + fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") + { + Name = "\"file\"", + FileName = "\"" + fileName + "\"" + }; + fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); + return fileContent; + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from System.Net.Http.FormUrlEncodedContent VirusTotalNET.VirusTotal::CreateContent(System.Collections.Generic.Dictionary`2) at Line 594) of type System.Net.Http.FormUrlEncodedContent in method "Task`1 VirusTotal.GetUrlReport(Uri,Boolean)". + +### Severity: +ERROR + +### Procedure: +Task`1 VirusTotal.GetUrlReport(Uri,Boolean) + +### File: +VirusTotal.NET/VirusTotal.cs + +### Key: +VirusTotal.cs|GetUrlReport|DOTNET_RESOURCE_LEAK + +### Hash: +415cf7da9fcc93adc24a00a48a10c7cd + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0906/instruction.md b/inferredbugs-0906/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fd351c67f56f6bf94f1ecfc02a4dac482541d105 --- /dev/null +++ b/inferredbugs-0906/instruction.md @@ -0,0 +1,500 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** netDumbster +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace netDumbster.Test +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Net.Mail; + using System.Net.Mime; + using System.Text; + using netDumbster.smtp; + using netDumbster.smtp.Logging; + using Xunit; + using System.Threading.Tasks; + using System.Net.Sockets; + + public class TestsBase : IDisposable + { + protected SimpleSmtpServer server; + + private Random _Rnd = new Random(); + + public TestsBase() + { + LogManager.GetLogger = type => new ConsoleLogger(type); + this.server = this.StartServer(); + } + + protected virtual SimpleSmtpServer StartServer() + { + return SimpleSmtpServer.Start(); + } + + protected virtual SimpleSmtpServer StartServer(int port) + { + return SimpleSmtpServer.Start(port); + } + + [Fact] + public void Send_10_Mails() + { + for (var i = 0; i < 10; i++) + { + this.SendMail(); + Assert.Equal(i + 1, this.server.ReceivedEmailCount); + } + + Assert.Equal(10, this.server.ReceivedEmailCount); + } + + [Fact] + public void Send_10_Mail_With_SmtpAuth() + { + for (var i = 0; i < 10; i++) + { + this.SendMail(true); + Assert.Equal(i + 1, this.server.ReceivedEmailCount); + } + + Assert.Equal(10, this.server.ReceivedEmailCount); + } + + [Fact] + public void Send_Email_And_Restart_Server_Using_The_Same_Port() + { + int port = 5003; + SimpleSmtpServer fixedPortServer = this.StartServer(port); + + this.SendMail(false, false, null, port); + + Assert.Equal(1, fixedPortServer.ReceivedEmailCount); + Assert.Equal("this is the body", fixedPortServer.ReceivedEmail[0].MessageParts[0].BodyData); + + fixedPortServer.Stop(); + + fixedPortServer = this.StartServer(port); + + this.SendMail(false, false, null, port); + + Assert.Equal(1, fixedPortServer.ReceivedEmailCount); + Assert.Equal("this is the body", fixedPortServer.ReceivedEmail[0].MessageParts[0].BodyData); + + fixedPortServer.Stop(); + } + + // Test is run several several times since we're testing asynchronous behaviour + [Theory] + [Repeat(5)] + public void Send_Email_When_Server_Not_Running() + { + this.server.Stop(); + Assert.Throws(() => this.SendMail()); + } + + [Fact] + public void Send_Email_With_AlternateViews() + { + using (var client = new SmtpClient("localhost", this.server.Configuration.Port)) + { + var mailMessage = new MailMessage("carlos@mendible.com", "karina@mendible.com", "test", "this is the body"); + mailMessage.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("FooBar", new ContentType("text/html"))); + client.Send(mailMessage); + } + + Assert.Equal(1, this.server.ReceivedEmailCount); + var smtpMessage = this.server.ReceivedEmail[0]; + + Assert.Equal(2, smtpMessage.MessageParts.Length); + Assert.True(smtpMessage.MessageParts[0].HeaderData.Contains("text/plain")); + Assert.Equal("this is the body", smtpMessage.MessageParts[0].BodyData); + Assert.True(smtpMessage.MessageParts[1].HeaderData.Contains("text/html")); + Assert.Equal("FooBar", smtpMessage.MessageParts[1].BodyData); + } + + [Fact] + public void Send_Email_With_AlternateViews_And_Attachments() + { + using (var client = new SmtpClient("localhost", this.server.Configuration.Port)) + { + var mailMessage = new MailMessage("carlos@mendible.com", "karina@mendible.com", "test", "this is the body"); + mailMessage.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("FooBar", new ContentType("text/html"))); + mailMessage.Attachments.Add(Attachment.CreateAttachmentFromString("Attachment1", new ContentType("application/octet-stream"))); + mailMessage.Attachments.Add(Attachment.CreateAttachmentFromString("Attachment2", new ContentType("application/octet-stream"))); + mailMessage.Attachments.Add(Attachment.CreateAttachmentFromString("Attachment3", new ContentType("application/octet-stream"))); + client.Send(mailMessage); + } + + Assert.Equal(1, this.server.ReceivedEmailCount); + var smtpMessage = this.server.ReceivedEmail[0]; + Assert.Equal(5, smtpMessage.MessageParts.Length); + Assert.True(smtpMessage.MessageParts[0].HeaderData.Contains("text/plain")); + Assert.Equal("this is the body", smtpMessage.MessageParts[0].BodyData); + Assert.True(smtpMessage.MessageParts[1].HeaderData.Contains("text/html")); + Assert.Equal("FooBar", smtpMessage.MessageParts[1].BodyData); + } + + [Fact] + public void Send_Email_With_Attachment() + { + var data = new byte[] { 0x1 }; + + this.SendMail(false, true, data); + Assert.Equal(1, this.server.ReceivedEmailCount); + Assert.Equal("this is the html body", this.server.ReceivedEmail[0].MessageParts[0].BodyData); + Assert.NotNull(this.server.ReceivedEmail[0].MessageParts[1]); + Assert.NotNull(this.server.ReceivedEmail[0].MessageParts[1].BodyData); + Assert.NotEmpty(this.server.ReceivedEmail[0].MessageParts[1].BodyData); + Assert.Equal(data, UTF8Encoding.UTF8.GetBytes(this.server.ReceivedEmail[0].MessageParts[1].BodyData)); + } + + [Fact] + public void Send_Multiline_Email() + { + var expectedBody = $"this is the body{Environment.NewLine}line2{Environment.NewLine}line3"; + + using (SmtpClient client = new SmtpClient("localhost", this.server.Configuration.Port)) + { + var mailMessage = new MailMessage("carlos@mendible.com", "karina@mendible.com", "test", expectedBody); + mailMessage.IsBodyHtml = false; + client.Send(mailMessage); + } + + Assert.Equal(1, this.server.ReceivedEmailCount); + Assert.Equal(expectedBody, this.server.ReceivedEmail[0].MessageParts[0].BodyData); + } + + [Fact] + public void Send_Email_With_Priority() + { + using (SmtpClient client = new SmtpClient("localhost", this.server.Configuration.Port)) + { + var mailMessage = new MailMessage("carlos@mendible.com", "karina@mendible.com", "test", "this is the body"); + mailMessage.IsBodyHtml = false; + mailMessage.Priority = MailPriority.High; + client.Send(mailMessage); + } + + Assert.Equal(1, this.server.ReceivedEmailCount); + Assert.Equal("this is the body", this.server.ReceivedEmail[0].MessageParts[0].BodyData); + Assert.Equal("1", this.server.ReceivedEmail[0].XPriority); + Assert.Equal("urgent", this.server.ReceivedEmail[0].Priority); + Assert.Equal("high", this.server.ReceivedEmail[0].Importance); + } + + [Fact] + public void Send_Email_With_RussianText() + { + string body = string.Empty; + using (SmtpClient client = new SmtpClient("localhost", this.server.Configuration.Port)) + { + body = "Съешь ещё этих мягких французских булок, да выпей чаю" + + "Съешь ещё этих мягких французских булок, да выпей чаю" + + "Съешь ещё этих мягких французских булок, да выпей чаю" + + "Съешь ещё этих мягких французских булок, да выпей чаю" + + "Съешь ещё этих мягких французских булок, да выпей чаю" + + "Съешь ещё этих мягких французских булок, да выпей чаю"; + var mailMessage = new MailMessage("carlos@mendible.com", "karina@mendible.com", "test", body); + mailMessage.IsBodyHtml = false; + client.Send(mailMessage); + } + + Assert.Equal(1, this.server.ReceivedEmailCount); + Assert.Equal(body, this.server.ReceivedEmail[0].MessageParts[0].BodyData); + + this.server.Stop(); + } + + [Fact] + public void Send_Email_With_UTF8_Chars() + { + string body = string.Empty; + using (SmtpClient client = new SmtpClient("localhost", this.server.Configuration.Port)) + { + body = "µ¶®¥§"; + var mailMessage = new MailMessage("carlos@mendible.com", "karina@mendible.com", "test", body); + mailMessage.IsBodyHtml = false; + client.Send(mailMessage); + } + + Assert.Equal(1, this.server.ReceivedEmailCount); + Assert.Equal(body, this.server.ReceivedEmail[0].MessageParts[0].BodyData); + + this.server.Stop(); + } + + [Fact] + public void Send_Fires_Message_Received_Event() + { + int port = 50004; + SimpleSmtpServer fixedPortServer = this.StartServer(port); + fixedPortServer.MessageReceived += (sender, args) => + { + Assert.NotNull(args.Message); + Assert.Equal(1, fixedPortServer.ReceivedEmailCount); + Assert.Equal("this is the body", args.Message.MessageParts[0].BodyData); + }; + + this.SendMail(false, false, null, port); + + fixedPortServer.Stop(); + } + + [Fact] + public void Send_Html_Email() + { + this.SendMail(false, true, null); + Assert.Equal(1, this.server.ReceivedEmailCount); + Assert.Equal("this is the html body", this.server.ReceivedEmail[0].MessageParts[0].BodyData); + } + + [Fact] + public void Send_One_Mail() + { + this.SendMail(); + Assert.Equal(1, this.server.ReceivedEmailCount); + Assert.Equal("this is the body", this.server.ReceivedEmail[0].MessageParts[0].BodyData); + } + + [Fact] + public void If_Client_Is_Not_Disposed_Server_Everything_Keeps_Working() + { + var port = GetRandomUnusedPort(); + var host = "localhost"; + using (SimpleSmtpServer emailServer = this.StartServer(port)) + { + SmtpClient client = new SmtpClient(host, port); + client.Send("noone@nowhere.com", "nobody@nowhere.com", "This is an email", "body of email"); + } + + using (SimpleSmtpServer emailServer = this.StartServer(port)) + { + using (SmtpClient client = new SmtpClient(host, port)) + client.Send("noone@nowhere.com", "nobody@nowhere.com", "This is an email", "body of email"); + } + } + + [Fact] + public void Send_One_Mail_Clear_Send_Another_Mail() + { + this.SendMail(); + Assert.Equal(1, this.server.ReceivedEmailCount); + Assert.Equal("this is the body", this.server.ReceivedEmail[0].MessageParts[0].BodyData); + this.server.ClearReceivedEmail(); + this.SendMail(); + Assert.Equal("this is the body", this.server.ReceivedEmail[0].MessageParts[0].BodyData); + } + + [Fact] + public void Send_One_Mail_With_SmtpAuth() + { + this.SendMail(true); + Assert.Equal(1, this.server.ReceivedEmailCount); + } + + [Fact] + public void Start_Server_Random_Port() + { + SimpleSmtpServer randomPortServer = this.StartServer(); + Assert.True(randomPortServer.Configuration.Port > 0); + randomPortServer.Stop(); + } + + [Fact] + public void Send_Attachments_Mails_SpecialChars() + { + var files = Directory.GetFiles("Content"); + SendMail(false, files); + Assert.Equal(files.Length, this.server.ReceivedEmailCount); + var smtpMail = this.server.ReceivedEmail[0]; + using (MailMessage mailMessage = MailMessageMimeParser.ParseMessage(new System.IO.StringReader(smtpMail.Data))) + { + foreach (var m in mailMessage.Attachments) + { + Console.WriteLine(m.Name); + Assert.True(files[0].EndsWith(m.Name)); + } + } + } + + [Fact(Timeout = 10000)] + public async Task Reusing_Smtp_Client_Should_Not_Fail() + { + var config = Configuration.Configure(); + using var server = SimpleSmtpServer.Start(config.WithRandomPort().Port); + var mailClient = new SmtpClient + { + Host = "localhost", + Port = server.Configuration.Port, + EnableSsl = false + }; + + for (int messageNo = 0; messageNo < 2; messageNo++) + { + var mailMessage = new MailMessage("one@example.com", "two@example.com"); + + await mailClient.SendMailAsync(mailMessage); + + Assert.Equal(messageNo + 1, server.ReceivedEmailCount); + } + } + + protected void SendMail() + { + this.SendMail(false); + } + + protected void SendMail(bool smtpAuth) + { + this.SendMail(smtpAuth, false, null); + } + + protected void SendMail(bool smtpAuth, bool isBodyHtml, byte[] attachment) + { + this.SendMail(smtpAuth, isBodyHtml, attachment, this.server.Configuration.Port); + } + + protected void SendMail(bool smtpAuth, bool isBodyHtml, byte[] attachment, int serverPort) + { + using (SmtpClient client = new SmtpClient("localhost", serverPort)) + { + var mailMessage = new MailMessage("carlos@mendible.com", "karina@mendible.com", "test", "this is the body"); + mailMessage.Bcc.Add(new MailAddress("bcc@mendible.com")); + mailMessage.CC.Add(new MailAddress("cc@mendible.com")); + mailMessage.IsBodyHtml = isBodyHtml; + + if (isBodyHtml) + { + mailMessage.Body = "this is the html body"; + } + + if (smtpAuth) + { + NetworkCredential credentials = new NetworkCredential("user", "pwd"); + client.Credentials = credentials; + client.EnableSsl = false; + } + + if (attachment != null) + { + mailMessage.Attachments.Add(new Attachment(new MemoryStream(attachment), "image/jpeg")); + } + + client.Send(mailMessage); + } + } + + protected void SendMail(bool smtpAuth, IEnumerable attach) + { + SmtpClient client = new SmtpClient("localhost", this.server.Configuration.Port); + var mailMessage = new MailMessage("cfm@mendible.com", "kbm@mendible.com", "test", "test test test"); + foreach (var fileName in attach) + mailMessage.Attachments.Add(new Attachment(fileName)); + + if (smtpAuth) + { + NetworkCredential credentials = new NetworkCredential("user", "pwd"); + client.Credentials = credentials; + client.EnableSsl = false; + } + client.Send(mailMessage); + + client.Dispose(); + } + + private bool disposedValue = false; // To detect redundant calls + + protected virtual void Dispose(bool disposing) + { + if (!disposedValue) + { + if (disposing) + { + this.server.Stop(); + } + + disposedValue = true; + } + } + + static int GetRandomUnusedPort() + { + try + { + var listener = new TcpListener(IPAddress.Any, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + return port; + } + catch + { + throw; + } + } + + // This code added to correctly implement the disposable pattern. + void IDisposable.Dispose() + { + Dispose(true); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource mailMessage of type System.Net.Mail.MailMessage in method "Void TestsBase.Send_Email_With_UTF8_Chars()". + +### Severity: +ERROR + +### Procedure: +Void TestsBase.Send_Email_With_UTF8_Chars() + +### File: +netDumbster.Test/TestsBase.cs + +### Key: +TestsBase.cs|Send_Email_With_UTF8_Chars|DOTNET_RESOURCE_LEAK + +### Hash: +93d61e95a86034965186b58ff240f48d + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0908/instruction.md b/inferredbugs-0908/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3c00a4cb31de11844fdcc37b264e9bebdbd64aed --- /dev/null +++ b/inferredbugs-0908/instruction.md @@ -0,0 +1,306 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** pusher-http-dotnet +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Newtonsoft.Json; +using NUnit.Framework; +using PusherServer.Exceptions; +using PusherServer.Tests.Helpers; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; + +namespace PusherServer.Tests.AcceptanceTests +{ + [TestFixture] + public class When_Triggering_an_Event_on_a_single_Channel + { + IPusher _pusher; + + [OneTimeSetUp] + public void Setup() + { + PusherClient.Pusher.Trace.Listeners.Add(new ConsoleTraceListener(true)); + _pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() + { + HostName = Config.HttpHost + }); + } + + [Test] + public async Task It_should_return_a_200_response_async() + { + ITriggerResult asyncResult = await _pusher.TriggerAsync("my-channel", "my_event", new { hello = "world" }); + + Assert.AreEqual(HttpStatusCode.OK, asyncResult.StatusCode); + } + + [Test] + [Ignore("This test requires a node that support batch triggers, which isn't available on the default")] + public async Task it_should_expose_the_event_id_async() + { + var waiting = new AutoResetEvent(false); + + ITriggerResult asyncResult = await _pusher.TriggerAsync("my-channel", "my_event", new { hello = "world" }); + + waiting.Set(); + + Assert.IsFalse(string.IsNullOrEmpty(asyncResult.EventIds["my-channel"])); + } + + [Test] + public async Task It_should_be_received_by_a_client_async() + { + string channelName = "my_channel"; + string eventName = "my_event"; + + bool eventReceived = false; + AutoResetEvent reset = new AutoResetEvent(false); + + var client = new PusherClient.Pusher(Config.AppKey) + { + Host = Config.WebSocketHost, + }; + client.Connected += new PusherClient.ConnectedEventHandler(delegate (object sender) + { + Debug.WriteLine("connected"); + reset.Set(); + }); + + Debug.WriteLine("connecting"); + client.Connect(); + + Debug.WriteLine("waiting to connect"); + reset.WaitOne(TimeSpan.FromSeconds(5)); + + Debug.WriteLine("subscribing"); + var channel = client.Subscribe(channelName); + channel.Subscribed += new PusherClient.SubscriptionEventHandler(delegate (object s) + { + Debug.WriteLine("subscribed"); + reset.Set(); + }); + + Debug.WriteLine("waiting for Subscribed"); + reset.WaitOne(TimeSpan.FromSeconds(5)); + + Debug.WriteLine("binding"); + channel.Bind(eventName, delegate (dynamic data) + { + Debug.WriteLine("event received"); + eventReceived = true; + reset.Set(); + }); + + Debug.WriteLine("Bound. Triggering"); + await _pusher.TriggerAsync(channelName, eventName, new { hello = "world" }); + + Debug.WriteLine("waiting for event to be received"); + reset.WaitOne(TimeSpan.FromSeconds(10)); + + Assert.IsTrue(eventReceived); + } + + [Test] + public async Task it_can_trigger_an_event_with_a_percent_in_the_message_async() + { + string fileName = Path.Combine(Assembly.GetExecutingAssembly().Location, @"..\..\..\..\AcceptanceTests\percent-message.json"); + var eventJSON = File.ReadAllText(fileName); + var message = JsonConvert.DeserializeObject(eventJSON); + + ITriggerResult result = await _pusher.TriggerAsync("my-channel", "my_event", message); + Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); + } + + [Test] + [ExpectedException(typeof(EventDataSizeExceededException))] + public async Task It_should_fail_for_an_event_data_size_greater_than_10KB_async() + { + IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() + { + HostName = Config.HttpHost, + BatchEventDataSizeLimit = PusherOptions.DEFAULT_BATCH_EVENT_DATA_SIZE_LIMIT, + }); + int size = PusherOptions.DEFAULT_BATCH_EVENT_DATA_SIZE_LIMIT + 1; + List largeEvent = DataHelper.CreateEvents(numberOfEvents: 1, eventSizeInBytes: size); + await pusher.TriggerAsync("my-channel", "my_event", largeEvent[0]); + } + } + + [TestFixture] + public class When_Triggering_an_Event_on_a_multiple_Channels + { + [Test] + public async Task It_should_return_a_200_response_async() + { + IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() + { + HostName = Config.HttpHost + }); + + ITriggerResult asyncResult = await pusher.TriggerAsync(new string[] { "my-channel-1", "my-channel-2" }, "my_event", new { hello = "world" }); + + Assert.AreEqual(HttpStatusCode.OK, asyncResult.StatusCode); + } + } + + [TestFixture] + public class When_Triggering_a_Batch_of_Events + { + [Test] + public async Task It_should_return_a_200_response_async() + { + IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() + { + HostName = Config.HttpHost, + BatchEventDataSizeLimit = PusherOptions.DEFAULT_BATCH_EVENT_DATA_SIZE_LIMIT, + }); + + List events = DataHelper.CreateEvents(numberOfEvents: 9, eventSizeInBytes: 84); + int size = PusherOptions.DEFAULT_BATCH_EVENT_DATA_SIZE_LIMIT; + List largeEvent = DataHelper.CreateEvents(numberOfEvents: 1, eventSizeInBytes: size); + events.AddRange(largeEvent); + + var result = await pusher.TriggerAsync(events.ToArray()); + + Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); + } + + [Test] + [ExpectedException(typeof(EventDataSizeExceededException))] + public async Task It_should_fail_for_an_event_data_size_greater_than_10KB_async() + { + IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() + { + HostName = Config.HttpHost, + BatchEventDataSizeLimit = PusherOptions.DEFAULT_BATCH_EVENT_DATA_SIZE_LIMIT, + }); + + List events = DataHelper.CreateEvents(numberOfEvents: 9, eventSizeInBytes: 84); + int size = PusherOptions.DEFAULT_BATCH_EVENT_DATA_SIZE_LIMIT + 1; + List largeEvent = DataHelper.CreateEvents(numberOfEvents: 1, eventSizeInBytes: size); + events.AddRange(largeEvent); + + await pusher.TriggerAsync(events.ToArray()); + } + + [Test] + [ExpectedException(typeof(EventBatchSizeExceededException))] + public async Task It_should_fail_for_a_batch_size_greater_than_10_async() + { + IPusher pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() + { + HostName = Config.HttpHost, + BatchEventDataSizeLimit = PusherOptions.DEFAULT_BATCH_EVENT_DATA_SIZE_LIMIT, + }); + + List events = DataHelper.CreateEvents(numberOfEvents: 11, eventSizeInBytes: 92); + await pusher.TriggerAsync(events.ToArray()); + } + } + + [TestFixture] + public class When_Triggering_an_Event_over_HTTPS + { + IPusher _pusher = null; + + [OneTimeSetUp] + public void Setup() + { + PusherClient.Pusher.Trace.Listeners.Add(new ConsoleTraceListener(true)); + + _pusher = new Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherOptions() + { + Encrypted = true, + HostName = Config.HttpHost + }); + } + + [Test] + public async Task It_should_return_a_200_response() + { + ITriggerResult result = await _pusher.TriggerAsync("my-channel", "my_event", new { hello = "world" }); + Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); + } + + [Test] + [Ignore("This test requires a node that support batch triggers, which isn't available on the default")] + public async Task It_should_expose_a_single_event_id_when_publishing_to_a_single_channel() + { + ITriggerResult result = await _pusher.TriggerAsync("ch1", "my_event", new { hello = "world" }); + Assert.IsTrue(result.EventIds.ContainsKey("ch1")); + Assert.AreEqual(1, result.EventIds.Count); + } + + [Test] + [Ignore("This test requires a node that support batch triggers, which isn't available on the default")] + public async Task It_should_expose_a_multiple_event_ids_when_publishing_to_multiple_channels() + { + var channels = new string[] { "ch1", "ch2", "ch3" }; + ITriggerResult result = await _pusher.TriggerAsync(channels, "my_event", new { hello = "world" }); + Assert.IsTrue(result.EventIds.ContainsKey("ch1")); + Assert.IsTrue(result.EventIds.ContainsKey("ch2")); + Assert.IsTrue(result.EventIds.ContainsKey("ch3")); + Assert.AreEqual(channels.Length, result.EventIds.Count); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of System.Diagnostics.ConsoleTraceListener::.ctor() at Line 211) of type System.Diagnostics.ConsoleTraceListener in method "Void When_Triggering_an_Event_over_HTTPS.Setup()". + +### Severity: +ERROR + +### Procedure: +Void When_Triggering_an_Event_over_HTTPS.Setup() + +### File: +PusherServer.Tests/AcceptanceTests/Trigger.cs + +### Key: +Trigger.cs|Setup|DOTNET_RESOURCE_LEAK + +### Hash: +74c77d1ea017ab2572fd90512429c667 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0930/instruction.md b/inferredbugs-0930/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..262bd291013f833d46104f5071dfaa93936a7aff --- /dev/null +++ b/inferredbugs-0930/instruction.md @@ -0,0 +1,170 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Ruffles +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using NUnit.Framework; +using Ruffles.Channeling.Channels; +using Ruffles.Memory; +using Ruffles.Tests.Helpers; +using Ruffles.Tests.Stubs; +using System; + +namespace Ruffles.Tests.Channels +{ + [TestFixture()] + public class ReliableSequencedChannelTests + { + [Test()] + public void TestSimpleMessage() + { + Configuration.SocketConfig config = new Configuration.SocketConfig(); + + MemoryManager memoryManager = new MemoryManager(config); + + ConnectionStub clientsConnectionToServer = new ConnectionStub(); + ConnectionStub serversConnectionToClient = new ConnectionStub(); + + ReliableSequencedChannel clientChannel = new ReliableSequencedChannel(0, clientsConnectionToServer, config, memoryManager); + ReliableSequencedChannel serverChannel = new ReliableSequencedChannel(0, serversConnectionToClient, config, memoryManager); + + byte[] message = BufferHelper.GetRandomBuffer(1024); + + HeapMemory messageMemory = clientChannel.CreateOutgoingMessage(new ArraySegment(message, 0, 1024), out bool dealloc)[0]; + ArraySegment? payload = serverChannel.HandleIncomingMessagePoll(new ArraySegment(messageMemory.Buffer, (int)messageMemory.VirtualOffset + 2, (int)messageMemory.VirtualCount - 2), out bool hasMore); + + Assert.NotNull(payload); + Assert.False(hasMore); + + byte[] bytePayload = new byte[payload.Value.Count]; + Array.Copy(payload.Value.Array, payload.Value.Offset, bytePayload, 0, payload.Value.Count); + + Assert.AreEqual(message, bytePayload); + } + + [Test()] + public void TestOutOfOrder() + { + Configuration.SocketConfig config = new Configuration.SocketConfig(); + + MemoryManager memoryManager = new MemoryManager(config); + + ConnectionStub clientsConnectionToServer = new ConnectionStub(); + ConnectionStub serversConnectionToClient = new ConnectionStub(); + + ReliableSequencedChannel clientChannel = new ReliableSequencedChannel(0, clientsConnectionToServer, config, memoryManager); + ReliableSequencedChannel serverChannel = new ReliableSequencedChannel(0, serversConnectionToClient, config, memoryManager); + + // Create 3 payloads + byte[] message1 = BufferHelper.GetRandomBuffer(1024); + byte[] message2 = BufferHelper.GetRandomBuffer(1024); + byte[] message3 = BufferHelper.GetRandomBuffer(1024); + + // Sequence all payloads as outgoing + HeapMemory message1Memory = clientChannel.CreateOutgoingMessage(new ArraySegment(message1, 0, 1024), out bool dealloc)[0]; + HeapMemory message2Memory = clientChannel.CreateOutgoingMessage(new ArraySegment(message2, 0, 1024), out dealloc)[0]; + HeapMemory message3Memory = clientChannel.CreateOutgoingMessage(new ArraySegment(message3, 0, 1024), out dealloc)[0]; + + // Consume 1st payload + ArraySegment? payload1 = serverChannel.HandleIncomingMessagePoll(new ArraySegment(message1Memory.Buffer, (int)message1Memory.VirtualOffset + 2, (int)message1Memory.VirtualCount - 2), out bool hasMore1); + // Consume 3rd payload + ArraySegment? payload3 = serverChannel.HandleIncomingMessagePoll(new ArraySegment(message3Memory.Buffer, (int)message3Memory.VirtualOffset + 2, (int)message3Memory.VirtualCount - 2), out bool hasMore3); + // Consume 2nd payload + ArraySegment? payload2 = serverChannel.HandleIncomingMessagePoll(new ArraySegment(message2Memory.Buffer, (int)message2Memory.VirtualOffset + 2, (int)message2Memory.VirtualCount - 2), out bool hasMore2); + + HeapMemory pollMemory = serverChannel.HandlePoll(); + + { + Assert.NotNull(payload1); + Assert.False(hasMore1); + + byte[] bytePayload = new byte[payload1.Value.Count]; + Array.Copy(payload1.Value.Array, payload1.Value.Offset, bytePayload, 0, payload1.Value.Count); + + Assert.AreEqual(message1, bytePayload); + } + + { + Assert.Null(payload3); + Assert.False(hasMore3); + } + + { + Assert.NotNull(payload2); + Assert.True(hasMore2); + + byte[] bytePayload = new byte[payload2.Value.Count]; + Array.Copy(payload2.Value.Array, payload2.Value.Offset, bytePayload, 0, payload2.Value.Count); + + Assert.AreEqual(message2, bytePayload); + } + + { + // Check for the third packet + Assert.NotNull(pollMemory); + + byte[] bytePayload = new byte[pollMemory.VirtualCount]; + Array.Copy(pollMemory.Buffer, pollMemory.VirtualOffset, bytePayload, 0, pollMemory.VirtualCount); + + Assert.AreEqual(message3, bytePayload); + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `pollMemory` last assigned on line 70 could be null and is dereferenced at line 101, column 17. + +### Severity: +ERROR + +### Procedure: +Void ReliableSequencedChannelTests.TestOutOfOrder() + +### File: +Ruffles.Tests/Channels/ReliableSequencedChannelTests.cs + +### Key: +ReliableSequencedChannelTests.cs|TestOutOfOrder|NULL_DEREFERENCE + +### Node Key: +4c5a0b70536cd3f04e9da256c6c8ae68 + +### Hash: +227b3b156d544bfee136c58068d5aba0 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0937/instruction.md b/inferredbugs-0937/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fcdc9cb1f60c45fdd76462211ad617f06059251b --- /dev/null +++ b/inferredbugs-0937/instruction.md @@ -0,0 +1,127 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** HttpMock +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Net; +using HttpMock; +using NUnit.Framework; + +namespace StubHttp +{ + [TestFixture] + public class MultipleTestsUsingTheSameStubServer + { + private IHttpEndpoint _httpEndpoint; + + [TestFixtureSetUp] + public void SetUp() { + _httpEndpoint = new HttpEndpoint().At("http://localhost:8081/"); + } + + [Test] + public void FirstTest() { + var wc = new WebClient(); + string stubbedReponse = "Response for first test"; + _httpEndpoint.WithNewContext() + .Stub(x => x.Post("/firsttest")) + .Return(stubbedReponse) + .OK(); + + Assert.That(wc.DownloadString("Http://localhost:8081/firsttest/"), Is.EqualTo(stubbedReponse)); + } + + [Test] + public void SecondTest() + { + var wc = new WebClient(); + string stubbedReponse = "Response for second test"; + _httpEndpoint.WithNewContext() + .Stub(x => x.Post("/secondtest")) + .Return(stubbedReponse).OK(); + + Assert.That(wc.DownloadString("Http://localhost:8081/secondtest/"), Is.EqualTo(stubbedReponse)); + } + + [Test] + public void Stubs_should_be_unique_within_context() + { + var wc = new WebClient(); + string stubbedReponseOne = "Response for first test in context"; + string stubbedReponseTwo = "Response for second test in context"; + + var stubHttp = _httpEndpoint.WithNewContext(); + + stubHttp + .Stub(x => x.Post("/firsttest")) + .Return(stubbedReponseOne).OK(); + + stubHttp + .Stub(x => x.Post("/secondtest")) + .Return(stubbedReponseTwo).OK(); + + Assert.That(wc.DownloadString("Http://localhost:8081/firsttest/"), Is.EqualTo(stubbedReponseOne)); + Assert.That(wc.DownloadString("Http://localhost:8081/secondtest/"), Is.EqualTo(stubbedReponseTwo)); + + } + + + [TestFixtureTearDown] + public void TearDown() { + _httpEndpoint.Dispose(); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of HttpMock.HttpEndpoint::.ctor() at Line 14) of type HttpMock.HttpEndpoint in method "Void MultipleTestsUsingTheSameStubServer.SetUp()". + +### Severity: +ERROR + +### Procedure: +Void MultipleTestsUsingTheSameStubServer.SetUp() + +### File: +src/HttpMock.Integration.Tests/MultipleTestsUsingTheSameStubServer.cs + +### Key: +MultipleTestsUsingTheSameStubServer.cs|SetUp|DOTNET_RESOURCE_LEAK + +### Hash: +cb930139a44f2849240e2fa5d8dc2dff + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0939/instruction.md b/inferredbugs-0939/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7a01aaf73d737be9c83bdcdf3e547be9cf033818 --- /dev/null +++ b/inferredbugs-0939/instruction.md @@ -0,0 +1,83 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** HttpMock +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using Kayak; + +namespace HttpMock +{ + public static class HttpMockRepository + { + private static readonly Dictionary _httpServers = new Dictionary(); + + public static IStubHttp At(Uri uri) + { + if (!_httpServers.ContainsKey(uri.Port)) { + HttpServer httpServer = HttpServerFactory.BuildServer(uri); + _httpServers.Add(uri.Port, httpServer); + } + return _httpServers[uri.Port].WithNewContext(uri.AbsolutePath); + } + + public static IStubHttp At(string uri) + { + return At(new Uri(uri)); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource httpServer of type HttpMock.HttpServer in method "IStubHttp HttpMockRepository.At(Uri)". + +### Severity: +ERROR + +### Procedure: +IStubHttp HttpMockRepository.At(Uri) + +### File: +src/HttpMock/HttpMockRepository.cs + +### Key: +HttpMockRepository.cs|At|DOTNET_RESOURCE_LEAK + +### Hash: +148b30ec2deda4053f03a9065915313a + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0953/instruction.md b/inferredbugs-0953/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bd2b2bb0cf24855b3b4f1dcbc0a8630ab73fce27 --- /dev/null +++ b/inferredbugs-0953/instruction.md @@ -0,0 +1,521 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** SampSharp +**Bug ID:** 9 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// SampSharp +// Copyright 2017 Tim Potze +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using System; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Text; +using SampSharp.Core.CodePages; +using SampSharp.Core.Communication.Clients; +using SampSharp.Core.Logging; + +namespace SampSharp.Core +{ + /// + /// Represents a configuration build for running a SampSharp game mode. + /// + public sealed class GameModeBuilder + { + private Func _builder; + private ICommunicationClient _communicationClient; + private GameModeExitBehaviour _exitBehaviour = GameModeExitBehaviour.ShutDown; + private IGameModeProvider _gameModeProvider; + private bool _redirectConsoleOutput; + private GameModeStartBehaviour _startBehaviour = GameModeStartBehaviour.Gmx; + private Encoding _encoding; + private bool _hosted; + + private const string DefaultUnixDomainSocketPath = "/tmp/SampSharp"; + private const string DefaultPipeName = "SampSharp"; + private const string DefaultTcpIp = "127.0.0.1"; + private const int DefaultTcpPort = 8888; + + + /// + /// Initializes a new instance of the class. + /// + public GameModeBuilder() + { + ParseArguments(); + } + + #region Communication + + /// + /// Use the specified communication client to communicate with the SampSharp server. + /// + /// The communication client. + /// The updated game mode configuration builder. + public GameModeBuilder UseCommunicationClient(ICommunicationClient communicationClient) + { + _communicationClient = communicationClient ?? throw new ArgumentNullException(nameof(communicationClient)); + + return this; + } + + /// + /// Use a named pipe with the specified to communicate with the SampSharp server. + /// + /// Name of the pipe. + /// The updated game mode configuration builder. + public GameModeBuilder UsePipe(string pipeName) + { + if (pipeName == null) throw new ArgumentNullException(nameof(pipeName)); + return UseCommunicationClient(new NamedPipeClient(pipeName)); + } + + /// + /// Use an unix domain socket with a file at the specified to communicate with the SampSharp + /// server. + /// + /// The path to the domain socket file. + /// The updated game mode configuration builder. + public GameModeBuilder UseUnixDomainSocket(string path) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + return UseCommunicationClient(new UnixDomainSocketCommunicationClient(path)); + } + + /// + /// Use a TCP client to communicate with the SampSharp server on localhost. + /// + /// The port on which to connect. + /// The updated game mode configuration builder. + public GameModeBuilder UseTcpClient(int port) + { + return UseCommunicationClient(new TcpCommunicationClient(DefaultTcpIp, port)); + } + + /// + /// Use a TCP client to communicate with the SampSharp server. + /// + /// The host to which to connect. + /// The port on which to connect. + /// The updated game mode configuration builder. + public GameModeBuilder UseTcpClient(string host, int port) + { + if (host == null) throw new ArgumentNullException(nameof(host)); + return UseCommunicationClient(new TcpCommunicationClient(host, port)); + } + + #endregion + + #region Encoding + + /// + /// Use the specified when en/decoding text messages sent to/from the server. + /// + /// The encoding to use when en/decoding text messages send to/from the server. + /// The updated game mode configuration builder. + public GameModeBuilder UseEncoding(Encoding encoding) + { + _encoding = encoding ?? throw new ArgumentNullException(nameof(encoding)); + return this; + } + + /// + /// Use the code page described by the file at the specified when en/decoding text messages sent to/from the server. + /// + /// The path to the code page file. + /// The updated game mode configuration builder. + public GameModeBuilder UseEncoding(string path) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + return UseEncoding(CodePageEncoding.Load(path)); + } + + /// + /// Use the code page described by the specified when en/decoding text messages sent to/from the server. + /// + /// The stream containing the code page definition. + /// The updated game mode configuration builder. + public GameModeBuilder UseEncoding(Stream stream) + { + return UseEncoding(CodePageEncoding.Load(stream)); + } + + #endregion + + #region Game Mode Provider + + /// + /// Use the specified game mode. + /// + /// The game mode to use. + /// The updated game mode configuration builder. + public GameModeBuilder Use(IGameModeProvider gameMode) + { + _gameModeProvider = gameMode ?? throw new ArgumentNullException(nameof(gameMode)); + return this; + } + + /// + /// Use the gamemode of the specified type. + /// + /// The type of the game mode to use. + /// The updated game mode configuration builder. + public GameModeBuilder Use() where TGameMode : IGameModeProvider + { + return Use(Activator.CreateInstance()); + } + + #endregion + + /// + /// Redirect the console output to the server. + /// + /// The updated game mode configuration builder. + public GameModeBuilder RedirectConsoleOutput() + { + _redirectConsoleOutput = true; + return this; + } + + #region Logging + + /// + /// Uses the specified log level as the maximum level which is written to the log by SampSharp. + /// + /// The log level. + /// The updated game mode configuration builder. + public GameModeBuilder UseLogLevel(CoreLogLevel logLevel) + { + CoreLog.LogLevel = logLevel; + return this; + } + + /// + /// Uses the specified stream to log SampSharp log messages to. + /// + /// The stream to log SampSharp log messages to. + /// If a null value is specified as stream, no log messages will appear. + /// The updated game mode configuration builder. + public GameModeBuilder UseLogStream(Stream stream) + { + CoreLog.Stream = stream; + return this; + } + + #endregion + + /// + /// Indicate the game mode will be hosted in the SA-MP server process. + /// + /// The updated game mode configuration builder. + public GameModeBuilder UseHosted() + { + _hosted = true; + return RedirectConsoleOutput(); + } + + /// + /// Sets the behaviour used once a OnGameModeExit call has been received. + /// + /// The exit behaviour. + /// The exit behaviour is ignored when using a hosted game mode environment. + /// The updated game mode configuration builder. + public GameModeBuilder UseExitBehaviour(GameModeExitBehaviour exitBehaviour) + { + _exitBehaviour = exitBehaviour; + return this; + } + + + /// + /// Use the specified start method when attaching to the server. + /// + /// The start behaviour. + /// The updated game mode configuration builder. + public GameModeBuilder UseStartBehaviour(GameModeStartBehaviour startBehaviour) + { + _startBehaviour = startBehaviour; + return this; + } + + /// + /// Use a custom build procedure to load a custom game mode client. + /// + /// The building function. + /// The updated game mode configuration builder. + public GameModeBuilder BuildWith(Func builder) + { + _builder = builder; + return this; + } + + + /// + /// Run the game mode using the build configuration stored in this instance. + /// + public void Run() + { + ApplyDefaults(); + + if (!_hosted && _communicationClient == null) + throw new GameModeBuilderException("No communication client has been specified"); + if (_gameModeProvider == null) + throw new GameModeBuilderException("No game mode provider has been specified"); + + var redirect = _redirectConsoleOutput; + + var runner = Build(); + + if (runner == null) + { + return; + } + + if (redirect) + { + Console.SetOut(new ServerLogWriter(runner.Client)); + } + + if (_hosted) + { + // Ignore exit behaviours for hosted environments. + runner.Run(); + } + else + { + do + { + // If true is returned, the runner wants to shut down. + if (runner.Run()) + { + break; + } + + } while (_exitBehaviour == GameModeExitBehaviour.Restart); + + if (redirect) + Console.SetOut(new StreamWriter(Console.OpenStandardOutput())); + } + } + + private void ParseArguments() + { + var args = Environment.GetCommandLineArgs(); + + if (args == null || args.Length == 0) + { + return; + } + + for (int i = 0; i < args.Length; i++) + { + string option = null; + string value; + if (args[i].Length < 2 || !args[i].StartsWith("-")) + continue; + + if (args[i].StartsWith("--")) + { + option = args[i]; + value = args.Length > i + 1 + ? args[i + 1] + : null; + } + else + { + option = args[i].Substring(0, 2); + value = args[i].Length > 2 + ? args[i].Substring(2) + : args.Length > i + 1 + ? args[i + 1] + : null; + } + + switch (option) + { + case "--hosted": + case "-h": + UseHosted(); + break; + case "--redirect-console-output": + case "-r": + RedirectConsoleOutput(); + break; + case "--pipe": + case "-p": + if (value != null && !value.StartsWith("-")) + { + UsePipe(value); + i++; + } + else + { + UsePipe(DefaultPipeName); + } + break; + case "--unix": + case "-u": + if (value != null && !value.StartsWith("-")) + { + UseUnixDomainSocket(value); + i++; + } + else + { + UseUnixDomainSocket(DefaultUnixDomainSocketPath); + } + break; + case "--tcp": + var ip = DefaultTcpIp; + var port = DefaultTcpPort; + + if (value != null && !value.StartsWith("-")) + { + var colon = value.IndexOf(":", StringComparison.Ordinal); + + if (colon < 0) + { + if (IPAddress.TryParse(value.Substring(0, colon), out var addr) && addr.AddressFamily == AddressFamily.InterNetwork) + ip = value.Substring(0, colon); + int.TryParse(value.Substring(colon + 1), out port); + } + else + { + int.TryParse(value, out port); + } + + i++; + } + + UseTcpClient(ip, port); + break; + case "--log-level": + case "-l": + if (value == null) + break; + + if (Enum.TryParse(value, out var level)) + UseLogLevel(level); + + i++; + break; + case "--start-behaviour": + case "-s": + if (value == null) + break; + + if (Enum.TryParse(value, out var startBehaviour)) + UseStartBehaviour(startBehaviour); + + i++; + break; + case "--exit-behaviour": + case "-e": + if (value == null) + break; + + if (Enum.TryParse(value, out var exitBehaviour)) + UseExitBehaviour(exitBehaviour); + + i++; + break; + } + } + } + + private void ApplyDefaults() + { + if (_communicationClient == null && !_hosted) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + _communicationClient = new UnixDomainSocketCommunicationClient(DefaultUnixDomainSocketPath); + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + _communicationClient = new NamedPipeClient(DefaultPipeName); + } + } + + private IGameModeRunner Build() + { + if (_builder != null) + { + return _builder(_communicationClient, _startBehaviour, _gameModeProvider); + } + + if (_hosted) + { + return new HostedGameModeClient(_startBehaviour, _gameModeProvider, _encoding); + } + else + { + return new MultiProcessGameModeClient(_communicationClient, _startBehaviour, _gameModeProvider, _encoding); + } + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource runner.SampSharp.Core.MultiProcessGameModeClient._commandWaitQueue.SampSharp.Core.Threading.CommandWaitQueue._semaphore of type System.Threading.SemaphoreSlim, Leaked resource (output of System.IO.StreamWriter::.ctor() at Line 306) of type System.IO.StreamWriter, Leaked resource (output of SampSharp.Core.ServerLogWriter::.ctor() at Line 285) of type SampSharp.Core.ServerLogWriter in method "Void GameModeBuilder.Run()". + +### Severity: +ERROR + +### Procedure: +Void GameModeBuilder.Run() + +### File: +src/SampSharp.Core/GameModeBuilder.cs + +### Key: +GameModeBuilder.cs|Run|DOTNET_RESOURCE_LEAK + +### Hash: +7822f4093e39a71784a119a78138c76f + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0954/instruction.md b/inferredbugs-0954/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a35e15c99f2451e667fa742155afd1af44c8319c --- /dev/null +++ b/inferredbugs-0954/instruction.md @@ -0,0 +1,94 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** SampSharp +**Bug ID:** 7 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// SampSharp +// Copyright 2017 Tim Potze +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using System; +using SampSharp.Core; +using SampSharp.Core.Logging; + +namespace TestMode +{ + internal class Program + { + private static void Main(string[] args) + { + Console.WriteLine("ARGS: " + string.Join(" ", Environment.GetCommandLineArgs())); + + new GameModeBuilder() + .UseLogLevel(CoreLogLevel.Debug) + .UseHosted() + .UseStartBehaviour(GameModeStartBehaviour.FakeGmx) + .Use() + .Run(); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +in method "Void Program.Main(String[])". + +### Severity: +ERROR + +### Procedure: +Void Program.Main(String[]) + +### File: +src/TestMode.DotNetCore/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +821f2677df83c24a83fd108b595805d1 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0955/instruction.md b/inferredbugs-0955/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..123cc505dece39e1aef1f7394be320e01710be58 --- /dev/null +++ b/inferredbugs-0955/instruction.md @@ -0,0 +1,282 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** SampSharp +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// SampSharp +// Copyright 2017 Tim Potze +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using System; +using System.IO; +using System.Runtime.InteropServices; +using SampSharp.Core.Communication.Clients; +using SampSharp.Core.Logging; + +namespace SampSharp.Core +{ + /// + /// Represents a configuration build for running a SampSharp game mode. + /// + public sealed class GameModeBuilder + { + private Func _builder; + private ICommunicationClient _communicationClient; + private GameModeExitBehaviour _exitBehaviour = GameModeExitBehaviour.ShutDown; + private IGameModeProvider _gameModeProvider; + private bool _redirectConsoleOutput; + private GameModeStartBehaviour _startBehaviour = GameModeStartBehaviour.Gmx; + + + /// + /// Initializes a new instance of the class. + /// + public GameModeBuilder() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + _communicationClient = new UnixDomainSocketCommunicationClient("/tmp/SampSharp"); + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + _communicationClient = new NamedPipeClient("SampSharp"); + } + + /// + /// Use a named pipe with the specified to communicate with the SampSharp server. + /// + /// Name of the pipe. + /// The updated game mode configuration builder. + public GameModeBuilder UsePipe(string pipeName) + { + if (pipeName == null) throw new ArgumentNullException(nameof(pipeName)); + return UseCommunicationClient(new NamedPipeClient(pipeName)); + } + + /// + /// Use an unix domain socket with a file at the specified to communicate with the SampSharp + /// server. + /// + /// The path to the domain socket file. + /// The updated game mode configuration builder. + public GameModeBuilder UseUnixDomainSocket(string path) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + return UseCommunicationClient(new UnixDomainSocketCommunicationClient(path)); + } + + /// + /// Use a TCP client to communicate with the SampSharp server on localhost. + /// + /// The port on which to connect. + /// The updated game mode configuration builder. + public GameModeBuilder UseTcpClient(int port) + { + return UseCommunicationClient(new TcpCommunicationClient("127.0.0.1", port)); + } + + /// + /// Use a TCP client to communicate with the SampSharp server. + /// + /// The host to which to connect. + /// The port on which to connect. + /// The updated game mode configuration builder. + public GameModeBuilder UseTcpClient(string host, int port) + { + if (host == null) throw new ArgumentNullException(nameof(host)); + return UseCommunicationClient(new TcpCommunicationClient(host, port)); + } + + /// + /// Use the specified communication client to communicate with the SampSharp server. + /// + /// The communication client. + /// The updated game mode configuration builder. + public GameModeBuilder UseCommunicationClient(ICommunicationClient communicationClient) + { + _communicationClient = communicationClient ?? throw new ArgumentNullException(nameof(communicationClient)); + return this; + } + + /// + /// Redirect the console output to the server. + /// + /// The updated game mode configuration builder. + public GameModeBuilder RedirectConsoleOutput() + { + _redirectConsoleOutput = true; + return this; + } + + /// + /// Use the specified game mode. + /// + /// The game mode to use. + /// The updated game mode configuration builder. + public GameModeBuilder Use(IGameModeProvider gameMode) + { + _gameModeProvider = gameMode ?? throw new ArgumentNullException(nameof(gameMode)); + return this; + } + + /// + /// Use the gamemode of the specified type. + /// + /// The type of the game mode to use. + /// The updated game mode configuration builder. + public GameModeBuilder Use() where TGameMode : IGameModeProvider + { + return Use(Activator.CreateInstance()); + } + + /// + /// Uses the specified log level as the maximum level which is written to the log by SampSharp. + /// + /// The log level. + /// The updated game mode configuration builder. + public GameModeBuilder UseLogLevel(CoreLogLevel logLevel) + { + CoreLog.LogLevel = logLevel; + return this; + } + + /// + /// Uses the specified stream to log SampSharp log messages to. + /// + /// The stream to log SampSharp log messages to. + /// If a null value is specified as stream, no log messages will appear. + /// The updated game mode configuration builder. + public GameModeBuilder UseLogStream(Stream stream) + { + CoreLog.Stream = stream; + return this; + } + + /// + /// Sets the behaviour used once a OnGameModeExit call has been received. + /// + /// The exit behaviour. + /// The updated game mode configuration builder. + public GameModeBuilder UseExitBehaviour(GameModeExitBehaviour exitBehaviour) + { + _exitBehaviour = exitBehaviour; + return this; + } + + + /// + /// Use the specified start method when attaching to the server. + /// + /// The start behaviour. + /// The updated game mode configuration builder. + public GameModeBuilder UseStartBehaviour(GameModeStartBehaviour startBehaviour) + { + _startBehaviour = startBehaviour; + return this; + } + + /// + /// Use a custom build procedure to load a custom game mode client. + /// + /// The building function. + /// The updated game mode configuration builder. + public GameModeBuilder BuildWith(Func builder) + { + _builder = builder; + return this; + } + + + /// + /// Run the game mode using the build configuration stored in this instance. + /// + public void Run() + { + if (_communicationClient == null) + throw new GameModeBuilderException("No communication client has been specified"); + if (_gameModeProvider == null) + throw new GameModeBuilderException("No game mode provider has been specified"); + + var redirect = _redirectConsoleOutput; + + var runner = Build(); + if (redirect) + Console.SetOut(new ServerLogWriter(runner.Client)); + + do + { + runner.Run(); + } while (_exitBehaviour == GameModeExitBehaviour.Restart); + + if (redirect) + Console.SetOut(new StreamWriter(Console.OpenStandardOutput())); + } + + private IGameModeRunner Build() + { + return _builder?.Invoke(_communicationClient, _startBehaviour, _gameModeProvider) + ?? new GameModeClient(_communicationClient, _startBehaviour, _gameModeProvider); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of System.IO.StreamWriter::.ctor() at Line 215) of type System.IO.StreamWriter, Leaked resource (output of SampSharp.Core.ServerLogWriter::.ctor() at Line 207) of type SampSharp.Core.ServerLogWriter in method "Void GameModeBuilder.Run()". + +### Severity: +ERROR + +### Procedure: +Void GameModeBuilder.Run() + +### File: +src/SampSharp.Core/GameModeBuilder.cs + +### Key: +GameModeBuilder.cs|Run|DOTNET_RESOURCE_LEAK + +### Hash: +7443f6eb54bfa61fc9b39b5a57f5ef0e + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0962/instruction.md b/inferredbugs-0962/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1ea6ee971d721ffdd6fcb7abeb014c4e8b879996 --- /dev/null +++ b/inferredbugs-0962/instruction.md @@ -0,0 +1,143 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** SampSharp +**Bug ID:** 5 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using RiverShell.World; +using SampSharp.GameMode; +using SampSharp.GameMode.Controllers; +using SampSharp.GameMode.Definitions; +using SampSharp.GameMode.Natives; +using SampSharp.GameMode.SAMP; +using SampSharp.GameMode.World; +using SampSharp.GameMode.Events; + +namespace RiverShell.Controllers +{ + public class ObjectiveController : IEventListener, IController + { + public void RegisterEvents(BaseMode gameMode) + { + gameMode.PlayerEnterCheckpoint += gameMode_PlayerEnterCheckpoint; + gameMode.PlayerStateChanged += gameMode_PlayerStateChanged; + } + + private void gameMode_PlayerStateChanged(object sender, PlayerStateEventArgs e) + { + var player = e.Player as RPlayer; + + switch (e.NewState) + { + case PlayerState.Driving: + if (player.Vehicle == player.Team.TargetVehicle) + { + // It's the objective vehicle + player.Color = 0xE2C063FF; + player.GameText("~w~Take the ~y~boat ~w~back to the ~r~spawn!", 3000, 5); + player.SetCheckpoint(player.Team.Target, 10.0f); + } + break; + case PlayerState.OnFoot: + player.Color = player.Team.Color; + player.DisableCheckpoint(); + break; + } + } + + private void gameMode_PlayerEnterCheckpoint(object sender, PlayerEventArgs e) + { + var player = e.Player as RPlayer; + + var vehicle = player.Vehicle; + + //Check if game's already over + if (GameMode.ObjectiveReached) + return; + + //Check if we're in target vehicle + if (vehicle != player.Team.TargetVehicle) return; + + // objective reached. + player.Team.TimesCaptured++; + player.Score += 5; + + if (player.Team.TimesCaptured == Config.CapturesToWin) + { + RPlayer.GameTextForAll(string.Format("{0} wins!", player.Team.GameTextTeamName), 3000, 5); + GameMode.ObjectiveReached = true; + foreach (var p in RPlayer.All) + p.PlaySound(1185); + + var exitTimer = new Timer(6000, false); + exitTimer.Tick += (tsender, args) => + { + foreach (var p in RPlayer.All) + p.PlaySound(1186); + Native.GameModeExit(); + }; + } + else + { + RPlayer.GameTextForAll(string.Format("{0} captured the ~y~boat!", player.Team.GameTextTeamName), 3000, 5); + vehicle.Respawn(); + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `player` last assigned on line 22 could be null and is dereferenced at line 27, column 21. + +### Severity: +ERROR + +### Procedure: +Void ObjectiveController.gameMode_PlayerStateChanged(Object,PlayerStateEventArgs) + +### File: +source/RiverShell/Controllers/ObjectiveController.cs + +### Key: +ObjectiveController.cs|gameMode_PlayerStateChanged|NULL_DEREFERENCE + +### Node Key: +0a2f2289efc1b4f27401d167fdf3ab36 + +### Hash: +1974753c34df4dee7c499f66d15fce6e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0963/instruction.md b/inferredbugs-0963/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c43b7fc88ee19e5eaac5026572d77707f65ef95f --- /dev/null +++ b/inferredbugs-0963/instruction.md @@ -0,0 +1,738 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** YamlDotNet +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// This file is part of YamlDotNet - A .NET library for YAML. +// Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Antoine Aubry + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; + +namespace YamlDotNet.RepresentationModel.Serialization +{ + /// + /// Options that control the deserialization process. + /// + [Flags] + public enum DeserializationFlags + { + /// + /// Serializes using the default options + /// + None = 0, + + ///// + ///// Ensures that it will be possible to deserialize the serialized objects. + ///// + //Roundtrip = 1, + + ///// + ///// If this flag is specified, if the same object appears more than once in the + ///// serialization graph, it will be serialized each time instead of just once. + ///// + ///// + ///// If the serialization graph contains circular references and this flag is set, + ///// a will be thrown. + ///// If this flag is not set, there is a performance penalty because the entire + ///// object graph must be walked twice. + ///// + //DisableAliases = 2, + + ///// + ///// Forces every value to be serialized, even if it is the default value for that type. + ///// + //EmitDefaults = 4, + + /// + /// Ensures that the result of the serialization is valid JSON. + /// + JsonCompatible = 8, + } + + /// + /// Reads objects from YAML. + /// + public class Deserializer + { + private readonly IEnumerable _deserializers; + private readonly IEnumerable _typeResolvers; + + public Deserializer() + { + // TODO: Allow to override the object factory + var objectFactory = new DefaultObjectFactory(); + + _deserializers = new INodeDeserializer[] + { + new NullNodeDeserializer(), + new ScalarNodeDeserializer(), + new GenericDictionaryDeserializer(objectFactory), + new NonGenericDictionaryDeserializer(objectFactory), + new GenericCollectionDeserializer(objectFactory), + new NonGenericListDeserializer(objectFactory), + new EnumerableDeserializer(), + new ObjectNodeDeserializer(objectFactory), + }; + + _typeResolvers = new INodeTypeResolver[] + { + new PredefinedTagsNodeTypeResolver(), + new TypeNameInTagNodeTypeResolver(), + new DefaultContainersNodeTypeResolver(), + }; + } + + public object Deserialize(TextReader input, DeserializationFlags options = DeserializationFlags.None) + { + return Deserialize(input, typeof(object), options); + } + + public object Deserialize(TextReader input, Type type, DeserializationFlags options = DeserializationFlags.None) + { + return Deserialize(new EventReader(new Parser(input)), type, options); + } + + public object Deserialize(EventReader reader, DeserializationFlags options = DeserializationFlags.None) + { + return Deserialize(reader, typeof(object), options); + } + + /// + /// Deserializes an object of the specified type. + /// + /// The where to deserialize the object. + /// The static type of the object to deserialize. + /// Options that control how the deserialization is to be performed. + /// Returns the deserialized object. + public object Deserialize(EventReader reader, Type type, DeserializationFlags options = DeserializationFlags.None) + { + if (reader == null) + { + throw new ArgumentNullException("reader"); + } + + if (type == null) + { + throw new ArgumentNullException("type"); + } + + var hasStreamStart = reader.Allow() != null; + + var hasDocumentStart = reader.Allow() != null; + + object result = DeserializeValue(reader, type, null); + + if (hasDocumentStart) + { + reader.Expect(); + } + + if (hasStreamStart) + { + reader.Expect(); + } + + return result; + } + + private object DeserializeValue(EventReader reader, Type expectedType, object context) + { + var nodeEvent = reader.Peek(); + + var nodeType = GetTypeFromEvent(nodeEvent, expectedType); + + foreach (var deserializer in _deserializers) + { + object value; + if (deserializer.Deserialize(reader, nodeType, (r, t) => DeserializeValue(r, t, context), out value)) + { + return value; + } + } + + throw new Exception("TODO"); + + //return deserializer.Deserialize(reader, expectedType); + + //if (reader.Accept()) + //{ + // throw new NotImplementedException(); + // //return context.Anchors[reader.Expect().Value]; + //} + + //var nodeEvent = (NodeEvent)reader.Parser.Current; + + //if (IsNull(nodeEvent)) + //{ + // reader.Expect(); + // AddAnchoredObject(nodeEvent, null, context.Anchors); + // return null; + //} + + //object result = DeserializeValueNotNull(reader, context, nodeEvent, expectedType); + //return ObjectConverter.Convert(result, expectedType); + } + + //private bool IsNull(NodeEvent nodeEvent) + //{ + // if (nodeEvent.Tag == "tag:yaml.org,2002:null") + // { + // return true; + // } + + // if (JsonCompatible) + // { + // var scalar = nodeEvent as Scalar; + // if (scalar != null && scalar.Style == Core.ScalarStyle.Plain && scalar.Value == "null") + // { + // return true; + // } + // } + + // return false; + //} + + + private Type GetTypeFromEvent(NodeEvent nodeEvent, Type currentType)//, TagMappings mappings) + { + foreach (var typeResolver in _typeResolvers) + { + if (typeResolver.Resolve(nodeEvent, ref currentType)) + { + break; + } + } + return currentType; + } + } + + public interface INodeTypeResolver + { + /// + /// Determines the type of the specified node. + /// + /// The node to be deserialized. + /// The type that has been determined so far. + /// + /// true if has been resolved completely; + /// false if the next type should be invoked. + /// + bool Resolve(NodeEvent nodeEvent, ref Type currentType); + } + + public sealed class PredefinedTagsNodeTypeResolver : INodeTypeResolver + { + private static readonly Dictionary predefinedTypes = new Dictionary + { + { "tag:yaml.org,2002:map", typeof(Dictionary) }, + { "tag:yaml.org,2002:bool", typeof(bool) }, + { "tag:yaml.org,2002:float", typeof(double) }, + { "tag:yaml.org,2002:int", typeof(int) }, + { "tag:yaml.org,2002:str", typeof(string) }, + { "tag:yaml.org,2002:timestamp", typeof(DateTime) }, + }; + + bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType) + { + Type predefinedType; + if (!string.IsNullOrEmpty(nodeEvent.Tag) && predefinedTypes.TryGetValue(nodeEvent.Tag, out predefinedType)) + { + currentType = predefinedType; + return true; + } + return false; + } + } + + public sealed class DefaultContainersNodeTypeResolver : INodeTypeResolver + { + bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType) + { + if (currentType == typeof(object)) + { + if (nodeEvent is SequenceStart) + { + currentType = typeof(List); + return true; + } + if (nodeEvent is MappingStart) + { + currentType = typeof(Dictionary); + return true; + } + } + + return false; + } + } + + public sealed class TypeNameInTagNodeTypeResolver : INodeTypeResolver + { + bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType) + { + if (!string.IsNullOrEmpty(nodeEvent.Tag)) + { + currentType = Type.GetType(nodeEvent.Tag.Substring(1), true); + return true; + } + return false; + } + } + + public interface INodeDeserializer + { + bool Deserialize(EventReader reader, Type expectedType, Func nestedObjectDeserializer, out object value); + } + + public sealed class NullNodeDeserializer : INodeDeserializer + { + bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func nestedObjectDeserializer, out object value) + { + value = null; + var evt = reader.Peek(); + var isNull = evt != null + && evt.Tag == "tag:yaml.org,2002:null"; + + if (isNull) + { + reader.Skip(); + } + return isNull; + } + } + + public sealed class JsonNullNodeDeserializer : INodeDeserializer + { + bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func nestedObjectDeserializer, out object value) + { + value = null; + var scalar = reader.Peek(); + var isNull = scalar != null + && scalar.Style == Core.ScalarStyle.Plain + && scalar.Value == "null"; + + if (isNull) + { + reader.Skip(); + } + return isNull; + } + } + + public sealed class ScalarNodeDeserializer : INodeDeserializer + { + bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func nestedObjectDeserializer, out object value) + { + var scalar = reader.Allow(); + if (scalar == null) + { + value = null; + return false; + } + + if (expectedType.IsEnum) + { + value = Enum.Parse(expectedType, scalar.Value); + } + else + { + TypeCode typeCode = Type.GetTypeCode(expectedType); + switch (typeCode) + { + case TypeCode.Boolean: + value = bool.Parse(scalar.Value); + break; + + case TypeCode.Byte: + value = Byte.Parse(scalar.Value, numberFormat); + break; + + case TypeCode.Int16: + value = Int16.Parse(scalar.Value, numberFormat); + break; + + case TypeCode.Int32: + value = Int32.Parse(scalar.Value, numberFormat); + break; + + case TypeCode.Int64: + value = Int64.Parse(scalar.Value, numberFormat); + break; + + case TypeCode.SByte: + value = SByte.Parse(scalar.Value, numberFormat); + break; + + case TypeCode.UInt16: + value = UInt16.Parse(scalar.Value, numberFormat); + break; + + case TypeCode.UInt32: + value = UInt32.Parse(scalar.Value, numberFormat); + break; + + case TypeCode.UInt64: + value = UInt64.Parse(scalar.Value, numberFormat); + break; + + case TypeCode.Single: + value = Single.Parse(scalar.Value, numberFormat); + break; + + case TypeCode.Double: + value = Double.Parse(scalar.Value, numberFormat); + break; + + case TypeCode.Decimal: + value = Decimal.Parse(scalar.Value, numberFormat); + break; + + case TypeCode.String: + value = scalar.Value; + break; + + case TypeCode.Char: + value = scalar.Value[0]; + break; + + case TypeCode.DateTime: + // TODO: This is probably incorrect. Use the correct regular expression. + value = DateTime.Parse(scalar.Value, CultureInfo.InvariantCulture); + break; + + default: + if (expectedType == typeof(object)) + { + // Default to string + value = scalar.Value; + } + else + { + TypeConverter converter = TypeDescriptor.GetConverter(expectedType); + if (converter != null && converter.CanConvertFrom(typeof(string))) + { + value = converter.ConvertFromInvariantString(scalar.Value); + } + else + { + value = Convert.ChangeType(scalar.Value, expectedType, CultureInfo.InvariantCulture); + } + } + break; + } + } + return true; + } + + private static readonly NumberFormatInfo numberFormat = new NumberFormatInfo + { + CurrencyDecimalSeparator = ".", + CurrencyGroupSeparator = "_", + CurrencyGroupSizes = new[] { 3 }, + CurrencySymbol = string.Empty, + CurrencyDecimalDigits = 99, + NumberDecimalSeparator = ".", + NumberGroupSeparator = "_", + NumberGroupSizes = new[] { 3 }, + NumberDecimalDigits = 99 + }; + } + + public sealed class ObjectNodeDeserializer : INodeDeserializer + { + private readonly IObjectFactory _objectFactory; + + public ObjectNodeDeserializer(IObjectFactory objectFactory) + { + _objectFactory = objectFactory; + } + + bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func nestedObjectDeserializer, out object value) + { + var mapping = reader.Allow(); + if (mapping == null) + { + value = null; + return false; + } + + value = _objectFactory.Create(expectedType); + while (!reader.Accept()) + { + var propertyName = reader.Expect(); + + // TODO: Find property according to naming conventions + var property = expectedType.GetProperty(propertyName.Value, BindingFlags.Instance | BindingFlags.Public); + var propertyValue = nestedObjectDeserializer(reader, property.PropertyType); + property.SetValue(value, propertyValue, null); + } + + reader.Expect(); + return true; + } + } + + public sealed class GenericDictionaryDeserializer : INodeDeserializer + { + private readonly IObjectFactory _objectFactory; + + public GenericDictionaryDeserializer(IObjectFactory objectFactory) + { + _objectFactory = objectFactory; + } + + bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func nestedObjectDeserializer, out object value) + { + var iDictionary = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IDictionary<,>)); + if (iDictionary == null) + { + value = false; + return false; + } + + reader.Expect(); + + value = _objectFactory.Create(expectedType); + _deserializeHelperMethod + .MakeGenericMethod(iDictionary.GetGenericArguments()) + .Invoke(null, new object[] { reader, expectedType, nestedObjectDeserializer, value }); + + reader.Expect(); + + return true; + } + + private static MethodInfo _deserializeHelperMethod = typeof(GenericDictionaryDeserializer) + .GetMethod("DeserializeHelper", BindingFlags.Static | BindingFlags.NonPublic); + + private static void DeserializeHelper(EventReader reader, Type expectedType, Func nestedObjectDeserializer, IDictionary result) + { + while (!reader.Accept()) + { + var key = (TKey)nestedObjectDeserializer(reader, typeof(TKey)); + var value = (TValue)nestedObjectDeserializer(reader, typeof(TValue)); + result.Add(key, value); + } + } + } + + public sealed class NonGenericDictionaryDeserializer : INodeDeserializer + { + private readonly IObjectFactory _objectFactory; + + public NonGenericDictionaryDeserializer(IObjectFactory objectFactory) + { + _objectFactory = objectFactory; + } + + bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func nestedObjectDeserializer, out object value) + { + if(!typeof(IDictionary).IsAssignableFrom(expectedType)) + { + value = false; + return false; + } + + reader.Expect(); + + var dictionary = (IDictionary)_objectFactory.Create(expectedType); + while (!reader.Accept()) + { + var key = nestedObjectDeserializer(reader, typeof(object)); + var keyValue = nestedObjectDeserializer(reader, typeof(object)); + dictionary.Add(key, keyValue); + } + value = dictionary; + + reader.Expect(); + + return true; + } + } + + public sealed class GenericCollectionDeserializer : INodeDeserializer + { + private readonly IObjectFactory _objectFactory; + + public GenericCollectionDeserializer(IObjectFactory objectFactory) + { + _objectFactory = objectFactory; + } + + bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func nestedObjectDeserializer, out object value) + { + var iCollection = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(ICollection<>)); + if (iCollection == null) + { + value = false; + return false; + } + + reader.Expect(); + + value = _objectFactory.Create(expectedType); + _deserializeHelperMethod + .MakeGenericMethod(iCollection.GetGenericArguments()) + .Invoke(null, new object[] { reader, expectedType, nestedObjectDeserializer, value }); + + reader.Expect(); + + return true; + } + + private static MethodInfo _deserializeHelperMethod = typeof(GenericCollectionDeserializer) + .GetMethod("DeserializeHelper", BindingFlags.Static | BindingFlags.NonPublic); + + private static void DeserializeHelper(EventReader reader, Type expectedType, Func nestedObjectDeserializer, ICollection result) + { + while (!reader.Accept()) + { + var value = (TItem)nestedObjectDeserializer(reader, typeof(TItem)); + result.Add(value); + } + } + } + + public sealed class NonGenericListDeserializer : INodeDeserializer + { + private readonly IObjectFactory _objectFactory; + + public NonGenericListDeserializer(IObjectFactory objectFactory) + { + _objectFactory = objectFactory; + } + + bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func nestedObjectDeserializer, out object value) + { + if (!typeof(IList).IsAssignableFrom(expectedType)) + { + value = false; + return false; + } + + reader.Expect(); + + var list = (IList)_objectFactory.Create(expectedType); + while (!reader.Accept()) + { + var item = nestedObjectDeserializer(reader, typeof(object)); + list.Add(item); + } + value = list; + + reader.Expect(); + + return true; + } + } + + public sealed class EnumerableDeserializer : INodeDeserializer + { + bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func nestedObjectDeserializer, out object value) + { + Type itemsType; + if (expectedType == typeof(IEnumerable)) + { + itemsType = typeof(object); + } + else + { + var iEnumerable = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IEnumerable<>)); + if (iEnumerable != expectedType) + { + value = null; + return false; + } + + itemsType = iEnumerable.GetGenericArguments()[0]; + } + + var collectionType = typeof(List<>).MakeGenericType(itemsType); + value = nestedObjectDeserializer(reader, collectionType); + return true; + } + } + +} +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`iEnumerable` could be null (from the call to `ReflectionUtility.GetImplementedGenericInterface(...)` on line 664) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +Boolean EnumerableDeserializer.YamlDotNet.RepresentationModel.Serialization.INodeDeserializer.Deserialize(EventReader,Type,Func`3,Object&) + +### File: +YamlDotNet.RepresentationModel/Serialization/Deserializer.cs + +### Key: +Deserializer.cs|YamlDotNet.RepresentationModel.Serialization.INodeDeserializer.Deserialize|NULLPTR_DEREFERENCE + +### Hash: +c2d42f277f8da5c838a5bde211bb590b + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0964/instruction.md b/inferredbugs-0964/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8e8a8a8afbdb7d4aa4fb5e4edb5f6c3f893a461a --- /dev/null +++ b/inferredbugs-0964/instruction.md @@ -0,0 +1,93 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Disqord +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Threading.Tasks; +using Disqord.Gateway.Api; +using Disqord.Gateway.Api.Models; + +namespace Disqord.Gateway.Default.Dispatcher +{ + public class GuildMemberUpdateHandler : Handler + { + public override ValueTask HandleDispatchAsync(IGatewayApiClient shard, GuildMemberUpdateJsonModel model) + { + CachedMember oldMember; + IMember newMember; + if (CacheProvider.TryGetMembers(model.GuildId, out var cache) && cache.TryGetValue(model.User.Value.Id, out var member)) + { + newMember = member; + var oldUser = member.SharedUser.Clone() as CachedSharedUser; + oldMember = member.Clone() as CachedMember; + oldMember.SharedUser = oldUser; + newMember.Update(model); + } + else + { + oldMember = null; + newMember = new TransientMember(Client, model.GuildId, model); + } + + var e = new MemberUpdatedEventArgs(oldMember, newMember); + return new(e); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `oldMember` last assigned on line 19 could be null and is dereferenced at line 20, column 17. + +### Severity: +ERROR + +### Procedure: +ValueTask`1 GuildMemberUpdateDispatchHandler.HandleDispatchAsync(IShard,GuildMemberUpdateJsonModel) + +### File: +src/Disqord.Gateway/Default/Dispatcher/Dispatches/Member/GUILD_MEMBER_UPDATE.cs + +### Key: +GUILD_MEMBER_UPDATE.cs|HandleDispatchAsync|NULL_DEREFERENCE + +### Node Key: +5f12004af86bc692e0983547f0c7b710 + +### Hash: +44209158cda04dd4adb48f6583f52fa4 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0965/instruction.md b/inferredbugs-0965/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8cea1a4555866ebfd5ff1b99c475b9b77f516e1d --- /dev/null +++ b/inferredbugs-0965/instruction.md @@ -0,0 +1,97 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Disqord +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Threading.Tasks; +using Disqord.Gateway.Api; +using Disqord.Gateway.Api.Models; + +namespace Disqord.Gateway.Default.Dispatcher +{ + public class GuildMemberUpdateHandler : Handler + { + public override ValueTask HandleDispatchAsync(IGatewayApiClient shard, GuildMemberUpdateJsonModel model) + { + CachedMember oldMember = null; + IMember newMember = null; + if (CacheProvider.TryGetMembers(model.GuildId, out var memberCache)) + { + if (memberCache.TryGetValue(model.User.Value.Id, out var member)) + { + newMember = member; + var oldUser = member.SharedUser.Clone() as CachedSharedUser; + oldMember = member.Clone() as CachedMember; + oldMember.SharedUser = oldUser; + newMember.Update(model); + } + else if (CacheProvider.TryGetUsers(out var userCache)) + { + newMember = Dispatcher.GetOrAddMember(userCache, memberCache, model.GuildId, model); + } + } + + newMember ??= new TransientMember(Client, model.GuildId, model); + + var e = new MemberUpdatedEventArgs(oldMember, newMember); + return new(e); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `oldMember` last assigned on line 19 could be null and is dereferenced at line 20, column 17. + +### Severity: +ERROR + +### Procedure: +ValueTask`1 GuildMemberUpdateDispatchHandler.HandleDispatchAsync(IShard,GuildMemberUpdateJsonModel) + +### File: +src/Disqord.Gateway/Default/Dispatcher/Dispatches/Member/GUILD_MEMBER_UPDATE.cs + +### Key: +GUILD_MEMBER_UPDATE.cs|HandleDispatchAsync|NULL_DEREFERENCE + +### Node Key: +5f12004af86bc692e0983547f0c7b710 + +### Hash: +44209158cda04dd4adb48f6583f52fa4 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0996/instruction.md b/inferredbugs-0996/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8bdf9fa1f4375969e57b0d643f23b34e29e32840 --- /dev/null +++ b/inferredbugs-0996/instruction.md @@ -0,0 +1,465 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Downloader +**Bug ID:** 38 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.IO; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters.Binary; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Newtonsoft.Json; + +namespace Downloader.Test +{ + [TestClass] + public class ChunkTest + { + private readonly byte[] _testData = DummyData.GenerateOrderedBytes(1024); + + [TestMethod] + public void ClearTest() + { + // arrange + var chunk = new Chunk(0, 1000) { Position = 100, Timeout = 100 }; + chunk.CanTryAgainOnFailover(); + + // act + chunk.Clear(); + + // assert + Assert.AreEqual(0, chunk.Position); + Assert.AreEqual(0, chunk.FailoverCount); + } + + [TestMethod] + public void ClearFileStorageTest() + { + // arrange + var chunk = new Chunk(0, 1000) { Storage = new FileStorage("") }; + chunk.Storage.WriteAsync(_testData, 0, 5).Wait(); + + // act + chunk.Clear(); + + // assert + Assert.AreEqual(0, chunk.Storage.GetLength()); + } + + [TestMethod] + public void ClearMemoryStorageTest() + { + // arrange + var chunk = new Chunk(0, 1000) { Storage = new MemoryStorage() }; + chunk.Storage.WriteAsync(_testData, 0, 5).Wait(); + + // act + chunk.Clear(); + + // assert + Assert.AreEqual(0, chunk.Storage.GetLength()); + } + + [TestMethod] + public void IsDownloadCompletedOnBeginTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Storage = (new MemoryStorage()) }; + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsFalse(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenNoStorageTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { + Position = size-1 + }; + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsFalse(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenFileStorageNoDataTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Position = size - 1, Storage = (new FileStorage("")) }; + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsFalse(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenMemoryStorageNoDataTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Position = size - 1, Storage = (new MemoryStorage()) }; + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsFalse(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenMemoryStorageDataIsExistTest() + { + // arrange + var chunk = new Chunk(0, _testData.Length - 1) { Position = _testData.Length - 1, Storage = new MemoryStorage() }; + chunk.Storage.WriteAsync(_testData, 0, _testData.Length).Wait(); + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsTrue(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenFileStorageDataIsExistTest() + { + // arrange + var chunk = new Chunk(0, _testData.Length - 1) { Position = _testData.Length - 1, Storage = new FileStorage("") }; + chunk.Storage.WriteAsync(_testData, 0, _testData.Length).Wait(); + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsTrue(isDownloadCompleted); + } + + [TestMethod] + public void IsValidPositionWithMemoryStorageTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Storage = new MemoryStorage() }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWithFileStorageTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Storage = new FileStorage("") }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void IsValidPositionOnOverflowTest() + { + // arrange + var chunk = new Chunk(0, _testData.Length - 1) { + Position = _testData.Length, + Storage = new MemoryStorage() // overflowed + }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsFalse(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWithEqualStorageSizeTest() + { + // arrange + var chunk = new Chunk(0, _testData.Length - 1) { Position = 7, Storage = new MemoryStorage() }; + chunk.Storage.WriteAsync(_testData, 0, 7); + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWithNoEqualStorageSizeTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size - 1) { Position = 10, Storage = (new MemoryStorage()) }; + chunk.Storage.WriteAsync(new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 }, 0, 10); + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsFalse(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWhenNoStorageAndPositivePositionTest() + { + // arrange + var chunk = new Chunk(0, 1024) { + Position = 1 + }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsFalse(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWhenNoStorageAndZeroPositionTest() + { + // arrange + var chunk = new Chunk(0, 1024) { + Position = 0 + }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void IsValidPositionOnZeroSizeTest() + { + // arrange + var chunk = new Chunk(0, -1) { Position = 0, Storage = new MemoryStorage() }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void SetValidPositionOnOverflowTest() + { + // arrange + var chunk = new Chunk(0, 1023) { + Position = 1024, + Storage = new MemoryStorage() // overflowed + }; + + // act + chunk.SetValidPosition(); + + // assert + Assert.AreEqual(0, chunk.Position); + } + + [TestMethod] + public void SetValidPositionWhenNoStorageAndPositivePositionTest() + { + // arrange + var chunk = new Chunk(0, 1024) { + Position = 1 + }; + + // act + chunk.SetValidPosition(); + + // assert + Assert.AreEqual(0, chunk.Position); + } + + [TestMethod] + public void SetValidPositionWithStorageAndPositivePositionTest() + { + // arrange + var chunk = new Chunk(0, 1024) { Position = 1, Storage = new MemoryStorage() }; + + // act + chunk.SetValidPosition(); + + // assert + Assert.AreEqual(0, chunk.Position); + } + + [TestMethod] + public void TestSetValidPositionWhenMemoryStorageChanged() + { + TestSetValidPositionWhenStorageChanged(new MemoryStorage()); + } + + [TestMethod] + public void TestSetValidPositionWhenFileStorageChanged() + { + TestSetValidPositionWhenStorageChanged(new FileStorage()); + } + + private void TestSetValidPositionWhenStorageChanged(IStorage storage) + { + // arrange + var nextPosition = 512; + var chunk = new Chunk(0, 1024) { + Position = 1, + Storage = storage + }; + + // act + storage.WriteAsync(DummyData.GenerateRandomBytes(nextPosition), 0, nextPosition); + chunk.SetValidPosition(); + + // assert + Assert.AreEqual(nextPosition, chunk.Position); + + storage.Clear(); + } + + [TestMethod] + public void ChunkSerializationWhenFileStorageTest() + { + ChunkSerializationTest(new FileStorage()); + } + + [TestMethod] + public void ChunkSerializationWhenMemoryStorageTest() + { + ChunkSerializationTest(new MemoryStorage()); + } + + private void ChunkSerializationTest(IStorage storage) + { + // arrange + var settings = new JsonSerializerSettings(); + settings.Converters.Add(new StorageConverter()); + var chunk = new Chunk(1024, 1024 + _testData.Length) { + Position = 1, + Timeout = 1000, + MaxTryAgainOnFailover = 3000, + Storage = new MemoryStorage() + }; + chunk.Storage.WriteAsync(_testData, 0, _testData.Length).Wait(); + + // act + var serializedChunk = JsonConvert.SerializeObject(chunk); + var deserializedChunk = JsonConvert.DeserializeObject(serializedChunk, settings); + + // assert + AssertHelper.AreEquals(chunk, deserializedChunk); + + chunk.Clear(); + } + + [TestMethod] + public void ChunkBinarySerializationWhenFileStorageTest() + { + ChunkBinarySerializationTest(new FileStorage()); + } + + [TestMethod] + public void ChunkBinarySerializationWhenMemoryStorageTest() + { + ChunkBinarySerializationTest(new MemoryStorage()); + } + + private void ChunkBinarySerializationTest(IStorage storage) + { + // arrange + IFormatter formatter = new BinaryFormatter(); + var chunk = new Chunk(1024, 1024 + _testData.Length) { + Position = 1, + Timeout = 1000, + MaxTryAgainOnFailover = 3000, + Storage = storage + }; + chunk.Storage.WriteAsync(_testData, 0, _testData.Length).Wait(); + using var serializedChunk = new MemoryStream(); + + // act + formatter.Serialize(serializedChunk, chunk); + serializedChunk.Flush(); + serializedChunk.Seek(0, SeekOrigin.Begin); + var deserializedChunk = formatter.Deserialize(serializedChunk) as Chunk; + + // assert + AssertHelper.AreEquals(chunk, deserializedChunk); + + chunk.Clear(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Downloader.MemoryStorage::.ctor() at Line 250) of type Downloader.MemoryStorage in method "Void ChunkTest.IsValidPositionOnZeroSizeTest()". + +### Severity: +ERROR + +### Procedure: +Void ChunkTest.IsValidPositionOnZeroSizeTest() + +### File: +src/Downloader.Test/ChunkTest.cs + +### Key: +ChunkTest.cs|IsValidPositionOnZeroSizeTest|DOTNET_RESOURCE_LEAK + +### Hash: +f422c5fd21e5357a860c3e4691d7094a + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0997/instruction.md b/inferredbugs-0997/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..056b9aa334cacf256062d789e9cf11492aea2ddd --- /dev/null +++ b/inferredbugs-0997/instruction.md @@ -0,0 +1,465 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Downloader +**Bug ID:** 36 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.IO; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters.Binary; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Newtonsoft.Json; + +namespace Downloader.Test +{ + [TestClass] + public class ChunkTest + { + private readonly byte[] _testData = DummyData.GenerateOrderedBytes(1024); + + [TestMethod] + public void ClearTest() + { + // arrange + var chunk = new Chunk(0, 1000) { Position = 100, Timeout = 100 }; + chunk.CanTryAgainOnFailover(); + + // act + chunk.Clear(); + + // assert + Assert.AreEqual(0, chunk.Position); + Assert.AreEqual(0, chunk.FailoverCount); + } + + [TestMethod] + public void ClearFileStorageTest() + { + // arrange + var chunk = new Chunk(0, 1000) { Storage = new FileStorage("") }; + chunk.Storage.WriteAsync(_testData, 0, 5).Wait(); + + // act + chunk.Clear(); + + // assert + Assert.AreEqual(0, chunk.Storage.GetLength()); + } + + [TestMethod] + public void ClearMemoryStorageTest() + { + // arrange + var chunk = new Chunk(0, 1000) { Storage = new MemoryStorage() }; + chunk.Storage.WriteAsync(_testData, 0, 5).Wait(); + + // act + chunk.Clear(); + + // assert + Assert.AreEqual(0, chunk.Storage.GetLength()); + } + + [TestMethod] + public void IsDownloadCompletedOnBeginTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Storage = (new MemoryStorage()) }; + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsFalse(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenNoStorageTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { + Position = size-1 + }; + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsFalse(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenFileStorageNoDataTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Position = size - 1, Storage = (new FileStorage("")) }; + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsFalse(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenMemoryStorageNoDataTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Position = size - 1, Storage = (new MemoryStorage()) }; + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsFalse(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenMemoryStorageDataIsExistTest() + { + // arrange + var chunk = new Chunk(0, _testData.Length - 1) { Position = _testData.Length - 1, Storage = new MemoryStorage() }; + chunk.Storage.WriteAsync(_testData, 0, _testData.Length).Wait(); + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsTrue(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenFileStorageDataIsExistTest() + { + // arrange + var chunk = new Chunk(0, _testData.Length - 1) { Position = _testData.Length - 1, Storage = new FileStorage("") }; + chunk.Storage.WriteAsync(_testData, 0, _testData.Length).Wait(); + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsTrue(isDownloadCompleted); + } + + [TestMethod] + public void IsValidPositionWithMemoryStorageTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Storage = new MemoryStorage() }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWithFileStorageTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Storage = new FileStorage("") }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void IsValidPositionOnOverflowTest() + { + // arrange + var chunk = new Chunk(0, _testData.Length - 1) { + Position = _testData.Length, + Storage = new MemoryStorage() // overflowed + }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsFalse(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWithEqualStorageSizeTest() + { + // arrange + var chunk = new Chunk(0, _testData.Length - 1) { Position = 7, Storage = new MemoryStorage() }; + chunk.Storage.WriteAsync(_testData, 0, 7); + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWithNoEqualStorageSizeTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size - 1) { Position = 10, Storage = (new MemoryStorage()) }; + chunk.Storage.WriteAsync(new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 }, 0, 10); + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsFalse(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWhenNoStorageAndPositivePositionTest() + { + // arrange + var chunk = new Chunk(0, 1024) { + Position = 1 + }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsFalse(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWhenNoStorageAndZeroPositionTest() + { + // arrange + var chunk = new Chunk(0, 1024) { + Position = 0 + }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void IsValidPositionOnZeroSizeTest() + { + // arrange + var chunk = new Chunk(0, -1) { Position = 0, Storage = new MemoryStorage() }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void SetValidPositionOnOverflowTest() + { + // arrange + var chunk = new Chunk(0, 1023) { + Position = 1024, + Storage = new MemoryStorage() // overflowed + }; + + // act + chunk.SetValidPosition(); + + // assert + Assert.AreEqual(0, chunk.Position); + } + + [TestMethod] + public void SetValidPositionWhenNoStorageAndPositivePositionTest() + { + // arrange + var chunk = new Chunk(0, 1024) { + Position = 1 + }; + + // act + chunk.SetValidPosition(); + + // assert + Assert.AreEqual(0, chunk.Position); + } + + [TestMethod] + public void SetValidPositionWithStorageAndPositivePositionTest() + { + // arrange + var chunk = new Chunk(0, 1024) { Position = 1, Storage = new MemoryStorage() }; + + // act + chunk.SetValidPosition(); + + // assert + Assert.AreEqual(0, chunk.Position); + } + + [TestMethod] + public void TestSetValidPositionWhenMemoryStorageChanged() + { + TestSetValidPositionWhenStorageChanged(new MemoryStorage()); + } + + [TestMethod] + public void TestSetValidPositionWhenFileStorageChanged() + { + TestSetValidPositionWhenStorageChanged(new FileStorage()); + } + + private void TestSetValidPositionWhenStorageChanged(IStorage storage) + { + // arrange + var nextPosition = 512; + var chunk = new Chunk(0, 1024) { + Position = 1, + Storage = storage + }; + + // act + storage.WriteAsync(DummyData.GenerateRandomBytes(nextPosition), 0, nextPosition); + chunk.SetValidPosition(); + + // assert + Assert.AreEqual(nextPosition, chunk.Position); + + storage.Clear(); + } + + [TestMethod] + public void ChunkSerializationWhenFileStorageTest() + { + ChunkSerializationTest(new FileStorage()); + } + + [TestMethod] + public void ChunkSerializationWhenMemoryStorageTest() + { + ChunkSerializationTest(new MemoryStorage()); + } + + private void ChunkSerializationTest(IStorage storage) + { + // arrange + var settings = new JsonSerializerSettings(); + settings.Converters.Add(new StorageConverter()); + var chunk = new Chunk(1024, 1024 + _testData.Length) { + Position = 1, + Timeout = 1000, + MaxTryAgainOnFailover = 3000, + Storage = new MemoryStorage() + }; + chunk.Storage.WriteAsync(_testData, 0, _testData.Length).Wait(); + + // act + var serializedChunk = JsonConvert.SerializeObject(chunk); + var deserializedChunk = JsonConvert.DeserializeObject(serializedChunk, settings); + + // assert + AssertHelper.AreEquals(chunk, deserializedChunk); + + chunk.Clear(); + } + + [TestMethod] + public void ChunkBinarySerializationWhenFileStorageTest() + { + ChunkBinarySerializationTest(new FileStorage()); + } + + [TestMethod] + public void ChunkBinarySerializationWhenMemoryStorageTest() + { + ChunkBinarySerializationTest(new MemoryStorage()); + } + + private void ChunkBinarySerializationTest(IStorage storage) + { + // arrange + IFormatter formatter = new BinaryFormatter(); + var chunk = new Chunk(1024, 1024 + _testData.Length) { + Position = 1, + Timeout = 1000, + MaxTryAgainOnFailover = 3000, + Storage = storage + }; + chunk.Storage.WriteAsync(_testData, 0, _testData.Length).Wait(); + using var serializedChunk = new MemoryStream(); + + // act + formatter.Serialize(serializedChunk, chunk); + serializedChunk.Flush(); + serializedChunk.Seek(0, SeekOrigin.Begin); + var deserializedChunk = formatter.Deserialize(serializedChunk) as Chunk; + + // assert + AssertHelper.AreEquals(chunk, deserializedChunk); + + chunk.Clear(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Downloader.MemoryStorage::.ctor() at Line 294) of type Downloader.MemoryStorage in method "Void ChunkTest.SetValidPositionWithStorageAndPositivePositionTest()". + +### Severity: +ERROR + +### Procedure: +Void ChunkTest.SetValidPositionWithStorageAndPositivePositionTest() + +### File: +src/Downloader.Test/ChunkTest.cs + +### Key: +ChunkTest.cs|SetValidPositionWithStorageAndPositivePositionTest|DOTNET_RESOURCE_LEAK + +### Hash: +da3ef37c01fec57c5b4816ab224bd18e + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0998/instruction.md b/inferredbugs-0998/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..173f7f74d15a26af232469bf7cd74918ebcf1436 --- /dev/null +++ b/inferredbugs-0998/instruction.md @@ -0,0 +1,399 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Downloader +**Bug ID:** 31 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Newtonsoft.Json; + +namespace Downloader.Test +{ + [TestClass] + public class ChunkTest + { + [TestMethod] + public void ClearTest() + { + // arrange + var chunk = new Chunk(0, 1000) { Position = 100, Timeout = 100 }; + chunk.CanTryAgainOnFailover(); + + // act + chunk.Clear(); + + // assert + Assert.AreEqual(0, chunk.Position); + Assert.AreEqual(0, chunk.Timeout); + Assert.AreEqual(0, chunk.FailoverCount); + } + + [TestMethod] + public void ClearFileStorageTest() + { + // arrange + var chunk = new Chunk(0, 1000) { Storage = new FileStorage("") }; + chunk.Storage.WriteAsync(new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4 }, 0, 5).Wait(); + + // act + chunk.Clear(); + + // assert + Assert.AreEqual(0, chunk.Storage.GetLength()); + } + + [TestMethod] + public void ClearMemoryStorageTest() + { + // arrange + var chunk = new Chunk(0, 1000) { Storage = new MemoryStorage() }; + chunk.Storage.WriteAsync(new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4 }, 0, 5).Wait(); + + // act + chunk.Clear(); + + // assert + Assert.AreEqual(0, chunk.Storage.GetLength()); + } + + [TestMethod] + public void IsDownloadCompletedOnBeginTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Storage = (new MemoryStorage()) }; + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsFalse(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenNoStorageTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { + Position = size-1 + }; + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsFalse(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenFileStorageNoDataTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Position = size - 1, Storage = (new FileStorage("")) }; + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsFalse(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenMemoryStorageNoDataTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Position = size - 1, Storage = (new MemoryStorage()) }; + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsFalse(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenMemoryStorageDataIsExistTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size - 1) { Position = size - 1, Storage = (new MemoryStorage()) }; + chunk.Storage.WriteAsync(DummyData.GenerateRandomBytes(size), 0, size).Wait(); + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsTrue(isDownloadCompleted); + } + + [TestMethod] + public void IsDownloadCompletedWhenFileStorageDataIsExistTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size - 1) { Position = size - 1, Storage = (new FileStorage("")) }; + var dummyData = DummyData.GenerateRandomBytes(size); + chunk.Storage.WriteAsync(dummyData, 0, size).Wait(); + + // act + bool isDownloadCompleted = chunk.IsDownloadCompleted(); + + // assert + Assert.IsTrue(isDownloadCompleted); + } + + [TestMethod] + public void IsValidPositionWithMemoryStorageTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Storage = (new MemoryStorage()) }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWithFileStorageTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Storage = (new FileStorage("")) }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void IsValidPositionOnOverflowTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size - 1) { + Position = size, + Storage = (new MemoryStorage()) // overflowed + }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsFalse(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWithEqualStorageSizeTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size - 1) { Position = 7, Storage = (new MemoryStorage()) }; + chunk.Storage.WriteAsync(new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 }, 0, 7); + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWithNoEqualStorageSizeTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size - 1) { Position = 10, Storage = (new MemoryStorage()) }; + chunk.Storage.WriteAsync(new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 }, 0, 10); + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsFalse(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWhenNoStorageAndPositivePositionTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { + Position = 1 + }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsFalse(isValidPosition); + } + + [TestMethod] + public void IsValidPositionWhenNoStorageAndZeroPositionTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { + Position = 0 + }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void IsValidPositionOnZeroSizeTest() + { + // arrange + var chunk = new Chunk(0, -1) { Position = 0, Storage = (new MemoryStorage()) }; + + // act + bool isValidPosition = chunk.IsValidPosition(); + + // assert + Assert.IsTrue(isValidPosition); + } + + [TestMethod] + public void SetValidPositionOnOverflowTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size - 1) { + Position = size, + Storage = (new MemoryStorage()) // overflowed + }; + + // act + chunk.SetValidPosition(); + + // assert + Assert.AreEqual(0, chunk.Position); + } + + [TestMethod] + public void SetValidPositionWhenNoStorageAndPositivePositionTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { + Position = 1 + }; + + // act + chunk.SetValidPosition(); + + // assert + Assert.AreEqual(0, chunk.Position); + } + + [TestMethod] + public void SetValidPositionWithStorageAndPositivePositionTest() + { + // arrange + var size = 1024; + var chunk = new Chunk(0, size) { Position = 1, Storage = new MemoryStorage() }; + + // act + chunk.SetValidPosition(); + + // assert + Assert.AreEqual(0, chunk.Position); + } + + [TestMethod] + public void SerializeChunkWhenHasFileStorageTest() + { + // arrange + var settings = new JsonSerializerSettings(); + settings.Converters.Add(new StorageConverter()); + var data = DummyData.GenerateOrderedBytes(1024); + var chunk = new Chunk(1024, 1024 + data.Length) { + Position = 1, + Timeout = 1000, + MaxTryAgainOnFailover = 3000, + Storage = new FileStorage() + }; + + // act + var serializedChunk = JsonConvert.SerializeObject(chunk); + chunk.Storage.Close(); + var deserializedChunk = JsonConvert.DeserializeObject(serializedChunk, settings); + + // assert + Assert.IsNotNull(deserializedChunk); + Assert.AreEqual(chunk.Id, deserializedChunk.Id); + Assert.AreEqual(chunk.Start, deserializedChunk.Start); + Assert.AreEqual(chunk.End, deserializedChunk.End); + Assert.AreEqual(chunk.Length, deserializedChunk.Length); + Assert.AreEqual(chunk.Position, deserializedChunk.Position); + Assert.AreEqual(chunk.Timeout, deserializedChunk.Timeout); + Assert.AreEqual(chunk.MaxTryAgainOnFailover, deserializedChunk.MaxTryAgainOnFailover); + Assert.AreEqual(chunk.Storage.GetLength(), deserializedChunk.Storage.GetLength()); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Downloader.MemoryStorage::.ctor() at Line 147) of type Downloader.MemoryStorage in method "Void ChunkTest.IsValidPositionWithMemoryStorageTest()". + +### Severity: +ERROR + +### Procedure: +Void ChunkTest.IsValidPositionWithMemoryStorageTest() + +### File: +src/Downloader.Test/ChunkTest.cs + +### Key: +ChunkTest.cs|IsValidPositionWithMemoryStorageTest|DOTNET_RESOURCE_LEAK + +### Hash: +03f0cb1d59dbbc591e3bf41680053d6d + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10011/instruction.md b/inferredbugs-10011/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9438b3c40cba8402b58b9abf498b091acc060a51 --- /dev/null +++ b/inferredbugs-10011/instruction.md @@ -0,0 +1,1018 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ttorrent +**Bug ID:** 51 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2011-2012 Turn, Inc. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.turn.ttorrent.client; + +import com.turn.ttorrent.Constants; +import com.turn.ttorrent.client.announce.Announce; +import com.turn.ttorrent.client.announce.AnnounceException; +import com.turn.ttorrent.client.announce.AnnounceResponseListener; +import com.turn.ttorrent.client.network.CountLimitConnectionAllower; +import com.turn.ttorrent.client.network.OutgoingConnectionListener; +import com.turn.ttorrent.client.network.StateChannelListener; +import com.turn.ttorrent.client.peer.PeerActivityListener; +import com.turn.ttorrent.client.peer.SharingPeer; +import com.turn.ttorrent.common.*; +import com.turn.ttorrent.common.protocol.AnnounceRequestMessage; +import com.turn.ttorrent.common.protocol.PeerMessage; +import com.turn.ttorrent.network.ConnectTask; +import com.turn.ttorrent.network.ConnectionListener; +import com.turn.ttorrent.network.ConnectionManager; +import com.turn.ttorrent.network.ConnectionManagerContext; +import org.slf4j.Logger; + +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URI; +import java.nio.ByteBuffer; +import java.nio.channels.ByteChannel; +import java.security.NoSuchAlgorithmException; +import java.util.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import static com.turn.ttorrent.Constants.DEFAULT_SOCKET_CONNECTION_TIMEOUT_MILLIS; +import static com.turn.ttorrent.common.protocol.AnnounceRequestMessage.RequestEvent.*; + +/** + * A pure-java BitTorrent client. + *

+ *

+ * A BitTorrent client in its bare essence shares a given torrent. If the + * torrent is not complete locally, it will continue to download it. If or + * after the torrent is complete, the client may eventually continue to seed it + * for other clients. + *

+ *

+ *

+ * This BitTorrent client implementation is made to be simple to embed and + * simple to use. First, initialize a ShareTorrent object from a torrent + * meta-info source (either a file or a byte array, see + * com.turn.ttorrent.SharedTorrent for how to create a SharedTorrent object). + *

+ * + * @author mpetazzoni + */ +public class Client implements AnnounceResponseListener, PeerActivityListener, TorrentStateListener, Context, ConnectionManagerContext { + + protected static final Logger logger = TorrentLoggerFactory.getLogger(); + + /** + * Peers unchoking frequency, in seconds. Current BitTorrent specification + * recommends 10 seconds to avoid choking fibrilation. + */ + private static final int UNCHOKING_FREQUENCY = 3; + + /** + * Optimistic unchokes are done every 2 loop iterations, i.e. every + * 2*UNCHOKING_FREQUENCY seconds. + */ + private static final int OPTIMISTIC_UNCHOKE_ITERATIONS = 3; + + private static final int RATE_COMPUTATION_ITERATIONS = 2; + private static final int MAX_DOWNLOADERS_UNCHOKE = 10; + + /** + * Default data output directory. + */ + private static final String DEFAULT_OUTPUT_DIRECTORY = "/tmp"; + + public static final String BITTORRENT_ID_PREFIX = "-TO0042-"; + + private AtomicBoolean stop = new AtomicBoolean(false); + + private Announce announce; + + private Random random; + private volatile boolean myStarted = false; + private final TorrentLoader myTorrentLoader; + private final TorrentsStorage torrentsStorage; + private final CountLimitConnectionAllower myInConnectionAllower; + private final CountLimitConnectionAllower myOutConnectionAllower; + private final AtomicInteger mySendBufferSize; + private final AtomicInteger myReceiveBufferSize; + private final PeersStorage peersStorage; + private volatile ConnectionManager myConnectionManager; + private final ExecutorService myExecutorService; + + /** + * @param executorService executor service for run connection worker and process incoming data. Must have a pool size at least 2 + */ + public Client(ExecutorService executorService) { + this.random = new Random(System.currentTimeMillis()); + this.announce = new Announce(this); + this.torrentsStorage = new TorrentsStorage(); + this.peersStorage = new PeersStorage(); + this.mySendBufferSize = new AtomicInteger(); + this.myTorrentLoader = new TorrentLoaderImpl(this.torrentsStorage); + this.myReceiveBufferSize = new AtomicInteger(); + this.myInConnectionAllower = new CountLimitConnectionAllower(peersStorage); + this.myOutConnectionAllower = new CountLimitConnectionAllower(peersStorage); + this.myExecutorService = executorService; + } + + public String addTorrent(String dotTorrentFilePath, String downloadDirPath) throws IOException, InterruptedException, NoSuchAlgorithmException { + return addTorrent(dotTorrentFilePath, downloadDirPath, false, false); + } + + public String addTorrent(String dotTorrentFilePath, String downloadDirPath, boolean seeder, boolean leecher) throws IOException, InterruptedException, NoSuchAlgorithmException { + Torrent torrent = Torrent.load(new File(dotTorrentFilePath)); + final AnnounceableTorrentImpl announceableTorrent = new AnnounceableTorrentImpl( + new TorrentStatistic(), + torrent.getHexInfoHash(), + torrent.getInfoHash(), + torrent.getAnnounceList(), + torrent.getAnnounce(), + downloadDirPath, + dotTorrentFilePath, + seeder); + this.torrentsStorage.addAnnounceableTorrent(torrent.getHexInfoHash(), announceableTorrent); + + if (seeder) { + announceableTorrent.getTorrentStatistic().setLeft(0); + } else { + announceableTorrent.getTorrentStatistic().setLeft(torrent.getSize()); + } + + forceAnnounceAndLogError(announceableTorrent, seeder ? COMPLETED : STARTED, announceableTorrent.getDotTorrentFilePath()); + logger.debug(String.format("Added torrent %s (%s)", torrent.getName(), torrent.getHexInfoHash())); + return torrent.getHexInfoHash(); + } + + private void forceAnnounceAndLogError(AnnounceableTorrent torrent, AnnounceRequestMessage.RequestEvent event, + String dotTorrentFilePath) { + try { + this.announce.forceAnnounce(torrent, this, event); + } catch (IOException e) { + logger.warn("unable to force announce torrent {}. Dot torrent path is {}", torrent.getHexInfoHash(), dotTorrentFilePath); + logger.debug("", e); + } + } + + public void removeTorrent(TorrentHash torrentHash) { + logger.debug("Stopping seeding " + torrentHash.getHexInfoHash()); + final Pair torrents = torrentsStorage.remove(torrentHash.getHexInfoHash()); + + SharedTorrent torrent = torrents.first(); + if (torrent != null) { + torrent.setClientState(ClientState.DONE); + torrent.close(); + } else { + logger.warn(String.format("Torrent %s already removed from myTorrents", torrentHash.getHexInfoHash())); + } + sendStopEvent(torrents.second(), torrentHash.getHexInfoHash()); + } + + public void removeAndDeleteTorrent(String torrentHash, SharedTorrent torrent) { + final Pair torrents = torrentsStorage.remove(torrentHash); + final SharedTorrent sharedTorrent = torrents.first() == null ? torrent : torrents.first(); + if (sharedTorrent != null) { + sharedTorrent.setClientState(ClientState.DONE); + sharedTorrent.delete(); + } + sendStopEvent(torrents.second(), torrentHash); + } + + private void sendStopEvent(AnnounceableFileTorrent announceableFileTorrent, String torrentHash) { + if (announceableFileTorrent == null) { + logger.info("Announceable torrent {} not found in storage after unsuccessful download attempt", torrentHash); + return; + } + forceAnnounceAndLogError(announceableFileTorrent, STOPPED, announceableFileTorrent.getDotTorrentFilePath()); + } + + public void setAnnounceInterval(final int announceInterval) { + announce.setAnnounceInterval(announceInterval); + } + + /** + * Return the torrent this client is exchanging on. + */ + public Collection getTorrents() { + return this.torrentsStorage.activeTorrents(); + } + + public SharedTorrent getTorrentByFilePath(File file) { + String path = file.getAbsolutePath(); + for (SharedTorrent torrent : torrentsStorage.activeTorrents()) { + File parentFile = torrent.getParentFile(); + final List filenames = torrent.getFilenames(); + for (String filename : filenames) { + File seededFile = new File(parentFile, filename); + if (seededFile.getAbsolutePath().equals(path)) { + return torrent; + } + } + } + return null; + } + + public URI getDefaultTrackerURI() { + return announce.getDefaultTrackerURI(); + } + + /** + * Returns the set of known peers. + */ + public Set getPeers() { + return new HashSet(this.peersStorage.getSharingPeers()); + } + + public void setMaxInConnectionsCount(int maxConnectionsCount) { + this.myInConnectionAllower.setMyMaxConnectionCount(maxConnectionsCount); + } + + /** + * set ups new receive buffer size, that will be applied to all new connections. + * If value is equal or less, than zero, then method doesn't have effect + * + * @param newSize new size + */ + public void setReceiveBufferSize(int newSize) { + myReceiveBufferSize.set(newSize); + } + + /** + * set ups new send buffer size, that will be applied to all new connections. + * If value is equal or less, than zero, then method doesn't have effect + * + * @param newSize new size + */ + public void setSendBufferSize(int newSize) { + mySendBufferSize.set(newSize); + } + + public void setMaxOutConnectionsCount(int maxConnectionsCount) { + this.myOutConnectionAllower.setMyMaxConnectionCount(maxConnectionsCount); + } + + public void start(final InetAddress... bindAddresses) throws IOException { + start(bindAddresses, Constants.DEFAULT_ANNOUNCE_INTERVAL_SEC, null); + } + + public void start(final InetAddress[] bindAddresses, final URI defaultTrackerURI) throws IOException { + start(bindAddresses, Constants.DEFAULT_ANNOUNCE_INTERVAL_SEC, defaultTrackerURI); + } + + public Peer[] getSelfPeers(final InetAddress[] bindAddresses) throws UnsupportedEncodingException { + Peer self = peersStorage.getSelf(); + + if (self == null) { + return new Peer[0]; + } + + Peer[] result = new Peer[bindAddresses.length]; + for (int i = 0; i < bindAddresses.length; i++) { + final InetAddress bindAddress = bindAddresses[i]; + final Peer peer = new Peer(new InetSocketAddress(bindAddress.getHostAddress(), self.getPort())); + peer.setTorrentHash(self.getHexInfoHash()); + //if we have more, that one bind address, then only for first set self peer id. For other generate it + if (i == 0) { + peer.setPeerId(self.getPeerId()); + } else { + final String id = Client.BITTORRENT_ID_PREFIX + UUID.randomUUID().toString().split("-")[4]; + byte[] idBytes = id.getBytes(Torrent.BYTE_ENCODING); + peer.setPeerId(ByteBuffer.wrap(idBytes)); + } + result[i] = peer; + } + return result; + } + + public void start(final InetAddress[] bindAddresses, final int announceIntervalSec, final URI defaultTrackerURI) throws IOException { + this.myConnectionManager = new ConnectionManager( + this, + new SystemTimeService(), + myInConnectionAllower, + myOutConnectionAllower, + mySendBufferSize, + myReceiveBufferSize); + this.setSocketConnectionTimeout(DEFAULT_SOCKET_CONNECTION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + try { + this.myConnectionManager.initAndRunWorker(); + } catch (IOException e) { + LoggerUtils.errorAndDebugDetails(logger, "error in initialization server channel", e); + this.stop(); + return; + } + final String id = Client.BITTORRENT_ID_PREFIX + UUID.randomUUID().toString().split("-")[4]; + byte[] idBytes = id.getBytes(Torrent.BYTE_ENCODING); + Peer self = new Peer(new InetSocketAddress(myConnectionManager.getBindPort()), ByteBuffer.wrap(idBytes)); + peersStorage.setSelf(self); + logger.info("BitTorrent client [{}] started and " + + "listening at {}:{}...", + new Object[]{ + self.getShortHexPeerId(), + self.getIp(), + self.getPort() + }); + + announce.start(defaultTrackerURI, this, getSelfPeers(bindAddresses), announceIntervalSec); + this.stop.set(false); + + myStarted = true; + } + + /** + * Immediately but gracefully stop this client. + */ + public void stop() { + this.stop(60, TimeUnit.SECONDS); + } + + public void stop(int timeout, TimeUnit timeUnit) { + boolean wasStopped = this.stop.getAndSet(true); + if (wasStopped) return; + + if (!myStarted) + return; + + this.myConnectionManager.close(); + + logger.trace("try stop announce thread..."); + + this.announce.stop(); + + logger.trace("announce thread is stopped"); + + for (SharedTorrent torrent : this.torrentsStorage.activeTorrents()) { + logger.trace("try close torrent {}", torrent); + torrent.close(); + if (torrent.isFinished()) { + torrent.setClientState(ClientState.DONE); + } else { + torrent.setClientState(ClientState.ERROR); + } + } + + logger.debug("Closing all remaining peer connections..."); + for (SharingPeer peer : this.peersStorage.getSharingPeers()) { + peer.unbind(true); + } + + torrentsStorage.clear(); + logger.info("BitTorrent client signing off."); + } + + public void setCleanupTimeout(int timeout, TimeUnit timeUnit) throws IllegalStateException { + ConnectionManager connectionManager = this.myConnectionManager; + if (connectionManager == null) { + throw new IllegalStateException("connection manager is null"); + } + connectionManager.setCleanupTimeout(timeUnit.toMillis(timeout)); + } + + public void setSocketConnectionTimeout(int timeout, TimeUnit timeUnit) throws IllegalStateException { + ConnectionManager connectionManager = this.myConnectionManager; + if (connectionManager == null) { + throw new IllegalStateException("connection manager is null"); + } + connectionManager.setSocketConnectionTimeout(timeUnit.toMillis(timeout)); + } + + /** + * Tells whether we are a seed for the torrent we're sharing. + */ + public boolean isSeed(String hexInfoHash) { + SharedTorrent t = this.torrentsStorage.getTorrent(hexInfoHash); + return t != null && t.isComplete(); + } + + public void downloadUninterruptibly(final String dotTorrentPath, + final String downloadDirPath, + final long downloadTimeoutSeconds) throws IOException, InterruptedException, NoSuchAlgorithmException { + downloadUninterruptibly(dotTorrentPath, downloadDirPath, downloadTimeoutSeconds, 1, new AtomicBoolean(false), 5000); + } + + public void downloadUninterruptibly(final String dotTorrentPath, + final String downloadDirPath, + final long idleTimeoutSec, + final int minSeedersCount, + final AtomicBoolean isInterrupted, + final long maxTimeForConnectMs) throws IOException, InterruptedException, NoSuchAlgorithmException { + downloadUninterruptibly(dotTorrentPath, downloadDirPath, idleTimeoutSec, minSeedersCount, isInterrupted, + maxTimeForConnectMs, new DownloadProgressListener.NopeListener()); + } + + public void downloadUninterruptibly(final String dotTorrentPath, + final String downloadDirPath, + final long idleTimeoutSec, + final int minSeedersCount, + final AtomicBoolean isInterrupted, + final long maxTimeForConnectMs, + DownloadProgressListener listener) throws IOException, InterruptedException, NoSuchAlgorithmException { + String hash = addTorrent(dotTorrentPath, downloadDirPath, false, true); + + SharedTorrent torrent; + int timeoutForFoundPeersMs = 10000; + long start = System.currentTimeMillis(); + + while (((torrent = torrentsStorage.getTorrent(hash)) == null) && (System.currentTimeMillis() - start) < timeoutForFoundPeersMs) { + Thread.sleep(10); + } + + long maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000; + if (torrent != null) { + torrent.addDownloadProgressListener(listener); + final long startDownloadAt = System.currentTimeMillis(); + long currentLeft = torrent.getLeft(); + + while (torrent.getClientState() != ClientState.SEEDING && + torrent.getClientState() != ClientState.ERROR && + (torrent.getSeedersCount() >= minSeedersCount || torrent.getLastAnnounceTime() < 0) && + (System.currentTimeMillis() <= maxIdleTime)) { + if (Thread.currentThread().isInterrupted() || isInterrupted.get()) + throw new InterruptedException("Download of " + torrent.getName() + " was interrupted"); + if (currentLeft > torrent.getLeft()) { + currentLeft = torrent.getLeft(); + maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000; + } + if (System.currentTimeMillis() - startDownloadAt > maxTimeForConnectMs) { + if (getPeersForTorrent(torrent.getHexInfoHash()).size() < minSeedersCount) { + break; + } + } + Thread.sleep(100); + } + } + + if (torrent == null || !(torrent.isFinished() && torrent.getClientState() == ClientState.SEEDING)) { + removeAndDeleteTorrent(hash, torrent); + + final List peersForTorrent = getPeersForTorrent(hash); + int connectedPeersForTorrent = peersForTorrent.size(); + for (SharingPeer peer : peersForTorrent) { + peer.unbind(true); + } + + final String errorMsg; + if (torrent == null) { + errorMsg = "Unable to download torrent completely - cannot initialize torrent in " + timeoutForFoundPeersMs + " ms"; + } else if (System.currentTimeMillis() > maxIdleTime) { + int completedPieces = torrent.getCompletedPieces().cardinality(); + int totalPieces = torrent.getPieceCount(); + errorMsg = String.format("No pieces has been downloaded in %d seconds. Downloaded pieces %d/%d, connected peers %d" + , idleTimeoutSec, completedPieces, totalPieces, connectedPeersForTorrent); + } else if (connectedPeersForTorrent < minSeedersCount) { + errorMsg = String.format("Not enough seeders. Required %d, found %d", minSeedersCount, connectedPeersForTorrent); + } else if (torrent.getClientState() == ClientState.ERROR) { + errorMsg = "Torrent state is ERROR"; + } else { + errorMsg = "Unknown error"; + } + throw new IOException("Unable to download torrent completely - " + errorMsg); + } + } + + public List getPeersForTorrent(String torrentHash) { + if (torrentHash == null) return new ArrayList(); + + List result = new ArrayList(); + for (SharingPeer sharingPeer : peersStorage.getSharingPeers()) { + if (torrentHash.equals(sharingPeer.getHexInfoHash())) { + result.add(sharingPeer); + } + } + return result; + } + + public boolean isRunning() { + return myStarted; + } + + /** + * Display information about the BitTorrent client state. + *

+ *

+ * This emits an information line in the log about this client's state. It + * includes the number of choked peers, number of connected peers, number + * of known peers, information about the torrent availability and + * completion and current transmission rates. + *

+ */ + public synchronized void info() { + float dl = 0; + float ul = 0; + int numConnected = 0; + for (SharingPeer peer : getConnectedPeers()) { + dl += peer.getDLRate().get(); + ul += peer.getULRate().get(); + numConnected++; + } + +/* + for (SharedTorrent torrent : this.torrents.values()) { + logger.debug("[{}]{} {}/{} (Downloaded {} bytes) pieces ({}%) [{}/{}] with {}/{} peers at {}/{} kB/s.", + new Object[]{ + Arrays.toString(torrent.getFilenames().toArray()), + torrent.getClientState().name(), + torrent.getCompletedPieces().cardinality(), + torrent.getPieceCount(), + torrent.getDownloaded(), + String.format("%.2f", torrent.getCompletion()), + torrent.getAvailablePieces().cardinality(), + torrent.getRequestedPieces().cardinality(), + numConnected, + this.peers.size(), + String.format("%.2f", dl / 1024.0), + String.format("%.2f", ul / 1024.0), + }); + } +*/ +// logger.debug("Downloaded bytes: {}", PeerExchange.readBytes); + + } + + /** + * Reset peers download and upload rates. + *

+ *

+ * This method is called every RATE_COMPUTATION_ITERATIONS to reset the + * download and upload rates of all peers. This contributes to making the + * download and upload rate computations rolling averages every + * UNCHOKING_FREQUENCY * RATE_COMPUTATION_ITERATIONS seconds (usually 20 + * seconds). + *

+ */ + private synchronized void resetPeerRates() { + for (SharingPeer peer : getConnectedPeers()) { + peer.getDLRate().reset(); + peer.getULRate().reset(); + } + } + + /** + * Retrieve a peer comparator. + *

+ *

+ * Returns a peer comparator based on either the download rate or the + * upload rate of each peer depending on our state. While sharing, we rely + * on the download rate we get from each peer. When our download is + * complete and we're only seeding, we use the upload rate instead. + *

+ * + * @return A SharingPeer comparator that can be used to sort peers based on + * the download or upload rate we get from them. + */ + private Comparator getPeerRateComparator() { +/* + if (this.seed == 0) { + return new SharingPeer.ULRateComparator(); + } +*/ + + return new SharingPeer.DLRateComparator(); + } + + /** + * Unchoke connected peers. + *

+ *

+ * This is one of the "clever" places of the BitTorrent client. Every + * OPTIMISTIC_UNCHOKING_FREQUENCY seconds, we decide which peers should be + * unchocked and authorized to grab pieces from us. + *

+ *

+ *

+ * Reciprocation (tit-for-tat) and upload capping is implemented here by + * carefully choosing which peers we unchoke, and which peers we choke. + *

+ *

+ *

+ * The four peers with the best download rate and are interested in us get + * unchoked. This maximizes our download rate as we'll be able to get data + * from there four "best" peers quickly, while allowing these peers to + * download from us and thus reciprocate their generosity. + *

+ *

+ *

+ * Peers that have a better download rate than these four downloaders but + * are not interested get unchoked too, we want to be able to download from + * them to get more data more quickly. If one becomes interested, it takes + * a downloader's place as one of the four top downloaders (i.e. we choke + * the downloader with the worst upload rate). + *

+ * + * @param optimistic Whether to perform an optimistic unchoke as well. + */ + private synchronized void unchokePeers(boolean optimistic) { + // Build a set of all connected peers, we don't care about peers we're + // not connected to. + List bound = new ArrayList(peersStorage.getSharingPeers()); + Collections.sort(bound, this.getPeerRateComparator()); + Collections.reverse(bound); + if (bound.size() == 0) { + logger.trace("No connected peers, skipping unchoking."); + return; + } else { + logger.trace("Running unchokePeers() on {} connected peers. Client {}", + new Object[]{bound.size(), Thread.currentThread()}); + } + + int downloaders = 0; + Set choked = new HashSet(); + + // We're interested in the top downloaders first, so use a descending + // set. + for (SharingPeer peer : bound) { + if (downloaders < Client.MAX_DOWNLOADERS_UNCHOKE) { + // Unchoke up to MAX_DOWNLOADERS_UNCHOKE interested peers + if (peer.isInterested()) { + downloaders++; + peer.unchoke(); + } + continue; + } + // Choke everybody else + choked.add(peer); + } + + // Actually choke all chosen peers (if any), except the eventual + // optimistic unchoke. + if (choked.size() > 0) { + SharingPeer randomPeer = choked.toArray( + new SharingPeer[0])[this.random.nextInt(choked.size())]; + + for (SharingPeer peer : choked) { + if (optimistic && peer == randomPeer) { + logger.debug("Optimistic unchoke of {}.", peer); + continue; + } + + peer.choke(); + } + } + } + + private Collection getConnectedPeers() { + Set result = new HashSet(); + Set toRemove = new HashSet(); + for (SharingPeer peer : this.peersStorage.getSharingPeers()) { + if (peer.isConnected()) { + result.add(peer); + } else { + toRemove.add(peer); + } + } + for (SharingPeer peer : toRemove) { + this.peersStorage.removeSharingPeer(peer); + } + return result; + } + + public boolean containsTorrentWithHash(String hash) { + return torrentsStorage.hasTorrent(hash); + } + + @Override + public PeersStorage getPeersStorage() { + return peersStorage; + } + + @Override + public TorrentsStorage getTorrentsStorage() { + return torrentsStorage; + } + + @Override + public ExecutorService getExecutor() { + return myExecutorService; + } + + @Override + public ConnectionListener newChannelListener() { + return new StateChannelListener(this); + } + + @Override + public SharingPeer createSharingPeer(String host, int port, ByteBuffer peerId, SharedTorrent torrent, ByteChannel channel) { + return new SharingPeer(host, port, peerId, torrent, getConnectionManager(), this, channel); + } + + @Override + public TorrentLoader getTorrentLoader() { + return myTorrentLoader; + } + + + /** AnnounceResponseListener handler(s). **********************************/ + + /** + * Handle an announce response event. + * + * @param interval The announce interval requested by the tracker. + * @param complete The number of seeders on this torrent. + * @param incomplete The number of leechers on this torrent. + */ + @Override + public void handleAnnounceResponse(int interval, int complete, int incomplete, String hexInfoHash) { + final SharedTorrent sharedTorrent = this.torrentsStorage.getTorrent(hexInfoHash); + if (sharedTorrent != null) { + sharedTorrent.setSeedersCount(complete); + sharedTorrent.setLastAnnounceTime(System.currentTimeMillis()); + } + setAnnounceInterval(interval); + } + + /** + * Handle the discovery of new peers. + * + * @param peers The list of peers discovered (from the announce response or + * any other means like DHT/PEX, etc.). + */ + @Override + public void handleDiscoveredPeers(List peers, String hexInfoHash) { + + if (peers.size() == 0) return; + + SharedTorrent torrent = torrentsStorage.getTorrent(hexInfoHash); + + if (torrent != null && torrent.isFinished()) return; + + final AnnounceableFileTorrent announceableTorrent = torrentsStorage.getAnnounceableTorrent(hexInfoHash); + if (announceableTorrent == null) { + logger.info("announceable torrent {} is not found in storage. Maybe it was removed", hexInfoHash); + return; + } + + if (announceableTorrent.isSeeded()) return; + + logger.debug("Got {} peer(s) ({}) for {} in tracker response", new Object[]{peers.size(), + Arrays.toString(peers.toArray()), hexInfoHash}); + + Map uniquePeers = new HashMap(); + for (Peer peer : peers) { + final PeerUID peerUID = new PeerUID(peer.getAddress(), hexInfoHash); + if (uniquePeers.containsKey(peerUID)) continue; + uniquePeers.put(peerUID, peer); + } + + for (Map.Entry e : uniquePeers.entrySet()) { + + PeerUID peerUID = e.getKey(); + Peer peer = e.getValue(); + boolean alreadyConnectedToThisPeer = peersStorage.getSharingPeer(peerUID) != null; + + if (alreadyConnectedToThisPeer) { + logger.debug("skipping peer {}, because we already connected to this peer", peer); + continue; + } + + ConnectionListener connectionListener = new OutgoingConnectionListener( + this, + announceableTorrent, + peer.getIp(), + peer.getPort()); + + logger.debug("trying to connect to the peer {}", peer); + + boolean connectTaskAdded = this.myConnectionManager.offerConnect( + new ConnectTask(peer.getIp(), + peer.getPort(), + connectionListener, + new SystemTimeService().now(), + Constants.DEFAULT_CONNECTION_TIMEOUT_MILLIS), 1, TimeUnit.SECONDS); + if (!connectTaskAdded) { + logger.info("can not connect to peer {}. Unable to add connect task to connection manager", peer); + } + } + } + + /** + * PeerActivityListener handler(s). ************************************* + */ + + @Override + public void handlePeerChoked(SharingPeer peer) { /* Do nothing */ } + + @Override + public void handlePeerReady(SharingPeer peer) { /* Do nothing */ } + + @Override + public void handlePieceAvailability(SharingPeer peer, + Piece piece) { /* Do nothing */ } + + @Override + public void handleBitfieldAvailability(SharingPeer peer, + BitSet availablePieces) { /* Do nothing */ } + + @Override + public void handlePieceSent(SharingPeer peer, + Piece piece) { /* Do nothing */ } + + /** + * Piece download completion handler. + *

+ *

+ * When a piece is completed, and valid, we announce to all connected peers + * that we now have this piece. + *

+ *

+ *

+ * We use this handler to identify when all of the pieces have been + * downloaded. When that's the case, we can start the seeding period, if + * any. + *

+ * + * @param peer The peer we got the piece from. + * @param piece The piece in question. + */ + @Override + public void handlePieceCompleted(final SharingPeer peer, Piece piece) + throws IOException { + final SharedTorrent torrent = peer.getTorrent(); + final String torrentHash = torrent.getHexInfoHash(); + if (piece.isValid()) { + // Send a HAVE message to all connected peers + PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex()); + for (SharingPeer remote : getConnectedPeers()) { + if (remote.getTorrent().getHexInfoHash().equals(torrentHash)) + remote.send(have); + } + } + synchronized (torrent) { + if (piece.isValid()) { + // Make sure the piece is marked as completed in the torrent + // Note: this is required because the order the + // PeerActivityListeners are called is not defined, and we + // might be called before the torrent's piece completion + // handler is. + torrent.markCompleted(piece); + logger.debug("Completed download of {} from {}, now has {}/{} pieces.", + new Object[]{ + piece, + peer, + torrent.getCompletedPieces().cardinality(), + torrent.getPieceCount() + }); + + BitSet completed = new BitSet(); + completed.or(torrent.getCompletedPieces()); + completed.and(peer.getAvailablePieces()); + if (completed.equals(peer.getAvailablePieces())) { + // send not interested when have no interested pieces; + peer.send(PeerMessage.NotInterestedMessage.craft()); + } + + } else { + logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer); + peer.getPoorlyAvailablePieces().set(piece.getIndex()); + } + + if (torrent.isComplete()) { + //close connection with all peers for this torrent + logger.debug("Download of {} complete.", torrent.getName()); + + torrent.finish(); + + try { + this.announce.getCurrentTrackerClient(torrent) + .announceAllInterfaces(COMPLETED, true, torrent); + } catch (AnnounceException e) { + logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce()); + } + + } + } + } + + @Override + public void handlePeerDisconnected(SharingPeer peer) { + final SharedTorrent peerTorrent = peer.getTorrent(); + Peer p = new Peer(peer.getIp(), peer.getPort()); + p.setPeerId(peer.getPeerId()); + p.setTorrentHash(peer.getHexInfoHash()); + PeerUID peerUID = new PeerUID(p.getAddress(), p.getHexInfoHash()); + SharingPeer sharingPeer = this.peersStorage.removeSharingPeer(peerUID); + logger.debug("Peer {} disconnected, [{}/{}].", + new Object[]{ + peer, + getConnectedPeers().size(), + this.peersStorage.getSharingPeers().size() + }); + } + + @Override + public void afterPeerRemoved(SharingPeer peer) { + logger.trace("disconnected peer " + peer); + torrentsStorage.peerDisconnected(peer.getHexInfoHash()); + } + + @Override + public void handleIOException(SharingPeer peer, IOException ioe) { + logger.debug("I/O problem occured when reading or writing piece data for peer {}: {}.", peer, ioe.getMessage()); + + peer.unbind(true); + } + + @Override + public void handleNewPeerConnected(SharingPeer peer) { + //do nothing + } + + @Override + public void torrentStateChanged(ClientState newState, SharedTorrent torrent) { + if (newState.equals(ClientState.ERROR)) { + removeTorrent(torrent); + } + } + + public ConnectionManager getConnectionManager() throws IllegalStateException { + ConnectionManager connectionManager = this.myConnectionManager; + if (connectionManager == null) { + throw new IllegalStateException("connection manager is null"); + } + return connectionManager; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `Client.announce.getCurrentTrackerClient(torrent)` could be null and is dereferenced at line 887. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Client.handlePieceCompleted(SharingPeer,Piece) + +### Procedure Id: +com.turn.ttorrent.client.Client.handlePieceCompleted(com.turn.ttorrent.client.peer.SharingPeer,com.t.125f29b82f5812c06334c7d1b1514ba0 + +### File: +ttorrent-client/src/main/java/com/turn/ttorrent/client/Client.java + +### Key: +Client.java|handlePieceCompleted|NULL_DEREFERENCE + +### Node Key: +da9314e4de9524be1935785051e00611 + +### Hash: +50404a1e9df6ce6fce6f92944fd5c821 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10016/instruction.md b/inferredbugs-10016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..25c240b9e5c9ba444156ad479f8bff3450ecc827 --- /dev/null +++ b/inferredbugs-10016/instruction.md @@ -0,0 +1,255 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ttorrent +**Bug ID:** 20 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2011-2012 Turn, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.turn.ttorrent.client.storage; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; + +import org.apache.commons.io.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Single-file torrent byte data storage. + * + *

+ * This implementation of TorrentByteStorageFile provides a torrent byte data + * storage relying on a single underlying file and uses a RandomAccessFile + * FileChannel to expose thread-safe read/write methods. + *

+ * + * @author mpetazzoni + */ +public class FileStorage implements TorrentByteStorage { + + private static final Logger logger = + LoggerFactory.getLogger(FileStorage.class); + + private final File target; + private File partial; + private final long offset; + private final long size; + + private RandomAccessFile raf; + private FileChannel channel; + private File current; + + public FileStorage(File file, long offset, long size) + throws IOException { + this.target = file; + this.offset = offset; + this.size = size; + + } + + public void open() throws IOException { + this.partial = new File(this.target.getAbsolutePath() + + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); + + if (this.partial.exists()) { + logger.debug("Partial download found at {}. Continuing...", + this.partial.getAbsolutePath()); + this.current = this.partial; + } else if (!this.target.exists()) { + logger.debug("Downloading new file to {}...", + this.partial.getAbsolutePath()); + this.current = this.partial; + } else { + logger.debug("Using existing file {}.", + this.target.getAbsolutePath()); + this.current = this.target; + } + + this.raf = new RandomAccessFile(this.current, "rw"); + + // Set the file length to the appropriate size, eventually truncating + // or extending the file if it already exists with a different size. + this.raf.setLength(this.size); + + this.channel = raf.getChannel(); + + logger.debug("Opened byte storage file at {} " + + "({}+{} byte(s)).", + new Object[] { + this.current.getAbsolutePath(), + this.offset, + this.size, + }); + } + + protected long offset() { + return this.offset; + } + + @Override + public long size() { + return this.size; + } + + @Override + public int read(ByteBuffer buffer, long offset) throws IOException { + int requested = buffer.remaining(); + + if (offset + requested > this.size) { + throw new IllegalArgumentException("Invalid storage read request!"); + } + + int bytes = this.channel.read(buffer, offset); + if (bytes < requested) { + throw new IOException("Storage underrun!"); + } + + return bytes; + } + + @Override + public int write(ByteBuffer buffer, long offset) throws IOException { + int requested = buffer.remaining(); + + if (offset + requested > this.size) { + throw new IllegalArgumentException("Invalid storage write request!"); + } + + return this.channel.write(buffer, offset); + } + + @Override + public synchronized void close() throws IOException { + logger.debug("Closing file channel to {}. Channel open: {}", current.getName(), channel.isOpen()); + if (this.channel.isOpen()) { + this.channel.force(true); + } + this.raf.close(); + } + + /** Move the partial file to its final location. + */ + @Override + public synchronized void finish() throws IOException { + logger.debug("Closing file channel to " + this.current.getName() + + " (download complete)."); + if (this.channel.isOpen()) { + this.channel.force(true); + } + + // Nothing more to do if we're already on the target file. + if (this.isFinished()) { + return; + } + + this.raf.close(); + FileUtils.deleteQuietly(this.target); + FileUtils.moveFile(this.current, this.target); + + logger.debug("Re-opening torrent byte storage at {}.", + this.target.getAbsolutePath()); + + this.raf = new RandomAccessFile(this.target, "rw"); + this.raf.setLength(this.size); + this.channel = this.raf.getChannel(); + this.current = this.target; + + FileUtils.deleteQuietly(this.partial); + logger.info("Moved torrent data from {} to {}.", + this.partial.getName(), + this.target.getName()); + } + + @Override + public boolean isFinished() { + return this.current.equals(this.target); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.turn.ttorrent.client.storage.FileStorage.write` reads without synchronization from `this.com.turn.ttorrent.client.storage.FileStorage.channel`. Potentially races with write in method `FileStorage.finish()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int FileStorage.write(ByteBuffer,long) + +### Procedure Id: +com.turn.ttorrent.client.storage.FileStorage.write(java.nio.ByteBuffer,long):int.9c4302516a4c2a1046e5807e8ddc2037 + +### File: +src/main/java/com/turn/ttorrent/client/storage/FileStorage.java + +### Key: +FileStorage.java|write|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +da5c707005e461bada8189acfdf74e40 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10020/instruction.md b/inferredbugs-10020/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6f6f0dc170189f3334a0b9ad00ce10b8f440fc62 --- /dev/null +++ b/inferredbugs-10020/instruction.md @@ -0,0 +1,182 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ttorrent +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2012 Turn, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.turn.ttorrent.client.announce; + +import com.turn.ttorrent.client.SharedTorrent; +import com.turn.ttorrent.common.Peer; +import com.turn.ttorrent.common.protocol.TrackerMessage; +import com.turn.ttorrent.common.protocol.TrackerMessage.*; +import com.turn.ttorrent.common.protocol.udp.*; + +import java.net.DatagramSocket; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.channels.UnsupportedAddressTypeException; +import java.util.Random; + + +/** + * Announcer for UDP trackers. + * + *

+ * The UDP tracker protocol requires a two-step announce request/response + * exchange where the peer is first required to establish a "connection" + * with the tracker by sending a connection request message and retreiving + * a connection ID from the tracker to use in the following announce + * request messages (valid for 2 minutes). + *

+ * + *

+ * It also contains a backing-off retry mechanism (on a 15*2^n seconds + * scheme), in which if the announce request times-out for more than the + * connection ID validity period, another connection request/response + * exchange must be made before attempting to retransmit the announce + * request. + *

+ * + * @author mpetazzoni + */ +public class UDPAnnounce extends Announce { + + private final DatagramSocket socket; + private final Random random; + + /** + * + * @param torrent + */ + protected UDPAnnounce(SharedTorrent torrent, Peer peer) + throws SocketException, UnknownHostException { + super(torrent, peer, "udp"); + + /** + * The UDP announce request protocol only supports IPv4 + * + * @see http://bittorrent.org/beps/bep_0015.html#ipv6 + */ + if (! (InetAddress.getByName(peer.getIp()) instanceof Inet4Address)) { + throw new UnsupportedAddressTypeException(); + } + + URL announceURL = this.torrent.getAnnounceUrl(); + this.socket = new DatagramSocket(); + this.socket.connect(new InetSocketAddress( + announceURL.getHost(), + announceURL.getPort())); + this.random = new Random(); + } + + @Override + public void announce(AnnounceRequestMessage.RequestEvent event, + boolean inhibitEvents) throws AnnounceException { + logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...", + new Object[] { + this.formatAnnounceEvent(event), + this.torrent.getUploaded(), + this.torrent.getDownloaded(), + this.torrent.getLeft() + }); + + try { + ByteBuffer data = null; + UDPTrackerMessage.UDPTrackerResponseMessage message = + UDPTrackerMessage.UDPTrackerResponseMessage.parse(data); + this.handleTrackerResponse(message, inhibitEvents); + } catch (MessageValidationException mve) { + logger.error("Tracker message violates expected protocol: {}!", + mve.getMessage(), mve); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `data` last assigned on line 99 could be null and is dereferenced by call to `parse(...)` at line 101. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void UDPAnnounce.announce(TrackerMessage$AnnounceRequestMessage$RequestEvent,boolean) + +### Procedure Id: +com.turn.ttorrent.client.announce.UDPAnnounce.announce(com.turn.ttorrent.common.protocol.TrackerMess.0d63c59351ae4c18faff3e6e29598ebb + +### File: +src/main/java/com/turn/ttorrent/client/announce/UDPAnnounce.java + +### Key: +UDPAnnounce.java|announce|NULL_DEREFERENCE + +### Node Key: +4a55d6b597cfb713c1c61a4cc5ecd5f2 + +### Hash: +490919529c96229398f6bbe40c8de256 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10027/instruction.md b/inferredbugs-10027/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0dc6b3f127446c5db9a3946decc30bb249ca5a28 --- /dev/null +++ b/inferredbugs-10027/instruction.md @@ -0,0 +1,170 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ttorrent +**Bug ID:** 28 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.turn.ttorrent.client.network; + +import com.turn.ttorrent.client.Handshake; +import com.turn.ttorrent.client.SharedTorrent; +import com.turn.ttorrent.client.peer.SharingPeer; +import com.turn.ttorrent.common.ConnectionUtils; +import com.turn.ttorrent.common.Peer; +import com.turn.ttorrent.common.PeersStorageFactory; +import com.turn.ttorrent.common.TorrentsStorageFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.ByteChannel; +import java.text.ParseException; +import java.util.Arrays; + +public class HandshakeReceiver implements DataProcessor { + + private static final Logger logger = LoggerFactory.getLogger(HandshakeReceiver.class); + + private final String uid; + private final PeersStorageFactory peersStorageFactory; + private final TorrentsStorageFactory torrentsStorageFactory; + private ByteBuffer messageBytes; + private int pstrLength; + + public HandshakeReceiver(String uid, PeersStorageFactory peersStorageFactory, TorrentsStorageFactory torrentsStorageFactory) { + this.uid = uid; + this.peersStorageFactory = peersStorageFactory; + this.torrentsStorageFactory = torrentsStorageFactory; + this.pstrLength = -1; + } + + @Override + public DataProcessor processAndGetNext(ByteChannel socketChannel) throws IOException { + if (pstrLength == -1) { + ByteBuffer len = ByteBuffer.allocate(1); + int readBytes = -1; + try { + readBytes = socketChannel.read(len); + } catch (IOException ignored) { + } + if (readBytes == -1) { + return new ShutdownProcessor(uid, peersStorageFactory); + } + if (readBytes == 0) { + return this; + } + len.rewind(); + byte pstrLen = len.get(); + this.pstrLength = pstrLen; + messageBytes = ByteBuffer.allocate(this.pstrLength + Handshake.BASE_HANDSHAKE_LENGTH); + messageBytes.put(pstrLen); + } + int readBytes = -1; + try { + readBytes = socketChannel.read(messageBytes); + } catch (IOException e) { + e.printStackTrace(); + } + if (readBytes == -1) { + return new ShutdownProcessor(uid, peersStorageFactory); + } + if (messageBytes.remaining() != 0) { + return this; + } + Handshake hs; + try { + messageBytes.rewind(); + hs = Handshake.parse(messageBytes, pstrLength); + } catch (ParseException e) { + logger.debug("incorrect handshake message from " + socketChannel.toString(), e); + return new ShutdownProcessor(uid, peersStorageFactory); + } + if (!torrentsStorageFactory.getTorrentsStorage().hasTorrent(hs.getHexInfoHash())) { + logger.debug("peer {} try download torrent with hash {}, but it's unknown torrent for self", + Arrays.toString(hs.getPeerId()), + hs.getHexInfoHash()); + return new ShutdownProcessor(uid, peersStorageFactory); + } + + Peer peer = peersStorageFactory.getPeersStorage().getPeer(uid); + logger.trace("set peer id to peer " + peer); + peer.setPeerId(ByteBuffer.wrap(hs.getPeerId())); + peer.setTorrentHash(hs.getHexInfoHash()); + ConnectionUtils.sendHandshake(socketChannel, hs.getInfoHash(), peersStorageFactory.getPeersStorage().getSelf().getPeerIdArray()); + SharedTorrent torrent = torrentsStorageFactory.getTorrentsStorage().getTorrent(hs.getHexInfoHash()); + SharingPeer sharingPeer = new SharingPeer(peer.getIp(), peer.getPort(), peer.getPeerId(), torrent); + sharingPeer.register(torrent); + sharingPeer.bind(socketChannel, true); + peersStorageFactory.getPeersStorage().addSharingPeer(peer, sharingPeer); + return new WorkingReceiver(this.uid, peersStorageFactory, torrentsStorageFactory); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `sharingPeer.hexPeerId` last assigned on line 90 could be null and is dereferenced by call to `bind(...)` at line 92. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +DataProcessor HandshakeReceiver.processAndGetNext(ByteChannel) + +### Procedure Id: +com.turn.ttorrent.client.network.HandshakeReceiver.processAndGetNext(java.nio.channels.ByteChannel):.1ff68496e425307ca21b07a073c11499 + +### File: +src/main/java/com/turn/ttorrent/client/network/HandshakeReceiver.java + +### Key: +HandshakeReceiver.java|processAndGetNext|NULL_DEREFERENCE + +### Node Key: +ba01ace7a7caa022fb6d2cdad5b791bd + +### Hash: +edbb7d182717367472b61248aa700206 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10043/instruction.md b/inferredbugs-10043/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef3956fb4c6d8accdedbb9f35627fe6dea4afa7d --- /dev/null +++ b/inferredbugs-10043/instruction.md @@ -0,0 +1,272 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ttorrent +**Bug ID:** 37 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2012 Turn, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.turn.ttorrent.client.announce; + +import com.turn.ttorrent.common.Peer; +import com.turn.ttorrent.common.TorrentInfo; +import com.turn.ttorrent.common.protocol.TrackerMessage.*; +import com.turn.ttorrent.common.protocol.http.*; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.output.ByteArrayOutputStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Announcer for HTTP trackers. + * + * @author mpetazzoni + * @see BitTorrent tracker request specification + */ +public class HTTPTrackerClient extends TrackerClient { + + protected static final Logger logger = + LoggerFactory.getLogger(HTTPTrackerClient.class); + + /** + * Create a new HTTP announcer for the given torrent. + * + * @param peers Our own peer specification. + */ + public HTTPTrackerClient(List peers, URI tracker) { + super(peers, tracker); + } + + /** + * Build, send and process a tracker announce request. + * + *

+ * This function first builds an announce request for the specified event + * with all the required parameters. Then, the request is made to the + * tracker and the response analyzed. + *

+ * + *

+ * All registered {@link AnnounceResponseListener} objects are then fired + * with the decoded payload. + *

+ * + * @param event The announce event type (can be AnnounceEvent.NONE for + * periodic updates). + * @param inhibitEvents Prevent event listeners from being notified. + * @param torrentInfo + */ + public void announce(final AnnounceRequestMessage.RequestEvent event, + boolean inhibitEvents, final TorrentInfo torrentInfo, final List peers) throws AnnounceException { + logAnnounceRequest(event, torrentInfo); + + List trackerResponses = new ArrayList(); + for (final Peer peer : peers) { + try { + HTTPAnnounceRequestMessage request = this.buildAnnounceRequest(event, torrentInfo, peer); + URL target = request.buildAnnounceURL(this.tracker.toURL()); + trackerResponses.add(sendAnnounce(target)); + } catch (MalformedURLException mue) { + throw new AnnounceException("Invalid announce URL (" + + mue.getMessage() + ")", mue); + } catch (MessageValidationException mve) { + throw new AnnounceException("Announce request creation violated " + + "expected protocol (" + mve.getMessage() + ")", mve); + } catch (IOException ioe) { + throw new AnnounceException("Error building announce request (" + + ioe.getMessage() + ")", ioe); + } + } + // we process only first request: + if (trackerResponses.size() > 0) { + final HTTPTrackerMessage message = trackerResponses.get(0); + this.handleTrackerAnnounceResponse(message, inhibitEvents, torrentInfo.getHexInfoHash()); + } + } + + private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException { + HttpURLConnection conn = null; + InputStream in = null; + try { + conn = (HttpURLConnection)url.openConnection(); + conn.setConnectTimeout(10000); + conn.setReadTimeout(10000); + in = conn.getInputStream(); + } catch (IOException ioe) { + if (conn != null) { + in = conn.getErrorStream(); + } + } + + // At this point if the input stream is null it means we have neither a + // response body nor an error stream from the server. No point in going + // any further. + if (in == null) { + throw new AnnounceException("No response or unreachable tracker!"); + } + + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + byte[] buf = new byte[8192]; + int len; + while ((len=in.read(buf)) > 0){ + baos.write(buf, 0, len); + } + + // Parse and handle the response + return HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray())); + } catch (IOException ioe) { + throw new AnnounceException("Error reading tracker response!", ioe); + } catch (MessageValidationException mve) { + throw new AnnounceException("Tracker message violates expected " + + "protocol (" + mve.getMessage() + ")", mve); + } finally { + // Make sure we close everything down at the end to avoid resource + // leaks. + try { + in.close(); + } catch (IOException ioe) { + logger.info("Problem ensuring error stream closed!"); + logger.debug("Problem ensuring error stream closed!", ioe); + } + + // This means trying to close the error stream as well. + InputStream err = conn.getErrorStream(); + if (err != null) { + try { + err.close(); + } catch (IOException ioe) { + logger.info("Problem ensuring error stream closed!"); + logger.debug("Problem ensuring error stream closed!", ioe); + } + } + } + } + + /** + * Build the announce request tracker message. + * + * @param event The announce event (can be NONE or null) + * @return Returns an instance of a {@link HTTPAnnounceRequestMessage} + * that can be used to generate the fully qualified announce URL, with + * parameters, to make the announce request. + * @throws UnsupportedEncodingException + * @throws IOException + * @throws MessageValidationException + */ + private HTTPAnnounceRequestMessage buildAnnounceRequest( + AnnounceRequestMessage.RequestEvent event, TorrentInfo torrentInfo, Peer peer) + throws IOException, + MessageValidationException { + // Build announce request message + final long uploaded = torrentInfo.getUploaded(); + final long downloaded = torrentInfo.getDownloaded(); + final long left = torrentInfo.getLeft(); + return HTTPAnnounceRequestMessage.craft( + torrentInfo.getInfoHash(), + peer.getPeerIdArray(), + peer.getPort(), + uploaded, + downloaded, + left, + true, false, event, + peer.getIp(), + AnnounceRequestMessage.DEFAULT_NUM_WANT); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.io.output.ByteArrayOutputStream` acquired to `baos` by call to `new()` at line 129 is not released after line 139. +**Note**: potential exception at line 133 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +HTTPTrackerMessage HTTPTrackerClient.sendAnnounce(URL) + +### Procedure Id: +com.turn.ttorrent.client.announce.HTTPTrackerClient.sendAnnounce(java.net.URL):com.turn.ttorrent.com.1ba1aad425b77c5305395d83fdb195e9 + +### File: +src/main/java/com/turn/ttorrent/client/announce/HTTPTrackerClient.java + +### Key: +HTTPTrackerClient.java|sendAnnounce|RESOURCE_LEAK + +### Node Key: +f645aafdf4c7de4e5a37ff7e8f2268a3 + +### Hash: +feb93ba608bb0b564b15deb66f7f3874 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10044/instruction.md b/inferredbugs-10044/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0d39b4b6be31c34f40669f4508a45375a87ed486 --- /dev/null +++ b/inferredbugs-10044/instruction.md @@ -0,0 +1,982 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ttorrent +**Bug ID:** 39 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2011-2012 Turn, Inc. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.turn.ttorrent.client; + +import com.turn.ttorrent.Constants; +import com.turn.ttorrent.client.announce.Announce; +import com.turn.ttorrent.client.announce.AnnounceException; +import com.turn.ttorrent.client.announce.AnnounceResponseListener; +import com.turn.ttorrent.client.network.*; +import com.turn.ttorrent.client.peer.PeerActivityListener; +import com.turn.ttorrent.client.peer.SharingPeer; +import com.turn.ttorrent.common.*; +import com.turn.ttorrent.common.protocol.PeerMessage; +import com.turn.ttorrent.common.protocol.TrackerMessage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URI; +import java.nio.ByteBuffer; +import java.util.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import static com.turn.ttorrent.Constants.DEFAULT_SOCKET_CONNECTION_TIMEOUT_MILLIS; + +/** + * A pure-java BitTorrent client. + *

+ *

+ * A BitTorrent client in its bare essence shares a given torrent. If the + * torrent is not complete locally, it will continue to download it. If or + * after the torrent is complete, the client may eventually continue to seed it + * for other clients. + *

+ *

+ *

+ * This BitTorrent client implementation is made to be simple to embed and + * simple to use. First, initialize a ShareTorrent object from a torrent + * meta-info source (either a file or a byte array, see + * com.turn.ttorrent.SharedTorrent for how to create a SharedTorrent object). + *

+ * + * @author mpetazzoni + */ +public class Client implements Runnable, + AnnounceResponseListener, PeerActivityListener, TorrentStateListener { + + protected static final Logger logger = LoggerFactory.getLogger(Client.class); + + /** + * Peers unchoking frequency, in seconds. Current BitTorrent specification + * recommends 10 seconds to avoid choking fibrilation. + */ + private static final int UNCHOKING_FREQUENCY = 3; + + /** + * Optimistic unchokes are done every 2 loop iterations, i.e. every + * 2*UNCHOKING_FREQUENCY seconds. + */ + private static final int OPTIMISTIC_UNCHOKE_ITERATIONS = 3; + + private static final int RATE_COMPUTATION_ITERATIONS = 2; + private static final int MAX_DOWNLOADERS_UNCHOKE = 10; + + /** + * Default data output directory. + */ + private static final String DEFAULT_OUTPUT_DIRECTORY = "/tmp"; + + public static final String BITTORRENT_ID_PREFIX = "-TO0042-"; + + private Thread thread; + private AtomicBoolean stop = new AtomicBoolean(false); + + private Announce announce; + + private Random random; + private boolean myStarted = false; + private final String myClientNameSuffix; + private final PeersStorageProvider peersStorageProvider; + private final TorrentsStorageProvider torrentsStorageProvider; + private final TorrentsStorage torrentsStorage; + private final CountLimitConnectionAllower myInConnectionAllower; + private final CountLimitConnectionAllower myOutConnectionAllower; + private final PeersStorage peersStorage; + private volatile ConnectionManager myConnectionManager; + private final ExecutorService myExecutorService; + + public Client(ExecutorService executorService) { + this("", executorService); + } + + /** + * @param name client thread name + * @param executorService executor service for run connection worker and process incoming data. Must have a pool size at least 2 + */ + public Client(String name, ExecutorService executorService) { + this.random = new Random(System.currentTimeMillis()); + this.announce = new Announce(); + this.peersStorageProvider = new PeersStorageProviderImpl(); + this.torrentsStorageProvider = new TorrentsStorageProviderImpl(); + this.torrentsStorage = this.torrentsStorageProvider.getTorrentsStorage(); + this.peersStorage = this.peersStorageProvider.getPeersStorage(); + this.myClientNameSuffix = name; + this.myInConnectionAllower = new CountLimitConnectionAllower(peersStorage); + this.myOutConnectionAllower = new CountLimitConnectionAllower(peersStorage); + this.myExecutorService = executorService; + } + + public void addTorrent(SharedTorrent torrent) throws IOException, InterruptedException { + if (torrent.getSize() == 0) { + // we don't seed zero-size files + return; + } + torrent.init(); + if (!torrent.isInitialized()) { + torrent.close(); + return; + } + + this.torrentsStorage.put(torrent.getHexInfoHash(), torrent); + + // Initial completion test + if (torrent.isFinished()) { + torrent.setClientState(ClientState.SEEDING); + } else { + torrent.setClientState(ClientState.SHARING); + } + torrent.setTorrentStateListener(this); + + this.announce.addTorrent(torrent, this); + logger.info(String.format("Added torrent %s (%s)", torrent.getName(), torrent.getHexInfoHash())); + } + + public void removeTorrent(TorrentHash torrentHash) { + logger.info("Stopping seeding " + torrentHash.getHexInfoHash()); + this.announce.removeTorrent(torrentHash); + + SharedTorrent torrent = this.torrentsStorage.remove(torrentHash.getHexInfoHash()); + if (torrent != null) { + torrent.setClientState(ClientState.DONE); + torrent.close(); + } else { + logger.warn(String.format("Torrent %s already removed from myTorrents", torrentHash.getHexInfoHash())); + } + } + + public void removeAndDeleteTorrent(TorrentHash torrentHash) { + this.announce.removeTorrent(torrentHash); + + SharedTorrent torrent = this.torrentsStorage.remove(torrentHash.getHexInfoHash()); + if (torrent != null) { + torrent.setClientState(ClientState.DONE); + torrent.delete(); + } + } + + public void setAnnounceInterval(final int announceInterval) { + announce.setAnnounceInterval(announceInterval); + } + + /** + * Return the torrent this client is exchanging on. + */ + public Collection getTorrents() { + return this.torrentsStorage.values(); + } + + public SharedTorrent getTorrentByFilePath(File file) { + String path = file.getAbsolutePath(); + for (SharedTorrent torrent : torrentsStorage.values()) { + File parentFile = torrent.getParentFile(); + final List filenames = torrent.getFilenames(); + for (String filename : filenames) { + File seededFile = new File(parentFile, filename); + if (seededFile.getAbsolutePath().equals(path)) { + return torrent; + } + } + } + return null; + } + + public URI getDefaultTrackerURI() { + return announce.getDefaultTrackerURI(); + } + + /** + * Returns the set of known peers. + */ + public Set getPeers() { + return new HashSet(this.peersStorage.getSharingPeers()); + } + + public void setMaxInConnectionsCount(int maxConnectionsCount) { + this.myInConnectionAllower.setMyMaxConnectionCount(maxConnectionsCount); + } + + public void setMaxOutConnectionsCount(int maxConnectionsCount) { + this.myOutConnectionAllower.setMyMaxConnectionCount(maxConnectionsCount); + } + + public void start(final InetAddress... bindAddresses) throws IOException { + start(bindAddresses, Constants.DEFAULT_ANNOUNCE_INTERVAL_SEC, null); + } + + public void start(final InetAddress[] bindAddresses, final URI defaultTrackerURI) throws IOException { + start(bindAddresses, Constants.DEFAULT_ANNOUNCE_INTERVAL_SEC, defaultTrackerURI); + } + + public Peer[] getSelfPeers(final InetAddress[] bindAddresses) throws UnsupportedEncodingException { + Peer self = this.peersStorageProvider.getPeersStorage().getSelf(); + + if (self == null) { + return new Peer[0]; + } + + Peer[] result = new Peer[bindAddresses.length]; + for (int i = 0; i < bindAddresses.length; i++) { + final InetAddress bindAddress = bindAddresses[i]; + final Peer peer = new Peer(new InetSocketAddress(bindAddress.getHostAddress(), self.getPort())); + peer.setTorrentHash(self.getHexInfoHash()); + //if we have more, that one bind address, then only for first set self peer id. For other generate it + if (i == 0) { + peer.setPeerId(self.getPeerId()); + } else { + final String id = Client.BITTORRENT_ID_PREFIX + UUID.randomUUID().toString().split("-")[4]; + byte[] idBytes = id.getBytes(Torrent.BYTE_ENCODING); + peer.setPeerId(ByteBuffer.wrap(idBytes)); + } + result[i] = peer; + } + return result; + } + + public void start(final InetAddress[] bindAddresses, final int announceIntervalSec, final URI defaultTrackerURI) throws IOException { + ChannelListenerFactoryImpl channelListenerFactory = new ChannelListenerFactoryImpl(peersStorageProvider, + torrentsStorageProvider, + myExecutorService, + new SharingPeerFactoryImpl(this)); + this.myConnectionManager = new ConnectionManager(channelListenerFactory, + myExecutorService, + new SystemTimeService(), + myInConnectionAllower, + myOutConnectionAllower); + this.setSocketConnectionTimeout(DEFAULT_SOCKET_CONNECTION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + try { + this.myConnectionManager.initAndRunWorker(); + } catch (IOException e) { + LoggerUtils.errorAndDebugDetails(logger, "error in initialization server channel", e); + this.stop(); + return; + } + final String id = Client.BITTORRENT_ID_PREFIX + UUID.randomUUID().toString().split("-")[4]; + byte[] idBytes = id.getBytes(Torrent.BYTE_ENCODING); + Peer self = new Peer(new InetSocketAddress(myConnectionManager.getBindPort()), ByteBuffer.wrap(idBytes)); + peersStorageProvider.getPeersStorage().setSelf(self); + logger.info("BitTorrent client [{}] started and " + + "listening at {}:{}...", + new Object[]{ + self.getShortHexPeerId(), + self.getIp(), + self.getPort() + }); + + announce.start(defaultTrackerURI, this, getSelfPeers(bindAddresses), announceIntervalSec); + this.stop.set(false); + + if (this.thread == null || !this.thread.isAlive()) { + this.thread = new Thread(this); + this.thread.setName("bt-client " + myClientNameSuffix); + this.thread.start(); + } + myStarted = true; + } + + /** + * Immediately but gracefully stop this client. + */ + public void stop() { + this.stop(60, TimeUnit.SECONDS); + } + + public void stop(int timeout, TimeUnit timeUnit) { + boolean wasStopped = this.stop.getAndSet(true); + if (wasStopped) return; + + if (!myStarted) + return; + + boolean wait = timeout != 0; + this.myConnectionManager.close(); + + if (this.thread != null && this.thread.isAlive()) { + this.thread.interrupt(); + if (wait) { + this.waitForCompletion(); + } + } + this.thread = null; + } + + public void setCleanupTimeout(int timeout, TimeUnit timeUnit) throws IllegalStateException { + ConnectionManager connectionManager = this.myConnectionManager; + if (connectionManager == null) { + throw new IllegalStateException("connection manager is null"); + } + connectionManager.setCleanupTimeout(timeUnit.toMillis(timeout)); + } + + public void setSocketConnectionTimeout(int timeout, TimeUnit timeUnit) throws IllegalStateException { + ConnectionManager connectionManager = this.myConnectionManager; + if (connectionManager == null) { + throw new IllegalStateException("connection manager is null"); + } + connectionManager.setSocketConnectionTimeout(timeUnit.toMillis(timeout)); + } + + + /** + * Wait for downloading (and seeding, if requested) to complete. + */ + public void waitForCompletion() { + if (this.thread != null && this.thread.isAlive()) { + try { + this.thread.join(); + } catch (InterruptedException ie) { + logger.error(ie.getMessage(), ie); + } + } + } + + /** + * Tells whether we are a seed for the torrent we're sharing. + */ + public boolean isSeed(String hexInfoHash) { + SharedTorrent t = this.torrentsStorage.getTorrent(hexInfoHash); + return t != null && t.isComplete(); + } + + public void downloadUninterruptibly(final SharedTorrent torrent, + final long downloadTimeoutSeconds) throws IOException, InterruptedException { + downloadUninterruptibly(torrent, downloadTimeoutSeconds, 1, new AtomicBoolean(false)); + } + + public void downloadUninterruptibly(final SharedTorrent torrent, + final long idleTimeoutSec, + final int minSeedersCount, + final AtomicBoolean isInterrupted) throws IOException, InterruptedException { + addTorrent(torrent); + // we must ensure that at every moment we are downloading a piece of that torrent + int seedersCount = torrent.getSeedersCount(); + long maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000; + long currentLeft = torrent.getLeft(); + + while (torrent.getClientState() != ClientState.SEEDING && + torrent.getClientState() != ClientState.ERROR && + ((seedersCount = torrent.getSeedersCount()) >= minSeedersCount || torrent.getLastAnnounceTime() < 0) && + (System.currentTimeMillis() <= maxIdleTime)) { + if (Thread.currentThread().isInterrupted() || isInterrupted.get()) + throw new InterruptedException("Download of " + torrent.getName() + " was interrupted"); + if (currentLeft > torrent.getLeft()) { + currentLeft = torrent.getLeft(); + maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000; + } + Thread.sleep(100); + } + if (!(torrent.isFinished() && torrent.getClientState() == ClientState.SEEDING)) { + removeAndDeleteTorrent(torrent); + + final List peersForTorrent = getPeersForTorrent(torrent.getHexInfoHash()); + int connectedPeersForTorrent = peersForTorrent.size(); + for (SharingPeer peer : peersForTorrent) { + peer.unbind(true); + } + + final String errorMsg; + if (System.currentTimeMillis() > maxIdleTime) { + int completedPieces = torrent.getCompletedPieces().cardinality(); + int totalPieces = torrent.getPieceCount(); + errorMsg = String.format("No pieces has been downloaded in %d seconds. Downloaded pieces %d/%d, connected peers %d" + , idleTimeoutSec, completedPieces, totalPieces, connectedPeersForTorrent); + } else if (seedersCount < minSeedersCount) { + errorMsg = String.format("Not enough seeders. Required %d, found %d", minSeedersCount, seedersCount); + } else if (torrent.getClientState() == ClientState.ERROR) { + errorMsg = "Torrent state is ERROR"; + } else { + errorMsg = "Unknown error"; + } + throw new IOException("Unable to download torrent completely - " + errorMsg); + } + } + + public List getPeersForTorrent(String torrentHash) { + if (torrentHash == null) return new ArrayList(); + + List result = new ArrayList(); + for (SharingPeer sharingPeer : peersStorage.getSharingPeers()) { + if (torrentHash.equals(sharingPeer.getHexInfoHash())) { + result.add(sharingPeer); + } + } + return result; + } + + /** + * Main client loop. + *

+ *

+ * The main client download loop is very simple: it starts the announce + * request thread, the incoming connection handler service, and loops + * unchoking peers every UNCHOKING_FREQUENCY seconds until told to stop. + * Every OPTIMISTIC_UNCHOKE_ITERATIONS, an optimistic unchoke will be + * attempted to try out other peers. + *

+ *

+ *

+ * Once done, it stops the announce and connection services, and returns. + *

+ */ + @Override + public void run() { + // Detect early stop + if (this.stop.get()) { + logger.info("Early stop detected. Stopping..."); + this.finish(); + return; + } + + int optimisticIterations = 0; + int rateComputationIterations = 0; + + while (!this.stop.get()) { + optimisticIterations = + (optimisticIterations == 0 ? + Client.OPTIMISTIC_UNCHOKE_ITERATIONS : + optimisticIterations - 1); + + rateComputationIterations = + (rateComputationIterations == 0 ? + Client.RATE_COMPUTATION_ITERATIONS : + rateComputationIterations - 1); + + try { + this.unchokePeers(optimisticIterations == 0); + this.info(); + if (rateComputationIterations == 0) { + this.resetPeerRates(); + } + } catch (Exception e) { + logger.error("An exception occurred during the BitTorrent " + + "client main loop execution!", e); + } + + try { + Thread.sleep(Client.UNCHOKING_FREQUENCY * 1000); + } catch (InterruptedException ie) { + logger.trace("BitTorrent main loop interrupted."); + break; + } + } + + // Close all peer connections + logger.debug("Closing all remaining peer connections..."); + for (SharingPeer peer : this.peersStorage.getSharingPeers()) { + peer.unbind(true); + } + + this.finish(); + } + + public boolean isRunning() { + return this.thread != null && this.thread.isAlive(); + } + + /** + * Close torrent and set final client state before signing off. + */ + private void finish() { + logger.trace("try stop announce thread..."); + + this.announce.stop(); + + logger.trace("announce thread is stopped"); + + for (SharedTorrent torrent : this.torrentsStorage.values()) { + logger.trace("try close torrent {}", torrent); + torrent.close(); + if (torrent.isFinished()) { + torrent.setClientState(ClientState.DONE); + } else { + torrent.setClientState(ClientState.ERROR); + } + } + + logger.info("BitTorrent client signing off."); + } + + /** + * Display information about the BitTorrent client state. + *

+ *

+ * This emits an information line in the log about this client's state. It + * includes the number of choked peers, number of connected peers, number + * of known peers, information about the torrent availability and + * completion and current transmission rates. + *

+ */ + public synchronized void info() { + float dl = 0; + float ul = 0; + int numConnected = 0; + for (SharingPeer peer : getConnectedPeers()) { + dl += peer.getDLRate().get(); + ul += peer.getULRate().get(); + numConnected++; + } + +/* + for (SharedTorrent torrent : this.torrents.values()) { + logger.debug("[{}]{} {}/{} (Downloaded {} bytes) pieces ({}%) [{}/{}] with {}/{} peers at {}/{} kB/s.", + new Object[]{ + Arrays.toString(torrent.getFilenames().toArray()), + torrent.getClientState().name(), + torrent.getCompletedPieces().cardinality(), + torrent.getPieceCount(), + torrent.getDownloaded(), + String.format("%.2f", torrent.getCompletion()), + torrent.getAvailablePieces().cardinality(), + torrent.getRequestedPieces().cardinality(), + numConnected, + this.peers.size(), + String.format("%.2f", dl / 1024.0), + String.format("%.2f", ul / 1024.0), + }); + } +*/ +// logger.debug("Downloaded bytes: {}", PeerExchange.readBytes); + + } + + /** + * Reset peers download and upload rates. + *

+ *

+ * This method is called every RATE_COMPUTATION_ITERATIONS to reset the + * download and upload rates of all peers. This contributes to making the + * download and upload rate computations rolling averages every + * UNCHOKING_FREQUENCY * RATE_COMPUTATION_ITERATIONS seconds (usually 20 + * seconds). + *

+ */ + private synchronized void resetPeerRates() { + for (SharingPeer peer : getConnectedPeers()) { + peer.getDLRate().reset(); + peer.getULRate().reset(); + } + } + + /** + * Retrieve a peer comparator. + *

+ *

+ * Returns a peer comparator based on either the download rate or the + * upload rate of each peer depending on our state. While sharing, we rely + * on the download rate we get from each peer. When our download is + * complete and we're only seeding, we use the upload rate instead. + *

+ * + * @return A SharingPeer comparator that can be used to sort peers based on + * the download or upload rate we get from them. + */ + private Comparator getPeerRateComparator() { +/* + if (this.seed == 0) { + return new SharingPeer.ULRateComparator(); + } +*/ + + return new SharingPeer.DLRateComparator(); + } + + /** + * Unchoke connected peers. + *

+ *

+ * This is one of the "clever" places of the BitTorrent client. Every + * OPTIMISTIC_UNCHOKING_FREQUENCY seconds, we decide which peers should be + * unchocked and authorized to grab pieces from us. + *

+ *

+ *

+ * Reciprocation (tit-for-tat) and upload capping is implemented here by + * carefully choosing which peers we unchoke, and which peers we choke. + *

+ *

+ *

+ * The four peers with the best download rate and are interested in us get + * unchoked. This maximizes our download rate as we'll be able to get data + * from there four "best" peers quickly, while allowing these peers to + * download from us and thus reciprocate their generosity. + *

+ *

+ *

+ * Peers that have a better download rate than these four downloaders but + * are not interested get unchoked too, we want to be able to download from + * them to get more data more quickly. If one becomes interested, it takes + * a downloader's place as one of the four top downloaders (i.e. we choke + * the downloader with the worst upload rate). + *

+ * + * @param optimistic Whether to perform an optimistic unchoke as well. + */ + private synchronized void unchokePeers(boolean optimistic) { + // Build a set of all connected peers, we don't care about peers we're + // not connected to. + List bound = new ArrayList(peersStorage.getSharingPeers()); + Collections.sort(bound, this.getPeerRateComparator()); + Collections.reverse(bound); + if (bound.size() == 0) { + logger.trace("No connected peers, skipping unchoking."); + return; + } else { + logger.trace("Running unchokePeers() on {} connected peers. Client {}", + new Object[]{bound.size(), Thread.currentThread()}); + } + + int downloaders = 0; + Set choked = new HashSet(); + + // We're interested in the top downloaders first, so use a descending + // set. + for (SharingPeer peer : bound) { + if (downloaders < Client.MAX_DOWNLOADERS_UNCHOKE) { + // Unchoke up to MAX_DOWNLOADERS_UNCHOKE interested peers + if (peer.isInterested()) { + downloaders++; + peer.unchoke(); + } + continue; + } + // Choke everybody else + choked.add(peer); + } + + // Actually choke all chosen peers (if any), except the eventual + // optimistic unchoke. + if (choked.size() > 0) { + SharingPeer randomPeer = choked.toArray( + new SharingPeer[0])[this.random.nextInt(choked.size())]; + + for (SharingPeer peer : choked) { + if (optimistic && peer == randomPeer) { + logger.debug("Optimistic unchoke of {}.", peer); + continue; + } + + peer.choke(); + } + } + } + + private Collection getConnectedPeers() { + Set result = new HashSet(); + Set toRemove = new HashSet(); + for (SharingPeer peer : this.peersStorage.getSharingPeers()) { + if (peer.isConnected()) { + result.add(peer); + } else { + toRemove.add(peer); + } + } + for (SharingPeer peer : toRemove) { + this.peersStorage.removeSharingPeer(peer); + } + return result; + } + + public boolean containsTorrentWithHash(String hash) { + return torrentsStorage.hasTorrent(hash); + } + + /** AnnounceResponseListener handler(s). **********************************/ + + /** + * Handle an announce response event. + * + * @param interval The announce interval requested by the tracker. + * @param complete The number of seeders on this torrent. + * @param incomplete The number of leechers on this torrent. + */ + @Override + public void handleAnnounceResponse(int interval, int complete, int incomplete, String hexInfoHash) { + final SharedTorrent sharedTorrent = this.torrentsStorage.getTorrent(hexInfoHash); + if (sharedTorrent != null) { + sharedTorrent.setSeedersCount(complete); + sharedTorrent.setLastAnnounceTime(System.currentTimeMillis()); + } + setAnnounceInterval(interval); + } + + /** + * Handle the discovery of new peers. + * + * @param peers The list of peers discovered (from the announce response or + * any other means like DHT/PEX, etc.). + */ + @Override + public void handleDiscoveredPeers(List peers, String hexInfoHash) { + logger.info("Got {} peer(s) ({}) for {} in tracker response", new Object[]{peers.size(), + Arrays.toString(peers.toArray()), hexInfoHash}); + + SharedTorrent torrent = torrentsStorage.getTorrent(hexInfoHash); + + for (Peer peer : peers) { + + boolean alreadyConnectedToThisPeer = false; + String peerId = peersStorage.getPeerIdByAddress(peer.getIp(), peer.getPort()); + if (peerId != null) { + PeerUID peerUID = new PeerUID(peerId, hexInfoHash); + alreadyConnectedToThisPeer = peersStorage.getSharingPeer(peerUID) != null; + } + + if (alreadyConnectedToThisPeer) { + logger.debug("skipping peer {}, because we already connected to this peer", peer); + continue; + } + + ConnectionListener connectionListener = new OutgoingConnectionListener( + peersStorageProvider, + torrentsStorageProvider, + new SharingPeerFactoryImpl(this), torrent, + new InetSocketAddress(peer.getIp(), peer.getPort()), + myExecutorService); + + logger.debug("trying to connect to the peer {}", peer); + + boolean connectTaskAdded = this.myConnectionManager.offerConnect( + new ConnectTask(peer.getIp(), + peer.getPort(), + connectionListener, + new SystemTimeService().now(), + Constants.DEFAULT_CONNECTION_TIMEOUT_MILLIS), 1, TimeUnit.SECONDS); + if (!connectTaskAdded) { + logger.info("can not connect to peer {}. Unable to add connect task to connection manager", peer); + } + } + } + + /** + * PeerActivityListener handler(s). ************************************* + */ + + @Override + public void handlePeerChoked(SharingPeer peer) { /* Do nothing */ } + + @Override + public void handlePeerReady(SharingPeer peer) { /* Do nothing */ } + + @Override + public void handlePieceAvailability(SharingPeer peer, + Piece piece) { /* Do nothing */ } + + @Override + public void handleBitfieldAvailability(SharingPeer peer, + BitSet availablePieces) { /* Do nothing */ } + + @Override + public void handlePieceSent(SharingPeer peer, + Piece piece) { /* Do nothing */ } + + /** + * Piece download completion handler. + *

+ *

+ * When a piece is completed, and valid, we announce to all connected peers + * that we now have this piece. + *

+ *

+ *

+ * We use this handler to identify when all of the pieces have been + * downloaded. When that's the case, we can start the seeding period, if + * any. + *

+ * + * @param peer The peer we got the piece from. + * @param piece The piece in question. + */ + @Override + public void handlePieceCompleted(final SharingPeer peer, Piece piece) + throws IOException { + final SharedTorrent torrent = peer.getTorrent(); + synchronized (torrent) { + if (piece.isValid()) { + // Make sure the piece is marked as completed in the torrent + // Note: this is required because the order the + // PeerActivityListeners are called is not defined, and we + // might be called before the torrent's piece completion + // handler is. + torrent.markCompleted(piece); + logger.debug("Completed download of {} from {}, now has {}/{} pieces.", + new Object[]{ + piece, + peer, + torrent.getCompletedPieces().cardinality(), + torrent.getPieceCount() + }); + + // Send a HAVE message to all connected peers + PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex()); + final String torrentHash = torrent.getHexInfoHash(); + for (SharingPeer remote : getConnectedPeers()) { + if (remote.getTorrent().getHexInfoHash().equals(torrentHash)) + remote.send(have); + } + + BitSet completed = new BitSet(); + completed.or(torrent.getCompletedPieces()); + completed.and(peer.getAvailablePieces()); + if (completed.equals(peer.getAvailablePieces())) { + // send not interested when have no interested pieces; + peer.send(PeerMessage.NotInterestedMessage.craft()); + } + + } else { + logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer); + peer.getPoorlyAvailablePieces().set(piece.getIndex()); + } + + if (torrent.isComplete()) { + //close connection with all peers for this torrent + logger.info("Download of {} complete.", torrent.getName()); + + torrent.finish(); + + try { + this.announce.getCurrentTrackerClient(torrent) + .announceAllInterfaces(TrackerMessage.AnnounceRequestMessage.RequestEvent.COMPLETED, true, torrent); + } catch (AnnounceException e) { + logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce()); + } + + } + } + } + + @Override + public void handlePeerDisconnected(SharingPeer peer) { + final SharedTorrent peerTorrent = peer.getTorrent(); + Peer p = new Peer(peer.getIp(), peer.getPort()); + p.setPeerId(peer.getPeerId()); + p.setTorrentHash(peer.getHexInfoHash()); + PeerUID peerUID = new PeerUID(p.getStringPeerId(), p.getHexInfoHash()); + SharingPeer sharingPeer = this.peersStorage.removeSharingPeer(peerUID); + logger.debug("Peer {} disconnected, [{}/{}].", + new Object[]{ + peer, + getConnectedPeers().size(), + this.peersStorage.getSharingPeers().size() + }); + } + + @Override + public void handleIOException(SharingPeer peer, IOException ioe) { + logger.debug("I/O problem occured when reading or writing piece data for peer {}: {}.", peer, ioe.getMessage()); + + peer.unbind(true); + } + + @Override + public void handleNewPeerConnected(SharingPeer peer) { + //do nothing + } + + @Override + public void torrentStateChanged(ClientState newState, SharedTorrent torrent) { + if (newState.equals(ClientState.ERROR)) { + removeTorrent(torrent); + } + } + + public ConnectionManager getConnectionManager() throws IllegalStateException { + ConnectionManager connectionManager = this.myConnectionManager; + if (connectionManager == null) { + throw new IllegalStateException("connection manager is null"); + } + return connectionManager; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `Client.announce.getCurrentTrackerClient(torrent)` could be null and is dereferenced at line 857. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Client.handlePieceCompleted(SharingPeer,Piece) + +### Procedure Id: +com.turn.ttorrent.client.Client.handlePieceCompleted(com.turn.ttorrent.client.peer.SharingPeer,com.t.125f29b82f5812c06334c7d1b1514ba0 + +### File: +src/main/java/com/turn/ttorrent/client/Client.java + +### Key: +Client.java|handlePieceCompleted|NULL_DEREFERENCE + +### Node Key: +da9314e4de9524be1935785051e00611 + +### Hash: +50404a1e9df6ce6fce6f92944fd5c821 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10072/instruction.md b/inferredbugs-10072/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f467a5793c403b1ff2cf59401edfa642dec6fc7f --- /dev/null +++ b/inferredbugs-10072/instruction.md @@ -0,0 +1,430 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ik-analyzer-solr +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * IK 中文分词 版本 7.0 + * IK Analyzer release 7.0 + * update by 高志成(magese@live.cn) + */ +package org.wltea.analyzer.dic; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Collection; +import java.util.List; + +import org.wltea.analyzer.cfg.Configuration; +import org.wltea.analyzer.cfg.DefaultConfig; + +/** + * 词典管理类,单子模式 + */ +@SuppressWarnings("unused") +public class Dictionary { + + /* + * 词典单子实例 + */ + private static Dictionary singleton; + + /* + * 主词典对象 + */ + private DictSegment _MainDict; + + /* + * 停止词词典 + */ + private DictSegment _StopWordDict; + /* + * 量词词典 + */ + private DictSegment _QuantifierDict; + + /** + * 配置对象 + */ + private Configuration cfg; + + private Dictionary(Configuration cfg) { + this.cfg = cfg; + this.loadMainDict(); + this.loadStopWordDict(); + this.loadQuantifierDict(); + } + + /** + * 词典初始化 + * 由于IK Analyzer的词典采用Dictionary类的静态方法进行词典初始化 + * 只有当Dictionary类被实际调用时,才会开始载入词典, + * 这将延长首次分词操作的时间 + * 该方法提供了一个在应用加载阶段就初始化字典的手段 + */ + public static void initial(Configuration cfg) { + if (singleton == null) { + synchronized (Dictionary.class) { + if (singleton == null) { + singleton = new Dictionary(cfg); + } + } + } + } + + /** + * 获取词典单子实例 + * + * @return Dictionary 单例对象 + */ + public static Dictionary getSingleton() { + if (singleton == null) { + throw new IllegalStateException("词典尚未初始化,请先调用initial方法"); + } + return singleton; + } + + /** + * 重新更新词典 + * 由于停用词等不经常变也不建议常增加,故这里只修改动态扩展词库 + */ + public static void reloadDic(List inputStreamList) { + if (singleton == null) { + Configuration cfg = DefaultConfig.getInstance(); + initial(cfg); + } + for (InputStream is : inputStreamList) { + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + singleton._MainDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + } catch (IOException ioe) { + System.err.println("Other Dictionary loading exception."); + ioe.printStackTrace(); + } finally { + try { + if (is != null) { + is.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + /** + * 批量加载新词条 + * + * @param words 词条列表 + */ + public void addWords(Collection words) { + if (words != null) { + for (String word : words) { + if (word != null) { + //批量加载词条到主内存词典中 + singleton._MainDict.fillSegment(word.trim().toLowerCase().toCharArray()); + } + } + } + } + + /** + * 批量移除(屏蔽)词条 + */ + public void disableWords(Collection words) { + if (words != null) { + for (String word : words) { + if (word != null) { + //批量屏蔽词条 + singleton._MainDict.disableSegment(word.trim().toLowerCase().toCharArray()); + } + } + } + } + + /** + * 检索匹配主词典 + * + * @return Hit 匹配结果描述 + */ + public Hit matchInMainDict(char[] charArray) { + return singleton._MainDict.match(charArray); + } + + /** + * 检索匹配主词典 + * + * @return Hit 匹配结果描述 + */ + public Hit matchInMainDict(char[] charArray, int begin, int length) { + return singleton._MainDict.match(charArray, begin, length); + } + + /** + * 检索匹配量词词典 + * + * @return Hit 匹配结果描述 + */ + public Hit matchInQuantifierDict(char[] charArray, int begin, int length) { + return singleton._QuantifierDict.match(charArray, begin, length); + } + + + /** + * 从已匹配的Hit中直接取出DictSegment,继续向下匹配 + * + * @return Hit + */ + public Hit matchWithHit(char[] charArray, int currentIndex, Hit matchedHit) { + DictSegment ds = matchedHit.getMatchedDictSegment(); + return ds.match(charArray, currentIndex, 1, matchedHit); + } + + + /** + * 判断是否是停止词 + * + * @return boolean + */ + public boolean isStopWord(char[] charArray, int begin, int length) { + return singleton._StopWordDict.match(charArray, begin, length).isMatch(); + } + + /** + * 加载主词典及扩展词典 + */ + private void loadMainDict() { + //建立一个主词典实例 + _MainDict = new DictSegment((char) 0); + //读取主词典文件 + InputStream is = this.getClass().getClassLoader().getResourceAsStream(cfg.getMainDictionary()); + if (is == null) { + throw new RuntimeException("Main Dictionary not found!!!"); + } + + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + _MainDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + + } catch (IOException ioe) { + System.err.println("Main Dictionary loading exception."); + ioe.printStackTrace(); + + } finally { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + //加载扩展词典 + this.loadExtDict(); + } + + /** + * 加载用户配置的扩展词典到主词库表 + */ + private void loadExtDict() { + //加载扩展词典配置 + List extDictFiles = cfg.getExtDictionarys(); + if (extDictFiles != null) { + InputStream is; + for (String extDictName : extDictFiles) { + //读取扩展词典文件 + System.out.println("加载扩展词典:" + extDictName); + is = this.getClass().getClassLoader().getResourceAsStream(extDictName); + //如果找不到扩展的字典,则忽略 + if (is == null) { + continue; + } + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + //加载扩展词典数据到主内存词典中 + //System.out.println(theWord); + _MainDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + + } catch (IOException ioe) { + System.err.println("Extension Dictionary loading exception."); + ioe.printStackTrace(); + + } finally { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } + + /** + * 加载用户扩展的停止词词典 + */ + private void loadStopWordDict() { + //建立一个主词典实例 + _StopWordDict = new DictSegment((char) 0); + //加载扩展停止词典 + List extStopWordDictFiles = cfg.getExtStopWordDictionarys(); + if (extStopWordDictFiles != null) { + InputStream is; + for (String extStopWordDictName : extStopWordDictFiles) { + System.out.println("加载扩展停止词典:" + extStopWordDictName); + //读取扩展词典文件 + is = this.getClass().getClassLoader().getResourceAsStream(extStopWordDictName); + //如果找不到扩展的字典,则忽略 + if (is == null) { + continue; + } + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + //System.out.println(theWord); + //加载扩展停止词典数据到内存中 + _StopWordDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + + } catch (IOException ioe) { + System.err.println("Extension Stop word Dictionary loading exception."); + ioe.printStackTrace(); + + } finally { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } + + /** + * 加载量词词典 + */ + private void loadQuantifierDict() { + //建立一个量词典实例 + _QuantifierDict = new DictSegment((char) 0); + //读取量词词典文件 + InputStream is = this.getClass().getClassLoader().getResourceAsStream(cfg.getQuantifierDicionary()); + if (is == null) { + throw new RuntimeException("Quantifier Dictionary not found!!!"); + } + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + _QuantifierDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + + } catch (IOException ioe) { + System.err.println("Quantifier Dictionary loading exception."); + ioe.printStackTrace(); + + } finally { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `InputStreamReader(...)` at line 209 is not released after line 218. +**Note**: potential exception at line 212 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Dictionary.loadMainDict() + +### Procedure Id: +org.wltea.analyzer.dic.Dictionary.loadMainDict():void.5444da1b3f5445b04732010759d0af65 + +### File: +src/main/java/org/wltea/analyzer/dic/Dictionary.java + +### Key: +Dictionary.java|loadMainDict|RESOURCE_LEAK + +### Node Key: +f645aafdf4c7de4e5a37ff7e8f2268a3 + +### Hash: +a9c539c41c647bb126eb613ae7079448 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10073/instruction.md b/inferredbugs-10073/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..42911a21d4a8355aede782483f0366d3cef9ae29 --- /dev/null +++ b/inferredbugs-10073/instruction.md @@ -0,0 +1,430 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ik-analyzer-solr +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * IK 中文分词 版本 7.0 + * IK Analyzer release 7.0 + * update by 高志成(magese@live.cn) + */ +package org.wltea.analyzer.dic; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Collection; +import java.util.List; + +import org.wltea.analyzer.cfg.Configuration; +import org.wltea.analyzer.cfg.DefaultConfig; + +/** + * 词典管理类,单子模式 + */ +@SuppressWarnings("unused") +public class Dictionary { + + /* + * 词典单子实例 + */ + private static Dictionary singleton; + + /* + * 主词典对象 + */ + private DictSegment _MainDict; + + /* + * 停止词词典 + */ + private DictSegment _StopWordDict; + /* + * 量词词典 + */ + private DictSegment _QuantifierDict; + + /** + * 配置对象 + */ + private Configuration cfg; + + private Dictionary(Configuration cfg) { + this.cfg = cfg; + this.loadMainDict(); + this.loadStopWordDict(); + this.loadQuantifierDict(); + } + + /** + * 词典初始化 + * 由于IK Analyzer的词典采用Dictionary类的静态方法进行词典初始化 + * 只有当Dictionary类被实际调用时,才会开始载入词典, + * 这将延长首次分词操作的时间 + * 该方法提供了一个在应用加载阶段就初始化字典的手段 + */ + public static void initial(Configuration cfg) { + if (singleton == null) { + synchronized (Dictionary.class) { + if (singleton == null) { + singleton = new Dictionary(cfg); + } + } + } + } + + /** + * 获取词典单子实例 + * + * @return Dictionary 单例对象 + */ + public static Dictionary getSingleton() { + if (singleton == null) { + throw new IllegalStateException("词典尚未初始化,请先调用initial方法"); + } + return singleton; + } + + /** + * 重新更新词典 + * 由于停用词等不经常变也不建议常增加,故这里只修改动态扩展词库 + */ + public static void reloadDic(List inputStreamList) { + if (singleton == null) { + Configuration cfg = DefaultConfig.getInstance(); + initial(cfg); + } + for (InputStream is : inputStreamList) { + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + singleton._MainDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + } catch (IOException ioe) { + System.err.println("Other Dictionary loading exception."); + ioe.printStackTrace(); + } finally { + try { + if (is != null) { + is.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + /** + * 批量加载新词条 + * + * @param words 词条列表 + */ + public void addWords(Collection words) { + if (words != null) { + for (String word : words) { + if (word != null) { + //批量加载词条到主内存词典中 + singleton._MainDict.fillSegment(word.trim().toLowerCase().toCharArray()); + } + } + } + } + + /** + * 批量移除(屏蔽)词条 + */ + public void disableWords(Collection words) { + if (words != null) { + for (String word : words) { + if (word != null) { + //批量屏蔽词条 + singleton._MainDict.disableSegment(word.trim().toLowerCase().toCharArray()); + } + } + } + } + + /** + * 检索匹配主词典 + * + * @return Hit 匹配结果描述 + */ + public Hit matchInMainDict(char[] charArray) { + return singleton._MainDict.match(charArray); + } + + /** + * 检索匹配主词典 + * + * @return Hit 匹配结果描述 + */ + public Hit matchInMainDict(char[] charArray, int begin, int length) { + return singleton._MainDict.match(charArray, begin, length); + } + + /** + * 检索匹配量词词典 + * + * @return Hit 匹配结果描述 + */ + public Hit matchInQuantifierDict(char[] charArray, int begin, int length) { + return singleton._QuantifierDict.match(charArray, begin, length); + } + + + /** + * 从已匹配的Hit中直接取出DictSegment,继续向下匹配 + * + * @return Hit + */ + public Hit matchWithHit(char[] charArray, int currentIndex, Hit matchedHit) { + DictSegment ds = matchedHit.getMatchedDictSegment(); + return ds.match(charArray, currentIndex, 1, matchedHit); + } + + + /** + * 判断是否是停止词 + * + * @return boolean + */ + public boolean isStopWord(char[] charArray, int begin, int length) { + return singleton._StopWordDict.match(charArray, begin, length).isMatch(); + } + + /** + * 加载主词典及扩展词典 + */ + private void loadMainDict() { + //建立一个主词典实例 + _MainDict = new DictSegment((char) 0); + //读取主词典文件 + InputStream is = this.getClass().getClassLoader().getResourceAsStream(cfg.getMainDictionary()); + if (is == null) { + throw new RuntimeException("Main Dictionary not found!!!"); + } + + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + _MainDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + + } catch (IOException ioe) { + System.err.println("Main Dictionary loading exception."); + ioe.printStackTrace(); + + } finally { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + //加载扩展词典 + this.loadExtDict(); + } + + /** + * 加载用户配置的扩展词典到主词库表 + */ + private void loadExtDict() { + //加载扩展词典配置 + List extDictFiles = cfg.getExtDictionarys(); + if (extDictFiles != null) { + InputStream is; + for (String extDictName : extDictFiles) { + //读取扩展词典文件 + System.out.println("加载扩展词典:" + extDictName); + is = this.getClass().getClassLoader().getResourceAsStream(extDictName); + //如果找不到扩展的字典,则忽略 + if (is == null) { + continue; + } + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + //加载扩展词典数据到主内存词典中 + //System.out.println(theWord); + _MainDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + + } catch (IOException ioe) { + System.err.println("Extension Dictionary loading exception."); + ioe.printStackTrace(); + + } finally { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } + + /** + * 加载用户扩展的停止词词典 + */ + private void loadStopWordDict() { + //建立一个主词典实例 + _StopWordDict = new DictSegment((char) 0); + //加载扩展停止词典 + List extStopWordDictFiles = cfg.getExtStopWordDictionarys(); + if (extStopWordDictFiles != null) { + InputStream is; + for (String extStopWordDictName : extStopWordDictFiles) { + System.out.println("加载扩展停止词典:" + extStopWordDictName); + //读取扩展词典文件 + is = this.getClass().getClassLoader().getResourceAsStream(extStopWordDictName); + //如果找不到扩展的字典,则忽略 + if (is == null) { + continue; + } + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + //System.out.println(theWord); + //加载扩展停止词典数据到内存中 + _StopWordDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + + } catch (IOException ioe) { + System.err.println("Extension Stop word Dictionary loading exception."); + ioe.printStackTrace(); + + } finally { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } + + /** + * 加载量词词典 + */ + private void loadQuantifierDict() { + //建立一个量词典实例 + _QuantifierDict = new DictSegment((char) 0); + //读取量词词典文件 + InputStream is = this.getClass().getClassLoader().getResourceAsStream(cfg.getQuantifierDicionary()); + if (is == null) { + throw new RuntimeException("Quantifier Dictionary not found!!!"); + } + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + _QuantifierDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + + } catch (IOException ioe) { + System.err.println("Quantifier Dictionary loading exception."); + ioe.printStackTrace(); + + } finally { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `InputStreamReader(...)` at line 95 is not released after line 103. +**Note**: potential exception at line 98 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Dictionary.reloadDic(List) + +### Procedure Id: +org.wltea.analyzer.dic.Dictionary.reloadDic(java.util.List):void.ab880697807edf1fbd2d24d6b9de921c + +### File: +src/main/java/org/wltea/analyzer/dic/Dictionary.java + +### Key: +Dictionary.java|reloadDic|RESOURCE_LEAK + +### Node Key: +f645aafdf4c7de4e5a37ff7e8f2268a3 + +### Hash: +ec560a2f42fc8319832a94cdff69a67c + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10074/instruction.md b/inferredbugs-10074/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51d29cca2832d6a4985f8db2ddf7d3e24ad6714f --- /dev/null +++ b/inferredbugs-10074/instruction.md @@ -0,0 +1,430 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ik-analyzer-solr +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * IK 中文分词 版本 7.0 + * IK Analyzer release 7.0 + * update by 高志成(magese@live.cn) + */ +package org.wltea.analyzer.dic; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Collection; +import java.util.List; + +import org.wltea.analyzer.cfg.Configuration; +import org.wltea.analyzer.cfg.DefaultConfig; + +/** + * 词典管理类,单子模式 + */ +@SuppressWarnings("unused") +public class Dictionary { + + /* + * 词典单子实例 + */ + private static Dictionary singleton; + + /* + * 主词典对象 + */ + private DictSegment _MainDict; + + /* + * 停止词词典 + */ + private DictSegment _StopWordDict; + /* + * 量词词典 + */ + private DictSegment _QuantifierDict; + + /** + * 配置对象 + */ + private Configuration cfg; + + private Dictionary(Configuration cfg) { + this.cfg = cfg; + this.loadMainDict(); + this.loadStopWordDict(); + this.loadQuantifierDict(); + } + + /** + * 词典初始化 + * 由于IK Analyzer的词典采用Dictionary类的静态方法进行词典初始化 + * 只有当Dictionary类被实际调用时,才会开始载入词典, + * 这将延长首次分词操作的时间 + * 该方法提供了一个在应用加载阶段就初始化字典的手段 + */ + public static void initial(Configuration cfg) { + if (singleton == null) { + synchronized (Dictionary.class) { + if (singleton == null) { + singleton = new Dictionary(cfg); + } + } + } + } + + /** + * 获取词典单子实例 + * + * @return Dictionary 单例对象 + */ + public static Dictionary getSingleton() { + if (singleton == null) { + throw new IllegalStateException("词典尚未初始化,请先调用initial方法"); + } + return singleton; + } + + /** + * 重新更新词典 + * 由于停用词等不经常变也不建议常增加,故这里只修改动态扩展词库 + */ + public static void reloadDic(List inputStreamList) { + if (singleton == null) { + Configuration cfg = DefaultConfig.getInstance(); + initial(cfg); + } + for (InputStream is : inputStreamList) { + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + singleton._MainDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + } catch (IOException ioe) { + System.err.println("Other Dictionary loading exception."); + ioe.printStackTrace(); + } finally { + try { + if (is != null) { + is.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + /** + * 批量加载新词条 + * + * @param words 词条列表 + */ + public void addWords(Collection words) { + if (words != null) { + for (String word : words) { + if (word != null) { + //批量加载词条到主内存词典中 + singleton._MainDict.fillSegment(word.trim().toLowerCase().toCharArray()); + } + } + } + } + + /** + * 批量移除(屏蔽)词条 + */ + public void disableWords(Collection words) { + if (words != null) { + for (String word : words) { + if (word != null) { + //批量屏蔽词条 + singleton._MainDict.disableSegment(word.trim().toLowerCase().toCharArray()); + } + } + } + } + + /** + * 检索匹配主词典 + * + * @return Hit 匹配结果描述 + */ + public Hit matchInMainDict(char[] charArray) { + return singleton._MainDict.match(charArray); + } + + /** + * 检索匹配主词典 + * + * @return Hit 匹配结果描述 + */ + public Hit matchInMainDict(char[] charArray, int begin, int length) { + return singleton._MainDict.match(charArray, begin, length); + } + + /** + * 检索匹配量词词典 + * + * @return Hit 匹配结果描述 + */ + public Hit matchInQuantifierDict(char[] charArray, int begin, int length) { + return singleton._QuantifierDict.match(charArray, begin, length); + } + + + /** + * 从已匹配的Hit中直接取出DictSegment,继续向下匹配 + * + * @return Hit + */ + public Hit matchWithHit(char[] charArray, int currentIndex, Hit matchedHit) { + DictSegment ds = matchedHit.getMatchedDictSegment(); + return ds.match(charArray, currentIndex, 1, matchedHit); + } + + + /** + * 判断是否是停止词 + * + * @return boolean + */ + public boolean isStopWord(char[] charArray, int begin, int length) { + return singleton._StopWordDict.match(charArray, begin, length).isMatch(); + } + + /** + * 加载主词典及扩展词典 + */ + private void loadMainDict() { + //建立一个主词典实例 + _MainDict = new DictSegment((char) 0); + //读取主词典文件 + InputStream is = this.getClass().getClassLoader().getResourceAsStream(cfg.getMainDictionary()); + if (is == null) { + throw new RuntimeException("Main Dictionary not found!!!"); + } + + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + _MainDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + + } catch (IOException ioe) { + System.err.println("Main Dictionary loading exception."); + ioe.printStackTrace(); + + } finally { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + //加载扩展词典 + this.loadExtDict(); + } + + /** + * 加载用户配置的扩展词典到主词库表 + */ + private void loadExtDict() { + //加载扩展词典配置 + List extDictFiles = cfg.getExtDictionarys(); + if (extDictFiles != null) { + InputStream is; + for (String extDictName : extDictFiles) { + //读取扩展词典文件 + System.out.println("加载扩展词典:" + extDictName); + is = this.getClass().getClassLoader().getResourceAsStream(extDictName); + //如果找不到扩展的字典,则忽略 + if (is == null) { + continue; + } + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + //加载扩展词典数据到主内存词典中 + //System.out.println(theWord); + _MainDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + + } catch (IOException ioe) { + System.err.println("Extension Dictionary loading exception."); + ioe.printStackTrace(); + + } finally { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } + + /** + * 加载用户扩展的停止词词典 + */ + private void loadStopWordDict() { + //建立一个主词典实例 + _StopWordDict = new DictSegment((char) 0); + //加载扩展停止词典 + List extStopWordDictFiles = cfg.getExtStopWordDictionarys(); + if (extStopWordDictFiles != null) { + InputStream is; + for (String extStopWordDictName : extStopWordDictFiles) { + System.out.println("加载扩展停止词典:" + extStopWordDictName); + //读取扩展词典文件 + is = this.getClass().getClassLoader().getResourceAsStream(extStopWordDictName); + //如果找不到扩展的字典,则忽略 + if (is == null) { + continue; + } + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + //System.out.println(theWord); + //加载扩展停止词典数据到内存中 + _StopWordDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + + } catch (IOException ioe) { + System.err.println("Extension Stop word Dictionary loading exception."); + ioe.printStackTrace(); + + } finally { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } + + /** + * 加载量词词典 + */ + private void loadQuantifierDict() { + //建立一个量词典实例 + _QuantifierDict = new DictSegment((char) 0); + //读取量词词典文件 + InputStream is = this.getClass().getClassLoader().getResourceAsStream(cfg.getQuantifierDicionary()); + if (is == null) { + throw new RuntimeException("Quantifier Dictionary not found!!!"); + } + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512); + String theWord; + do { + theWord = br.readLine(); + if (theWord != null && !"".equals(theWord.trim())) { + _QuantifierDict.fillSegment(theWord.trim().toLowerCase().toCharArray()); + } + } while (theWord != null); + + } catch (IOException ioe) { + System.err.println("Quantifier Dictionary loading exception."); + ioe.printStackTrace(); + + } finally { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `InputStreamReader(...)` at line 295 is not released after line 306. +**Note**: potential exception at line 298 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Dictionary.loadStopWordDict() + +### Procedure Id: +org.wltea.analyzer.dic.Dictionary.loadStopWordDict():void.4e45ec289ac072ece4f8a6a7608026b7 + +### File: +src/main/java/org/wltea/analyzer/dic/Dictionary.java + +### Key: +Dictionary.java|loadStopWordDict|RESOURCE_LEAK + +### Node Key: +f645aafdf4c7de4e5a37ff7e8f2268a3 + +### Hash: +169a10bb648a1bb5617b5bab6a2dc7f2 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10075/instruction.md b/inferredbugs-10075/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a5de3c0df61bd44e7d23ebe5f7901c98e27370ac --- /dev/null +++ b/inferredbugs-10075/instruction.md @@ -0,0 +1,1305 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jsonapi-converter +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.jasminb.jsonapi; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.type.MapType; +import com.fasterxml.jackson.databind.type.TypeFactory; +import com.github.jasminb.jsonapi.annotations.Relationship; +import com.github.jasminb.jsonapi.annotations.Type; +import com.github.jasminb.jsonapi.exceptions.DocumentSerializationException; +import com.github.jasminb.jsonapi.models.errors.Error; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static com.github.jasminb.jsonapi.JSONAPISpecConstants.*; + +/** + * JSON API data converter.
+ * + * Provides methods for conversion between JSON API resources to java POJOs and vice versa. + * + * @author jbegic + */ +public class ResourceConverter { + private final ConverterConfiguration configuration; + private final ObjectMapper objectMapper; + private final Map, RelationshipResolver> typedResolvers = new HashMap<>(); + private final ResourceCache resourceCache; + private final Set deserializationFeatures = DeserializationFeature.getDefaultFeatures(); + private final Set serializationFeatures = SerializationFeature.getDefaultFeatures(); + + private RelationshipResolver globalResolver; + + private String baseURL; + + /** + * Creates new ResourceConverter. + *

+ * All classes that should be handled by instance of {@link ResourceConverter} must be registered + * when creating a new instance of it. + *

+ * @param classes {@link Class} array of classes to be handled by this resource converter instance + */ + public ResourceConverter(Class... classes) { + this(null, null, classes); + } + + /** + * Creates new ResourceConverter. + *

+ * All classes that should be handled by instance of {@link ResourceConverter} must be registered + * when creating a new instance of it. + *

+ * @param baseURL {@link String} base URL, eg. https://api.mysite.com + * @param classes {@link Class} array of classes to be handled by this resource converter instance + */ + public ResourceConverter(String baseURL, Class... classes) { + this(null, baseURL, classes); + } + + public ResourceConverter(ObjectMapper mapper, Class... classes) { + this(mapper, null, classes); + } + + /** + * Creates new ResourceConverter. + * @param mapper {@link ObjectMapper} custom mapper to be used for resource parsing + * @param baseURL {@link String} base URL, eg. https://api.mysite.com + * @param classes {@link Class} array of classes to be handled by this resource converter instance + */ + public ResourceConverter(ObjectMapper mapper, String baseURL, Class... classes) { + this.configuration = new ConverterConfiguration(classes); + this.baseURL = baseURL != null ? baseURL : ""; + + // Set custom mapper if provided + if (mapper != null) { + objectMapper = mapper; + } else { + objectMapper = new ObjectMapper(); + } + + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + resourceCache = new ResourceCache(); + } + + /** + * Registers global relationship resolver. This resolver will be used in case relationship is present in the + * API response but not provided in the included section and relationship resolving is enabled + * trough relationship annotation.
+ * In case type resolver is registered it will be used instead. + * @param resolver resolver instance + */ + public void setGlobalResolver(RelationshipResolver resolver) { + this.globalResolver = resolver; + } + + /** + * Registers relationship resolver for given type. Resolver will be used if relationship resolution is enabled + * trough relationship annotation. + * @param resolver resolver instance + * @param type type + */ + public void setTypeResolver(RelationshipResolver resolver, Class type) { + if (resolver != null) { + String typeName = ReflectionUtils.getTypeName(type); + + if (typeName != null) { + typedResolvers.put(type, resolver); + } + } + } + /** + * Converts raw data input into requested target type. + * @param data raw data + * @param clazz target object + * @param type + * @return converted object + * @throws RuntimeException in case conversion fails + */ + @Deprecated + public T readObject(byte [] data, Class clazz) { + return readDocument(data, clazz).get(); + } + + /** + * Converts rawdata input into a collection of requested output objects. + * @param data raw data input + * @param clazz target type + * @param type + * @return collection of converted elements + * @throws RuntimeException in case conversion fails + */ + @Deprecated + public List readObjectCollection(byte [] data, Class clazz) { + return readDocumentCollection(data, clazz).get(); + } + + /** + * Reads JSON API spec document and converts it into target type. + * @param data {@link byte} raw data (server response) + * @param clazz {@link Class} target type + * @param type + * @return {@link JSONAPIDocument} + */ + public JSONAPIDocument readDocument(byte[] data, Class clazz) { + return readDocument(new ByteArrayInputStream(data), clazz); + } + + /** + * Reads JSON API spec document and converts it into target type. + * @param dataStream {@link byte} raw dataStream (server response) + * @param clazz {@link Class} target type + * @param type + * @return {@link JSONAPIDocument} + */ + public JSONAPIDocument readDocument(InputStream dataStream, Class clazz) { + try { + resourceCache.init(); + + JsonNode rootNode = objectMapper.readTree(dataStream); + + // Validate + ValidationUtils.ensureNotError(objectMapper, rootNode); + ValidationUtils.ensureValidResource(rootNode); + + resourceCache.cache(parseIncluded(rootNode)); + + JsonNode dataNode = rootNode.get(DATA); + + JSONAPIDocument result; + + if (dataNode != null && dataNode.isObject()) { + T resourceObject = readObject(dataNode, clazz, true); + result = new JSONAPIDocument<>(resourceObject, objectMapper); + } else { + result = new JSONAPIDocument<>(null, objectMapper); + } + + // Handle top-level meta + if (rootNode.has(META)) { + result.setMeta(mapMeta(rootNode.get(META))); + } + + // Handle top-level links + if (rootNode.has(LINKS)) { + result.setLinks(new Links(mapLinks(rootNode.get(LINKS)))); + } + + return result; + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } finally { + resourceCache.clear(); + } + } + + /** + * Reads JSON API spec document and converts it into collection of target type objects. + * @param data {@link byte} raw data (server response) + * @param clazz {@link Class} target type + * @param type + * @return {@link JSONAPIDocument} + */ + public JSONAPIDocument> readDocumentCollection(byte[] data, Class clazz) { + return readDocumentCollection(new ByteArrayInputStream(data), clazz); + } + /** + * Reads JSON API spec document and converts it into collection of target type objects. + * @param dataStream {@link InputStream} input stream + * @param clazz {@link Class} target type + * @param type + * @return {@link JSONAPIDocument} + */ + public JSONAPIDocument> readDocumentCollection(InputStream dataStream, Class clazz) { + try { + resourceCache.init(); + + JsonNode rootNode = objectMapper.readTree(dataStream); + + // Validate + ValidationUtils.ensureNotError(objectMapper, rootNode); + ValidationUtils.ensureValidResource(rootNode); + + resourceCache.cache(parseIncluded(rootNode)); + + List resourceList = new ArrayList<>(); + + if (rootNode.has(DATA) && rootNode.get(DATA).isArray()) { + for (JsonNode element : rootNode.get(DATA)) { + T pojo = readObject(element, clazz, true); + resourceList.add(pojo); + } + } + + JSONAPIDocument> result = new JSONAPIDocument<>(resourceList, objectMapper); + + // Handle top-level meta + if (rootNode.has(META)) { + result.setMeta(mapMeta(rootNode.get(META))); + } + + // Handle top-level links + if (rootNode.has(LINKS)) { + result.setLinks(new Links(mapLinks(rootNode.get(LINKS)))); + } + + return result; + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } finally { + resourceCache.clear(); + } + } + + /** + * Converts provided input into a target object. After conversion completes any relationships defined are resolved. + * @param source JSON source + * @param clazz target type + * @param type + * @return converted target object + * @throws IOException + * @throws IllegalAccessException + */ + private T readObject(JsonNode source, Class clazz, boolean handleRelationships) + throws IOException, IllegalAccessException, InstantiationException { + String identifier = createIdentifier(source); + + T result = (T) resourceCache.get(identifier); + if (result == null) { + Class type = getActualType(source, clazz); + + if (source.has(ATTRIBUTES)) { + result = (T) objectMapper.treeToValue(source.get(ATTRIBUTES), type); + } else { + if (type.isInterface()) { + result = null; + } else { + result = (T) objectMapper.treeToValue(objectMapper.createObjectNode(), type); + } + } + + // Handle meta + if (source.has(META)) { + Field field = configuration.getMetaField(type); + if (field != null) { + Class metaType = configuration.getMetaType(type); + Object metaObject = objectMapper.treeToValue(source.get(META), metaType); + field.set(result, metaObject); + } + } + + // Handle links + if (source.has(LINKS)) { + Field linkField = configuration.getLinksField(type); + if (linkField != null) { + linkField.set(result, new Links(mapLinks(source.get(LINKS)))); + } + } + + if (result != null) { + // Add parsed object to cache + resourceCache.cache(identifier, result); + + // Set object id + setIdValue(result, source.get(ID)); + + if (handleRelationships) { + // Handle relationships + handleRelationships(source, result); + } + } + } + + return result; + } + + + /** + * Converts included data and returns it as pairs of its unique identifiers and converted types. + * @param parent data source + * @return identifier/object pairs + * @throws IOException + * @throws IllegalAccessException + */ + private Map parseIncluded(JsonNode parent) + throws IOException, IllegalAccessException, InstantiationException { + Map result = new HashMap<>(); + + if (parent.has(INCLUDED)) { + // Get resources + List includedResources = getIncludedResources(parent); + + if (!includedResources.isEmpty()) { + // Add to result + for (Resource includedResource : includedResources) { + result.put(includedResource.getIdentifier(), includedResource.getObject()); + } + + ArrayNode includedArray = (ArrayNode) parent.get(INCLUDED); + for (int i = 0; i < includedResources.size(); i++) { + Resource resource = includedResources.get(i); + + // Handle relationships + JsonNode node = includedArray.get(i); + handleRelationships(node, resource.getObject()); + } + } + } + + return result; + } + + /** + * Parses out included resources excluding relationships. + * @param parent root node + * @return map of identifier/resource pairs + * @throws IOException + * @throws IllegalAccessException + * @throws InstantiationException + */ + private List getIncludedResources(JsonNode parent) + throws IOException, IllegalAccessException, InstantiationException { + List result = new ArrayList<>(); + + if (parent.has(INCLUDED)) { + for (JsonNode jsonNode : parent.get(INCLUDED)) { + String type = jsonNode.get(TYPE).asText(); + + Class clazz = configuration.getTypeClass(type); + + if (clazz != null) { + Object object = readObject(jsonNode, clazz, false); + if (object != null) { + result.add(new Resource(createIdentifier(jsonNode), object)); + } + } else if (!deserializationFeatures.contains(DeserializationFeature.ALLOW_UNKNOWN_INCLUSIONS)) { + throw new IllegalArgumentException("Included section contains unknown resource type: " + type); + } + } + } + + return result; + } + + private void handleRelationships(JsonNode source, Object object) + throws IllegalAccessException, IOException, InstantiationException { + JsonNode relationships = source.get(RELATIONSHIPS); + + if (relationships != null) { + Iterator fields = relationships.fieldNames(); + + while (fields.hasNext()) { + String field = fields.next(); + + JsonNode relationship = relationships.get(field); + Field relationshipField = configuration.getRelationshipField(object.getClass(), field); + + if (relationshipField != null) { + // Get target type + Class type = configuration.getRelationshipType(object.getClass(), field); + + // In case type is not defined, relationship object cannot be processed + if (type == null) { + continue; + } + + // Handle meta if present + if (relationship.has(META)) { + Field relationshipMetaField = configuration.getRelationshipMetaField(object.getClass(), field); + + if (relationshipMetaField != null) { + relationshipMetaField.set(object, objectMapper.treeToValue(relationship.get(META), + configuration.getRelationshipMetaType(object.getClass(), field))); + } + } + + // Handle links if present + if (relationship.has(LINKS)) { + Field relationshipLinksField = configuration.getRelationshipLinksField(object.getClass(), field); + if (relationshipLinksField != null) { + Links links = new Links(mapLinks(relationship.get(LINKS))); + relationshipLinksField.set(object, links); + } + } + + // Get resolve flag + boolean resolveRelationship = configuration.getFieldRelationship(relationshipField).resolve(); + RelationshipResolver resolver = getResolver(type); + + // Use resolver if possible + if (resolveRelationship && resolver != null && relationship.has(LINKS)) { + String relType = configuration.getFieldRelationship(relationshipField).relType().getRelName(); + JsonNode linkNode = relationship.get(LINKS).get(relType); + + String link; + + if (linkNode != null && ((link = getLink(linkNode)) != null)) { + if (isCollection(relationship)) { + relationshipField.set(object, + readDocumentCollection(new ByteArrayInputStream(resolver.resolve(link)), type).get()); + } else { + relationshipField.set(object, readDocument(new ByteArrayInputStream(resolver.resolve(link)), type).get()); + } + } + } else { + if (isCollection(relationship)) { + @SuppressWarnings("rawtypes") + Collection elements = createCollectionInstance(relationshipField.getType()); + + for (JsonNode element : relationship.get(DATA)) { + Object relationshipObject = parseRelationship(element, type); + if (relationshipObject != null) { + elements.add(relationshipObject); + } + } + relationshipField.set(object, elements); + } else { + Object relationshipObject = parseRelationship(relationship.get(DATA), type); + if (relationshipObject != null) { + relationshipField.set(object, relationshipObject); + } + } + } + } + } + } + } + + /** + * Accepts a JsonNode which encapsulates a link. The link may be represented as a simple string or as + * link object. This method introspects on the + * {@code linkNode}, returning the value of the {@code href} member, if it exists, or returns the string form + * of the {@code linkNode} if it doesn't. + *

+ * Package-private for unit testing. + *

+ * @param linkNode a JsonNode representing a link, may return {@code null} + * @return the link URL + */ + String getLink(JsonNode linkNode) { + // Handle both representations of a link: as a string or as an object + // http://jsonapi.org/format/#document-links (v1.0) + if (linkNode.has(HREF)) { + // object form + return linkNode.get(HREF).asText(); + } + return linkNode.asText(null); + } + + /** + * Creates relationship object by consuming provided 'data' node. + * @param relationshipDataNode relationship data node + * @param type object type + * @return created object or null in case data node is not valid + * @throws IOException + * @throws IllegalAccessException + * @throws InstantiationException + */ + private Object parseRelationship(JsonNode relationshipDataNode, Class type) + throws IOException, IllegalAccessException, InstantiationException { + if (ValidationUtils.isRelationshipParsable(relationshipDataNode)) { + String identifier = createIdentifier(relationshipDataNode); + + if (resourceCache.contains(identifier)) { + return resourceCache.get(identifier); + } else { + // Never cache relationship objects + resourceCache.lock(); + try { + return readObject(relationshipDataNode, type, true); + } finally { + resourceCache.unlock(); + } + } + } + + return null; + } + + /** + * Generates unique resource identifier by combining resource type and resource id fields.
+ * By specification id/type combination guarantees uniqueness. + * @param object data object + * @return concatenated id and type values + */ + private String createIdentifier(JsonNode object) { + JsonNode idNode = object.get(ID); + + String id = idNode != null ? idNode.asText().trim() : ""; + + if (id.isEmpty() && deserializationFeatures.contains(DeserializationFeature.REQUIRE_RESOURCE_ID)) { + throw new IllegalArgumentException("Resource must have an non null and non-empty 'id' attribute!"); + } + + String type = object.get(TYPE).asText(); + return type.concat(id); + } + + /** + * Sets an id attribute value to a target object. + * @param target target POJO + * @param idValue id node + * @throws IllegalAccessException thrown in case target field is not accessible + */ + private void setIdValue(Object target, JsonNode idValue) throws IllegalAccessException { + Field idField = configuration.getIdField(target.getClass()); + + // By specification, id value is always a String type + if (idValue != null) { + idField.set(target, idValue.asText()); + } + } + + /** + * Checks if data object is an array or just single object holder. + * @param source data node + * @return true if data node is an array else false + */ + private boolean isCollection(JsonNode source) { + JsonNode data = source.get(DATA); + return data != null && data.isArray(); + } + + + /** + * Converts input object to byte array. + * @param object input object + * @return raw bytes + * @throws JsonProcessingException + * @throws IllegalAccessException + */ + @Deprecated + public byte [] writeObject(Object object) throws JsonProcessingException, IllegalAccessException { + try { + return writeDocument(new JSONAPIDocument<>(object)); + } catch (DocumentSerializationException e) { + throw new RuntimeException(e); + } + } + + /** + * Serializes provided {@link JSONAPIDocument} into JSON API Spec compatible byte representation. + * @param document {@link JSONAPIDocument} document to serialize + * @return serialized content in bytes + * @throws DocumentSerializationException thrown in case serialization fails + */ + public byte [] writeDocument(JSONAPIDocument document) throws DocumentSerializationException { + return writeDocument(document, null); + } + + /** + * Serializes provided {@link JSONAPIDocument} into JSON API Spec compatible byte representation. + * @param document {@link JSONAPIDocument} document to serialize + * @param settings {@link SerializationSettings} settings that override global serialization settings + * @return serialized content in bytes + * @throws DocumentSerializationException thrown in case serialization fails + */ + public byte [] writeDocument(JSONAPIDocument document, SerializationSettings settings) + throws DocumentSerializationException { + try { + resourceCache.init(); + + Map includedDataMap = new HashMap<>(); + + ObjectNode result = objectMapper.createObjectNode(); + + // Serialize data if present + if (document.get() != null) { + ObjectNode dataNode = getDataNode(document.get(), includedDataMap, settings); + result.set(DATA, dataNode); + result = addIncludedSection(result, includedDataMap); + } + + // Serialize errors if present + if (document.getErrors() != null) { + ArrayNode errorsNode = objectMapper.createArrayNode(); + for (Error error : document.getErrors()) { + errorsNode.add(objectMapper.valueToTree(error)); + } + + result.set(ERRORS, errorsNode); + } + + // Serialize global links and meta + serializeMeta(document, result, settings); + serializeLinks(document, result, settings); + return objectMapper.writeValueAsBytes(result); + } catch (Exception e) { + throw new DocumentSerializationException(e); + } finally { + resourceCache.clear(); + } + } + + private void serializeMeta(JSONAPIDocument document, ObjectNode resultNode, SerializationSettings settings) { + // Handle global links and meta + if (document.getMeta() != null && !document.getMeta().isEmpty() && shouldSerializeMeta(settings)) { + resultNode.set(META, objectMapper.valueToTree(document.getMeta())); + } + } + + private void serializeLinks(JSONAPIDocument document, ObjectNode resultNode, SerializationSettings settings) { + if (document.getLinks() != null && !document.getLinks().getLinks().isEmpty() && + shouldSerializeLinks(settings)) { + resultNode.set(LINKS, objectMapper.valueToTree(document.getLinks()).get(LINKS)); + } + } + + /** + * Serializes provided {@link JSONAPIDocument} into JSON API Spec compatible byte representation. + * @param documentCollection {@link JSONAPIDocument} document collection to serialize + * @return serialized content in bytes + * @throws DocumentSerializationException thrown in case serialization fails + */ + public byte [] writeDocumentCollection(JSONAPIDocument> documentCollection) + throws DocumentSerializationException { + return writeDocumentCollection(documentCollection, null); + } + + /** + * Serializes provided {@link JSONAPIDocument} into JSON API Spec compatible byte representation. + * @param documentCollection {@link JSONAPIDocument} document collection to serialize + * @param serializationSettings {@link SerializationSettings} settings that override global serialization settings + * @return serialized content in bytes + * @throws DocumentSerializationException thrown in case serialization fails + */ + public byte [] writeDocumentCollection(JSONAPIDocument> documentCollection, + SerializationSettings serializationSettings) + throws DocumentSerializationException { + + try { + resourceCache.init(); + ArrayNode results = objectMapper.createArrayNode(); + Map includedDataMap = new HashMap<>(); + + for (Object object : documentCollection.get()) { + results.add(getDataNode(object, includedDataMap, serializationSettings)); + } + + ObjectNode result = objectMapper.createObjectNode(); + result.set(DATA, results); + + result = addIncludedSection(result, includedDataMap); + + // Handle global links and meta + serializeMeta(documentCollection, result, serializationSettings); + serializeLinks(documentCollection, result, serializationSettings); + return objectMapper.writeValueAsBytes(result); + } catch (Exception e) { + throw new DocumentSerializationException(e); + } finally { + resourceCache.clear(); + } + } + + + private ObjectNode getDataNode(Object object, Map includedContainer, + SerializationSettings settings) throws IllegalAccessException { + ObjectNode dataNode = objectMapper.createObjectNode(); + + // Perform initial conversion + ObjectNode attributesNode = objectMapper.valueToTree(object); + + // Handle id, meta and relationship fields + Field idField = configuration.getIdField(object.getClass()); + JsonNode id = attributesNode.remove(idField.getName()); + + // Handle meta + Field metaField = configuration.getMetaField(object.getClass()); + if (metaField != null) { + JsonNode meta = attributesNode.remove(metaField.getName()); + if (meta != null && shouldSerializeMeta(settings)) { + dataNode.set(META, meta); + } + } + + // Handle links + JsonNode jsonLinks = getResourceLinks(object, attributesNode, id.textValue(), settings); + String selfHref = null; + + if (jsonLinks != null) { + dataNode.set(LINKS, jsonLinks); + + if (jsonLinks.has(SELF)) { + selfHref = jsonLinks.get(SELF).get(HREF).asText(); + } + } + + // Handle resource identifier + dataNode.put(TYPE, configuration.getTypeName(object.getClass())); + + String resourceId = (String) idField.get(object); + if (resourceId != null) { + dataNode.put(ID, resourceId); + + // Cache the object for recursion breaking purposes + resourceCache.cache(resourceId.concat(configuration.getTypeName(object.getClass())), null); + } + dataNode.set(ATTRIBUTES, attributesNode); + + + // Handle relationships (remove from base type and add as relationships) + List relationshipFields = configuration.getRelationshipFields(object.getClass()); + + if (relationshipFields != null) { + ObjectNode relationshipsNode = objectMapper.createObjectNode(); + + for (Field relationshipField : relationshipFields) { + Object relationshipObject = relationshipField.get(object); + + if (relationshipObject != null) { + attributesNode.remove(relationshipField.getName()); + + Relationship relationship = configuration.getFieldRelationship(relationshipField); + + // In case serialisation is disabled for a given relationship, skip it + if (!relationship.serialise()) { + continue; + } + + String relationshipName = relationship.value(); + + ObjectNode relationshipDataNode = objectMapper.createObjectNode(); + relationshipsNode.set(relationshipName, relationshipDataNode); + + // Serialize relationship meta + JsonNode relationshipMeta = getRelationshipMeta(object, relationshipName, settings); + if (relationshipMeta != null) { + relationshipDataNode.set(META, relationshipMeta); + attributesNode.remove(configuration + .getRelationshipMetaField(object.getClass(), relationshipName).getName()); + } + + // Serialize relationship links + JsonNode relationshipLinks = getRelationshipLinks(object, relationship, selfHref, settings); + + if (relationshipLinks != null) { + relationshipDataNode.set(LINKS, relationshipLinks); + + // Remove link object from serialized JSON + Field refField = configuration + .getRelationshipLinksField(object.getClass(), relationshipName); + + if (refField != null) { + attributesNode.remove(refField.getName()); + } + } + + if (relationshipObject instanceof Collection) { + ArrayNode dataArrayNode = objectMapper.createArrayNode(); + + for (Object element : (Collection) relationshipObject) { + String relationshipType = configuration.getTypeName(element.getClass()); + String idValue = (String) configuration.getIdField(element.getClass()).get(element); + + ObjectNode identifierNode = objectMapper.createObjectNode(); + identifierNode.put(TYPE, relationshipType); + identifierNode.put(ID, idValue); + dataArrayNode.add(identifierNode); + + // Handle included data + if (shouldSerializeRelationship(relationshipName, settings) && idValue != null) { + String identifier = idValue.concat(relationshipType); + if (!includedContainer.containsKey(identifier) && !resourceCache.contains(identifier)) { + includedContainer.put(identifier, + getDataNode(element, includedContainer, settings)); + } + } + } + relationshipDataNode.set(DATA, dataArrayNode); + + } else { + String relationshipType = configuration.getTypeName(relationshipObject.getClass()); + String idValue = (String) configuration.getIdField(relationshipObject.getClass()) + .get(relationshipObject); + + ObjectNode identifierNode = objectMapper.createObjectNode(); + identifierNode.put(TYPE, relationshipType); + identifierNode.put(ID, idValue); + + relationshipDataNode.set(DATA, identifierNode); + + if (shouldSerializeRelationship(relationshipName, settings) && idValue != null) { + String identifier = idValue.concat(relationshipType); + if (!includedContainer.containsKey(identifier)) { + includedContainer.put(identifier, + getDataNode(relationshipObject, includedContainer, settings)); + } + } + } + } + + } + + if (relationshipsNode.size() > 0) { + dataNode.set(RELATIONSHIPS, relationshipsNode); + } + } + return dataNode; + } + + /** + * Converts input object to byte array. + * + * @param objects List of input objects + * @return raw bytes + * @throws JsonProcessingException + * @throws IllegalAccessException + * @deprecated use writeDocumentCollection instead + */ + @Deprecated + public byte[] writeObjectCollection(Iterable objects) throws JsonProcessingException, IllegalAccessException { + try { + return writeDocumentCollection(new JSONAPIDocument<>(objects)); + } catch (DocumentSerializationException e) { + if (e.getCause() instanceof JsonProcessingException) { + throw (JsonProcessingException) e.getCause(); + } else if (e.getCause() instanceof IllegalAccessException) { + throw (IllegalAccessException) e.getCause(); + } + throw new RuntimeException(e.getCause()); + } + } + + /** + * Checks if provided type is registered with this converter instance. + * @param type class to check + * @return returns true if type is registered, else false + */ + public boolean isRegisteredType(Class type) { + return configuration.isRegisteredType(type); + } + + /** + * Returns relationship resolver for given type. In case no specific type resolver is registered, global resolver + * is returned. + * @param type relationship object type + * @return relationship resolver or null + */ + private RelationshipResolver getResolver(Class type) { + RelationshipResolver resolver = typedResolvers.get(type); + return resolver != null ? resolver : globalResolver; + } + + private static class Resource { + private String identifier; + private Object object; + + public Resource(String identifier, Object resource) { + this.identifier = identifier; + this.object = resource; + } + + public String getIdentifier() { + return identifier; + } + + public Object getObject() { + return object; + } + } + + /** + * Deserializes a JSON-API links object to a {@code Map} + * keyed by the link name. + *

+ * The {@code linksObject} may represent links in string form or object form; both are supported by this method. + *

+ *

+ * E.g. + *

+	 * "links": {
+	 *   "self": "http://example.com/posts"
+	 * }
+	 * 
+ *

+ *

+ * or + *

+	 * "links": {
+	 *   "related": {
+	 *     "href": "http://example.com/articles/1/comments",
+	 *     "meta": {
+	 *       "count": 10
+	 *     }
+	 *   }
+	 * }
+	 * 
+ *

+ * + * @param linksObject a {@code JsonNode} representing a links object + * @return a {@code Map} keyed by link name + */ + private Map mapLinks(JsonNode linksObject) { + Map result = new HashMap<>(); + + Iterator> linkItr = linksObject.fields(); + + while (linkItr.hasNext()) { + Map.Entry linkNode = linkItr.next(); + Link linkObj = new Link(); + + linkObj.setHref( + getLink( + linkNode.getValue())); + + if (linkNode.getValue().has(META)) { + linkObj.setMeta( + mapMeta( + linkNode.getValue().get(META))); + } + + result.put(linkNode.getKey(), linkObj); + } + + return result; + } + + /** + * Deserializes a JSON-API meta object to a {@code Map} + * keyed by the member names. Because {@code meta} objects contain arbitrary information, the values in the + * map are of unknown type. + * + * @param metaNode a JsonNode representing a meta object + * @return a Map of the meta information, keyed by member name. + */ + private Map mapMeta(JsonNode metaNode) { + JsonParser p = objectMapper.treeAsTokens(metaNode); + MapType mapType = TypeFactory.defaultInstance() + .constructMapType(HashMap.class, String.class, Object.class); + try { + return objectMapper.readValue(p, mapType); + } catch (IOException e) { + // TODO: log? No recovery. + } + + return null; + } + + private ObjectNode addIncludedSection(ObjectNode rootNode, Map includedDataMap) { + if (!includedDataMap.isEmpty()) { + ArrayNode includedArray = objectMapper.createArrayNode(); + includedArray.addAll(includedDataMap.values()); + + rootNode.set(INCLUDED, includedArray); + } + + return rootNode; + } + + /** + * Resolves actual type to be used for resource deserialization. + *

+ * If user provides class with type annotation that is equal to the type value in response data, same class + * will be used. If provided class is super type of actual class that is resolved using response type value, + * subclass will be returned. This allows for deserializing responses in use cases where one of many subtypes + * can be returned by the server and user is not sure which one will it be. + *

+ * @param object JSON object containing type value + * @param userType provided user type + * @return {@link Class} + */ + private Class getActualType(JsonNode object, Class userType) { + String type = object.get(TYPE).asText(); + + String definedTypeName = configuration.getTypeName(userType); + + if (definedTypeName != null && definedTypeName.equals(type)) { + return userType; + } else { + Class actualType = configuration.getTypeClass(type); + + if (actualType != null && userType.isAssignableFrom(actualType)) { + return actualType; + } + } + + + throw new RuntimeException("No class was registered for type '" + type + "'."); + } + + + private Collection createCollectionInstance(Class type) + throws InstantiationException, IllegalAccessException { + if (!type.isInterface() && !Modifier.isAbstract(type.getModifiers())) { + return (Collection) type.newInstance(); + } + + if (List.class.equals(type) || Collection.class.equals(type)) { + return new ArrayList<>(); + } + + if (Set.class.equals(type)) { + return new HashSet<>(); + } + + throw new RuntimeException("Unable to create appropriate instance for type: " + type.getSimpleName()); + } + + private JsonNode getRelationshipMeta(Object source, String relationshipName, SerializationSettings settings) + throws IllegalAccessException { + if (shouldSerializeMeta(settings)) { + Field relationshipMetaField = configuration + .getRelationshipMetaField(source.getClass(), relationshipName); + + if (relationshipMetaField != null && relationshipMetaField.get(source) != null) { + return objectMapper.valueToTree(relationshipMetaField.get(source)); + } + } + return null; + } + + private JsonNode getResourceLinks(Object resource, ObjectNode serializedResource, String resourceId, + SerializationSettings settings) throws IllegalAccessException { + Type type = configuration.getType(resource.getClass()); + + // Check if there are user-provided links + Links links = null; + Field linksField = configuration.getLinksField(resource.getClass()); + if (linksField != null) { + links = (Links) linksField.get(resource); + + // Remove links from attributes object + //TODO: this state change needs to be removed from here + if (links != null) { + serializedResource.remove(linksField.getName()); + } + } + + // If enabled, handle links + if (shouldSerializeLinks(settings)) { + Map linkMap = new HashMap<>(); + + if (links != null) { + linkMap.putAll(links.getLinks()); + } + + // If link path is defined in type and id is not null and user did not explicitly set link value, create it + if (!type.path().trim().isEmpty() && !linkMap.containsKey(SELF) && resourceId != null) { + linkMap.put(SELF, new Link(createURL(baseURL, type.path().replace("{id}", resourceId)))); + } + + // If there is at least one link generated, serialize and return + if (!linkMap.isEmpty()) { + return objectMapper.valueToTree(new Links(linkMap)).get(LINKS); + } + } + return null; + } + + private JsonNode getRelationshipLinks(Object source, Relationship relationship, String ownerLink, + SerializationSettings settings) throws IllegalAccessException { + if (shouldSerializeLinks(settings)) { + Links links = null; + + Field relationshipLinksField = configuration + .getRelationshipLinksField(source.getClass(), relationship.value()); + + if (relationshipLinksField != null) { + links = (Links) relationshipLinksField.get(source); + } + + Map linkMap = new HashMap<>(); + + if (links != null) { + linkMap.putAll(links.getLinks()); + } + + if (!relationship.path().trim().isEmpty() && !linkMap.containsKey(SELF)) { + linkMap.put(SELF, new Link(createURL(ownerLink, relationship.path()))); + } + + if (!relationship.relatedPath().trim().isEmpty() && !linkMap.containsKey(RELATED)) { + linkMap.put(RELATED, new Link(createURL(ownerLink, relationship.relatedPath()))); + } + + if (!linkMap.isEmpty()) { + return objectMapper.valueToTree(new Links(linkMap)).get(LINKS); + } + } + return null; + } + + private String createURL(String base, String path) { + String result = base; + if (!result.endsWith("/")) { + result = result.concat("/"); + } + + if (path.startsWith("/")) { + result = result.concat(path.substring(1)); + } else { + result = result.concat(path); + } + + return result; + } + + private boolean shouldSerializeRelationship(String relationshipName, SerializationSettings settings) { + if (settings != null) { + if (settings.isRelationshipIncluded(relationshipName) && !settings.isRelationshipExcluded(relationshipName)) { + return true; + } + + if (settings.isRelationshipExcluded(relationshipName)) { + return false; + } + } + return serializationFeatures.contains(SerializationFeature.INCLUDE_RELATIONSHIP_ATTRIBUTES); + } + + private boolean shouldSerializeLinks(SerializationSettings settings) { + if (settings != null && settings.serializeLinks() != null) { + return settings.serializeLinks(); + } + return serializationFeatures.contains(SerializationFeature.INCLUDE_LINKS); + } + + private boolean shouldSerializeMeta(SerializationSettings settings) { + if (settings != null && settings.serializeMeta() != null) { + return settings.serializeMeta(); + } + return serializationFeatures.contains(SerializationFeature.INCLUDE_META); + } + + /** + * Registers new type to be used with this converter instance. + * @param type {@link Class} type to register + * @return true if type was registed, else false (in case type was registered already or + * type is not eligible for registering ie. missing required annotations) + */ + public boolean registerType(Class type) { + if (!configuration.isRegisteredType(type) && ConverterConfiguration.isEligibleType(type)) { + return configuration.registerType(type); + } + return false; + } + + /** + * Adds (enables) new deserialization option. + * @param option {@link DeserializationFeature} option + */ + public void enableDeserializationOption(DeserializationFeature option) { + this.deserializationFeatures.add(option); + } + + /** + * Removes (disables) existing deserialization option. + * @param option {@link DeserializationFeature} feature to disable + */ + public void disableDeserializationOption(DeserializationFeature option) { + this.deserializationFeatures.remove(option); + } + + /** + * Adds (enables) new serialization option. + * @param option {@link SerializationFeature} option + */ + public void enableSerializationOption(SerializationFeature option) { + this.serializationFeatures.add(option); + } + + /** + * Removes (disables) existing serialization option. + * @param option {@link SerializationFeature} feature to disable + */ + public void disableSerializationOption(SerializationFeature option) { + this.serializationFeatures.remove(option); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `id` last assigned on line 727 could be null and is dereferenced at line 739. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +ObjectNode ResourceConverter.getDataNode(Object,Map,SerializationSettings) + +### Procedure Id: +com.github.jasminb.jsonapi.ResourceConverter.getDataNode(java.lang.Object,java.util.Map,com.github.j.5ded2b912191d88ae32f7be9db044d53 + +### File: +src/main/java/com/github/jasminb/jsonapi/ResourceConverter.java + +### Key: +ResourceConverter.java|getDataNode|NULL_DEREFERENCE + +### Node Key: +052a13a1df613b5098c09aba20e3cfbc + +### Hash: +d6316b184fce0e715df6f143b4e62ce7 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10080/instruction.md b/inferredbugs-10080/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..545afcfffbebd00a60438c56c95e60edf41ca9d6 --- /dev/null +++ b/inferredbugs-10080/instruction.md @@ -0,0 +1,178 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-wkhtmltopdf-wrapper +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package br.eti.mertz.wkhtmltopdf.wrapper; + +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import br.eti.mertz.wkhtmltopdf.wrapper.options.GlobalOption; +import lombok.Data; + +@Data +public class Pdf implements PdfService { + + private String command; + private List params; + private String htmlInput = null; + private boolean htmlFromString = false; + + public Pdf(String wkhtmltopdf, List params) { + this.command = wkhtmltopdf; + this.params = params; + } + + public Pdf(List params) { + this("wkhtmltopdf", params); + } + + public Pdf(Param... params) { + this("wkhtmltopdf", Arrays.asList(params)); + } + + public Pdf() { + this("wkhtmltopdf", new ArrayList()); + } + + public void addHtmlInput(String input) { + this.htmlFromString = true; + this.htmlInput = input; + } + + /** + * TODO Add a HTML file, a HTML string or a page from a URL + */ + public void addCover(String cover) { + // TODO Auto-generated method stub + } + + /** + * TODO just the TOC option from wkhtmltopdf + */ + public void addToc() { + // TODO Auto-generated method stub + } + + public void addParam(Param param) { + params.add(param); + } + + public void addParam(Param... params) { + for (Param param : params) { + addParam(param); + } + } + + /** + * TODO save file and returns + * + * @throws IOException + * @throws InterruptedException + */ + public File saveAs(String path) throws IOException, InterruptedException { + Runtime rt = Runtime.getRuntime(); + String command = this.commandWithParameters() + Symbol.separator + path; + Process proc = rt.exec(command); + if(htmlFromString) { + OutputStream stdin = proc.getOutputStream(); + stdin.write(htmlInput.getBytes()); + stdin.close(); + } + + proc.waitFor(); + if(proc.exitValue() != 0) { + throw new RuntimeException("Process (" + command + ") exited with status code " + proc.exitValue()); + } + + return new File(path); + } + + public String commandWithParameters() { + StringBuilder sb = new StringBuilder(); + for (Param param : params) { + sb.append(param); + } + + return command + sb.toString(); + } + + public void addParam(GlobalOption option) { + addParam(new Param(option.toString())); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.lang.Process` acquired to `proc` by call to `exec(...)` at line 76 is not released after line 85. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +File Pdf.saveAs(String) + +### Procedure Id: +br.eti.mertz.wkhtmltopdf.wrapper.Pdf.saveAs(java.lang.String):java.io.File.bb18462cfae09748bd14d6051b8e8547 + +### File: +src/main/java/br/eti/mertz/wkhtmltopdf/wrapper/Pdf.java + +### Key: +Pdf.java|saveAs|RESOURCE_LEAK + +### Node Key: +3677875e6aead27ee1320f16c80d8b0f + +### Hash: +a323478e6066fb1a7394f37f85e3850c + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10081/instruction.md b/inferredbugs-10081/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cb4754e08f08651f1ba9e234cc99858513e35f2a --- /dev/null +++ b/inferredbugs-10081/instruction.md @@ -0,0 +1,203 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-wkhtmltopdf-wrapper +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package br.eti.mertz.wkhtmltopdf.wrapper; + +import java.io.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import br.eti.mertz.wkhtmltopdf.wrapper.options.GlobalOption; +import lombok.Data; + +@Data +public class Pdf implements PdfService { + + private String command; + private List params; + private String htmlInput = null; + private boolean htmlFromString = false; + + public Pdf(String wkhtmltopdf, List params) { + this.command = wkhtmltopdf; + this.params = params; + } + + public Pdf(List params) { + this("wkhtmltopdf", params); + } + + public Pdf(Param... params) { + this("wkhtmltopdf", Arrays.asList(params)); + } + + public Pdf() { + this("wkhtmltopdf", new ArrayList()); + } + + public void addHtmlInput(String input) { + this.htmlFromString = true; + this.htmlInput = input; + } + + /** + * TODO Add a HTML file, a HTML string or a page from a URL + */ + public void addCover(String cover) { + // TODO Auto-generated method stub + } + + /** + * TODO just the TOC option from wkhtmltopdf + */ + public void addToc() { + // TODO Auto-generated method stub + } + + public void addParam(Param param) { + params.add(param); + } + + public void addParam(Param... params) { + for (Param param : params) { + addParam(param); + } + } + + /** + * @throws IOException + * @throws InterruptedException + */ + public File saveAs(String path) throws IOException, InterruptedException { + byte[] pdf = this.getPDF(); + File file = new File(path); + + BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file)); + bufferedOutputStream.write(pdf); + bufferedOutputStream.flush(); + bufferedOutputStream.close(); + + return file; + } + + public byte[] getPDF() throws IOException, InterruptedException { + Runtime runtime = Runtime.getRuntime(); + if(htmlFromString && !this.params.contains(new Param("-"))) { + this.addParam(new Param("-")); + } + String command = this.commandWithParameters() + Symbol.separator + "-"; + Process process = runtime.exec(command); + if(htmlFromString) { + OutputStream stdInStream = process.getOutputStream(); + stdInStream.write(htmlInput.getBytes()); + stdInStream.close(); + } + InputStream stdOutStream = process.getInputStream(); + InputStream stdErrStream = process.getErrorStream(); + process.waitFor(); + + ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); + ByteArrayOutputStream stdErr = new ByteArrayOutputStream(); + + for(int i = 0; i < stdOutStream.available(); i++) { + stdOut.write((char) stdOutStream.read()); + } + stdOutStream.close(); + for(int i = 0; i < stdErrStream.available(); i++) { + stdErr.write((char) stdErrStream.read()); + } + stdErrStream.close(); + + if(process.exitValue() != 0) { + throw new RuntimeException("Process (" + command + ") exited with status code " + process.exitValue() + ":\n"+new String(stdErr.toByteArray())); + } + + return stdOut.toByteArray(); + } + + public String commandWithParameters() { + StringBuilder sb = new StringBuilder(); + for (Param param : params) { + sb.append(param); + } + + return command + sb.toString(); + } + + public void addParam(GlobalOption option) { + addParam(new Param(option.toString())); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.lang.Process` acquired to `process` by call to `exec(...)` at line 87 is not released after line 110. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +byte[] Pdf.getPDF() + +### Procedure Id: +br.eti.mertz.wkhtmltopdf.wrapper.Pdf.getPDF():byte[].a0ffdba01dc77854a88921a51f861962 + +### File: +src/main/java/br/eti/mertz/wkhtmltopdf/wrapper/Pdf.java + +### Key: +Pdf.java|getPDF|RESOURCE_LEAK + +### Node Key: +3677875e6aead27ee1320f16c80d8b0f + +### Hash: +49dcc2afbecfa2eec47379b680fe0ee1 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10086/instruction.md b/inferredbugs-10086/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f0b1e33762f7af8b7fda198e284a4f46a1c00501 --- /dev/null +++ b/inferredbugs-10086/instruction.md @@ -0,0 +1,1018 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** lizzie +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package featurecat.lizzie.analysis; + +import featurecat.lizzie.Lizzie; +import featurecat.lizzie.gui.MainFrame; +import featurecat.lizzie.rules.Board; +import featurecat.lizzie.rules.BoardData; +import featurecat.lizzie.rules.Stone; +import featurecat.lizzie.util.Utils; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.ResourceBundle; +import java.util.StringTokenizer; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.swing.JOptionPane; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * An interface with leelaz go engine. Can be adapted for GTP, but is specifically designed for + * GCP's Leela Zero. leelaz is modified to output information as it ponders see + * www.github.com/gcp/leela-zero + */ +public class Leelaz { + private static final ResourceBundle resourceBundle = MainFrame.resourceBundle; + + private static final long MINUTE = 60 * 1000; // number of milliseconds in a minute + + private long maxAnalyzeTimeMillis; // , maxThinkingTimeMillis; + private int cmdNumber; + private int currentCmdNum; + private ArrayDeque cmdQueue; + + private Process process; + + private BufferedInputStream inputStream; + private BufferedOutputStream outputStream; + + private boolean printCommunication; + public boolean gtpConsole; + + public Board board; + private List bestMoves; + private List bestMovesTemp; + + private List listeners; + + private boolean isPondering; + private long startPonderTime; + + // fixed_handicap + public boolean isSettingHandicap = false; + + // genmove + public boolean isThinking = false; + public boolean isInputCommand = false; + + public boolean preload = false; + private boolean started = false; + private boolean isLoaded = false; + private boolean isCheckingName; + private boolean isCheckingVersion; + + // for Multiple Engine + private String engineCommand; + private List commands; + private JSONObject config; + private String currentWeightFile = ""; + private String currentWeight = ""; + private boolean switching = false; + private int currentEngineN = -1; + private ScheduledExecutorService executor; + + // dynamic komi and opponent komi as reported by dynamic-komi version of leelaz + private float dynamicKomi = Float.NaN; + private float dynamicOppKomi = Float.NaN; + public boolean isKataGo = false; + public boolean supportScoremean = false; + ArrayList estimateArray = new ArrayList(); + public double scoreMean = 0; + public double scoreStdev = 0; + + /** + * Initializes the leelaz process and starts reading output + * + * @throws IOException + */ + public Leelaz(String engineCommand) throws IOException, JSONException { + board = new Board(); + bestMoves = new ArrayList<>(); + bestMovesTemp = new ArrayList<>(); + listeners = new CopyOnWriteArrayList<>(); + + isPondering = false; + startPonderTime = System.currentTimeMillis(); + cmdNumber = 1; + currentCmdNum = 0; + cmdQueue = new ArrayDeque<>(); + + // Move config to member for other method call + config = Lizzie.config.config.getJSONObject("leelaz"); + + printCommunication = config.getBoolean("print-comms"); + gtpConsole = printCommunication; + maxAnalyzeTimeMillis = MINUTE * config.getInt("max-analyze-time-minutes"); + + // command string for starting the engine + if (engineCommand == null || engineCommand.isEmpty()) { + engineCommand = config.getString("engine-command"); + // substitute in the weights file + engineCommand = engineCommand.replaceAll("%network-file", config.getString("network-file")); + } + this.engineCommand = engineCommand; + if (engineCommand.toLowerCase().contains("override-version")) { + this.isKataGo = true; + } + commands = splitCommand(engineCommand); + // Initialize current engine number and start engine + currentEngineN = 0; + } + + public void startEngine() throws IOException { + if (engineCommand.trim().isEmpty()) { + return; + } + + isLoaded = false; + isKataGo = false; + bestMoves = new ArrayList<>(); + Lizzie.board.getData().tryToClearBestMoves(); + + // Get weight name + Pattern wPattern = Pattern.compile("(?s).*?(--weights |-w |-model )([^'\" ]+)(?s).*"); + Matcher wMatcher = wPattern.matcher(engineCommand); + if (wMatcher.matches() && wMatcher.groupCount() == 2) { + currentWeightFile = wMatcher.group(2); + String[] names = currentWeightFile.split("[\\\\|/]"); + currentWeight = names.length > 1 ? names[names.length - 1] : currentWeightFile; + } + + // Check if engine is present + // Commented for remote ssh. TODO keep or remove this code? + // File startfolder = new File(config.optString("engine-start-location", ".")); + // File lef = startfolder.toPath().resolve(new File(commands.get(0)).toPath()).toFile(); + // System.out.println(lef.getPath()); + // if (!lef.exists()) { + // JOptionPane.showMessageDialog( + // null, + // resourceBundle.getString("LizzieFrame.display.leelaz-missing"), + // "Lizzie - Error!", + // JOptionPane.ERROR_MESSAGE); + // throw new IOException("engine not present"); + // } + + // Check if network file is present + // File wf = startfolder.toPath().resolve(new File(currentWeightFile).toPath()).toFile(); + // if (!wf.exists()) { + // JOptionPane.showMessageDialog( + // null, resourceBundle.getString("LizzieFrame.display.network-missing")); + // throw new IOException("network-file not present"); + // } + + // run leelaz + ProcessBuilder processBuilder = new ProcessBuilder(commands); + // Commented for remote ssh + // processBuilder.directory(startfolder); + processBuilder.redirectErrorStream(true); + process = processBuilder.start(); + + initializeStreams(); + + // Send a name request to check if the engine is KataGo + // Response handled in parseLine + isCheckingName = true; + sendCommand("name"); + + // Send a version request to check that we have a supported version + // Response handled in parseLine + isCheckingVersion = true; + sendCommand("version"); + boardSize(Lizzie.board.boardWidth, Lizzie.board.boardHeight); + komi(Lizzie.board.getHistory().getGameInfo().getKomi()); + + // start a thread to continuously read Leelaz output + // new Thread(this::read).start(); + // can stop engine for switching weights + executor = Executors.newSingleThreadScheduledExecutor(); + executor.execute(this::read); + started = true; + Lizzie.frame.refreshBackground(); + } + + public void restartEngine() throws IOException { + if (engineCommand.trim().isEmpty()) { + return; + } + switching = true; + this.engineCommand = engineCommand; + // stop the ponder + if (isPondering()) { + togglePonder(); + } + normalQuit(); + startEngine(); + // currentEngineN = index; + togglePonder(); + } + + public void normalQuit() { + sendCommand("quit"); + executor.shutdown(); + try { + while (!executor.awaitTermination(1, TimeUnit.SECONDS)) { + executor.shutdownNow(); + } + if (executor.awaitTermination(1, TimeUnit.SECONDS)) { + shutdown(); + } + } catch (InterruptedException e) { + executor.shutdownNow(); + Thread.currentThread().interrupt(); + } + started = false; + isLoaded = false; + Lizzie.engineManager.updateEngineIcon(); + } + + /** Initializes the input and output streams */ + private void initializeStreams() { + inputStream = new BufferedInputStream(process.getInputStream()); + outputStream = new BufferedOutputStream(process.getOutputStream()); + } + + public List parseInfo(String line) { + List bestMoves = new ArrayList<>(); + String[] variations = line.split(" info "); + for (String var : variations) { + if (!var.trim().isEmpty()) { + if (Lizzie.config.limitBestMoveNum > 0 + && bestMoves.size() >= Lizzie.config.limitBestMoveNum) { + break; + } + bestMoves.add(MoveData.fromInfo(var)); + } + } + Lizzie.board.getData().tryToSetBestMoves(bestMoves); + return bestMoves; + } + + public List parseInfoKatago(String line) { + List bestMoves = new ArrayList<>(); + String[] variations = line.split(" info "); + for (String var : variations) { + if (!var.trim().isEmpty()) { + if (Lizzie.config.limitBestMoveNum > 0 + && bestMoves.size() >= Lizzie.config.limitBestMoveNum) { + break; + } + bestMoves.add(MoveData.fromInfoKatago(var)); + } + } + Lizzie.board.getData().tryToSetBestMoves(bestMoves); + return bestMoves; + } + + /** + * Parse a line of Leelaz output + * + * @param line output line + */ + private void parseLine(String line) { + synchronized (this) { + if (printCommunication || gtpConsole) { + Lizzie.gtpConsole.addLine(line); + } + if (line.startsWith("komi=")) { + try { + dynamicKomi = Float.parseFloat(line.substring("komi=".length()).trim()); + } catch (NumberFormatException nfe) { + dynamicKomi = Float.NaN; + } + } else if (line.startsWith("opp_komi=")) { + try { + dynamicOppKomi = Float.parseFloat(line.substring("opp_komi=".length()).trim()); + } catch (NumberFormatException nfe) { + dynamicOppKomi = Float.NaN; + } + } else if (line.equals("\n")) { + // End of response + } else if (line.startsWith("info")) { + if (!isLoaded) { + Lizzie.frame.refresh(); + } + isLoaded = true; + // Clear switching prompt + switching = false; + // Display engine command in the title + Lizzie.frame.updateTitle(); + if (isResponseUpToDate()) { + // This should not be stale data when the command number match + if (isKataGo) { + this.bestMoves = parseInfoKatago(line.substring(5)); + if (Lizzie.config.showKataGoEstimate) { + if (line.contains("ownership")) { + estimateArray = new ArrayList(); + String[] params = line.trim().split("ownership"); + String[] params2 = params[1].trim().split(" "); + for (int i = 0; i < params2.length; i++) { + estimateArray.add(Double.parseDouble(params2[i])); + } + Lizzie.frame.drawEstimateRectKata(estimateArray); + } + } + } else { + this.bestMoves = parseInfo(line.substring(5)); + } + notifyBestMoveListeners(); + Lizzie.frame.refresh(1); + // don't follow the maxAnalyzeTime rule if we are in analysis mode + if (System.currentTimeMillis() - startPonderTime > maxAnalyzeTimeMillis + && !Lizzie.board.inAnalysisMode()) { + togglePonder(); + } + } + } else if (line.contains(" -> ")) { + if (!isLoaded) { + Lizzie.frame.refresh(); + } + isLoaded = true; + if (isResponseUpToDate() + || isThinking + && (!isPondering && Lizzie.frame.isPlayingAgainstLeelaz || isInputCommand)) { + // TODO Do not update the best moves when playing against Leela Zero + // Because it is equivalent to the winrate of the previous move. + if (!Lizzie.frame.isPlayingAgainstLeelaz + && (Lizzie.config.limitBestMoveNum == 0 + || bestMoves.size() < Lizzie.config.limitBestMoveNum)) { + bestMoves.add(MoveData.fromSummary(line)); + notifyBestMoveListeners(); + Lizzie.frame.refresh(1); + } + } + } else if (line.startsWith("play")) { + // In lz-genmove_analyze + if (Lizzie.frame.isPlayingAgainstLeelaz) { + Lizzie.board.place(line.substring(5).trim()); + } + isThinking = false; + + } else if (line.startsWith("=") || line.startsWith("?")) { + if (printCommunication || gtpConsole) { + System.out.print(line); + Lizzie.gtpConsole.addLine(line); + } + String[] params = line.trim().split(" "); + currentCmdNum = Integer.parseInt(params[0].substring(1).trim()); + + trySendCommandFromQueue(); + + if (line.startsWith("?") || params.length == 1) return; + + if (isSettingHandicap) { + bestMoves = new ArrayList<>(); + for (int i = 1; i < params.length; i++) { + Lizzie.board + .asCoordinates(params[i]) + .ifPresent(coords -> Lizzie.board.getHistory().setStone(coords, Stone.BLACK)); + } + isSettingHandicap = false; + } else if (isThinking && !isPondering) { + if (Lizzie.frame.isPlayingAgainstLeelaz || isInputCommand) { + Lizzie.board.place(params[1]); + if (Lizzie.frame.isAutoEstimating) { + if (Lizzie.board.getHistory().isBlacksTurn()) + Lizzie.frame.zen.sendCommand("play " + "w " + params[1]); + else Lizzie.frame.zen.sendCommand("play " + "b " + params[1]); + Lizzie.frame.zen.countStones(); + } + // TODO Do not ponder when playing against Leela Zero + // togglePonder(); + if (!isInputCommand) { + isPondering = false; + } + isThinking = false; + if (isInputCommand) { + isInputCommand = false; + } + } + } else if (isCheckingName) { + if (params[1].startsWith("KataGo")) { + this.isKataGo = true; + Lizzie.initializeAfterVersionCheck(this); + } + isCheckingName = false; + } else if (isCheckingVersion && !isKataGo) { + String[] ver = params[1].split("\\."); + int minor = Integer.parseInt(ver[1]); + // Gtp support added in version 15 + if (minor < 15) { + JOptionPane.showMessageDialog( + Lizzie.frame, + "Lizzie requires version 0.15 or later of Leela Zero for analysis (found " + + params[1] + + ")"); + } + isCheckingVersion = false; + Lizzie.initializeAfterVersionCheck(this); + } + } + } + } + + /** + * Parse a move-data line of Leelaz output + * + * @param line output line + */ + private void parseMoveDataLine(String line) { + line = line.trim(); + // ignore passes, and only accept lines that start with a coordinate letter + if (line.length() > 0 && Character.isLetter(line.charAt(0)) && !line.startsWith("pass")) { + if (!(Lizzie.frame.isPlayingAgainstLeelaz + && Lizzie.frame.playerIsBlack != Lizzie.board.getData().blackToPlay)) { + try { + bestMovesTemp.add(MoveData.fromInfo(line)); + } catch (ArrayIndexOutOfBoundsException e) { + // this is very rare but is possible. ignore + } + } + } + } + + /** Continually reads and processes output from leelaz */ + private void read() { + try { + int c; + StringBuilder line = new StringBuilder(); + while ((c = inputStream.read()) != -1) { + line.append((char) c); + if ((c == '\n')) { + parseLine(line.toString()); + line = new StringBuilder(); + } + } + // this line will be reached when Leelaz shuts down + System.out.println("Engine process ended."); + + shutdown(); + // Do no exit for switching weights + // System.exit(-1); + } catch (IOException e) { + e.printStackTrace(); + System.exit(-1); + } + } + + /** + * Sends a command to command queue for leelaz to execute + * + * @param command a GTP command containing no newline characters + */ + public void sendCommand(String command) { + synchronized (cmdQueue) { + // For efficiency, delete unnecessary "lz-analyze" that will be stopped immediately + if (!cmdQueue.isEmpty() + && (cmdQueue.peekLast().startsWith("lz-analyze") + || cmdQueue.peekLast().startsWith("kata-analyze"))) { + cmdQueue.removeLast(); + } + cmdQueue.addLast(command); + trySendCommandFromQueue(); + if (Lizzie.frame.isAutoEstimating) { + if (command.startsWith("play") || command.startsWith("undo")) { + Lizzie.frame.zen.sendCommand(command); + Lizzie.frame.zen.countStones(); + } + } + } + } + + /** Sends a command from command queue for leelaz to execute if it is ready */ + private void trySendCommandFromQueue() { + // Defer sending "lz-analyze" if leelaz is not ready yet. + // Though all commands should be deferred theoretically, + // only "lz-analyze" is deferred here for fear of + // possible hang-up by missing response for some reason. + // cmdQueue can be replaced with a mere String variable in this case, + // but it is kept for future change of our mind. + synchronized (cmdQueue) { + if (cmdQueue.isEmpty() + || (cmdQueue.peekFirst().startsWith("lz-analyze") + || cmdQueue.peekFirst().startsWith("kata-analyze")) + && !isResponseUpToDate()) { + return; + } + String command = cmdQueue.removeFirst(); + sendCommandToLeelaz(command); + } + } + + /** + * Sends a command for leelaz to execute + * + * @param command a GTP command containing no newline characters + */ + private void sendCommandToLeelaz(String command) { + if (command.startsWith("fixed_handicap") + || (isKataGo && command.startsWith("place_free_handicap"))) isSettingHandicap = true; + if (printCommunication) { + System.out.printf("> %d %s\n", cmdNumber, command); + } + Lizzie.gtpConsole.addCommand(command, cmdNumber); + command = cmdNumber + " " + command; + cmdNumber++; + try { + outputStream.write((command + "\n").getBytes()); + outputStream.flush(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** Check whether leelaz is responding to the last command */ + private boolean isResponseUpToDate() { + // Use >= instead of == for avoiding hang-up, though it cannot happen + return currentCmdNum >= cmdNumber - 1; + } + + /** + * @param color color of stone to play + * @param move coordinate of the coordinate + */ + public void playMove(Stone color, String move) { + synchronized (this) { + String colorString; + switch (color) { + case BLACK: + colorString = "B"; + break; + case WHITE: + colorString = "W"; + break; + default: + throw new IllegalArgumentException( + "The stone color must be B or W, but was " + color.toString()); + } + + sendCommand("play " + colorString + " " + move); + bestMoves = new ArrayList<>(); + + if (isPondering && !Lizzie.frame.isPlayingAgainstLeelaz) ponder(); + } + } + + public void genmove(String color) { + String command = "genmove " + color; + /* + * We don't support displaying this while playing, so no reason to request it (for now) + if (isPondering) { + command = "lz-genmove_analyze " + color + " 10"; + }*/ + sendCommand(command); + isThinking = true; + isPondering = false; + } + + public void genmove_analyze(String color) { + String command = + "lz-genmove_analyze " + + color + + " " + + Lizzie.config + .config + .getJSONObject("leelaz") + .getInt("analyze-update-interval-centisec"); + sendCommand(command); + isThinking = true; + isPondering = false; + } + + public void time_settings() { + sendCommand( + "time_settings 0 " + + Lizzie.config.config.getJSONObject("leelaz").getInt("max-game-thinking-time-seconds") + + " 1"); + } + + public void clear() { + synchronized (this) { + supportScoremean = false; + sendCommand("clear_board"); + bestMoves = new ArrayList<>(); + if (isPondering) ponder(); + } + } + + public void boardSize(int size) { + boardSize(size, size); + } + + public void boardSize(int width, int height) { + synchronized (this) { + sendCommand("boardsize " + width + (width != height ? " " + height : "")); + } + } + + public void komi(double komi) { + synchronized (this) { + sendCommand("komi " + (komi == 0.0 ? "0" : komi)); + bestMoves = new ArrayList<>(); + Lizzie.board.getData().tryToClearBestMoves(); + if (isPondering) ponder(); + } + } + + public void handicap(int num) { + sendCommand((isKataGo ? "place_free_handicap " : "fixed_handicap ") + num); + } + + public void undo() { + synchronized (this) { + sendCommand("undo"); + bestMoves = new ArrayList<>(); + if (isPondering) ponder(); + } + } + + public void analyzeAvoid(String type, String color, String coordList, int untilMove) { + analyzeAvoid( + String.format("%s %s %s %d", type, color, coordList, untilMove <= 0 ? 1 : untilMove)); + } + + public void analyzeAvoid(String parameters) { + bestMoves = new ArrayList<>(); + if (!isPondering) { + isPondering = true; + startPonderTime = System.currentTimeMillis(); + } + sendCommand( + String.format( + "lz-analyze %d %s", + Lizzie.config.config.getJSONObject("leelaz").getInt("analyze-update-interval-centisec"), + parameters)); + } + + /** This initializes leelaz's pondering mode at its current position */ + public void ponder() { + isPondering = true; + startPonderTime = System.currentTimeMillis(); + if (Lizzie.board.isAvoding && Lizzie.board.isKeepingAvoid && !isKataGo) + analyzeAvoid( + "avoid", + Lizzie.board.getHistory().isBlacksTurn() ? "w" : "b", + Lizzie.board.avoidCoords, + +Lizzie.config.config.getJSONObject("leelaz").getInt("avoid-keep-variations")); + else + sendCommand( + (this.isKataGo ? "kata-analyze " : "lz-analyze ") + + Lizzie.config + .config + .getJSONObject("leelaz") + .getInt("analyze-update-interval-centisec") + + (this.isKataGo && Lizzie.config.showKataGoEstimate ? " ownership true" : "")); + // until it responds to this, incoming + // ponder results are obsolete + } + + public void togglePonder() { + isPondering = !isPondering; + if (isPondering) { + ponder(); + } else { + sendCommand("name"); // ends pondering + } + Lizzie.frame.updateBasicInfo(); + } + + /** End the process */ + public void shutdown() { + process.destroy(); + } + + public List getBestMoves() { + synchronized (this) { + return bestMoves; + } + } + + public Optional getDynamicKomi() { + if (Float.isNaN(dynamicKomi) || Float.isNaN(dynamicOppKomi)) { + return Optional.empty(); + } else { + return Optional.of(String.format("%.1f / %.1f", dynamicKomi, dynamicOppKomi)); + } + } + + public boolean isPondering() { + return isPondering; + } + + public class WinrateStats { + public double maxWinrate; + public double maxScoreMean; + public int totalPlayouts; + + public WinrateStats(double maxWinrate, int totalPlayouts) { + this.maxWinrate = maxWinrate; + this.totalPlayouts = totalPlayouts; + } + } + + /* + * Return the best win rate and total number of playouts. + * If no analysis available, win rate is negative and playouts is 0. + */ + public WinrateStats getWinrateStats() { + WinrateStats stats = new WinrateStats(-100, 0); + + if (!bestMoves.isEmpty()) { + // we should match the Leelaz UCTNode get_eval, which is a weighted average + // copy the list to avoid concurrent modification exception... TODO there must be a better way + // (note the concurrent modification exception is very very rare) + // We should use Lizzie Board's best moves as they will generally be the most accurate + final List moves = new ArrayList(Lizzie.board.getData().bestMoves); + + // get the total number of playouts in moves + int totalPlayouts = moves.stream().mapToInt(move -> move.playouts).sum(); + stats.totalPlayouts = totalPlayouts; + + stats.maxWinrate = BoardData.getWinrateFromBestMoves(moves); + if (isKataGo) { + stats.maxScoreMean = BoardData.getScoreMeanFromBestMoves(moves); + } + } + + return stats; + } + + /* + * initializes the normalizing factor for winrate_to_handicap_stones conversion. + */ + public void estimatePassWinrate() { + // we use A1 instead of pass, because valuenetwork is more accurate for A1 on empty board than a + // pass. + // probably the reason for higher accuracy is that networks have randomness which produces + // occasionally A1 as first move, but never pass. + // for all practical purposes, A1 should equal pass for the value it provides, hence good + // replacement. + // this way we avoid having to run lots of playouts for accurate winrate for pass. + playMove(Stone.BLACK, "A1"); + togglePonder(); + WinrateStats stats = getWinrateStats(); + + // we could use a timelimit or higher minimum playouts to get a more accurate measurement. + while (stats.totalPlayouts < 1) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + throw new Error(e); + } + stats = getWinrateStats(); + } + mHandicapWinrate = stats.maxWinrate; + togglePonder(); + undo(); + Lizzie.board.clear(); + } + + public static double mHandicapWinrate = 25; + + /** + * Convert winrate to handicap stones, by normalizing winrate by first move pass winrate (one + * stone handicap). + */ + public static double winrateToHandicap(double pWinrate) { + // we assume each additional handicap lowers winrate by fixed percentage. + // this is pretty accurate for human handicap games at least. + // also this kind of property is a requirement for handicaps to determined based on rank + // difference. + + // lets convert the 0%-50% range and 100%-50% from both the move and and pass into range of 0-1 + double moveWinrateSymmetric = 1 - Math.abs(1 - (pWinrate / 100) * 2); + double passWinrateSymmetric = 1 - Math.abs(1 - (mHandicapWinrate / 100) * 2); + + // convert the symmetric move winrate into correctly scaled log scale, so that winrate of + // passWinrate equals 1 handicap. + double handicapSymmetric = Math.log(moveWinrateSymmetric) / Math.log(passWinrateSymmetric); + + // make it negative if we had low winrate below 50. + return Math.signum(pWinrate - 50) * handicapSymmetric; + } + + public synchronized void addListener(LeelazListener listener) { + listeners.add(listener); + } + + // Beware, due to race conditions, bestMoveNotification can be called once even after item is + // removed + // with removeListener + public synchronized void removeListener(LeelazListener listener) { + listeners.remove(listener); + } + + private synchronized void notifyBestMoveListeners() { + for (LeelazListener listener : listeners) { + listener.bestMoveNotification(bestMoves); + } + } + + private static enum ParamState { + NORMAL, + QUOTE, + DOUBLE_QUOTE + } + + public List splitCommand(String commandLine) { + if (commandLine == null || commandLine.length() == 0) { + return new ArrayList(); + } + + final ArrayList commandList = new ArrayList(); + final StringBuilder param = new StringBuilder(); + final StringTokenizer tokens = new StringTokenizer(commandLine, " '\"", true); + boolean lastTokenQuoted = false; + ParamState state = ParamState.NORMAL; + + while (tokens.hasMoreTokens()) { + String nextToken = tokens.nextToken(); + switch (state) { + case QUOTE: + if ("'".equals(nextToken)) { + state = ParamState.NORMAL; + lastTokenQuoted = true; + } else { + param.append(nextToken); + } + break; + case DOUBLE_QUOTE: + if ("\"".equals(nextToken)) { + state = ParamState.NORMAL; + lastTokenQuoted = true; + } else { + param.append(nextToken); + } + break; + default: + if ("'".equals(nextToken)) { + state = ParamState.QUOTE; + } else if ("\"".equals(nextToken)) { + state = ParamState.DOUBLE_QUOTE; + } else if (" ".equals(nextToken)) { + if (lastTokenQuoted || param.length() != 0) { + commandList.add(Utils.withQuote(param.toString())); + param.delete(0, param.length()); + } + } else { + param.append(nextToken); + } + lastTokenQuoted = false; + break; + } + } + if (lastTokenQuoted || param.length() != 0) { + commandList.add(param.toString()); + } + return commandList; + } + + public boolean isCommandChange(String command) { + List newList = splitCommand(command); + if (this.commands.size() != newList.size()) { + return true; + } else { + for (int i = 0; i < this.commands.size(); i++) { + String param = this.commands.get(i); + String newParam = newList.get(i); + if ((!Utils.isBlank(param) || !Utils.isBlank(newParam)) + && (Utils.isBlank(param) || !param.equals(newParam))) { + return true; + } + } + return false; + } + } + + public boolean isStarted() { + return started; + } + + public boolean isLoaded() { + return isLoaded; + } + + public boolean supportScoremean() { + return isKataGo || supportScoremean; + } + + public String currentWeight() { + return currentWeight; + } + + public String currentShortWeight() { + if (currentWeight != null && currentWeight.length() > 18) { + return currentWeight.substring(0, 16) + ".."; + } + return currentWeight; + } + + public boolean switching() { + return switching; + } + + public int currentEngineN() { + return currentEngineN; + } + + public String engineCommand() { + return this.engineCommand; + } + + public void toggleGtpConsole() { + gtpConsole = !gtpConsole; + } + + public void setWeightName() { + Pattern wPattern = Pattern.compile("(?s).*?(--weights |-w |-model )([^'\" ]+)(?s).*"); + Matcher wMatcher = wPattern.matcher(engineCommand); + if (wMatcher.matches() && wMatcher.groupCount() == 2) { + currentWeightFile = wMatcher.group(2); + String[] names = currentWeightFile.split("[\\\\|/]"); + currentWeight = names.length > 1 ? names[names.length - 1] : currentWeightFile; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `featurecat.lizzie.analysis.Leelaz.ponder` indirectly writes to field `$T5_32.featurecat.lizzie.analysis.Leelaz.isPondering` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Leelaz.ponder() + +### Procedure Id: +featurecat.lizzie.analysis.Leelaz.ponder():void.8a699fc10e6e7598db8ecccc9be0d4b5 + +### File: +src/main/java/featurecat/lizzie/analysis/Leelaz.java + +### Key: +Leelaz.java|ponder|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +97ceb6c5b5b79a98f747b22527ddc754 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10101/instruction.md b/inferredbugs-10101/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f2b09e8dc44ebe0b0b7930cd012099e24b77f963 --- /dev/null +++ b/inferredbugs-10101/instruction.md @@ -0,0 +1,292 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jadb +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package se.vidstige.jadb; + +import se.vidstige.jadb.managers.Bash; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +public class JadbDevice { + @SuppressWarnings("squid:S00115") + public enum State { + Unknown, + Offline, + Device, + Recovery, + BootLoader + } + + private final String serial; + private final ITransportFactory transportFactory; + + JadbDevice(String serial, String type, ITransportFactory tFactory) { + this.serial = serial; + this.transportFactory = tFactory; + } + + static JadbDevice createAny(JadbConnection connection) { + return new JadbDevice(connection); + } + + private JadbDevice(ITransportFactory tFactory) { + serial = null; + this.transportFactory = tFactory; + } + + private State convertState(String type) { + switch (type) { + case "device": return State.Device; + case "offline": return State.Offline; + case "bootloader": return State.BootLoader; + case "recovery": return State.Recovery; + default: return State.Unknown; + } + } + + private Transport getTransport() throws IOException, JadbException { + Transport transport = transportFactory.createTransport(); + send(transport, serial == null ? "host:transport-any" : "host:transport:" + serial ); + return transport; + } + + public String getSerial() { + return serial; + } + + public State getState() throws IOException, JadbException { + Transport transport = transportFactory.createTransport(); + send(transport, serial == null ? "host:get-state" : "host-serial:" + serial + ":get-state"); + + State state = convertState(transport.readString()); + transport.close(); + return state; + } + + /**

Execute a shell command.

+ * + *

For Lollipop and later see: {@link #execute(String, String...)}

+ * + * @param command main command to run. E.g. "ls" + * @param args arguments to the command. + * @return combined stdout/stderr stream. + * @throws IOException + * @throws JadbException + */ + public InputStream executeShell(String command, String... args) throws IOException, JadbException { + Transport transport = getTransport(); + StringBuilder shellLine = buildCmdLine(command, args); + send(transport, "shell:" + shellLine.toString()); + return new AdbFilterInputStream(new BufferedInputStream(transport.getInputStream())); + } + + /** + * + * @deprecated Use InputStream executeShell(String command, String... args) method instead. Together with + * Stream.copy(in, out), it is possible to achieve the same effect. + */ + @Deprecated + public void executeShell(OutputStream output, String command, String... args) throws IOException, JadbException { + Transport transport = getTransport(); + StringBuilder shellLine = buildCmdLine(command, args); + send(transport, "shell:" + shellLine.toString()); + if (output != null) { + AdbFilterOutputStream out = new AdbFilterOutputStream(output); + try { + transport.readResponseTo(out); + } finally { + out.close(); + } + } + } + + /**

Execute a command with raw binary output.

+ * + *

Support for this command was added in Lollipop (Android 5.0), and is the recommended way to transmit binary + * data with that version or later. For earlier versions of Android, use + * {@link #executeShell(String, String...)}.

+ * + * @param command main command to run, e.g. "screencap" + * @param args arguments to the command, e.g. "-p". + * @return combined stdout/stderr stream. + * @throws IOException + * @throws JadbException + */ + public InputStream execute(String command, String... args) throws IOException, JadbException { + Transport transport = getTransport(); + StringBuilder shellLine = buildCmdLine(command, args); + send(transport, "exec:" + shellLine.toString()); + return new BufferedInputStream(transport.getInputStream()); + } + + /** + * Builds a command line string from the command and its arguments. + * + * @param command the command. + * @param args the list of arguments. + * @return the command line. + */ + private StringBuilder buildCmdLine(String command, String... args) { + StringBuilder shellLine = new StringBuilder(command); + for (String arg : args) { + shellLine.append(" "); + shellLine.append(Bash.quote(arg)); + } + return shellLine; + } + + public List list(String remotePath) throws IOException, JadbException { + Transport transport = getTransport(); + SyncTransport sync = transport.startSync(); + sync.send("LIST", remotePath); + + List result = new ArrayList<>(); + for (RemoteFileRecord dent = sync.readDirectoryEntry(); dent != RemoteFileRecord.DONE; dent = sync.readDirectoryEntry()) { + result.add(dent); + } + return result; + } + + private int getMode(File file) { + //noinspection OctalInteger + return 0664; + } + + public void push(InputStream source, long lastModified, int mode, RemoteFile remote) throws IOException, JadbException { + Transport transport = getTransport(); + SyncTransport sync = transport.startSync(); + sync.send("SEND", remote.getPath() + "," + Integer.toString(mode)); + + sync.sendStream(source); + + sync.sendStatus("DONE", (int) lastModified); + sync.verifyStatus(); + } + + public void push(File local, RemoteFile remote) throws IOException, JadbException { + FileInputStream fileStream = new FileInputStream(local); + push(fileStream, local.lastModified(), getMode(local), remote); + fileStream.close(); + } + + public void pull(RemoteFile remote, OutputStream destination) throws IOException, JadbException { + Transport transport = getTransport(); + SyncTransport sync = transport.startSync(); + sync.send("RECV", remote.getPath()); + + sync.readChunksTo(destination); + } + + public void pull(RemoteFile remote, File local) throws IOException, JadbException { + FileOutputStream fileStream = new FileOutputStream(local); + pull(remote, fileStream); + fileStream.close(); + } + + private void send(Transport transport, String command) throws IOException, JadbException { + transport.send(command); + transport.verifyResponse(); + } + + @Override + public String toString() { + return "Android Device with serial " + serial; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((serial == null) ? 0 : serial.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + JadbDevice other = (JadbDevice) obj; + if (serial == null) { + return other.serial == null; + } + return serial.equals(other.serial); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired to `fileStream` by call to `FileInputStream(...)` at line 166 is not released after line 169. +**Note**: potential exception at line 167 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JadbDevice.push(File,RemoteFile) + +### Procedure Id: +se.vidstige.jadb.JadbDevice.push(java.io.File,se.vidstige.jadb.RemoteFile):void.3894c5695ee1ceb9ce5f72a0422ed6f4 + +### File: +src/se/vidstige/jadb/JadbDevice.java + +### Key: +JadbDevice.java|push|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +787149f5cf47ff24c65ced445c4c80ec + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10108/instruction.md b/inferredbugs-10108/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..60d195530e784443214c8f6f43205c78a960e027 --- /dev/null +++ b/inferredbugs-10108/instruction.md @@ -0,0 +1,265 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jadb +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package se.vidstige.jadb; + +import se.vidstige.jadb.managers.Bash; + +import java.io.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class JadbDevice { + public enum State { + Unknown, + Offline, + Device, + BootLoader + }; + + private final String serial; + private final ITransportFactory transportFactory; + + JadbDevice(String serial, String type, ITransportFactory tFactory) { + this.serial = serial; + this.transportFactory = tFactory; + } + + static JadbDevice createAny(JadbConnection connection) { + return new JadbDevice(connection); + } + + private JadbDevice(ITransportFactory tFactory) { + serial = null; + this.transportFactory = tFactory; + } + + private State convertState(String type) { + switch (type) { + case "device": return State.Device; + case "offline": return State.Offline; + case "bootloader": return State.BootLoader; + default: return State.Unknown; + } + } + + private Transport getTransport() throws IOException, JadbException { + Transport transport = transportFactory.createTransport(); + if (serial == null) { + transport.send("host:transport-any"); + transport.verifyResponse(); + } else { + transport.send("host:transport:" + serial); + transport.verifyResponse(); + } + return transport; + } + + public String getSerial() { + return serial; + } + + public State getState() throws IOException, JadbException { + Transport transport = transportFactory.createTransport(); + if (serial == null) { + transport.send("host:get-state"); + transport.verifyResponse(); + } else { + transport.send("host-serial:" + serial + ":get-state"); + transport.verifyResponse(); + } + + State state = convertState(transport.readString()); + transport.close(); + return state; + } + + public InputStream executeShell(String command, String... args) throws IOException, JadbException { + Transport transport = getTransport(); + StringBuilder shellLine = new StringBuilder(command); + for (String arg : args) { + shellLine.append(" "); + shellLine.append(Bash.quote(arg)); + } + send(transport, "shell:" + shellLine.toString()); + return new AdbFilterInputStream(new BufferedInputStream(transport.getInputStream())); + } + + /** + * + * @deprecated Use InputStream executeShell(String command, String... args) method instead. Together with + * Stream.copy(in, out), it is possible to achieve the same effect. + */ + @Deprecated + public void executeShell(OutputStream output, String command, String... args) throws IOException, JadbException { + Transport transport = getTransport(); + StringBuilder shellLine = new StringBuilder(command); + for (String arg : args) { + shellLine.append(" "); + shellLine.append(Bash.quote(arg)); + } + send(transport, "shell:" + shellLine.toString()); + if (output != null) { + transport.readResponseTo(new AdbFilterOutputStream(output)); + } + } + + public List list(String remotePath) throws IOException, JadbException { + Transport transport = getTransport(); + SyncTransport sync = transport.startSync(); + sync.send("LIST", remotePath); + + List result = new ArrayList(); + for (RemoteFileRecord dent = sync.readDirectoryEntry(); dent != RemoteFileRecord.DONE; dent = sync.readDirectoryEntry()) { + result.add(dent); + } + return result; + } + + private int getMode(File file) { + //noinspection OctalInteger + return 0664; + } + + public void push(InputStream source, long lastModified, int mode, RemoteFile remote) throws IOException, JadbException { + Transport transport = getTransport(); + SyncTransport sync = transport.startSync(); + sync.send("SEND", remote.getPath() + "," + Integer.toString(mode)); + + sync.sendStream(source); + + sync.sendStatus("DONE", (int) lastModified); + sync.verifyStatus(); + } + + public void push(File local, RemoteFile remote) throws IOException, JadbException { + FileInputStream fileStream = new FileInputStream(local); + push(fileStream, local.lastModified(), getMode(local), remote); + fileStream.close(); + } + + public void pull(RemoteFile remote, OutputStream destination) throws IOException, JadbException { + Transport transport = getTransport(); + SyncTransport sync = transport.startSync(); + sync.send("RECV", remote.getPath()); + + sync.readChunksTo(destination); + } + + public void pull(RemoteFile remote, File local) throws IOException, JadbException { + FileOutputStream fileStream = new FileOutputStream(local); + pull(remote, fileStream); + fileStream.close(); + } + + private void send(Transport transport, String command) throws IOException, JadbException { + transport.send(command); + transport.verifyResponse(); + } + + @Override + public String toString() { + return "Android Device with serial " + serial; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((serial == null) ? 0 : serial.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + JadbDevice other = (JadbDevice) obj; + if (serial == null) { + if (other.serial != null) + return false; + } else if (!serial.equals(other.serial)) + return false; + return true; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `se.vidstige.jadb.AdbFilterOutputStream` acquired by call to `AdbFilterOutputStream(...)` at line 104 is not released after line 104. +**Note**: potential exception at line 104 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JadbDevice.executeShell(OutputStream,String,java.lang.String[]) + +### Procedure Id: +se.vidstige.jadb.JadbDevice.executeShell(java.io.OutputStream,java.lang.String,java.lang.String[]):v.07ea9a6702911ff562b3cee92b720e8e + +### File: +src/se/vidstige/jadb/JadbDevice.java + +### Key: +JadbDevice.java|executeShell|RESOURCE_LEAK + +### Node Key: +f3e05835b2e0d3828d170cbdd6a93256 + +### Hash: +2ed6f3c47ec3997126f5feabcee83232 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10130/instruction.md b/inferredbugs-10130/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d36f4caedaa9c939275b532e047759a340146ef6 --- /dev/null +++ b/inferredbugs-10130/instruction.md @@ -0,0 +1,223 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** CERMINE +**Bug ID:** 24 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * This file is part of CERMINE project. + * Copyright (c) 2011-2016 ICM-UW + * + * CERMINE is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * CERMINE 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with CERMINE. If not, see . + */ +package pl.edu.icm.cermine.structure; + +import com.google.common.collect.Lists; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Enumeration; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import org.junit.Before; +import org.junit.Test; +import pl.edu.icm.cermine.exception.TransformationException; +import pl.edu.icm.cermine.structure.model.*; +import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; + +/** + * @author Pawel Szostek + */ +public class HierarchicalReadingOrderResolverTest { + + private final static String PATH = "/pl/edu/icm/cermine/structure/"; + private final static String[] TEST_FILENAMES = {"1748717X.xml"}; + private final static String ZIP_FILE_NAME = "roa_test_small.zip"; + + private ZipFile zipFile; + + @Before + public void setUp() throws URISyntaxException, ZipException, IOException { + URL url = HierarchicalReadingOrderResolverTest.class.getResource(PATH + ZIP_FILE_NAME); + URI uri = url.toURI(); + File file = new File(uri); + zipFile = new ZipFile(file); + } + + private BxDocument getDocumentFromZip(String filename) throws TransformationException, IOException { + TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); + Enumeration entries = zipFile.entries(); + while (entries.hasMoreElements()) { + ZipEntry zipEntry = (ZipEntry) entries.nextElement(); + if (zipEntry.getName().equals(filename)) { + List pages = tvReader.read(new InputStreamReader(zipFile.getInputStream(zipEntry))); + BxDocument newDoc = new BxDocument(); + for (BxPage page : pages) { + page.setParent(newDoc); + } + newDoc.setFilename(zipEntry.getName()); + newDoc.setPages(pages); + return newDoc; + } + } + return null; + } + + private Boolean areDocumentsEqual(BxDocument doc1, BxDocument doc2) { + if (doc1.childrenCount() != doc2.childrenCount()) { + return false; + } + for (Integer pageIdx = 0; pageIdx < doc1.childrenCount(); ++pageIdx) { + BxPage page1 = doc1.getChild(pageIdx); + BxPage page2 = doc2.getChild(pageIdx); + if (page1.childrenCount() != page2.childrenCount()) { + return false; + } + for (Integer zoneIdx = 0; zoneIdx < page1.childrenCount(); ++zoneIdx) { + BxZone zone1 = page1.getChild(zoneIdx); + BxZone zone2 = page2.getChild(zoneIdx); + if (zone1.getChunks().size() != zone2.getChunks().size()) { + return false; + } + for (Integer chunkIdx = 0; chunkIdx < zone1.getChunks().size(); ++chunkIdx) { + BxChunk chunk1 = zone1.getChunks().get(chunkIdx); + BxChunk chunk2 = zone2.getChunks().get(chunkIdx); + if (!chunk1.toText().equals(chunk2.toText())) { + return false; + } + } + } + } + return true; + } + + @Test + public void testSetReadingOrder() throws TransformationException, IOException { + for (Enumeration e = zipFile.entries(); e.hasMoreElements();) { + String filename = e.nextElement().getName(); + if (!filename.endsWith(".xml")) { + continue; + } + BxDocument doc = getDocumentFromZip(filename); + BxDocument modelOrderedDoc = getDocumentFromZip(filename + ".out"); + + HierarchicalReadingOrderResolver roa = new HierarchicalReadingOrderResolver(); + BxDocument orderedDoc = roa.resolve(doc); + + assertTrue(areDocumentsEqual(orderedDoc, modelOrderedDoc)); + } + } + + @Test + public void testConstantElementsNumber() throws TransformationException, IOException { + for (String filename : TEST_FILENAMES) { + BxDocument doc = getDocumentFromZip(filename); + + HierarchicalReadingOrderResolver roa = new HierarchicalReadingOrderResolver(); + BxDocument orderedDoc = roa.resolve(doc); + + List pages1 = Lists.newArrayList(doc.asPages()); + List pages2 = Lists.newArrayList(orderedDoc.asPages()); + List zones1 = Lists.newArrayList(doc.asZones()); + List zones2 = Lists.newArrayList(orderedDoc.asZones()); + List lines1 = Lists.newArrayList(doc.asLines()); + List lines2 = Lists.newArrayList(orderedDoc.asLines()); + List words1 = Lists.newArrayList(doc.asWords()); + List words2 = Lists.newArrayList(orderedDoc.asWords()); + List chunks1 = Lists.newArrayList(doc.asChunks()); + List chunks2 = Lists.newArrayList(orderedDoc.asChunks()); + + assertEquals(pages1.size(), pages2.size()); + assertEquals(zones1.size(), zones2.size()); + assertEquals(lines1.size(), lines2.size()); + assertEquals(words1.size(), words2.size()); + assertEquals(chunks1.size(), chunks2.size()); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 65 is not released after line 65. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +BxDocument HierarchicalReadingOrderResolverTest.getDocumentFromZip(String) + +### Procedure Id: +pl.edu.icm.cermine.structure.HierarchicalReadingOrderResolverTest.getDocumentFromZip(java.lang.Strin.d535080948c4d91d1fbbe29d5e12a095 + +### File: +cermine-impl/src/test/java/pl/edu/icm/cermine/structure/HierarchicalReadingOrderResolverTest.java + +### Key: +HierarchicalReadingOrderResolverTest.java|getDocumentFromZip|RESOURCE_LEAK + +### Node Key: +ce0488985df17883c0fe7bff0ee1ed09 + +### Hash: +99abdbbac3937f8ed99e677660dda6ba + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10137/instruction.md b/inferredbugs-10137/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3db2259e6071754d082cb14cd09423ede4556773 --- /dev/null +++ b/inferredbugs-10137/instruction.md @@ -0,0 +1,152 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** CERMINE +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * This file is part of CERMINE project. + * Copyright (c) 2011-2016 ICM-UW + * + * CERMINE is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * CERMINE 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with CERMINE. If not, see . + */ + +package pl.edu.icm.cermine.tools; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import org.apache.commons.io.FileUtils; +import pl.edu.icm.cermine.exception.TransformationException; +import pl.edu.icm.cermine.structure.model.BxDocument; +import pl.edu.icm.cermine.structure.model.BxPage; +import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; + +/** + * @author Pawel Szostek + */ +public class RecursiveDirExtractor implements DocumentsExtractor { + + protected File directory; + + public RecursiveDirExtractor(String path) { + directory = new File(path); + if (!directory.exists() || !directory.isDirectory()) { + throw new RuntimeException("Source directory for documents doesn't exist: " + path); + } + } + + public RecursiveDirExtractor(File directory) { + this.directory = directory; + } + + @Override + public List getDocuments() throws TransformationException { + TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); + List documents = new ArrayList(); + + for (File file : FileUtils.listFiles(directory, new String[]{"xml"}, true)) { + InputStream is = null; + try { + is = new FileInputStream(file); + List pages = tvReader.read(new InputStreamReader(is)); + BxDocument doc = new BxDocument(); + doc.setFilename(file.getName()); + doc.setPages(pages); + documents.add(doc); + } catch (FileNotFoundException ex) { + throw new TransformationException(ex); + } finally { + if (is != null) { + try { + is.close(); + } catch (IOException ex) { + throw new TransformationException("Cannot close stream!", ex); + } + } + } + } + + return documents; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 57 is not released after line 57. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List RecursiveDirExtractor.getDocuments() + +### Procedure Id: +pl.edu.icm.cermine.tools.RecursiveDirExtractor.getDocuments():java.util.List.5b08ef934e4e1bf0f895ff15084a2a91 + +### File: +cermine-impl/src/main/java/pl/edu/icm/cermine/tools/RecursiveDirExtractor.java + +### Key: +RecursiveDirExtractor.java|getDocuments|RESOURCE_LEAK + +### Node Key: +ce0488985df17883c0fe7bff0ee1ed09 + +### Hash: +86f7e0a6f3997a51fdce104312bf68d1 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1015/instruction.md b/inferredbugs-1015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0abe404e70a4dcc2217927a41820bcbf44d84473 --- /dev/null +++ b/inferredbugs-1015/instruction.md @@ -0,0 +1,97 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** PatreonDownloader +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.IO; +using System.Linq; +using System.Text; +using UniversalDownloaderPlatform.Common.Enums; +using UniversalDownloaderPlatform.Common.Helpers; + +namespace PatreonDownloader.Implementation +{ + /// + /// Helper used to generate name for post subdirectories + /// + internal class PostSubdirectoryHelper + { + /// + /// Create a sanitized directory name based on supplied name pattern + /// + /// Crawled url with published date, post title and post id + /// Pattern for directory name + /// + public static string CreateNameFromPattern(PatreonCrawledUrl crawledUrl, string pattern) + { + string postTitle = crawledUrl.Title.Trim(); + while (postTitle.Length > 1 && postTitle[^1] == '.') + postTitle = postTitle.Remove(postTitle.Length - 1).Trim(); + + string retString = pattern.ToLowerInvariant() + .Replace("%publishedat%", crawledUrl.PublishedAt.ToString("yyyy-MM-dd")) + .Replace("%posttitle%", postTitle) + .Replace("%postid%", crawledUrl.PostId); + + return PathSanitizer.SanitizePath(retString); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `postTitle` last assigned on line 25 could be null and is dereferenced at line 24, column 13. + +### Severity: +ERROR + +### Procedure: +String PostSubdirectoryHelper.CreateNameFromPattern(PatreonCrawledUrl,String) + +### File: +PatreonDownloader.Implementation/Helpers/PostSubdirectoryHelper.cs + +### Key: +PostSubdirectoryHelper.cs|CreateNameFromPattern|NULL_DEREFERENCE + +### Node Key: +c16cc1d2b5bc88a6c7c2310f1d47f089 + +### Hash: +ef29fb18d6fab0384e5fae7f7cb6854b + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10212/instruction.md b/inferredbugs-10212/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..097ef444e20f63c11ecc54e75f9ba22a5c1d2e72 --- /dev/null +++ b/inferredbugs-10212/instruction.md @@ -0,0 +1,661 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** spotify-web-api-java +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.wrapper.spotify; + +import com.wrapper.spotify.UtilProtos.Url.Scheme; +import com.wrapper.spotify.methods.Request; +import com.wrapper.spotify.models.AlbumType; +import net.sf.json.JSONObject; +import org.apache.commons.codec.binary.Base64; +import org.junit.Test; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import static com.wrapper.spotify.Assertions.*; +import static junit.framework.TestCase.assertEquals; + +public class ApiTest { + + @Test + public void shouldCreateAGetAlbumUrl() { + Api api = Api.DEFAULT_API; + Request request = api.getAlbum("5oEljuMoe9MXH6tBIPbd5e").build(); + assertEquals("https://api.spotify.com:443/v1/albums/5oEljuMoe9MXH6tBIPbd5e", request.toString()); + } + + @Test + public void shouldCreateGetAudioFeaturesUrl(){ + Api api = Api.DEFAULT_API; + Request request = api.getAudioFeature("1hmNbafW4sAPNaGc7LeXAZ").build(); + assertEquals("https://api.spotify.com:443/v1/audio-features/1hmNbafW4sAPNaGc7LeXAZ", request.toString()); + } + + @Test + public void shouldCreateAGetArtistUrl() { + Api api = Api.DEFAULT_API; + Request request = api.getArtist("5rSXSAkZ67PYJSvpUpkOr7").build(); + assertEquals("https://api.spotify.com:443/v1/artists/5rSXSAkZ67PYJSvpUpkOr7", request.toString()); + } + + @Test + public void shouldCreateAGetTrackUrl() { + Api api = Api.DEFAULT_API; + Request request = api.getTrack("6hDH3YWFdcUNQjubYztIsG").build(); + assertEquals("https://api.spotify.com:443/v1/tracks/6hDH3YWFdcUNQjubYztIsG", request.toString()); + } + + @Test + public void shouldCreateAGetAlbumsUrl() { + Api api = Api.DEFAULT_API; + Request request = api.getAlbums("6hDH3YWFdcUNQjubYztIsG", "2IA4WEsWAYpV9eKkwR2UYv").build(); + assertEquals("https://api.spotify.com:443/v1/albums", request.toString()); + assertHasParameter(request.toUrl(), "ids", "6hDH3YWFdcUNQjubYztIsG,2IA4WEsWAYpV9eKkwR2UYv"); + } + + @Test + public void shouldCreateAGetAlbumsUrlFromAList() { + Api api = Api.DEFAULT_API; + Request request = api.getAlbums(Arrays.asList("6hDH3YWFdcUNQjubYztIsG", "2IA4WEsWAYpV9eKkwR2UYv")).build(); + assertEquals("https://api.spotify.com:443/v1/albums", request.toString()); + assertHasParameter(request.toUrl(), "ids", "6hDH3YWFdcUNQjubYztIsG,2IA4WEsWAYpV9eKkwR2UYv"); + } + + @Test + public void shouldCreateAGetTracksUrl() { + Api api = Api.DEFAULT_API; + Request request = api.getTracks("6hDH3YWFdcUNQjubYztIsG", "2IA4WEsWAYpV9eKkwR2UYv").build(); + assertEquals("https://api.spotify.com:443/v1/tracks", request.toString()); + assertHasParameter(request.toUrl(), "ids", "6hDH3YWFdcUNQjubYztIsG,2IA4WEsWAYpV9eKkwR2UYv"); + } + + @Test + public void shouldCreateAGetTracksUrlFromList() { + Api api = Api.DEFAULT_API; + Request request = api.getTracks(Arrays.asList("6hDH3YWFdcUNQjubYztIsG", "2IA4WEsWAYpV9eKkwR2UYv")).build(); + assertEquals("https://api.spotify.com:443/v1/tracks", request.toString()); + assertHasParameter(request.toUrl(), "ids", "6hDH3YWFdcUNQjubYztIsG,2IA4WEsWAYpV9eKkwR2UYv"); + } + + @Test + public void shouldCreateAUrlForArtistsAlbum() { + Api api = Api.DEFAULT_API; + Request request = api.getAlbumsForArtist("4AK6F7OLvEQ5QYCBNiQWHq").build(); + assertEquals("https://api.spotify.com:443/v1/artists/4AK6F7OLvEQ5QYCBNiQWHq/albums", request.toString()); + } + + @Test + public void shouldHaveMultipleAlbumTypeParametersInArtistsAlbumUrl() { + Api api = Api.DEFAULT_API; + Request request = api.getAlbumsForArtist("4AK6F7OLvEQ5QYCBNiQWHq") + .types(AlbumType.ALBUM, AlbumType.SINGLE) + .market("SE") + .build(); + + assertEquals("https://api.spotify.com:443/v1/artists/4AK6F7OLvEQ5QYCBNiQWHq/albums", request.toString()); + assertHasParameter(request.toUrl(), "album_type", "ALBUM,SINGLE"); + assertHasParameter(request.toUrl(), "market", "SE"); + } + + @Test + public void shouldHaveSingleAlbumTypeParametersInArtistsAlbumUrl() { + Api api = Api.DEFAULT_API; + Request request = api.getAlbumsForArtist("4AK6F7OLvEQ5QYCBNiQWHq").types(AlbumType.SINGLE).build(); + assertEquals("https://api.spotify.com:443/v1/artists/4AK6F7OLvEQ5QYCBNiQWHq/albums", request.toString()); + assertHasParameter(request.toUrl(), "album_type", "SINGLE"); + } + + @Test + public void shouldFailIfAlbumTypeParametersIsInArtistsAlbumUrl() { + Api api = Api.DEFAULT_API; + Request request = api.getAlbumsForArtist("4AK6F7OLvEQ5QYCBNiQWHq").types(AlbumType.SINGLE).build(); + assertEquals("https://api.spotify.com:443/v1/artists/4AK6F7OLvEQ5QYCBNiQWHq/albums", request.toString()); + assertHasParameter(request.toUrl(), "album_type", "SINGLE"); + } + + @Test + public void shouldHaveLimitParameterInArtistsAlbumUrl() { + Api api = Api.DEFAULT_API; + Request request = api.getAlbumsForArtist("4AK6F7OLvEQ5QYCBNiQWHq").limit(2).build(); + assertEquals("https://api.spotify.com:443/v1/artists/4AK6F7OLvEQ5QYCBNiQWHq/albums", request.toString()); + assertHasParameter(request.toUrl(), "limit", "2"); + } + + @Test + public void shouldHaveOffsetParameterInArtistsAlbumUrl() { + Api api = Api.DEFAULT_API; + Request request = api.getAlbumsForArtist("4AK6F7OLvEQ5QYCBNiQWHq").offset(5).build(); + assertEquals("https://api.spotify.com:443/v1/artists/4AK6F7OLvEQ5QYCBNiQWHq/albums", request.toString()); + assertHasParameter(request.toUrl(), "offset", "5"); + } + + @Test + public void shouldHaveSeveralQueryParametersAtTheSameTimeInArtistsAlbumUrl() { + Api api = Api.DEFAULT_API; + Request request = api.getAlbumsForArtist("4AK6F7OLvEQ5QYCBNiQWHq").types(AlbumType.SINGLE).limit(2).offset(5).build(); + assertEquals("https://api.spotify.com:443/v1/artists/4AK6F7OLvEQ5QYCBNiQWHq/albums", request.toString()); + assertHasParameter(request.toUrl(), "offset", "5"); + assertHasParameter(request.toUrl(), "limit", "2"); + assertHasParameter(request.toUrl(), "album_type", "SINGLE"); + } + + @Test + public void shouldCreateAGetArtistsUrl() { + Api api = Api.DEFAULT_API; + Request request = api.getArtists("4AK6F7OLvEQ5QYCBNiQWHq", "6rEzedK7cKWjeQWdAYvWVG").build(); + assertEquals("https://api.spotify.com:443/v1/artists", request.toString()); + assertHasParameter(request.toUrl(), "ids", "4AK6F7OLvEQ5QYCBNiQWHq,6rEzedK7cKWjeQWdAYvWVG"); + } + + @Test + public void shouldCreateSearchUrl() { + Api api = Api.DEFAULT_API; + Request request = api.searchTracks("moulat swalf").build(); + assertEquals("https://api.spotify.com:443/v1/search", request.toString()); + assertHasParameter(request.toUrl(), "q", "moulat swalf"); + assertHasParameter(request.toUrl(), "type", "track"); + } + + @Test + public void shouldCreateSearchUrlForAlbum() { + Api api = Api.DEFAULT_API; + Request request = api.searchAlbums("meeep").market("from_token").build(); + assertEquals("https://api.spotify.com:443/v1/search", request.toString()); + assertHasParameter(request.toUrl(), "q", "meeep"); + assertHasParameter(request.toUrl(), "type", "album"); + assertHasParameter(request.toUrl(), "market", "from_token"); + } + + @Test + public void shouldCreateSearchUrlForArtist() { + Api api = Api.DEFAULT_API; + Request request = api.searchArtists("meeep").market("GB").build(); + assertEquals("https://api.spotify.com:443/v1/search", request.toString()); + assertHasParameter(request.toUrl(), "q", "meeep"); + assertHasParameter(request.toUrl(), "type", "artist"); + assertHasParameter(request.toUrl(), "market", "GB"); + } + + @Test + public void shouldCreateSearchUrlWithLimitParameter() { + Api api = Api.DEFAULT_API; + Request request = api.searchTracks("moulat swalf").limit(2).market("SE").build(); + assertEquals("https://api.spotify.com:443/v1/search", request.toString()); + assertHasParameter(request.toUrl(), "q", "moulat swalf"); + assertHasParameter(request.toUrl(), "limit", "2"); + assertHasParameter(request.toUrl(), "type", "track"); + assertHasParameter(request.toUrl(), "market", "SE"); + } + + @Test + public void shouldCreateSearchUrlWithOffsetParameter() { + Api api = Api.DEFAULT_API; + Request request = api.searchTracks("moulat swalf").offset(2).build(); + assertEquals("https://api.spotify.com:443/v1/search", request.toString()); + assertHasParameter(request.toUrl(), "q", "moulat swalf"); + assertHasParameter(request.toUrl(), "offset", "2"); + assertHasParameter(request.toUrl(), "type", "track"); + } + + @Test + public void shouldModifySchemeInUrl() { + Api api = Api.builder().scheme(Scheme.HTTP).build(); + Request request = api.getAlbum("5oEljuMoe9MXH6tBIPbd5e").build(); + assertEquals("http://api.spotify.com:443/v1/albums/5oEljuMoe9MXH6tBIPbd5e", request.toString()); + } + + @Test + public void shouldModifyPortInUrl() { + Api api = Api.builder().port(8080).build(); + Request request = api.getAlbum("5oEljuMoe9MXH6tBIPbd5e").build(); + assertEquals("https://api.spotify.com:8080/v1/albums/5oEljuMoe9MXH6tBIPbd5e", request.toString()); + } + + @Test + public void shouldModifyHostInUrl() { + Api api = Api.builder().host("www.wrapper.se").build(); + Request request = api.getAlbum("5oEljuMoe9MXH6tBIPbd5e").build(); + assertEquals("https://www.wrapper.se:443/v1/albums/5oEljuMoe9MXH6tBIPbd5e", request.toString()); + } + + @Test + public void shouldCreateTopTracksUrl() { + Api api = Api.DEFAULT_API; + Request request = api.getTopTracksForArtist("0LcJLqbBmaGUft1e9Mm8HV", "GB").build(); + assertEquals("https://api.spotify.com:443/v1/artists/0LcJLqbBmaGUft1e9Mm8HV/toptracks", request.toString()); + assertHasParameter(request.toUrl(), "country", "GB"); + } + + @Test + public void shouldCreateUserProfileUrl() { + Api api = Api.DEFAULT_API; + Request request = api.getUser("wizzler").build(); + assertEquals("https://api.spotify.com:443/v1/users/wizzler", request.toString()); + } + + @Test + public void shouldCreateUrlForListingAUsersPlaylists() throws Exception { + final String accessToken = "myVeryLongAccessToken"; + final Api api = Api.builder().accessToken(accessToken).build(); + + final Request request = api.getPlaylistsForUser("wizzler").build(); + + assertEquals("https://api.spotify.com:443/v1/users/wizzler/playlists", request.toString()); + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + } + + @Test + public void shouldCreateRequestForTokensUrl() { + final String clientId = "myClientId"; + final String clientSecret = "myClientSecret"; + final String redirectURI = "myRedirectUri"; + final String code = "returnedCode"; + + final Api api = Api.builder() + .clientId(clientId) + .clientSecret(clientSecret) + .redirectURI(redirectURI) + .build(); + + final Request request = api.authorizationCodeGrant(code).build(); + + assertEquals("https://accounts.spotify.com:443/api/token", request.toString()); + assertHasBodyParameter(request.toUrl(), "grant_type", "authorization_code"); + assertHasBodyParameter(request.toUrl(), "code", code); + assertHasBodyParameter(request.toUrl(), "redirect_uri", redirectURI); + + final String idSecret = clientId + ":" + clientSecret; + assertHasHeader(request.toUrl(), "Authorization", "Basic " + new String(Base64.encodeBase64(idSecret.getBytes()))); + } + + @Test + public void shouldCreateRefreshAccessTokenUrl() { + final String clientId = "myClientId"; + final String clientSecret = "myClientSecret"; + final String refreshToken = "myRefreshToken"; + + final Api api = Api + .builder() + .clientId(clientId) + .clientSecret(clientSecret) + .refreshToken(refreshToken) + .build(); + + final Request request = api.refreshAccessToken().build(); + + assertEquals("https://accounts.spotify.com:443/api/token", request.toString()); + assertHasBodyParameter(request.toUrl(), "grant_type", "refresh_token"); + assertHasBodyParameter(request.toUrl(), "refresh_token", refreshToken); + + final String idSecret = clientId + ":" + clientSecret; + assertHasHeader(request.toUrl(), "Authorization", "Basic " + new String(Base64.encodeBase64(idSecret.getBytes()))); + } + + @Test + public void shouldCreatePlaylistLookupUrl() { + final String accessToken = "myVeryLongAccessToken"; + final Api api = Api.builder().accessToken(accessToken).build(); + + final String playlistId = "3ktAYNcRHpazJ9qecm3ptn"; + final String userId = "thelinmichael"; + + final Request request = api.getPlaylist(userId, playlistId).build(); + + assertEquals("https://api.spotify.com:443/v1/users/" + userId + "/playlists/" + playlistId, request.toString()); + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + } + + @Test + public void shouldCreateCurrentUserLookupUrl() { + final String accessToken = "myVeryLongAccessToken"; + + final Api api = Api.builder().accessToken(accessToken).build(); + + final Request request = api.getMe().build(); + + assertEquals("https://api.spotify.com:443/v1/me", request.toString()); + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + } + + @Test + public void shouldCreateCreatePlaylistUrl() { + final String accessToken = "myVeryLongAccessToken"; + final Api api = Api.builder().accessToken(accessToken).build(); + + final String myUsername = "thelinmichael"; + final String title = "The greatest playlist ever"; + final boolean publicAccess = true; + + final Request request = api.createPlaylist(myUsername, title).publicAccess(publicAccess).build(); + + assertEquals("https://api.spotify.com:443/v1/users/thelinmichael/playlists", request.toString()); + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + assertHasHeader(request.toUrl(), "Content-Type", "application/json"); + assertHasJsonBody(request.toUrl(), "{\"name\":\"The greatest playlist ever\",\"public\":\"true\"}"); + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + } + + @Test + public void shouldCreateAddTrackToPlaylistUrl() { + final String accessToken = "myVeryLongAccessToken"; + final Api api = Api.builder().accessToken(accessToken).build(); + + final String myUsername = "thelinmichael"; + final String myPlaylistId = "5ieJqeLJjjI8iJWaxeBLuK"; + final List tracksToAdd = Arrays.asList("spotify:track:4BYGxv4rxSNcTgT3DsFB9o","spotify:tracks:0BG2iE6McPhmAEKIhfqy1X"); + final int insertIndex = 3; + + final Request request = api.addTracksToPlaylist(myUsername, myPlaylistId, tracksToAdd).position(insertIndex).build(); + + assertEquals("https://api.spotify.com:443/v1/users/thelinmichael/playlists/" + myPlaylistId + "/tracks", request.toString()); + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + assertHasHeader(request.toUrl(), "Content-Type", "application/json"); + assertHasJsonBody(request.toUrl(), "[\"spotify:track:4BYGxv4rxSNcTgT3DsFB9o\",\"spotify:tracks:0BG2iE6McPhmAEKIhfqy1X\"]"); + assertHasParameter(request.toUrl(), "position", String.valueOf(insertIndex)); + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + } + + @Test + public void shouldCreateChangePlaylistDetailsUrl() { + final String accessToken = "myVeryLongAccessToken"; + final Api api = Api.builder().accessToken(accessToken).build(); + + final String myUsername = "thelinmichael"; + final String myPlaylistId = "5ieJqeLJjjI8iJWaxeBLuK"; + + final boolean isPublic = false; + final String name = "Testing name change"; + + final Request request = api.changePlaylistDetails(myUsername, myPlaylistId) + .publicAccess(isPublic) + .name(name) + .build(); + + assertEquals("https://api.spotify.com:443/v1/users/thelinmichael/playlists/" + myPlaylistId, + request.toString()); + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + assertHasHeader(request.toUrl(), "Content-Type", "application/json"); + + JSONObject jsonBody = JSONObject.fromObject(request.toUrl().getJsonBody()); + assertEquals(name, jsonBody.getString("name")); + assertEquals(isPublic, jsonBody.getBoolean("public")); + + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + } + + @Test + public void shouldCreateClientCredentialsGrantUrl() { + final String clientId = "myClientId"; + final String clientSecret = "myClientSecret"; + + final Api api = Api.builder() + .clientId(clientId) + .clientSecret(clientSecret) + .build(); + + final List scopes = Arrays.asList("some-scope", "some-other-scope"); + + final Request request = api.clientCredentialsGrant().scopes(scopes).build(); + + assertEquals("https://accounts.spotify.com:443/api/token", request.toString()); + + assertHasBodyParameter(request.toUrl(), "grant_type", "client_credentials"); + assertHasBodyParameter(request.toUrl(), "scope", "some-scope some-other-scope"); + + final String idSecret = clientId + ":" + clientSecret; + assertHasHeader(request.toUrl(), "Authorization", "Basic " + new String(Base64.encodeBase64(idSecret.getBytes()))); + } + + @Test + public void shouldCreateAGetPlaylistTracksURL() { + final String accessToken = "myAccessToken"; + final String userId = "thelinmichael"; + final String playlistId = "5ieJqeLJjjI8iJWaxeBLuK"; + + final Api api = Api.builder() + .accessToken(accessToken) + .build(); + + final Request request = api + .getPlaylistTracks(userId, playlistId) + .fields("items") + .limit(20) + .offset(1) + .build(); + + assertEquals("https://api.spotify.com:443/v1/users/" + userId + "/playlists/" + playlistId + "/tracks", request.toString()); + assertHasParameter(request.toUrl(), "fields", "items"); + assertHasParameter(request.toUrl(), "limit", "20"); + assertHasParameter(request.toUrl(), "offset", "1"); + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + } + + @Test + public void shouldCreateRelatedArtistsURL() { + final Api api = Api.DEFAULT_API; + + final String artistId = "0qeei9KQnptjwb8MgkqEoy"; + + final Request request = api.getArtistRelatedArtists(artistId).build(); + + assertEquals("https://api.spotify.com:443/v1/artists/" + artistId + "/related-artists", request.toString()); + } + + @Test + public void shouldCreateAuthorizeURL() { + final String redirectURI = "http://www.michaelthelin.se/test-callback"; + final String clientId = "fcecfc79122e4cd299473677a17cbd4d"; + + final Api api = Api.builder() + .clientId(clientId) + .redirectURI(redirectURI) + .build(); + + final List scopes = Arrays.asList("user-read-private", "user-read-email"); + final String state = "someExpectedStateString"; + + String authorizeURL = api.createAuthorizeURL(scopes, state); + assertEquals("https://accounts.spotify.com:443/authorize?client_id=fcecfc79122e4cd299473677a17cbd4d&response_type=code&redirect_uri=http://www.michaelthelin.se/test-callback&scope=user-read-private%20user-read-email&state=someExpectedStateString", authorizeURL); + } + + @Test + public void shouldCreateAuthorizeUrlWithOptionalParameters() { + final String redirectURI = "http://www.michaelthelin.se/test-callback"; + final String clientId = "fcecfc79122e4cd299473677a17cbd4d"; + + final Api api = Api.builder() + .clientId(clientId) + .redirectURI(redirectURI) + .build(); + + final List scopes = Arrays.asList("user-read-private", "user-read-email"); + final String state = "someExpectedStateString"; + + String authorizeURL = api.createAuthorizeURL(scopes). + state(state). + showDialog(false). + build(). + toStringWithQueryParameters(); + + assertEquals("https://accounts.spotify.com:443/authorize?client_id=fcecfc79122e4cd299473677a17cbd4d&response_type=code&redirect_uri=http://www.michaelthelin.se/test-callback&scope=user-read-private%20user-read-email&state=someExpectedStateString&show_dialog=false", authorizeURL); + } + + @Test + public void shouldCreateGetMyTracksURL() { + final String accessToken = "myAccessToken"; + + final Api api = Api.builder() + .accessToken(accessToken) + .build(); + + final Request request = api + .getMySavedTracks() + .limit(5) + .offset(1) + .build(); + + assertEquals("https://api.spotify.com:443/v1/me/tracks", request.toString()); + assertHasParameter(request.toUrl(), "limit", "5"); + assertHasParameter(request.toUrl(), "offset", "1"); + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + } + + @Test + public void shouldCreatePutTracksURL() { + final String accessToken = "myAccessToken"; + + final Api api = Api.builder() + .accessToken(accessToken) + .build(); + + final Request request = api + .addToMySavedTracks(Arrays.asList("test", "test2")) + .build(); + + assertEquals("https://api.spotify.com:443/v1/me/tracks", request.toString()); + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + } + + @Test + public void shouldCreateRemoveTracksURL() { + final String accessToken = "myAccessToken"; + + final Api api = Api.builder() + .accessToken(accessToken) + .build(); + + final Request request = api + .removeFromMySavedTracks(Arrays.asList("test", "test2")) + .build(); + + assertEquals("https://api.spotify.com:443/v1/me/tracks", request.toString()); + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + } + + @Test + public void shouldCreateGetNewReleasesRequest() { + final String accessToken = "myAccessToken"; + + final Api api = Api.builder() + .accessToken(accessToken) + .build(); + + final Request request = api.getNewReleases().limit(4).offset(1).country("SE").build(); + + assertEquals("https://api.spotify.com:443/v1/browse/new-releases", request.toString()); + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + assertHasParameter(request.toUrl(), "limit", "4"); + assertHasParameter(request.toUrl(), "offset", "1"); + assertHasParameter(request.toUrl(), "country", "SE"); + } + + @Test + public void shouldCreateFeaturedPlaylistsRequest() { + final String accessToken = "myAccessToken"; + + final Api api = Api.builder() + .accessToken(accessToken) + .build(); + + + Calendar calendar = Calendar.getInstance(); + calendar.set(2014, 11, 22, 13, 59, 30); + Date timestamp = calendar.getTime(); + + final Request request = api + .getFeaturedPlaylists() + .country("SE") + .locale("es_MX") + .limit(5) + .offset(1) + .timestamp(timestamp) + .build(); + + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + + assertEquals("https://api.spotify.com:443/v1/browse/featured-playlists", request.toString()); + assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken); + assertHasParameter(request.toUrl(), "limit", "5"); + assertHasParameter(request.toUrl(), "offset", "1"); + assertHasParameter(request.toUrl(), "country", "SE"); + assertHasParameter(request.toUrl(), "locale", "es_MX"); + assertHasParameter(request.toUrl(), "timestamp", format.format(timestamp)); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.http.impl.conn.PoolingHttpClientConnectionManager` acquired by call to `build()` at line 560 is not released after line 574. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ApiTest.shouldCreateFeaturedPlaylistsRequest() + +### Procedure Id: +com.wrapper.spotify.ApiTest.shouldCreateFeaturedPlaylistsRequest():void.f2fa481b0ff4ae2467d2a02d9e7d28a0 + +### File: +src/test/java/com/wrapper/spotify/ApiTest.java + +### Key: +ApiTest.java|shouldCreateFeaturedPlaylistsRequest|RESOURCE_LEAK + +### Node Key: +939bacd846f19fa9053d3f2bc15017ae + +### Hash: +f3c52f314911d85a4e73917fee54ffdb + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10223/instruction.md b/inferredbugs-10223/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3aed2e83255be14cfc41c90b25f68cf459ef1b5 --- /dev/null +++ b/inferredbugs-10223/instruction.md @@ -0,0 +1,100 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ios-driver +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.uiautomation.ios.ide.pages.begin; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.StringReader; + +import org.apache.commons.io.IOUtils; +import org.json.JSONException; +import org.json.JSONObject; + +public class IDETestHelper { + + + public static void persist(File screenshot, JSONObject tree, File dest) + throws FileNotFoundException, IOException, JSONException { + System.out.println(screenshot.getAbsolutePath()); + FileWriter write = new FileWriter(dest); + IOUtils.copy(new StringReader(tree.toString(2)), new FileOutputStream(dest), "UTF-8"); + System.out.println(dest.getAbsolutePath()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileWriter` acquired to `write` by call to `new()` at line 21 is not released after line 21. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void IDETestHelper.persist(File,JSONObject,File) + +### Procedure Id: +org.uiautomation.ios.ide.pages.begin.IDETestHelper.persist(java.io.File,org.json.JSONObject,java.io..aa1900db585942e760950453fb468509 + +### File: +ide/src/test/java/org/uiautomation/ios/ide/pages/begin/IDETestHelper.java + +### Key: +IDETestHelper.java|persist|RESOURCE_LEAK + +### Node Key: +8bb6c8289be64f76292c61dfe72b9d80 + +### Hash: +07378eb4a086ba07c1218052bc678b70 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10224/instruction.md b/inferredbugs-10224/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6f8c8f0fad72b8e6d5f1d756720ee8a6f1a5bab7 --- /dev/null +++ b/inferredbugs-10224/instruction.md @@ -0,0 +1,372 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ios-driver +**Bug ID:** 17 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2012 ios-driver committers. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package org.uiautomation.ios.server; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.openqa.selenium.TimeoutException; +import org.openqa.selenium.WebDriverException; +import org.uiautomation.ios.mobileSafari.EventListener; +import org.uiautomation.ios.mobileSafari.NodeId; +import org.uiautomation.ios.mobileSafari.events.ChildNodeRemoved; +import org.uiautomation.ios.mobileSafari.events.Event; +import org.uiautomation.ios.mobileSafari.events.EventHistory; +import org.uiautomation.ios.mobileSafari.events.inserted.ChildIframeInserted; +import org.uiautomation.ios.webInspector.DOM.DOM; +import org.uiautomation.ios.webInspector.DOM.RemoteExceptionException; +import org.uiautomation.ios.webInspector.DOM.RemoteWebElement; + +import java.util.List; +import java.util.logging.Logger; + + +// TODO freynaud revisit pageLoad, reset, setFrame and newContext and expose only 1 thing. +public class DOMContext implements EventListener { + + private static final Logger log = Logger.getLogger(DOMContext.class.getName()); + + private volatile boolean pageLoaded = false; + + private volatile boolean isReady = true; + private NodeId parent; + + private final ServerSideSession session; + + private RemoteWebElement window; + private RemoteWebElement document; + private RemoteWebElement iframe; + + private boolean isOnMainFrame = true; + private RemoteWebElement mainDocument; + private RemoteWebElement mainWindow; + + private final EventHistory eventHistory = new EventHistory(); + + public RemoteWebElement getDocument() { + int cpt = 0; + while (!isReady) { + cpt++; + if (cpt > 20) { + isReady = true; + throw new TimeoutException("doc not ready."); + } + try { + // System.err.println("cannot get document. Something is happening."); + Thread.sleep(250); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + return document; + } + + public RemoteWebElement getWindow() { + return window; + } + + public void newContext() { + window = null; + document = null; + iframe = null; + mainDocument = null; + } + + public String toString() { + StringBuilder b = new StringBuilder(); + b.append("window " + window); + b.append("document " + document); + b.append("iframe " + iframe); + b.append("mainDocument " + mainDocument); + return b.toString(); + } + + // TODO freynaud reset() != pageLoad + public void reset() { + RemoteWebElement newDocument = null; + RemoteWebElement newWindow = null; + + // check is what changed was the context for the current frame. + if (iframe != null) { + try { + newDocument = iframe.getContentDocument(); + newWindow = iframe.getContentWindow(); + setCurrentFrame(iframe, newDocument, newWindow); + return; + } catch (Exception e) { + e.printStackTrace(); + } + } + // couldn't update the current frame. Reseting everything. + newContext(); + } + + // TODO freynaud. Cleanup. A reference to the main document of the page needs + // to be kept. + // calling getDocument again to have the document after siwtching to an iframe + // breaks the nodeId reference. + public void setCurrentFrame(RemoteWebElement iframe, RemoteWebElement document, + RemoteWebElement window) { + this.iframe = iframe; + this.document = document; + this.window = window; + + if (iframe != null) { + isOnMainFrame = false; + } else { + isOnMainFrame = true; + } + + // switchToDefaultContent. revert to main document if it was set. + if (iframe == null && document == null) { + this.document = mainDocument; + this.window = mainWindow; + } + + // setting the main document for the first time + if (iframe == null && document != null) { + mainDocument = document; + mainWindow = window; + } + + } + + public boolean isOnMainFrame() { + return isOnMainFrame; + } + + public RemoteWebElement getCurrentFrame() { + return iframe; + } + + @Override + public void onPageLoad() { + System.err.println("new page loaded"); + pageLoaded = true; + reset(); + try { + Thread.sleep(5000); + System.out.println( + "on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument()) + .optJSONObject("root").optString("documentURL")); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void waitForPageToLoad(long timeout) { + long start = System.currentTimeMillis(); + long deadLine = start + timeout; + while (!pageLoaded) { + if (System.currentTimeMillis() > deadLine) { + throw new TimeoutException("failed to load the page after " + timeout + " ms."); + } + try { + Thread.sleep(50); + } catch (InterruptedException e) { + // ignore + } + } + + pageLoaded = false; + waitForDocumentReady(deadLine); + + return; + } + + public boolean isLoading() { + return !isReady(); + } + + public String getDocumentReadyState() { + String state = null; + try { + state = (String) session.getWebInspector().executeScript( + "var state = document.readyState; return state", + new JSONArray()); + } catch (RemoteExceptionException e) { + // Arguments should belong to the same JavaScript world as the target object. + System.err.println("error, reseting because " + e.getMessage()); + reset(); + return "unknown"; + } + return state; ///*"interactive".equals(state) + /*String state = null; + try { + state = (String)session.getWebInspector().evaluate("document.readyState;"); + } catch (Exception e) { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } + System.out.println("state:"+state); + return state; */ + } + + private boolean isReady() { + return "complete".equals(getDocumentReadyState()); + } + + private void waitForDocumentReady(long deadLine) { + while (!isReady()) { + if (System.currentTimeMillis() > deadLine) { + throw new TimeoutException("failed to load the page"); + } + } + } + + public DOMContext(ServerSideSession session) { + this.session = session; + } + + @Override + public synchronized void domHasChanged(Event e) { + try { + + if (e instanceof ChildNodeRemoved) { + ChildNodeRemoved removed = (ChildNodeRemoved) e; + if (iframe != null ? removed.getNode().equals(iframe.getNodeId()) : false) { + isReady = false; + parent = removed.getParent(); + log.fine("current frame " + iframe.getNodeId() + " is gone.Parent = " + parent); + List newOnes = eventHistory.getInsertedFrames(parent); + if (newOnes.size() == 0) { + return; + } else if (newOnes.size() == 1) { + Event newFrame = newOnes.get(0); + assignNewFrameFromEvent((ChildIframeInserted) newFrame); + eventHistory.removeEvent(newFrame); + } else { + log.warning( + "there should be only 1 newly created frame with parent =" + parent + ". Found " + + newOnes.size()); + } + } + return; + } + + if (e instanceof ChildIframeInserted) { + ChildIframeInserted newFrame = (ChildIframeInserted) e; + // are we waiting for something ? + if (isReady) { + eventHistory.add(newFrame); + return; + } else { + // is it the new node we're looking for ? + if (parent.equals(newFrame.getParent())) { + log.fine("the new node is here :" + newFrame.getNode()); + assignNewFrameFromEvent(newFrame); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + private void assignNewFrameFromEvent(ChildIframeInserted newFrameEvent) throws Exception { + RemoteWebElement frame = new RemoteWebElement(newFrameEvent.getNode(), session); + RemoteWebElement document = new RemoteWebElement(newFrameEvent.getContentDocument(), session); + RemoteWebElement window = frame.getContentWindow(); + setCurrentFrame(frame, document, window); + isReady = true; + } + + @Override + public void frameDied(JSONObject message) { + // if that's the one we're working on, deselect it. + if (iframe != null) { + if (!iframe.exists()) { + log.fine( + "the current frame is dead. Will need to switch to default content or another frame before being able to do anything."); + isReady = true; + } + } + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.uiautomation.ios.server.DOMContext.onPageLoad` indirectly reads without synchronization from `mobileSafari.DebugProtocol.org.uiautomation.ios.mobileSafari.DebugProtocol.socket`. Potentially races with write in method `DOMContext.domHasChanged(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DOMContext.onPageLoad() + +### Procedure Id: +org.uiautomation.ios.server.DOMContext.onPageLoad():void.4d1fabeb3c630c0928aa89b385ba220d + +### File: +server/src/main/java/org/uiautomation/ios/server/DOMContext.java + +### Key: +DOMContext.java|onPageLoad|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +1177e3fa6e8a9dd0a805774111291b0d + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1023/instruction.md b/inferredbugs-1023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9a1412d6421275ec63fec09ca2f1ed166d3829e3 --- /dev/null +++ b/inferredbugs-1023/instruction.md @@ -0,0 +1,86 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** PKHeX-Plugins +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.IO; +using System.Net; + +namespace PKHeX.Core.AutoMod +{ + public static class NetUtil + { + public static string GetPageText(string url) + { + var request = (HttpWebRequest)WebRequest.Create(url); + var response = (HttpWebResponse)request.GetResponse(); + return new StreamReader(response.GetResponseStream()).ReadToEnd(); + } + + public static string DownloadString(string address) + { + var request = (HttpWebRequest)WebRequest.Create(address); + request.Method = "GET"; + request.UserAgent = "PKHeX-Auto-Legality-Mod"; + request.Accept = "application/json"; + WebResponse response = request.GetResponse(); //Error Here + Stream dataStream = response.GetResponseStream(); + StreamReader reader = new StreamReader(dataStream); + return reader.ReadToEnd(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of System.IO.StreamReader::.ctor() at Line 12) of type System.IO.StreamReader in method "String NetUtil.GetPageText(String)". + +### Severity: +ERROR + +### Procedure: +String NetUtil.GetPageText(String) + +### File: +PKHeX.Core.AutoMod/Enhancements/NetUtil.cs + +### Key: +NetUtil.cs|GetPageText|DOTNET_RESOURCE_LEAK + +### Hash: +5c5f933a6f2bccd858859d7dc78756fc + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1024/instruction.md b/inferredbugs-1024/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..abd1995182c9ab821ef499cee3845d9df762492a --- /dev/null +++ b/inferredbugs-1024/instruction.md @@ -0,0 +1,86 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** PKHeX-Plugins +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.IO; +using System.Net; + +namespace PKHeX.Core.AutoMod +{ + public static class NetUtil + { + public static string GetPageText(string url) + { + var request = (HttpWebRequest)WebRequest.Create(url); + var response = (HttpWebResponse)request.GetResponse(); + return new StreamReader(response.GetResponseStream()).ReadToEnd(); + } + + public static string DownloadString(string address) + { + var request = (HttpWebRequest)WebRequest.Create(address); + request.Method = "GET"; + request.UserAgent = "PKHeX-Auto-Legality-Mod"; + request.Accept = "application/json"; + WebResponse response = request.GetResponse(); //Error Here + Stream dataStream = response.GetResponseStream(); + StreamReader reader = new StreamReader(dataStream); + return reader.ReadToEnd(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource reader of type System.IO.StreamReader in method "String NetUtil.DownloadString(String)". + +### Severity: +ERROR + +### Procedure: +String NetUtil.DownloadString(String) + +### File: +PKHeX.Core.AutoMod/Enhancements/NetUtil.cs + +### Key: +NetUtil.cs|DownloadString|DOTNET_RESOURCE_LEAK + +### Hash: +9eea0a9b92991d79b3820113ccc40696 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10240/instruction.md b/inferredbugs-10240/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6b979d0b94eea5151c7d3d88c7e84955f01bbe5d --- /dev/null +++ b/inferredbugs-10240/instruction.md @@ -0,0 +1,262 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helper +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * This file is part of helper, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.helper.plugin; + +import com.google.common.base.Preconditions; + +import me.lucko.helper.Scheduler; +import me.lucko.helper.config.Configs; +import me.lucko.helper.internal.LoaderUtils; +import me.lucko.helper.maven.LibraryLoader; +import me.lucko.helper.terminable.Terminable; +import me.lucko.helper.terminable.composite.CompositeTerminable; +import me.lucko.helper.terminable.registry.TerminableRegistry; +import me.lucko.helper.utils.CommandMapUtil; + +import org.bukkit.command.CommandExecutor; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.event.Listener; +import org.bukkit.plugin.ServicePriority; +import org.bukkit.plugin.java.JavaPlugin; + +import ninja.leaping.configurate.ConfigurationNode; + +import java.io.File; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * An "extended" JavaPlugin class. + */ +public class ExtendedJavaPlugin extends JavaPlugin implements HelperPlugin { + + // the backing terminable registry + private TerminableRegistry terminableRegistry; + + // Used by subclasses to perform logic for plugin load/enable/disable. + protected void load() {} + protected void enable() {} + protected void disable() {} + + @Override + public final void onLoad() { + LoaderUtils.getPlugin(); // cache the loader plugin & run initial setup + terminableRegistry = TerminableRegistry.create(); + + LibraryLoader.loadAll(getClass()); + + // call subclass + load(); + } + + @Override + public final void onEnable() { + // schedule cleanup of the registry + Scheduler.runTaskRepeatingAsync(terminableRegistry::cleanup, 600L, 600L).bindWith(terminableRegistry); + + // call subclass + enable(); + } + + @Override + public final void onDisable() { + + // call subclass + disable(); + + // terminate the registry + terminableRegistry.terminate(); + } + + @Nonnull + @Override + public T bind(@Nonnull T terminable) { + return terminableRegistry.bind(terminable); + } + + @Nonnull + @Override + public T bindRunnable(@Nonnull T runnable) { + return terminableRegistry.bindRunnable(runnable); + } + + @Nonnull + @Override + public T bindComposite(@Nonnull T terminable) { + return terminableRegistry.bindComposite(terminable); + } + + @Nonnull + @Override + public T registerListener(@Nonnull T listener) { + Preconditions.checkNotNull(listener, "listener"); + getServer().getPluginManager().registerEvents(listener, this); + return listener; + } + + @Nonnull + @Override + public T registerCommand(@Nonnull T command, @Nonnull String... aliases) { + return CommandMapUtil.registerCommand(this, command, aliases); + } + + @Nullable + @Override + public T getService(@Nonnull Class service) { + return getServer().getServicesManager().load(service); + } + + @Nonnull + @Override + public T provideService(@Nonnull Class clazz, @Nonnull T instance, @Nonnull ServicePriority priority) { + getServer().getServicesManager().register(clazz, instance, this, priority); + return instance; + } + + @Nonnull + @Override + public T provideService(@Nonnull Class clazz, @Nonnull T instance) { + Preconditions.checkNotNull(clazz, "clazz"); + Preconditions.checkNotNull(instance, "instance"); + return provideService(clazz, instance, ServicePriority.Normal); + } + + @SuppressWarnings("unchecked") + @Nullable + @Override + public T getPlugin(@Nonnull String name, @Nonnull Class pluginClass) { + Preconditions.checkNotNull(name, "name"); + Preconditions.checkNotNull(pluginClass, "pluginClass"); + return (T) getServer().getPluginManager().getPlugin(name); + } + + @Nonnull + @Override + public File getBundledFile(@Nonnull String name) { + Preconditions.checkNotNull(name, "name"); + getDataFolder().mkdirs(); + File file = new File(getDataFolder(), name); + if (!file.exists()) { + saveResource(name, false); + } + return file; + } + + @Nonnull + @Override + public YamlConfiguration loadConfig(@Nonnull String file) { + Preconditions.checkNotNull(file, "file"); + return YamlConfiguration.loadConfiguration(getBundledFile(file)); + } + + @Nonnull + @Override + public ConfigurationNode loadConfigNode(@Nonnull String file) { + Preconditions.checkNotNull(file, "file"); + return Configs.yamlLoad(getBundledFile(file)); + } + + @Nonnull + @Override + public ClassLoader getClassloader() { + return super.getClassLoader(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `me.lucko.helper.Scheduler$HelperTask` acquired by call to `runTaskRepeatingAsync(...)` at line 79 is not released after line 79. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExtendedJavaPlugin.onEnable() + +### Procedure Id: +me.lucko.helper.plugin.ExtendedJavaPlugin.onEnable():void.6c4e05f3837740a3ab5d796fd90dfeca + +### File: +helper/src/main/java/me/lucko/helper/plugin/ExtendedJavaPlugin.java + +### Key: +ExtendedJavaPlugin.java|onEnable|RESOURCE_LEAK + +### Node Key: +5501c1a00b003765b925f59b37017f3c + +### Hash: +468aad4fc465fbaa0f456cf4daa1fbcd + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10241/instruction.md b/inferredbugs-10241/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c1ad15330381bc4f417c566c80d9f83371b2cc5b --- /dev/null +++ b/inferredbugs-10241/instruction.md @@ -0,0 +1,214 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helper +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * This file is part of helper, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.helper.serialize; + +import com.google.common.base.Preconditions; +import com.google.gson.JsonElement; +import com.google.gson.JsonPrimitive; + +import org.bukkit.Bukkit; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.bukkit.util.io.BukkitObjectOutputStream; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +/** + * Utility methods for converting ItemStacks and Inventories to and from JSON. + */ +public final class Serializers { + + public static JsonPrimitive serializeItemstack(ItemStack item) { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + try (BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream)) { + dataOutput.writeObject(item); + return new JsonPrimitive(Base64Coder.encodeLines(outputStream.toByteArray())); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static ItemStack deserializeItemstack(JsonElement data) { + Preconditions.checkArgument(data.isJsonPrimitive()); + try (ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data.getAsString()))) { + try (BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream)) { + return (ItemStack) dataInput.readObject(); + } + } catch (ClassNotFoundException | IOException e) { + throw new RuntimeException(e); + } + } + + public static JsonPrimitive serializeItemstacks(ItemStack[] items) { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + try (BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream)) { + dataOutput.writeInt(items.length); + + for (ItemStack item : items) { + dataOutput.writeObject(item); + } + + return new JsonPrimitive(Base64Coder.encodeLines(outputStream.toByteArray())); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static JsonPrimitive serializeInventory(Inventory inventory) { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + try (BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream)) { + dataOutput.writeInt(inventory.getSize()); + + for (int i = 0; i < inventory.getSize(); i++) { + dataOutput.writeObject(inventory.getItem(i)); + } + + return new JsonPrimitive(Base64Coder.encodeLines(outputStream.toByteArray())); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static ItemStack[] deserializeItemstacks(JsonElement data) { + Preconditions.checkArgument(data.isJsonPrimitive()); + try (ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data.getAsString()))) { + try (BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream)) { + ItemStack[] items = new ItemStack[dataInput.readInt()]; + + for (int i = 0; i < items.length; i++) { + items[i] = (ItemStack) dataInput.readObject(); + } + + return items; + } + } catch (ClassNotFoundException | IOException e) { + throw new RuntimeException(e); + } + } + + public static Inventory deserializeInventory(JsonElement data, String title) { + Preconditions.checkArgument(data.isJsonPrimitive()); + try (ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data.getAsString()))) { + try (BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream)) { + Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt(), title); + + for (int i = 0; i < inventory.getSize(); i++) { + inventory.setItem(i, (ItemStack) dataInput.readObject()); + } + + return inventory; + } + } catch (ClassNotFoundException | IOException e) { + throw new RuntimeException(e); + } + } + + private Serializers() { + throw new UnsupportedOperationException("This class cannot be instantiated"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.bukkit.util.io.BukkitObjectInputStream` acquired to `dataInput` by call to `new()` at line 122 is not released after line 130. +**Note**: potential exception at line 123 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Inventory Serializers.deserializeInventory(JsonElement,String) + +### Procedure Id: +me.lucko.helper.serialize.Serializers.deserializeInventory(com.google.gson.JsonElement,java.lang.Str.f498a5cefba24008526fc308a0aaab34 + +### File: +helper/src/main/java/me/lucko/helper/serialize/Serializers.java + +### Key: +Serializers.java|deserializeInventory|RESOURCE_LEAK + +### Node Key: +8df5c427b4dc1c9b8027fae958400e1e + +### Hash: +b2f96da77bc75b767eee40d67e68f85f + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10246/instruction.md b/inferredbugs-10246/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c1b418c4393d73a2ae05dd91f9b567dcac711daf --- /dev/null +++ b/inferredbugs-10246/instruction.md @@ -0,0 +1,197 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** motan +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2009-2016 Weibo, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.weibo.api.motan.config.handler; + +import com.weibo.api.motan.cluster.Cluster; +import com.weibo.api.motan.cluster.support.ClusterSupport; +import com.weibo.api.motan.common.MotanConstants; +import com.weibo.api.motan.common.URLParamType; +import com.weibo.api.motan.core.extension.ExtensionLoader; +import com.weibo.api.motan.core.extension.SpiMeta; +import com.weibo.api.motan.protocol.support.ProtocolFilterDecorator; +import com.weibo.api.motan.proxy.ProxyFactory; +import com.weibo.api.motan.proxy.RefererInvocationHandler; +import com.weibo.api.motan.registry.Registry; +import com.weibo.api.motan.registry.RegistryFactory; +import com.weibo.api.motan.rpc.*; +import com.weibo.api.motan.util.LoggerUtil; +import com.weibo.api.motan.util.StringTools; + +import java.util.Collection; +import java.util.List; + + +/** + * + * Handle refUrl to get referers, assemble to a cluster, create a proxy + * + * @author fishermen + * @version V1.0 created at: 2013-5-31 + */ + +@SpiMeta(name = MotanConstants.DEFAULT_VALUE) +public class SimpleConfigHandler implements ConfigHandler { + + @Override + public ClusterSupport buildClusterSupport(Class interfaceClass, List registryUrls) { + ClusterSupport clusterSupport = new ClusterSupport(interfaceClass, registryUrls); + clusterSupport.init(); + + return clusterSupport; + } + + @Override + public T refer(Class interfaceClass, List> clusters, String proxyType) { + ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension(proxyType); + return proxyFactory.getProxy(interfaceClass, new RefererInvocationHandler(interfaceClass, clusters)); + } + + @Override + public Exporter export(Class interfaceClass, T ref, List registryUrls) { + + String serviceStr = StringTools.urlDecode(registryUrls.get(0).getParameter(URLParamType.embed.getName())); + URL serviceUrl = URL.valueOf(serviceStr); + + // export service + // 利用protocol decorator来增加filter特性 + String protocolName = serviceUrl.getParameter(URLParamType.protocol.getName(), URLParamType.protocol.getValue()); + Protocol protocol = new ProtocolFilterDecorator(ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(protocolName)); + Provider provider = new DefaultProvider(ref, serviceUrl, interfaceClass); + Exporter exporter = protocol.export(provider, serviceUrl); + + // register service + register(registryUrls, serviceUrl); + + return exporter; + } + + @Override + public void unexport(List> exporters, Collection registryUrls) { + try { + unRegister(registryUrls); + } catch (Exception e1) { + LoggerUtil.warn("Exception when unregister urls:" + registryUrls); + } + try { + for (Exporter exporter : exporters) { + exporter.unexport(); + } + } catch (Exception e) { + LoggerUtil.warn("Exception when unexport exporters:" + exporters); + } + } + + private void register(List registryUrls, URL serviceUrl) { + for (URL url : registryUrls) { + // 根据check参数的设置,register失败可能会抛异常,上层应该知晓 + RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getExtension(url.getProtocol()); + Registry registry = registryFactory.getRegistry(url); + registry.register(serviceUrl); + } + } + + private void unRegister(Collection registryUrls) { + for (URL url : registryUrls) { + // 不管check的设置如何,做完所有unregistry,做好清理工作 + try { + String serviceStr = StringTools.urlDecode(url.getParameter(URLParamType.embed.getName())); + URL serviceUrl = URL.valueOf(serviceStr); + + RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getExtension(url.getProtocol()); + Registry registry = registryFactory.getRegistry(url); + registry.unregister(serviceUrl); + } catch (Exception e) { + LoggerUtil.warn(String.format("unregister url false:%s", url), e); + } + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `registryFactory` last assigned on line 101 could be null and is dereferenced at line 102. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SimpleConfigHandler.register(List,URL) + +### Procedure Id: +com.weibo.api.motan.config.handler.SimpleConfigHandler.register(java.util.List,com.weibo.api.motan.r.3ff1c2e7ea3a6d612815a8f4cb390b76 + +### File: +motan-core/src/main/java/com/weibo/api/motan/config/handler/SimpleConfigHandler.java + +### Key: +SimpleConfigHandler.java|register|NULL_DEREFERENCE + +### Node Key: +0a853e99fcfdcdf63138383f6a919826 + +### Hash: +4f8277da41337f87361e9425d31366e4 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10247/instruction.md b/inferredbugs-10247/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..03d8b22b8ba62706236c6ab64b19427c3b92e337 --- /dev/null +++ b/inferredbugs-10247/instruction.md @@ -0,0 +1,198 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nlp-lang +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nlpcn.commons.lang.occurrence; + +import org.nlpcn.commons.lang.util.MapCount; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.*; + +/** + * 词语共现计算工具,愚人节快乐 + * Created by ansj on 4/1/14. + */ +public class Occurrence { + + private int seqId = 0; + + private Map word2Mc = new HashMap(); + + private Map idWordMap = new HashMap(); + + private MapCount ww2Mc = new MapCount(); + + private static final String CONN = "\u0000"; + + public void add(List words) { + Count count = null; + for (Element word : words) { + if ((count = word2Mc.get(word.getName())) != null) { + count.upCount(); + } else { + count = new Count(word.getNature()); + word2Mc.put(word.getName(), count); + idWordMap.put(count.id, word.getName()); + } + + } + + Element e1 = null; + Element e2 = null; + Count count1 = null; + Count count2 = null; + for (int i = 0; i < words.size() - 1; i++) { + e1 = words.get(i); + count1 = word2Mc.get(e1.getName()); + for (int j = i + 1; j < words.size(); j++) { + e2 = words.get(j); + count2 = word2Mc.get(e2.getName()); + if (count1.id == count2.id) { + continue; + } + + if (count1.id < count2.id) { + ww2Mc.add(e1.getName() + CONN + e2.getName()); + } else { + ww2Mc.add(e2.getName() + CONN + e2.getName()); + } + count1.upRelation(count2.id); + count2.upRelation(count1.id); + } + } + } + + /** + * 保存模型 + */ + public void saveModel(String filePath) throws IOException { + BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath))) ; + writeMap(bw,idWordMap) ; + writeMap(bw,word2Mc) ; + writeMap(bw,ww2Mc.get()) ; + + } + + private void writeMap(BufferedWriter bw, Map map) throws IOException { + bw.write(word2Mc.size()); + bw.newLine(); + for(Map.Entry entry : word2Mc.entrySet()){ + bw.write(entry.getKey()+"\t"+entry.getValue()); + bw.newLine(); + } + } + + + /** + * 读取模型 + */ + public void loadModel(String filePath) { + + } + + class Count { + int id = 0; + int count = 1; //这个词 + int relationCount; //这个词和其他词共同出现多少次 + String nature; + + Set relationSet = new HashSet(); + + public Count(String nature) { + this.nature = nature; + seqId++; + this.id = seqId; + } + + + public void upCount() { + this.count++; + } + + public void upRelation(int rId) { + this.relationCount++; + this.relationSet.add(rId); + } + + + @Override + public String toString() { + return this.id + "\t" + this.count + "\t" + this.relationCount; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.BufferedWriter` acquired to `bw` by call to `new()` at line 69 is not released after line 72. +**Note**: potential exception at line 72 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Occurrence.saveModel(String) + +### Procedure Id: +org.nlpcn.commons.lang.occurrence.Occurrence.saveModel(java.lang.String):void.f688111cf23dbaf64469d68526126a91 + +### File: +src/main/java/org/nlpcn/commons/lang/occurrence/Occurrence.java + +### Key: +Occurrence.java|saveModel|RESOURCE_LEAK + +### Node Key: +4ccf2cdec4d9aa1f5a688d2290975408 + +### Hash: +686aa2d7f927858a858a130c5221f378 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10248/instruction.md b/inferredbugs-10248/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef56f4573c1a59dd59ee0d43812f4d15b1ebdf47 --- /dev/null +++ b/inferredbugs-10248/instruction.md @@ -0,0 +1,324 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nlp-lang +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nlpcn.commons.lang.util; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +public class ObjConver { + + public static final String DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + + public static Double getDouble(String value) { + return castToDouble(value); + } + + public static Double getDoubleValue(String value) { + if (StringUtil.isBlank(value)) { + return 0D; + } + return castToDouble(value); + } + + public static Float getFloat(String value) { + if (StringUtil.isBlank(value)) { + return null; + } + return castToFloat(value); + } + + public static Float getFloatValue(String value) { + return castToFloat(value).floatValue(); + } + + public static Integer getInteger(String value) { + return castToInt(value); + } + + public static int getIntValue(String value) { + if (StringUtil.isBlank(value)) { + return 0; + } + return castToInt(value); + } + + public static Date getDate(String value) { + if (StringUtil.isBlank(value)) { + return null; + } + return castToDate(value); + } + + public static Long getLong(String value) { + return castToLong(value); + } + + public static long getLongValue(String value) { + if (StringUtil.isBlank(value)) { + return 0L; + } + return castToLong(value); + } + + public static Boolean getBoolean(String value) { + return castToBoolean(value); + } + + public static boolean getBooleanValue(String value) { + if (StringUtil.isBlank(value)) { + return false; + } + return castToBoolean(value); + + } + + public static final Float castToFloat(Object value) { + if (value == null) { + return null; + } + + if (value instanceof Number) { + return ((Number) value).floatValue(); + } + + if (value instanceof String) { + String strVal = value.toString(); + if (strVal.length() == 0) { + return null; + } + + return Float.parseFloat(strVal); + } + + throw new ClassCastException("can not cast to float, value : " + value); + } + + public static final Double castToDouble(Object value) { + if (value == null) { + return null; + } + if (value instanceof Number) { + return ((Number) value).doubleValue(); + } else if (value instanceof String) { + String strVal = value.toString(); + if (strVal.length() == 0) { + return null; + } + return Double.parseDouble(strVal); + } + throw new RuntimeException("can not cast to double, value : " + value); + } + + public static final Date castToDate(Object value) { + if (value == null) { + return null; + } + long longValue = -1; + + if (value instanceof Number) { + longValue = ((Number) value).longValue(); + } else if (value instanceof String) { + String strVal = (String) value; + + if (strVal.indexOf('-') != -1) { + String format = null; + if (strVal.length() == DEFFAULT_DATE_FORMAT.length()) { + format = DEFFAULT_DATE_FORMAT; + } else if (strVal.length() == 10) { + format = "yyyy-MM-dd"; + } else if (strVal.length() == "yyyy-MM-dd HH".length()) { + format = "yyyy-MM-dd HH"; + } else if (strVal.length() == "yyyy-MM-dd HH:mm".length()) { + format = "yyyy-MM-dd HH:mm"; + } else if (strVal.length() == "yyyy-MM-dd HH:mm:ss".length()) { + format = "yyyy-MM-dd HH:mm:ss"; + } else if (strVal.length() == "yyyy-MM-dd HH:mm:SSS".length()) { + format = "yyyy-MM-dd HH:mm:ss.SSS"; + } else { + return null; + } + + SimpleDateFormat dateFormat = new SimpleDateFormat(format); + try { + return dateFormat.parse(strVal); + } catch (ParseException e) { + throw new RuntimeException("can not cast to Date, value : " + strVal); + } + } + + if (strVal.length() == 0) { + return null; + } + + longValue = Long.parseLong(strVal); + } + + if (longValue < 0) { + throw new ClassCastException("can not cast to Date, value : " + value); + } + + return new Date(longValue); + } + + public static final Long castToLong(Object value) { + if (value == null) { + return null; + } + + if (value instanceof Number) { + return ((Number) value).longValue(); + } + + if (value instanceof String) { + String strVal = (String) value; + if (strVal.length() == 0) { + return null; + } + + try { + return Long.parseLong(strVal); + } catch (NumberFormatException ex) { + } + + Date date = castToDate(strVal); + + if (date != null) { + return date.getTime(); + } + } + + throw new ClassCastException("can not cast to long, value : " + value); + } + + public static final Integer castToInt(Object value) { + if (value == null) { + return null; + } + + if (value instanceof Integer) { + return (Integer) value; + } + + if (value instanceof Number) { + return ((Number) value).intValue(); + } + + if (value instanceof String) { + String strVal = (String) value; + if (strVal.length() == 0) { + return null; + } + + return Integer.parseInt(strVal); + } + + throw new ClassCastException("can not cast to int, value : " + value); + } + + public static final Boolean castToBoolean(Object value) { + if (value == null) { + return null; + } + + if (value instanceof Boolean) { + return (Boolean) value; + } + + if (value instanceof Number) { + return ((Number) value).intValue() == 1; + } + + if (value instanceof String) { + String str = (String) value; + if (str.length() == 0) { + return null; + } + + if ("true".equalsIgnoreCase(str)) { + return Boolean.TRUE; + } + if ("false".equalsIgnoreCase(str)) { + return Boolean.FALSE; + } + + if ("1".equalsIgnoreCase(str)) { + return Boolean.TRUE; + } + } + + throw new ClassCastException("can not cast to int, value : " + value); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `castToInt(value)` could be null and is dereferenced at line 41. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int ObjConver.getIntValue(String) + +### Procedure Id: +org.nlpcn.commons.lang.util.ObjConver.getIntValue(java.lang.String):int.77309a7d7c0ebfe74ec9fe0c68c88e8e + +### File: +src/main/java/org/nlpcn/commons/lang/util/ObjConver.java + +### Key: +ObjConver.java|getIntValue|NULL_DEREFERENCE + +### Node Key: +3534744d3537de8ddf14c788351b1bdd + +### Hash: +2aa2690306e09d931cef37194d62a71f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10276/instruction.md b/inferredbugs-10276/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6261321293486c73d212c88f9061d8846228f098 --- /dev/null +++ b/inferredbugs-10276/instruction.md @@ -0,0 +1,320 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** cloudsim-plus +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * CloudSim Plus: A modern, highly-extensible and easier-to-use Framework for + * Modeling and Simulation of Cloud Computing Infrastructures and Services. + * http://cloudsimplus.org + * + * Copyright (C) 2015-2018 Universidade da Beira Interior (UBI, Portugal) and + * the Instituto Federal de Educação Ciência e Tecnologia do Tocantins (IFTO, Brazil). + * + * This file is part of CloudSim Plus. + * + * CloudSim Plus 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 of the License, or + * (at your option) any later version. + * + * CloudSim Plus 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 CloudSim Plus. If not, see . + */ +package org.cloudsimplus.examples; + +import org.cloudbus.cloudsim.allocationpolicies.VmAllocationPolicySimple; +import org.cloudbus.cloudsim.brokers.DatacenterBroker; +import org.cloudbus.cloudsim.brokers.DatacenterBrokerSimple; +import org.cloudbus.cloudsim.cloudlets.Cloudlet; +import org.cloudbus.cloudsim.cloudlets.CloudletSimple; +import org.cloudbus.cloudsim.core.CloudSim; +import org.cloudbus.cloudsim.datacenters.Datacenter; +import org.cloudbus.cloudsim.datacenters.DatacenterSimple; +import org.cloudbus.cloudsim.hosts.Host; +import org.cloudbus.cloudsim.hosts.HostSimple; +import org.cloudbus.cloudsim.provisioners.PeProvisionerSimple; +import org.cloudbus.cloudsim.provisioners.ResourceProvisioner; +import org.cloudbus.cloudsim.provisioners.ResourceProvisionerSimple; +import org.cloudbus.cloudsim.resources.Pe; +import org.cloudbus.cloudsim.resources.PeSimple; +import org.cloudbus.cloudsim.schedulers.cloudlet.CloudletSchedulerTimeShared; +import org.cloudbus.cloudsim.schedulers.vm.VmScheduler; +import org.cloudbus.cloudsim.schedulers.vm.VmSchedulerTimeShared; +import org.cloudbus.cloudsim.utilizationmodels.UtilizationModel; +import org.cloudbus.cloudsim.utilizationmodels.UtilizationModelDynamic; +import org.cloudbus.cloudsim.utilizationmodels.UtilizationModelFull; +import org.cloudbus.cloudsim.vms.Vm; +import org.cloudbus.cloudsim.vms.VmSimple; +import org.cloudsimplus.builders.tables.CloudletsTableBuilder; +import org.cloudsimplus.listeners.EventListener; +import org.cloudsimplus.listeners.VmHostEventInfo; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; + +/** + * Shows how to destroy an overloaded VM during simulation runtime, + * after its CPU usage reaches a defined threshold. + * + *

The example uses the {@link UtilizationModelDynamic} to + * increase VM CPU usage over time (in seconds). + * This {@link UtilizationModelDynamic} relies on a {@link Function} + * to increase resource usage. Such a Function is defined using a Lambda Expression.

+ * + *

It shows Host CPU utilization every second, so that when the overloaded VM + * is destroyed, we can check the Host CPU utilization reduces.

+ * + *

Lambda Expressions and Functional Interfaces are Java 8 features. + * If you don't know what these features are, I suggest checking out this + * tutorial

+ * + * @author Manoel Campos da Silva Filho + * @since CloudSim Plus 1.3.0 + */ +public class VmDestructionExample { + /** + * Defines, between other things, the time intervals + * to update the processing of simulation events. + * This way, simulation clock increases according to this time. + * Since a {@link UtilizationModelDynamic} is being used to define CPU usage of VMs, + * the utilization is updated at this time interval. + * + * Setting the Datacenter scheduling interval is required to allow + * the CPU utilization to increase along the simulation execution. + * + * @see Datacenter#setSchedulingInterval(double) + */ + private static final int SCHEDULING_INTERVAL = 1; + + private static final int HOSTS = 1; + private static final int HOST_PES = 8; + + private static final int VMS = 2; + private static final int VM_PES = 4; + + private static final int CLOUDLETS = 4; + private static final int CLOUDLET_PES = 2; + private static final int CLOUDLET_LENGTH = 10000; + + private final CloudSim simulation; + private DatacenterBroker broker0; + private List vmList; + private List cloudletList; + private Datacenter datacenter0; + + public static void main(String[] args) { + new VmDestructionExample(); + } + + public VmDestructionExample() { + /*Enables just some level of log messages. + Make sure to import org.cloudsimplus.util.Log;*/ + //Log.setLevel(ch.qos.logback.classic.Level.WARN); + + simulation = new CloudSim(); + datacenter0 = createDatacenter(); + + //Creates a broker that is a software acting on behalf a cloud customer to manage his/her VMs and Cloudlets + broker0 = new DatacenterBrokerSimple(simulation); + + vmList = createVms(); + cloudletList = createCloudlets(); + + /* Adds a Listener to track the execution update of VM 1. + * If you want to track the update processing of multiple VMs, you can + * add this event listener for each desired VM that it will work + * transparently for any VM. + */ + vmList.get(1).addOnUpdateProcessingListener(this::vmProcessingUpdateListener); + + broker0.submitVmList(vmList); + broker0.submitCloudletList(cloudletList); + + simulation.start(); + + final List finishedCloudlets = broker0.getCloudletFinishedList(); + new CloudletsTableBuilder(finishedCloudlets).build(); + } + + /** + * Tracks the update of execution for a VM. + * If that VM is overloaded then destroys it. + * In this example, this {@link EventListener} is just + * attached for VM 1, therefore, just such a VM will be destroyed + * if overloaded. + * + * @param info event information, including the VM that was updated + */ + private void vmProcessingUpdateListener(VmHostEventInfo info) { + final Vm vm = info.getVm(); + //Destroys VM 1 when its CPU usage reaches 90% + if(vm.getCpuPercentUtilization() > 0.9 && vm.isCreated()){ + System.out.printf( + "\n# %.2f: Intentionally destroying %s due to CPU overload. Current VM CPU usage is %.2f%%\n", + info.getTime(), vm, vm.getCpuPercentUtilization()*100); + vm.getHost().destroyVm(vm); + } + + datacenter0.getHostList().forEach(h -> System.out.printf("# %.2f: %s CPU Utilization %.2f%%\n", info.getTime(), h, h.getCpuPercentUtilization()*100)); + } + + /** + * Creates a Datacenter and its Hosts. + */ + private Datacenter createDatacenter() { + final List hostList = new ArrayList<>(HOSTS); + for(int i = 0; i < HOSTS; i++) { + Host host = createHost(); + hostList.add(host); + } + + final Datacenter dc = new DatacenterSimple(simulation, hostList, new VmAllocationPolicySimple()); + dc.setSchedulingInterval(SCHEDULING_INTERVAL); + return dc; + } + + private Host createHost() { + List peList = new ArrayList<>(HOST_PES); + //List of Host's CPUs (Processing Elements, PEs) + for (int i = 0; i < HOST_PES; i++) { + peList.add(new PeSimple(1000, new PeProvisionerSimple())); + } + + final long ram = 2048; //in Megabytes + final long bw = 10000; //in Megabits/s + final long storage = 1000000; //in Megabytes + ResourceProvisioner ramProvisioner = new ResourceProvisionerSimple(); + ResourceProvisioner bwProvisioner = new ResourceProvisionerSimple(); + VmScheduler vmScheduler = new VmSchedulerTimeShared(); + Host host = new HostSimple(ram, bw, storage, peList); + host + .setRamProvisioner(ramProvisioner) + .setBwProvisioner(bwProvisioner) + .setVmScheduler(vmScheduler); + return host; + } + + /** + * Creates a list of VMs. + */ + private List createVms() { + final List list = new ArrayList<>(VMS); + for (int i = 0; i < VMS; i++) { + Vm vm = + new VmSimple(i, 1000, VM_PES) + .setRam(512).setBw(1000).setSize(10000) + .setCloudletScheduler(new CloudletSchedulerTimeShared()); + + list.add(vm); + } + + return list; + } + + /** + * Creates a list of Cloudlets. + */ + private List createCloudlets() { + final List list = new ArrayList<>(CLOUDLETS); + UtilizationModel utilization = new UtilizationModelFull(); + + /*Creates a utilization model that enables increasing resource usage over time. + * It is used to define the CPU usage of VMs dynamically.*/ + UtilizationModelDynamic dynamicUtilization = new UtilizationModelDynamic(); + + /** + * Sets a {@link Function} that enables the utilization model to increment resource usage by 10% over time. + * This function is defined using a Lambda Expression. + */ + dynamicUtilization.setUtilizationUpdateFunction(um -> um.getUtilization() + um.getTimeSpan()*0.1); + + for (int i = 0; i < CLOUDLETS; i++) { + Cloudlet cloudlet = + new CloudletSimple(i, CLOUDLET_LENGTH, CLOUDLET_PES) + .setFileSize(1024) + .setOutputSize(1024) + .setUtilizationModelRam(utilization) + .setUtilizationModelBw(utilization) + .setUtilizationModelCpu(dynamicUtilization); + list.add(cloudlet); + } + + return list; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +CHECKERS_PRINTF_ARGS + +### Qualifier: +format string arguments don't mach provided arguments in printf(...) at line 154. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void VmDestructionExample.vmProcessingUpdateListener(VmHostEventInfo) + +### Procedure Id: +org.cloudsimplus.examples.VmDestructionExample.vmProcessingUpdateListener(org.cloudsimplus.listeners.a790fccc622d1ab321c06d8c19eb59a5 + +### File: +cloudsim-plus-examples/src/main/java/org/cloudsimplus/examples/VmDestructionExample.java + +### Key: +VmDestructionExample.java|vmProcessingUpdateListener|CHECKERS_PRINTF_ARGS + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +5ca2727b3e8494bef68ca9c88cd1a908 + +### Bug Type Hum: +Checkers Printf Args + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10278/instruction.md b/inferredbugs-10278/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e36fef8ffb54a6e7520da9027c8949ca97051e63 --- /dev/null +++ b/inferredbugs-10278/instruction.md @@ -0,0 +1,330 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** cloudsim-plus +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Title: CloudSim Toolkit + * Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds + * Licence: GPL - http://www.gnu.org/copyleft/gpl.html + * + * Copyright (c) 2009-2012, The University of Melbourne, Australia + */ +package org.cloudbus.cloudsim.network.topologies; + +import org.cloudbus.cloudsim.network.DelayMatrix; +import org.cloudbus.cloudsim.network.topologies.readers.TopologyReaderBrite; +import org.cloudbus.cloudsim.util.ResourceLoader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Implements a network layer by reading the topology from a file in the + * BRITE + * format, the Boston university + * Representative Internet Topology gEnerator + * (http://www.cs.bu.edu/brite/), + * and generates a topological network + * from it. Information of this network is used to simulate latency in network + * traffic of CloudSim. + * + *

The topology file may contain more nodes than the number of entities in the + * simulation. It allows users to increase the scale of the simulation without + * changing the topology file. Nevertheless, each CloudSim entity must be mapped + * to one (and only one) BRITE node to allow proper work of the network + * simulation. Each BRITE node can be mapped to only one entity at a time.

+ * + * @author Rodrigo N. Calheiros + * @author Anton Beloglazov + * @since CloudSim Toolkit 1.0 + * @see #getInstance(String) + */ +public final class BriteNetworkTopology implements NetworkTopology { + private static final Logger LOGGER = LoggerFactory.getLogger(BriteNetworkTopology.class.getSimpleName()); + + /** + * The BRITE id to use for the next node to be created in the network. + */ + private int nextIdx; + + private boolean networkEnabled; + + /** + * A matrix containing the delay between every pair of nodes in the network. + */ + private DelayMatrix delayMatrix; + + private double[][] bwMatrix; + + /** + * The Topological Graph of the network. + */ + private TopologicalGraph graph; + + /** + * The map between CloudSim entities and BRITE entities. + * Each key is a CloudSim entity ID and each value the corresponding BRITE entity ID. + */ + private Map map; + + /** + * Instantiates a Network Topology from a file inside the application's resource directory. + * @param fileName the relative name of the BRITE file + * @return the BriteNetworkTopology instance. + */ + public static BriteNetworkTopology getInstance(final String fileName){ + final InputStreamReader reader = new InputStreamReader(ResourceLoader.getInputStream(fileName, BriteNetworkTopology.class)); + return new BriteNetworkTopology(reader); + } + + /** + * Instantiates a Network Topology. + * @see #BriteNetworkTopology(String) + * @see #BriteNetworkTopology(InputStreamReader) + * @see #getInstance(String) + */ + public BriteNetworkTopology() { + map = new HashMap<>(); + bwMatrix = new double[0][0]; + graph = new TopologicalGraph(); + delayMatrix = new DelayMatrix(); + } + + /** + * Instantiates a Network Topology if a given file exists and can be successfully + * parsed. File is written in the BRITE format and contains + * topological information on simulation entities. + * + * @param filePath the path of the BRITE file + * @see #BriteNetworkTopology() + * @see #BriteNetworkTopology(InputStreamReader) + * @see #getInstance(String) + */ + public BriteNetworkTopology(final String filePath) { + this(ResourceLoader.getFileReader(filePath)); + LOGGER.info("Topology file: {}", filePath); + } + + /** + * Creates a network topology from a given input stream reader. + * The file is written in the BRITE format and contains + * topological information on simulation entities. + * + * @param streamReader the reader to read the topology file + * @see #BriteNetworkTopology() + * @see #BriteNetworkTopology(InputStreamReader) + * @see #getInstance(String) + */ + private BriteNetworkTopology(final InputStreamReader streamReader) { + this(); + final TopologyReaderBrite reader = new TopologyReaderBrite(); + graph = reader.readGraphFile(streamReader); + generateMatrices(); + } + + /** + * Generates the matrices used internally to set latency and bandwidth + * between elements. + */ + private void generateMatrices() { + // creates the delay matrix + delayMatrix = new DelayMatrix(getTopologycalGraph(), false); + + // creates the bw matrix + bwMatrix = createBwMatrix(getTopologycalGraph(), false); + + networkEnabled = true; + } + + /** + * Creates the matrix containing the available bandwidth between every pair + * of nodes. + * + * @param graph topological graph describing the topology + * @param directed true if the graph is directed; false otherwise + * @return the bandwidth graph + */ + private double[][] createBwMatrix(final TopologicalGraph graph, final boolean directed) { + final int nodes = graph.getNumberOfNodes(); + + final double[][] mtx = new double[nodes][nodes]; + + // cleanup matrix + for (int i = 0; i < nodes; i++) { + for (int j = 0; j < nodes; j++) { + mtx[i][j] = 0.0; + } + } + + for (final TopologicalLink edge : graph.getLinksList()) { + mtx[edge.getSrcNodeID()][edge.getDestNodeID()] = edge.getLinkBw(); + if (!directed) { + mtx[edge.getDestNodeID()][edge.getSrcNodeID()] = edge.getLinkBw(); + } + } + + return mtx; + } + + + @Override + public void addLink(final long srcId, final long destId, final double bandwidth, final double latency) { + if (getTopologycalGraph() == null) { + graph = new TopologicalGraph(); + } + + if (map == null) { + map = new HashMap<>(); + } + + // maybe add the nodes + addNodeMapping(srcId); + addNodeMapping(destId); + + // generate a new link + getTopologycalGraph().addLink(new TopologicalLink(map.get(srcId), map.get(destId), (float) latency, (float) bandwidth)); + + generateMatrices(); + } + + private void addNodeMapping(final long cloudSimEntityId) { + if (!map.containsKey(cloudSimEntityId)) { + getTopologycalGraph().addNode(new TopologicalNode(nextIdx)); + map.put(cloudSimEntityId, nextIdx); + nextIdx++; + } + } + + @Override + public void mapNode(final long cloudSimEntityID, final int briteID) { + if (!networkEnabled) { + return; + } + + if (map.containsKey(cloudSimEntityID)) { + LOGGER.warn("Network mapping: CloudSim entity {} already mapped.", cloudSimEntityID); + return; + } + + if (map.containsValue(briteID)) { + LOGGER.warn("BRITE node {} already in use.", briteID); + return; + } + + map.put(cloudSimEntityID, briteID); + } + + @Override + public void unmapNode(final long cloudSimEntityID) { + if (!networkEnabled) { + return; + } + + map.remove(cloudSimEntityID); + } + + @Override + public double getDelay(final long srcID, final long destID) { + if (!networkEnabled) { + return 0.0; + } + + try { + return delayMatrix.getDelay(map.getOrDefault(srcID, -1), map.getOrDefault(destID, -1)); + } catch (ArrayIndexOutOfBoundsException e) { + return 0.0; + } + } + + @Override + public boolean isNetworkEnabled() { + return networkEnabled; + } + + @Override + public TopologicalGraph getTopologycalGraph() { + return graph; + } + + /** + * Gets acopy of the matrix containing the bandwidth between every pair of nodes in the + * network. + */ + public double[][] getBwMatrix() { + return Arrays.copyOf(bwMatrix, bwMatrix.length); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `BriteNetworkTopology.map.get(valueOf(srcId))` could be null and is dereferenced at line 185. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BriteNetworkTopology.addLink(long,long,double,double) + +### Procedure Id: +org.cloudbus.cloudsim.network.topologies.BriteNetworkTopology.addLink(long,long,double,double):void.a5079c9f2bace7a7acfbb14295da3765 + +### File: +cloudsim-plus/src/main/java/org/cloudbus/cloudsim/network/topologies/BriteNetworkTopology.java + +### Key: +BriteNetworkTopology.java|addLink|NULL_DEREFERENCE + +### Node Key: +d5610a79cc016a1c47ca3aa635360294 + +### Hash: +2856732d99ffa5131fa2a44e8d1d68e7 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10284/instruction.md b/inferredbugs-10284/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4d4cecc8d2c1d5a579d78693071331658b9372f7 --- /dev/null +++ b/inferredbugs-10284/instruction.md @@ -0,0 +1,310 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MOE +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +// Copyright 2011 The MOE Authors All Rights Reserved. + +package com.google.devtools.moe.client.codebase; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; +import com.google.devtools.moe.client.CommandRunner.CommandException; +import com.google.devtools.moe.client.FileSystem; +import com.google.devtools.moe.client.Injector; +import com.google.devtools.moe.client.MoeProblem; +import com.google.devtools.moe.client.parser.RepositoryExpression; +import com.google.devtools.moe.client.parser.Term; +import com.google.devtools.moe.client.tools.FileDifference; + +import java.io.File; +import java.io.IOException; +import java.util.Set; + +/** + * Merges all changes that lead from {@code originalCodebase} to {@code modifiedCodebase} into + * destinationCodebase when its {@link #merge()} method is invoked. + * + *

Here is a description of the UNIX merge(1) tool from its man page: + *

{@code
+ *
+ *   merge [ options ] file1 file2 file3
+ *
+ *   merge incorporates all changes that lead from file2 to file3 into file1.  The result
+ *   ordinarily goes into file1.  merge is useful for combining separate changes to an original.
+ *   Suppose file2 is the original, and both file1 and file3 are modifications of file2.  Then
+ *   merge combines both changes.
+ *
+ * }
+ * + *

{@link CodebaseMerger#merge()} performs this type of merge on each file in the three + * codebases. In {@link CodebaseMerger#merge}, {@code originalCodebase} is analogous to + * {@code file2}, {@code modifiedCodebase} is analogous to {@code file3}, and + * {@code destinationCodebase} is analogous to {@code file1}. The output of + * {@link CodebaseMerger#merge()} is a codebase that incorporates the changes that both + * {@code modifiedCodebase} and {@code destinationCodebase} made on the {@code originalCodebase}. + * The differences between {@code modifiedCodebase} and the {@code originalCodebase} are brought + * into a copy of {@code destinationCodebase}. The result is the merged codebase. + * + *

This is useful when bringing changes to the public repository into the internal repository. + * For example, say you run: + * + *

{@code
+ *    merge_codebases --originalCodebase "publicrepo(revision=142)"
+ *                    --modifiedCodebase "publicrepo(revision=143)"
+ *                    --destinationCodebase "internalrepo(revision=74)"
+ * }
+ * + *

Let internalrepo(revision=74) be in equivalence with publicrepo(revision=142). That is, let + * publicrepo(revision=142) represent the same state of the code as internalrepo(revision=74) + * minus any confidential code that may have been scrubbed during translation. That means that + * publicrepo(revision=143) is a change to the public repository which has yet to be brought to + * the internal repository. By running the above merge_codebases, the changes from the public + * revision 142 to 143 will be merged into a copy of internal revision 74. The result is an + * internal revision 75 which has the new public changes and still has the confidential code that + * a public revision wouldn't have. Thus, internal revision 75 would be equivalent with public + * revision 143 assuming there were no conflicts when merging. + */ +public class CodebaseMerger { + + private final Codebase originalCodebase, destinationCodebase, modifiedCodebase, mergedCodebase; + private final Set mergedFiles, failedToMergeFiles; + + public CodebaseMerger( + Codebase originalCodebase, Codebase modifiedCodebase, Codebase destinationCodebase) { + this.originalCodebase = originalCodebase; + this.modifiedCodebase = modifiedCodebase; + this.destinationCodebase = destinationCodebase; + + File mergedDir = Injector.INSTANCE.fileSystem().getTemporaryDirectory("merged_codebase_"); + RepositoryExpression mergedExpression = + new RepositoryExpression(new Term("merged", ImmutableMap.of())); + this.mergedCodebase = new Codebase(mergedDir, "merged", mergedExpression); + + mergedFiles = Sets.newHashSet(); + failedToMergeFiles = Sets.newHashSet(); + } + + public Set getMergedFiles() { + return ImmutableSet.copyOf(mergedFiles); + } + + public Set getFailedToMergeFiles() { + return ImmutableSet.copyOf(failedToMergeFiles); + } + + /** + * For each file in the union of the modified and destination codebases, run + * generateMergedFile(...) and then report() the results. + * + * @return the merged Codebase + */ + public Codebase merge() { + Set filesToMerge = + Sets.union( + destinationCodebase.getRelativeFilenames(), modifiedCodebase.getRelativeFilenames()); + for (String filename : filesToMerge) { + this.generateMergedFile(filename); + } + this.report(); + return mergedCodebase; + } + + /** + * Print the results of a merge to the UI. + */ + public void report() { + Injector.INSTANCE + .ui() + .info("Merged codebase generated at: %s", mergedCodebase.getPath().getAbsolutePath()); + Injector.INSTANCE + .ui() + .info( + "%d files merged successfully\n%d files have merge " + + "conflicts. Edit the following files to resolve conflicts:\n%s", + mergedFiles.size(), + failedToMergeFiles.size(), + failedToMergeFiles); + } + + private static boolean areDifferent(String filename, File x, File y) { + return FileDifference.CONCRETE_FILE_DIFFER.diffFiles(filename, x, y).isDifferent(); + } + + /** + * Copy the destFile into the merged codebase. This is where the output of merge will be + * written to. + */ + private File copyToMergedCodebase(String filename, File destFile) { + FileSystem fs = Injector.INSTANCE.fileSystem(); + File mergedFile = mergedCodebase.getFile(filename); + try { + fs.makeDirsForFile(mergedFile); + fs.copyFile(destFile, mergedFile); + return mergedFile; + } catch (IOException e) { + throw new MoeProblem(e.getMessage()); + } + } + + /** + * Given a filename, this method finds the file with that name in each of the three codebases. + * Using the UNIX merge(1) tool, those three files are merged and the result is placed in the + * merged codebase. Any conflicts that occurred during merging will appear in the merged codebase + * file for the user to resolve. + * + * In the case where the file specified by the given filename exists in the original codebase and + * in either the modified codebase or the destination codebase (but not both) and if the file + * is unchanged between those codebases, then a file in the merged codebase will NOT be created + * and this method will return leaving the merged codebase unchanged. + * + * @param filename the name of the file to merge + */ + public void generateMergedFile(String filename) { + FileSystem fs = Injector.INSTANCE.fileSystem(); + + File origFile = originalCodebase.getFile(filename); + boolean origExists = fs.exists(origFile); + + File destFile = destinationCodebase.getFile(filename); + boolean destExists = fs.exists(destFile); + + File modFile = modifiedCodebase.getFile(filename); + boolean modExists = fs.exists(modFile); + + if (!destExists && !modExists) { + // This should never be thrown since generateMergedFile(...) is only called on filesToMerge + // from merge() which is the union of the files in the destination and modified codebases. + throw new MoeProblem( + "%s doesn't exist in either %s nor %s. This should not be possible.", + filename, + destinationCodebase, + modifiedCodebase); + + } else if (origExists && modExists && !destExists) { + if (areDifferent(filename, origFile, modFile)) { + // Proceed and merge in /dev/null, which should produce a merge conflict (incoming edit on + // delete). + destFile = new File("/dev/null"); + } else { + // Defer to deletion in destination codebase. + return; + } + + } else if (origExists && !modExists && destExists) { + // Blindly follow deletion of the original file by not copying it into the merged codebase. + return; + + } else if (!origExists && !(modExists && destExists)) { + // File exists only in modified or destination codebase, so just copy it over. + File existingFile = (modExists ? modFile : destFile); + copyToMergedCodebase(filename, existingFile); + return; + + } else if (!origExists && modExists && destExists) { + // Merge both new files (conflict expected). + origFile = new File("/dev/null"); + } + + File mergedFile = copyToMergedCodebase(filename, destFile); + + try { + // Merges the changes that lead from origFile to modFile into mergedFile (which is a copy + // of destFile). After, mergedFile will have the combined changes of modFile and destFile. + Injector.INSTANCE + .cmd() + .runCommand( + "merge", + ImmutableList.of( + mergedFile.getAbsolutePath(), + origFile.getAbsolutePath(), + modFile.getAbsolutePath()), + this.mergedCodebase.getPath().getAbsolutePath()); + // Return status was 0 and the merge was successful. Note it. + mergedFiles.add(mergedFile.getAbsolutePath()); + } catch (CommandException e) { + // If merge fails with exit status 1, then a conflict occurred. Make a note of the filepath. + if (e.returnStatus == 1) { + failedToMergeFiles.add(mergedFile.getAbsolutePath()); + } else { + throw new MoeProblem( + "Merge returned with unexpected status %d when trying to run \"merge -p %s %s %s\"", + e.returnStatus, + destFile.getAbsolutePath(), + origFile.getAbsolutePath(), + modFile.getAbsolutePath()); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `fs` last assigned on line 136 at line 139. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +File CodebaseMerger.copyToMergedCodebase(String,File) + +### Procedure Id: +com.google.devtools.moe.client.codebase.CodebaseMerger.copyToMergedCodebase(java.lang.String,java.io.4cb520384d6c3e130f413b1d13ae6ef6 + +### File: +java/com/google/devtools/moe/client/codebase/CodebaseMerger.java + +### Key: +CodebaseMerger.java|copyToMergedCodebase|NULL_DEREFERENCE + +### Node Key: +755589d225f31e8637e855506d73c7f3 + +### Hash: +cb9a5b8010d519b764dc5fbcfee7b30b + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10285/instruction.md b/inferredbugs-10285/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9409ffd7b0639be3402bb5ac8c45eacb05987eef --- /dev/null +++ b/inferredbugs-10285/instruction.md @@ -0,0 +1,310 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MOE +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +// Copyright 2011 The MOE Authors All Rights Reserved. + +package com.google.devtools.moe.client.codebase; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; +import com.google.devtools.moe.client.CommandRunner.CommandException; +import com.google.devtools.moe.client.FileSystem; +import com.google.devtools.moe.client.Injector; +import com.google.devtools.moe.client.MoeProblem; +import com.google.devtools.moe.client.parser.RepositoryExpression; +import com.google.devtools.moe.client.parser.Term; +import com.google.devtools.moe.client.tools.FileDifference; + +import java.io.File; +import java.io.IOException; +import java.util.Set; + +/** + * Merges all changes that lead from {@code originalCodebase} to {@code modifiedCodebase} into + * destinationCodebase when its {@link #merge()} method is invoked. + * + *

Here is a description of the UNIX merge(1) tool from its man page: + *

{@code
+ *
+ *   merge [ options ] file1 file2 file3
+ *
+ *   merge incorporates all changes that lead from file2 to file3 into file1.  The result
+ *   ordinarily goes into file1.  merge is useful for combining separate changes to an original.
+ *   Suppose file2 is the original, and both file1 and file3 are modifications of file2.  Then
+ *   merge combines both changes.
+ *
+ * }
+ * + *

{@link CodebaseMerger#merge()} performs this type of merge on each file in the three + * codebases. In {@link CodebaseMerger#merge}, {@code originalCodebase} is analogous to + * {@code file2}, {@code modifiedCodebase} is analogous to {@code file3}, and + * {@code destinationCodebase} is analogous to {@code file1}. The output of + * {@link CodebaseMerger#merge()} is a codebase that incorporates the changes that both + * {@code modifiedCodebase} and {@code destinationCodebase} made on the {@code originalCodebase}. + * The differences between {@code modifiedCodebase} and the {@code originalCodebase} are brought + * into a copy of {@code destinationCodebase}. The result is the merged codebase. + * + *

This is useful when bringing changes to the public repository into the internal repository. + * For example, say you run: + * + *

{@code
+ *    merge_codebases --originalCodebase "publicrepo(revision=142)"
+ *                    --modifiedCodebase "publicrepo(revision=143)"
+ *                    --destinationCodebase "internalrepo(revision=74)"
+ * }
+ * + *

Let internalrepo(revision=74) be in equivalence with publicrepo(revision=142). That is, let + * publicrepo(revision=142) represent the same state of the code as internalrepo(revision=74) + * minus any confidential code that may have been scrubbed during translation. That means that + * publicrepo(revision=143) is a change to the public repository which has yet to be brought to + * the internal repository. By running the above merge_codebases, the changes from the public + * revision 142 to 143 will be merged into a copy of internal revision 74. The result is an + * internal revision 75 which has the new public changes and still has the confidential code that + * a public revision wouldn't have. Thus, internal revision 75 would be equivalent with public + * revision 143 assuming there were no conflicts when merging. + */ +public class CodebaseMerger { + + private final Codebase originalCodebase, destinationCodebase, modifiedCodebase, mergedCodebase; + private final Set mergedFiles, failedToMergeFiles; + + public CodebaseMerger( + Codebase originalCodebase, Codebase modifiedCodebase, Codebase destinationCodebase) { + this.originalCodebase = originalCodebase; + this.modifiedCodebase = modifiedCodebase; + this.destinationCodebase = destinationCodebase; + + File mergedDir = Injector.INSTANCE.fileSystem().getTemporaryDirectory("merged_codebase_"); + RepositoryExpression mergedExpression = + new RepositoryExpression(new Term("merged", ImmutableMap.of())); + this.mergedCodebase = new Codebase(mergedDir, "merged", mergedExpression); + + mergedFiles = Sets.newHashSet(); + failedToMergeFiles = Sets.newHashSet(); + } + + public Set getMergedFiles() { + return ImmutableSet.copyOf(mergedFiles); + } + + public Set getFailedToMergeFiles() { + return ImmutableSet.copyOf(failedToMergeFiles); + } + + /** + * For each file in the union of the modified and destination codebases, run + * generateMergedFile(...) and then report() the results. + * + * @return the merged Codebase + */ + public Codebase merge() { + Set filesToMerge = + Sets.union( + destinationCodebase.getRelativeFilenames(), modifiedCodebase.getRelativeFilenames()); + for (String filename : filesToMerge) { + this.generateMergedFile(filename); + } + this.report(); + return mergedCodebase; + } + + /** + * Print the results of a merge to the UI. + */ + public void report() { + Injector.INSTANCE + .ui() + .info("Merged codebase generated at: %s", mergedCodebase.getPath().getAbsolutePath()); + Injector.INSTANCE + .ui() + .info( + "%d files merged successfully\n%d files have merge " + + "conflicts. Edit the following files to resolve conflicts:\n%s", + mergedFiles.size(), + failedToMergeFiles.size(), + failedToMergeFiles); + } + + private static boolean areDifferent(String filename, File x, File y) { + return FileDifference.CONCRETE_FILE_DIFFER.diffFiles(filename, x, y).isDifferent(); + } + + /** + * Copy the destFile into the merged codebase. This is where the output of merge will be + * written to. + */ + private File copyToMergedCodebase(String filename, File destFile) { + FileSystem fs = Injector.INSTANCE.fileSystem(); + File mergedFile = mergedCodebase.getFile(filename); + try { + fs.makeDirsForFile(mergedFile); + fs.copyFile(destFile, mergedFile); + return mergedFile; + } catch (IOException e) { + throw new MoeProblem(e.getMessage()); + } + } + + /** + * Given a filename, this method finds the file with that name in each of the three codebases. + * Using the UNIX merge(1) tool, those three files are merged and the result is placed in the + * merged codebase. Any conflicts that occurred during merging will appear in the merged codebase + * file for the user to resolve. + * + * In the case where the file specified by the given filename exists in the original codebase and + * in either the modified codebase or the destination codebase (but not both) and if the file + * is unchanged between those codebases, then a file in the merged codebase will NOT be created + * and this method will return leaving the merged codebase unchanged. + * + * @param filename the name of the file to merge + */ + public void generateMergedFile(String filename) { + FileSystem fs = Injector.INSTANCE.fileSystem(); + + File origFile = originalCodebase.getFile(filename); + boolean origExists = fs.exists(origFile); + + File destFile = destinationCodebase.getFile(filename); + boolean destExists = fs.exists(destFile); + + File modFile = modifiedCodebase.getFile(filename); + boolean modExists = fs.exists(modFile); + + if (!destExists && !modExists) { + // This should never be thrown since generateMergedFile(...) is only called on filesToMerge + // from merge() which is the union of the files in the destination and modified codebases. + throw new MoeProblem( + "%s doesn't exist in either %s nor %s. This should not be possible.", + filename, + destinationCodebase, + modifiedCodebase); + + } else if (origExists && modExists && !destExists) { + if (areDifferent(filename, origFile, modFile)) { + // Proceed and merge in /dev/null, which should produce a merge conflict (incoming edit on + // delete). + destFile = new File("/dev/null"); + } else { + // Defer to deletion in destination codebase. + return; + } + + } else if (origExists && !modExists && destExists) { + // Blindly follow deletion of the original file by not copying it into the merged codebase. + return; + + } else if (!origExists && !(modExists && destExists)) { + // File exists only in modified or destination codebase, so just copy it over. + File existingFile = (modExists ? modFile : destFile); + copyToMergedCodebase(filename, existingFile); + return; + + } else if (!origExists && modExists && destExists) { + // Merge both new files (conflict expected). + origFile = new File("/dev/null"); + } + + File mergedFile = copyToMergedCodebase(filename, destFile); + + try { + // Merges the changes that lead from origFile to modFile into mergedFile (which is a copy + // of destFile). After, mergedFile will have the combined changes of modFile and destFile. + Injector.INSTANCE + .cmd() + .runCommand( + "merge", + ImmutableList.of( + mergedFile.getAbsolutePath(), + origFile.getAbsolutePath(), + modFile.getAbsolutePath()), + this.mergedCodebase.getPath().getAbsolutePath()); + // Return status was 0 and the merge was successful. Note it. + mergedFiles.add(mergedFile.getAbsolutePath()); + } catch (CommandException e) { + // If merge fails with exit status 1, then a conflict occurred. Make a note of the filepath. + if (e.returnStatus == 1) { + failedToMergeFiles.add(mergedFile.getAbsolutePath()); + } else { + throw new MoeProblem( + "Merge returned with unexpected status %d when trying to run \"merge -p %s %s %s\"", + e.returnStatus, + destFile.getAbsolutePath(), + origFile.getAbsolutePath(), + modFile.getAbsolutePath()); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `fs` last assigned on line 161 at line 164. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CodebaseMerger.generateMergedFile(String) + +### Procedure Id: +com.google.devtools.moe.client.codebase.CodebaseMerger.generateMergedFile(java.lang.String):void.9c5c65863d228a4d22b4acc1aeb5e2c7 + +### File: +java/com/google/devtools/moe/client/codebase/CodebaseMerger.java + +### Key: +CodebaseMerger.java|generateMergedFile|NULL_DEREFERENCE + +### Node Key: +945e767fe445b06359d6930a48da0055 + +### Hash: +99776ac82552d67c864749efa29cf6ad + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10302/instruction.md b/inferredbugs-10302/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..040bd40178066848e92837396f7199b0854eefab --- /dev/null +++ b/inferredbugs-10302/instruction.md @@ -0,0 +1,957 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** httpcomponents-client +**Bug ID:** 51 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * . + * + */ +package org.apache.http.impl.client.cache; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.Header; +import org.apache.http.HeaderElement; +import org.apache.http.HttpException; +import org.apache.http.HttpHost; +import org.apache.http.HttpMessage; +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.HttpVersion; +import org.apache.http.ProtocolException; +import org.apache.http.ProtocolVersion; +import org.apache.http.RequestLine; +import org.apache.http.annotation.ThreadSafe; +import org.apache.http.client.cache.CacheResponseStatus; +import org.apache.http.client.cache.HeaderConstants; +import org.apache.http.client.cache.HttpCacheContext; +import org.apache.http.client.cache.HttpCacheEntry; +import org.apache.http.client.cache.HttpCacheStorage; +import org.apache.http.client.cache.ResourceFactory; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpExecutionAware; +import org.apache.http.client.methods.HttpRequestWrapper; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.client.utils.DateUtils; +import org.apache.http.client.utils.URIUtils; +import org.apache.http.conn.routing.HttpRoute; +import org.apache.http.impl.execchain.ClientExecChain; +import org.apache.http.message.BasicHttpResponse; +import org.apache.http.protocol.HTTP; +import org.apache.http.protocol.HttpContext; +import org.apache.http.protocol.HttpCoreContext; +import org.apache.http.util.Args; +import org.apache.http.util.VersionInfo; + +/** + * Request executor in the request execution chain that is responsible for + * transparent client-side caching. The current implementation is conditionally + * compliant with HTTP/1.1 (meaning all the MUST and MUST NOTs are obeyed), + * although quite a lot, though not all, of the SHOULDs and SHOULD NOTs + * are obeyed too. + *

+ * Folks that would like to experiment with alternative storage backends + * should look at the {@link HttpCacheStorage} interface and the related + * package documentation there. You may also be interested in the provided + * {@link org.apache.http.impl.client.cache.ehcache.EhcacheHttpCacheStorage + * EhCache} and {@link + * org.apache.http.impl.client.cache.memcached.MemcachedHttpCacheStorage + * memcached} storage backends. + *

+ * Further responsibilities such as communication with the opposite + * endpoint is delegated to the next executor in the request execution + * chain. + * + * @since 4.3 + */ +@ThreadSafe // So long as the responseCache implementation is threadsafe +public class CachingExec implements ClientExecChain { + + private final static boolean SUPPORTS_RANGE_AND_CONTENT_RANGE_HEADERS = false; + + private final AtomicLong cacheHits = new AtomicLong(); + private final AtomicLong cacheMisses = new AtomicLong(); + private final AtomicLong cacheUpdates = new AtomicLong(); + + private final Map viaHeaders = new HashMap(4); + + private final CacheConfig cacheConfig; + private final ClientExecChain backend; + private final HttpCache responseCache; + private final CacheValidityPolicy validityPolicy; + private final CachedHttpResponseGenerator responseGenerator; + private final CacheableRequestPolicy cacheableRequestPolicy; + private final CachedResponseSuitabilityChecker suitabilityChecker; + private final ConditionalRequestBuilder conditionalRequestBuilder; + private final ResponseProtocolCompliance responseCompliance; + private final RequestProtocolCompliance requestCompliance; + private final ResponseCachingPolicy responseCachingPolicy; + + private final AsynchronousValidator asynchRevalidator; + + private final Log log = LogFactory.getLog(getClass()); + + public CachingExec( + final ClientExecChain backend, + final HttpCache cache, + final CacheConfig config) { + this(backend, cache, config, null); + } + + public CachingExec( + final ClientExecChain backend, + final HttpCache cache, + final CacheConfig config, + final AsynchronousValidator asynchRevalidator) { + super(); + Args.notNull(backend, "HTTP backend"); + Args.notNull(cache, "HttpCache"); + this.cacheConfig = config != null ? config : CacheConfig.DEFAULT; + this.backend = backend; + this.responseCache = cache; + this.validityPolicy = new CacheValidityPolicy(); + this.responseGenerator = new CachedHttpResponseGenerator(this.validityPolicy); + this.cacheableRequestPolicy = new CacheableRequestPolicy(); + this.suitabilityChecker = new CachedResponseSuitabilityChecker(this.validityPolicy, this.cacheConfig); + this.conditionalRequestBuilder = new ConditionalRequestBuilder(); + this.responseCompliance = new ResponseProtocolCompliance(); + this.requestCompliance = new RequestProtocolCompliance(this.cacheConfig.isWeakETagOnPutDeleteAllowed()); + this.responseCachingPolicy = new ResponseCachingPolicy( + this.cacheConfig.getMaxObjectSize(), this.cacheConfig.isSharedCache(), + this.cacheConfig.isNeverCacheHTTP10ResponsesWithQuery(), this.cacheConfig.is303CachingEnabled()); + this.asynchRevalidator = asynchRevalidator; + } + + public CachingExec( + final ClientExecChain backend, + final ResourceFactory resourceFactory, + final HttpCacheStorage storage, + final CacheConfig config) { + this(backend, new BasicHttpCache(resourceFactory, storage, config), config); + } + + public CachingExec(final ClientExecChain backend) { + this(backend, new BasicHttpCache(), CacheConfig.DEFAULT); + } + + CachingExec( + final ClientExecChain backend, + final HttpCache responseCache, + final CacheValidityPolicy validityPolicy, + final ResponseCachingPolicy responseCachingPolicy, + final CachedHttpResponseGenerator responseGenerator, + final CacheableRequestPolicy cacheableRequestPolicy, + final CachedResponseSuitabilityChecker suitabilityChecker, + final ConditionalRequestBuilder conditionalRequestBuilder, + final ResponseProtocolCompliance responseCompliance, + final RequestProtocolCompliance requestCompliance, + final CacheConfig config, + final AsynchronousValidator asynchRevalidator) { + this.cacheConfig = config != null ? config : CacheConfig.DEFAULT; + this.backend = backend; + this.responseCache = responseCache; + this.validityPolicy = validityPolicy; + this.responseCachingPolicy = responseCachingPolicy; + this.responseGenerator = responseGenerator; + this.cacheableRequestPolicy = cacheableRequestPolicy; + this.suitabilityChecker = suitabilityChecker; + this.conditionalRequestBuilder = conditionalRequestBuilder; + this.responseCompliance = responseCompliance; + this.requestCompliance = requestCompliance; + this.asynchRevalidator = asynchRevalidator; + } + + /** + * Reports the number of times that the cache successfully responded + * to an {@link HttpRequest} without contacting the origin server. + * @return the number of cache hits + */ + public long getCacheHits() { + return cacheHits.get(); + } + + /** + * Reports the number of times that the cache contacted the origin + * server because it had no appropriate response cached. + * @return the number of cache misses + */ + public long getCacheMisses() { + return cacheMisses.get(); + } + + /** + * Reports the number of times that the cache was able to satisfy + * a response by revalidating an existing but stale cache entry. + * @return the number of cache revalidations + */ + public long getCacheUpdates() { + return cacheUpdates.get(); + } + + public CloseableHttpResponse execute( + final HttpRoute route, + final HttpRequestWrapper request) throws IOException, HttpException { + return execute(route, request, HttpClientContext.create(), null); + } + + public CloseableHttpResponse execute( + final HttpRoute route, + final HttpRequestWrapper request, + final HttpClientContext context) throws IOException, HttpException { + return execute(route, request, context, null); + } + + @Override + public CloseableHttpResponse execute( + final HttpRoute route, + final HttpRequestWrapper request, + final HttpClientContext context, + final HttpExecutionAware execAware) throws IOException, HttpException { + + final HttpHost target = context.getTargetHost(); + final String via = generateViaHeader(request.getOriginal()); + + // default response context + setResponseStatus(context, CacheResponseStatus.CACHE_MISS); + + if (clientRequestsOurOptions(request)) { + setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); + return Proxies.enhanceResponse(new OptionsHttp11Response()); + } + + final HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse(request, context); + if (fatalErrorResponse != null) { + return Proxies.enhanceResponse(fatalErrorResponse); + } + + requestCompliance.makeRequestCompliant(request); + request.addHeader("Via",via); + + flushEntriesInvalidatedByRequest(context.getTargetHost(), request); + + if (!cacheableRequestPolicy.isServableFromCache(request)) { + log.debug("Request is not servable from cache"); + return callBackend(route, request, context, execAware); + } + + final HttpCacheEntry entry = satisfyFromCache(target, request); + if (entry == null) { + log.debug("Cache miss"); + return handleCacheMiss(route, request, context, execAware); + } else { + return handleCacheHit(route, request, context, execAware, entry); + } + } + + private CloseableHttpResponse handleCacheHit( + final HttpRoute route, + final HttpRequestWrapper request, + final HttpClientContext context, + final HttpExecutionAware execAware, + final HttpCacheEntry entry) throws IOException, HttpException { + final HttpHost target = context.getTargetHost(); + recordCacheHit(target, request); + CloseableHttpResponse out = null; + final Date now = getCurrentDate(); + if (suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) { + log.debug("Cache hit"); + out = generateCachedResponse(request, context, entry, now); + } else if (!mayCallBackend(request)) { + log.debug("Cache entry not suitable but only-if-cached requested"); + out = generateGatewayTimeout(context); + } else if (!(entry.getStatusCode() == HttpStatus.SC_NOT_MODIFIED + && !suitabilityChecker.isConditional(request))) { + log.debug("Revalidating cache entry"); + return revalidateCacheEntry(route, request, context, execAware, entry, now); + } else { + log.debug("Cache entry not usable; calling backend"); + return callBackend(route, request, context, execAware); + } + context.setAttribute(HttpClientContext.HTTP_ROUTE, route); + context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); + context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); + context.setAttribute(HttpCoreContext.HTTP_RESPONSE, out); + context.setAttribute(HttpCoreContext.HTTP_REQ_SENT, Boolean.TRUE); + return out; + } + + private CloseableHttpResponse revalidateCacheEntry( + final HttpRoute route, + final HttpRequestWrapper request, + final HttpClientContext context, + final HttpExecutionAware execAware, + final HttpCacheEntry entry, + final Date now) throws HttpException { + + try { + if (asynchRevalidator != null + && !staleResponseNotAllowed(request, entry, now) + && validityPolicy.mayReturnStaleWhileRevalidating(entry, now)) { + log.trace("Serving stale with asynchronous revalidation"); + final CloseableHttpResponse resp = generateCachedResponse(request, context, entry, now); + asynchRevalidator.revalidateCacheEntry(this, route, request, context, execAware, entry); + return resp; + } + return revalidateCacheEntry(route, request, context, execAware, entry); + } catch (final IOException ioex) { + return handleRevalidationFailure(request, context, entry, now); + } + } + + private CloseableHttpResponse handleCacheMiss( + final HttpRoute route, + final HttpRequestWrapper request, + final HttpClientContext context, + final HttpExecutionAware execAware) throws IOException, HttpException { + final HttpHost target = context.getTargetHost(); + recordCacheMiss(target, request); + + if (!mayCallBackend(request)) { + return Proxies.enhanceResponse( + new BasicHttpResponse( + HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT, "Gateway Timeout")); + } + + final Map variants = getExistingCacheVariants(target, request); + if (variants != null && !variants.isEmpty()) { + return negotiateResponseFromVariants(route, request, context, + execAware, variants); + } + + return callBackend(route, request, context, execAware); + } + + private HttpCacheEntry satisfyFromCache( + final HttpHost target, final HttpRequestWrapper request) { + HttpCacheEntry entry = null; + try { + entry = responseCache.getCacheEntry(target, request); + } catch (final IOException ioe) { + log.warn("Unable to retrieve entries from cache", ioe); + } + return entry; + } + + private HttpResponse getFatallyNoncompliantResponse( + final HttpRequestWrapper request, + final HttpContext context) { + HttpResponse fatalErrorResponse = null; + final List fatalError = requestCompliance.requestIsFatallyNonCompliant(request); + + for (final RequestProtocolError error : fatalError) { + setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); + fatalErrorResponse = requestCompliance.getErrorForRequest(error); + } + return fatalErrorResponse; + } + + private Map getExistingCacheVariants( + final HttpHost target, + final HttpRequestWrapper request) { + Map variants = null; + try { + variants = responseCache.getVariantCacheEntriesWithEtags(target, request); + } catch (final IOException ioe) { + log.warn("Unable to retrieve variant entries from cache", ioe); + } + return variants; + } + + private void recordCacheMiss(final HttpHost target, final HttpRequestWrapper request) { + cacheMisses.getAndIncrement(); + if (log.isTraceEnabled()) { + final RequestLine rl = request.getRequestLine(); + log.trace("Cache miss [host: " + target + "; uri: " + rl.getUri() + "]"); + } + } + + private void recordCacheHit(final HttpHost target, final HttpRequestWrapper request) { + cacheHits.getAndIncrement(); + if (log.isTraceEnabled()) { + final RequestLine rl = request.getRequestLine(); + log.trace("Cache hit [host: " + target + "; uri: " + rl.getUri() + "]"); + } + } + + private void recordCacheUpdate(final HttpContext context) { + cacheUpdates.getAndIncrement(); + setResponseStatus(context, CacheResponseStatus.VALIDATED); + } + + private void flushEntriesInvalidatedByRequest( + final HttpHost target, + final HttpRequestWrapper request) { + try { + responseCache.flushInvalidatedCacheEntriesFor(target, request); + } catch (final IOException ioe) { + log.warn("Unable to flush invalidated entries from cache", ioe); + } + } + + private CloseableHttpResponse generateCachedResponse(final HttpRequestWrapper request, + final HttpContext context, final HttpCacheEntry entry, final Date now) { + final CloseableHttpResponse cachedResponse; + if (request.containsHeader(HeaderConstants.IF_NONE_MATCH) + || request.containsHeader(HeaderConstants.IF_MODIFIED_SINCE)) { + cachedResponse = responseGenerator.generateNotModifiedResponse(entry); + } else { + cachedResponse = responseGenerator.generateResponse(entry); + } + setResponseStatus(context, CacheResponseStatus.CACHE_HIT); + if (validityPolicy.getStalenessSecs(entry, now) > 0L) { + cachedResponse.addHeader(HeaderConstants.WARNING,"110 localhost \"Response is stale\""); + } + return cachedResponse; + } + + private CloseableHttpResponse handleRevalidationFailure( + final HttpRequestWrapper request, + final HttpContext context, + final HttpCacheEntry entry, + final Date now) { + if (staleResponseNotAllowed(request, entry, now)) { + return generateGatewayTimeout(context); + } else { + return unvalidatedCacheHit(context, entry); + } + } + + private CloseableHttpResponse generateGatewayTimeout( + final HttpContext context) { + setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); + return Proxies.enhanceResponse(new BasicHttpResponse( + HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT, + "Gateway Timeout")); + } + + private CloseableHttpResponse unvalidatedCacheHit( + final HttpContext context, final HttpCacheEntry entry) { + final CloseableHttpResponse cachedResponse = responseGenerator.generateResponse(entry); + setResponseStatus(context, CacheResponseStatus.CACHE_HIT); + cachedResponse.addHeader(HeaderConstants.WARNING, "111 localhost \"Revalidation failed\""); + return cachedResponse; + } + + private boolean staleResponseNotAllowed( + final HttpRequestWrapper request, + final HttpCacheEntry entry, + final Date now) { + return validityPolicy.mustRevalidate(entry) + || (cacheConfig.isSharedCache() && validityPolicy.proxyRevalidate(entry)) + || explicitFreshnessRequest(request, entry, now); + } + + private boolean mayCallBackend(final HttpRequestWrapper request) { + for (final Header h: request.getHeaders(HeaderConstants.CACHE_CONTROL)) { + for (final HeaderElement elt : h.getElements()) { + if ("only-if-cached".equals(elt.getName())) { + log.trace("Request marked only-if-cached"); + return false; + } + } + } + return true; + } + + private boolean explicitFreshnessRequest( + final HttpRequestWrapper request, + final HttpCacheEntry entry, + final Date now) { + for(final Header h : request.getHeaders(HeaderConstants.CACHE_CONTROL)) { + for(final HeaderElement elt : h.getElements()) { + if (HeaderConstants.CACHE_CONTROL_MAX_STALE.equals(elt.getName())) { + try { + final int maxstale = Integer.parseInt(elt.getValue()); + final long age = validityPolicy.getCurrentAgeSecs(entry, now); + final long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry); + if (age - lifetime > maxstale) { + return true; + } + } catch (final NumberFormatException nfe) { + return true; + } + } else if (HeaderConstants.CACHE_CONTROL_MIN_FRESH.equals(elt.getName()) + || HeaderConstants.CACHE_CONTROL_MAX_AGE.equals(elt.getName())) { + return true; + } + } + } + return false; + } + + private String generateViaHeader(final HttpMessage msg) { + + final ProtocolVersion pv = msg.getProtocolVersion(); + final String existingEntry = viaHeaders.get(pv); + if (existingEntry != null) { + return existingEntry; + } + + final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client", getClass().getClassLoader()); + final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE; + + String value; + final Integer major = Integer.valueOf(pv.getMajor()); + final Integer minor = Integer.valueOf(pv.getMinor()); + if ("http".equalsIgnoreCase(pv.getProtocol())) { + value = String.format("%d.%d localhost (Apache-HttpClient/%s (cache))", major, minor, + release); + } else { + value = String.format("%s/%d.%d localhost (Apache-HttpClient/%s (cache))", pv.getProtocol(), major, + minor, release); + } + viaHeaders.put(pv, value); + + return value; + } + + private void setResponseStatus(final HttpContext context, final CacheResponseStatus value) { + if (context != null) { + context.setAttribute(HttpCacheContext.CACHE_RESPONSE_STATUS, value); + } + } + + /** + * Reports whether this {@code CachingHttpClient} implementation + * supports byte-range requests as specified by the {@code Range} + * and {@code Content-Range} headers. + * @return {@code true} if byte-range requests are supported + */ + public boolean supportsRangeAndContentRangeHeaders() { + return SUPPORTS_RANGE_AND_CONTENT_RANGE_HEADERS; + } + + Date getCurrentDate() { + return new Date(); + } + + boolean clientRequestsOurOptions(final HttpRequest request) { + final RequestLine line = request.getRequestLine(); + + if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod())) { + return false; + } + + if (!"*".equals(line.getUri())) { + return false; + } + + if (!"0".equals(request.getFirstHeader(HeaderConstants.MAX_FORWARDS).getValue())) { + return false; + } + + return true; + } + + CloseableHttpResponse callBackend( + final HttpRoute route, + final HttpRequestWrapper request, + final HttpClientContext context, + final HttpExecutionAware execAware) throws IOException, HttpException { + + final Date requestDate = getCurrentDate(); + + log.trace("Calling the backend"); + final CloseableHttpResponse backendResponse = backend.execute(route, request, context, execAware); + try { + backendResponse.addHeader("Via", generateViaHeader(backendResponse)); + return handleBackendResponse(request, context, requestDate, getCurrentDate(), + backendResponse); + } catch (final IOException ex) { + backendResponse.close(); + throw ex; + } catch (final RuntimeException ex) { + backendResponse.close(); + throw ex; + } + } + + private boolean revalidationResponseIsTooOld(final HttpResponse backendResponse, + final HttpCacheEntry cacheEntry) { + final Header entryDateHeader = cacheEntry.getFirstHeader(HTTP.DATE_HEADER); + final Header responseDateHeader = backendResponse.getFirstHeader(HTTP.DATE_HEADER); + if (entryDateHeader != null && responseDateHeader != null) { + final Date entryDate = DateUtils.parseDate(entryDateHeader.getValue()); + final Date respDate = DateUtils.parseDate(responseDateHeader.getValue()); + if (entryDate == null || respDate == null) { + // either backend response or cached entry did not have a valid + // Date header, so we can't tell if they are out of order + // according to the origin clock; thus we can skip the + // unconditional retry recommended in 13.2.6 of RFC 2616. + return false; + } + if (respDate.before(entryDate)) { + return true; + } + } + return false; + } + + CloseableHttpResponse negotiateResponseFromVariants( + final HttpRoute route, + final HttpRequestWrapper request, + final HttpClientContext context, + final HttpExecutionAware execAware, + final Map variants) throws IOException, HttpException { + final HttpRequestWrapper conditionalRequest = conditionalRequestBuilder + .buildConditionalRequestFromVariants(request, variants); + + final Date requestDate = getCurrentDate(); + final CloseableHttpResponse backendResponse = backend.execute( + route, conditionalRequest, context, execAware); + try { + final Date responseDate = getCurrentDate(); + + backendResponse.addHeader("Via", generateViaHeader(backendResponse)); + + if (backendResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_MODIFIED) { + return handleBackendResponse(request, context, requestDate, responseDate, + backendResponse); + } + + final Header resultEtagHeader = backendResponse.getFirstHeader(HeaderConstants.ETAG); + if (resultEtagHeader == null) { + log.warn("304 response did not contain ETag"); + IOUtils.consume(backendResponse.getEntity()); + backendResponse.close(); + return callBackend(route, request, context, execAware); + } + + final String resultEtag = resultEtagHeader.getValue(); + final Variant matchingVariant = variants.get(resultEtag); + if (matchingVariant == null) { + log.debug("304 response did not contain ETag matching one sent in If-None-Match"); + IOUtils.consume(backendResponse.getEntity()); + backendResponse.close(); + return callBackend(route, request, context, execAware); + } + + final HttpCacheEntry matchedEntry = matchingVariant.getEntry(); + + if (revalidationResponseIsTooOld(backendResponse, matchedEntry)) { + IOUtils.consume(backendResponse.getEntity()); + backendResponse.close(); + return retryRequestUnconditionally(route, request, context, execAware, matchedEntry); + } + + recordCacheUpdate(context); + + final HttpCacheEntry responseEntry = getUpdatedVariantEntry( + context.getTargetHost(), conditionalRequest, requestDate, responseDate, + backendResponse, matchingVariant, matchedEntry); + backendResponse.close(); + + final CloseableHttpResponse resp = responseGenerator.generateResponse(responseEntry); + tryToUpdateVariantMap(context.getTargetHost(), request, matchingVariant); + + if (shouldSendNotModifiedResponse(request, responseEntry)) { + return responseGenerator.generateNotModifiedResponse(responseEntry); + } + return resp; + } catch (final IOException ex) { + backendResponse.close(); + throw ex; + } catch (final RuntimeException ex) { + backendResponse.close(); + throw ex; + } + } + + private CloseableHttpResponse retryRequestUnconditionally( + final HttpRoute route, + final HttpRequestWrapper request, + final HttpClientContext context, + final HttpExecutionAware execAware, + final HttpCacheEntry matchedEntry) throws IOException, HttpException { + final HttpRequestWrapper unconditional = conditionalRequestBuilder + .buildUnconditionalRequest(request, matchedEntry); + return callBackend(route, unconditional, context, execAware); + } + + private HttpCacheEntry getUpdatedVariantEntry( + final HttpHost target, + final HttpRequestWrapper conditionalRequest, + final Date requestDate, + final Date responseDate, + final CloseableHttpResponse backendResponse, + final Variant matchingVariant, + final HttpCacheEntry matchedEntry) throws IOException { + HttpCacheEntry responseEntry = matchedEntry; + try { + responseEntry = responseCache.updateVariantCacheEntry(target, conditionalRequest, + matchedEntry, backendResponse, requestDate, responseDate, matchingVariant.getCacheKey()); + } catch (final IOException ioe) { + log.warn("Could not update cache entry", ioe); + } finally { + backendResponse.close(); + } + return responseEntry; + } + + private void tryToUpdateVariantMap( + final HttpHost target, + final HttpRequestWrapper request, + final Variant matchingVariant) { + try { + responseCache.reuseVariantEntryFor(target, request, matchingVariant); + } catch (final IOException ioe) { + log.warn("Could not update cache entry to reuse variant", ioe); + } + } + + private boolean shouldSendNotModifiedResponse( + final HttpRequestWrapper request, + final HttpCacheEntry responseEntry) { + return (suitabilityChecker.isConditional(request) + && suitabilityChecker.allConditionalsMatch(request, responseEntry, new Date())); + } + + CloseableHttpResponse revalidateCacheEntry( + final HttpRoute route, + final HttpRequestWrapper request, + final HttpClientContext context, + final HttpExecutionAware execAware, + final HttpCacheEntry cacheEntry) throws IOException, HttpException { + + final HttpRequestWrapper conditionalRequest = conditionalRequestBuilder.buildConditionalRequest(request, cacheEntry); + final URI uri = conditionalRequest.getURI(); + if (uri != null) { + try { + request.setURI(URIUtils.rewriteURIForRoute(uri, route)); + } catch (final URISyntaxException ex) { + throw new ProtocolException("Invalid URI: " + uri, ex); + } + } + + Date requestDate = getCurrentDate(); + CloseableHttpResponse backendResponse = backend.execute( + route, conditionalRequest, context, execAware); + Date responseDate = getCurrentDate(); + + if (revalidationResponseIsTooOld(backendResponse, cacheEntry)) { + backendResponse.close(); + final HttpRequestWrapper unconditional = conditionalRequestBuilder + .buildUnconditionalRequest(request, cacheEntry); + requestDate = getCurrentDate(); + backendResponse = backend.execute(route, unconditional, context, execAware); + responseDate = getCurrentDate(); + } + + backendResponse.addHeader(HeaderConstants.VIA, generateViaHeader(backendResponse)); + + final int statusCode = backendResponse.getStatusLine().getStatusCode(); + if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_OK) { + recordCacheUpdate(context); + } + + if (statusCode == HttpStatus.SC_NOT_MODIFIED) { + final HttpCacheEntry updatedEntry = responseCache.updateCacheEntry( + context.getTargetHost(), request, cacheEntry, + backendResponse, requestDate, responseDate); + if (suitabilityChecker.isConditional(request) + && suitabilityChecker.allConditionalsMatch(request, updatedEntry, new Date())) { + return responseGenerator + .generateNotModifiedResponse(updatedEntry); + } + return responseGenerator.generateResponse(updatedEntry); + } + + if (staleIfErrorAppliesTo(statusCode) + && !staleResponseNotAllowed(request, cacheEntry, getCurrentDate()) + && validityPolicy.mayReturnStaleIfError(request, cacheEntry, responseDate)) { + try { + final CloseableHttpResponse cachedResponse = responseGenerator.generateResponse(cacheEntry); + cachedResponse.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\""); + return cachedResponse; + } finally { + backendResponse.close(); + } + } + return handleBackendResponse(conditionalRequest, context, requestDate, responseDate, + backendResponse); + } + + private boolean staleIfErrorAppliesTo(final int statusCode) { + return statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR + || statusCode == HttpStatus.SC_BAD_GATEWAY + || statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE + || statusCode == HttpStatus.SC_GATEWAY_TIMEOUT; + } + + CloseableHttpResponse handleBackendResponse( + final HttpRequestWrapper request, + final HttpClientContext context, + final Date requestDate, + final Date responseDate, + final CloseableHttpResponse backendResponse) throws IOException { + + log.trace("Handling Backend response"); + responseCompliance.ensureProtocolCompliance(request, backendResponse); + + final HttpHost target = context.getTargetHost(); + final boolean cacheable = responseCachingPolicy.isResponseCacheable(request, backendResponse); + responseCache.flushInvalidatedCacheEntriesFor(target, request, backendResponse); + if (cacheable && !alreadyHaveNewerCacheEntry(target, request, backendResponse)) { + storeRequestIfModifiedSinceFor304Response(request, backendResponse); + return responseCache.cacheAndReturnResponse(target, request, + backendResponse, requestDate, responseDate); + } + if (!cacheable) { + try { + responseCache.flushCacheEntriesFor(target, request); + } catch (final IOException ioe) { + log.warn("Unable to flush invalid cache entries", ioe); + } + } + return backendResponse; + } + + /** + * For 304 Not modified responses, adds a "Last-Modified" header with the + * value of the "If-Modified-Since" header passed in the request. This + * header is required to be able to reuse match the cache entry for + * subsequent requests but as defined in http specifications it is not + * included in 304 responses by backend servers. This header will not be + * included in the resulting response. + */ + private void storeRequestIfModifiedSinceFor304Response( + final HttpRequest request, final HttpResponse backendResponse) { + if (backendResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { + final Header h = request.getFirstHeader("If-Modified-Since"); + if (h != null) { + backendResponse.addHeader("Last-Modified", h.getValue()); + } + } + } + + private boolean alreadyHaveNewerCacheEntry(final HttpHost target, final HttpRequestWrapper request, + final HttpResponse backendResponse) { + HttpCacheEntry existing = null; + try { + existing = responseCache.getCacheEntry(target, request); + } catch (final IOException ioe) { + // nop + } + if (existing == null) { + return false; + } + final Header entryDateHeader = existing.getFirstHeader(HTTP.DATE_HEADER); + if (entryDateHeader == null) { + return false; + } + final Header responseDateHeader = backendResponse.getFirstHeader(HTTP.DATE_HEADER); + if (responseDateHeader == null) { + return false; + } + final Date entryDate = DateUtils.parseDate(entryDateHeader.getValue()); + final Date responseDate = DateUtils.parseDate(responseDateHeader.getValue()); + if (entryDate == null || responseDate == null) { + return false; + } + return responseDate.before(entryDate); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.apache.http.impl.client.cache.CachingExec.revalidateCacheEntry` indirectly writes to field `request.org.apache.http.client.methods.HttpRequestWrapper.uri` outside of synchronization. + Reporting because the current class is annotated `@ThreadSafe`, so we assume that this method can run in parallel with other non-private methods in the class (including itself). + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +CloseableHttpResponse CachingExec.revalidateCacheEntry(HttpRoute,HttpRequestWrapper,HttpClientContext,HttpExecutionAware,HttpCacheEntry) + +### Procedure Id: +org.apache.http.impl.client.cache.CachingExec.revalidateCacheEntry(org.apache.http.conn.routing.Http.97c7f8fe25445be5e81d86801ad82d5e + +### File: +httpclient-cache/src/main/java/org/apache/http/impl/client/cache/CachingExec.java + +### Key: +CachingExec.java|revalidateCacheEntry|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +ace70cf0612727a6f990fb718ccd775e + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10305/instruction.md b/inferredbugs-10305/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..392264b967c7aaf0372f707f5ab79d98c69255ae --- /dev/null +++ b/inferredbugs-10305/instruction.md @@ -0,0 +1,966 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** httpcomponents-client +**Bug ID:** 20 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * . + * + */ +package org.apache.http.impl.client.cache; + +import java.io.IOException; +import java.net.URI; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.Header; +import org.apache.http.HeaderElement; +import org.apache.http.HttpHost; +import org.apache.http.HttpMessage; +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.HttpVersion; +import org.apache.http.ProtocolException; +import org.apache.http.ProtocolVersion; +import org.apache.http.RequestLine; +import org.apache.http.annotation.ThreadSafe; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.HttpClient; +import org.apache.http.client.ResponseHandler; +import org.apache.http.client.cache.CacheResponseStatus; +import org.apache.http.client.cache.HeaderConstants; +import org.apache.http.client.cache.HttpCacheEntry; +import org.apache.http.client.cache.HttpCacheStorage; +import org.apache.http.client.cache.ResourceFactory; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.cookie.DateParseException; +import org.apache.http.impl.cookie.DateUtils; +import org.apache.http.message.BasicHttpResponse; +import org.apache.http.params.HttpParams; +import org.apache.http.protocol.HttpContext; +import org.apache.http.util.VersionInfo; + +/** + *

The {@link CachingHttpClient} is meant to be a drop-in replacement for + * a {@link DefaultHttpClient} that transparently adds client-side caching. + * The current implementation is conditionally compliant with HTTP/1.1 + * (meaning all the MUST and MUST NOTs are obeyed), although quite a lot, + * though not all, of the SHOULDs and SHOULD NOTs are obeyed too. Generally + * speaking, you construct a {@code CachingHttpClient} by providing a + * "backend" {@link HttpClient} used for making actual network requests and + * provide an {@link HttpCacheStorage} instance to use for holding onto + * cached responses. Additional configuration options can be provided by + * passing in a {@link CacheConfig}. Note that all of the usual client + * related configuration you want to do vis-a-vis timeouts and connection + * pools should be done on this backend client before constructing a {@code + * CachingHttpClient} from it.

+ * + *

Generally speaking, the {@code CachingHttpClient} is implemented as a + * Decorator + * of the backend client; for any incoming request it attempts to satisfy + * it from the cache, but if it can't, or if it needs to revalidate a stale + * cache entry, it will use the backend client to make an actual request. + * However, a proper HTTP/1.1 cache won't change the semantics of a request + * and response; in particular, if you issue an unconditional request you + * will get a full response (although it may be served to you from the cache, + * or the cache may make a conditional request on your behalf to the origin). + * This notion of "semantic transparency" means you should be able to drop + * a {@link CachingHttpClient} into an existing application without breaking + * anything.

+ * + *

Folks that would like to experiment with alternative storage backends + * should look at the {@link HttpCacheStorage} interface and the related + * package documentation there. You may also be interested in the provided + * {@link org.apache.http.impl.client.cache.ehcache.EhcacheHttpCacheStorage + * EhCache} and {@link + * org.apache.http.impl.client.cache.memcached.MemcachedHttpCacheStorage + * memcached} storage backends.

+ *

+ * @since 4.1 + */ +@ThreadSafe // So long as the responseCache implementation is threadsafe +public class CachingHttpClient implements HttpClient { + + /** + * This is the name under which the {@link + * org.apache.http.client.cache.CacheResponseStatus} of a request + * (for example, whether it resulted in a cache hit) will be recorded if an + * {@link HttpContext} is provided during execution. + */ + public static final String CACHE_RESPONSE_STATUS = "http.cache.response.status"; + + private final static boolean SUPPORTS_RANGE_AND_CONTENT_RANGE_HEADERS = false; + + private final AtomicLong cacheHits = new AtomicLong(); + private final AtomicLong cacheMisses = new AtomicLong(); + private final AtomicLong cacheUpdates = new AtomicLong(); + + private final HttpClient backend; + private final HttpCache responseCache; + private final CacheValidityPolicy validityPolicy; + private final ResponseCachingPolicy responseCachingPolicy; + private final CachedHttpResponseGenerator responseGenerator; + private final CacheableRequestPolicy cacheableRequestPolicy; + private final CachedResponseSuitabilityChecker suitabilityChecker; + + private final ConditionalRequestBuilder conditionalRequestBuilder; + + private final long maxObjectSizeBytes; + private final boolean sharedCache; + + private final ResponseProtocolCompliance responseCompliance; + private final RequestProtocolCompliance requestCompliance; + + private final AsynchronousValidator asynchRevalidator; + + private final Log log = LogFactory.getLog(getClass()); + + CachingHttpClient( + HttpClient client, + HttpCache cache, + CacheConfig config) { + super(); + if (client == null) { + throw new IllegalArgumentException("HttpClient may not be null"); + } + if (cache == null) { + throw new IllegalArgumentException("HttpCache may not be null"); + } + if (config == null) { + throw new IllegalArgumentException("CacheConfig may not be null"); + } + this.maxObjectSizeBytes = config.getMaxObjectSize(); + this.sharedCache = config.isSharedCache(); + this.backend = client; + this.responseCache = cache; + this.validityPolicy = new CacheValidityPolicy(); + this.responseCachingPolicy = new ResponseCachingPolicy(maxObjectSizeBytes, sharedCache); + this.responseGenerator = new CachedHttpResponseGenerator(this.validityPolicy); + this.cacheableRequestPolicy = new CacheableRequestPolicy(); + this.suitabilityChecker = new CachedResponseSuitabilityChecker(this.validityPolicy, config); + this.conditionalRequestBuilder = new ConditionalRequestBuilder(); + + this.responseCompliance = new ResponseProtocolCompliance(); + this.requestCompliance = new RequestProtocolCompliance(); + + this.asynchRevalidator = makeAsynchronousValidator(config); + } + + /** + * Constructs a {@code CachingHttpClient} with default caching settings that + * stores cache entries in memory and uses a vanilla {@link DefaultHttpClient} + * for backend requests. + */ + public CachingHttpClient() { + this(new DefaultHttpClient(), + new BasicHttpCache(), + new CacheConfig()); + } + + /** + * Constructs a {@code CachingHttpClient} with the given caching options that + * stores cache entries in memory and uses a vanilla {@link DefaultHttpClient} + * for backend requests. + * @param config cache module options + */ + public CachingHttpClient(CacheConfig config) { + this(new DefaultHttpClient(), + new BasicHttpCache(config), + config); + } + + /** + * Constructs a {@code CachingHttpClient} with default caching settings that + * stores cache entries in memory and uses the given {@link HttpClient} + * for backend requests. + * @param client used to make origin requests + */ + public CachingHttpClient(HttpClient client) { + this(client, + new BasicHttpCache(), + new CacheConfig()); + } + + /** + * Constructs a {@code CachingHttpClient} with the given caching options that + * stores cache entries in memory and uses the given {@link HttpClient} + * for backend requests. + * @param config cache module options + * @param client used to make origin requests + */ + public CachingHttpClient(HttpClient client, CacheConfig config) { + this(client, + new BasicHttpCache(config), + config); + } + + /** + * Constructs a {@code CachingHttpClient} with the given caching options + * that stores cache entries in the provided storage backend and uses + * the given {@link HttpClient} for backend requests. However, cached + * response bodies are managed using the given {@link ResourceFactory}. + * @param client used to make origin requests + * @param resourceFactory how to manage cached response bodies + * @param storage where to store cache entries + * @param config cache module options + */ + public CachingHttpClient( + HttpClient client, + ResourceFactory resourceFactory, + HttpCacheStorage storage, + CacheConfig config) { + this(client, + new BasicHttpCache(resourceFactory, storage, config), + config); + } + + /** + * Constructs a {@code CachingHttpClient} with the given caching options + * that stores cache entries in the provided storage backend and uses + * the given {@link HttpClient} for backend requests. + * @param client used to make origin requests + * @param storage where to store cache entries + * @param config cache module options + */ + public CachingHttpClient( + HttpClient client, + HttpCacheStorage storage, + CacheConfig config) { + this(client, + new BasicHttpCache(new HeapResourceFactory(), storage, config), + config); + } + + CachingHttpClient( + HttpClient backend, + CacheValidityPolicy validityPolicy, + ResponseCachingPolicy responseCachingPolicy, + HttpCache responseCache, + CachedHttpResponseGenerator responseGenerator, + CacheableRequestPolicy cacheableRequestPolicy, + CachedResponseSuitabilityChecker suitabilityChecker, + ConditionalRequestBuilder conditionalRequestBuilder, + ResponseProtocolCompliance responseCompliance, + RequestProtocolCompliance requestCompliance) { + CacheConfig config = new CacheConfig(); + this.maxObjectSizeBytes = config.getMaxObjectSize(); + this.sharedCache = config.isSharedCache(); + this.backend = backend; + this.validityPolicy = validityPolicy; + this.responseCachingPolicy = responseCachingPolicy; + this.responseCache = responseCache; + this.responseGenerator = responseGenerator; + this.cacheableRequestPolicy = cacheableRequestPolicy; + this.suitabilityChecker = suitabilityChecker; + this.conditionalRequestBuilder = conditionalRequestBuilder; + this.responseCompliance = responseCompliance; + this.requestCompliance = requestCompliance; + this.asynchRevalidator = makeAsynchronousValidator(config); + } + + private AsynchronousValidator makeAsynchronousValidator( + CacheConfig config) { + if (config.getAsynchronousWorkersMax() > 0) { + return new AsynchronousValidator(this, config); + } + return null; + } + + /** + * Reports the number of times that the cache successfully responded + * to an {@link HttpRequest} without contacting the origin server. + * @return the number of cache hits + */ + public long getCacheHits() { + return cacheHits.get(); + } + + /** + * Reports the number of times that the cache contacted the origin + * server because it had no appropriate response cached. + * @return the number of cache misses + */ + public long getCacheMisses() { + return cacheMisses.get(); + } + + /** + * Reports the number of times that the cache was able to satisfy + * a response by revalidating an existing but stale cache entry. + * @return the number of cache revalidations + */ + public long getCacheUpdates() { + return cacheUpdates.get(); + } + + public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException { + HttpContext defaultContext = null; + return execute(target, request, defaultContext); + } + + public T execute(HttpHost target, HttpRequest request, + ResponseHandler responseHandler) throws IOException { + return execute(target, request, responseHandler, null); + } + + public T execute(HttpHost target, HttpRequest request, + ResponseHandler responseHandler, HttpContext context) throws IOException { + HttpResponse resp = execute(target, request, context); + return responseHandler.handleResponse(resp); + } + + public HttpResponse execute(HttpUriRequest request) throws IOException { + HttpContext context = null; + return execute(request, context); + } + + public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException { + URI uri = request.getURI(); + HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); + return execute(httpHost, request, context); + } + + public T execute(HttpUriRequest request, ResponseHandler responseHandler) + throws IOException { + return execute(request, responseHandler, null); + } + + public T execute(HttpUriRequest request, ResponseHandler responseHandler, + HttpContext context) throws IOException { + HttpResponse resp = execute(request, context); + return responseHandler.handleResponse(resp); + } + + public ClientConnectionManager getConnectionManager() { + return backend.getConnectionManager(); + } + + public HttpParams getParams() { + return backend.getParams(); + } + + public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) + throws IOException { + + // default response context + setResponseStatus(context, CacheResponseStatus.CACHE_MISS); + + String via = generateViaHeader(request); + + if (clientRequestsOurOptions(request)) { + setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); + return new OptionsHttp11Response(); + } + + HttpResponse fatalErrorResponse = getFatallyNoncompliantResponse( + request, context); + if (fatalErrorResponse != null) return fatalErrorResponse; + + request = requestCompliance.makeRequestCompliant(request); + request.addHeader("Via",via); + + flushEntriesInvalidatedByRequest(target, request); + + if (!cacheableRequestPolicy.isServableFromCache(request)) { + return callBackend(target, request, context); + } + + HttpCacheEntry entry = satisfyFromCache(target, request); + if (entry == null) { + return handleCacheMiss(target, request, context); + } + + return handleCacheHit(target, request, context, entry); + } + + private HttpResponse handleCacheHit(HttpHost target, HttpRequest request, + HttpContext context, HttpCacheEntry entry) + throws ClientProtocolException, IOException { + recordCacheHit(target, request); + + Date now = getCurrentDate(); + if (suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) { + return generateCachedResponse(request, context, entry, now); + } + + if (!mayCallBackend(request)) { + return generateGatewayTimeout(context); + } + + if (validityPolicy.isRevalidatable(entry)) { + return revalidateCacheEntry(target, request, context, entry, now); + } + return callBackend(target, request, context); + } + + private HttpResponse revalidateCacheEntry(HttpHost target, + HttpRequest request, HttpContext context, HttpCacheEntry entry, + Date now) throws ClientProtocolException { + log.trace("Revalidating the cache entry"); + + try { + if (asynchRevalidator != null + && !staleResponseNotAllowed(request, entry, now) + && validityPolicy.mayReturnStaleWhileRevalidating(entry, now)) { + final HttpResponse resp = generateCachedResponse(request, context, entry, now); + + asynchRevalidator.revalidateCacheEntry(target, request, context, entry); + + return resp; + } + return revalidateCacheEntry(target, request, context, entry); + } catch (IOException ioex) { + return handleRevalidationFailure(request, context, entry, now); + } catch (ProtocolException e) { + throw new ClientProtocolException(e); + } + } + + private HttpResponse handleCacheMiss(HttpHost target, HttpRequest request, + HttpContext context) throws IOException { + recordCacheMiss(target, request); + + if (!mayCallBackend(request)) { + return new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT, + "Gateway Timeout"); + } + + Map variants = + getExistingCacheVariants(target, request); + if (variants != null && variants.size() > 0) { + return negotiateResponseFromVariants(target, request, context, variants); + } + + return callBackend(target, request, context); + } + + private HttpCacheEntry satisfyFromCache(HttpHost target, HttpRequest request) { + HttpCacheEntry entry = null; + try { + entry = responseCache.getCacheEntry(target, request); + } catch (IOException ioe) { + log.warn("Unable to retrieve entries from cache", ioe); + } + return entry; + } + + private HttpResponse getFatallyNoncompliantResponse(HttpRequest request, + HttpContext context) { + HttpResponse fatalErrorResponse = null; + List fatalError = requestCompliance.requestIsFatallyNonCompliant(request); + + for (RequestProtocolError error : fatalError) { + setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); + fatalErrorResponse = requestCompliance.getErrorForRequest(error); + } + return fatalErrorResponse; + } + + private Map getExistingCacheVariants(HttpHost target, + HttpRequest request) { + Map variants = null; + try { + variants = responseCache.getVariantCacheEntriesWithEtags(target, request); + } catch (IOException ioe) { + log.warn("Unable to retrieve variant entries from cache", ioe); + } + return variants; + } + + private void recordCacheMiss(HttpHost target, HttpRequest request) { + cacheMisses.getAndIncrement(); + if (log.isTraceEnabled()) { + RequestLine rl = request.getRequestLine(); + log.trace("Cache miss [host: " + target + "; uri: " + rl.getUri() + "]"); + } + } + + private void recordCacheHit(HttpHost target, HttpRequest request) { + cacheHits.getAndIncrement(); + if (log.isTraceEnabled()) { + RequestLine rl = request.getRequestLine(); + log.trace("Cache hit [host: " + target + "; uri: " + rl.getUri() + "]"); + } + } + + private void recordCacheUpdate(HttpContext context) { + cacheUpdates.getAndIncrement(); + setResponseStatus(context, CacheResponseStatus.VALIDATED); + } + + private void flushEntriesInvalidatedByRequest(HttpHost target, + HttpRequest request) { + try { + responseCache.flushInvalidatedCacheEntriesFor(target, request); + } catch (IOException ioe) { + log.warn("Unable to flush invalidated entries from cache", ioe); + } + } + + private HttpResponse generateCachedResponse(HttpRequest request, + HttpContext context, HttpCacheEntry entry, Date now) { + final HttpResponse cachedResponse; + if (request.containsHeader(HeaderConstants.IF_NONE_MATCH) + || request.containsHeader(HeaderConstants.IF_MODIFIED_SINCE)) { + cachedResponse = responseGenerator.generateNotModifiedResponse(entry); + } else { + cachedResponse = responseGenerator.generateResponse(entry); + } + setResponseStatus(context, CacheResponseStatus.CACHE_HIT); + if (validityPolicy.getStalenessSecs(entry, now) > 0L) { + cachedResponse.addHeader("Warning","110 localhost \"Response is stale\""); + } + return cachedResponse; + } + + private HttpResponse handleRevalidationFailure(HttpRequest request, + HttpContext context, HttpCacheEntry entry, Date now) { + if (staleResponseNotAllowed(request, entry, now)) { + return generateGatewayTimeout(context); + } else { + return unvalidatedCacheHit(context, entry); + } + } + + private HttpResponse generateGatewayTimeout(HttpContext context) { + setResponseStatus(context, CacheResponseStatus.CACHE_MODULE_RESPONSE); + return new BasicHttpResponse(HttpVersion.HTTP_1_1, + HttpStatus.SC_GATEWAY_TIMEOUT, "Gateway Timeout"); + } + + private HttpResponse unvalidatedCacheHit(HttpContext context, + HttpCacheEntry entry) { + final HttpResponse cachedResponse = responseGenerator.generateResponse(entry); + setResponseStatus(context, CacheResponseStatus.CACHE_HIT); + cachedResponse.addHeader(HeaderConstants.WARNING, "111 localhost \"Revalidation failed\""); + return cachedResponse; + } + + private boolean staleResponseNotAllowed(HttpRequest request, + HttpCacheEntry entry, Date now) { + return validityPolicy.mustRevalidate(entry) + || (isSharedCache() && validityPolicy.proxyRevalidate(entry)) + || explicitFreshnessRequest(request, entry, now); + } + + private boolean mayCallBackend(HttpRequest request) { + for (Header h: request.getHeaders("Cache-Control")) { + for (HeaderElement elt : h.getElements()) { + if ("only-if-cached".equals(elt.getName())) { + return false; + } + } + } + return true; + } + + private boolean explicitFreshnessRequest(HttpRequest request, HttpCacheEntry entry, Date now) { + for(Header h : request.getHeaders("Cache-Control")) { + for(HeaderElement elt : h.getElements()) { + if ("max-stale".equals(elt.getName())) { + try { + int maxstale = Integer.parseInt(elt.getValue()); + long age = validityPolicy.getCurrentAgeSecs(entry, now); + long lifetime = validityPolicy.getFreshnessLifetimeSecs(entry); + if (age - lifetime > maxstale) return true; + } catch (NumberFormatException nfe) { + return true; + } + } else if ("min-fresh".equals(elt.getName()) + || "max-age".equals(elt.getName())) { + return true; + } + } + } + return false; + } + + private String generateViaHeader(HttpMessage msg) { + final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client", getClass().getClassLoader()); + final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE; + final ProtocolVersion pv = msg.getProtocolVersion(); + if ("http".equalsIgnoreCase(pv.getProtocol())) { + return String.format("%d.%d localhost (Apache-HttpClient/%s (cache))", + pv.getMajor(), pv.getMinor(), release); + } else { + return String.format("%s/%d.%d localhost (Apache-HttpClient/%s (cache))", + pv.getProtocol(), pv.getMajor(), pv.getMinor(), release); + } + } + + private void setResponseStatus(final HttpContext context, final CacheResponseStatus value) { + if (context != null) { + context.setAttribute(CACHE_RESPONSE_STATUS, value); + } + } + + /** + * Reports whether this {@code CachingHttpClient} implementation + * supports byte-range requests as specified by the {@code Range} + * and {@code Content-Range} headers. + * @return {@code true} if byte-range requests are supported + */ + public boolean supportsRangeAndContentRangeHeaders() { + return SUPPORTS_RANGE_AND_CONTENT_RANGE_HEADERS; + } + + /** + * Reports whether this {@code CachingHttpClient} is configured as + * a shared (public) or non-shared (private) cache. See {@link + * CacheConfig#setSharedCache(boolean)}. + * @return {@code true} if we are behaving as a shared (public) + * cache + */ + public boolean isSharedCache() { + return sharedCache; + } + + Date getCurrentDate() { + return new Date(); + } + + boolean clientRequestsOurOptions(HttpRequest request) { + RequestLine line = request.getRequestLine(); + + if (!HeaderConstants.OPTIONS_METHOD.equals(line.getMethod())) + return false; + + if (!"*".equals(line.getUri())) + return false; + + if (!"0".equals(request.getFirstHeader(HeaderConstants.MAX_FORWARDS).getValue())) + return false; + + return true; + } + + HttpResponse callBackend(HttpHost target, HttpRequest request, HttpContext context) + throws IOException { + + Date requestDate = getCurrentDate(); + + log.trace("Calling the backend"); + HttpResponse backendResponse = backend.execute(target, request, context); + backendResponse.addHeader("Via", generateViaHeader(backendResponse)); + return handleBackendResponse(target, request, requestDate, getCurrentDate(), + backendResponse); + + } + + private boolean revalidationResponseIsTooOld(HttpResponse backendResponse, + HttpCacheEntry cacheEntry) { + final Header entryDateHeader = cacheEntry.getFirstHeader("Date"); + final Header responseDateHeader = backendResponse.getFirstHeader("Date"); + if (entryDateHeader != null && responseDateHeader != null) { + try { + Date entryDate = DateUtils.parseDate(entryDateHeader.getValue()); + Date respDate = DateUtils.parseDate(responseDateHeader.getValue()); + if (respDate.before(entryDate)) return true; + } catch (DateParseException e) { + // either backend response or cached entry did not have a valid + // Date header, so we can't tell if they are out of order + // according to the origin clock; thus we can skip the + // unconditional retry recommended in 13.2.6 of RFC 2616. + } + } + return false; + } + + HttpResponse negotiateResponseFromVariants(HttpHost target, + HttpRequest request, HttpContext context, + Map variants) throws IOException { + HttpRequest conditionalRequest = conditionalRequestBuilder.buildConditionalRequestFromVariants(request, variants); + + Date requestDate = getCurrentDate(); + HttpResponse backendResponse = backend.execute(target, conditionalRequest, context); + Date responseDate = getCurrentDate(); + + backendResponse.addHeader("Via", generateViaHeader(backendResponse)); + + if (backendResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_MODIFIED) { + return handleBackendResponse(target, request, requestDate, responseDate, backendResponse); + } + + Header resultEtagHeader = backendResponse.getFirstHeader(HeaderConstants.ETAG); + if (resultEtagHeader == null) { + log.warn("304 response did not contain ETag"); + return callBackend(target, request, context); + } + + String resultEtag = resultEtagHeader.getValue(); + Variant matchingVariant = variants.get(resultEtag); + if (matchingVariant == null) { + log.debug("304 response did not contain ETag matching one sent in If-None-Match"); + return callBackend(target, request, context); + } + + HttpCacheEntry matchedEntry = matchingVariant.getEntry(); + + if (revalidationResponseIsTooOld(backendResponse, matchedEntry)) { + return retryRequestUnconditionally(target, request, context, + matchedEntry); + } + + recordCacheUpdate(context); + + HttpCacheEntry responseEntry = getUpdatedVariantEntry(target, + conditionalRequest, requestDate, responseDate, backendResponse, + matchingVariant, matchedEntry); + + HttpResponse resp = responseGenerator.generateResponse(responseEntry); + tryToUpdateVariantMap(target, request, matchingVariant); + + if (shouldSendNotModifiedResponse(request, responseEntry)) { + return responseGenerator.generateNotModifiedResponse(responseEntry); + } + + return resp; + } + + private HttpResponse retryRequestUnconditionally(HttpHost target, + HttpRequest request, HttpContext context, + HttpCacheEntry matchedEntry) throws IOException { + HttpRequest unconditional = conditionalRequestBuilder + .buildUnconditionalRequest(request, matchedEntry); + return callBackend(target, unconditional, context); + } + + private HttpCacheEntry getUpdatedVariantEntry(HttpHost target, + HttpRequest conditionalRequest, Date requestDate, + Date responseDate, HttpResponse backendResponse, + Variant matchingVariant, HttpCacheEntry matchedEntry) { + HttpCacheEntry responseEntry = matchedEntry; + try { + responseEntry = responseCache.updateVariantCacheEntry(target, conditionalRequest, + matchedEntry, backendResponse, requestDate, responseDate, matchingVariant.getCacheKey()); + } catch (IOException ioe) { + log.warn("Could not update cache entry", ioe); + } + return responseEntry; + } + + private void tryToUpdateVariantMap(HttpHost target, HttpRequest request, + Variant matchingVariant) { + try { + responseCache.reuseVariantEntryFor(target, request, matchingVariant); + } catch (IOException ioe) { + log.warn("Could not update cache entry to reuse variant", ioe); + } + } + + private boolean shouldSendNotModifiedResponse(HttpRequest request, + HttpCacheEntry responseEntry) { + return (suitabilityChecker.isConditional(request) + && suitabilityChecker.allConditionalsMatch(request, responseEntry, new Date())); + } + + HttpResponse revalidateCacheEntry( + HttpHost target, + HttpRequest request, + HttpContext context, + HttpCacheEntry cacheEntry) throws IOException, ProtocolException { + + HttpRequest conditionalRequest = conditionalRequestBuilder.buildConditionalRequest(request, cacheEntry); + + Date requestDate = getCurrentDate(); + HttpResponse backendResponse = backend.execute(target, conditionalRequest, context); + Date responseDate = getCurrentDate(); + + if (revalidationResponseIsTooOld(backendResponse, cacheEntry)) { + HttpRequest unconditional = conditionalRequestBuilder + .buildUnconditionalRequest(request, cacheEntry); + requestDate = getCurrentDate(); + backendResponse = backend.execute(target, unconditional, context); + responseDate = getCurrentDate(); + } + + backendResponse.addHeader("Via", generateViaHeader(backendResponse)); + + int statusCode = backendResponse.getStatusLine().getStatusCode(); + if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_OK) { + recordCacheUpdate(context); + } + + if (statusCode == HttpStatus.SC_NOT_MODIFIED) { + HttpCacheEntry updatedEntry = responseCache.updateCacheEntry(target, request, cacheEntry, + backendResponse, requestDate, responseDate); + if (suitabilityChecker.isConditional(request) + && suitabilityChecker.allConditionalsMatch(request, updatedEntry, new Date())) { + return responseGenerator.generateNotModifiedResponse(updatedEntry); + } + return responseGenerator.generateResponse(updatedEntry); + } + + if (staleIfErrorAppliesTo(statusCode) + && !staleResponseNotAllowed(request, cacheEntry, getCurrentDate()) + && validityPolicy.mayReturnStaleIfError(request, cacheEntry, responseDate)) { + final HttpResponse cachedResponse = responseGenerator.generateResponse(cacheEntry); + cachedResponse.addHeader(HeaderConstants.WARNING, "110 localhost \"Response is stale\""); + return cachedResponse; + } + + return handleBackendResponse(target, conditionalRequest, requestDate, responseDate, + backendResponse); + } + + private boolean staleIfErrorAppliesTo(int statusCode) { + return statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR + || statusCode == HttpStatus.SC_BAD_GATEWAY + || statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE + || statusCode == HttpStatus.SC_GATEWAY_TIMEOUT; + } + + HttpResponse handleBackendResponse( + HttpHost target, + HttpRequest request, + Date requestDate, + Date responseDate, + HttpResponse backendResponse) throws IOException { + + log.trace("Handling Backend response"); + responseCompliance.ensureProtocolCompliance(request, backendResponse); + + boolean cacheable = responseCachingPolicy.isResponseCacheable(request, backendResponse); + responseCache.flushInvalidatedCacheEntriesFor(target, request, backendResponse); + if (cacheable && + !alreadyHaveNewerCacheEntry(target, request, backendResponse)) { + try { + return responseCache.cacheAndReturnResponse(target, request, backendResponse, requestDate, + responseDate); + } catch (IOException ioe) { + log.warn("Unable to store entries in cache", ioe); + } + } + if (!cacheable) { + try { + responseCache.flushCacheEntriesFor(target, request); + } catch (IOException ioe) { + log.warn("Unable to flush invalid cache entries", ioe); + } + } + return backendResponse; + } + + private boolean alreadyHaveNewerCacheEntry(HttpHost target, HttpRequest request, + HttpResponse backendResponse) { + HttpCacheEntry existing = null; + try { + existing = responseCache.getCacheEntry(target, request); + } catch (IOException ioe) { + // nop + } + if (existing == null) return false; + Header entryDateHeader = existing.getFirstHeader("Date"); + if (entryDateHeader == null) return false; + Header responseDateHeader = backendResponse.getFirstHeader("Date"); + if (responseDateHeader == null) return false; + try { + Date entryDate = DateUtils.parseDate(entryDateHeader.getValue()); + Date responseDate = DateUtils.parseDate(responseDateHeader.getValue()); + return responseDate.before(entryDate); + } catch (DateParseException e) { + } + return false; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +INTERFACE_NOT_THREAD_SAFE + +### Qualifier: +Unprotected call to method of un-annotated interface org.apache.http.HttpMessage. Consider annotating the class with `@ThreadSafe`, adding a lock, or using an interface that is known to be thread-safe. + Reporting because the current class is annotated `@ThreadSafe`. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +HttpResponse CachingHttpClient.execute(HttpHost,HttpRequest,HttpContext) + +### Procedure Id: +org.apache.http.impl.client.cache.CachingHttpClient.execute(org.apache.http.HttpHost,org.apache.http.0b238c37cf1ca012154fb39c6beb58fc + +### File: +httpclient-cache/src/main/java/org/apache/http/impl/client/cache/CachingHttpClient.java + +### Key: +CachingHttpClient.java|execute|INTERFACE_NOT_THREAD_SAFE + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +e88abfda398623912152949dea1eb420 + +### Bug Type Hum: +Interface Not Thread Safe + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1040/instruction.md b/inferredbugs-1040/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..50baac4660f74e56b204d023d3c473871f5defc9 --- /dev/null +++ b/inferredbugs-1040/instruction.md @@ -0,0 +1,338 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** dotNext +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Globalization; +using System.Collections.Generic; +using System.Reflection; +using System.Linq; +using System.Linq.Expressions; + +namespace DotNext.Reflection +{ + /// + /// Represents reflected method. + /// + /// Type of delegate describing signature of the reflected method. + public sealed class Method : MethodInfo, IMethod, IEquatable>, IEquatable + where D : MulticastDelegate + { + private const BindingFlags StaticPublicFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy; + private const BindingFlags StaticNonPublicFlags = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + private const BindingFlags InstancePublicFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy; + private const BindingFlags InstanceNonPublicFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + + private readonly MethodInfo method; + private readonly D invoker; + + private Method(MethodInfo method, Expression[] args, ParameterExpression[] parameters) + { + this.method = method; + invoker = Expression.Lambda(Expression.Call(method, args), parameters).Compile(); + } + + private Method(MethodInfo method, ParameterExpression instance, Expression[] args, ParameterExpression[] parameters) + { + this.method = method; + invoker = Expression.Lambda(Expression.Call(instance, method, args), parameters.Insert(instance, 0)).Compile(); + } + + private Method(MethodInfo method) + { + this.method = method; + this.invoker = Delegates.CreateDelegate(method); + } + + internal Method OfType() => method.DeclaringType.IsAssignableFrom(typeof(T)) ? this : null; + + public sealed override MethodAttributes Attributes => method.Attributes; + public sealed override CallingConventions CallingConvention => method.CallingConvention; + public sealed override bool ContainsGenericParameters => method.ContainsGenericParameters; + public sealed override Delegate CreateDelegate(Type delegateType) => method.CreateDelegate(delegateType); + public sealed override Delegate CreateDelegate(Type delegateType, object target) => method.CreateDelegate(delegateType, target); + public sealed override IEnumerable CustomAttributes => method.CustomAttributes; + public sealed override Type DeclaringType => method.DeclaringType; + public sealed override MethodInfo GetBaseDefinition() => method.GetBaseDefinition(); + public sealed override object[] GetCustomAttributes(bool inherit) => method.GetCustomAttributes(inherit); + public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) => method.GetCustomAttributes(attributeType, inherit); + public sealed override IList GetCustomAttributesData() => method.GetCustomAttributesData(); + public sealed override Type[] GetGenericArguments() => method.GetGenericArguments(); + public sealed override MethodInfo GetGenericMethodDefinition() => method.GetGenericMethodDefinition(); + public sealed override MethodBody GetMethodBody() => method.GetMethodBody(); + public sealed override MethodImplAttributes GetMethodImplementationFlags() => method.GetMethodImplementationFlags(); + public sealed override ParameterInfo[] GetParameters() => method.GetParameters(); + public sealed override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + => method.Invoke(obj, invokeAttr, binder, parameters, culture); + public sealed override bool IsDefined(Type attributeType, bool inherit) + => method.IsDefined(attributeType, inherit); + public sealed override bool IsGenericMethod => method.IsGenericMethod; + public sealed override bool IsGenericMethodDefinition => method.IsGenericMethodDefinition; + public sealed override bool IsSecurityCritical => method.IsSecurityCritical; + public sealed override bool IsSecuritySafeCritical => method.IsSecuritySafeCritical; + public sealed override bool IsSecurityTransparent => method.IsSecurityTransparent; + public sealed override MethodInfo MakeGenericMethod(params Type[] typeArguments) => method.MakeGenericMethod(typeArguments); + public sealed override MemberTypes MemberType => MemberTypes.Method; + public sealed override int MetadataToken => method.MetadataToken; + public sealed override RuntimeMethodHandle MethodHandle => method.MethodHandle; + public sealed override MethodImplAttributes MethodImplementationFlags => method.MethodImplementationFlags; + public sealed override Module Module => method.Module; + public sealed override string Name => method.Name; + public sealed override Type ReflectedType => method.ReflectedType; + public sealed override ParameterInfo ReturnParameter => method.ReturnParameter; + public sealed override Type ReturnType => method.ReturnType; + public sealed override ICustomAttributeProvider ReturnTypeCustomAttributes => method.ReturnTypeCustomAttributes; + + public bool Equals(MethodInfo other) => method == other; + public bool Equals(Method other) => Equals(other?.method); + + public override bool Equals(object other) + { + switch (other) + { + case Method method: + return Equals(method); + case MethodInfo method: + return Equals(method); + default: + return false; + } + } + + public override int GetHashCode() => method.GetHashCode(); + + public static implicit operator D(Method method) => method?.invoker; + + MethodInfo IMember.RuntimeMember => method; + D IMember.Invoker => invoker; + + public override string ToString() => method.ToString(); + + private static Method ReflectStatic(Type declaringType, Type[] parameters, Type returnType, string methodName, bool nonPublic) + { + var targetMethod = declaringType.GetMethod(methodName, + nonPublic ? StaticNonPublicFlags : StaticPublicFlags, + Type.DefaultBinder, + parameters, + Array.Empty()); + return targetMethod is null || returnType != targetMethod.ReturnType ? null : new Method(targetMethod); + } + + private static Method ReflectStatic(Type declaringType, Type argumentsType, Type returnType, string methodName, bool nonPublic) + { + var (parameters, arglist, input) = Signature.Reflect(argumentsType); + var targetMethod = declaringType.GetMethod(methodName, + nonPublic ? StaticNonPublicFlags : StaticPublicFlags, + Type.DefaultBinder, + parameters, + Array.Empty()); + return targetMethod is null || returnType != targetMethod.ReturnType ? null : new Method(targetMethod, arglist, new[]{ input }); + } + + private static Type NonRefType(Type type) => type.IsByRef ? type.GetElementType() : type; + + private static Method ReflectInstance(Type thisParam, Type[] parameters, Type returnType, string methodName, bool nonPublic) + { + var targetMethod = NonRefType(thisParam).GetMethod(methodName, + nonPublic ? InstanceNonPublicFlags : InstancePublicFlags, + Type.DefaultBinder, + parameters, + Array.Empty()); + + //this parameter can be passed as REF so handle this situation + //first parameter should be passed by REF for structure types + if(targetMethod is null || returnType != targetMethod.ReturnType) + return null; + else if(thisParam.IsByRef ^ thisParam.IsValueType) + { + var thisParamDeclaration = Expression.Parameter(thisParam); + var parametersDeclaration = parameters.Convert(Expression.Parameter); + return new Method(targetMethod, thisParamDeclaration, parametersDeclaration, parametersDeclaration); + } + else + return new Method(targetMethod); + } + + private static Method ReflectInstance(Type thisParam, Type argumentsType, Type returnType, string methodName, bool nonPublic) + { + var (parameters, arglist, input) = Signature.Reflect(argumentsType); + var thisParamDeclaration = Expression.Parameter(thisParam.MakeByRefType()); + var targetMethod = thisParam.GetMethod(methodName, + nonPublic ? InstanceNonPublicFlags : InstancePublicFlags, + Type.DefaultBinder, + parameters, + Array.Empty()); + return targetMethod is null || returnType != targetMethod.ReturnType ? null : new Method(targetMethod, thisParamDeclaration, arglist, new[]{ input }); + } + + /// + /// Reflects instance method. + /// + /// + /// + /// + internal static Method Reflect(string methodName, bool nonPublic) + { + var delegateType = typeof(D); + if (delegateType.IsAbstract) + throw new AbstractDelegateException(); + else if (delegateType.IsGenericInstanceOf(typeof(Function<,,>)) && delegateType.GetGenericArguments().Take(out var thisParam, out var argumentsType, out var returnType) == 3L) + return ReflectInstance(thisParam, argumentsType, returnType, methodName, nonPublic); + else if(delegateType.IsGenericInstanceOf(typeof(Procedure<,>)) && delegateType.GetGenericArguments().Take(out thisParam, out argumentsType) == 2L) + return ReflectInstance(thisParam, argumentsType, typeof(void), methodName, nonPublic); + else + { + Delegates.GetInvokeMethod().Decompose(Methods.GetParameterTypes, method => method.ReturnType, out var parameters, out returnType); + thisParam = parameters.FirstOrDefault() ?? throw new ArgumentException("Delegate type should have THIS parameter"); + return ReflectInstance(thisParam, parameters.RemoveFirst(1), returnType, methodName, nonPublic); + } + } + + /// + /// Reflects static method. + /// + /// Name of method. + /// True to reflect non-public static method. + /// Declaring type. + /// Reflected static method. + internal static Method Reflect(string methodName, bool nonPublic) + { + var delegateType = typeof(D); + if (delegateType.IsAbstract) + throw new AbstractDelegateException(); + else if (delegateType.IsGenericInstanceOf(typeof(Function<,>)) && delegateType.GetGenericArguments().Take(out var argumentsType, out var returnType) == 2L) + return ReflectStatic(typeof(T), argumentsType, returnType, methodName, nonPublic); + else if(delegateType.IsGenericInstanceOf(typeof(Procedure<>))) + return ReflectStatic(typeof(T), delegateType.GetGenericArguments()[0], typeof(void), methodName, nonPublic); + else + { + Delegates.GetInvokeMethod().Decompose(Methods.GetParameterTypes, method => method.ReturnType, out var parameters, out returnType); + return ReflectStatic(typeof(T), parameters, returnType, methodName, nonPublic); + } + } + + private static Method UnreflectStatic(MethodInfo method) + { + var delegateType = typeof(D); + if(delegateType.IsGenericInstanceOf(typeof(Function<,>)) && delegateType.GetGenericArguments().Take(out var argumentsType, out var returnType) == 2L) + { + var (parameters, arglist, input) = Signature.Reflect(argumentsType); + return returnType == method.ReturnType && method.SignatureEquals(parameters) ? new Method(method, arglist, new[]{ input }) : null; + } + else if(delegateType.IsGenericInstanceOf(typeof(Procedure<>))) + { + argumentsType = delegateType.GetGenericArguments()[0]; + var (parameters, arglist, input) = Signature.Reflect(argumentsType); + return typeof(void) == method.ReturnType && method.SignatureEquals(parameters) ? new Method(method, arglist, new[]{ input }) : null; + } + else if(Delegates.GetInvokeMethod().SignatureEquals(method)) + return new Method(method); + else + return null; + } + + private static Method UnreflectInstance(MethodInfo method) + { + var delegateType = typeof(D); + if(delegateType.IsGenericInstanceOf(typeof(Function<,,>)) && delegateType.GetGenericArguments().Take(out var thisParam, out var argumentsType, out var returnType) == 3L) + { + var (parameters, arglist, input) = Signature.Reflect(argumentsType); + return thisParam.IsAssignableFrom(method.DeclaringType) && returnType == method.ReturnType && method.SignatureEquals(parameters) ? new Method(method, Expression.Parameter(thisParam.MakeByRefType(), "this"), arglist, new[]{ input }) : null; + } + else if(delegateType.IsGenericInstanceOf(typeof(Procedure<,>)) && delegateType.GetGenericArguments().Take(out thisParam, out argumentsType) == 2L) + { + var (parameters, arglist, input) = Signature.Reflect(argumentsType); + return thisParam.IsAssignableFrom(method.DeclaringType) && typeof(void) == method.ReturnType && method.SignatureEquals(parameters) ? new Method(method, Expression.Parameter(thisParam.MakeByRefType(), "this"), arglist, new[]{ input }) : null; + } + else if(delegateType.IsGenericInstanceOf(typeof(MemberGetter<,>)) && delegateType.GetGenericArguments().Take(out thisParam, out returnType) == 2L) + { + var thisParamDecl = Expression.Parameter(thisParam.MakeByRefType(), "this"); + return method.DeclaringType.IsAssignableFrom(thisParam) && returnType == method.ReturnType && method.GetParameters().IsNullOrEmpty() ? new Method(method, thisParamDecl, Array.Empty(), Array.Empty()) : null; + } + else if(delegateType.IsGenericInstanceOf(typeof(MemberSetter<,>)) && delegateType.GetGenericArguments().Take(out thisParam, out argumentsType) == 2L) + { + var thisParamDecl = Expression.Parameter(thisParam.MakeByRefType(), "this"); + var argDecl = Expression.Parameter(argumentsType); + return thisParam.IsAssignableFrom(method.DeclaringType) && method.GetParameterTypes().FirstOrDefault() == argumentsType && method.ReturnType == typeof(void) ? new Method(method, thisParamDecl, new[] { argDecl }, new[] { argDecl }) : null; + } + else + { + Delegates.GetInvokeMethod().Decompose(Methods.GetParameterTypes, m => m.ReturnType, out var parameters, out returnType); + thisParam = parameters.FirstOrDefault() ?? throw new ArgumentException("Delegate type should have THIS parameter"); + parameters = parameters.RemoveFirst(1); + return method.SignatureEquals(parameters) && method.ReturnType == returnType && method.DeclaringType.IsAssignableFrom(thisParam) ? + new Method(method) : + null; + } + } + + internal static Method Unreflect(MethodInfo method) + { + var delegateType = typeof(D); + if (delegateType.IsAbstract) + throw new AbstractDelegateException(); + else if (method is Method existing) + return existing; + else if (method.IsGenericMethodDefinition || method.IsAbstract || method.IsConstructor) + return null; + else if (method.IsStatic) + return UnreflectStatic(method); + else + return UnreflectInstance(method); + } + } +} +``` + +### Bug Type: +PULSE_UNINITIALIZED_VALUE + +### Qualifier: +`argumentsType` is read without initialization. + +### Severity: +ERROR + +### Procedure: +Method`1 Method`1.UnreflectStatic(MethodInfo) + +### File: +DotNext.Reflection/Reflection/Method.cs + +### Key: +Method.cs|UnreflectStatic|PULSE_UNINITIALIZED_VALUE + +### Hash: +cd7bbf29a4d540a87c448b6644c0de3b + +### Bug Type Hum: +Uninitialized Value + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10410/instruction.md b/inferredbugs-10410/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..75819283d4b44153459ecc97daa3cbd21e3ead38 --- /dev/null +++ b/inferredbugs-10410/instruction.md @@ -0,0 +1,736 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** AppiumTestDistribution +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.appium.manager; + +import com.annotation.values.SkipIf; +import com.appium.ios.IOSDeviceConfiguration; +import com.appium.utils.ImageUtils; +import com.relevantcodes.extentreports.ExtentTest; +import com.relevantcodes.extentreports.LogStatus; +import com.report.factory.ExtentManager; +import com.report.factory.ExtentTestManager; +import io.appium.java_client.AppiumDriver; +import io.appium.java_client.MobileElement; +import io.appium.java_client.android.AndroidDriver; +import io.appium.java_client.ios.IOSDriver; +import io.appium.java_client.remote.AndroidMobileCapabilityType; +import io.appium.java_client.remote.IOSMobileCapabilityType; +import io.appium.java_client.remote.MobileCapabilityType; +import io.appium.java_client.service.local.AppiumServiceBuilder; +import org.apache.commons.io.FileUtils; +import org.im4java.core.IM4JavaException; +import org.openqa.selenium.By; +import org.openqa.selenium.OutputType; +import org.openqa.selenium.TakesScreenshot; +import org.openqa.selenium.logging.LogEntry; +import org.openqa.selenium.remote.DesiredCapabilities; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.testng.ITestListener; +import org.testng.ITestResult; +import org.testng.SkipException; +import org.testng.TestListenerAdapter; + +import java.awt.*; +import java.io.*; +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.*; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; + + +public class AppiumParallelTest extends TestListenerAdapter implements ITestListener { + public AppiumDriver driver = null; + public AppiumManager appiumMan = new AppiumManager(); + public String device_udid; + public List logEntries; + public File logFile; + public PrintWriter log_file_writer; + public DesiredCapabilities capabilities = new DesiredCapabilities(); + public String category = null; + public ExtentTest parent; + public ExtentTest child; + public String deviceModel; + public File scrFile = null; + String screenShotNameWithTimeStamp; + + private Map parentContext = new HashMap(); + private static ArrayList devices = new ArrayList(); + public static Properties prop = new Properties(); + public static IOSDeviceConfiguration iosDevice = new IOSDeviceConfiguration(); + public static AndroidDeviceConfiguration androidDevice = new AndroidDeviceConfiguration(); + public static ConcurrentHashMap deviceMapping = + new ConcurrentHashMap(); + public ImageUtils imageUtils = new ImageUtils(); + + static { + try { + prop.load(new FileInputStream("config.properties")); + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.getIOSUDID() != null) { + System.out.println("Adding iOS devices"); + devices.addAll(iosDevice.getIOSUDID()); + } + if (androidDevice.getDeviceSerial() != null) { + System.out.println("Adding Android devices"); + devices.addAll(androidDevice.getDeviceSerial()); + } + } else { + if (androidDevice.getDeviceSerial() != null) { + System.out.println("Adding Android devices"); + devices.addAll(androidDevice.getDeviceSerial()); + } + } + for (String device : devices) { + deviceMapping.put(device, true); + } + System.out.println(deviceMapping); + } catch (IOException e) { + e.printStackTrace(); + System.out.println("Failed to initialize framework"); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Failed to initialize framework"); + } + } + + public static synchronized String getNextAvailableDeviceId() { + ConcurrentHashMap.KeySetView devices = deviceMapping.keySet(); + int i = 0; + for (String device : devices) { + Thread t = Thread.currentThread(); + t.setName("Thread_" + i); + System.out.println("Parallel Thread is::" + t.getName()); + i++; + if (deviceMapping.get(device) == true) { + deviceMapping.put(device, false); + return device; + } + } + return null; + } + + + public static void freeDevice(String deviceId) { + deviceMapping.put(deviceId, true); + } + + public synchronized AppiumServiceBuilder startAppiumServer(String methodName) throws Exception { + device_udid = getNextAvailableDeviceId(); + if (device_udid == null) { + System.out.println("No devices are free to run test or Failed to run test"); + return null; + } + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.checkiOSDevice(device_udid)) { + iosDevice.setIOSWebKitProxyPorts(device_udid); + category = iosDevice.getDeviceName(device_udid).replace(" ", "_"); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + category = androidDevice.getDeviceModel(device_udid); + System.out.println(category); + } + } else { + category = androidDevice.getDeviceModel(device_udid); + } + + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + parent = ExtentTestManager.startTest(methodName, "Mobile Appium Test", + category + "_" + device_udid.replaceAll("\\W", "_")); + parentContext.put(Thread.currentThread().getId(), parent); + ExtentTestManager.getTest().log(LogStatus.INFO, "AppiumServerLogs", + "Logs"); + } + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.checkiOSDevice(device_udid)) { + String webKitPort = iosDevice.startIOSWebKit(device_udid); + return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + return appiumMan.appiumServerForAndroid(device_udid, methodName); + } + } else { + return appiumMan.appiumServerForAndroid(device_udid, methodName); + } + return null; + } + + + public synchronized AppiumDriver startAppiumServerInParallel(String methodName) + throws Exception { + ExtentTestManager.loadConfig(); + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + child = ExtentTestManager.startTest(methodName.toString()) + .assignCategory(category + "_" + device_udid.replaceAll("\\W", "_")); + } + Thread.sleep(3000); + startingServerInstance(); + return driver; + } + + public synchronized AppiumDriver startAppiumServerInParallel(String methodName, + DesiredCapabilities iosCaps, DesiredCapabilities androidCaps) throws Exception { + ExtentTestManager.loadConfig(); + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + child = ExtentTestManager.startTest(methodName.toString()) + .assignCategory(category + "_" + device_udid.replaceAll("\\W", "_")); + } + Thread.sleep(3000); + startingServerInstance(iosCaps, androidCaps); + return driver; + } + + public synchronized AppiumDriver startAppiumServerInParallel(String methodName, + DesiredCapabilities caps) throws Exception { + ExtentTestManager.loadConfig(); + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + child = ExtentTestManager.startTest(methodName.toString()) + .assignCategory(category + "_" + device_udid.replaceAll("\\W", "_")); + } + startingServerInstance(caps); + return driver; + } + + public void startingServerInstance() throws Exception { + if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb()); + } else { + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.checkiOSDevice(device_udid)) { + driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative()); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative()); + } + } else { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative()); + } + } + } + + public void startingServerInstance(DesiredCapabilities caps) throws Exception { + if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb()); + } else { + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (caps.asMap().get("bundleId") != null) { + driver = new IOSDriver<>(appiumMan.getAppiumUrl(), caps); + } else { + checkSelendroid(caps); + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), caps); + } + } else { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), caps); + } + } + } + + public void startingServerInstance(DesiredCapabilities iosCaps, DesiredCapabilities androidCaps) + throws Exception { + if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb()); + } else { + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.checkiOSDevice(device_udid)) { + driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosCaps); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + checkSelendroid(androidCaps); + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidCaps); + } + } else { + checkSelendroid(androidCaps); + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidCaps); + } + } + } + + public DesiredCapabilities checkSelendroid(DesiredCapabilities androidCaps) { + int android_api = 0; + try { + String deviceAPI = androidDevice.getDevices().get(device_udid); + android_api = Integer.parseInt(deviceAPI); + } catch (Exception e) { + e.printStackTrace(); + } + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("Android API Level::" + android_api); + if (android_api <= 16) { + androidCaps.setCapability(MobileCapabilityType.AUTOMATION_NAME, "Selendroid"); + } + return androidCaps; + } + + public void startLogResults(String methodName) + throws FileNotFoundException, FileNotFoundException { + if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) { + System.out.println("Starting ADB logs" + device_udid); + logEntries = driver.manage().logs().get("logcat").filter(Level.ALL); + logFile = new File(System.getProperty("user.dir") + "/target/adblogs/" + device_udid + .replaceAll("\\W", "_") + "__" + methodName + ".txt"); + log_file_writer = new PrintWriter(logFile); + } + } + + public void endLogTestResults(ITestResult result) throws IOException, InterruptedException { + + final String classNameCur = result.getName().split(" ")[2].substring(1); + final Package[] packages = Package.getPackages(); + String className = null; + for (final Package p : packages) { + final String pack = p.getName(); + final String tentative = pack + "." + classNameCur; + try { + Class.forName(tentative); + } catch (final ClassNotFoundException e) { + continue; + } + className = tentative; + break; + } + + + if (result.isSuccess()) { + ExtentTestManager.getTest() + .log(LogStatus.PASS, result.getMethod().getMethodName(), "Pass"); + if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) { + log_file_writer.println(logEntries); + log_file_writer.flush(); + ExtentTestManager.getTest().log(LogStatus.INFO, result.getMethod().getMethodName(), + "ADBLogs:: AdbLogs"); + System.out.println(driver.getSessionId() + ": Saving device log - Done."); + } + + } + if (result.getStatus() == ITestResult.FAILURE) { + ExtentTestManager.getTest() + .log(LogStatus.FAIL, result.getMethod().getMethodName(), result.getThrowable()); + if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) { + System.out.println("im in"); + deviceModel = androidDevice.getDeviceModel(device_udid); + //captureScreenshot(result.getMethod().getMethodName(), "android", className); + captureScreenShot(result.getMethod().getMethodName(), result.getStatus(), + result.getTestClass().getName()); + } else if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + deviceModel = iosDevice.getIOSDeviceProductTypeAndVersion(device_udid); + captureScreenShot(result.getMethod().getMethodName(), result.getStatus(), + result.getTestClass().getName()); + } + + if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) { + File framedImageAndroid = new File( + System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod() + .getMethodName() + "/" + screenShotNameWithTimeStamp + deviceModel + + "_failed_" + result.getMethod().getMethodName() + "_framed.png"); + if (framedImageAndroid.exists()) { + ExtentTestManager.getTest() + .log(LogStatus.INFO, result.getMethod().getMethodName(), + "Snapshot below: " + ExtentTestManager.getTest().addScreenCapture( + System.getProperty("user.dir") + "/target/screenshot/android/" + + device_udid.replaceAll("\\W", "_") + "/" + className + "/" + + result.getMethod().getMethodName() + "/" + + screenShotNameWithTimeStamp + deviceModel + "_failed_" + + result.getMethod().getMethodName() + "_framed.png")); + } else { + ExtentTestManager.getTest() + .log(LogStatus.INFO, result.getMethod().getMethodName(), + "Snapshot below: " + ExtentTestManager.getTest().addScreenCapture( + System.getProperty("user.dir") + "/target/screenshot/android/" + + device_udid.replaceAll("\\W", "_") + "/" + className + "/" + + result.getMethod().getMethodName() + "/" + + screenShotNameWithTimeStamp + deviceModel + "_" + result + .getMethod().getMethodName() + "_failed.png")); + } + + + } + if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + File framedImageIOS = new File( + System.getProperty("user.dir") + "/target/screenshot/iOS/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod() + .getMethodName() + "/" + screenShotNameWithTimeStamp + deviceModel + + "_failed_" + result.getMethod().getMethodName() + "_framed.png"); + if (framedImageIOS.exists()) { + ExtentTestManager.getTest() + .log(LogStatus.INFO, result.getMethod().getMethodName(), + "Snapshot below: " + ExtentTestManager.getTest().addScreenCapture( + System.getProperty("user.dir") + "/target/screenshot/iOS/" + + device_udid.replaceAll("\\W", "_") + "/" + className + "/" + + result.getMethod().getMethodName() + "/" + + screenShotNameWithTimeStamp + deviceModel + "_failed_" + + result.getMethod().getMethodName() + "_framed.png")); + } else { + ExtentTestManager.getTest() + .log(LogStatus.INFO, result.getMethod().getMethodName(), + "Snapshot below: " + ExtentTestManager.getTest().addScreenCapture( + System.getProperty("user.dir") + "/target/screenshot/iOS/" + + device_udid.replaceAll("\\W", "_") + "/" + className + "/" + + result.getMethod().getMethodName() + "/" + + screenShotNameWithTimeStamp + deviceModel + "_" + result + .getMethod().getMethodName() + "_failed.png")); + } + + } + + + if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) { + log_file_writer.println(logEntries); + log_file_writer.flush(); + ExtentTestManager.getTest().log(LogStatus.INFO, result.getMethod().getMethodName(), + "ADBLogs:: AdbLogs"); + System.out.println(driver.getSessionId() + ": Saving device log - Done."); + } + + } + if (result.getStatus() == ITestResult.SKIP) { + ExtentTestManager.getTest().log(LogStatus.SKIP, "Test skipped"); + } + parentContext.get(Thread.currentThread().getId()).appendChild(child); + ExtentManager.getInstance().flush(); + } + + public synchronized void killAppiumServer() throws InterruptedException, IOException { + System.out.println( + "**************ClosingAppiumSession****************" + Thread.currentThread().getId()); + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + ExtentManager.getInstance().endTest(parent); + ExtentManager.getInstance().flush(); + } + appiumMan.destroyAppiumNode(); + if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + iosDevice.destroyIOSWebKitProxy(); + } + freeDevice(device_udid); + } + + protected String getStackTrace(Throwable t) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + return sw.toString(); + } + + public void waitForElement(By id, int time) { + WebDriverWait wait = new WebDriverWait(driver, 20); + wait.until(ExpectedConditions.elementToBeClickable((id))); + } + + public void resetAppData() throws InterruptedException, IOException { + androidDevice.clearAppData(device_udid, prop.getProperty("APP_PACKAGE")); + } + + public void closeOpenApp() throws InterruptedException, IOException { + androidDevice.closeRunningApp(device_udid, prop.getProperty("APP_PACKAGE")); + } + + public void removeApkFromDevice(String app_package) throws Exception { + androidDevice.removeApkFromDevices(device_udid, app_package); + } + + + public synchronized DesiredCapabilities androidNative() { + System.out.println("Setting Android Desired Capabilities:"); + DesiredCapabilities androidCapabilities = new DesiredCapabilities(); + androidCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android"); + androidCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "5.X"); + androidCapabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, + prop.getProperty("APP_ACTIVITY")); + androidCapabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, + prop.getProperty("APP_PACKAGE")); + androidCapabilities.setCapability("browserName", ""); + checkSelendroid(androidCapabilities); + androidCapabilities + .setCapability(MobileCapabilityType.APP, prop.getProperty("ANDROID_APP_PATH")); + androidCapabilities.setCapability(MobileCapabilityType.UDID, device_udid); + return androidCapabilities; + } + + public synchronized DesiredCapabilities androidWeb() { + DesiredCapabilities androidWebCapabilities = new DesiredCapabilities(); + androidWebCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android"); + androidWebCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "5.0.X"); + // If you want the tests on real device, make sure chrome browser is + // installed + androidWebCapabilities + .setCapability(MobileCapabilityType.BROWSER_NAME, prop.getProperty("BROWSER_TYPE")); + androidWebCapabilities.setCapability(MobileCapabilityType.TAKES_SCREENSHOT, true); + return androidWebCapabilities; + } + + public synchronized DesiredCapabilities iosNative() { + DesiredCapabilities iOSCapabilities = new DesiredCapabilities(); + System.out.println("Setting iOS Desired Capabilities:"); + iOSCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "9.0"); + iOSCapabilities.setCapability(MobileCapabilityType.APP, prop.getProperty("IOS_APP_PATH")); + iOSCapabilities + .setCapability(IOSMobileCapabilityType.BUNDLE_ID, prop.getProperty("BUNDLE_ID")); + iOSCapabilities.setCapability(IOSMobileCapabilityType.AUTO_ACCEPT_ALERTS, true); + iOSCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone"); + iOSCapabilities.setCapability(MobileCapabilityType.UDID, device_udid); + return iOSCapabilities; + } + + public void deleteAppIOS(String bundleID) throws InterruptedException, IOException { + iosDevice.unInstallApp(device_udid, bundleID); + } + + public void installAppIOS(String appPath) throws InterruptedException, IOException { + iosDevice.installApp(device_udid, appPath); + } + + public Boolean checkAppIsInstalled(String bundleID) throws InterruptedException, IOException { + return iosDevice.checkIfAppIsInstalled(bundleID); + } + + + public AppiumDriver getDriver() { + return driver; + } + + public void onTestStart(ITestResult result) { + Object currentClass = result.getInstance(); + AppiumDriver driver = ((AppiumParallelTest) currentClass).getDriver(); + SkipIf skip = + result.getMethod().getConstructorOrMethod().getMethod().getAnnotation(SkipIf.class); + if (skip != null) { + String info = skip.platform(); + if (driver.toString().split("\\(")[0].trim().toString().contains(info)) { + System.out.println("skipping test"); + throw new SkipException("Skipped because property was set to :::" + info); + } + } + } + + public static Image getImage(final String pathAndFileName) { + final URL url = Thread.currentThread().getContextClassLoader().getResource(pathAndFileName); + return Toolkit.getDefaultToolkit().getImage(url); + } + + public void captureScreenshot(String methodName, String device, String className) + throws IOException, InterruptedException { + String context = getDriver().getContext(); + boolean contextChanged = false; + if (getDriver().toString().split(":")[0].trim().equals("AndroidDriver") + && !context.equals("NATIVE_APP")) { + getDriver().context("NATIVE_APP"); + contextChanged = true; + } + scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); + if (contextChanged) { + getDriver().context(context); + } + FileUtils.copyFile(scrFile, new File( + System.getProperty("user.dir") + "/target/screenshot/" + device + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + deviceModel + + "_" + methodName + "_failed" + ".png")); + Thread.sleep(3000); + } + + public void logger(String message) { + ExtentTestManager.logger(message); + } + + public void captureScreenShot(String screenShotName, int status, String className, + String methodName) throws IOException, InterruptedException { + String context = getDriver().getContext(); + boolean contextChanged = false; + if (getDriver().toString().split(":")[0].trim().equals("AndroidDriver") + && !context.equals("NATIVE_APP")) { + getDriver().context("NATIVE_APP"); + contextChanged = true; + } + File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); + if (contextChanged) { + getDriver().context(context); + } + StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); + screenShotNameWithTimeStamp = currentDateAndTime(); + if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) { + String androidModel = + screenShotNameWithTimeStamp + androidDevice.getDeviceModel(device_udid); + screenShotAndFrame(screenShotName, status, scrFile, methodName, className, androidModel, + "android"); + } else if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + String iosModel = screenShotNameWithTimeStamp + iosDevice + .getIOSDeviceProductTypeAndVersion(device_udid); + screenShotAndFrame(screenShotName, status, scrFile, methodName, className, iosModel, + "iOS"); + } + } + + public void captureScreenShot(String screenShotName, int status, String screenClassName) + throws IOException, InterruptedException { + captureScreenShot(screenShotName, status, screenClassName, screenShotName); + } + + public void captureScreenShot(String screenShotName) throws InterruptedException, IOException { + String methodName = new Exception().getStackTrace()[1].getMethodName(); + String className = new Exception().getStackTrace()[1].getClassName(); + captureScreenShot(screenShotName, 1, className, methodName); + } + + public void screenShotAndFrame(String screenShotName, int status, File scrFile, + String methodName, String className, String model, String platform) { + String failedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + + screenShotNameWithTimeStamp + deviceModel + "_" + methodName + "_failed" + ".png"; + String capturedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + screenShotName + + ".png"; + String framedCapturedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + model + "_" + + screenShotName + "_results.png"; + String framedFailedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + model + + "_failed_" + methodName + "_framed.png"; + + try { + File framePath = + new File(System.getProperty("user.dir") + "/src/test/resources/frames/"); + if (status == ITestResult.FAILURE) { + FileUtils.copyFile(scrFile, new File(failedScreen)); + } else { + FileUtils.copyFile(scrFile, new File(capturedScreen)); + } + + File[] files1 = framePath.listFiles(); + if (framePath.exists()) { + for (int i = 0; i < files1.length; i++) { + if (files1[i].isFile()) { //this line weeds out other directories/folders + System.out.println(files1[i]); + + Path p = Paths.get(files1[i].toString()); + String fileName = p.getFileName().toString().toLowerCase(); + if (model.toString().toLowerCase() + .contains(fileName.split(".png")[0].toLowerCase())) { + try { + if (status == ITestResult.FAILURE) { + String screenToFrame = failedScreen; + imageUtils.wrapDeviceFrames(files1[i].toString(), screenToFrame, + framedFailedScreen); + ExtentTestManager.logOutPut(framedFailedScreen, + screenShotName.toUpperCase()); + File fileToDelete = new File(screenToFrame); + fileToDelete.delete(); + } else { + String screenToFrame = capturedScreen; + imageUtils.wrapDeviceFrames(files1[i].toString(), screenToFrame, + framedCapturedScreen); + ExtentTestManager.logOutPut(framedCapturedScreen, + screenShotName.toUpperCase()); + File fileToDelete = new File(screenToFrame); + fileToDelete.delete(); + } + + break; + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (IM4JavaException e) { + e.printStackTrace(); + } + } + } + } + } + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public String currentDateAndTime() { + LocalDateTime now = LocalDateTime.now(); + DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME; + return now.truncatedTo(ChronoUnit.SECONDS).format(dtf); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.lang.Process` acquired to `com.appium.utils.CommandPrompt.p` by call to `checkiOSDevice(...)` at line 132 is not released after line 149. +**Note**: potential exception at line 129 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +AppiumServiceBuilder AppiumParallelTest.startAppiumServer(String) + +### Procedure Id: +com.appium.manager.AppiumParallelTest.startAppiumServer(java.lang.String):io.appium.java_client.serv.7ffa8619cf50bee466b6dbdf53c80c20 + +### File: +src/main/java/com/appium/manager/AppiumParallelTest.java + +### Key: +AppiumParallelTest.java|startAppiumServer|RESOURCE_LEAK + +### Node Key: +8f3ce21e00809294f8fa2c93c169621c + +### Hash: +e5e1dc40f8fd5f34757fefc3f2b5fdd6 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10411/instruction.md b/inferredbugs-10411/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..01e660d5b4262404970acddc586616939ba74824 --- /dev/null +++ b/inferredbugs-10411/instruction.md @@ -0,0 +1,963 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** AppiumTestDistribution +**Bug ID:** 27 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.appium.manager; + +import com.annotation.values.Author; +import com.annotation.values.Description; +import com.annotation.values.SkipIf; +import com.appium.ios.IOSDeviceConfiguration; +import com.appium.utils.ImageUtils; +import com.appium.utils.MobilePlatform; +import com.aventstack.extentreports.ExtentTest; +import com.aventstack.extentreports.Status; +import com.report.factory.ExtentManager; +import com.report.factory.ExtentTestManager; +import com.video.recorder.Flick; +import io.appium.java_client.AppiumDriver; +import io.appium.java_client.MobileElement; +import io.appium.java_client.android.AndroidDriver; +import io.appium.java_client.ios.IOSDriver; +import io.appium.java_client.remote.AndroidMobileCapabilityType; +import io.appium.java_client.remote.IOSMobileCapabilityType; +import io.appium.java_client.remote.MobileCapabilityType; +import io.appium.java_client.service.local.AppiumServiceBuilder; +import org.apache.commons.io.FileUtils; +import org.im4java.core.IM4JavaException; +import org.openqa.selenium.By; +import org.openqa.selenium.OutputType; +import org.openqa.selenium.TakesScreenshot; +import org.openqa.selenium.logging.LogEntry; +import org.openqa.selenium.remote.DesiredCapabilities; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.testng.ITestListener; +import org.testng.ITestResult; +import org.testng.SkipException; +import org.testng.TestListenerAdapter; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Parameters; + + +import java.awt.Image; +import java.awt.Toolkit; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; + + +public class AppiumParallelTest extends TestListenerAdapter implements ITestListener { + public static ArrayList devices = new ArrayList(); + public static Properties prop = new Properties(); + public static IOSDeviceConfiguration iosDevice = new IOSDeviceConfiguration(); + public static AndroidDeviceConfiguration androidDevice = new AndroidDeviceConfiguration(); + public static ConcurrentHashMap deviceMapping = + new ConcurrentHashMap(); + public AppiumDriver driver = null; + public AppiumManager appiumMan = new AppiumManager(); + public String device_udid; + public List logEntries; + public File logFile; + public PrintWriter log_file_writer; + public String category = null; + public ExtentTest parent; + public ExtentTest child; + public String deviceModel; + public File scrFile = null; + public String testDescription = ""; + public ImageUtils imageUtils = new ImageUtils(); + private String screenShotNameWithTimeStamp; + private String CI_BASE_URI = null; + private Flick videoRecording = new Flick(); + public ThreadLocal parentTest = new ThreadLocal(); + public ThreadLocal test = new ThreadLocal(); + + static { + try { + prop.load(new FileInputStream("config.properties")); + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (IOSDeviceConfiguration.deviceUDIDiOS != null) { + System.out.println("Adding iOS devices"); + devices.addAll(IOSDeviceConfiguration.deviceUDIDiOS); + } + if (androidDevice.getDeviceSerial() != null) { + System.out.println("Adding Android devices"); + devices.addAll(AndroidDeviceConfiguration.deviceSerail); + } + } else { + if (androidDevice.getDeviceSerial() != null) { + System.out.println("Adding Android devices"); + devices.addAll(AndroidDeviceConfiguration.deviceSerail); + } + } + for (String device : devices) { + deviceMapping.put(device, true); + } + System.out.println(deviceMapping); + } catch (IOException e) { + e.printStackTrace(); + System.out.println("Failed to initialize framework"); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Failed to initialize framework"); + } + } + + public static synchronized String getNextAvailableDeviceId() { + ConcurrentHashMap.KeySetView devices = deviceMapping.keySet(); + int i = 0; + for (String device : devices) { + Thread t = Thread.currentThread(); + t.setName("Thread_" + i); + System.out.println("Parallel Thread is::" + t.getName()); + i++; + if (deviceMapping.get(device)) { + deviceMapping.put(device, false); + System.out.println(device); + return device; + } + } + return null; + } + + + public static void freeDevice(String deviceId) { + deviceMapping.put(deviceId, true); + } + + public static Image getImage(final String pathAndFileName) { + final URL url = Thread.currentThread().getContextClassLoader().getResource(pathAndFileName); + return Toolkit.getDefaultToolkit().getImage(url); + } + + public static boolean buildStatus() { + BufferedReader br = null; + try { + String sCurrentLine; + br = new BufferedReader( + new FileReader(System.getProperty("user.dir") + "/target/failed.txt")); + while ((sCurrentLine = br.readLine()) != null) { + if (sCurrentLine.contains("TestFailed")) { + return true; + } + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (br != null) { + br.close(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } + return false; + } + + public synchronized AppiumServiceBuilder startAppiumServer( + String device, String methodName) throws Exception { + if (prop.containsKey("CI_BASE_URI")) { + CI_BASE_URI = prop.getProperty("CI_BASE_URI").toString().trim(); + } else if (CI_BASE_URI == null || CI_BASE_URI.isEmpty()) { + CI_BASE_URI = System.getProperty("user.dir"); + } + if (device.isEmpty()) { + System.out.println("Into Empty devices"); + device_udid = getNextAvailableDeviceId(); + System.out.println("Into block" + device_udid); + } else { + device_udid = device; + } + System.out.println("Devices*******" + device_udid); + if (device_udid == null) { + System.out.println("No devices are free to run test or Failed to run test"); + return null; + } + System.out.println("****************Device*************" + device_udid); + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + getDeviceCategory(); + } else { + category = androidDevice.getDeviceModel(device_udid); + } + createParentNodeExtent(methodName, "", category + + device_udid.replaceAll("\\W", "_")); + + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.checkiOSDevice(device_udid)) { + AppiumServiceBuilder webKitPort = getAppiumServiceBuilder(methodName); + if (webKitPort != null) { + return webKitPort; + } + } else { + return appiumMan.appiumServerForAndroid(device_udid, methodName); + } + } + return null; + } + + + @BeforeClass(alwaysRun = true) + @Parameters({"device"}) + public synchronized AppiumServiceBuilder startAppiumServer(String device) throws Exception { + String methodName = getClass().getSimpleName(); + if (prop.containsKey("CI_BASE_URI")) { + CI_BASE_URI = prop.getProperty("CI_BASE_URI").toString().trim(); + } else if (CI_BASE_URI == null || CI_BASE_URI.isEmpty()) { + CI_BASE_URI = System.getProperty("user.dir"); + } + if (device.isEmpty()) { + device_udid = getNextAvailableDeviceId(); + } else { + device_udid = device; + } + + if (device_udid == null) { + System.out.println("No devices are free to run test or Failed to run test"); + return null; + } + System.out.println("****************Device*************" + device_udid); + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + getDeviceCategory(); + } else { + category = androidDevice.getDeviceModel(device_udid); + } + + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + if (getClass().getAnnotation(Description.class) != null) { + testDescription = getClass().getAnnotation(Description.class).value(); + } + createParentNodeExtent(methodName, testDescription, + category + "_" + device_udid.replaceAll("\\W", "_")); + } + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + AppiumServiceBuilder webKitPort = getAppiumServiceBuilder(methodName); + if (webKitPort != null) { + return webKitPort; + } + } else { + return appiumMan.appiumServerForAndroid(device_udid, methodName); + } + return null; + } + + public AppiumServiceBuilder getAppiumServiceBuilder(String methodName) throws Exception { + if (iosDevice.checkiOSDevice(device_udid)) { + String webKitPort = iosDevice.startIOSWebKit(device_udid); + return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + return appiumMan.appiumServerForAndroid(device_udid, methodName); + } + return null; + } + + public void getDeviceCategory() throws Exception { + if (iosDevice.checkiOSDevice(device_udid)) { + iosDevice.setIOSWebKitProxyPorts(device_udid); + category = iosDevice.getDeviceName(device_udid).replace(" ", "_"); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + category = androidDevice.getDeviceModel(device_udid); + System.out.println(category); + } + } + + public void createParentNodeExtent(String methodName, String testDescription, String deviceId) { + parent = ExtentTestManager.createTest(methodName, testDescription, + deviceId); + parentTest.set(parent); + ExtentTestManager.getTest().log(Status.INFO, + "AppiumServerLogs"); + } + + public synchronized AppiumDriver startAppiumServerInParallel(String methodName) + throws Exception { + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + setAuthorName(methodName); + } else { + child = parentTest.get().createNode(methodName, category + + device_udid.replaceAll("\\W", "_")); + test.set(child); + } + Thread.sleep(3000); + startingServerInstance(); + return driver; + } + + public synchronized AppiumDriver startAppiumServerInParallel(String methodName, + DesiredCapabilities iosCaps, DesiredCapabilities androidCaps) throws Exception { + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + setAuthorName(methodName); + } + Thread.sleep(3000); + startingServerInstance(iosCaps, androidCaps); + return driver; + } + + public synchronized AppiumDriver startAppiumServerInParallel(String methodName, + DesiredCapabilities caps) throws Exception { + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + setAuthorName(methodName); + } + startingServerInstance(caps); + return driver; + } + + public void setAuthorName(String methodName) throws NoSuchMethodException { + String authorName; + ArrayList listeners = new ArrayList<>(); + if (getClass().getMethod(methodName).getAnnotation(Author.class) != null) { + authorName = getClass().getMethod(methodName).getAnnotation(Author.class).name(); + Collections.addAll(listeners, authorName.split("\\s*,\\s*")); + child = parentTest.get() + .createNode(methodName, + category + "_" + device_udid.replaceAll("\\W", "_")).assignAuthor( + String.valueOf(listeners)); + test.set(child); + } else { + child = parentTest.get().createNode(methodName, + category + "_" + device_udid.replaceAll("\\W", "_")); + test.set(child); + } + } + + public void startingServerInstance() throws Exception { + if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb()); + } else { + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.checkiOSDevice(device_udid)) { + driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative()); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative()); + } + } else { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative()); + } + } + } + + public void startingServerInstance(DesiredCapabilities caps) throws Exception { + if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb()); + } else { + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (caps.asMap().get("bundleId") != null) { + driver = new IOSDriver<>(appiumMan.getAppiumUrl(), caps); + } else { + checkSelendroid(caps); + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), caps); + } + } else { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), caps); + } + } + } + + public void startingServerInstance(DesiredCapabilities iosCaps, DesiredCapabilities androidCaps) + throws Exception { + if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb()); + } else { + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.checkiOSDevice(device_udid)) { + driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosCaps); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + checkSelendroid(androidCaps); + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidCaps); + } + } else { + checkSelendroid(androidCaps); + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidCaps); + } + } + } + + public DesiredCapabilities checkSelendroid(DesiredCapabilities androidCaps) { + int android_api = 0; + try { + System.out.println("System API Level" + androidDevice.getDevices().get(device_udid)); + String deviceAPI = androidDevice.getDevices().get(device_udid); + android_api = Integer.parseInt(deviceAPI); + } catch (Exception e) { + e.printStackTrace(); + } + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("Android API Level::" + android_api); + if (android_api <= 16) { + androidCaps.setCapability(MobileCapabilityType.AUTOMATION_NAME, "Selendroid"); + } + return androidCaps; + } + + public void startLogResults(String methodName) throws FileNotFoundException { + if (System.getenv("VIDEO_LOGS") != null) { + try { + videoRecording + .startVideoRecording(device_udid, getClass().getName(), methodName, methodName); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) { + System.out.println("Starting ADB logs" + device_udid); + logEntries = driver.manage().logs().get("logcat").filter(Level.ALL); + logFile = new File(System.getProperty("user.dir") + "/target/adblogs/" + device_udid + .replaceAll("\\W", "_") + "__" + methodName + ".txt"); + log_file_writer = new PrintWriter(logFile); + } + } + + public void endLogTestResults(ITestResult result) throws IOException, InterruptedException { + + final String classNameCur = result.getName().split(" ")[2].substring(1); + final Package[] packages = Package.getPackages(); + String className = null; + for (final Package p : packages) { + final String pack = p.getName(); + final String tentative = pack + "." + classNameCur; + try { + Class.forName(tentative); + } catch (final ClassNotFoundException e) { + continue; + } + className = tentative; + break; + } + + if (System.getenv("VIDEO_LOGS") != null) { + try { + videoRecording.stopVideoRecording(device_udid, getClass().getName(), + result.getMethod().getMethodName(), result.getMethod().getMethodName()); + } catch (IOException e) { + videoRecording.stopVideoRecording(device_udid, getClass().getName(), + result.getMethod().getMethodName(), result.getMethod().getMethodName()); + } catch (InterruptedException e) { + System.out.println(""); + } + } + + if (result.isSuccess()) { + writeFailureToTxt("TestPassed"); + test.get().log(Status.PASS, result.getMethod().getMethodName()); + if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) { + log_file_writer.println(logEntries); + log_file_writer.flush(); + test.get().log(Status.INFO, + "AdbLogs"); + System.out.println(driver.getSessionId() + ": Saving device log - Done."); + } + File videoFile = new File(System.getProperty("user.dir") + "/target/screenshot/android/" + + device_udid.replaceAll("\\W", "_") + "/" + + className + "/" + result.getMethod().getMethodName() + + "/" + result.getMethod().getMethodName() + ".mp4"); + System.out.println(videoFile); + if (videoFile.exists()) { + videoFile.delete(); + } + + } + /* + * Failure Block + */ + if (result.getStatus() == ITestResult.FAILURE) { + writeFailureToTxt("TestFailed"); + ExtentTest log = test.get() + .log(Status.FAIL, "
" + result.getThrowable() + "
"); + if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) { + deviceModel = androidDevice.getDeviceModel(device_udid); + captureScreenShot(result.getMethod().getMethodName(), result.getStatus(), + result.getTestClass().getName()); + } else if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + deviceModel = iosDevice.getIOSDeviceProductTypeAndVersion(device_udid); + captureScreenShot(result.getMethod().getMethodName(), result.getStatus(), + result.getTestClass().getName()); + } + if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) { + File framedImageAndroid = new File( + System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod() + .getMethodName() + "/" + screenShotNameWithTimeStamp + deviceModel + + "_failed_" + result.getMethod().getMethodName() + "_framed.png"); + if (framedImageAndroid.exists()) { + log + .addScreenCaptureFromPath( + "screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/" + + className + "/" + result.getMethod().getMethodName() + "/" + + screenShotNameWithTimeStamp + deviceModel + "_failed_" + result + .getMethod().getMethodName() + "_framed.png"); + } else { + log.addScreenCaptureFromPath( + "screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/" + + className + "/" + result.getMethod().getMethodName() + "/" + + screenShotNameWithTimeStamp + deviceModel + "_" + result + .getMethod().getMethodName() + "_failed.png"); + } + + + } + if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + File framedImageIOS = new File( + System.getProperty("user.dir") + "/target/screenshot/iOS/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod() + .getMethodName() + "/" + screenShotNameWithTimeStamp + deviceModel + + "_failed_" + result.getMethod().getMethodName() + "_framed.png"); + System.out.println("************************" + framedImageIOS.exists() + + "***********************"); + if (framedImageIOS.exists()) { + log.addScreenCaptureFromPath("screenshot/iOS/" + + device_udid.replaceAll("\\W", "_") + + "/" + className + + "/" + result.getMethod().getMethodName() + "/" + + screenShotNameWithTimeStamp + deviceModel + "_failed_" + result + .getMethod().getMethodName() + "_framed.png"); + } else { + log.addScreenCaptureFromPath("screenshot/iOS/" + + device_udid.replaceAll("\\W", "_") + + "/" + className + + "/" + result.getMethod().getMethodName() + "/" + + screenShotNameWithTimeStamp + deviceModel + "_" + result + .getMethod().getMethodName() + "_failed.png"); + } + + } + + + if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) { + log_file_writer.println(logEntries); + log_file_writer.flush(); + test.get().log(Status.INFO, + "AdbLogs"); + System.out.println(driver.getSessionId() + ": Saving device log - Done."); + } + + } + /* + * Skip block + */ + if (result.getStatus() == ITestResult.SKIP) { + writeFailureToTxt("TestSkipped"); + test.get().log(Status.SKIP, "Test skipped"); + } + + if (System.getenv("VIDEO_LOGS") != null) { + if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) { + if (new File( + System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod() + .getMethodName() + "/" + result.getMethod().getMethodName() + ".mp4") + .exists()) { + test.get().log(Status.INFO, "Videologs"); + } + } else if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + if (new File( + System.getProperty("user.dir") + "/target/screenshot/iOS/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod() + .getMethodName() + "/" + result.getMethod().getMethodName() + ".mp4") + .exists()) { + test.get().log(Status.INFO, "Videologs"); + } + } + } + ExtentManager.getExtent().flush(); + } + + @AfterClass(alwaysRun = true) public synchronized void killAppiumServer() + throws InterruptedException, IOException { + System.out.println( + "**************ClosingAppiumSession****************" + Thread.currentThread().getId()); + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + //ExtentManager.getInstance().endTest(parent); + ExtentManager.getExtent().flush(); + } + appiumMan.destroyAppiumNode(); + if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + iosDevice.destroyIOSWebKitProxy(); + } + freeDevice(device_udid); + } + + protected String getStackTrace(Throwable t) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + return sw.toString(); + } + + public void waitForElement(By id, int time) { + WebDriverWait wait = new WebDriverWait(driver, 20); + wait.until(ExpectedConditions.elementToBeClickable((id))); + } + + public void resetAppData() throws InterruptedException, IOException { + androidDevice.clearAppData(device_udid, prop.getProperty("APP_PACKAGE")); + } + + public void closeOpenApp() throws InterruptedException, IOException { + androidDevice.closeRunningApp(device_udid, prop.getProperty("APP_PACKAGE")); + } + + public void removeApkFromDevice(String app_package) throws Exception { + androidDevice.removeApkFromDevices(device_udid, app_package); + } + + public synchronized DesiredCapabilities androidNative() { + System.out.println("Setting Android Desired Capabilities:"); + DesiredCapabilities androidCapabilities = new DesiredCapabilities(); + androidCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android"); + androidCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "5.X"); + androidCapabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, + prop.getProperty("APP_ACTIVITY")); + androidCapabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, + prop.getProperty("APP_PACKAGE")); + androidCapabilities.setCapability("browserName", ""); + checkSelendroid(androidCapabilities); + androidCapabilities + .setCapability(MobileCapabilityType.APP, prop.getProperty("ANDROID_APP_PATH")); + androidCapabilities.setCapability(MobileCapabilityType.UDID, device_udid); + return androidCapabilities; + } + + public synchronized DesiredCapabilities androidWeb() { + DesiredCapabilities androidWebCapabilities = new DesiredCapabilities(); + androidWebCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android"); + androidWebCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "5.0.X"); + // If you want the tests on real device, make sure chrome browser is + // installed + androidWebCapabilities + .setCapability(MobileCapabilityType.BROWSER_NAME, prop.getProperty("BROWSER_TYPE")); + androidWebCapabilities.setCapability(MobileCapabilityType.TAKES_SCREENSHOT, true); + return androidWebCapabilities; + } + + public synchronized DesiredCapabilities iosNative() { + DesiredCapabilities iOSCapabilities = new DesiredCapabilities(); + System.out.println("Setting iOS Desired Capabilities:"); + iOSCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "9.0"); + iOSCapabilities.setCapability(MobileCapabilityType.APP, prop.getProperty("IOS_APP_PATH")); + iOSCapabilities + .setCapability(IOSMobileCapabilityType.BUNDLE_ID, prop.getProperty("BUNDLE_ID")); + iOSCapabilities.setCapability(IOSMobileCapabilityType.AUTO_ACCEPT_ALERTS, true); + iOSCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone"); + iOSCapabilities.setCapability(MobileCapabilityType.UDID, device_udid); + return iOSCapabilities; + } + + public void deleteAppIOS(String bundleID) throws InterruptedException, IOException { + iosDevice.unInstallApp(device_udid, bundleID); + } + + public void installAppIOS(String appPath) throws InterruptedException, IOException { + iosDevice.installApp(device_udid, appPath); + } + + public Boolean checkAppIsInstalled(String bundleID) throws InterruptedException, IOException { + return iosDevice.checkIfAppIsInstalled(bundleID); + } + + public AppiumDriver getDriver() { + return driver; + } + + public void onTestStart(ITestResult result) { + Object currentClass = result.getInstance(); + AppiumDriver driver = ((AppiumParallelTest) currentClass).getDriver(); + SkipIf skip = + result.getMethod().getConstructorOrMethod().getMethod().getAnnotation(SkipIf.class); + if (skip != null) { + String info = skip.platform(); + if (driver.toString().split("\\(")[0].trim().toString().contains(info)) { + System.out.println("skipping test"); + throw new SkipException("Skipped because property was set to :::" + info); + } + } + } + + public void captureScreenshot(String methodName, String device, String className) + throws IOException, InterruptedException { + String context = getDriver().getContext(); + boolean contextChanged = false; + if (getDriver().toString().split(":")[0].trim().equals("AndroidDriver") && !context + .equals("NATIVE_APP")) { + getDriver().context("NATIVE_APP"); + contextChanged = true; + } + scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); + if (contextChanged) { + getDriver().context(context); + } + FileUtils.copyFile(scrFile, new File( + "screenshot/" + device + "/" + device_udid.replaceAll("\\W", "_") + "/" + className + + "/" + methodName + "/" + deviceModel + "_" + methodName + "_failed" + ".png")); + Thread.sleep(3000); + } + + public void logger(String message) { + ExtentTestManager.logger(message); + } + + public void captureScreenShot(String screenShotName, int status, String className, + String methodName) throws IOException, InterruptedException { + String context = getDriver().getContext(); + boolean contextChanged = false; + if (getDriver().toString().split(":")[0].trim().equals("AndroidDriver") && !context + .equals("NATIVE_APP")) { + getDriver().context("NATIVE_APP"); + contextChanged = true; + } + File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); + if (contextChanged) { + getDriver().context(context); + } + StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); + screenShotNameWithTimeStamp = currentDateAndTime(); + if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) { + String androidModel = + screenShotNameWithTimeStamp + androidDevice.getDeviceModel(device_udid); + screenShotAndFrame(screenShotName, status, scrFile, methodName, className, androidModel, + "android"); + } else if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + String iosModel = screenShotNameWithTimeStamp + iosDevice + .getIOSDeviceProductTypeAndVersion(device_udid); + screenShotAndFrame(screenShotName, status, scrFile, methodName, className, iosModel, + "iOS"); + } + } + + public void captureScreenShot(String screenShotName, int status, String screenClassName) + throws IOException, InterruptedException { + captureScreenShot(screenShotName, status, screenClassName, screenShotName); + } + + public void captureScreenShot(String screenShotName) throws InterruptedException, IOException { + String methodName = new Exception().getStackTrace()[1].getMethodName(); + String className = new Exception().getStackTrace()[1].getClassName(); + captureScreenShot(screenShotName, 1, className, methodName); + } + + public void screenShotAndFrame(String screenShotName, int status, File scrFile, + String methodName, String className, String model, String platform) { + String failedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + + screenShotNameWithTimeStamp + deviceModel + "_" + methodName + "_failed" + ".png"; + String capturedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + screenShotName + + ".png"; + String framedCapturedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + model + "_" + + screenShotName + "_results.png"; + String framedFailedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + model + + "_failed_" + methodName + "_framed.png"; + + try { + File framePath = + new File(System.getProperty("user.dir") + "/src/test/resources/frames/"); + if (status == ITestResult.FAILURE) { + FileUtils.copyFile(scrFile, new File(failedScreen)); + } else { + FileUtils.copyFile(scrFile, new File(capturedScreen)); + } + + File[] files1 = framePath.listFiles(); + if (framePath.exists()) { + for (int i = 0; i < files1.length; i++) { + if (files1[i].isFile()) { //this line weeds out other directories/folders + System.out.println(files1[i]); + + Path p = Paths.get(files1[i].toString()); + String fileName = p.getFileName().toString().toLowerCase(); + if (model.toString().toLowerCase() + .contains(fileName.split(".png")[0].toLowerCase())) { + try { + if (status == ITestResult.FAILURE) { + String screenToFrame = failedScreen; + imageUtils.wrapDeviceFrames(files1[i].toString(), screenToFrame, + framedFailedScreen); + ExtentTestManager.logOutPut(framedFailedScreen, + screenShotName.toUpperCase()); + deleteFile(screenToFrame); + } else { + String screenToFrame = capturedScreen; + imageUtils.wrapDeviceFrames(files1[i].toString(), screenToFrame, + framedCapturedScreen); + ExtentTestManager.logOutPut(framedCapturedScreen, + screenShotName.toUpperCase()); + deleteFile(screenToFrame); + } + + break; + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (IM4JavaException e) { + e.printStackTrace(); + } + } + } + } + } + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void deleteFile(String screenToFrame) { + File fileToDelete = new File(screenToFrame); + if (fileToDelete.exists()) { + fileToDelete.delete(); + } + } + + public String currentDateAndTime() { + LocalDateTime now = LocalDateTime.now(); + DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME; + return now.truncatedTo(ChronoUnit.SECONDS).format(dtf); + } + + public void writeFailureToTxt(String content) { + try { + File file = new File(System.getProperty("user.dir") + "/target/failed.txt"); + if (!file.exists()) { + file.createNewFile(); + } + FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); + BufferedWriter bw = new BufferedWriter(fw); + bw.write(content); + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public MobilePlatform getMobilePlatform(String device_udid) { + MobilePlatform platform = null; + + if (device_udid.length() == IOSDeviceConfiguration.IOS_UDID_LENGTH) { + platform = MobilePlatform.IOS; + } else { + platform = MobilePlatform.ANDROID; + } + return platform; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.appium.manager.AppiumParallelTest.startingServerInstance` reads without synchronization from `this.com.appium.manager.AppiumParallelTest.device_udid`. Potentially races with write in method `AppiumParallelTest.startAppiumServer(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AppiumParallelTest.startingServerInstance() + +### Procedure Id: +com.appium.manager.AppiumParallelTest.startingServerInstance():void.6ec016d0ed7f5b5ab793b9185e8b58eb + +### File: +src/main/java/com/appium/manager/AppiumParallelTest.java + +### Key: +AppiumParallelTest.java|startingServerInstance|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +a4870ac8ad56ebc803df41ed159da6a6 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10416/instruction.md b/inferredbugs-10416/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..16ff3b925959212a09882ea59e4fb5f05a2e641f --- /dev/null +++ b/inferredbugs-10416/instruction.md @@ -0,0 +1,134 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** AppiumTestDistribution +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.appium.utils; + +/** + * Command Prompt - this class contains method to run windows and mac commands + */ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class CommandPrompt { + + static Process p; + ProcessBuilder builder; + + + public String runCommand(String command) throws InterruptedException, IOException { + p = Runtime.getRuntime().exec(command); + // get std output + BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); + String line = ""; + String allLine = ""; + int i = 1; + while ((line = r.readLine()) != null) { + allLine = allLine + "" + line + "\n"; + if (line.contains("Console LogLevel: debug") && line.contains("Complete")) { + break; + } + i++; + } + return allLine; + + } + + public String runCommandThruProcessBuilder(String command) + throws InterruptedException, IOException { + List commands = new ArrayList(); + commands.add("/bin/sh"); + commands.add("-c"); + commands.add(command); + ProcessBuilder builder = new ProcessBuilder(commands); + Map environ = builder.environment(); + + final Process process = builder.start(); + InputStream is = process.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + String line; + String allLine = ""; + while ((line = br.readLine()) != null) { + allLine = allLine + "" + line + "\n"; + System.out.println(allLine); + } + return allLine.split(":")[1].replace("\n", "").trim(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 49 is not released after line 57. +**Note**: potential exception at line 53 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String CommandPrompt.runCommandThruProcessBuilder(String) + +### Procedure Id: +com.appium.utils.CommandPrompt.runCommandThruProcessBuilder(java.lang.String):java.lang.String.74aeace553df66230e09e2ce724dc15c + +### File: +src/main/java/com/appium/utils/CommandPrompt.java + +### Key: +CommandPrompt.java|runCommandThruProcessBuilder|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +eca1c540686d2680508b0ce21d3b18f4 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10417/instruction.md b/inferredbugs-10417/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..461136b638fc5cf08df331b20d5593fe2528d53f --- /dev/null +++ b/inferredbugs-10417/instruction.md @@ -0,0 +1,303 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** AppiumTestDistribution +**Bug ID:** 42 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.appium.manager; + +import com.appium.utils.CommandPrompt; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class AndroidDeviceConfiguration { + + private CommandPrompt cmd = new CommandPrompt(); + private Map devices = new HashMap(); + public static ArrayList deviceSerail = new ArrayList(); + ArrayList deviceModel = new ArrayList(); + + /** + * This method start adb server + */ + public void startADB() throws Exception { + String output = cmd.runCommand("adb start-server"); + String[] lines = output.split("\n"); + if (lines[0].contains("internal or external command")) { + System.out.println("Please set ANDROID_HOME in your system variables"); + } + } + + /** + * This method stop adb server + */ + public void stopADB() throws Exception { + cmd.runCommand("adb kill-server"); + } + + /** + * This method return connected devices + * + * @return hashmap of connected devices information + */ + public Map getDevices() throws Exception { + + startADB(); // start adb service + String output = cmd.runCommand("adb devices"); + String[] lines = output.split("\n"); + + if (lines.length <= 1) { + System.out.println("No Device Connected"); + stopADB(); + return null; + } else { + for (int i = 1; i < lines.length; i++) { + lines[i] = lines[i].replaceAll("\\s+", ""); + + if (lines[i].contains("device")) { + lines[i] = lines[i].replaceAll("device", ""); + String deviceID = lines[i]; + String model = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model") + .replaceAll("\\s+", ""); + String brand = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand") + .replaceAll("\\s+", ""); + String osVersion = cmd.runCommand( + "adb -s " + deviceID + " shell getprop ro.build.version.release") + .replaceAll("\\s+", ""); + String deviceName = brand + " " + model; + String apiLevel = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk") + .replaceAll("\n", ""); + + devices.put("deviceID" + i, deviceID); + devices.put("deviceName" + i, deviceName); + devices.put("osVersion" + i, osVersion); + devices.put(deviceID, apiLevel); + } else if (lines[i].contains("unauthorized")) { + lines[i] = lines[i].replaceAll("unauthorized", ""); + String deviceID = lines[i]; + } else if (lines[i].contains("offline")) { + lines[i] = lines[i].replaceAll("offline", ""); + String deviceID = lines[i]; + } + } + return devices; + } + } + + public ArrayList getDeviceSerial() throws Exception { + + startADB(); // start adb service + String output = cmd.runCommand("adb devices"); + String[] lines = output.split("\n"); + + if (lines.length <= 1) { + System.out.println("No Device Connected"); + return null; + } else { + for (int i = 1; i < lines.length; i++) { + lines[i] = lines[i].replaceAll("\\s+", ""); + + if (lines[i].contains("device")) { + lines[i] = lines[i].replaceAll("device", ""); + String deviceID = lines[i]; + deviceSerail.add(deviceID); + } else if (lines[i].contains("unauthorized")) { + lines[i] = lines[i].replaceAll("unauthorized", ""); + String deviceID = lines[i]; + } else if (lines[i].contains("offline")) { + lines[i] = lines[i].replaceAll("offline", ""); + String deviceID = lines[i]; + } + } + return deviceSerail; + } + } + + /* + * This method gets the device model name + */ + public String getDeviceModel(String deviceID) { + String deviceModelName = null; + String brand = null; + String deviceModel = null; + try { + deviceModelName = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model") + .replaceAll("\\W", ""); + + brand = cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand"); + } catch (InterruptedException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + deviceModel = deviceModelName.concat("_" + brand); + + return deviceModel.trim(); + + } + + /* + * This method gets the device OS API Level + */ + public String deviceOS(String deviceID) { + String deviceOSLevel = null; + try { + deviceOSLevel = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk") + .replaceAll("\\W", ""); + } catch (InterruptedException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return deviceOSLevel; + + } + + /** + * This method will close the running app + * + * @throws IOException + * @throws InterruptedException + */ + public void closeRunningApp(String deviceID, String app_package) + throws InterruptedException, IOException { + // adb -s 192.168.56.101:5555 com.android2.calculator3 + cmd.runCommand("adb -s " + deviceID + " shell am force-stop " + app_package); + } + + /** + * This method clears the app data only for android + * + * @throws IOException + * @throws InterruptedException + */ + public void clearAppData(String deviceID, String app_package) + throws InterruptedException, IOException { + // adb -s 192.168.56.101:5555 com.android2.calculator3 + cmd.runCommand("adb -s " + deviceID + " shell pm clear " + app_package); + } + + /** + * This method removes apk from the devices attached + * + * @param app_package + * @throws Exception + */ + + public void removeApkFromDevices(String deviceID, String app_package) throws Exception { + cmd.runCommand("adb -s " + deviceID + " uninstall " + app_package); + } + + public String screenRecord(String deviceID, String fileName) + throws IOException, InterruptedException { + return "adb -s " + deviceID + " shell screenrecord --bit-rate 3000000 /sdcard/" + fileName + + ".mp4"; + } + + public boolean checkIfRecordable(String deviceID) throws IOException, InterruptedException { + String screenrecord = + cmd.runCommand("adb -s " + deviceID + " shell ls /system/bin/screenrecord"); + if (screenrecord.trim().equals("/system/bin/screenrecord")) { + return true; + } else { + return false; + } + } + + public String getDeviceManufacturer(String deviceID) throws IOException, InterruptedException { + return cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.manufacturer") + .trim(); + } + + public AndroidDeviceConfiguration pullVideoFromDevice(String deviceID, String fileName, + String destination) throws IOException, InterruptedException { + ProcessBuilder pb = + new ProcessBuilder("adb", "-s", deviceID, "pull", "/sdcard/" + fileName + ".mp4", + destination); + Process pc = pb.start(); + pc.waitFor(); + System.out.println("Exited with Code::" + pc.exitValue()); + System.out.println("Done"); + Thread.sleep(5000); + return new AndroidDeviceConfiguration(); + } + + public void removeVideoFileFromDevice(String deviceID, String fileName) + throws IOException, InterruptedException { + cmd.runCommand("adb -s " + deviceID + " shell rm -f /sdcard/" + fileName + ".mp4"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.lang.Process` acquired to `com.appium.utils.CommandPrompt.p` by call to `runCommand(...)` at line 58 is not released after line 61. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Map AndroidDeviceConfiguration.getDevices() + +### Procedure Id: +com.appium.manager.AndroidDeviceConfiguration.getDevices():java.util.Map.3f7f267efe46020ad2fb48490d4b57fe + +### File: +src/main/java/com/appium/manager/AndroidDeviceConfiguration.java + +### Key: +AndroidDeviceConfiguration.java|getDevices|RESOURCE_LEAK + +### Node Key: +241d42dae50053d7648ace8f5b7dfc3f + +### Hash: +fce917702e9b7cf60c3f9a71a2a84b3c + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10418/instruction.md b/inferredbugs-10418/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2f459ef79d558520f25c18d7d23efb103424840c --- /dev/null +++ b/inferredbugs-10418/instruction.md @@ -0,0 +1,303 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** AppiumTestDistribution +**Bug ID:** 45 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.appium.manager; + +import com.appium.utils.CommandPrompt; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class AndroidDeviceConfiguration { + + private CommandPrompt cmd = new CommandPrompt(); + private Map devices = new HashMap(); + public static ArrayList deviceSerail = new ArrayList(); + ArrayList deviceModel = new ArrayList(); + + /** + * This method start adb server + */ + public void startADB() throws Exception { + String output = cmd.runCommand("adb start-server"); + String[] lines = output.split("\n"); + if (lines[0].contains("internal or external command")) { + System.out.println("Please set ANDROID_HOME in your system variables"); + } + } + + /** + * This method stop adb server + */ + public void stopADB() throws Exception { + cmd.runCommand("adb kill-server"); + } + + /** + * This method return connected devices + * + * @return hashmap of connected devices information + */ + public Map getDevices() throws Exception { + + startADB(); // start adb service + String output = cmd.runCommand("adb devices"); + String[] lines = output.split("\n"); + + if (lines.length <= 1) { + System.out.println("No Device Connected"); + stopADB(); + return null; + } else { + for (int i = 1; i < lines.length; i++) { + lines[i] = lines[i].replaceAll("\\s+", ""); + + if (lines[i].contains("device")) { + lines[i] = lines[i].replaceAll("device", ""); + String deviceID = lines[i]; + String model = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model") + .replaceAll("\\s+", ""); + String brand = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand") + .replaceAll("\\s+", ""); + String osVersion = cmd.runCommand( + "adb -s " + deviceID + " shell getprop ro.build.version.release") + .replaceAll("\\s+", ""); + String deviceName = brand + " " + model; + String apiLevel = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk") + .replaceAll("\n", ""); + + devices.put("deviceID" + i, deviceID); + devices.put("deviceName" + i, deviceName); + devices.put("osVersion" + i, osVersion); + devices.put(deviceID, apiLevel); + } else if (lines[i].contains("unauthorized")) { + lines[i] = lines[i].replaceAll("unauthorized", ""); + String deviceID = lines[i]; + } else if (lines[i].contains("offline")) { + lines[i] = lines[i].replaceAll("offline", ""); + String deviceID = lines[i]; + } + } + return devices; + } + } + + public ArrayList getDeviceSerial() throws Exception { + + startADB(); // start adb service + String output = cmd.runCommand("adb devices"); + String[] lines = output.split("\n"); + + if (lines.length <= 1) { + System.out.println("No Device Connected"); + return null; + } else { + for (int i = 1; i < lines.length; i++) { + lines[i] = lines[i].replaceAll("\\s+", ""); + + if (lines[i].contains("device")) { + lines[i] = lines[i].replaceAll("device", ""); + String deviceID = lines[i]; + deviceSerail.add(deviceID); + } else if (lines[i].contains("unauthorized")) { + lines[i] = lines[i].replaceAll("unauthorized", ""); + String deviceID = lines[i]; + } else if (lines[i].contains("offline")) { + lines[i] = lines[i].replaceAll("offline", ""); + String deviceID = lines[i]; + } + } + return deviceSerail; + } + } + + /* + * This method gets the device model name + */ + public String getDeviceModel(String deviceID) { + String deviceModelName = null; + String brand = null; + String deviceModel = null; + try { + deviceModelName = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model") + .replaceAll("\\W", ""); + + brand = cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand"); + } catch (InterruptedException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + deviceModel = deviceModelName.concat("_" + brand); + + return deviceModel.trim(); + + } + + /* + * This method gets the device OS API Level + */ + public String deviceOS(String deviceID) { + String deviceOSLevel = null; + try { + deviceOSLevel = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk") + .replaceAll("\\W", ""); + } catch (InterruptedException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return deviceOSLevel; + + } + + /** + * This method will close the running app + * + * @throws IOException + * @throws InterruptedException + */ + public void closeRunningApp(String deviceID, String app_package) + throws InterruptedException, IOException { + // adb -s 192.168.56.101:5555 com.android2.calculator3 + cmd.runCommand("adb -s " + deviceID + " shell am force-stop " + app_package); + } + + /** + * This method clears the app data only for android + * + * @throws IOException + * @throws InterruptedException + */ + public void clearAppData(String deviceID, String app_package) + throws InterruptedException, IOException { + // adb -s 192.168.56.101:5555 com.android2.calculator3 + cmd.runCommand("adb -s " + deviceID + " shell pm clear " + app_package); + } + + /** + * This method removes apk from the devices attached + * + * @param app_package + * @throws Exception + */ + + public void removeApkFromDevices(String deviceID, String app_package) throws Exception { + cmd.runCommand("adb -s " + deviceID + " uninstall " + app_package); + } + + public String screenRecord(String deviceID, String fileName) + throws IOException, InterruptedException { + return "adb -s " + deviceID + " shell screenrecord --bit-rate 3000000 /sdcard/" + fileName + + ".mp4"; + } + + public boolean checkIfRecordable(String deviceID) throws IOException, InterruptedException { + String screenrecord = + cmd.runCommand("adb -s " + deviceID + " shell ls /system/bin/screenrecord"); + if (screenrecord.trim().equals("/system/bin/screenrecord")) { + return true; + } else { + return false; + } + } + + public String getDeviceManufacturer(String deviceID) throws IOException, InterruptedException { + return cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.manufacturer") + .trim(); + } + + public AndroidDeviceConfiguration pullVideoFromDevice(String deviceID, String fileName, + String destination) throws IOException, InterruptedException { + ProcessBuilder pb = + new ProcessBuilder("adb", "-s", deviceID, "pull", "/sdcard/" + fileName + ".mp4", + destination); + Process pc = pb.start(); + pc.waitFor(); + System.out.println("Exited with Code::" + pc.exitValue()); + System.out.println("Done"); + Thread.sleep(5000); + return new AndroidDeviceConfiguration(); + } + + public void removeVideoFileFromDevice(String deviceID, String fileName) + throws IOException, InterruptedException { + cmd.runCommand("adb -s " + deviceID + " shell rm -f /sdcard/" + fileName + ".mp4"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.lang.Process` acquired to `com.appium.utils.CommandPrompt.p` by call to `startADB()` at line 89 is not released after line 90. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +ArrayList AndroidDeviceConfiguration.getDeviceSerial() + +### Procedure Id: +com.appium.manager.AndroidDeviceConfiguration.getDeviceSerial():java.util.ArrayList.99a21e6e5ff70142fea59714ea87049a + +### File: +src/main/java/com/appium/manager/AndroidDeviceConfiguration.java + +### Key: +AndroidDeviceConfiguration.java|getDeviceSerial|RESOURCE_LEAK + +### Node Key: +e24115bb7ba8298b5824ecd29ac84dd1 + +### Hash: +55e4a181b15c75f3767fb26435048f00 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10420/instruction.md b/inferredbugs-10420/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef8b3e8e486a1f2cb57d20db178c21ccf6962d76 --- /dev/null +++ b/inferredbugs-10420/instruction.md @@ -0,0 +1,963 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** AppiumTestDistribution +**Bug ID:** 28 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.appium.manager; + +import com.annotation.values.Author; +import com.annotation.values.Description; +import com.annotation.values.SkipIf; +import com.appium.ios.IOSDeviceConfiguration; +import com.appium.utils.ImageUtils; +import com.appium.utils.MobilePlatform; +import com.aventstack.extentreports.ExtentTest; +import com.aventstack.extentreports.Status; +import com.report.factory.ExtentManager; +import com.report.factory.ExtentTestManager; +import com.video.recorder.Flick; +import io.appium.java_client.AppiumDriver; +import io.appium.java_client.MobileElement; +import io.appium.java_client.android.AndroidDriver; +import io.appium.java_client.ios.IOSDriver; +import io.appium.java_client.remote.AndroidMobileCapabilityType; +import io.appium.java_client.remote.IOSMobileCapabilityType; +import io.appium.java_client.remote.MobileCapabilityType; +import io.appium.java_client.service.local.AppiumServiceBuilder; +import org.apache.commons.io.FileUtils; +import org.im4java.core.IM4JavaException; +import org.openqa.selenium.By; +import org.openqa.selenium.OutputType; +import org.openqa.selenium.TakesScreenshot; +import org.openqa.selenium.logging.LogEntry; +import org.openqa.selenium.remote.DesiredCapabilities; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.testng.ITestListener; +import org.testng.ITestResult; +import org.testng.SkipException; +import org.testng.TestListenerAdapter; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Parameters; + + +import java.awt.Image; +import java.awt.Toolkit; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; + + +public class AppiumParallelTest extends TestListenerAdapter implements ITestListener { + public static ArrayList devices = new ArrayList(); + public static Properties prop = new Properties(); + public static IOSDeviceConfiguration iosDevice = new IOSDeviceConfiguration(); + public static AndroidDeviceConfiguration androidDevice = new AndroidDeviceConfiguration(); + public static ConcurrentHashMap deviceMapping = + new ConcurrentHashMap(); + public AppiumDriver driver = null; + public AppiumManager appiumMan = new AppiumManager(); + public String device_udid; + public List logEntries; + public File logFile; + public PrintWriter log_file_writer; + public String category = null; + public ExtentTest parent; + public ExtentTest child; + public String deviceModel; + public File scrFile = null; + public String testDescription = ""; + public ImageUtils imageUtils = new ImageUtils(); + private String screenShotNameWithTimeStamp; + private String CI_BASE_URI = null; + private Flick videoRecording = new Flick(); + public ThreadLocal parentTest = new ThreadLocal(); + public ThreadLocal test = new ThreadLocal(); + + static { + try { + prop.load(new FileInputStream("config.properties")); + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (IOSDeviceConfiguration.deviceUDIDiOS != null) { + System.out.println("Adding iOS devices"); + devices.addAll(IOSDeviceConfiguration.deviceUDIDiOS); + } + if (androidDevice.getDeviceSerial() != null) { + System.out.println("Adding Android devices"); + devices.addAll(AndroidDeviceConfiguration.deviceSerail); + } + } else { + if (androidDevice.getDeviceSerial() != null) { + System.out.println("Adding Android devices"); + devices.addAll(AndroidDeviceConfiguration.deviceSerail); + } + } + for (String device : devices) { + deviceMapping.put(device, true); + } + System.out.println(deviceMapping); + } catch (IOException e) { + e.printStackTrace(); + System.out.println("Failed to initialize framework"); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Failed to initialize framework"); + } + } + + public static synchronized String getNextAvailableDeviceId() { + ConcurrentHashMap.KeySetView devices = deviceMapping.keySet(); + int i = 0; + for (String device : devices) { + Thread t = Thread.currentThread(); + t.setName("Thread_" + i); + System.out.println("Parallel Thread is::" + t.getName()); + i++; + if (deviceMapping.get(device)) { + deviceMapping.put(device, false); + System.out.println(device); + return device; + } + } + return null; + } + + + public static void freeDevice(String deviceId) { + deviceMapping.put(deviceId, true); + } + + public static Image getImage(final String pathAndFileName) { + final URL url = Thread.currentThread().getContextClassLoader().getResource(pathAndFileName); + return Toolkit.getDefaultToolkit().getImage(url); + } + + public static boolean buildStatus() { + BufferedReader br = null; + try { + String sCurrentLine; + br = new BufferedReader( + new FileReader(System.getProperty("user.dir") + "/target/failed.txt")); + while ((sCurrentLine = br.readLine()) != null) { + if (sCurrentLine.contains("TestFailed")) { + return true; + } + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (br != null) { + br.close(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } + return false; + } + + public synchronized AppiumServiceBuilder startAppiumServer( + String device, String methodName) throws Exception { + if (prop.containsKey("CI_BASE_URI")) { + CI_BASE_URI = prop.getProperty("CI_BASE_URI").toString().trim(); + } else if (CI_BASE_URI == null || CI_BASE_URI.isEmpty()) { + CI_BASE_URI = System.getProperty("user.dir"); + } + if (device.isEmpty()) { + System.out.println("Into Empty devices"); + device_udid = getNextAvailableDeviceId(); + System.out.println("Into block" + device_udid); + } else { + device_udid = device; + } + System.out.println("Devices*******" + device_udid); + if (device_udid == null) { + System.out.println("No devices are free to run test or Failed to run test"); + return null; + } + System.out.println("****************Device*************" + device_udid); + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + getDeviceCategory(); + } else { + category = androidDevice.getDeviceModel(device_udid); + } + createParentNodeExtent(methodName, "", category + + device_udid.replaceAll("\\W", "_")); + + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.checkiOSDevice(device_udid)) { + AppiumServiceBuilder webKitPort = getAppiumServiceBuilder(methodName); + if (webKitPort != null) { + return webKitPort; + } + } else { + return appiumMan.appiumServerForAndroid(device_udid, methodName); + } + } + return null; + } + + + @BeforeClass(alwaysRun = true) + @Parameters({"device"}) + public synchronized AppiumServiceBuilder startAppiumServer(String device) throws Exception { + String methodName = getClass().getSimpleName(); + if (prop.containsKey("CI_BASE_URI")) { + CI_BASE_URI = prop.getProperty("CI_BASE_URI").toString().trim(); + } else if (CI_BASE_URI == null || CI_BASE_URI.isEmpty()) { + CI_BASE_URI = System.getProperty("user.dir"); + } + if (device.isEmpty()) { + device_udid = getNextAvailableDeviceId(); + } else { + device_udid = device; + } + + if (device_udid == null) { + System.out.println("No devices are free to run test or Failed to run test"); + return null; + } + System.out.println("****************Device*************" + device_udid); + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + getDeviceCategory(); + } else { + category = androidDevice.getDeviceModel(device_udid); + } + + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + if (getClass().getAnnotation(Description.class) != null) { + testDescription = getClass().getAnnotation(Description.class).value(); + } + createParentNodeExtent(methodName, testDescription, + category + "_" + device_udid.replaceAll("\\W", "_")); + } + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + AppiumServiceBuilder webKitPort = getAppiumServiceBuilder(methodName); + if (webKitPort != null) { + return webKitPort; + } + } else { + return appiumMan.appiumServerForAndroid(device_udid, methodName); + } + return null; + } + + public AppiumServiceBuilder getAppiumServiceBuilder(String methodName) throws Exception { + if (iosDevice.checkiOSDevice(device_udid)) { + String webKitPort = iosDevice.startIOSWebKit(device_udid); + return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + return appiumMan.appiumServerForAndroid(device_udid, methodName); + } + return null; + } + + public void getDeviceCategory() throws Exception { + if (iosDevice.checkiOSDevice(device_udid)) { + iosDevice.setIOSWebKitProxyPorts(device_udid); + category = iosDevice.getDeviceName(device_udid).replace(" ", "_"); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + category = androidDevice.getDeviceModel(device_udid); + System.out.println(category); + } + } + + public void createParentNodeExtent(String methodName, String testDescription, String deviceId) { + parent = ExtentTestManager.createTest(methodName, testDescription, + deviceId); + parentTest.set(parent); + ExtentTestManager.getTest().log(Status.INFO, + "AppiumServerLogs"); + } + + public synchronized AppiumDriver startAppiumServerInParallel(String methodName) + throws Exception { + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + setAuthorName(methodName); + } else { + child = parentTest.get().createNode(methodName, category + + device_udid.replaceAll("\\W", "_")); + test.set(child); + } + Thread.sleep(3000); + startingServerInstance(); + return driver; + } + + public synchronized AppiumDriver startAppiumServerInParallel(String methodName, + DesiredCapabilities iosCaps, DesiredCapabilities androidCaps) throws Exception { + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + setAuthorName(methodName); + } + Thread.sleep(3000); + startingServerInstance(iosCaps, androidCaps); + return driver; + } + + public synchronized AppiumDriver startAppiumServerInParallel(String methodName, + DesiredCapabilities caps) throws Exception { + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + setAuthorName(methodName); + } + startingServerInstance(caps); + return driver; + } + + public void setAuthorName(String methodName) throws NoSuchMethodException { + String authorName; + ArrayList listeners = new ArrayList<>(); + if (getClass().getMethod(methodName).getAnnotation(Author.class) != null) { + authorName = getClass().getMethod(methodName).getAnnotation(Author.class).name(); + Collections.addAll(listeners, authorName.split("\\s*,\\s*")); + child = parentTest.get() + .createNode(methodName, + category + "_" + device_udid.replaceAll("\\W", "_")).assignAuthor( + String.valueOf(listeners)); + test.set(child); + } else { + child = parentTest.get().createNode(methodName, + category + "_" + device_udid.replaceAll("\\W", "_")); + test.set(child); + } + } + + public void startingServerInstance() throws Exception { + if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb()); + } else { + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.checkiOSDevice(device_udid)) { + driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative()); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative()); + } + } else { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative()); + } + } + } + + public void startingServerInstance(DesiredCapabilities caps) throws Exception { + if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb()); + } else { + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (caps.asMap().get("bundleId") != null) { + driver = new IOSDriver<>(appiumMan.getAppiumUrl(), caps); + } else { + checkSelendroid(caps); + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), caps); + } + } else { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), caps); + } + } + } + + public void startingServerInstance(DesiredCapabilities iosCaps, DesiredCapabilities androidCaps) + throws Exception { + if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb()); + } else { + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.checkiOSDevice(device_udid)) { + driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosCaps); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + checkSelendroid(androidCaps); + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidCaps); + } + } else { + checkSelendroid(androidCaps); + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidCaps); + } + } + } + + public DesiredCapabilities checkSelendroid(DesiredCapabilities androidCaps) { + int android_api = 0; + try { + System.out.println("System API Level" + androidDevice.getDevices().get(device_udid)); + String deviceAPI = androidDevice.getDevices().get(device_udid); + android_api = Integer.parseInt(deviceAPI); + } catch (Exception e) { + e.printStackTrace(); + } + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("Android API Level::" + android_api); + if (android_api <= 16) { + androidCaps.setCapability(MobileCapabilityType.AUTOMATION_NAME, "Selendroid"); + } + return androidCaps; + } + + public void startLogResults(String methodName) throws FileNotFoundException { + if (System.getenv("VIDEO_LOGS") != null) { + try { + videoRecording + .startVideoRecording(device_udid, getClass().getName(), methodName, methodName); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) { + System.out.println("Starting ADB logs" + device_udid); + logEntries = driver.manage().logs().get("logcat").filter(Level.ALL); + logFile = new File(System.getProperty("user.dir") + "/target/adblogs/" + device_udid + .replaceAll("\\W", "_") + "__" + methodName + ".txt"); + log_file_writer = new PrintWriter(logFile); + } + } + + public void endLogTestResults(ITestResult result) throws IOException, InterruptedException { + + final String classNameCur = result.getName().split(" ")[2].substring(1); + final Package[] packages = Package.getPackages(); + String className = null; + for (final Package p : packages) { + final String pack = p.getName(); + final String tentative = pack + "." + classNameCur; + try { + Class.forName(tentative); + } catch (final ClassNotFoundException e) { + continue; + } + className = tentative; + break; + } + + if (System.getenv("VIDEO_LOGS") != null) { + try { + videoRecording.stopVideoRecording(device_udid, getClass().getName(), + result.getMethod().getMethodName(), result.getMethod().getMethodName()); + } catch (IOException e) { + videoRecording.stopVideoRecording(device_udid, getClass().getName(), + result.getMethod().getMethodName(), result.getMethod().getMethodName()); + } catch (InterruptedException e) { + System.out.println(""); + } + } + + if (result.isSuccess()) { + writeFailureToTxt("TestPassed"); + test.get().log(Status.PASS, result.getMethod().getMethodName()); + if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) { + log_file_writer.println(logEntries); + log_file_writer.flush(); + test.get().log(Status.INFO, + "AdbLogs"); + System.out.println(driver.getSessionId() + ": Saving device log - Done."); + } + File videoFile = new File(System.getProperty("user.dir") + "/target/screenshot/android/" + + device_udid.replaceAll("\\W", "_") + "/" + + className + "/" + result.getMethod().getMethodName() + + "/" + result.getMethod().getMethodName() + ".mp4"); + System.out.println(videoFile); + if (videoFile.exists()) { + videoFile.delete(); + } + + } + /* + * Failure Block + */ + if (result.getStatus() == ITestResult.FAILURE) { + writeFailureToTxt("TestFailed"); + ExtentTest log = test.get() + .log(Status.FAIL, "
" + result.getThrowable() + "
"); + if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) { + deviceModel = androidDevice.getDeviceModel(device_udid); + captureScreenShot(result.getMethod().getMethodName(), result.getStatus(), + result.getTestClass().getName()); + } else if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + deviceModel = iosDevice.getIOSDeviceProductTypeAndVersion(device_udid); + captureScreenShot(result.getMethod().getMethodName(), result.getStatus(), + result.getTestClass().getName()); + } + if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) { + File framedImageAndroid = new File( + System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod() + .getMethodName() + "/" + screenShotNameWithTimeStamp + deviceModel + + "_failed_" + result.getMethod().getMethodName() + "_framed.png"); + if (framedImageAndroid.exists()) { + log + .addScreenCaptureFromPath( + "screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/" + + className + "/" + result.getMethod().getMethodName() + "/" + + screenShotNameWithTimeStamp + deviceModel + "_failed_" + result + .getMethod().getMethodName() + "_framed.png"); + } else { + log.addScreenCaptureFromPath( + "screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/" + + className + "/" + result.getMethod().getMethodName() + "/" + + screenShotNameWithTimeStamp + deviceModel + "_" + result + .getMethod().getMethodName() + "_failed.png"); + } + + + } + if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + File framedImageIOS = new File( + System.getProperty("user.dir") + "/target/screenshot/iOS/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod() + .getMethodName() + "/" + screenShotNameWithTimeStamp + deviceModel + + "_failed_" + result.getMethod().getMethodName() + "_framed.png"); + System.out.println("************************" + framedImageIOS.exists() + + "***********************"); + if (framedImageIOS.exists()) { + log.addScreenCaptureFromPath("screenshot/iOS/" + + device_udid.replaceAll("\\W", "_") + + "/" + className + + "/" + result.getMethod().getMethodName() + "/" + + screenShotNameWithTimeStamp + deviceModel + "_failed_" + result + .getMethod().getMethodName() + "_framed.png"); + } else { + log.addScreenCaptureFromPath("screenshot/iOS/" + + device_udid.replaceAll("\\W", "_") + + "/" + className + + "/" + result.getMethod().getMethodName() + "/" + + screenShotNameWithTimeStamp + deviceModel + "_" + result + .getMethod().getMethodName() + "_failed.png"); + } + + } + + + if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) { + log_file_writer.println(logEntries); + log_file_writer.flush(); + test.get().log(Status.INFO, + "AdbLogs"); + System.out.println(driver.getSessionId() + ": Saving device log - Done."); + } + + } + /* + * Skip block + */ + if (result.getStatus() == ITestResult.SKIP) { + writeFailureToTxt("TestSkipped"); + test.get().log(Status.SKIP, "Test skipped"); + } + + if (System.getenv("VIDEO_LOGS") != null) { + if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) { + if (new File( + System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod() + .getMethodName() + "/" + result.getMethod().getMethodName() + ".mp4") + .exists()) { + test.get().log(Status.INFO, "Videologs"); + } + } else if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + if (new File( + System.getProperty("user.dir") + "/target/screenshot/iOS/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod() + .getMethodName() + "/" + result.getMethod().getMethodName() + ".mp4") + .exists()) { + test.get().log(Status.INFO, "Videologs"); + } + } + } + ExtentManager.getExtent().flush(); + } + + @AfterClass(alwaysRun = true) public synchronized void killAppiumServer() + throws InterruptedException, IOException { + System.out.println( + "**************ClosingAppiumSession****************" + Thread.currentThread().getId()); + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + //ExtentManager.getInstance().endTest(parent); + ExtentManager.getExtent().flush(); + } + appiumMan.destroyAppiumNode(); + if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + iosDevice.destroyIOSWebKitProxy(); + } + freeDevice(device_udid); + } + + protected String getStackTrace(Throwable t) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + return sw.toString(); + } + + public void waitForElement(By id, int time) { + WebDriverWait wait = new WebDriverWait(driver, 20); + wait.until(ExpectedConditions.elementToBeClickable((id))); + } + + public void resetAppData() throws InterruptedException, IOException { + androidDevice.clearAppData(device_udid, prop.getProperty("APP_PACKAGE")); + } + + public void closeOpenApp() throws InterruptedException, IOException { + androidDevice.closeRunningApp(device_udid, prop.getProperty("APP_PACKAGE")); + } + + public void removeApkFromDevice(String app_package) throws Exception { + androidDevice.removeApkFromDevices(device_udid, app_package); + } + + public synchronized DesiredCapabilities androidNative() { + System.out.println("Setting Android Desired Capabilities:"); + DesiredCapabilities androidCapabilities = new DesiredCapabilities(); + androidCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android"); + androidCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "5.X"); + androidCapabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, + prop.getProperty("APP_ACTIVITY")); + androidCapabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, + prop.getProperty("APP_PACKAGE")); + androidCapabilities.setCapability("browserName", ""); + checkSelendroid(androidCapabilities); + androidCapabilities + .setCapability(MobileCapabilityType.APP, prop.getProperty("ANDROID_APP_PATH")); + androidCapabilities.setCapability(MobileCapabilityType.UDID, device_udid); + return androidCapabilities; + } + + public synchronized DesiredCapabilities androidWeb() { + DesiredCapabilities androidWebCapabilities = new DesiredCapabilities(); + androidWebCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android"); + androidWebCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "5.0.X"); + // If you want the tests on real device, make sure chrome browser is + // installed + androidWebCapabilities + .setCapability(MobileCapabilityType.BROWSER_NAME, prop.getProperty("BROWSER_TYPE")); + androidWebCapabilities.setCapability(MobileCapabilityType.TAKES_SCREENSHOT, true); + return androidWebCapabilities; + } + + public synchronized DesiredCapabilities iosNative() { + DesiredCapabilities iOSCapabilities = new DesiredCapabilities(); + System.out.println("Setting iOS Desired Capabilities:"); + iOSCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "9.0"); + iOSCapabilities.setCapability(MobileCapabilityType.APP, prop.getProperty("IOS_APP_PATH")); + iOSCapabilities + .setCapability(IOSMobileCapabilityType.BUNDLE_ID, prop.getProperty("BUNDLE_ID")); + iOSCapabilities.setCapability(IOSMobileCapabilityType.AUTO_ACCEPT_ALERTS, true); + iOSCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone"); + iOSCapabilities.setCapability(MobileCapabilityType.UDID, device_udid); + return iOSCapabilities; + } + + public void deleteAppIOS(String bundleID) throws InterruptedException, IOException { + iosDevice.unInstallApp(device_udid, bundleID); + } + + public void installAppIOS(String appPath) throws InterruptedException, IOException { + iosDevice.installApp(device_udid, appPath); + } + + public Boolean checkAppIsInstalled(String bundleID) throws InterruptedException, IOException { + return iosDevice.checkIfAppIsInstalled(bundleID); + } + + public AppiumDriver getDriver() { + return driver; + } + + public void onTestStart(ITestResult result) { + Object currentClass = result.getInstance(); + AppiumDriver driver = ((AppiumParallelTest) currentClass).getDriver(); + SkipIf skip = + result.getMethod().getConstructorOrMethod().getMethod().getAnnotation(SkipIf.class); + if (skip != null) { + String info = skip.platform(); + if (driver.toString().split("\\(")[0].trim().toString().contains(info)) { + System.out.println("skipping test"); + throw new SkipException("Skipped because property was set to :::" + info); + } + } + } + + public void captureScreenshot(String methodName, String device, String className) + throws IOException, InterruptedException { + String context = getDriver().getContext(); + boolean contextChanged = false; + if (getDriver().toString().split(":")[0].trim().equals("AndroidDriver") && !context + .equals("NATIVE_APP")) { + getDriver().context("NATIVE_APP"); + contextChanged = true; + } + scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); + if (contextChanged) { + getDriver().context(context); + } + FileUtils.copyFile(scrFile, new File( + "screenshot/" + device + "/" + device_udid.replaceAll("\\W", "_") + "/" + className + + "/" + methodName + "/" + deviceModel + "_" + methodName + "_failed" + ".png")); + Thread.sleep(3000); + } + + public void logger(String message) { + ExtentTestManager.logger(message); + } + + public void captureScreenShot(String screenShotName, int status, String className, + String methodName) throws IOException, InterruptedException { + String context = getDriver().getContext(); + boolean contextChanged = false; + if (getDriver().toString().split(":")[0].trim().equals("AndroidDriver") && !context + .equals("NATIVE_APP")) { + getDriver().context("NATIVE_APP"); + contextChanged = true; + } + File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); + if (contextChanged) { + getDriver().context(context); + } + StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); + screenShotNameWithTimeStamp = currentDateAndTime(); + if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) { + String androidModel = + screenShotNameWithTimeStamp + androidDevice.getDeviceModel(device_udid); + screenShotAndFrame(screenShotName, status, scrFile, methodName, className, androidModel, + "android"); + } else if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + String iosModel = screenShotNameWithTimeStamp + iosDevice + .getIOSDeviceProductTypeAndVersion(device_udid); + screenShotAndFrame(screenShotName, status, scrFile, methodName, className, iosModel, + "iOS"); + } + } + + public void captureScreenShot(String screenShotName, int status, String screenClassName) + throws IOException, InterruptedException { + captureScreenShot(screenShotName, status, screenClassName, screenShotName); + } + + public void captureScreenShot(String screenShotName) throws InterruptedException, IOException { + String methodName = new Exception().getStackTrace()[1].getMethodName(); + String className = new Exception().getStackTrace()[1].getClassName(); + captureScreenShot(screenShotName, 1, className, methodName); + } + + public void screenShotAndFrame(String screenShotName, int status, File scrFile, + String methodName, String className, String model, String platform) { + String failedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + + screenShotNameWithTimeStamp + deviceModel + "_" + methodName + "_failed" + ".png"; + String capturedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + screenShotName + + ".png"; + String framedCapturedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + model + "_" + + screenShotName + "_results.png"; + String framedFailedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + model + + "_failed_" + methodName + "_framed.png"; + + try { + File framePath = + new File(System.getProperty("user.dir") + "/src/test/resources/frames/"); + if (status == ITestResult.FAILURE) { + FileUtils.copyFile(scrFile, new File(failedScreen)); + } else { + FileUtils.copyFile(scrFile, new File(capturedScreen)); + } + + File[] files1 = framePath.listFiles(); + if (framePath.exists()) { + for (int i = 0; i < files1.length; i++) { + if (files1[i].isFile()) { //this line weeds out other directories/folders + System.out.println(files1[i]); + + Path p = Paths.get(files1[i].toString()); + String fileName = p.getFileName().toString().toLowerCase(); + if (model.toString().toLowerCase() + .contains(fileName.split(".png")[0].toLowerCase())) { + try { + if (status == ITestResult.FAILURE) { + String screenToFrame = failedScreen; + imageUtils.wrapDeviceFrames(files1[i].toString(), screenToFrame, + framedFailedScreen); + ExtentTestManager.logOutPut(framedFailedScreen, + screenShotName.toUpperCase()); + deleteFile(screenToFrame); + } else { + String screenToFrame = capturedScreen; + imageUtils.wrapDeviceFrames(files1[i].toString(), screenToFrame, + framedCapturedScreen); + ExtentTestManager.logOutPut(framedCapturedScreen, + screenShotName.toUpperCase()); + deleteFile(screenToFrame); + } + + break; + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (IM4JavaException e) { + e.printStackTrace(); + } + } + } + } + } + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void deleteFile(String screenToFrame) { + File fileToDelete = new File(screenToFrame); + if (fileToDelete.exists()) { + fileToDelete.delete(); + } + } + + public String currentDateAndTime() { + LocalDateTime now = LocalDateTime.now(); + DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME; + return now.truncatedTo(ChronoUnit.SECONDS).format(dtf); + } + + public void writeFailureToTxt(String content) { + try { + File file = new File(System.getProperty("user.dir") + "/target/failed.txt"); + if (!file.exists()) { + file.createNewFile(); + } + FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); + BufferedWriter bw = new BufferedWriter(fw); + bw.write(content); + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public MobilePlatform getMobilePlatform(String device_udid) { + MobilePlatform platform = null; + + if (device_udid.length() == IOSDeviceConfiguration.IOS_UDID_LENGTH) { + platform = MobilePlatform.IOS; + } else { + platform = MobilePlatform.ANDROID; + } + return platform; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.appium.manager.AppiumParallelTest.startingServerInstance` indirectly reads without synchronization from `this.com.appium.manager.AppiumParallelTest.appiumMan.com.appium.manager.AppiumManager.appiumDriverLocalService`. Potentially races with write in method `AppiumParallelTest.startAppiumServer(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AppiumParallelTest.startingServerInstance() + +### Procedure Id: +com.appium.manager.AppiumParallelTest.startingServerInstance():void.6ec016d0ed7f5b5ab793b9185e8b58eb + +### File: +src/main/java/com/appium/manager/AppiumParallelTest.java + +### Key: +AppiumParallelTest.java|startingServerInstance|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +73b34ead76a97499d24bc9034e43ee2e + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10427/instruction.md b/inferredbugs-10427/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e8c008cd78ca591f6b4f6ef6620ce6b24b26aa99 --- /dev/null +++ b/inferredbugs-10427/instruction.md @@ -0,0 +1,834 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** AppiumTestDistribution +**Bug ID:** 21 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.appium.manager; + +import com.annotation.values.Author; +import com.annotation.values.Description; +import com.annotation.values.SkipIf; +import com.appium.ios.IOSDeviceConfiguration; +import com.appium.utils.ImageUtils; +import com.relevantcodes.extentreports.ExtentTest; +import com.relevantcodes.extentreports.LogStatus; +import com.report.factory.ExtentManager; +import com.report.factory.ExtentTestManager; +import io.appium.java_client.AppiumDriver; +import io.appium.java_client.MobileElement; +import io.appium.java_client.android.AndroidDriver; +import io.appium.java_client.ios.IOSDriver; +import io.appium.java_client.remote.AndroidMobileCapabilityType; +import io.appium.java_client.remote.IOSMobileCapabilityType; +import io.appium.java_client.remote.MobileCapabilityType; +import io.appium.java_client.service.local.AppiumServiceBuilder; +import org.apache.commons.io.FileUtils; +import org.im4java.core.IM4JavaException; +import org.openqa.selenium.By; +import org.openqa.selenium.OutputType; +import org.openqa.selenium.TakesScreenshot; +import org.openqa.selenium.logging.LogEntry; +import org.openqa.selenium.remote.DesiredCapabilities; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.testng.ITestListener; +import org.testng.ITestResult; +import org.testng.SkipException; +import org.testng.TestListenerAdapter; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Parameters; + + +import java.awt.Image; +import java.awt.Toolkit; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; + + +public class AppiumParallelTest extends TestListenerAdapter implements ITestListener { + public AppiumDriver driver = null; + public AppiumManager appiumMan = new AppiumManager(); + public String device_udid; + public List logEntries; + public File logFile; + public PrintWriter log_file_writer; + public DesiredCapabilities capabilities = new DesiredCapabilities(); + public String category = null; + public ExtentTest parent; + public ExtentTest child; + public String deviceModel; + public File scrFile = null; + public String testDescription = ""; + String screenShotNameWithTimeStamp; + private String CI_BASE_URI = null; + + private Map parentContext = new HashMap(); + public static ArrayList devices = new ArrayList(); + public static Properties prop = new Properties(); + public static IOSDeviceConfiguration iosDevice = new IOSDeviceConfiguration(); + public static AndroidDeviceConfiguration androidDevice = new AndroidDeviceConfiguration(); + public static ConcurrentHashMap deviceMapping = + new ConcurrentHashMap(); + public ImageUtils imageUtils = new ImageUtils(); + + static { + try { + prop.load(new FileInputStream("config.properties")); + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (IOSDeviceConfiguration.deviceUDIDiOS != null) { + System.out.println("Adding iOS devices"); + devices.addAll(IOSDeviceConfiguration.deviceUDIDiOS); + } + if (androidDevice.getDeviceSerial() != null) { + System.out.println("Adding Android devices"); + devices.addAll(AndroidDeviceConfiguration.deviceSerail); + } + } else { + if (androidDevice.getDeviceSerial() != null) { + System.out.println("Adding Android devices"); + devices.addAll(AndroidDeviceConfiguration.deviceSerail); + } + } + for (String device : devices) { + deviceMapping.put(device, true); + } + System.out.println(deviceMapping); + } catch (IOException e) { + e.printStackTrace(); + System.out.println("Failed to initialize framework"); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Failed to initialize framework"); + } + } + + public static synchronized String getNextAvailableDeviceId() { + ConcurrentHashMap.KeySetView devices = deviceMapping.keySet(); + int i = 0; + for (String device : devices) { + Thread t = Thread.currentThread(); + t.setName("Thread_" + i); + System.out.println("Parallel Thread is::" + t.getName()); + i++; + if (deviceMapping.get(device)) { + deviceMapping.put(device, false); + return device; + } + } + return null; + } + + + public static void freeDevice(String deviceId) { + deviceMapping.put(deviceId, true); + } + + @BeforeClass(alwaysRun = true) + @Parameters({"device"}) + public synchronized AppiumServiceBuilder startAppiumServer(String device) throws Exception { + String methodName = getClass().getSimpleName(); + if (prop.containsKey("CI_BASE_URI")) { + CI_BASE_URI = prop.getProperty("CI_BASE_URI").toString().trim(); + } else if (CI_BASE_URI == null || CI_BASE_URI.isEmpty()) { + CI_BASE_URI = System.getProperty("user.dir"); + } + if (device.isEmpty()) { + device_udid = getNextAvailableDeviceId(); + } else { + device_udid = device; + } + + if (device_udid == null) { + System.out.println("No devices are free to run test or Failed to run test"); + return null; + } + System.out.println("****************Device*************" + device_udid); + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.checkiOSDevice(device_udid)) { + iosDevice.setIOSWebKitProxyPorts(device_udid); + category = iosDevice.getDeviceName(device_udid).replace(" ", "_"); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + category = androidDevice.getDeviceModel(device_udid); + System.out.println(category); + } + } else { + category = androidDevice.getDeviceModel(device_udid); + } + + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + if (getClass().getAnnotation(Description.class) != null) { + testDescription = getClass().getAnnotation(Description.class).value(); + } + parent = ExtentTestManager.startTest(methodName, testDescription, + category + "_" + device_udid.replaceAll("\\W", "_")); + parentContext.put(Thread.currentThread().getId(), parent); + ExtentTestManager.getTest().log(LogStatus.INFO, "AppiumServerLogs", + "Logs"); + } + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.checkiOSDevice(device_udid)) { + String webKitPort = iosDevice.startIOSWebKit(device_udid); + return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + return appiumMan.appiumServerForAndroid(device_udid, methodName); + } + } else { + return appiumMan.appiumServerForAndroid(device_udid, methodName); + } + return null; + } + + + public synchronized AppiumDriver startAppiumServerInParallel(String methodName) + throws Exception { + ExtentTestManager.loadConfig(); + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + setAuthorName(methodName); + } + Thread.sleep(3000); + startingServerInstance(); + return driver; + } + + public synchronized AppiumDriver startAppiumServerInParallel(String methodName, + DesiredCapabilities iosCaps, DesiredCapabilities androidCaps) throws Exception { + ExtentTestManager.loadConfig(); + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + setAuthorName(methodName); + } + Thread.sleep(3000); + startingServerInstance(iosCaps, androidCaps); + return driver; + } + + public synchronized AppiumDriver startAppiumServerInParallel(String methodName, + DesiredCapabilities caps) throws Exception { + ExtentTestManager.loadConfig(); + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + setAuthorName(methodName); + } + startingServerInstance(caps); + return driver; + } + + public void setAuthorName(String methodName) throws NoSuchMethodException { + String authorName; + ArrayList listeners = new ArrayList<>(); + if (getClass().getMethod(methodName).getAnnotation(Author.class) != null) { + authorName = getClass().getMethod(methodName).getAnnotation(Author.class).name(); + Collections.addAll(listeners, authorName.split("\\s*,\\s*")); + child = ExtentTestManager + .startTest(methodName.toString() + " ---- AuthorName:: " + authorName) + .assignCategory(category + "_" + device_udid.replaceAll("\\W", "_"), + "Author:" + listeners); + } else { + child = ExtentTestManager.startTest(methodName.toString()) + .assignCategory(category + "_" + device_udid.replaceAll("\\W", "_")); + } + } + + public void startingServerInstance() throws Exception { + if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb()); + } else { + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.checkiOSDevice(device_udid)) { + driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative()); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative()); + } + } else { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative()); + } + } + } + + public void startingServerInstance(DesiredCapabilities caps) throws Exception { + if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb()); + } else { + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (caps.asMap().get("bundleId") != null) { + driver = new IOSDriver<>(appiumMan.getAppiumUrl(), caps); + } else { + checkSelendroid(caps); + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), caps); + } + } else { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), caps); + } + } + } + + public void startingServerInstance(DesiredCapabilities iosCaps, DesiredCapabilities androidCaps) + throws Exception { + if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) { + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb()); + } else { + if (System.getProperty("os.name").toLowerCase().contains("mac")) { + if (iosDevice.checkiOSDevice(device_udid)) { + driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosCaps); + } else if (!iosDevice.checkiOSDevice(device_udid)) { + checkSelendroid(androidCaps); + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidCaps); + } + } else { + checkSelendroid(androidCaps); + driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidCaps); + } + } + } + + public DesiredCapabilities checkSelendroid(DesiredCapabilities androidCaps) { + int android_api = 0; + try { + System.out.println("System API Level" + androidDevice.getDevices().get(device_udid)); + String deviceAPI = androidDevice.getDevices().get(device_udid); + android_api = Integer.parseInt(deviceAPI); + } catch (Exception e) { + e.printStackTrace(); + } + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("Android API Level::" + android_api); + if (android_api <= 16) { + androidCaps.setCapability(MobileCapabilityType.AUTOMATION_NAME, "Selendroid"); + } + return androidCaps; + } + + public void startLogResults(String methodName) throws FileNotFoundException { + if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) { + System.out.println("Starting ADB logs" + device_udid); + logEntries = driver.manage().logs().get("logcat").filter(Level.ALL); + logFile = new File(System.getProperty("user.dir") + "/target/adblogs/" + device_udid + .replaceAll("\\W", "_") + "__" + methodName + ".txt"); + log_file_writer = new PrintWriter(logFile); + } + } + + public void endLogTestResults(ITestResult result) throws IOException, InterruptedException { + + final String classNameCur = result.getName().split(" ")[2].substring(1); + final Package[] packages = Package.getPackages(); + String className = null; + for (final Package p : packages) { + final String pack = p.getName(); + final String tentative = pack + "." + classNameCur; + try { + Class.forName(tentative); + } catch (final ClassNotFoundException e) { + continue; + } + className = tentative; + break; + } + + + if (result.isSuccess()) { + ExtentTestManager.getTest() + .log(LogStatus.PASS, result.getMethod().getMethodName(), "Pass"); + if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) { + log_file_writer.println(logEntries); + log_file_writer.flush(); + ExtentTestManager.getTest().log(LogStatus.INFO, result.getMethod().getMethodName(), + "ADBLogs:: AdbLogs"); + System.out.println(driver.getSessionId() + ": Saving device log - Done."); + } + + } + if (result.getStatus() == ITestResult.FAILURE) { + writeFailureToTxt(); + ExtentTestManager.getTest() + .log(LogStatus.FAIL, result.getMethod().getMethodName(), result.getThrowable()); + if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) { + System.out.println("im in"); + deviceModel = androidDevice.getDeviceModel(device_udid); + //captureScreenshot(result.getMethod().getMethodName(), "android", className); + captureScreenShot(result.getMethod().getMethodName(), result.getStatus(), + result.getTestClass().getName()); + } else if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + deviceModel = iosDevice.getIOSDeviceProductTypeAndVersion(device_udid); + captureScreenShot(result.getMethod().getMethodName(), result.getStatus(), + result.getTestClass().getName()); + } + + if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) { + File framedImageAndroid = new File( + System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod() + .getMethodName() + "/" + screenShotNameWithTimeStamp + deviceModel + + "_failed_" + result.getMethod().getMethodName() + "_framed.png"); + if (framedImageAndroid.exists()) { + ExtentTestManager.getTest() + .log(LogStatus.INFO, result.getMethod().getMethodName(), + "Snapshot below: " + ExtentTestManager.getTest().addScreenCapture( + CI_BASE_URI + "/target/screenshot/android/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result + .getMethod().getMethodName() + "/" + screenShotNameWithTimeStamp + + deviceModel + "_failed_" + result.getMethod().getMethodName() + + "_framed.png")); + } else { + ExtentTestManager.getTest() + .log(LogStatus.INFO, result.getMethod().getMethodName(), + "Snapshot below: " + ExtentTestManager.getTest().addScreenCapture( + CI_BASE_URI + "/target/screenshot/android/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result + .getMethod().getMethodName() + "/" + screenShotNameWithTimeStamp + + deviceModel + "_" + result.getMethod().getMethodName() + + "_failed.png")); + } + + + } + if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + File framedImageIOS = new File( + System.getProperty("user.dir") + "/target/screenshot/iOS/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod() + .getMethodName() + "/" + screenShotNameWithTimeStamp + deviceModel + + "_failed_" + result.getMethod().getMethodName() + "_framed.png"); + if (framedImageIOS.exists()) { + ExtentTestManager.getTest() + .log(LogStatus.INFO, result.getMethod().getMethodName(), + "Snapshot below: " + ExtentTestManager.getTest().addScreenCapture( + CI_BASE_URI + "/target/screenshot/iOS/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result + .getMethod().getMethodName() + "/" + screenShotNameWithTimeStamp + + deviceModel + "_failed_" + result.getMethod().getMethodName() + + "_framed.png")); + } else { + ExtentTestManager.getTest() + .log(LogStatus.INFO, result.getMethod().getMethodName(), + "Snapshot below: " + ExtentTestManager.getTest().addScreenCapture( + CI_BASE_URI + "/target/screenshot/iOS/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + result + .getMethod().getMethodName() + "/" + screenShotNameWithTimeStamp + + deviceModel + "_" + result.getMethod().getMethodName() + + "_failed.png")); + } + + } + + + if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) { + log_file_writer.println(logEntries); + log_file_writer.flush(); + ExtentTestManager.getTest().log(LogStatus.INFO, result.getMethod().getMethodName(), + "ADBLogs:: AdbLogs"); + System.out.println(driver.getSessionId() + ": Saving device log - Done."); + } + + } + if (result.getStatus() == ITestResult.SKIP) { + ExtentTestManager.getTest().log(LogStatus.SKIP, "Test skipped"); + } + parentContext.get(Thread.currentThread().getId()).appendChild(child); + ExtentManager.getInstance().flush(); + } + + @AfterClass(alwaysRun = true) public synchronized void killAppiumServer() + throws InterruptedException, IOException { + System.out.println( + "**************ClosingAppiumSession****************" + Thread.currentThread().getId()); + if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { + ExtentManager.getInstance().endTest(parent); + ExtentManager.getInstance().flush(); + } + appiumMan.destroyAppiumNode(); + if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + iosDevice.destroyIOSWebKitProxy(); + } + freeDevice(device_udid); + } + + protected String getStackTrace(Throwable t) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + return sw.toString(); + } + + public void waitForElement(By id, int time) { + WebDriverWait wait = new WebDriverWait(driver, 20); + wait.until(ExpectedConditions.elementToBeClickable((id))); + } + + public void resetAppData() throws InterruptedException, IOException { + androidDevice.clearAppData(device_udid, prop.getProperty("APP_PACKAGE")); + } + + public void closeOpenApp() throws InterruptedException, IOException { + androidDevice.closeRunningApp(device_udid, prop.getProperty("APP_PACKAGE")); + } + + public void removeApkFromDevice(String app_package) throws Exception { + androidDevice.removeApkFromDevices(device_udid, app_package); + } + + + public synchronized DesiredCapabilities androidNative() { + System.out.println("Setting Android Desired Capabilities:"); + DesiredCapabilities androidCapabilities = new DesiredCapabilities(); + androidCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android"); + androidCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "5.X"); + androidCapabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, + prop.getProperty("APP_ACTIVITY")); + androidCapabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, + prop.getProperty("APP_PACKAGE")); + androidCapabilities.setCapability("browserName", ""); + checkSelendroid(androidCapabilities); + androidCapabilities + .setCapability(MobileCapabilityType.APP, prop.getProperty("ANDROID_APP_PATH")); + androidCapabilities.setCapability(MobileCapabilityType.UDID, device_udid); + return androidCapabilities; + } + + public synchronized DesiredCapabilities androidWeb() { + DesiredCapabilities androidWebCapabilities = new DesiredCapabilities(); + androidWebCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android"); + androidWebCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "5.0.X"); + // If you want the tests on real device, make sure chrome browser is + // installed + androidWebCapabilities + .setCapability(MobileCapabilityType.BROWSER_NAME, prop.getProperty("BROWSER_TYPE")); + androidWebCapabilities.setCapability(MobileCapabilityType.TAKES_SCREENSHOT, true); + return androidWebCapabilities; + } + + public synchronized DesiredCapabilities iosNative() { + DesiredCapabilities iOSCapabilities = new DesiredCapabilities(); + System.out.println("Setting iOS Desired Capabilities:"); + iOSCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "9.0"); + iOSCapabilities.setCapability(MobileCapabilityType.APP, prop.getProperty("IOS_APP_PATH")); + iOSCapabilities + .setCapability(IOSMobileCapabilityType.BUNDLE_ID, prop.getProperty("BUNDLE_ID")); + iOSCapabilities.setCapability(IOSMobileCapabilityType.AUTO_ACCEPT_ALERTS, true); + iOSCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone"); + iOSCapabilities.setCapability(MobileCapabilityType.UDID, device_udid); + return iOSCapabilities; + } + + public void deleteAppIOS(String bundleID) throws InterruptedException, IOException { + iosDevice.unInstallApp(device_udid, bundleID); + } + + public void installAppIOS(String appPath) throws InterruptedException, IOException { + iosDevice.installApp(device_udid, appPath); + } + + public Boolean checkAppIsInstalled(String bundleID) throws InterruptedException, IOException { + return iosDevice.checkIfAppIsInstalled(bundleID); + } + + + public AppiumDriver getDriver() { + return driver; + } + + public void onTestStart(ITestResult result) { + Object currentClass = result.getInstance(); + AppiumDriver driver = ((AppiumParallelTest) currentClass).getDriver(); + SkipIf skip = + result.getMethod().getConstructorOrMethod().getMethod().getAnnotation(SkipIf.class); + if (skip != null) { + String info = skip.platform(); + if (driver.toString().split("\\(")[0].trim().toString().contains(info)) { + System.out.println("skipping test"); + throw new SkipException("Skipped because property was set to :::" + info); + } + } + } + + public static Image getImage(final String pathAndFileName) { + final URL url = Thread.currentThread().getContextClassLoader().getResource(pathAndFileName); + return Toolkit.getDefaultToolkit().getImage(url); + } + + public void captureScreenshot(String methodName, String device, String className) + throws IOException, InterruptedException { + String context = getDriver().getContext(); + boolean contextChanged = false; + if (getDriver().toString().split(":")[0].trim().equals("AndroidDriver") && !context + .equals("NATIVE_APP")) { + getDriver().context("NATIVE_APP"); + contextChanged = true; + } + scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); + if (contextChanged) { + getDriver().context(context); + } + FileUtils.copyFile(scrFile, new File( + CI_BASE_URI + "/target/screenshot/" + device + "/" + device_udid.replaceAll("\\W", "_") + + "/" + className + "/" + methodName + "/" + deviceModel + "_" + methodName + + "_failed" + ".png")); + Thread.sleep(3000); + } + + public void logger(String message) { + ExtentTestManager.logger(message); + } + + public void captureScreenShot(String screenShotName, int status, String className, + String methodName) throws IOException, InterruptedException { + String context = getDriver().getContext(); + boolean contextChanged = false; + if (getDriver().toString().split(":")[0].trim().equals("AndroidDriver") && !context + .equals("NATIVE_APP")) { + getDriver().context("NATIVE_APP"); + contextChanged = true; + } + File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); + if (contextChanged) { + getDriver().context(context); + } + StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); + screenShotNameWithTimeStamp = currentDateAndTime(); + if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) { + String androidModel = + screenShotNameWithTimeStamp + androidDevice.getDeviceModel(device_udid); + screenShotAndFrame(screenShotName, status, scrFile, methodName, className, androidModel, + "android"); + } else if (driver.toString().split(":")[0].trim().equals("IOSDriver")) { + String iosModel = screenShotNameWithTimeStamp + iosDevice + .getIOSDeviceProductTypeAndVersion(device_udid); + screenShotAndFrame(screenShotName, status, scrFile, methodName, className, iosModel, + "iOS"); + } + } + + public void captureScreenShot(String screenShotName, int status, String screenClassName) + throws IOException, InterruptedException { + captureScreenShot(screenShotName, status, screenClassName, screenShotName); + } + + public void captureScreenShot(String screenShotName) throws InterruptedException, IOException { + String methodName = new Exception().getStackTrace()[1].getMethodName(); + String className = new Exception().getStackTrace()[1].getClassName(); + captureScreenShot(screenShotName, 1, className, methodName); + } + + public void screenShotAndFrame(String screenShotName, int status, File scrFile, + String methodName, String className, String model, String platform) { + String failedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + + screenShotNameWithTimeStamp + deviceModel + "_" + methodName + "_failed" + ".png"; + String capturedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + screenShotName + + ".png"; + String framedCapturedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + model + "_" + + screenShotName + "_results.png"; + String framedFailedScreen = + System.getProperty("user.dir") + "/target/screenshot/" + platform + "/" + device_udid + .replaceAll("\\W", "_") + "/" + className + "/" + methodName + "/" + model + + "_failed_" + methodName + "_framed.png"; + + try { + File framePath = + new File(System.getProperty("user.dir") + "/src/test/resources/frames/"); + if (status == ITestResult.FAILURE) { + FileUtils.copyFile(scrFile, new File(failedScreen)); + } else { + FileUtils.copyFile(scrFile, new File(capturedScreen)); + } + + File[] files1 = framePath.listFiles(); + if (framePath.exists()) { + for (int i = 0; i < files1.length; i++) { + if (files1[i].isFile()) { //this line weeds out other directories/folders + System.out.println(files1[i]); + + Path p = Paths.get(files1[i].toString()); + String fileName = p.getFileName().toString().toLowerCase(); + if (model.toString().toLowerCase() + .contains(fileName.split(".png")[0].toLowerCase())) { + try { + if (status == ITestResult.FAILURE) { + String screenToFrame = failedScreen; + imageUtils.wrapDeviceFrames(files1[i].toString(), screenToFrame, + framedFailedScreen); + ExtentTestManager.logOutPut(framedFailedScreen, + screenShotName.toUpperCase()); + File fileToDelete = new File(screenToFrame); + fileToDelete.delete(); + } else { + String screenToFrame = capturedScreen; + imageUtils.wrapDeviceFrames(files1[i].toString(), screenToFrame, + framedCapturedScreen); + ExtentTestManager.logOutPut(framedCapturedScreen, + screenShotName.toUpperCase()); + File fileToDelete = new File(screenToFrame); + fileToDelete.delete(); + } + + break; + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (IM4JavaException e) { + e.printStackTrace(); + } + } + } + } + } + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public String currentDateAndTime() { + LocalDateTime now = LocalDateTime.now(); + DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME; + return now.truncatedTo(ChronoUnit.SECONDS).format(dtf); + } + + public void writeFailureToTxt() { + try { + String content = "TestFailed"; + File file = new File(System.getProperty("user.dir") + "/target/failed.txt"); + if (!file.exists()) { + file.createNewFile(); + } + FileWriter fw = new FileWriter(file.getAbsoluteFile()); + BufferedWriter bw = new BufferedWriter(fw); + bw.write(content); + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static boolean buildStatus() { + BufferedReader br = null; + try { + String sCurrentLine; + br = new BufferedReader( + new FileReader(System.getProperty("user.dir") + "/target/failed.txt")); + while ((sCurrentLine = br.readLine()) != null) { + if (sCurrentLine.contains("TestFailed")) { + return true; + } + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (br != null) { + br.close(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } + return false; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.appium.manager.AppiumParallelTest.captureScreenshot` reads without synchronization from `this.com.appium.manager.AppiumParallelTest.CI_BASE_URI`. Potentially races with write in method `AppiumParallelTest.startAppiumServer(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AppiumParallelTest.captureScreenshot(String,String,String) + +### Procedure Id: +com.appium.manager.AppiumParallelTest.captureScreenshot(java.lang.String,java.lang.String,java.lang..c715df504166b62673483e254f23f4a4 + +### File: +src/main/java/com/appium/manager/AppiumParallelTest.java + +### Key: +AppiumParallelTest.java|captureScreenshot|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +a4880f8b69ef7a3c654b6ebeafc7411f + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10428/instruction.md b/inferredbugs-10428/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..93825433c7aefdec7ff2049863477a51f5b3bf59 --- /dev/null +++ b/inferredbugs-10428/instruction.md @@ -0,0 +1,303 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** AppiumTestDistribution +**Bug ID:** 44 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.appium.manager; + +import com.appium.utils.CommandPrompt; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class AndroidDeviceConfiguration { + + private CommandPrompt cmd = new CommandPrompt(); + private Map devices = new HashMap(); + public static ArrayList deviceSerail = new ArrayList(); + ArrayList deviceModel = new ArrayList(); + + /** + * This method start adb server + */ + public void startADB() throws Exception { + String output = cmd.runCommand("adb start-server"); + String[] lines = output.split("\n"); + if (lines[0].contains("internal or external command")) { + System.out.println("Please set ANDROID_HOME in your system variables"); + } + } + + /** + * This method stop adb server + */ + public void stopADB() throws Exception { + cmd.runCommand("adb kill-server"); + } + + /** + * This method return connected devices + * + * @return hashmap of connected devices information + */ + public Map getDevices() throws Exception { + + startADB(); // start adb service + String output = cmd.runCommand("adb devices"); + String[] lines = output.split("\n"); + + if (lines.length <= 1) { + System.out.println("No Device Connected"); + stopADB(); + return null; + } else { + for (int i = 1; i < lines.length; i++) { + lines[i] = lines[i].replaceAll("\\s+", ""); + + if (lines[i].contains("device")) { + lines[i] = lines[i].replaceAll("device", ""); + String deviceID = lines[i]; + String model = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model") + .replaceAll("\\s+", ""); + String brand = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand") + .replaceAll("\\s+", ""); + String osVersion = cmd.runCommand( + "adb -s " + deviceID + " shell getprop ro.build.version.release") + .replaceAll("\\s+", ""); + String deviceName = brand + " " + model; + String apiLevel = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk") + .replaceAll("\n", ""); + + devices.put("deviceID" + i, deviceID); + devices.put("deviceName" + i, deviceName); + devices.put("osVersion" + i, osVersion); + devices.put(deviceID, apiLevel); + } else if (lines[i].contains("unauthorized")) { + lines[i] = lines[i].replaceAll("unauthorized", ""); + String deviceID = lines[i]; + } else if (lines[i].contains("offline")) { + lines[i] = lines[i].replaceAll("offline", ""); + String deviceID = lines[i]; + } + } + return devices; + } + } + + public ArrayList getDeviceSerial() throws Exception { + + startADB(); // start adb service + String output = cmd.runCommand("adb devices"); + String[] lines = output.split("\n"); + + if (lines.length <= 1) { + System.out.println("No Device Connected"); + return null; + } else { + for (int i = 1; i < lines.length; i++) { + lines[i] = lines[i].replaceAll("\\s+", ""); + + if (lines[i].contains("device")) { + lines[i] = lines[i].replaceAll("device", ""); + String deviceID = lines[i]; + deviceSerail.add(deviceID); + } else if (lines[i].contains("unauthorized")) { + lines[i] = lines[i].replaceAll("unauthorized", ""); + String deviceID = lines[i]; + } else if (lines[i].contains("offline")) { + lines[i] = lines[i].replaceAll("offline", ""); + String deviceID = lines[i]; + } + } + return deviceSerail; + } + } + + /* + * This method gets the device model name + */ + public String getDeviceModel(String deviceID) { + String deviceModelName = null; + String brand = null; + String deviceModel = null; + try { + deviceModelName = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model") + .replaceAll("\\W", ""); + + brand = cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand"); + } catch (InterruptedException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + deviceModel = deviceModelName.concat("_" + brand); + + return deviceModel.trim(); + + } + + /* + * This method gets the device OS API Level + */ + public String deviceOS(String deviceID) { + String deviceOSLevel = null; + try { + deviceOSLevel = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk") + .replaceAll("\\W", ""); + } catch (InterruptedException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return deviceOSLevel; + + } + + /** + * This method will close the running app + * + * @throws IOException + * @throws InterruptedException + */ + public void closeRunningApp(String deviceID, String app_package) + throws InterruptedException, IOException { + // adb -s 192.168.56.101:5555 com.android2.calculator3 + cmd.runCommand("adb -s " + deviceID + " shell am force-stop " + app_package); + } + + /** + * This method clears the app data only for android + * + * @throws IOException + * @throws InterruptedException + */ + public void clearAppData(String deviceID, String app_package) + throws InterruptedException, IOException { + // adb -s 192.168.56.101:5555 com.android2.calculator3 + cmd.runCommand("adb -s " + deviceID + " shell pm clear " + app_package); + } + + /** + * This method removes apk from the devices attached + * + * @param app_package + * @throws Exception + */ + + public void removeApkFromDevices(String deviceID, String app_package) throws Exception { + cmd.runCommand("adb -s " + deviceID + " uninstall " + app_package); + } + + public String screenRecord(String deviceID, String fileName) + throws IOException, InterruptedException { + return "adb -s " + deviceID + " shell screenrecord --bit-rate 3000000 /sdcard/" + fileName + + ".mp4"; + } + + public boolean checkIfRecordable(String deviceID) throws IOException, InterruptedException { + String screenrecord = + cmd.runCommand("adb -s " + deviceID + " shell ls /system/bin/screenrecord"); + if (screenrecord.trim().equals("/system/bin/screenrecord")) { + return true; + } else { + return false; + } + } + + public String getDeviceManufacturer(String deviceID) throws IOException, InterruptedException { + return cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.manufacturer") + .trim(); + } + + public AndroidDeviceConfiguration pullVideoFromDevice(String deviceID, String fileName, + String destination) throws IOException, InterruptedException { + ProcessBuilder pb = + new ProcessBuilder("adb", "-s", deviceID, "pull", "/sdcard/" + fileName + ".mp4", + destination); + Process pc = pb.start(); + pc.waitFor(); + System.out.println("Exited with Code::" + pc.exitValue()); + System.out.println("Done"); + Thread.sleep(5000); + return new AndroidDeviceConfiguration(); + } + + public void removeVideoFileFromDevice(String deviceID, String fileName) + throws IOException, InterruptedException { + cmd.runCommand("adb -s " + deviceID + " shell rm -f /sdcard/" + fileName + ".mp4"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.lang.Process` acquired to `com.appium.utils.CommandPrompt.p` by call to `runCommand(...)` at line 63 is not released after line 68. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Map AndroidDeviceConfiguration.getDevices() + +### Procedure Id: +com.appium.manager.AndroidDeviceConfiguration.getDevices():java.util.Map.3f7f267efe46020ad2fb48490d4b57fe + +### File: +src/main/java/com/appium/manager/AndroidDeviceConfiguration.java + +### Key: +AndroidDeviceConfiguration.java|getDevices|RESOURCE_LEAK + +### Node Key: +241d42dae50053d7648ace8f5b7dfc3f + +### Hash: +fce917702e9b7cf60c3f9a71a2a84b3c + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10429/instruction.md b/inferredbugs-10429/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..268634541ec1b7b601c903a3f1ffd9bb785a5d1a --- /dev/null +++ b/inferredbugs-10429/instruction.md @@ -0,0 +1,303 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** AppiumTestDistribution +**Bug ID:** 43 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.appium.manager; + +import com.appium.utils.CommandPrompt; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class AndroidDeviceConfiguration { + + private CommandPrompt cmd = new CommandPrompt(); + private Map devices = new HashMap(); + public static ArrayList deviceSerail = new ArrayList(); + ArrayList deviceModel = new ArrayList(); + + /** + * This method start adb server + */ + public void startADB() throws Exception { + String output = cmd.runCommand("adb start-server"); + String[] lines = output.split("\n"); + if (lines[0].contains("internal or external command")) { + System.out.println("Please set ANDROID_HOME in your system variables"); + } + } + + /** + * This method stop adb server + */ + public void stopADB() throws Exception { + cmd.runCommand("adb kill-server"); + } + + /** + * This method return connected devices + * + * @return hashmap of connected devices information + */ + public Map getDevices() throws Exception { + + startADB(); // start adb service + String output = cmd.runCommand("adb devices"); + String[] lines = output.split("\n"); + + if (lines.length <= 1) { + System.out.println("No Device Connected"); + stopADB(); + return null; + } else { + for (int i = 1; i < lines.length; i++) { + lines[i] = lines[i].replaceAll("\\s+", ""); + + if (lines[i].contains("device")) { + lines[i] = lines[i].replaceAll("device", ""); + String deviceID = lines[i]; + String model = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model") + .replaceAll("\\s+", ""); + String brand = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand") + .replaceAll("\\s+", ""); + String osVersion = cmd.runCommand( + "adb -s " + deviceID + " shell getprop ro.build.version.release") + .replaceAll("\\s+", ""); + String deviceName = brand + " " + model; + String apiLevel = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk") + .replaceAll("\n", ""); + + devices.put("deviceID" + i, deviceID); + devices.put("deviceName" + i, deviceName); + devices.put("osVersion" + i, osVersion); + devices.put(deviceID, apiLevel); + } else if (lines[i].contains("unauthorized")) { + lines[i] = lines[i].replaceAll("unauthorized", ""); + String deviceID = lines[i]; + } else if (lines[i].contains("offline")) { + lines[i] = lines[i].replaceAll("offline", ""); + String deviceID = lines[i]; + } + } + return devices; + } + } + + public ArrayList getDeviceSerial() throws Exception { + + startADB(); // start adb service + String output = cmd.runCommand("adb devices"); + String[] lines = output.split("\n"); + + if (lines.length <= 1) { + System.out.println("No Device Connected"); + return null; + } else { + for (int i = 1; i < lines.length; i++) { + lines[i] = lines[i].replaceAll("\\s+", ""); + + if (lines[i].contains("device")) { + lines[i] = lines[i].replaceAll("device", ""); + String deviceID = lines[i]; + deviceSerail.add(deviceID); + } else if (lines[i].contains("unauthorized")) { + lines[i] = lines[i].replaceAll("unauthorized", ""); + String deviceID = lines[i]; + } else if (lines[i].contains("offline")) { + lines[i] = lines[i].replaceAll("offline", ""); + String deviceID = lines[i]; + } + } + return deviceSerail; + } + } + + /* + * This method gets the device model name + */ + public String getDeviceModel(String deviceID) { + String deviceModelName = null; + String brand = null; + String deviceModel = null; + try { + deviceModelName = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model") + .replaceAll("\\W", ""); + + brand = cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand"); + } catch (InterruptedException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + deviceModel = deviceModelName.concat("_" + brand); + + return deviceModel.trim(); + + } + + /* + * This method gets the device OS API Level + */ + public String deviceOS(String deviceID) { + String deviceOSLevel = null; + try { + deviceOSLevel = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk") + .replaceAll("\\W", ""); + } catch (InterruptedException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return deviceOSLevel; + + } + + /** + * This method will close the running app + * + * @throws IOException + * @throws InterruptedException + */ + public void closeRunningApp(String deviceID, String app_package) + throws InterruptedException, IOException { + // adb -s 192.168.56.101:5555 com.android2.calculator3 + cmd.runCommand("adb -s " + deviceID + " shell am force-stop " + app_package); + } + + /** + * This method clears the app data only for android + * + * @throws IOException + * @throws InterruptedException + */ + public void clearAppData(String deviceID, String app_package) + throws InterruptedException, IOException { + // adb -s 192.168.56.101:5555 com.android2.calculator3 + cmd.runCommand("adb -s " + deviceID + " shell pm clear " + app_package); + } + + /** + * This method removes apk from the devices attached + * + * @param app_package + * @throws Exception + */ + + public void removeApkFromDevices(String deviceID, String app_package) throws Exception { + cmd.runCommand("adb -s " + deviceID + " uninstall " + app_package); + } + + public String screenRecord(String deviceID, String fileName) + throws IOException, InterruptedException { + return "adb -s " + deviceID + " shell screenrecord --bit-rate 3000000 /sdcard/" + fileName + + ".mp4"; + } + + public boolean checkIfRecordable(String deviceID) throws IOException, InterruptedException { + String screenrecord = + cmd.runCommand("adb -s " + deviceID + " shell ls /system/bin/screenrecord"); + if (screenrecord.trim().equals("/system/bin/screenrecord")) { + return true; + } else { + return false; + } + } + + public String getDeviceManufacturer(String deviceID) throws IOException, InterruptedException { + return cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.manufacturer") + .trim(); + } + + public AndroidDeviceConfiguration pullVideoFromDevice(String deviceID, String fileName, + String destination) throws IOException, InterruptedException { + ProcessBuilder pb = + new ProcessBuilder("adb", "-s", deviceID, "pull", "/sdcard/" + fileName + ".mp4", + destination); + Process pc = pb.start(); + pc.waitFor(); + System.out.println("Exited with Code::" + pc.exitValue()); + System.out.println("Done"); + Thread.sleep(5000); + return new AndroidDeviceConfiguration(); + } + + public void removeVideoFileFromDevice(String deviceID, String fileName) + throws IOException, InterruptedException { + cmd.runCommand("adb -s " + deviceID + " shell rm -f /sdcard/" + fileName + ".mp4"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.lang.Process` acquired to `com.appium.utils.CommandPrompt.p` by call to `runCommand(...)` at line 61 is not released after line 63. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Map AndroidDeviceConfiguration.getDevices() + +### Procedure Id: +com.appium.manager.AndroidDeviceConfiguration.getDevices():java.util.Map.3f7f267efe46020ad2fb48490d4b57fe + +### File: +src/main/java/com/appium/manager/AndroidDeviceConfiguration.java + +### Key: +AndroidDeviceConfiguration.java|getDevices|RESOURCE_LEAK + +### Node Key: +241d42dae50053d7648ace8f5b7dfc3f + +### Hash: +fce917702e9b7cf60c3f9a71a2a84b3c + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10443/instruction.md b/inferredbugs-10443/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..710d796425c839d7692321f4d204012f274cfa62 --- /dev/null +++ b/inferredbugs-10443/instruction.md @@ -0,0 +1,215 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** AppiumTestDistribution +**Bug ID:** 46 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.appium.utils; + +import com.appium.entities.MobilePlatform; +import com.appium.ios.IOSDeviceConfiguration; +import com.appium.manager.DeviceManager; +import com.thoughtworks.device.SimulatorManager; +import io.appium.java_client.remote.AndroidMobileCapabilityType; +import io.appium.java_client.remote.AutomationName; +import io.appium.java_client.remote.IOSMobileCapabilityType; +import io.appium.java_client.remote.MobileCapabilityType; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.openqa.selenium.remote.DesiredCapabilities; + +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.util.Optional; + +/** + * Created by saikrisv on 20/05/17. + */ +public class DesiredCapabilityBuilder { + + private AvailablePorts availablePorts; + private IOSDeviceConfiguration iosDevice; + private SimulatorManager simulatorManager; + + public static ThreadLocal desiredCapabilitiesThreadLocal + = new ThreadLocal<>(); + + public DesiredCapabilityBuilder() throws IOException { + availablePorts = new AvailablePorts(); + iosDevice = new IOSDeviceConfiguration(); + simulatorManager = new SimulatorManager(); + } + + public static DesiredCapabilities getDesiredCapability() { + return desiredCapabilitiesThreadLocal.get(); + } + + public DesiredCapabilities buildDesiredCapability(String platform, + String jsonPath) throws Exception { + final boolean[] flag = {false}; + DesiredCapabilities desiredCapabilities = new DesiredCapabilities(); + JSONArray jsonParsedObject = new JsonParser(jsonPath).getJsonParsedObject(); + Object getPlatformObject = jsonParsedObject.stream().filter(o -> ((JSONObject) o) + .get(platform) != null) + .findFirst(); + Object platFormCapabilities = ((JSONObject) ((Optional) getPlatformObject) + .get()).get(platform); + ((JSONObject) platFormCapabilities) + .forEach((caps, values) -> { + if ("browserName".equals(caps) && "chrome".equals(values.toString())) { + flag[0] = true; + try { + desiredCapabilities.setCapability("chromeDriverPort", + availablePorts.getPort()); + } catch (Exception e) { + e.printStackTrace(); + } + } + if ("app".equals(caps)) { + if (values instanceof JSONObject) { + if (DeviceManager.getDeviceUDID().length() + == IOSDeviceConfiguration.SIM_UDID_LENGTH) { + values = ((JSONObject) values).get("simulator"); + } else if (DeviceManager.getDeviceUDID().length() + == IOSDeviceConfiguration.IOS_UDID_LENGTH) { + values = ((JSONObject) values).get("device"); + } + + } + Path path = FileSystems.getDefault().getPath(values.toString()); + if (!path.getParent().isAbsolute()) { + desiredCapabilities.setCapability(caps.toString(), path.normalize() + .toAbsolutePath().toString()); + } else { + desiredCapabilities.setCapability(caps.toString(), path + .toString()); + } + } else { + desiredCapabilities.setCapability(caps.toString(), values.toString()); + } + }); + if (DeviceManager.getMobilePlatform().equals(MobilePlatform.ANDROID) && !flag[0]) { + if (desiredCapabilities.getCapability("automationName") == null + || desiredCapabilities.getCapability("automationName") + .toString() != "UIAutomator2") { + desiredCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, + AutomationName.ANDROID_UIAUTOMATOR2); + desiredCapabilities.setCapability(AndroidMobileCapabilityType.SYSTEM_PORT, + availablePorts.getPort()); + } + appPackage(desiredCapabilities); + } else if (DeviceManager.getMobilePlatform().equals(MobilePlatform.IOS)) { + String version = iosDevice.getIOSDeviceProductVersion(); + appPackageBundle(desiredCapabilities); + //Check if simulator.json exists and add the deviceName and OS + if (DeviceManager.getDeviceUDID().length() == IOSDeviceConfiguration.SIM_UDID_LENGTH) { + desiredCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, + simulatorManager.getSimulatorDetailsFromUDID( + DeviceManager.getDeviceUDID()).getName()); + desiredCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, + simulatorManager.getSimulatorDetailsFromUDID(DeviceManager.getDeviceUDID()) + .getOsVersion()); + } else { + desiredCapabilities.setCapability("webkitDebugProxyPort", + new IOSDeviceConfiguration().startIOSWebKit()); + } + + if (Float.valueOf(version.substring(0, version.length() - 2)) >= 10.0) { + desiredCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, + AutomationName.IOS_XCUI_TEST); + desiredCapabilities.setCapability(IOSMobileCapabilityType + .WDA_LOCAL_PORT, availablePorts.getPort()); + } + desiredCapabilities.setCapability(MobileCapabilityType.UDID, + DeviceManager.getDeviceUDID()); + } + desiredCapabilities.setCapability(MobileCapabilityType.UDID, + DeviceManager.getDeviceUDID()); + desiredCapabilitiesThreadLocal.set(desiredCapabilities); + return desiredCapabilities; + } + + public void appPackage(DesiredCapabilities desiredCapabilities) { + if (System.getenv("APP_PACKAGE") != null) { + desiredCapabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, + System.getenv("APP_PACKAGE")); + } + } + + private void appPackageBundle(DesiredCapabilities iOSCapabilities) { + if (System.getenv("APP_PACKAGE") != null) { + iOSCapabilities + .setCapability(IOSMobileCapabilityType.BUNDLE_ID, + System.getenv("APP_PACKAGE")); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `platFormCapabilities` last assigned on line 51 could be null and is dereferenced at line 53. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +DesiredCapabilities DesiredCapabilityBuilder.buildDesiredCapability(String,String) + +### Procedure Id: +com.appium.utils.DesiredCapabilityBuilder.buildDesiredCapability(java.lang.String,java.lang.String):.1e592248a79f85c18f480a097fdc6cbb + +### File: +src/main/java/com/appium/utils/DesiredCapabilityBuilder.java + +### Key: +DesiredCapabilityBuilder.java|buildDesiredCapability|NULL_DEREFERENCE + +### Node Key: +b1887f614aafef5d306f8e3a5966dfc4 + +### Hash: +c502c95102f0c587d94e5b649a97b200 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10444/instruction.md b/inferredbugs-10444/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c66425bc41ab8a5a77e1efa1ede760468bff94c --- /dev/null +++ b/inferredbugs-10444/instruction.md @@ -0,0 +1,303 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** AppiumTestDistribution +**Bug ID:** 41 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.appium.manager; + +import com.appium.utils.CommandPrompt; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class AndroidDeviceConfiguration { + + private CommandPrompt cmd = new CommandPrompt(); + private Map devices = new HashMap(); + public static ArrayList deviceSerail = new ArrayList(); + ArrayList deviceModel = new ArrayList(); + + /** + * This method start adb server + */ + public void startADB() throws Exception { + String output = cmd.runCommand("adb start-server"); + String[] lines = output.split("\n"); + if (lines[0].contains("internal or external command")) { + System.out.println("Please set ANDROID_HOME in your system variables"); + } + } + + /** + * This method stop adb server + */ + public void stopADB() throws Exception { + cmd.runCommand("adb kill-server"); + } + + /** + * This method return connected devices + * + * @return hashmap of connected devices information + */ + public Map getDevices() throws Exception { + + startADB(); // start adb service + String output = cmd.runCommand("adb devices"); + String[] lines = output.split("\n"); + + if (lines.length <= 1) { + System.out.println("No Device Connected"); + stopADB(); + return null; + } else { + for (int i = 1; i < lines.length; i++) { + lines[i] = lines[i].replaceAll("\\s+", ""); + + if (lines[i].contains("device")) { + lines[i] = lines[i].replaceAll("device", ""); + String deviceID = lines[i]; + String model = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model") + .replaceAll("\\s+", ""); + String brand = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand") + .replaceAll("\\s+", ""); + String osVersion = cmd.runCommand( + "adb -s " + deviceID + " shell getprop ro.build.version.release") + .replaceAll("\\s+", ""); + String deviceName = brand + " " + model; + String apiLevel = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk") + .replaceAll("\n", ""); + + devices.put("deviceID" + i, deviceID); + devices.put("deviceName" + i, deviceName); + devices.put("osVersion" + i, osVersion); + devices.put(deviceID, apiLevel); + } else if (lines[i].contains("unauthorized")) { + lines[i] = lines[i].replaceAll("unauthorized", ""); + String deviceID = lines[i]; + } else if (lines[i].contains("offline")) { + lines[i] = lines[i].replaceAll("offline", ""); + String deviceID = lines[i]; + } + } + return devices; + } + } + + public ArrayList getDeviceSerial() throws Exception { + + startADB(); // start adb service + String output = cmd.runCommand("adb devices"); + String[] lines = output.split("\n"); + + if (lines.length <= 1) { + System.out.println("No Device Connected"); + return null; + } else { + for (int i = 1; i < lines.length; i++) { + lines[i] = lines[i].replaceAll("\\s+", ""); + + if (lines[i].contains("device")) { + lines[i] = lines[i].replaceAll("device", ""); + String deviceID = lines[i]; + deviceSerail.add(deviceID); + } else if (lines[i].contains("unauthorized")) { + lines[i] = lines[i].replaceAll("unauthorized", ""); + String deviceID = lines[i]; + } else if (lines[i].contains("offline")) { + lines[i] = lines[i].replaceAll("offline", ""); + String deviceID = lines[i]; + } + } + return deviceSerail; + } + } + + /* + * This method gets the device model name + */ + public String getDeviceModel(String deviceID) { + String deviceModelName = null; + String brand = null; + String deviceModel = null; + try { + deviceModelName = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model") + .replaceAll("\\W", ""); + + brand = cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand"); + } catch (InterruptedException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + deviceModel = deviceModelName.concat("_" + brand); + + return deviceModel.trim(); + + } + + /* + * This method gets the device OS API Level + */ + public String deviceOS(String deviceID) { + String deviceOSLevel = null; + try { + deviceOSLevel = + cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk") + .replaceAll("\\W", ""); + } catch (InterruptedException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return deviceOSLevel; + + } + + /** + * This method will close the running app + * + * @throws IOException + * @throws InterruptedException + */ + public void closeRunningApp(String deviceID, String app_package) + throws InterruptedException, IOException { + // adb -s 192.168.56.101:5555 com.android2.calculator3 + cmd.runCommand("adb -s " + deviceID + " shell am force-stop " + app_package); + } + + /** + * This method clears the app data only for android + * + * @throws IOException + * @throws InterruptedException + */ + public void clearAppData(String deviceID, String app_package) + throws InterruptedException, IOException { + // adb -s 192.168.56.101:5555 com.android2.calculator3 + cmd.runCommand("adb -s " + deviceID + " shell pm clear " + app_package); + } + + /** + * This method removes apk from the devices attached + * + * @param app_package + * @throws Exception + */ + + public void removeApkFromDevices(String deviceID, String app_package) throws Exception { + cmd.runCommand("adb -s " + deviceID + " uninstall " + app_package); + } + + public String screenRecord(String deviceID, String fileName) + throws IOException, InterruptedException { + return "adb -s " + deviceID + " shell screenrecord --bit-rate 3000000 /sdcard/" + fileName + + ".mp4"; + } + + public boolean checkIfRecordable(String deviceID) throws IOException, InterruptedException { + String screenrecord = + cmd.runCommand("adb -s " + deviceID + " shell ls /system/bin/screenrecord"); + if (screenrecord.trim().equals("/system/bin/screenrecord")) { + return true; + } else { + return false; + } + } + + public String getDeviceManufacturer(String deviceID) throws IOException, InterruptedException { + return cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.manufacturer") + .trim(); + } + + public AndroidDeviceConfiguration pullVideoFromDevice(String deviceID, String fileName, + String destination) throws IOException, InterruptedException { + ProcessBuilder pb = + new ProcessBuilder("adb", "-s", deviceID, "pull", "/sdcard/" + fileName + ".mp4", + destination); + Process pc = pb.start(); + pc.waitFor(); + System.out.println("Exited with Code::" + pc.exitValue()); + System.out.println("Done"); + Thread.sleep(5000); + return new AndroidDeviceConfiguration(); + } + + public void removeVideoFileFromDevice(String deviceID, String fileName) + throws IOException, InterruptedException { + cmd.runCommand("adb -s " + deviceID + " shell rm -f /sdcard/" + fileName + ".mp4"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.lang.Process` acquired to `com.appium.utils.CommandPrompt.p` by call to `runCommand(...)` at line 43 is not released after line 58. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Map AndroidDeviceConfiguration.getDevices() + +### Procedure Id: +com.appium.manager.AndroidDeviceConfiguration.getDevices():java.util.Map.3f7f267efe46020ad2fb48490d4b57fe + +### File: +src/main/java/com/appium/manager/AndroidDeviceConfiguration.java + +### Key: +AndroidDeviceConfiguration.java|getDevices|RESOURCE_LEAK + +### Node Key: +241d42dae50053d7648ace8f5b7dfc3f + +### Hash: +fce917702e9b7cf60c3f9a71a2a84b3c + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1046/instruction.md b/inferredbugs-1046/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a23bfe50f7fcbc6b42bfe6ccb94f10914c551279 --- /dev/null +++ b/inferredbugs-1046/instruction.md @@ -0,0 +1,307 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** inotify +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Text.RegularExpressions; + +namespace Inotify.Sends +{ + public enum InputType + { + TEXT = 1, + CHECK = 2, + ENUM = 3, + } + + [AttributeUsage(AttributeTargets.Class)] + public class SendMethodKeyAttribute : Attribute + { + public string Key; + + public bool Open; + + public string Name; + + public int Order; + + public string Waring; + + public SendMethodKeyAttribute(string key, string name, bool open = true, string waring = "") + { + Key = key; + Name = name; + Open = open; + Waring = waring; + } + } + + public class InputTypeValue + { + + public InputTypeValue() + { + Show = true; + Readonly = false; + } + public string? Name { get; set; } + public string? Description { get; set; } + public string? Default { get; set; } + public InputType? Type { get; set; } + public int? Order { get; set; } + public string? Value { get; set; } + + public string? Warning { get; set; } + + public bool Show { get; set; } + + public bool Readonly { get; set; } + } + + public class InputTemeplate + { + public string? Type { get; set; } + public string? TypeName { get; set; } + public string? Key { get; set; } + public string? Name { get; set; } + public bool IsActive { get; set; } + public string Warning { get; set; } + public string? AuthData { get; set; } + public int? SendAuthId { get; set; } + public List? Values { get; set; } + + public string TemplateToAuth() + { + var jObject = new JObject(); + + if (Values != null) + { + foreach (var item in Values) + { + if (item.Name != null && item.Value != null) + { + if (item.Type == InputType.CHECK) + { + jObject.Add(item.Name, item.Value.ToLower() == "true"); + } + else + { + jObject.Add(item.Name, item.Value); + } + } + } + } + + return jObject.ToString(); + } + + public void AuthToTemplate(string authInfo) + { + if (!string.IsNullOrEmpty(authInfo)) + { + var jObject = JObject.Parse(authInfo); + + if (Values != null) + { + foreach (var value in Values) + { + if (value.Name != null) + { + if (jObject.TryGetValue(value.Name, out JToken? jtoken)) + { + value.Value = jtoken == null ? "" : jtoken.Value(); + } + } + } + } + } + AuthData = authInfo; + } + } + + [AttributeUsage(AttributeTargets.Property)] + [JsonObject(MemberSerialization.OptIn)] + public class InputTypeAttribte : Attribute + { + public InputTypeValue InputTypeData { get; set; } + + + private InputTypeAttribte(int order, string name, string description, string defaultValue, InputType type, bool show = true, bool readOnly = false) + { + InputTypeData = new InputTypeValue + { + Name = name, + Description = description, + Default = defaultValue, + Order = order, + Type = type, + Show = show, + Readonly = readOnly + }; + } + + public InputTypeAttribte(int order, string name, string description, string defaultValue, bool show = true, bool readOnly = false) + : this(order, name, description, defaultValue, InputType.TEXT, show, readOnly) + { + + } + + public InputTypeAttribte(int order, string name, string description, bool defaultValue, bool show = true, bool readOnly = false) + : this(order, name, description, "", InputType.CHECK, show, readOnly) + { + InputTypeData.Default = defaultValue ? "是" : "否"; + } + } + + + public abstract class SendTemplate + { + public T Auth { get; set; } + + public void Composition(string authInfo) + { + Auth = JsonConvert.DeserializeObject(authInfo); + } + + public InputTemeplate GetTemeplate() + { + var values = typeof(T) + .GetProperties() + .SelectMany(e => e.GetCustomAttributes(typeof(InputTypeAttribte), false)) + .Cast() + .Select(e => e.InputTypeData) + .ToList(); + + var sendMethodKeyAttribute = GetType().GetCustomAttribute(); + + if (sendMethodKeyAttribute != null) + { + return new InputTemeplate() + { + Key = "", + Name = sendMethodKeyAttribute.Name, + Type = sendMethodKeyAttribute.Key, + TypeName = sendMethodKeyAttribute.Name, + Warning = sendMethodKeyAttribute.Waring, + Values = values + }; + } + + return null; + } + + public abstract bool SendMessage(SendMessage message); + + + protected WebProxy GetProxy() + { + if (SendCacheStore.GetSystemValue("proxyenable") == "true") + { + var proxyurl = SendCacheStore.GetSystemValue("proxy"); + if (proxyurl != null) + { + + WebProxy proxy = new WebProxy + { + Address = new Uri(proxyurl) + }; + return proxy; + } + } + return null; + } + + protected bool IsUrl(string url) + { + var regex = new Regex(@"(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]"); + if (!regex.IsMatch(url)) + { + return false; + } + return true; + } + + protected bool IsImage(string url) + { + var regex = new Regex(@".*?(jpeg|jpe|png|jpg)"); + if (!regex.IsMatch(url)) + { + return false; + } + return true; + } + + protected byte[] GetImage(string url) + { + if (IsUrl(url) && IsImage(url)) + { + WebClient mywebclient = new WebClient(); + return mywebclient.DownloadData(url); + } + return null; + } + } + + +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource mywebclient of type System.Net.WebClient in method "Byte[] SendTemplate`1.GetImage(String)". + +### Severity: +ERROR + +### Procedure: +Byte[] SendTemplate`1.GetImage(String) + +### File: +Inotify/Sends/SendTemplate.cs + +### Key: +SendTemplate.cs|GetImage|DOTNET_RESOURCE_LEAK + +### Hash: +4e6b7ea887fd0b76b787666b1fb919c3 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1047/instruction.md b/inferredbugs-1047/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f63e58d2ba7e5fd44b1097282bb7f4dbf5d0e07d --- /dev/null +++ b/inferredbugs-1047/instruction.md @@ -0,0 +1,113 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** inotify +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Inotify.Data; +using Inotify.Sends; + +using Microsoft.AspNetCore.Mvc; + +namespace Inotify.Controllers +{ + [ApiController] + [Route("api")] + public class SendController : BaseControlor + { + [HttpGet, Route("send")] + public JsonResult Send(string token, string title, string? data, string? key) + { + if (DBManager.Instance.IsToken(token, out bool hasActive)) + { + if (!hasActive) + { + return Fail(400, "you have no tunnel is acitve"); + } + + if (!string.IsNullOrEmpty(key)) + { + if (DBManager.Instance.IsSendKey(key, out bool isActive)) + { + if (!isActive) + { + return Fail(400, $"device:{key} tunnel is not acitve"); + } + } + else + { + return Fail(400, $"device:{key} is not registered"); + } + } + + var message = new SendMessage() + { + Token = token, + Title = title, + Data = data, + Key = key, + }; + + if (SendTaskManager.Instance.SendMessage(message)) + { + return OK(); + } + } + + return Fail(400, $"token:{token} is not registered"); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from Inotify.Data.DBManager Inotify.Data.DBManager::get_Instance() at Line 24).Inotify.Data.DBManager.m_migrator of type NPoco.Migrations.Migrator, Leaked resource (returned from Inotify.Data.DBManager Inotify.Data.DBManager::get_Instance() at Line 24).Inotify.Data.DBManager.m_dbConnection of type Microsoft.Data.Sqlite.SqliteConnection, Leaked resource (returned from Inotify.Data.DBManager Inotify.Data.DBManager::get_Instance() at Line 15).Inotify.Data.DBManager.m_migrator of type NPoco.Migrations.Migrator, Leaked resource (returned from Inotify.Data.DBManager Inotify.Data.DBManager::get_Instance() at Line 15).Inotify.Data.DBManager.m_dbConnection of type Microsoft.Data.Sqlite.SqliteConnection in method "JsonResult SendController.Send(String,String,String,String)". + +### Severity: +ERROR + +### Procedure: +JsonResult SendController.Send(String,String,String,String) + +### File: +Inotify/Controllers/SendControlor.cs + +### Key: +SendControlor.cs|Send|DOTNET_RESOURCE_LEAK + +### Hash: +1ba04b4a6335aa98e5ce048666d00786 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10472/instruction.md b/inferredbugs-10472/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..41ade563a72f0c96024d548484c728d6ed49a864 --- /dev/null +++ b/inferredbugs-10472/instruction.md @@ -0,0 +1,777 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jHiccup +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Written by Gil Tene of Azul Systems, and released to the public domain, + * as explained at http://creativecommons.org/publicdomain/zero/1.0/ + * + * @author Gil Tene + */ + +package org.jhiccup; + +import org.HdrHistogram.*; + +import java.io.*; +import java.util.*; +import java.text.SimpleDateFormat; +import java.lang.management.*; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +/** + * HiccupMeter is a platform pause measurement tool, it is meant to observe + * the underlying platform (JVM, OS, HW, etc.) responsiveness while under + * an unrelated application load, and establish a lower bound for the stalls + * the application would experience. It can be run as a wrapper around + * other applications so that measurements can be done without any changes + * to application code. + *

+ * The purpose of HiccupMeter is to aid application operators and testers + * in characterizing the inherent "platform hiccups" (execution stalls) + * that a Java platform will display when running under load. The hiccups + * measured are NOT stalls caused by the application's code. They are stalls + * caused by the platform (JVM, OS, HW, etc.) that would be visible to and + * affect any application thread running on the platform at the time of the + * stall. It is generally safe to assume that if HiccupMeter experiences and + * records a certain level of measured platform hiccups, the application + * running on the same JVM platform during that time had experienced + * hiccup/stall effects that are at least as large as the measured level. + *

+ * HiccupMeter's measurement works on the simple basis of measuring the time + * it takes an effectively empty workload to perform work (while running + * alongside whatever load the platform is carrying). Hiccup measurements are + * performed by a thread that repeatedly sleeps for a given interval (-r for + * resolutionMs, defaults to 1 msec), and logs the amount of time it took to + * actually wake up each time in a detailed internal hiccup histogram. The + * assumption is that if the measuring thread experienced some delay in waking + * up, any other thread in the system could/would have experienced a similar + * delay, resulting in application stalls. + *

+ * HiccupMeter collects both raw and corrected (weighted) histogram results. + * When the reported time in a histogram exceeds the interval used between + * measurements, the raw histogram data would reflect only the single reported + * results, while the corrected histogram data will reflect an appropriate + * number of additional results with linearly decreasing times (down to a time + * that is lower than the measurement interval). While raw and corrected + * histogram data are both tracked internally, it is the corrected numbers that + * are logged and reported, as they will more accurately reflect the response + * time that a random, uncoordinated request would have experienced. + *

+ * HiccupMeter logs a single line with hiccup %'ile stats each reporting + * interval (set with -i , defaults to 5000 msec) to a + * log file. The log file name can be optionally controlled with the -l + * flag, and will default (if no logfile name is supplied)to a name derived from + * the process id and time (hiccup.yyMMdd.HHmm.pid). HiccupMeter will also produce + * a detailed histogram log file under the .histogram name. A new + * histogram log file will be produced each interval, and will replace the + * one generated in the previous interval. + *

+ * HiccupMeter can be configured to delay the start of measurement + * (using the -d flag, defaults to 30000 msec). It can also be + * configured to terminate measurement after a given length of time (using the + * -t flag). If the -t flag is not used, HiccupMeter will continue + * to run until the Class executed with via the -exec parameter (see below) + * exits, or indefinitely (if no -exec is used). + *

+ * HiccupMeter can be configured to launch a separate "control process" on + * startup (using the -c flag, defaulting to + * nothing). This option launches a separate, standalone instance of + * HiccupMeter wrapping running an idle workload, such that a concurrent + * control measurement is established on the same system, at the same time + * as the main observed application load is run. + *

+ * For convenience in testing, HiccupMeter is typically launched as a + * javaagent. For example, if your program were normally executed as: + *

+ * java UsefulProgram -a -b -c + *

+ * This is how you would execute the same program so that HiccupMeter would + * record hiccups while it is running: + *

+ * java -javaagent:jHiccup.jar UsefulProgram -a -b -c + *

+ * Common use example: + *

+ * Measure internal jitter of JVM running MyProg, log into logFile and + * logFile.hgrm, report in 5 seconds intervals (which is the default), start + * measurements 60 seconds into the run, and run concurrent control process + * that will record hiccups on an idle workload running at the same time, + * logging those into c.logFile and c.logFile.hgrm: + *

+ * java -javaagent:jHiccup.jar="-d 60000 -l testLog -c c.testlog" MyProg + *

+ * Note: while HiccupMeter is typically executed as a javaagent, it can be + * run as a standalone program, in which case it will execute for the + * duration of time specified with the -t option, or if the + * -terminateOnStdIn flag is used, it will terminate execution when standard + * input is severed. This last option is useful for executing HiccupMeter as + * a standalone control process launched from a javaagent HiccupMeter + * instance. + * + * Note: HiccupMeter can be used to process data from an input file instead + * of sampling it. When the [-f inputFileName] option is used, the input file + * is expected to contain two white-space delimited values per line (in either + * integer or real number format), representing a time stamp and a measured + * latency, both in millisecond units. It's important to note that the default + * "expected interval between samples" resolution in jHiccup and HiccupMeter + * is 1 millisecond. When processing input files, it is imperative that the + * appropriate value be supplied to the -r option, and that this value correctly + * represent the expected interval between samples in the provided input file. + * HiccupMeter will use this parameter to determine whether additional, artificial + * values should be added to the histogram recording, between input samples that + * are farther apart in time than the expected interval specified to the -r option. + * This behavior corrects for "coordinated omission" situations (where long response + * times lead to "skipped" requests that would have typically correlated with "bad" + * response times). A "large" value (e.g. -r 100000) can easily be specified to + * avoid any correction of this situation. + * + * Note: HiccupMeter makes systemic use of HdrHistogram to collected and report + * on the statistical distribution of hiccups. HdrHistogram sources, documentation, + * and a ready to use jar file can all be found on GitHub, + * at http://giltene.github.com/HdrHistogram + */ + + +public class HiccupMeter extends Thread { + + private static final String versionString = "jHiccup version " + Version.version; + + static final String defaultHiccupLogFileName = "hiccup.%date.%pid.hlog"; + + protected final PrintStream log; + + protected final HistogramLogWriter histogramLogWriter; + + protected final HiccupMeterConfiguration config; + + protected static class HiccupMeterConfiguration { + public boolean terminateWithStdInput = false; + public double resolutionMs = 1.0; + public long runTimeMs = 0; + public long reportingIntervalMs = 5000; + public long startDelayMs = 30000; + public boolean startDelayMsExplicitlySpecified = false; + + public boolean verbose = false; + public boolean allocateObjects = false; + public String logFileName; + public boolean logFileExplicitlySpecified = false; + public String inputFileName = null; + public boolean logFormatCsv = false; + + public boolean launchControlProcess = false; + public String controlProcessLogFileName = null; + public String controlProcessCommand = null; + public boolean controlProcessJvmArgsExplicitlySpecified = false; + public String controlProcessJvmArgs; + + public boolean attachToProcess = false; + public String pidOfProcessToAttachTo = null; + public String agentJarFileName = null; + public String agentArgs = null; + + public boolean startTimeAtZero = false; + + public long lowestTrackableValue = 1000L * 20L; // default to ~20usec best-case resolution + public long highestTrackableValue = 3600 * 1000L * 1000L * 1000L; + public int numberOfSignificantValueDigits = 2; + + public boolean error = false; + public String errorMessage = ""; + + String fillInPidAndDate(String logFileName) { + final String processName = + java.lang.management.ManagementFactory.getRuntimeMXBean().getName(); + final String processID = processName.split("@")[0]; + final SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd.HHmm"); + final String formattedDate = formatter.format(new Date()); + + logFileName = logFileName.replaceAll("%pid", processID); + logFileName = logFileName.replaceAll("%date", formattedDate); + return logFileName; + } + + public HiccupMeterConfiguration(final String[] args, String defaultLogFileName) { + logFileName = defaultLogFileName; + try { + for (int i = 0; i < args.length; ++i) { + if (args[i].equals("-v")) { + verbose = true; + } else if (args[i].equals("-0")) { + startTimeAtZero = true; + } else if (args[i].equals("-p")) { + attachToProcess = true; + pidOfProcessToAttachTo = args[++i]; + } else if (args[i].equals("-j")) { + agentJarFileName = args[++i]; + } else if (args[i].equals("-terminateWithStdInput")) { + terminateWithStdInput = true; + } else if (args[i].equals("-i")) { + reportingIntervalMs = Long.parseLong(args[++i]); + } else if (args[i].equals("-t")) { + runTimeMs = Long.parseLong(args[++i]); + } else if (args[i].equals("-d")) { + startDelayMs = Long.parseLong(args[++i]); + startDelayMsExplicitlySpecified = true; + } else if (args[i].equals("-r")) { + resolutionMs = Double.parseDouble(args[++i]); + } else if (args[i].equals("-s")) { + numberOfSignificantValueDigits = Integer.parseInt(args[++i]); + } else if (args[i].equals("-l")) { + logFileName = args[++i]; + logFileExplicitlySpecified = true; + } else if (args[i].equals("-f")) { + inputFileName = args[++i]; + } else if (args[i].equals("-c")) { + launchControlProcess = true; + } else if (args[i].equals("-x")) { + controlProcessJvmArgs = args[++i]; + controlProcessJvmArgsExplicitlySpecified = true; + } else if (args[i].equals("-o")) { + logFormatCsv = true; + } else { + throw new Exception("Invalid args: " + args[i]); + } + } + + logFileName = fillInPidAndDate(logFileName); + + if (attachToProcess) { + if (!startDelayMsExplicitlySpecified) { + startDelayMs = 0; + } + + if (agentJarFileName == null) { + throw new Exception("Invalid args, missing agent jar file name, specify with -j option"); + } + agentArgs = "-d " + startDelayMs + + " -i " + reportingIntervalMs + + ((startTimeAtZero) ? " -0" : "") + + " -s " + numberOfSignificantValueDigits + + " -r " + resolutionMs; + + if (logFileExplicitlySpecified) { + agentArgs += " -l " + logFileName; + } + + if (launchControlProcess) { + agentArgs += " -c"; + } + + if (controlProcessJvmArgsExplicitlySpecified) { + agentArgs += " -x " + controlProcessJvmArgs; + } + + if (verbose) { + agentArgs += " -v"; + } + + if (logFormatCsv) { + agentArgs += " -o"; + } + } + + if (launchControlProcess) { + File filePath = new File(logFileName); + String parentFileNamePart = filePath.getParent(); + + String childFileNamePart = filePath.getName(); + // Derive control process log file name from logFileName: + File controlFilePath = new File(parentFileNamePart, childFileNamePart + ".c"); + controlProcessLogFileName = controlFilePath.getPath(); + + // Derive controlProcessCommand from our java home, class name, and parsed + // options: + controlProcessCommand = + System.getProperty("java.home") + + File.separator + "bin" + File.separator + "java" + + (controlProcessJvmArgsExplicitlySpecified ? " " + controlProcessJvmArgs : "") + + " -cp " + System.getProperty("java.class.path") + + " -Dorg.jhiccup.avoidRecursion=true" + + " " + HiccupMeter.class.getCanonicalName() + + " -l " + controlProcessLogFileName + + " -i " + reportingIntervalMs + + " -d " + startDelayMs + + ((startTimeAtZero) ? " -0" : "") + + ((logFormatCsv) ? " -o" : "") + + " -s " + numberOfSignificantValueDigits + + " -r " + resolutionMs + + " -terminateWithStdInput"; + } + if (resolutionMs < 0) { + System.err.println("resolutionMs must be positive."); + System.exit(1); + } + } catch (Exception e) { + error = true; + errorMessage = "Error: launched with the following args:\n"; + + for (String arg : args) { + errorMessage += arg + " "; + } + errorMessage += "\nWhich was parsed as an error, indicated by the following exception:\n" + e; + + System.err.println(errorMessage); + + String validArgs = + "\"[-v] [-c] [-x controlProcessArgs] [-o] [-0] [-n] [-p pidOfProcessToAttachTo] [-j jHiccupJarFileName] " + + "[-i reportingIntervalMs] [-h] [-t runTimeMs] [-d startDelayMs] " + + "[-l logFileName] [-r resolutionMs] [-terminateWithStdInput] [-f inputFileName]\"\n"; + + System.err.println("valid arguments = " + validArgs); + + System.err.println( + " [-h] help\n" + + " [-v] verbose\n" + + " [-l logFileName] Log hiccup information into logFileName and logFileName.hgrm\n" + + " (will replace occurrences of %pid and %date with appropriate information)\n" + + " [-o] Output log files in CSV format\n" + + " [-c] Launch a control process in a separate JVM\n" + + " logging hiccup data into logFileName.c and logFileName.c.hgrm\n" + + " [-x controlProcessArgs] Pass additional args to the control process JVM\n" + + " [-p pidOfProcessToAttachTo] Attach to the process with given pid and inject jHiccup as an agent\n" + + " [-j jHiccupJarFileName] File name for the jHiccup.jar file, and required with [-p] option above\n" + + " [-d startDelayMs] Delay the beginning of hiccup measurement by\n" + + " startDelayMs milliseconds [default 30000]\n" + + " [-0] Start timestamps at 0 (as opposed to at JVM runtime at start point)\n" + + " [-i reportingIntervalMs] Set reporting interval [default 5000]\n" + + " [-r resolutionMs] Set sampling resolution in milliseconds [default 1]\n" + + " [-t runTimeMs] Limit measurement time [default 0, for infinite]\n" + + " [-terminateWithStdInput] Take over standard input, and terminate process when\n" + + " standard input is severed (useful for control\n" + + " processes that wish to terminate when their launching\n" + + " parent does).\n" + + " [-f inputFileName] Read timestamp and latency data from input file\n" + + " instead of sampling it directly\n" + + " [-s numberOfSignificantValueDigits]\n"); + } + } + } + + public HiccupMeter(final String[] args, String defaultLogFileName) throws FileNotFoundException { + this.setName("HiccupMeter"); + config = new HiccupMeterConfiguration(args, defaultLogFileName); + log = new PrintStream(new FileOutputStream(config.logFileName), false); + histogramLogWriter = new HistogramLogWriter(log); + this.setDaemon(true); + } + + public static class ExecProcess extends Thread { + final String processName; + final String command; + final boolean verbose; + final PrintStream log; + + public ExecProcess(final String command, final String processName, + final PrintStream log, final boolean verbose) { + this.setDaemon(true); + this.setName(processName + "ExecThread"); + this.command = command; + this.processName = processName; + this.log = log; + this.verbose = verbose; + this.start(); + } + + public void run() { + try { + if (verbose) { + log.println("# HiccupMeter Executing " + processName + " command: " + command); + } + final Process p = Runtime.getRuntime().exec(command); + p.waitFor(); + } catch (Exception e) { + System.err.println("HiccupMeter: " + processName + " terminated."); + } + } + } + + class TerminateWithStdInputReader extends Thread { + TerminateWithStdInputReader() { + this.setDaemon(true); + this.setName("terminateWithStdInputReader"); + this.start(); + } + + @Override + public void run() { + // Ensure exit when stdin is severed. + try { + while (System.in.read() >= 0) { + } + System.exit(1); + } catch (Exception e) { + System.exit(1); + } + + } + } + + public class HiccupRecorder extends Thread { + public volatile boolean doRun; + private final boolean allocateObjects; + public volatile Long lastSleepTimeObj; // public volatile to make sure allocs are not optimized away... + protected final SingleWriterRecorder recorder; + + public HiccupRecorder(final SingleWriterRecorder recorder, final boolean allocateObjects) { + this.setDaemon(true); + this.setName("HiccupRecorder"); + this.recorder = recorder; + this.allocateObjects = allocateObjects; + doRun = true; + } + + public void terminate() { + doRun = false; + } + + + public long getCurrentTimeMsecWithDelay(final long nextReportingTime) throws InterruptedException { + final long now = System.currentTimeMillis(); + if (now < nextReportingTime) + Thread.sleep(nextReportingTime - now); + return now; + } + + public void run() { + final long resolutionNsec = (long)(config.resolutionMs * 1000L * 1000L); + try { + long shortestObservedDeltaTimeNsec = Long.MAX_VALUE; + while (doRun) { + final long timeBeforeMeasurement = System.nanoTime(); + if (config.resolutionMs != 0) { + TimeUnit.NANOSECONDS.sleep(resolutionNsec); + if (allocateObjects) { + // Allocate an object to make sure potential allocation stalls are measured. + lastSleepTimeObj = new Long(timeBeforeMeasurement); + } + } + final long timeAfterMeasurement = System.nanoTime(); + final long deltaTimeNsec = timeAfterMeasurement - timeBeforeMeasurement; + + if (deltaTimeNsec < shortestObservedDeltaTimeNsec) { + shortestObservedDeltaTimeNsec = deltaTimeNsec; + } + + long hiccupTimeNsec = deltaTimeNsec - shortestObservedDeltaTimeNsec; + + recorder.recordValueWithExpectedInterval(hiccupTimeNsec, resolutionNsec); + } + } catch (InterruptedException e) { + if (config.verbose) { + log.println("# HiccupRecorder interrupted/terminating..."); + } + } + } + } + + class InputRecorder extends HiccupRecorder { + final Scanner scanner; + + InputRecorder(final SingleWriterRecorder recorder, final String inputFileName) { + super(recorder, false); + Scanner newScanner = null; + try { + newScanner = new Scanner(new File(inputFileName)); + } catch (FileNotFoundException e) { + System.err.println("HiccupMeter: Failed to open input file \"" + inputFileName + "\""); + System.exit(-1); + } finally { + scanner = newScanner; + } + } + + long processInputLine(final Scanner scanner, final SingleWriterRecorder recorder) { + if (scanner.hasNextLine()) { + try { + final long timeMsec = (long) scanner.nextDouble(); // Timestamp is expect to be in millis + final long hiccupTimeNsec = (long) (scanner.nextDouble() * 1000000L); // Latency is expected to be in millis + recorder.recordValueWithExpectedInterval(hiccupTimeNsec, (long)(config.resolutionMs * 1000000L)); + return timeMsec; + } catch (java.util.NoSuchElementException e) { + return -1; + } + } + return -1; + } + + @Override + public long getCurrentTimeMsecWithDelay(final long nextReportingTime) throws InterruptedException { + return processInputLine(scanner, recorder); + } + + @Override + public void run() { + try { + while (doRun) { + Thread.sleep(10); + } + } catch (InterruptedException e) { + if (config.verbose) { + log.println("# HiccupRecorder interrupted/terminating..."); + } + } + } + } + + public HiccupRecorder createHiccupRecorder(SingleWriterRecorder recorder) { + return new HiccupRecorder(recorder, config.allocateObjects); + } + + public String getVersionString() { + return versionString; + } + + @Override + public void run() { + final SingleWriterRecorder recorder = + new SingleWriterRecorder( + config.lowestTrackableValue, + config.highestTrackableValue, + config.numberOfSignificantValueDigits + ); + + Histogram intervalHistogram = null; + + HiccupRecorder hiccupRecorder; + + final long uptimeAtInitialStartTime = ManagementFactory.getRuntimeMXBean().getUptime(); + long now = System.currentTimeMillis(); + long jvmStartTime = now - uptimeAtInitialStartTime; + long reportingStartTime = jvmStartTime; + + if (config.inputFileName == null) { + // Normal operating mode. + // Launch a hiccup recorder, a process termination monitor, and an optional control process: + hiccupRecorder = this.createHiccupRecorder(recorder); + if (config.terminateWithStdInput) { + new TerminateWithStdInputReader(); + } + if (config.controlProcessCommand != null) { + new ExecProcess(config.controlProcessCommand, "ControlProcess", log, config.verbose); + } + } else { + // Take input from file instead of sampling it ourselves. + // Launch an input hiccup recorder, but no termination monitoring or control process: + hiccupRecorder = new InputRecorder(recorder, config.inputFileName); + } + + histogramLogWriter.outputComment("[Logged with " + getVersionString() + "]"); + histogramLogWriter.outputLogFormatVersion(); + + try { + final long startTime; + + if (config.inputFileName == null) { + // Normal operating mode: + if (config.startDelayMs > 0) { + // Run hiccup recorder during startDelayMs time to let code warm up: + hiccupRecorder.start(); + while (config.startDelayMs > System.currentTimeMillis() - jvmStartTime) { + Thread.sleep(100); + } + hiccupRecorder.terminate(); + hiccupRecorder.join(); + + recorder.reset(); + hiccupRecorder = new HiccupRecorder(recorder, config.allocateObjects); + } + hiccupRecorder.start(); + startTime = System.currentTimeMillis(); + if (config.startTimeAtZero) { + reportingStartTime = startTime; + } + + histogramLogWriter.outputStartTime(reportingStartTime); + histogramLogWriter.setBaseTime(reportingStartTime); + + } else { + // Reading from input file, not sampling ourselves...: + hiccupRecorder.start(); + reportingStartTime = startTime = hiccupRecorder.getCurrentTimeMsecWithDelay(0); + + histogramLogWriter.outputComment("[Data read from input file \"" + config.inputFileName + "\" at " + new Date() + "]"); + } + + histogramLogWriter.outputLegend(); + + long nextReportingTime = startTime + config.reportingIntervalMs; + + while ((now > 0) && ((config.runTimeMs == 0) || (config.runTimeMs > now - startTime))) { + now = hiccupRecorder.getCurrentTimeMsecWithDelay(nextReportingTime); // could return -1 to indicate termination + if (now > nextReportingTime) { + // Get the latest interval histogram and give the recorder a fresh Histogram for the next interval + intervalHistogram = recorder.getIntervalHistogram(intervalHistogram); + + while (now > nextReportingTime) { + nextReportingTime += config.reportingIntervalMs; + } + + if (intervalHistogram.getTotalCount() > 0) { + histogramLogWriter.outputIntervalHistogram(intervalHistogram); + } + } + } + } catch (InterruptedException e) { + if (config.verbose) { + log.println("# HiccupMeter terminating..."); + } + } + + try { + hiccupRecorder.terminate(); + hiccupRecorder.join(); + } catch (InterruptedException e) { + if (config.verbose) { + log.println("# HiccupMeter terminate/join interrupted"); + } + } + } + + public static HiccupMeter commonMain(final String[] args, boolean exitOnError) { + HiccupMeter hiccupMeter = null; + try { + hiccupMeter = new HiccupMeter(args, defaultHiccupLogFileName); + + if (hiccupMeter.config.attachToProcess) { + String errorMessage = "Cannot use -p option with HiccupMeter (use HiccupMeterAttacher instead)"; + if (exitOnError) { + System.err.println(errorMessage); + System.exit(1); + } else { + throw new RuntimeException("Error: " + errorMessage); + } + } + + if (hiccupMeter.config.error) { + if (exitOnError) { + System.exit(1); + } else { + throw new RuntimeException("Error: " + hiccupMeter.config.errorMessage); + } + } + + if (hiccupMeter.config.verbose) { + hiccupMeter.log.print("# Executing: HiccupMeter"); + for (String arg : args) { + hiccupMeter.log.print(" " + arg); + } + hiccupMeter.log.println(""); + } + + hiccupMeter.start(); + + } catch (FileNotFoundException e) { + System.err.println("HiccupMeter: Failed to open log file."); + } + return hiccupMeter; + } + + public static void agentmain(String argsString, java.lang.instrument.Instrumentation inst) { + final String[] args = ((argsString != null) && !argsString.equals("")) ? argsString.split("[ ,;]+") : new String[0]; + final String avoidRecursion = System.getProperty("org.jhiccup.avoidRecursion"); + if (avoidRecursion != null) { + return; // If this is a -c invocation, we do not want the agent to do anything... + } + commonMain(args, false); + } + + public static void premain(String argsString, java.lang.instrument.Instrumentation inst) { + final String[] args = ((argsString != null) && !argsString.equals("")) ? argsString.split("[ ,;]+") : new String[0]; + final String avoidRecursion = System.getProperty("org.jhiccup.avoidRecursion"); + if (avoidRecursion != null) { + return; // If this is a -c invocation, we do not want the agent to do anything... + } + commonMain(args, true); + } + + public static void main(final String[] args) { + final HiccupMeter hiccupMeter = commonMain(args, true); + + if (hiccupMeter != null) { + // The HiccupMeter thread, on it's own, will not keep the JVM from exiting. If nothing else + // is running (i.e. we we are the main class), then keep main thread from exiting + // until the HiccupMeter thread does... + try { + hiccupMeter.join(); + } catch (InterruptedException e) { + if (hiccupMeter.config.verbose) { + hiccupMeter.log.println("# HiccupMeter main() interrupted"); + } + } + } + } +} + + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired by call to `HiccupMeter$InputRecorder(...)` at line 554 is not released after line 621. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void HiccupMeter.run() + +### Procedure Id: +org.jhiccup.HiccupMeter.run():void.93e8a87af287213cccc081a8a61e8ba9 + +### File: +src/main/java/org/jhiccup/HiccupMeter.java + +### Key: +HiccupMeter.java|run|RESOURCE_LEAK + +### Node Key: +b557d6b2918eb263209be8dd7349ace7 + +### Hash: +94e283f1e78ed667c00b1269818c2cca + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10475/instruction.md b/inferredbugs-10475/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2016c5a41babff1d4e812e9394235ed3078d536f --- /dev/null +++ b/inferredbugs-10475/instruction.md @@ -0,0 +1,271 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** opensearchserver +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * License Agreement for Jaeksoft SearchLib Community + * + * Copyright (C) 2008 Emmanuel Keller / Jaeksoft + * + * http://www.jaeksoft.com + * + * This file is part of Jaeksoft SearchLib Community. + * + * Jaeksoft SearchLib Community 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 of the License, or + * (at your option) any later version. + * + * Jaeksoft SearchLib Community 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 Jaeksoft SearchLib Community. + * If not, see . + **/ + +package com.jaeksoft.searchlib.render; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.lucene.index.CorruptIndexException; +import org.apache.lucene.queryParser.ParseException; + +import com.jaeksoft.searchlib.facet.Facet; +import com.jaeksoft.searchlib.facet.FacetField; +import com.jaeksoft.searchlib.facet.FacetItem; +import com.jaeksoft.searchlib.facet.FacetList; +import com.jaeksoft.searchlib.function.expression.SyntaxError; +import com.jaeksoft.searchlib.highlight.HighlightField; +import com.jaeksoft.searchlib.request.SearchRequest; +import com.jaeksoft.searchlib.result.Result; +import com.jaeksoft.searchlib.result.ResultDocument; +import com.jaeksoft.searchlib.schema.Field; +import com.jaeksoft.searchlib.util.Debug; +import com.jaeksoft.searchlib.web.ServletTransaction; + +public class RenderXml implements Render { + + private PrintWriter writer; + private Result result; + private SearchRequest searchRequest; + + public RenderXml(Result result) { + this.result = result; + this.searchRequest = result.getSearchRequest(); + } + + private void renderPrefix() throws ParseException, SyntaxError { + writer.println(""); + writer.println(""); + writer.println("

"); + writer.println("\t0"); + writer.print("\t"); + writer.print(searchRequest.getQueryParsed()); + writer.println(""); + Debug debug = result.getDebug(); + if (debug != null) + debug.xmlInfo(writer); + writer.println("
"); + } + + private void renderSuffix() { + writer.println(""); + } + + private void renderDocuments() throws CorruptIndexException, IOException, + ParseException, SyntaxError { + SearchRequest searchRequest = result.getSearchRequest(); + int start = searchRequest.getStart(); + int end = result.getDocumentCount() + searchRequest.getStart(); + writer.print(""); + if (!searchRequest.isDelete()) + for (int i = start; i < end; i++) + this.renderDocument(i); + writer.println(""); + } + + private void renderDocument(int pos) throws CorruptIndexException, + IOException, ParseException, SyntaxError { + writer.print("\t"); + ResultDocument doc = result.getDocument(pos); + for (Field field : searchRequest.getReturnFieldList()) + renderField(doc, field); + for (HighlightField field : searchRequest.getHighlightFieldList()) + renderHighlightValue(doc, field); + + int cc = result.getCollapseCount(pos); + if (cc > 0) { + writer.print("\t\t"); + writer.print(cc); + writer.println(""); + } + writer.println("\t"); + } + + private void renderField(ResultDocument doc, Field field) + throws CorruptIndexException, IOException { + String fieldName = field.getName(); + List values = doc.getValueList(field); + if (values == null) + return; + writer.println(); + for (String v : values) { + writer.print("\t\t"); + writer.print(StringEscapeUtils.escapeJava(StringEscapeUtils + .escapeXml(v))); + writer.println(""); + } + } + + private void renderHighlightValue(ResultDocument doc, HighlightField field) + throws IOException { + String fieldName = field.getName(); + String[] snippets = doc.getSnippetArray(field); + if (snippets == null) + return; + boolean highlighted = doc.isHighlighted(field.getName()); + writer.println(); + for (String snippet : snippets) { + writer.print("\t\t'); + writer.print(StringEscapeUtils.escapeJava(StringEscapeUtils + .escapeXml(snippet))); + writer.println("\t\t"); + } + } + + private void renderFacet(Facet facet) throws Exception { + FacetField facetField = facet.getFacetField(); + writer.print("\t\t"); + for (FacetItem facetItem : facet) { + writer.print("\t\t\t"); + writer.print(facetItem.getCount()); + writer.print(""); + } + writer.println("\t\t"); + } + + private void renderFacets() throws Exception { + FacetList facetList = result.getFacetList(); + if (facetList == null) + return; + writer.println(""); + for (Facet facet : facetList) + renderFacet(facet); + writer.println(""); + } + + public void render(PrintWriter writer) throws Exception { + this.writer = writer; + renderPrefix(); + renderDocuments(); + renderFacets(); + renderSuffix(); + + } + + public void render(ServletTransaction servletTransaction) throws Exception { + render(servletTransaction.getWriter("UTF-8")); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `doc` last assigned on line 106 could be null and is dereferenced by call to `renderField(...)` at line 108. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RenderXml.renderDocument(int) + +### Procedure Id: +com.jaeksoft.searchlib.render.RenderXml.renderDocument(int):void.a5dcba488899bb94ba85fd2b6860d783 + +### File: +src/java/com/jaeksoft/searchlib/render/RenderXml.java + +### Key: +RenderXml.java|renderDocument|NULL_DEREFERENCE + +### Node Key: +09634589313b8637b1fe1e1bb0135b05 + +### Hash: +e507874cf836a650e8d1d10fd0a8cce8 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10481/instruction.md b/inferredbugs-10481/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ab2802ea1ed1f1ecfb5c9a08b950829555c07050 --- /dev/null +++ b/inferredbugs-10481/instruction.md @@ -0,0 +1,388 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** opensearchserver +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * License Agreement for Jaeksoft SearchLib Community + * + * Copyright (C) 2008 Emmanuel Keller / Jaeksoft + * + * http://www.jaeksoft.com + * + * This file is part of Jaeksoft SearchLib Community. + * + * Jaeksoft SearchLib Community 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 of the License, or + * (at your option) any later version. + * + * Jaeksoft SearchLib Community 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 Jaeksoft SearchLib Community. + * If not, see . + **/ + +package com.jaeksoft.searchlib.highlight; + +import java.io.Externalizable; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; +import java.util.TreeMap; + +import org.apache.lucene.index.Term; +import org.apache.lucene.index.TermPositionVector; +import org.apache.lucene.index.TermVectorOffsetInfo; +import org.apache.lucene.queryParser.ParseException; +import org.apache.lucene.search.Query; +import org.w3c.dom.Node; + +import com.jaeksoft.searchlib.function.expression.SyntaxError; +import com.jaeksoft.searchlib.index.ReaderLocal; +import com.jaeksoft.searchlib.request.SearchRequest; +import com.jaeksoft.searchlib.schema.Field; +import com.jaeksoft.searchlib.schema.FieldList; +import com.jaeksoft.searchlib.schema.SchemaField; +import com.jaeksoft.searchlib.util.External; +import com.jaeksoft.searchlib.util.XPathParser; + +public class HighlightField extends Field implements Externalizable { + + private FragmenterAbstract fragmenter; + private String tag; + private int maxDocChar; + private String separator; + private int maxSnippetSize; + private int maxSnippetNumber; + private String[] searchTerms; + + public HighlightField() { + } + + private HighlightField(Field field, String tag, int maxDocChar, + String separator, int maxSnippetNumber, int maxSnippetSize, + FragmenterAbstract fragmenter) { + super(field.getName()); + this.searchTerms = null; + this.tag = tag; + this.maxDocChar = maxDocChar; + this.separator = separator; + this.maxSnippetNumber = maxSnippetNumber; + this.maxSnippetSize = maxSnippetSize; + this.fragmenter = fragmenter; + } + + public HighlightField(Field field) { + this(field, "em", Integer.MAX_VALUE, "...", 5, 200, null); + } + + public HighlightField(HighlightField field) { + super(field.name); + this.searchTerms = field.searchTerms; + fragmenter = field.fragmenter; + tag = field.tag; + maxDocChar = field.maxDocChar; + separator = field.separator; + maxSnippetNumber = field.maxSnippetNumber; + maxSnippetSize = field.maxSnippetSize; + } + + /** + * + */ + private static final long serialVersionUID = 4048179036729127707L; + + /** + * Retourne la liste des champs "highlighter". + * + * @param xPath + * @param node + * @param target + * @throws ClassNotFoundException + * @throws IllegalAccessException + * @throws InstantiationException + */ + public static void copyHighlightFields(Node node, + FieldList source, FieldList target) + throws InstantiationException, IllegalAccessException, + ClassNotFoundException { + String fieldName = XPathParser.getAttributeString(node, "name"); + String tag = XPathParser.getAttributeString(node, "tag"); + if (tag == null) + tag = "em"; + int maxDocChar = XPathParser.getAttributeValue(node, "maxDocBytes"); + if (maxDocChar == 0) + XPathParser.getAttributeValue(node, "maxDocChar"); + if (maxDocChar == 0) + maxDocChar = Integer.MAX_VALUE; + int maxSnippetNumber = XPathParser.getAttributeValue(node, + "maxSnippetNumber"); + if (maxSnippetNumber == 0) + maxSnippetNumber = 1; + int maxSnippetSize = XPathParser.getAttributeValue(node, + "maxSnippetSize"); + if (maxSnippetSize == 0) + maxSnippetSize = 200; + FragmenterAbstract fragmenter = FragmenterAbstract + .newInstance(XPathParser.getAttributeString(node, + "fragmenterClass")); + fragmenter.setAttributes(node.getAttributes()); + String separator = XPathParser.getAttributeString(node, "separator"); + if (separator == null) + separator = "..."; + HighlightField field = new HighlightField(source.get(fieldName), tag, + maxDocChar, separator, maxSnippetNumber, maxSnippetSize, + fragmenter); + target.add(field); + } + + private Iterator extractTermVectorIterator(int docId, + ReaderLocal reader) throws IOException, ParseException, SyntaxError { + if (searchTerms == null) + return null; + if (searchTerms.length == 0) + return null; + TermPositionVector termVector = (TermPositionVector) reader + .getTermFreqVector(docId, name); + if (termVector == null) + return null; + int[] termsIdx = termVector.indexesOf(searchTerms, 0, + searchTerms.length); + TreeMap map = new TreeMap(); + for (int termId : termsIdx) { + if (termId == -1) + continue; + TermVectorOffsetInfo[] offsets = termVector.getOffsets(termId); + for (TermVectorOffsetInfo offset : offsets) + map.put(offset.getStartOffset(), offset); + } + return map.values().iterator(); + } + + public void initSearchTerms(SearchRequest searchRequest) + throws ParseException, SyntaxError, IOException { + synchronized (this) { + Query query = searchRequest.getQuery(); + query.rewrite(null); + Set terms = new HashSet(); + query.extractTerms(terms); + String[] tempTerms = new String[terms.size()]; + int i = 0; + // Find term for that field only + for (Term term : terms) + if (name.equalsIgnoreCase(term.field())) + tempTerms[i++] = term.text(); + // Build final array + String[] finalTerms = new String[i]; + for (i = 0; i < finalTerms.length; i++) + finalTerms[i] = tempTerms[i]; + searchTerms = finalTerms; + } + } + + private TermVectorOffsetInfo checkValue(TermVectorOffsetInfo currentVector, + Iterator vectorIterator, int startOffset, + Fragment fragment) { + if (currentVector == null) + return null; + StringBuffer result = new StringBuffer(); + String originalText = fragment.getOriginalText(); + int originalTextLength = originalText.length(); + int endOffset = startOffset + originalTextLength; + int pos = 0; + while (currentVector != null) { + int end = currentVector.getEndOffset() - fragment.vectorOffset; + if (end > endOffset) + break; + int start = currentVector.getStartOffset() - fragment.vectorOffset; + if (start >= startOffset) { + result.append(originalText.substring(pos, start - startOffset)); + result.append("<"); + result.append(tag); + result.append(">"); + result.append(originalText.substring(start - startOffset, end + - startOffset)); + result.append(""); + pos = end - startOffset; + } + currentVector = vectorIterator.hasNext() ? vectorIterator.next() + : null; + } + if (result.length() == 0) + return currentVector; + if (pos < originalTextLength) + result.append(originalText.substring(pos, originalTextLength)); + fragment.setHighlightedText(result.toString()); + return currentVector; + } + + public boolean getSnippets(int docId, ReaderLocal reader, String[] values, + List snippets) throws IOException, ParseException, + SyntaxError { + + if (values == null) + return false; + TermVectorOffsetInfo currentVector = null; + Iterator vectorIterator = extractTermVectorIterator( + docId, reader); + if (vectorIterator != null) + currentVector = vectorIterator.hasNext() ? vectorIterator.next() + : null; + int startOffset = 0; + FragmentList fragments = new FragmentList(); + int vectorOffset = 0; + for (String value : values) { + if (value != null) { + // VectorOffset++ depends of EndOffset bug #patch Lucene 579 and + // 1458 + fragmenter.getFragments(value, fragments, vectorOffset); + if (fragments.getTotalSize() > maxDocChar) + break; + } + } + if (fragments.size() == 0) + return false; + ListIterator fragmentIterator = fragments.iterator(); + while (fragmentIterator.hasNext()) { + Fragment fragment = fragmentIterator.next(); + currentVector = checkValue(currentVector, vectorIterator, + startOffset, fragment); + startOffset += fragment.getOriginalText().length(); + } + + fragmentIterator = fragments.iterator(); + int snippetCounter = maxSnippetNumber; + while (snippetCounter-- != 0) { + Fragment fragment = fragments + .findNextHighlightedFragment(fragmentIterator); + if (fragment == null) + break; + StringBuffer snippet = fragments.getSnippet(maxSnippetSize, + separator, fragmentIterator, fragment); + if (snippet != null) + if (snippet.length() > 0) + snippets.add(snippet.toString()); + } + if (snippets.size() > 0) + return true; + + fragmentIterator = fragments.iterator(); + StringBuffer snippet = fragments.getSnippet(maxSnippetSize, separator, + fragmentIterator, fragmentIterator.next()); + if (snippet != null) + if (snippet.length() > 0) + snippets.add(snippet.toString()); + return false; + } + + public void readExternal(ObjectInput in) throws IOException, + ClassNotFoundException { + super.readExternal(in); + fragmenter = External.readObject(in); + tag = External.readUTF(in); + maxDocChar = in.readInt(); + separator = External.readUTF(in); + maxSnippetSize = in.readInt(); + maxSnippetNumber = in.readInt(); + int l = in.readInt(); + if (l > 0) { + searchTerms = new String[l]; + External.readArray(in, searchTerms); + } else + searchTerms = null; + } + + public void writeExternal(ObjectOutput out) throws IOException { + super.writeExternal(out); + External.writeObject(fragmenter, out); + External.writeUTF(tag, out); + out.writeInt(maxDocChar); + External.writeUTF(separator, out); + out.writeInt(maxSnippetSize); + out.writeInt(maxSnippetNumber); + External.writeArray(searchTerms, out); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.jaeksoft.searchlib.highlight.HighlightField.readExternal` reads without synchronization from `this.com.jaeksoft.searchlib.highlight.HighlightField.searchTerms`. Potentially races with write in method `HighlightField.initSearchTerms(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void HighlightField.readExternal(ObjectInput) + +### Procedure Id: +com.jaeksoft.searchlib.highlight.HighlightField.readExternal(java.io.ObjectInput):void.94a19401091dbe29506d241f86fd9da2 + +### File: +src/java/com/jaeksoft/searchlib/highlight/HighlightField.java + +### Key: +HighlightField.java|readExternal|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +f2e75196da2a217b62229b5b684890ac + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10486/instruction.md b/inferredbugs-10486/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..928156c7b70047f5a4eafbabeeab86fcabe3919c --- /dev/null +++ b/inferredbugs-10486/instruction.md @@ -0,0 +1,206 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** opensearchserver +**Bug ID:** 24 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * License Agreement for Jaeksoft OpenSearchServer + * + * Copyright (C) 2008-2009 Emmanuel Keller / Jaeksoft + * + * http://www.open-search-server.com + * + * This file is part of Jaeksoft OpenSearchServer. + * + * Jaeksoft OpenSearchServer 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 of the License, or + * (at your option) any later version. + * + * Jaeksoft OpenSearchServer 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 Jaeksoft OpenSearchServer. + * If not, see . + **/ + +package com.jaeksoft.searchlib.collapse; + +import java.io.IOException; + +import org.apache.lucene.queryParser.ParseException; +import org.apache.lucene.util.OpenBitSet; + +import com.jaeksoft.searchlib.function.expression.SyntaxError; +import com.jaeksoft.searchlib.request.SearchRequest; +import com.jaeksoft.searchlib.result.ResultScoreDoc; +import com.jaeksoft.searchlib.result.ResultSingle; + +public abstract class CollapseAbstract { + + private int collapsedDocCount; + private transient int collapseMax; + private transient String collapseField; + private transient CollapseMode collapseMode; + protected transient SearchRequest searchRequest; + private transient ResultScoreDoc[] collapsedDoc; + + protected CollapseAbstract(SearchRequest searchRequest) { + this.searchRequest = searchRequest; + this.collapseField = searchRequest.getCollapseField(); + this.collapseMax = searchRequest.getCollapseMax(); + this.collapseMode = searchRequest.getCollapseMode(); + this.collapsedDocCount = 0; + this.collapsedDoc = null; + } + + public void run(ResultScoreDoc[] fetchedDocs, int fetchLength) + throws IOException { + + collapsedDoc = null; + + if (fetchedDocs == null) + return; + + if (fetchLength > fetchedDocs.length) + fetchLength = fetchedDocs.length; + + OpenBitSet collapsedSet = new OpenBitSet(fetchLength); + + String lastTerm = null; + int adjacent = 0; + collapsedDocCount = 0; + for (int i = 0; i < fetchLength; i++) { + String term = fetchedDocs[i].collapseTerm; + if (term != null && term.equals(lastTerm)) { + if (++adjacent >= collapseMax) + collapsedSet.set(i); + } else { + lastTerm = term; + adjacent = 0; + } + } + collapsedDocCount = (int) collapsedSet.cardinality(); + + collapsedDoc = new ResultScoreDoc[fetchLength - collapsedDocCount]; + + int currentPos = 0; + ResultScoreDoc collapseDoc = null; + for (int i = 0; i < fetchLength; i++) { + if (!collapsedSet.get(i)) { + collapseDoc = fetchedDocs[i]; + collapseDoc.collapseCount = 0; + collapsedDoc[currentPos++] = collapseDoc; + } else { + collapseDoc.collapseCount++; + } + } + } + + public abstract ResultScoreDoc[] collapse(ResultSingle resultSingle) + throws IOException, ParseException, SyntaxError; + + public int getDocCount() { + return this.collapsedDocCount; + } + + protected String getCollapseField() { + return collapseField; + } + + public ResultScoreDoc[] getCollapsedDoc() { + return collapsedDoc; + } + + public CollapseMode getCollapseMode() { + return collapseMode; + } + + protected int getCollapsedDocsLength() { + if (collapsedDoc == null) + return 0; + return collapsedDoc.length; + } + + public static CollapseAbstract newInstance(SearchRequest searchRequest) { + CollapseMode mode = searchRequest.getCollapseMode(); + if (mode == CollapseMode.COLLAPSE_FULL) + return new CollapseFull(searchRequest); + else if (mode == CollapseMode.COLLAPSE_OPTIMIZED) + return new CollapseOptimized(searchRequest); + return null; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `collapseDoc` last assigned on line 86 could be null and is dereferenced at line 93. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CollapseAbstract.run(com.jaeksoft.searchlib.result.ResultScoreDoc[],int) + +### Procedure Id: +com.jaeksoft.searchlib.collapse.CollapseAbstract.run(com.jaeksoft.searchlib.result.ResultScoreDoc[],.9b514c33f74d54349b152323a11169f6 + +### File: +src/java/com/jaeksoft/searchlib/collapse/CollapseAbstract.java + +### Key: +CollapseAbstract.java|run|NULL_DEREFERENCE + +### Node Key: +12f1f1ccf6bf5f72377e5c7f02f1b45b + +### Hash: +5dc8dfbf44fc74e736d46828d61fde3c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10488/instruction.md b/inferredbugs-10488/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fdaef11b7b0b4baa8f71978c6bc39fe55f00a8e8 --- /dev/null +++ b/inferredbugs-10488/instruction.md @@ -0,0 +1,200 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** opensearchserver +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * License Agreement for Jaeksoft SearchLib Community + * + * Copyright (C) 2008-2009 Emmanuel Keller / Jaeksoft + * + * http://www.jaeksoft.com + * + * This file is part of Jaeksoft SearchLib Community. + * + * Jaeksoft SearchLib Community 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 of the License, or + * (at your option) any later version. + * + * Jaeksoft SearchLib Community 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 Jaeksoft SearchLib Community. + * If not, see . + **/ + +package com.jaeksoft.searchlib.web.controller.query; + +import java.util.ArrayList; +import java.util.List; + +import org.zkoss.zk.ui.event.Event; +import org.zkoss.zul.RowRenderer; + +import com.jaeksoft.searchlib.SearchLibException; +import com.jaeksoft.searchlib.facet.FacetField; +import com.jaeksoft.searchlib.schema.FieldList; +import com.jaeksoft.searchlib.schema.SchemaField; + +public class FacetController extends QueryController { + + /** + * + */ + private static final long serialVersionUID = 5748867672639969504L; + + private String selectedFacet = null; + + private List fieldLeft = null; + + private RowRenderer rowRenderer = null; + + public FacetController() throws SearchLibException { + super(); + } + + public RowRenderer getFacetFieldRenderer() { + synchronized (this) { + if (rowRenderer != null) + return rowRenderer; + rowRenderer = new FacetFieldRenderer(); + return rowRenderer; + } + } + + public boolean isFieldLeft() throws SearchLibException { + synchronized (this) { + return getFacetFieldLeft().size() > 0; + } + } + + public List getFacetFieldLeft() throws SearchLibException { + synchronized (this) { + if (fieldLeft != null) + return fieldLeft; + fieldLeft = new ArrayList(); + FieldList facetFields = getRequest() + .getFacetFieldList(); + for (SchemaField field : getClient().getSchema().getFieldList()) + if (field.isIndexed()) + if (facetFields.get(field.getName()) == null) { + if (selectedFacet == null) + selectedFacet = field.getName(); + fieldLeft.add(field.getName()); + } + return fieldLeft; + } + } + + public void onFacetRemove(Event event) throws SearchLibException { + synchronized (this) { + FacetField facetField = (FacetField) event.getData(); + getRequest().getFacetFieldList().remove(facetField); + reloadPage(); + } + } + + public void setSelectedFacet(String value) { + synchronized (this) { + selectedFacet = value; + } + } + + public String getSelectedFacet() { + synchronized (this) { + return selectedFacet; + } + } + + public void onFacetAdd() throws SearchLibException { + synchronized (this) { + if (selectedFacet == null) + return; + getRequest().getFacetFieldList().add( + new FacetField(selectedFacet, 0, false)); + reloadPage(); + } + } + + @Override + protected void reloadPage() { + fieldLeft = null; + selectedFacet = null; + super.reloadPage(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.jaeksoft.searchlib.web.controller.query.FacetController.reloadPage` writes to field `this.com.jaeksoft.searchlib.web.controller.query.FacetController.selectedFacet` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void FacetController.reloadPage() + +### Procedure Id: +com.jaeksoft.searchlib.web.controller.query.FacetController.reloadPage():void.acf7e3b2743ec502b15db2ee674a8536 + +### File: +src/java/com/jaeksoft/searchlib/web/controller/query/FacetController.java + +### Key: +FacetController.java|reloadPage|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +9150b06139f239a6726c4a672d12de32 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1049/instruction.md b/inferredbugs-1049/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..faa97f31c01027eaa6d4d27cee80e2bd3aeda903 --- /dev/null +++ b/inferredbugs-1049/instruction.md @@ -0,0 +1,233 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Nancy +**Bug ID:** 33 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace Nancy.Tests.Unit +{ + using System; + using System.Collections.Generic; + using System.IO; + using Xunit; + + public class RequestFixture + { + [Fact] + public void Should_throw_argumentnullexception_when_initialized_with_null_method() + { + // Given, When + var exception = + Record.Exception(() => new Request(null, "/")); + + // Then + exception.ShouldBeOfType(); + } + + [Fact] + public void Should_throw_argumentoutofrangeexception_when_initialized_with_empty_method() + { + // Given, When + var exception = + Record.Exception(() => new Request(string.Empty, "/")); + + // Then + exception.ShouldBeOfType(); + } + + [Fact] + public void Should_throw_argumentnullexception_when_initialized_with_null_uri() + { + // Given, When + var exception = + Record.Exception(() => new Request("GET", null)); + + // Then + exception.ShouldBeOfType(); + } + + [Fact] + public void Should_throw_argumentoutofrangeexception_when_initialized_with_empty_uri() + { + // Given, When + var exception = + Record.Exception(() => new Request("GET", string.Empty)); + + // Then + exception.ShouldBeOfType(); + } + + [Fact] + public void Should_throw_argumentnullexception_when_initialized_with_null_headers() + { + // Given, When + var exception = + Record.Exception(() => new Request("GET", "/", null, new MemoryStream())); + + // Then + exception.ShouldBeOfType(); + } + + [Fact] + public void Should_throw_argumentnullexception_when_initialized_with_null_body() + { + // Given, When + var exception = + Record.Exception(() => new Request("GET", "/", new Dictionary>(), null)); + + // Then + exception.ShouldBeOfType(); + } + + [Fact] + public void Should_set_method_parameter_value_to_method_property_when_initialized() + { + // Given + const string method = "GET"; + + // When + var request = new Request(method, "/"); + + // Then + request.Method.ShouldEqual(method); + } + + [Fact] + public void Should_set_uri_parameter_value_to_uri_property_when_initialized() + { + // Given + const string uri = "/"; + + // When + var request = new Request("GET", uri); + + // Then + request.Uri.ShouldEqual(uri); + } + + [Fact] + public void Should_set_header_parameter_value_to_header_property_when_initialized() + { + // Given + var headers = new Dictionary>(); + + // When + var request = new Request("GET", "/", headers, new MemoryStream()); + + // Then + request.Headers.ShouldBeSameAs(headers); + } + + [Fact] + public void Should_set_body_parameter_value_to_body_property_when_initialized() + { + // Given + var body = new MemoryStream(); + + // When + var request = new Request("GET", "/", new Dictionary>(), body); + + // Then + request.Body.ShouldBeSameAs(body); + } + + [Fact] + public void Should_set_extract_form_data_from_body_when_content_type_is_x_www_form_urlencoded() + { + // Given + const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D"; + var memory = new MemoryStream(); + var writer = new StreamWriter(memory); + writer.Write(bodyContent); + writer.Flush(); + memory.Position = 0; + + var headers = + new Dictionary> + { + { "content-type", new[] { "application/x-www-form-urlencoded" } } + }; + + // When + var request = new Request("POST", "/", headers, memory); + + // Then + ((string)request.Form.name).ShouldEqual("John Doe"); + } + + [Fact] + public void Should_be_able_to_invoke_form_repeatedly() + { + const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D"; + var memory = new MemoryStream(); + var writer = new StreamWriter(memory); + writer.Write(bodyContent); + writer.Flush(); + memory.Position = 0; + + var headers = + new Dictionary> + { + { "content-type", new[] { "application/x-www-form-urlencoded" } } + }; + + // When + var request = new Request("POST", "/", headers, memory); + request.Form.ToString(); + // Then + ((string)request.Form.name).ShouldEqual("John Doe"); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource request of type Nancy.Request, Leaked resource (output of System.IO.MemoryStream::.ctor() at Line 109) of type System.IO.MemoryStream in method "Void RequestFixture.Should_set_header_parameter_value_to_header_property_when_initialized()". + +### Severity: +ERROR + +### Procedure: +Void RequestFixture.Should_set_header_parameter_value_to_header_property_when_initialized() + +### File: +src/Nancy.Tests/Unit/RequestFixture.cs + +### Key: +RequestFixture.cs|Should_set_header_parameter_value_to_header_property_when_initialized|DOTNET_RESOURCE_LEAK + +### Hash: +01a15a19eaab17d4e99cf0071f347c38 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10553/instruction.md b/inferredbugs-10553/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..20c5f1f1f8934e52896dbcae71cc3fd5c5ee2025 --- /dev/null +++ b/inferredbugs-10553/instruction.md @@ -0,0 +1,371 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** pircbotx +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2010 Leon Blakey + * + * This file is part of PircBotX. + * + * PircBotX 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 of the License, or + * (at your option) any later version. + * + * PircBotX 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 PircBotX. If not, see . + */ +package org.pircbotx.test; + +import org.pircbotx.User; +import org.pircbotx.hooks.ChannelInfo.Event; +import org.pircbotx.hooks.Motd; +import org.pircbotx.hooks.Topic; +import org.pircbotx.hooks.UserList; +import org.pircbotx.hooks.helpers.BaseEvent; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.apache.commons.lang.StringUtils; +import org.pircbotx.Channel; +import org.pircbotx.ChannelListEntry; +import org.pircbotx.PircBotX; +import org.pircbotx.hooks.Action; +import org.pircbotx.hooks.ChannelInfo; +import org.pircbotx.hooks.helpers.MetaListener; +import org.testng.annotations.Test; +import static org.testng.Assert.*; + +/** + * + * @author Leon Blakey + */ +public class PircBotXTest { + public Class botClass = PircBotX.class; + final Signal signal = new Signal(); + PircBotXVisible bot = new PircBotXVisible() { + { + getListeners().addListener(new Listener()); + } + }; + + @Test + public void sendNamingTests() { + //Get all send method variations in one list + Map> sendMethods = new HashMap>(); + for (Method curMethod : botClass.getDeclaredMethods()) { + String name = curMethod.getName(); + if (name.startsWith("send")) { + if (!sendMethods.containsKey(name)) + sendMethods.put(name, new ArrayList()); + sendMethods.get(name).add(curMethod); + } + } + + //Exclude methods that don't make sense to have variations of + sendMethods.remove("sendRawLineViaQueue"); + sendMethods.remove("sendRawLine"); + + + for (Map.Entry> entry : sendMethods.entrySet()) { + List methods = entry.getValue(); + final String key = entry.getKey(); + + List requiredClassesBase = Collections.unmodifiableList(new ArrayList() { + { + add(String.class); + add(User.class); + add(BaseEvent.class); + //sendCTCP* and sendInvite shouldn't be sent to a channel + if (!key.startsWith("sendCTCP")) + add(Channel.class); + } + }); + + //---Make sure appropiate variations of a method exist---- + List requiredClasses = new ArrayList(requiredClassesBase); + for (Method curMethod : methods) { + Class firstParam = curMethod.getParameterTypes()[0]; + //Must exist + assertTrue(requiredClassesBase.contains(firstParam), "Unknown first parameter " + firstParam + " in method " + curMethod); + requiredClasses.remove(firstParam); + } + + //If something is left, then something is wrong! + assertTrue(requiredClasses.isEmpty(), "Method group " + key + " doesn't have a method(s) for " + StringUtils.join(requiredClasses, ", ")); + } + System.out.println("Success: PircBotX.send* methods work "); + } + + @Test + public void sendTest() { + //Setup + PircBotX bot = new PircBotX() { + @Override + public void sendAction(String target, String action) { + signal.set(target, action); + } + + @Override + public void sendCTCPCommand(String target, String command) { + signal.set(target, command); + } + + @Override + public void sendCTCPResponse(String target, String message) { + signal.set(target, message); + } + + @Override + public void sendInvite(String nick, String channel) { + signal.set(nick, channel); + } + + @Override + public void sendMessage(String target, String message) { + signal.set(target, message); + } + + @Override + public void sendNotice(String target, String notice) { + signal.set(target, notice); + } + }; + + //Make sure all methods call each other appropiatly + final String string = "AString"; + final User user = new User(bot, "AUser"); + final Channel chan = new Channel(bot, "AChannel"); + final BaseEvent event = new Action.Event(bot, user, chan, string); + + + bot.sendAction(event, string); + signal.compare("AUser", string); + + bot.sendAction(user, string); + signal.compare("AUser", string); + + bot.sendAction(chan, string); + signal.compare("AChannel", string); + + + bot.sendCTCPCommand(event, string); + signal.compare("AUser", string); + + bot.sendCTCPCommand(user, string); + signal.compare("AUser", string); + + + bot.sendCTCPResponse(event, string); + signal.compare("AUser", string); + + bot.sendCTCPResponse(user, string); + signal.compare("AUser", string); + + + bot.sendInvite(event, string); + signal.compare("AUser", string); + + bot.sendInvite(event, chan); + signal.compare("AUser", "AChannel"); + + bot.sendInvite(event, chan); + signal.compare("AUser", "AChannel"); + + bot.sendInvite(user, chan); + signal.compare("AUser", "AChannel"); + + bot.sendInvite(chan, chan); + signal.compare("AChannel", "AChannel"); + + + bot.sendMessage(event, string); + signal.compare("AUser", string); + + bot.sendMessage(user, string); + signal.compare("AUser", string); + + bot.sendMessage(chan, string); + signal.compare("AChannel", string); + + + bot.sendNotice(event, string); + signal.compare("AUser", string); + + bot.sendNotice(user, string); + signal.compare("AUser", string); + + bot.sendNotice(chan, string); + signal.compare("AChannel", string); + } + + @Test + public void processServerResponseTest() { + String aString = "I'm some super long string that has multiple words"; + + //Simulate /LIST response + bot.processServerResponse(321, "Channel :Users Name"); + bot.processServerResponse(322, "PircBotXUser #PircBotXChannel 99 :" + aString); + bot.processServerResponse(322, "PircBotXUser #PircBotXChannel1 100 :" + aString + aString); + bot.processServerResponse(322, "PircBotXUser #PircBotXChannel2 101 :" + aString + aString + aString); + bot.processServerResponse(323, ":End of /LIST"); + Set channels = ((ChannelInfo.Event) signal.event).getList(); + assertEquals(channels.size(), 3); + boolean channelParsed = false; + for (ChannelListEntry entry : channels) + if (entry.getName().equals("#PircBotXChannel1")) { + assertEquals(entry.getName(), "#PircBotXChannel1"); + assertEquals(entry.getTopic(), aString + aString); + assertEquals(entry.getUsers(), 100); + channelParsed = true; + } + assertEquals(channelParsed, true, "Channel #PircBotXChannel1 not found in /LIST results!"); + + //From a /TOPIC or /JOIN + Channel aChannel = bot.getChannel("#aChannel"); + bot.processServerResponse(332, "PircBotXUser #aChannel :" + aString + aString); + assertEquals(aChannel.getTopic(), aString + aString); + + bot.processServerResponse(333, "PircBotXUser #aChannel ISetTopic 1564842512"); + assertEquals(aChannel.getTopicSetter(), "ISetTopic"); + assertEquals(aChannel.getTopicTimestamp(), (long) 1564842512 * 1000); + } + + public class PircBotXVisible extends PircBotX { + @Override + public void processServerResponse(int code, String response) { + super.processServerResponse(code, response); + } + } + + public class Listener extends MetaListener { + @Override + public void onChannelInfo(Event event) { + signal.event = event; + } + + @Override + public void onMotd(Motd.Event event) { + signal.event = event; + } + + @Override + public void onTopic(Topic.Event event) { + signal.event = event; + } + + @Override + public void onUserList(UserList.Event event) { + signal.event = event; + } + } + + public class Signal { + public String target = null; + public String message = null; + public Channel chan = null; + public BaseEvent event = null; + + public void set(String target, String message) { + this.target = target; + this.message = message; + } + + public void set(String target, Channel chan) { + this.target = target; + this.chan = chan; + } + + public void compare(String expectTarget, String expectMessage) { + assertEquals(target, expectTarget); + assertEquals(message, expectMessage); + reset(); + } + + public void reset() { + target = null; + message = null; + chan = null; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `bot._outputThread` last assigned on line 109 could be null and is dereferenced by call to `sendAction(...)` at line 148. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PircBotXTest.sendTest() + +### Procedure Id: +org.pircbotx.test.PircBotXTest.sendTest():void.7f29f1bdefdc04d1af01fe48907ad5a5 + +### File: +src/test/java/org/pircbotx/test/PircBotXTest.java + +### Key: +PircBotXTest.java|sendTest|NULL_DEREFERENCE + +### Node Key: +2d351bb1a96c602adc152937ec412f90 + +### Hash: +93f1c3cef758049dc97c5967714f47ef + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10554/instruction.md b/inferredbugs-10554/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c9e1ffb3e8078d566923cc76a7623c447357d78 --- /dev/null +++ b/inferredbugs-10554/instruction.md @@ -0,0 +1,250 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** versions-maven-plugin +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.codehaus.mojo.versions; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException; +import org.apache.maven.artifact.versioning.ArtifactVersion; +import org.apache.maven.artifact.versioning.DefaultArtifactVersion; +import org.apache.maven.model.Dependency; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.codehaus.mojo.versions.api.ArtifactVersions; +import org.codehaus.mojo.versions.api.PomHelper; +import org.codehaus.mojo.versions.ordering.VersionComparator; +import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; + +import javax.xml.stream.XMLStreamException; +import java.util.Collection; +import java.util.Iterator; +import java.util.Arrays; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Replaces any release versions with the latest snapshot version (if it has been deployed). + * + * @author Stephen Connolly + * @goal use-latest-snapshots + * @requiresProject true + * @requiresDirectInvocation true + * @since 1.0-beta-1 + */ +public class UseLatestSnapshotsMojo + extends AbstractVersionsDependencyUpdaterMojo +{ + + /** + * Whether to allow the major version number to be changed. + * @parameter expression="${allowMajorUpdates}" default-value="false" + * @since 1.0-beta-1 + */ + protected Boolean allowMajorUpdates; + + /** + * Whether to allow the minor version number to be changed. + * @parameter expression="${allowMinorUpdates}" default-value="false" + * @since 1.0-beta-1 + */ + protected Boolean allowMinorUpdates; + + /** + * Whether to allow the incremental version number to be changed. + * @parameter expression="${allowIncrementalUpdates}" default-value="true" + * @since 1.0-beta-1 + */ + protected Boolean allowIncrementalUpdates; + + // ------------------------------ FIELDS ------------------------------ + + /** + * Pattern to match a snapshot version. + */ + public final Pattern matchSnapshotRegex = Pattern.compile( "^(.+)-((SNAPSHOT)|(\\d{8}\\.\\d{6}-\\d+))$" ); + + // ------------------------------ METHODS -------------------------- + + /** + * @param pom the pom to update. + * @throws org.apache.maven.plugin.MojoExecutionException + * when things go wrong + * @throws org.apache.maven.plugin.MojoFailureException + * when things go wrong in a very bad way + * @throws javax.xml.stream.XMLStreamException + * when things go wrong with XML streaming + * @see AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader) + */ + protected void update( ModifiedPomXMLEventReader pom ) + throws MojoExecutionException, MojoFailureException, XMLStreamException + { + try + { + if ( getProject().getDependencyManagement() != null && isProcessingDependencyManagement() ) + { + useLatestSnapshots( pom, getProject().getDependencyManagement().getDependencies() ); + } + if ( isProcessingDependencies() ) + { + useLatestSnapshots( pom, getProject().getDependencies() ); + } + } + catch ( ArtifactMetadataRetrievalException e ) + { + throw new MojoExecutionException( e.getMessage(), e ); + } + } + + private void useLatestSnapshots( ModifiedPomXMLEventReader pom, Collection dependencies ) + throws XMLStreamException, MojoExecutionException, ArtifactMetadataRetrievalException + { + int segment = determineUnchangedSegment(allowMajorUpdates, allowMinorUpdates, + allowIncrementalUpdates); + + Iterator i = dependencies.iterator(); + + while ( i.hasNext() ) + { + Dependency dep = (Dependency) i.next(); + + if ( isExcludeReactor() && isProducedByReactor( dep ) ) + { + getLog().info( "Ignoring reactor dependency: " + toString( dep ) ); + continue; + } + + String version = dep.getVersion(); + Matcher versionMatcher = matchSnapshotRegex.matcher( version ); + if ( !versionMatcher.matches() ) + { + getLog().debug( "Looking for latest snapshot of " + toString( dep ) ); + Artifact artifact = this.toArtifact( dep ); + if ( !isIncluded( artifact ) ) + { + continue; + } + + ArtifactVersions versions = getHelper().lookupArtifactVersions( artifact, false ); + final VersionComparator versionComparator = versions.getVersionComparator(); + final DefaultArtifactVersion lowerBound = new DefaultArtifactVersion( version ); + if ( segment + 1 > versionComparator.getSegmentCount( lowerBound ) ) + { + getLog().info( "Ignoring " + toString( dep ) + " as the version number is too short" ); + continue; + } + ArtifactVersion upperBound = segment >= 0 ? versionComparator.incrementSegment( lowerBound, segment ) : null; + getLog().info("Upper bound: " + upperBound.toString()); + ArtifactVersion[] newer = versions.getVersions( lowerBound, upperBound, true, false, false ); + getLog().debug( "Candidate versions " + Arrays.asList(newer)); + String latestVersion = null; + for ( int j = 0; j < newer.length; j++ ) + { + String newVersion = newer[j].toString(); + if ( matchSnapshotRegex.matcher( newVersion ).matches() ) + { + latestVersion = newVersion; + } + } + if ( latestVersion != null ) + { + if ( PomHelper.setDependencyVersion( pom, dep.getGroupId(), dep.getArtifactId(), version, + latestVersion ) ) + { + getLog().info( "Updated " + toString( dep ) + " to version " + latestVersion ); + } + } + } + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `upperBound` last assigned on line 151 could be null and is dereferenced at line 152. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void UseLatestSnapshotsMojo.useLatestSnapshots(ModifiedPomXMLEventReader,Collection) + +### Procedure Id: +org.codehaus.mojo.versions.UseLatestSnapshotsMojo.useLatestSnapshots(org.codehaus.mojo.versions.rewr.04620be21caead4028da7781dfe231ea + +### File: +src/main/java/org/codehaus/mojo/versions/UseLatestSnapshotsMojo.java + +### Key: +UseLatestSnapshotsMojo.java|useLatestSnapshots|NULL_DEREFERENCE + +### Node Key: +3677875e6aead27ee1320f16c80d8b0f + +### Hash: +f3826ac3286af464a4272b66bd7afb38 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10565/instruction.md b/inferredbugs-10565/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aca758d219f57f1f66bc1d99993b3aa4a1a5a542 --- /dev/null +++ b/inferredbugs-10565/instruction.md @@ -0,0 +1,1752 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** versions-maven-plugin +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.codehaus.mojo.versions.api; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; +import org.apache.maven.artifact.versioning.VersionRange; +import org.apache.maven.model.Dependency; +import org.apache.maven.model.Model; +import org.apache.maven.model.Parent; +import org.apache.maven.model.Plugin; +import org.apache.maven.model.Profile; +import org.apache.maven.model.ReportPlugin; +import org.apache.maven.model.io.xpp3.MavenXpp3Reader; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.profiles.ProfileManager; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.MavenProjectBuilder; +import org.apache.maven.project.ProjectBuildingException; +import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; +import org.codehaus.mojo.versions.utils.RegexUtils; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; +import org.codehaus.plexus.util.IOUtil; +import org.codehaus.plexus.util.ReaderFactory; +import org.codehaus.plexus.util.StringUtils; +import org.codehaus.plexus.util.xml.pull.XmlPullParserException; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.events.XMLEvent; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.Stack; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Helper class for modifying pom files. + * + * @author Stephen Connolly + * @since 1.0-alpha-3 + */ +public class PomHelper +{ + public static final String APACHE_MAVEN_PLUGINS_GROUPID = "org.apache.maven.plugins"; + + /** + * Gets the raw model before any interpolation what-so-ever. + * + * @param project The project to get the raw model for. + * @return The raw model. + * @throws IOException if the file is not found or if the file does not parse. + */ + public static Model getRawModel( MavenProject project ) + throws IOException + { + return getRawModel( project.getFile() ); + } + + /** + * Gets the raw model before any interpolation what-so-ever. + * + * @param moduleProjectFile The project file to get the raw model for. + * @return The raw model. + * @throws IOException if the file is not found or if the file does not parse. + */ + public static Model getRawModel( File moduleProjectFile ) + throws IOException + { + try (FileInputStream input = new FileInputStream( moduleProjectFile )) + { + return new MavenXpp3Reader().read( input ); + } + catch ( XmlPullParserException e ) + { + throw new IOException( e.getMessage(), e ); + } + } + + /** + * Gets the current raw model before any interpolation what-so-ever. + * + * @param modifiedPomXMLEventReader The {@link ModifiedPomXMLEventReader} to get the raw model for. + * @return The raw model. + * @throws IOException if the file is not found or if the file does not parse. + */ + public static Model getRawModel( ModifiedPomXMLEventReader modifiedPomXMLEventReader ) + throws IOException + { + try (StringReader stringReader = new StringReader( modifiedPomXMLEventReader.asStringBuilder().toString() )) + { + return new MavenXpp3Reader().read( stringReader ); + } + catch ( XmlPullParserException e ) + { + throw new IOException( e.getMessage(), e ); + } + } + + /** + * Searches the pom re-defining the specified property to the specified version. + * + * @param pom The pom to modify. + * @param profileId The profile in which to modify the property. + * @param property The property to modify. + * @param value The new value of the property. + * @return true if a replacement was made. + * @throws XMLStreamException if somethinh went wrong. + */ + public static boolean setPropertyVersion( final ModifiedPomXMLEventReader pom, final String profileId, + final String property, final String value ) + throws XMLStreamException + { + Stack stack = new Stack(); + String path = ""; + final Pattern propertyRegex; + final Pattern matchScopeRegex; + final Pattern projectProfileId; + boolean inMatchScope = false; + boolean madeReplacement = false; + if ( profileId == null ) + { + propertyRegex = Pattern.compile( "/project/properties/" + RegexUtils.quote( property ) ); + matchScopeRegex = Pattern.compile( "/project/properties" ); + projectProfileId = null; + } + else + { + propertyRegex = Pattern.compile( "/project/profiles/profile/properties/" + RegexUtils.quote( property ) ); + matchScopeRegex = Pattern.compile( "/project/profiles/profile" ); + projectProfileId = Pattern.compile( "/project/profiles/profile/id" ); + } + + pom.rewind(); + + while ( pom.hasNext() ) + { + XMLEvent event = pom.nextEvent(); + if ( event.isStartElement() ) + { + stack.push( path ); + path = path + "/" + event.asStartElement().getName().getLocalPart(); + + if ( propertyRegex.matcher( path ).matches() ) + { + pom.mark( 0 ); + } + else if ( matchScopeRegex.matcher( path ).matches() ) + { + // we're in a new match scope + // reset any previous partial matches + inMatchScope = profileId == null; + pom.clearMark( 0 ); + pom.clearMark( 1 ); + } + else if ( profileId != null && projectProfileId.matcher( path ).matches() ) + { + String candidateId = pom.getElementText(); + path = stack.pop(); // since getElementText will be after the end element + + inMatchScope = profileId.trim().equals( candidateId.trim() ); + } + } + if ( event.isEndElement() ) + { + if ( propertyRegex.matcher( path ).matches() ) + { + pom.mark( 1 ); + } + else if ( matchScopeRegex.matcher( path ).matches() ) + { + if ( inMatchScope && pom.hasMark( 0 ) && pom.hasMark( 1 ) ) + { + pom.replaceBetween( 0, 1, value ); + madeReplacement = true; + } + pom.clearMark( 0 ); + pom.clearMark( 1 ); + inMatchScope = false; + } + path = stack.pop(); + } + } + return madeReplacement; + } + + /** + * Searches the pom re-defining the project version to the specified version. + * + * @param pom The pom to modify. + * @param value The new value of the property. + * @return true if a replacement was made. + * @throws XMLStreamException if somethinh went wrong. + */ + public static boolean setProjectVersion( final ModifiedPomXMLEventReader pom, final String value ) + throws XMLStreamException + { + Stack stack = new Stack(); + String path = ""; + final Pattern matchScopeRegex; + boolean madeReplacement = false; + matchScopeRegex = Pattern.compile( "/project/version" ); + + pom.rewind(); + + while ( pom.hasNext() ) + { + XMLEvent event = pom.nextEvent(); + if ( event.isStartElement() ) + { + stack.push( path ); + path = path + "/" + event.asStartElement().getName().getLocalPart(); + + if ( matchScopeRegex.matcher( path ).matches() ) + { + pom.mark( 0 ); + } + } + if ( event.isEndElement() ) + { + if ( matchScopeRegex.matcher( path ).matches() ) + { + pom.mark( 1 ); + if ( pom.hasMark( 0 ) && pom.hasMark( 1 ) ) + { + pom.replaceBetween( 0, 1, value ); + madeReplacement = true; + } + pom.clearMark( 0 ); + pom.clearMark( 1 ); + } + path = stack.pop(); + } + } + return madeReplacement; + } + + /** + * Retrieves the project version from the pom. + * + * @param pom The pom. + * @return the project version or null if the project version is not defined (i.e. inherited from + * parent version). + * @throws XMLStreamException if something went wrong. + */ + public static String getProjectVersion( final ModifiedPomXMLEventReader pom ) + throws XMLStreamException + { + Stack stack = new Stack(); + String path = ""; + final Pattern matchScopeRegex = Pattern.compile( "/project/version" ); + + pom.rewind(); + + while ( pom.hasNext() ) + { + XMLEvent event = pom.nextEvent(); + if ( event.isStartElement() ) + { + stack.push( path ); + path = path + "/" + event.asStartElement().getName().getLocalPart(); + + if ( matchScopeRegex.matcher( path ).matches() ) + { + pom.mark( 0 ); + } + } + if ( event.isEndElement() ) + { + if ( matchScopeRegex.matcher( path ).matches() ) + { + pom.mark( 1 ); + if ( pom.hasMark( 0 ) && pom.hasMark( 1 ) ) + { + return pom.getBetween( 0, 1 ).trim(); + } + pom.clearMark( 0 ); + pom.clearMark( 1 ); + } + path = stack.pop(); + } + } + return null; + } + + /** + * Searches the pom re-defining the project version to the specified version. + * + * @param pom The pom to modify. + * @param value The new value of the property. + * @return true if a replacement was made. + * @throws XMLStreamException if somethinh went wrong. + */ + public static boolean setProjectParentVersion( final ModifiedPomXMLEventReader pom, final String value ) + throws XMLStreamException + { + Stack stack = new Stack(); + String path = ""; + final Pattern matchScopeRegex; + boolean madeReplacement = false; + matchScopeRegex = Pattern.compile( "/project/parent/version" ); + + pom.rewind(); + + while ( pom.hasNext() ) + { + XMLEvent event = pom.nextEvent(); + if ( event.isStartElement() ) + { + stack.push( path ); + path = path + "/" + event.asStartElement().getName().getLocalPart(); + + if ( matchScopeRegex.matcher( path ).matches() ) + { + pom.mark( 0 ); + } + } + if ( event.isEndElement() ) + { + if ( matchScopeRegex.matcher( path ).matches() ) + { + pom.mark( 1 ); + if ( pom.hasMark( 0 ) && pom.hasMark( 1 ) ) + { + pom.replaceBetween( 0, 1, value ); + madeReplacement = true; + } + pom.clearMark( 0 ); + pom.clearMark( 1 ); + } + path = stack.pop(); + } + } + return madeReplacement; + } + + /** + * Gets the parent artifact from the pom. + * + * @param pom The pom. + * @param helper The helper (used to create the artifact). + * @return The parent artifact or null if no parent is specified. + * @throws XMLStreamException if something went wrong. + */ + public static Artifact getProjectParent( final ModifiedPomXMLEventReader pom, VersionsHelper helper ) + throws XMLStreamException + { + Stack stack = new Stack<>(); + String path = ""; + final Pattern matchScopeRegex = Pattern.compile( "/project/parent((/groupId)|(/artifactId)|(/version))" ); + String groupId = null; + String artifactId = null; + String version = null; + + pom.rewind(); + + while ( pom.hasNext() ) + { + XMLEvent event = pom.nextEvent(); + if ( event.isStartElement() ) + { + stack.push( path ); + final String elementName = event.asStartElement().getName().getLocalPart(); + path = path + "/" + elementName; + + if ( matchScopeRegex.matcher( path ).matches() ) + { + if ( "groupId".equals( elementName ) ) + { + groupId = pom.getElementText().trim(); + path = stack.pop(); + } + else if ( "artifactId".equals( elementName ) ) + { + artifactId = pom.getElementText().trim(); + path = stack.pop(); + } + else if ( "version".equals( elementName ) ) + { + version = pom.getElementText().trim(); + path = stack.pop(); + } + } + } + if ( event.isEndElement() ) + { + path = stack.pop(); + } + } + if ( groupId == null || artifactId == null || version == null ) + { + return null; + } + return helper.createDependencyArtifact( groupId, artifactId, VersionRange.createFromVersion( version ), "pom", + null, null, false ); + } + + /** + * Searches the pom re-defining the specified dependency to the specified version. + * + * @param pom The pom to modify. + * @param groupId The groupId of the dependency. + * @param artifactId The artifactId of the dependency. + * @param oldVersion The old version of the dependency. + * @param newVersion The new version of the dependency. + * @param model The model to get the project properties from. + * @return true if a replacement was made. + * @throws XMLStreamException if something went wrong. + */ + public static boolean setDependencyVersion( final ModifiedPomXMLEventReader pom, final String groupId, + final String artifactId, final String oldVersion, + final String newVersion, final Model model ) + throws XMLStreamException + { + Stack stack = new Stack(); + String path = ""; + + Set implicitPaths = + new HashSet( Arrays.asList( "/project/parent/groupId", "/project/parent/artifactId", + "/project/parent/version", "/project/groupId", + "/project/artifactId", "/project/version" ) ); + Map implicitProperties = new HashMap(); + + for ( Map.Entry entry : model.getProperties().entrySet() ) + { + implicitProperties.put( (String) entry.getKey(), (String) entry.getValue() ); + } + + pom.rewind(); + + while ( pom.hasNext() ) + { + while ( pom.hasNext() ) + { + XMLEvent event = pom.nextEvent(); + if ( event.isStartElement() ) + { + stack.push( path ); + final String elementName = event.asStartElement().getName().getLocalPart(); + path = path + "/" + elementName; + + if ( implicitPaths.contains( path ) ) + { + final String elementText = pom.getElementText().trim(); + implicitProperties.put( path.substring( 1 ).replace( '/', '.' ), elementText ); + path = stack.pop(); + } + } + if ( event.isEndElement() ) + { + path = stack.pop(); + } + } + } + + boolean modified = true; + while ( modified ) + { + modified = false; + for ( Map.Entry entry : implicitProperties.entrySet() ) + { + if ( entry.getKey().contains( ".parent" ) ) + { + String child = entry.getKey().replace( ".parent", "" ); + if ( !implicitProperties.containsKey( child ) ) + { + implicitProperties.put( child, entry.getValue() ); + modified = true; + break; + } + } + } + } + + stack = new Stack<>(); + path = ""; + boolean inMatchScope = false; + boolean madeReplacement = false; + boolean haveGroupId = false; + boolean haveArtifactId = false; + boolean haveOldVersion = false; + + final Pattern matchScopeRegex = Pattern.compile( "/project" + "(/profiles/profile)?" + + "((/dependencyManagement)|(/build(/pluginManagement)?/plugins/plugin))?" + "/dependencies/dependency" ); + + final Pattern matchTargetRegex = Pattern.compile( "/project" + "(/profiles/profile)?" + + "((/dependencyManagement)|(/build(/pluginManagement)?/plugins/plugin))?" + "/dependencies/dependency" + + "((/groupId)|(/artifactId)|(/version))" ); + + pom.rewind(); + + while ( pom.hasNext() ) + { + XMLEvent event = pom.nextEvent(); + if ( event.isStartElement() ) + { + stack.push( path ); + final String elementName = event.asStartElement().getName().getLocalPart(); + path = path + "/" + elementName; + + if ( matchScopeRegex.matcher( path ).matches() ) + { + // we're in a new match scope + // reset any previous partial matches + inMatchScope = true; + pom.clearMark( 0 ); + pom.clearMark( 1 ); + + haveGroupId = false; + haveArtifactId = false; + haveOldVersion = false; + } + else if ( inMatchScope && matchTargetRegex.matcher( path ).matches() ) + { + if ( "groupId".equals( elementName ) ) + { + haveGroupId = groupId.equals( evaluate( pom.getElementText().trim(), implicitProperties ) ); + path = stack.pop(); + } + else if ( "artifactId".equals( elementName ) ) + { + haveArtifactId = + artifactId.equals( evaluate( pom.getElementText().trim(), implicitProperties ) ); + path = stack.pop(); + } + else if ( "version".equals( elementName ) ) + { + pom.mark( 0 ); + } + } + } + if ( event.isEndElement() ) + { + if ( matchTargetRegex.matcher( path ).matches() + && "version".equals( event.asEndElement().getName().getLocalPart() ) ) + { + pom.mark( 1 ); + String compressedPomVersion = StringUtils.deleteWhitespace( pom.getBetween( 0, 1 ).trim() ); + String compressedOldVersion = StringUtils.deleteWhitespace( oldVersion ); + + try + { + haveOldVersion = isVersionOverlap( compressedOldVersion, compressedPomVersion ); + } + catch ( InvalidVersionSpecificationException e ) + { + // fall back to string comparison + haveOldVersion = compressedOldVersion.equals( compressedPomVersion ); + } + } + else if ( matchScopeRegex.matcher( path ).matches() ) + { + if ( inMatchScope && pom.hasMark( 0 ) && pom.hasMark( 1 ) && haveGroupId && haveArtifactId + && haveOldVersion ) + { + pom.replaceBetween( 0, 1, newVersion ); + madeReplacement = true; + } + pom.clearMark( 0 ); + pom.clearMark( 1 ); + haveArtifactId = false; + haveGroupId = false; + haveOldVersion = false; + inMatchScope = false; + } + path = stack.pop(); + } + } + return madeReplacement; + } + + /** + * A lightweight expression evaluation function. + * + * @param expr The expression to evaluate. + * @param properties The properties to substitute. + * @return The evaluated expression. + */ + public static String evaluate( String expr, Map properties ) + { + if ( expr == null ) + { + return null; + } + + String expression = stripTokens( expr ); + if ( expression.equals( expr ) ) + { + int index = expr.indexOf( "${" ); + if ( index >= 0 ) + { + int lastIndex = expr.indexOf( "}", index ); + if ( lastIndex >= 0 ) + { + String retVal = expr.substring( 0, index ); + + if ( index > 0 && expr.charAt( index - 1 ) == '$' ) + { + retVal += expr.substring( index + 1, lastIndex + 1 ); + } + else + { + retVal += evaluate( expr.substring( index, lastIndex + 1 ), properties ); + } + + retVal += evaluate( expr.substring( lastIndex + 1 ), properties ); + return retVal; + } + } + + // Was not an expression + if ( expression.contains( "$$" ) ) + { + return expression.replaceAll( "\\$\\$", "\\$" ); + } + else + { + return expression; + } + } + + String value = properties.get( expression ); + + if ( value != null ) + { + int exprStartDelimiter = value.indexOf( "${" ); + + if ( exprStartDelimiter >= 0 ) + { + if ( exprStartDelimiter > 0 ) + { + value = value.substring( 0, exprStartDelimiter ) + + evaluate( value.substring( exprStartDelimiter ), properties ); + } + else + { + value = evaluate( value.substring( exprStartDelimiter ), properties ); + } + } + } + else + { + // TODO find a way to log that and not use this System.out!! + // this class could be a component with logger injected !! + System.out.println( "expression: " + expression + " no value " ); + } + return value == null ? expr : value; + } + + /** + * Strips the expression token markers from the start and end of the string. + * + * @param expr the string (perhaps with token markers) + * @return the string (definately without token markers) + */ + private static String stripTokens( String expr ) + { + if ( expr.startsWith( "${" ) && expr.indexOf( "}" ) == expr.length() - 1 ) + { + expr = expr.substring( 2, expr.length() - 1 ); + } + return expr; + } + + /** + * Checks if two versions or ranges have an overlap. + * + * @param leftVersionOrRange the 1st version number or range to test + * @param rightVersionOrRange the 2nd version number or range to test + * @return true if both versions have an overlap + * @throws InvalidVersionSpecificationException if the versions can't be parsed to a range + */ + public static boolean isVersionOverlap( String leftVersionOrRange, String rightVersionOrRange ) + throws InvalidVersionSpecificationException + { + VersionRange pomVersionRange = createVersionRange( leftVersionOrRange ); + if ( !pomVersionRange.hasRestrictions() ) + { + return true; + } + + VersionRange oldVersionRange = createVersionRange( rightVersionOrRange ); + if ( !oldVersionRange.hasRestrictions() ) + { + return true; + } + + VersionRange result = oldVersionRange.restrict( pomVersionRange ); + return result.hasRestrictions(); + } + + private static VersionRange createVersionRange( String versionOrRange ) + throws InvalidVersionSpecificationException + { + VersionRange versionRange = VersionRange.createFromVersionSpec( versionOrRange ); + if ( versionRange.getRecommendedVersion() != null ) + { + versionRange = VersionRange.createFromVersionSpec( "[" + versionOrRange + "]" ); + } + return versionRange; + } + + /** + * Searches the pom re-defining the specified plugin to the specified version. + * + * @param pom The pom to modify. + * @param groupId The groupId of the dependency. + * @param artifactId The artifactId of the dependency. + * @param oldVersion The old version of the dependency. + * @param newVersion The new version of the dependency. + * @return true if a replacement was made. + * @throws XMLStreamException if somethinh went wrong. + */ + public static boolean setPluginVersion( final ModifiedPomXMLEventReader pom, final String groupId, + final String artifactId, final String oldVersion, final String newVersion ) + throws XMLStreamException + { + Stack stack = new Stack<>(); + String path = ""; + final Pattern matchScopeRegex; + final Pattern matchTargetRegex; + boolean inMatchScope = false; + boolean madeReplacement = false; + boolean haveGroupId = false; + boolean needGroupId = groupId != null && !APACHE_MAVEN_PLUGINS_GROUPID.equals( groupId ); + boolean haveArtifactId = false; + boolean haveOldVersion = false; + + matchScopeRegex = Pattern.compile( "/project" + "(/profiles/profile)?" + + "((/build(/pluginManagement)?)|(/reporting))/plugins/plugin" ); + + matchTargetRegex = Pattern.compile( "/project" + "(/profiles/profile)?" + + "((/build(/pluginManagement)?)|(/reporting))/plugins/plugin" + "((/groupId)|(/artifactId)|(/version))" ); + + pom.rewind(); + + while ( pom.hasNext() ) + { + XMLEvent event = pom.nextEvent(); + if ( event.isStartElement() ) + { + stack.push( path ); + final String elementName = event.asStartElement().getName().getLocalPart(); + path = path + "/" + elementName; + + if ( matchScopeRegex.matcher( path ).matches() ) + { + // we're in a new match scope + // reset any previous partial matches + inMatchScope = true; + pom.clearMark( 0 ); + pom.clearMark( 1 ); + + haveGroupId = false; + haveArtifactId = false; + haveOldVersion = false; + } + else if ( inMatchScope && matchTargetRegex.matcher( path ).matches() ) + { + if ( "groupId".equals( elementName ) ) + { + haveGroupId = groupId.equals( pom.getElementText().trim() ); + path = stack.pop(); + } + else if ( "artifactId".equals( elementName ) ) + { + haveArtifactId = artifactId.equals( pom.getElementText().trim() ); + path = stack.pop(); + } + else if ( "version".equals( elementName ) ) + { + pom.mark( 0 ); + } + } + } + if ( event.isEndElement() ) + { + if ( matchTargetRegex.matcher( path ).matches() + && "version".equals( event.asEndElement().getName().getLocalPart() ) ) + { + pom.mark( 1 ); + + try + { + haveOldVersion = isVersionOverlap( oldVersion, pom.getBetween( 0, 1 ).trim() ); + } + catch ( InvalidVersionSpecificationException e ) + { + // fall back to string comparison + haveOldVersion = oldVersion.equals( pom.getBetween( 0, 1 ).trim() ); + } + } + else if ( matchScopeRegex.matcher( path ).matches() ) + { + if ( inMatchScope && pom.hasMark( 0 ) && pom.hasMark( 1 ) && ( haveGroupId || !needGroupId ) + && haveArtifactId && haveOldVersion ) + { + pom.replaceBetween( 0, 1, newVersion ); + madeReplacement = true; + pom.clearMark( 0 ); + pom.clearMark( 1 ); + haveArtifactId = false; + haveGroupId = false; + haveOldVersion = false; + } + inMatchScope = false; + } + path = stack.pop(); + } + } + return madeReplacement; + } + + /** + * Examines the project to find any properties which are associated with versions of artifacts in the project. + * + * @param helper Our versions helper. + * @param project The project to examine. + * @return An array of properties that are associated within the project. + * @throws ExpressionEvaluationException if an expression cannot be evaluated. + * @throws IOException if the project's pom file cannot be parsed. + * @since 1.0-alpha-3 + */ + public static PropertyVersionsBuilder[] getPropertyVersionsBuilders( VersionsHelper helper, MavenProject project ) + throws ExpressionEvaluationException, IOException + { + ExpressionEvaluator expressionEvaluator = helper.getExpressionEvaluator( project ); + Model model = getRawModel( project ); + Map result = new TreeMap(); + + Set activeProfiles = new TreeSet<>(); + for ( Profile profile : (List) project.getActiveProfiles() ) + { + activeProfiles.add( profile.getId() ); + } + + // add any properties from profiles first (as they override properties from the project + for ( Profile profile : model.getProfiles() ) + { + if ( !activeProfiles.contains( profile.getId() ) ) + { + continue; + } + addProperties( helper, result, profile.getId(), profile.getProperties() ); + if ( profile.getDependencyManagement() != null ) + { + addDependencyAssocations( helper, expressionEvaluator, result, + profile.getDependencyManagement().getDependencies(), false ); + } + addDependencyAssocations( helper, expressionEvaluator, result, profile.getDependencies(), false ); + if ( profile.getBuild() != null ) + { + if ( profile.getBuild().getPluginManagement() != null ) + { + addPluginAssociations( helper, expressionEvaluator, result, + profile.getBuild().getPluginManagement().getPlugins() ); + } + addPluginAssociations( helper, expressionEvaluator, result, profile.getBuild().getPlugins() ); + } + if ( profile.getReporting() != null ) + { + addReportPluginAssociations( helper, expressionEvaluator, result, profile.getReporting().getPlugins() ); + } + } + + // second, we add all the properties in the pom + addProperties( helper, result, null, model.getProperties() ); + if ( model.getDependencyManagement() != null ) + { + addDependencyAssocations( helper, expressionEvaluator, result, + model.getDependencyManagement().getDependencies(), false ); + } + addDependencyAssocations( helper, expressionEvaluator, result, model.getDependencies(), false ); + if ( model.getBuild() != null ) + { + if ( model.getBuild().getPluginManagement() != null ) + { + addPluginAssociations( helper, expressionEvaluator, result, + model.getBuild().getPluginManagement().getPlugins() ); + } + addPluginAssociations( helper, expressionEvaluator, result, model.getBuild().getPlugins() ); + } + if ( model.getReporting() != null ) + { + addReportPluginAssociations( helper, expressionEvaluator, result, model.getReporting().getPlugins() ); + } + + // third, we add any associations from the active profiles + for ( Profile profile : model.getProfiles() ) + { + if ( !activeProfiles.contains( profile.getId() ) ) + { + continue; + } + if ( profile.getDependencyManagement() != null ) + { + addDependencyAssocations( helper, expressionEvaluator, result, + profile.getDependencyManagement().getDependencies(), false ); + } + addDependencyAssocations( helper, expressionEvaluator, result, profile.getDependencies(), false ); + if ( profile.getBuild() != null ) + { + if ( profile.getBuild().getPluginManagement() != null ) + { + addPluginAssociations( helper, expressionEvaluator, result, + profile.getBuild().getPluginManagement().getPlugins() ); + } + addPluginAssociations( helper, expressionEvaluator, result, profile.getBuild().getPlugins() ); + } + if ( profile.getReporting() != null ) + { + addReportPluginAssociations( helper, expressionEvaluator, result, profile.getReporting().getPlugins() ); + } + } + + // finally, remove any properties without associations + purgeProperties( result ); + + return result.values().toArray( new PropertyVersionsBuilder[result.values().size()] ); + } + + /** + * Takes a list of {@link org.apache.maven.model.Plugin} instances and adds associations to properties used to + * define versions of the plugin artifact or any of the plugin dependencies specified in the pom. + * + * @param helper Our helper. + * @param expressionEvaluator Our expression evaluator. + * @param result The map of {@link org.codehaus.mojo.versions.api.PropertyVersionsBuilder} keyed by property name. + * @param plugins The list of {@link org.apache.maven.model.Plugin}. + * @throws ExpressionEvaluationException if an expression cannot be evaluated. + */ + private static void addPluginAssociations( VersionsHelper helper, ExpressionEvaluator expressionEvaluator, + Map result, List plugins ) + throws ExpressionEvaluationException + { + if ( plugins == null ) + { + return; + } + for ( Plugin plugin : plugins ) + { + String version = plugin.getVersion(); + if ( version != null && version.contains( "${" ) && version.indexOf( '}' ) != -1 ) + { + version = StringUtils.deleteWhitespace( version ); + for ( PropertyVersionsBuilder property : result.values() ) + { + // any of these could be defined by a property + final String propertyRef = "${" + property.getName() + "}"; + if ( version.contains( propertyRef ) ) + { + String groupId = plugin.getGroupId(); + if ( groupId == null || groupId.trim().length() == 0 ) + { + // group Id has a special default + groupId = APACHE_MAVEN_PLUGINS_GROUPID; + } + else + { + groupId = (String) expressionEvaluator.evaluate( groupId ); + } + String artifactId = plugin.getArtifactId(); + if ( artifactId == null || artifactId.trim().length() == 0 ) + { + // malformed pom + continue; + } + else + { + artifactId = (String) expressionEvaluator.evaluate( artifactId ); + } + // might as well capture the current value + VersionRange versionRange = + VersionRange.createFromVersion( (String) expressionEvaluator.evaluate( plugin.getVersion() ) ); + property.addAssociation( helper.createPluginArtifact( groupId, artifactId, versionRange ), + true ); + if ( !propertyRef.equals( version ) ) + { + addBounds( property, version, propertyRef, versionRange.toString() ); + } + } + } + } + addDependencyAssocations( helper, expressionEvaluator, result, plugin.getDependencies(), true ); + } + } + + private static void addReportPluginAssociations( VersionsHelper helper, ExpressionEvaluator expressionEvaluator, + Map result, + List reportPlugins ) + throws ExpressionEvaluationException + { + if ( reportPlugins == null ) + { + return; + } + for ( ReportPlugin plugin : reportPlugins ) + { + String version = plugin.getVersion(); + if ( version != null && version.contains( "${" ) && version.indexOf( '}' ) != -1 ) + { + version = StringUtils.deleteWhitespace( version ); + for ( PropertyVersionsBuilder property : result.values() ) + { + final String propertyRef = "${" + property.getName() + "}"; + if ( version.contains( propertyRef ) ) + { + // any of these could be defined by a property + String groupId = plugin.getGroupId(); + if ( groupId == null || groupId.trim().length() == 0 ) + { + // group Id has a special default + groupId = APACHE_MAVEN_PLUGINS_GROUPID; + } + else + { + groupId = (String) expressionEvaluator.evaluate( groupId ); + } + String artifactId = plugin.getArtifactId(); + if ( artifactId == null || artifactId.trim().length() == 0 ) + { + // malformed pom + continue; + } + else + { + artifactId = (String) expressionEvaluator.evaluate( artifactId ); + } + // might as well capture the current value + VersionRange versionRange = + VersionRange.createFromVersion( (String) expressionEvaluator.evaluate( plugin.getVersion() ) ); + property.addAssociation( helper.createPluginArtifact( groupId, artifactId, versionRange ), + true ); + if ( !propertyRef.equals( version ) ) + { + addBounds( property, version, propertyRef, versionRange.toString() ); + } + } + } + } + } + } + + private static void addDependencyAssocations( VersionsHelper helper, ExpressionEvaluator expressionEvaluator, + Map result, + List dependencies, boolean usePluginRepositories ) + throws ExpressionEvaluationException + { + if ( dependencies == null ) + { + return; + } + for ( Dependency dependency : dependencies ) + { + String version = dependency.getVersion(); + if ( version != null && version.contains( "${" ) && version.indexOf( '}' ) != -1 ) + { + version = StringUtils.deleteWhitespace( version ); + for ( PropertyVersionsBuilder property : result.values() ) + { + final String propertyRef = "${" + property.getName() + "}"; + if ( version.contains( propertyRef ) ) + { + // Any of these could be defined by a property + String groupId = dependency.getGroupId(); + if ( groupId == null || groupId.trim().length() == 0 ) + { + // malformed pom + continue; + } + else + { + groupId = (String) expressionEvaluator.evaluate( groupId ); + } + String artifactId = dependency.getArtifactId(); + if ( artifactId == null || artifactId.trim().length() == 0 ) + { + // malformed pom + continue; + } + else + { + artifactId = (String) expressionEvaluator.evaluate( artifactId ); + } + // might as well capture the current value + VersionRange versionRange = + VersionRange.createFromVersion( (String) expressionEvaluator.evaluate( dependency.getVersion() ) ); + property.addAssociation( helper.createDependencyArtifact( groupId, artifactId, versionRange, + dependency.getType(), + dependency.getClassifier(), + dependency.getScope(), + dependency.isOptional() ), + usePluginRepositories ); + if ( !propertyRef.equals( version ) ) + { + addBounds( property, version, propertyRef, versionRange.toString() ); + } + } + } + } + } + } + + private static void addBounds( PropertyVersionsBuilder builder, String rawVersionRange, String propertyRef, + String evaluatedVersionRange ) + { + Pattern lowerBound = Pattern.compile( "([(\\[])([^,]*)," + RegexUtils.quote( propertyRef ) + "([)\\]])" ); + Pattern upperBound = Pattern.compile( "([(\\[])" + RegexUtils.quote( propertyRef ) + ",([^,]*)([)\\]])" ); + Matcher m = lowerBound.matcher( rawVersionRange ); + if ( m.find() ) + { + boolean includeLower = "[".equals( m.group( 1 ) ); + String lowerLimit = m.group( 2 ); + if ( StringUtils.isNotEmpty( lowerLimit ) ) + { + builder.addLowerBound( lowerLimit, includeLower ); + } + } + m = upperBound.matcher( rawVersionRange ); + if ( m.find() ) + { + boolean includeUpper = "[".equals( m.group( 3 ) ); + String upperLimit = m.group( 2 ); + if ( StringUtils.isNotEmpty( upperLimit ) ) + { + builder.addUpperBound( upperLimit, includeUpper ); + } + } + } + + private static void addProperties( VersionsHelper helper, Map result, + String profileId, Properties properties ) + { + if ( properties == null ) + { + return; + } + for ( Enumeration j = properties.propertyNames(); j.hasMoreElements(); ) + { + String propertyName = (String) j.nextElement(); + if ( !result.containsKey( propertyName ) ) + { + result.put( propertyName, new PropertyVersionsBuilder( profileId, propertyName, helper ) ); + } + } + } + + private static void purgeProperties( Map result ) + { + for ( Iterator i = result.values().iterator(); i.hasNext(); ) + { + PropertyVersionsBuilder versions = (PropertyVersionsBuilder) i.next(); + if ( versions.getAssociations().length == 0 ) + { + i.remove(); + } + } + } + + /** + * Returns a set of all child modules for a project, including any defined in profiles (ignoring profile + * activation). + * + * @param project The project. + * @param logger The logger to use. + * @return the set of all child modules of the project. + */ + public static Set getAllChildModules( MavenProject project, Log logger ) + { + return getAllChildModules( project.getOriginalModel(), logger ); + } + + /** + * Returns a set of all child modules for a project, including any defined in profiles (ignoring profile + * activation). + * + * @param model The project model. + * @param logger The logger to use. + * @return the set of all child modules of the project. + */ + public static Set getAllChildModules( Model model, Log logger ) + { + logger.debug( "Finding child modules..." ); + Set childModules = new TreeSet(); + childModules.addAll( model.getModules() ); + for ( Profile profile : model.getProfiles() ) + { + childModules.addAll( profile.getModules() ); + } + debugModules( logger, "Child modules:", childModules ); + return childModules; + } + + /** + * Outputs a debug message with a list of modules. + * + * @param logger The logger to log to. + * @param message The message to display. + * @param modules The modules to append to the message. + */ + public static void debugModules( Log logger, String message, Collection modules ) + { + Iterator i; + if ( logger.isDebugEnabled() ) + { + logger.debug( message ); + if ( modules.isEmpty() ) + { + logger.debug( "None." ); + } + else + { + i = modules.iterator(); + while ( i.hasNext() ) + { + logger.debug( " " + i.next() ); + } + } + + } + } + + /** + * Modifies the collection of child modules removing those which cannot be found relative to the parent. + * + * @param logger The logger to log to. + * @param project the project. + * @param childModules the child modules. + */ + public static void removeMissingChildModules( Log logger, MavenProject project, Collection childModules ) + { + removeMissingChildModules( logger, project.getBasedir(), childModules ); + } + + /** + * Modifies the collection of child modules removing those which cannot be found relative to the parent. + * + * @param logger The logger to log to. + * @param basedir the project basedir. + * @param childModules the child modules. + */ + public static void removeMissingChildModules( Log logger, File basedir, Collection childModules ) + { + logger.debug( "Removing child modules which are missing..." ); + Iterator i = childModules.iterator(); + while ( i.hasNext() ) + { + String modulePath = i.next(); + File moduleFile = new File( basedir, modulePath ); + + if ( moduleFile.isDirectory() && new File( moduleFile, "pom.xml" ).isFile() ) + { + // it's a directory that exists + continue; + } + + if ( moduleFile.isFile() ) + { + // it's the pom.xml file directly referenced and it exists. + continue; + } + + logger.debug( "Removing missing child module " + modulePath ); + i.remove(); + } + debugModules( logger, "After removing missing", childModules ); + } + + /** + * Extracts the version from a raw model, interpolating from the parent if necessary. + * + * @param model The model. + * @return The version. + */ + public static String getVersion( Model model ) + { + String targetVersion = model.getVersion(); + if ( targetVersion == null && model.getParent() != null ) + { + targetVersion = model.getParent().getVersion(); + } + return targetVersion; + } + + /** + * Checks to see if the model contains an explicitly specified version. + * + * @param model The model. + * @return {@code true} if the model explicitly specifies the project version, i.e. /project/version + */ + public static boolean isExplicitVersion( Model model ) + { + return model.getVersion() != null; + } + + /** + * Extracts the artifactId from a raw model, interpolating from the parent if necessary. + * + * @param model The model. + * @return The artifactId. + */ + public static String getArtifactId( Model model ) + { + String sourceArtifactId = model.getArtifactId(); + if ( sourceArtifactId == null && model.getParent() != null ) + { + sourceArtifactId = model.getParent().getArtifactId(); + } + return sourceArtifactId; + } + + /** + * Extracts the groupId from a raw model, interpolating from the parent if necessary. + * + * @param model The model. + * @return The groupId. + */ + public static String getGroupId( Model model ) + { + String targetGroupId = model.getGroupId(); + if ( targetGroupId == null && model.getParent() != null ) + { + targetGroupId = model.getParent().getGroupId(); + } + return targetGroupId; + } + + /** + * Finds the local root of the specified project. + * + * @param project The project to find the local root for. + * @param localRepository the local repo. + * @param globalProfileManager the global profile manager. + * @param logger The logger to log to. + * @return The local root (note this may be the project passed as an argument). + */ + public static MavenProject getLocalRoot( MavenProjectBuilder builder, MavenProject project, + ArtifactRepository localRepository, ProfileManager globalProfileManager, + Log logger ) + { + logger.info( "Searching for local aggregator root..." ); + while ( true ) + { + final File parentDir = project.getBasedir().getParentFile(); + if ( parentDir != null && parentDir.isDirectory() ) + { + logger.debug( "Checking to see if " + parentDir + " is an aggregator parent" ); + File parent = new File( parentDir, "pom.xml" ); + if ( parent.isFile() ) + { + try + { + final MavenProject parentProject = + builder.build( parent, localRepository, globalProfileManager ); + if ( getAllChildModules( parentProject, logger ).contains( project.getBasedir().getName() ) ) + { + logger.debug( parentDir + " is an aggregator parent" ); + project = parentProject; + continue; + } + else + { + logger.debug( parentDir + " is not an aggregator parent" ); + } + } + catch ( ProjectBuildingException e ) + { + logger.warn( e ); + } + } + } + logger.debug( "Local aggregation root is " + project.getBasedir() ); + return project; + } + } + + /** + * Builds a map of raw models keyed by module path. + * + * @param project The project to build from. + * @param logger The logger for logging. + * @return A map of raw models keyed by path relative to the project's basedir. + * @throws IOException if things go wrong. + */ + public static Map getReactorModels( MavenProject project, Log logger ) + throws IOException + { + Map result = new LinkedHashMap<>(); + final Model model = getRawModel( project ); + final String path = ""; + result.put( path, model ); + result.putAll( getReactorModels( path, model, project, logger ) ); + return result; + } + + /** + * Builds a sub-map of raw models keyed by module path. + * + * @param path The relative path to base the sub-map on. + * @param model The model at the relative path. + * @param project The project to build from. + * @param logger The logger for logging. + * @return A map of raw models keyed by path relative to the project's basedir. + * @throws IOException if things go wrong. + */ + private static Map getReactorModels( String path, Model model, MavenProject project, Log logger ) + throws IOException + { + if ( path.length() > 0 && !path.endsWith( "/" ) ) + { + path += '/'; + } + Map result = new LinkedHashMap<>(); + Map childResults = new LinkedHashMap<>(); + + File baseDir = path.length() > 0 ? new File( project.getBasedir(), path ) : project.getBasedir(); + + Set childModules = getAllChildModules( model, logger ); + + removeMissingChildModules( logger, baseDir, childModules ); + + for ( String moduleName : childModules ) + { + String modulePath = path + moduleName; + + File moduleDir = new File( baseDir, moduleName ); + + File moduleProjectFile; + + if ( moduleDir.isDirectory() ) + { + moduleProjectFile = new File( moduleDir, "pom.xml" ); + } + else + { + // i don't think this should ever happen... but just in case + // the module references the file-name + moduleProjectFile = moduleDir; + } + + try + { + // the aim of this goal is to fix problems when the project cannot be parsed by Maven + // so we have to work with the raw model and not the interpolated parsed model from maven + Model moduleModel = getRawModel( moduleProjectFile ); + result.put( modulePath, moduleModel ); + childResults.putAll( getReactorModels( modulePath, moduleModel, project, logger ) ); + } + catch ( IOException e ) + { + logger.debug( "Could not parse " + moduleProjectFile.getPath(), e ); + } + } + result.putAll( childResults ); // more efficient update order if all children are added after siblings + return result; + } + + /** + * Returns all the models that have a specified groupId and artifactId as parent. + * + * @param reactor The map of models keyed by path. + * @param groupId The groupId of the parent. + * @param artifactId The artifactId of the parent. + * @return a map of models that have a specified groupId and artifactId as parent keyed by path. + */ + public static Map getChildModels( Map reactor, String groupId, String artifactId ) + { + final Map result = new LinkedHashMap(); + for ( Map.Entry entry : reactor.entrySet() ) + { + final String path = entry.getKey(); + final Model model = entry.getValue(); + final Parent parent = model.getParent(); + if ( parent != null && groupId.equals( parent.getGroupId() ) + && artifactId.equals( parent.getArtifactId() ) ) + { + result.put( path, model ); + } + } + return result; + } + + /** + * Returns the model that has the specified groupId and artifactId or null if no such model exists. + * + * @param reactor The map of models keyed by path. + * @param groupId The groupId to match. + * @param artifactId The artifactId to match. + * @return The model or null if the model was not in the reactor. + */ + public static Model getModel( Map reactor, String groupId, String artifactId ) + { + Map.Entry entry = getModelEntry( reactor, groupId, artifactId ); + return entry == null ? null : entry.getValue(); + } + + /** + * Returns the model that has the specified groupId and artifactId or null if no such model exists. + * + * @param reactor The map of models keyed by path. + * @param groupId The groupId to match. + * @param artifactId The artifactId to match. + * @return The model entry or null if the model was not in the reactor. + */ + public static Map.Entry getModelEntry( Map reactor, String groupId, + String artifactId ) + { + for ( Map.Entry entry : reactor.entrySet() ) + { + Model model = entry.getValue(); + if ( groupId.equals( getGroupId( model ) ) && artifactId.equals( getArtifactId( model ) ) ) + { + return entry; + } + } + return null; + } + + /** + * Returns a count of how many parents a model has in the reactor. + * + * @param reactor The map of models keyed by path. + * @param model The model. + * @return The number of parents of this model in the reactor. + */ + public static int getReactorParentCount( Map reactor, Model model ) + { + if ( model.getParent() == null ) + { + return 0; + } + else + { + Model parentModel = getModel( reactor, model.getParent().getGroupId(), model.getParent().getArtifactId() ); + if ( parentModel != null ) + { + return getReactorParentCount( reactor, parentModel ) + 1; + } + return 0; + } + } + + /** + * Reads a file into a String. + * + * @param outFile The file to read. + * @return String The content of the file. + * @throws java.io.IOException when things go wrong. + */ + public static StringBuilder readXmlFile( File outFile ) + throws IOException + { + try( Reader reader = ReaderFactory.newXmlReader( outFile ) ) + { + return new StringBuilder( IOUtil.toString( reader ) ); + } + } + + /** + * Returns the GAV coordinates of a model. + * + * @param model the model. + * @return the GAV coordinates of a model. + */ + public static String getGAV( Model model ) + { + return getGroupId( model ) + ":" + getArtifactId( model ) + ":" + getVersion( model ); + } + + /** + * Reads imported POMs from the dependency management section. + * + * @param pom + * @return a non-null list of {@link Dependency} for each imported POM + * @throws XMLStreamException + * @see bug #134 + * @since 2.4 + */ + public static List readImportedPOMsFromDependencyManagementSection( ModifiedPomXMLEventReader pom ) + throws XMLStreamException + { + List importedPOMs = new ArrayList(); + Stack stack = new Stack(); + + String groupIdElement = "groupId"; + String artifactIdElement = "artifactId"; + String versionElement = "version"; + String typeElement = "type"; + String scopeElement = "scope"; + Set recognizedElements = + new HashSet<>( Arrays.asList( groupIdElement, artifactIdElement, versionElement, typeElement, + scopeElement ) ); + Map depData = new HashMap<>(); + + pom.rewind(); + + String depMgmtDependencyPath = "/project/dependencyManagement/dependencies/dependency"; + + while ( pom.hasNext() ) + { + XMLEvent event = pom.nextEvent(); + + if ( event.isStartElement() ) + { + final String elementName = event.asStartElement().getName().getLocalPart(); + String parent = ""; + if ( !stack.isEmpty() ) + { + parent = stack.peek(); + } + String currentPath = parent + "/" + elementName; + stack.push( currentPath ); + + if ( currentPath.startsWith( depMgmtDependencyPath ) && recognizedElements.contains( elementName ) ) + { + final String elementText = pom.getElementText().trim(); + depData.put( elementName, elementText ); + stack.pop(); + } + } + if ( event.isEndElement() ) + { + String path = stack.pop(); + if ( depMgmtDependencyPath.equals( path ) ) + { + if ( "pom".equals( depData.get( typeElement ) ) && "import".equals( depData.get( scopeElement ) ) ) + { + Dependency dependency = new Dependency(); + dependency.setGroupId( depData.get( groupIdElement ) ); + dependency.setArtifactId( depData.get( artifactIdElement ) ); + dependency.setVersion( depData.get( versionElement ) ); + dependency.setType( depData.get( typeElement ) ); + dependency.setScope( depData.get( scopeElement ) ); + importedPOMs.add( dependency ); + } + depData.clear(); + } + } + } + return importedPOMs; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `event` last assigned on line 244 could be null and is dereferenced at line 245. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean PomHelper.setProjectVersion(ModifiedPomXMLEventReader,String) + +### Procedure Id: +org.codehaus.mojo.versions.api.PomHelper.setProjectVersion(org.codehaus.mojo.versions.rewriting.Modi.137acedb7fcbcc2f7710e9deee6dd5fb + +### File: +src/main/java/org/codehaus/mojo/versions/api/PomHelper.java + +### Key: +PomHelper.java|setProjectVersion|NULL_DEREFERENCE + +### Node Key: +00c1f65e387d55c612515ace03b6e05b + +### Hash: +620486de4789a91f70b1b6a437300910 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10598/instruction.md b/inferredbugs-10598/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..897a477fe06a5db5866d0b11c4dbb3474550901f --- /dev/null +++ b/inferredbugs-10598/instruction.md @@ -0,0 +1,180 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jkeymaster +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2011 Denis Tulskiy + * + * This program 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. + * + * 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with this work. If not, see . + */ + +package com.tulskiy.keymaster; + +import com.tulskiy.keymaster.common.HotKey; +import com.tulskiy.keymaster.common.HotKeyListener; +import com.tulskiy.keymaster.common.MediaKey; +import com.tulskiy.keymaster.common.Provider; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.util.Arrays; +import java.util.List; + +/** + * Author: Denis Tulskiy + * Date: 6/6/11 + */ +public class AWTTest { + public static final List MODIFIERS = Arrays.asList(KeyEvent.VK_ALT, KeyEvent.VK_CONTROL, KeyEvent.VK_SHIFT, KeyEvent.VK_META); + + public static void main(String[] args) { + final JFrame frame = new JFrame(); + final Provider provider = Provider.getCurrentProvider(true); + + if (provider == null) { + System.exit(1); + } + + frame.add(new JLabel("Press hotkey combination:"), BorderLayout.NORTH); + + final JTextField textField = new JTextField(); + textField.setFont(textField.getFont().deriveFont(Font.BOLD, 15f)); + textField.setEditable(false); + textField.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (MODIFIERS.contains(e.getKeyCode())) + textField.setText(""); + else + textField.setText(KeyStroke.getKeyStrokeForEvent(e).toString().replaceAll("pressed ", "")); + } + }); + frame.add(textField, BorderLayout.CENTER); + JPanel box = new JPanel(); + JButton grab = new JButton("Grab"); + box.add(grab); + final HotKeyListener listener = new HotKeyListener() { + public void onHotKey(final HotKey hotKey) { + JOptionPane.showMessageDialog(frame, "Hooray: " + hotKey); + } + }; + grab.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + String text = textField.getText(); + if (text != null && text.length() > 0) { + provider.reset(); + provider.register(KeyStroke.getKeyStroke(text), listener); + } + } + }); + + JButton grabMedia = new JButton("Grab media keys"); + grabMedia.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + provider.register(MediaKey.MEDIA_NEXT_TRACK, listener); + provider.register(MediaKey.MEDIA_PLAY_PAUSE, listener); + provider.register(MediaKey.MEDIA_PREV_TRACK, listener); + provider.register(MediaKey.MEDIA_STOP, listener); + } + }); + + box.add(grabMedia); + + frame.add(box, BorderLayout.PAGE_END); + + frame.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + provider.reset(); + provider.stop(); + System.exit(0); + } + }); + + frame.setSize(500, 150); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.tulskiy.keymaster.x11.X11Provider` acquired by call to `getCurrentProvider(...)` at line 40 is not released after line 93. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AWTTest.main(java.lang.String[]) + +### Procedure Id: +com.tulskiy.keymaster.AWTTest.main(java.lang.String[]):void.1e9242809cfa02c1fff5df6ffe473aed + +### File: +core/src/main/java/com/tulskiy/keymaster/AWTTest.java + +### Key: +AWTTest.java|main|RESOURCE_LEAK + +### Node Key: +c7a7f6d7ab5050598bee23d2132c7333 + +### Hash: +7e5863b2dc631b2b05cabcce78dcf03e + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10612/instruction.md b/inferredbugs-10612/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bbf6b10a61bec5e2ca1dc587238c6c761751773a --- /dev/null +++ b/inferredbugs-10612/instruction.md @@ -0,0 +1,377 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jdeb +**Bug ID:** 32 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2013 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.vafer.jdeb.ant; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.zip.GZIPInputStream; + +import junit.framework.TestCase; +import org.apache.commons.compress.archivers.ar.ArArchiveEntry; +import org.apache.commons.compress.archivers.ar.ArArchiveInputStream; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.DefaultLogger; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.ProjectHelper; +import org.apache.tools.bzip2.CBZip2InputStream; +import org.apache.tools.tar.TarEntry; +import org.apache.tools.tar.TarInputStream; +import org.vafer.jdeb.ar.NonClosingInputStream; + +/** + * @author Emmanuel Bourg + */ +public final class DebAntTaskTestCase extends TestCase { + + private Project project; + + protected void setUp() throws Exception { + project = new Project(); + project.setCoreLoader(getClass().getClassLoader()); + project.init(); + + File buildFile = new File("target/test-classes/testbuild.xml"); + project.setBaseDir(buildFile.getParentFile()); + + final ProjectHelper helper = ProjectHelper.getProjectHelper(); + helper.parse(project, buildFile); + + // remove the package previously build + File deb = new File("target/test.deb"); + if (deb.exists()) { + assertTrue("Unable to remove the test archive", deb.delete()); + } + } + + public void testMissingControl() { + try { + project.executeTarget("missing-control"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testInvalidControl() { + try { + project.executeTarget("invalid-control"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testMissingDestFile() { + try { + project.executeTarget("missing-destfile"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testEmptyPackage() { + try { + project.executeTarget("empty-package"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testPackageWithArchive() { + project.executeTarget("with-archive"); + + assertTrue("package not build", new File("target/test-classes/test.deb").exists()); + } + + public void testPackageWithMissingArchive() { + try { + project.executeTarget("with-missing-archive"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testPackageWithDirectory() { + project.executeTarget("with-directory"); + + assertTrue("package not build", new File("target/test-classes/test.deb").exists()); + } + + public void testPackageWithMissingDirectory() { + try { + project.executeTarget("with-missing-directory"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + /** + * Redirects the Ant output to the specified stream. + */ + private void redirectOutput( OutputStream out ) { + DefaultLogger logger = new DefaultLogger(); + logger.setOutputPrintStream(new PrintStream(out)); + logger.setMessageOutputLevel(Project.MSG_INFO); + project.addBuildListener(logger); + } + + public void testVerboseEnabled() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + redirectOutput(out); + + project.executeTarget("verbose-enabled"); + + assertTrue(out.toString().contains("Total size")); + } + + public void testVerboseDisabled() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + redirectOutput(out); + + project.executeTarget("verbose-disabled"); + + assertTrue(!out.toString().contains("Total size")); + } + + public void testMissingDataType() { + try { + project.executeTarget("missing-data-type"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testUnknownDataType() { + try { + project.executeTarget("unknown-data-type"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testFileSet() { + project.executeTarget("fileset"); + + assertTrue("package not build", new File("target/test-classes/test.deb").exists()); + } + + public void testTarFileSet() throws Exception { + project.executeTarget("tarfileset"); + + File deb = new File("target/test-classes/test.deb"); + assertTrue("package not build", deb.exists()); + + ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); + ArArchiveEntry entry; + while ((entry = in.getNextArEntry()) != null) { + if (entry.getName().equals("data.tar.gz")) { + TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(in))); + TarEntry tarentry; + while ((tarentry = tar.getNextEntry()) != null) { + assertTrue("prefix", tarentry.getName().startsWith("./foo/")); + if (tarentry.isDirectory()) { + assertEquals("directory mode (" + tarentry.getName() + ")", 040700, tarentry.getMode()); + } else { + assertEquals("file mode (" + tarentry.getName() + ")", 0100600, tarentry.getMode()); + } + assertEquals("user", "ebourg", tarentry.getUserName()); + assertEquals("group", "ebourg", tarentry.getGroupName()); + } + tar.close(); + } else { + // skip to the next entry + long skip = entry.getLength(); + while (skip > 0) { + long skipped = in.skip(skip); + if (skipped == -1) { + throw new IOException("Failed to skip"); + } + skip -= skipped; + } + } + } + in.close(); + } + + public void testUnkownCompression() throws Exception { + try { + project.executeTarget("unknown-compression"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testBZip2Compression() throws Exception { + project.executeTarget("bzip2-compression"); + + File deb = new File("target/test-classes/test.deb"); + assertTrue("package not build", deb.exists()); + + boolean found = false; + + ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); + ArArchiveEntry entry; + while ((entry = in.getNextArEntry()) != null) { + if (entry.getName().equals("data.tar.bz2")) { + found = true; + + assertEquals("header 0", (byte) 'B', in.read()); + assertEquals("header 1", (byte) 'Z', in.read()); + + TarInputStream tar = new TarInputStream(new CBZip2InputStream(in)); + while ((tar.getNextEntry()) != null) { + ; + } + tar.close(); + break; + } else { + // skip to the next entry + long skip = entry.getLength(); + while (skip > 0) { + long skipped = in.skip(skip); + if (skipped == -1) { + throw new IOException("Failed to skip"); + } + skip -= skipped; + } + } + } + in.close(); + + assertTrue("bz2 file not found", found); + } + + public void testNoCompression() throws Exception { + project.executeTarget("no-compression"); + + File deb = new File("target/test-classes/test.deb"); + assertTrue("package not build", deb.exists()); + + boolean found = false; + + ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); + ArArchiveEntry entry; + while ((entry = in.getNextArEntry()) != null) { + if (entry.getName().equals("data.tar")) { + found = true; + + TarInputStream tar = new TarInputStream(new NonClosingInputStream(in)); + while ((tar.getNextEntry()) != null) { + ; + } + tar.close(); + } else { + // skip to the next entry + long skip = entry.getLength(); + while (skip > 0) { + long skipped = in.skip(skip); + if (skipped == -1) { + throw new IOException("Failed to skip"); + } + skip -= skipped; + } + } + } + in.close(); + + assertTrue("tar file not found", found); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.compress.archivers.ar.ArArchiveInputStream` acquired by call to `new()` at line 187 is not released after line 210. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DebAntTaskTestCase.testTarFileSet() + +### Procedure Id: +org.vafer.jdeb.ant.DebAntTaskTestCase.testTarFileSet():void.8f0aab4969ae045893a0d5b32a93f68d + +### File: +src/test/java/org/vafer/jdeb/ant/DebAntTaskTestCase.java + +### Key: +DebAntTaskTestCase.java|testTarFileSet|RESOURCE_LEAK + +### Node Key: +99f813e1b01bd7111afa5cb643a24406 + +### Hash: +2ed5186ee287846e1f145f8285708832 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10615/instruction.md b/inferredbugs-10615/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0785436fc9b80a80c91cbbb7ba5cd1277695e3c1 --- /dev/null +++ b/inferredbugs-10615/instruction.md @@ -0,0 +1,377 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jdeb +**Bug ID:** 33 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2013 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.vafer.jdeb.ant; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.zip.GZIPInputStream; + +import junit.framework.TestCase; +import org.apache.commons.compress.archivers.ar.ArArchiveEntry; +import org.apache.commons.compress.archivers.ar.ArArchiveInputStream; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.DefaultLogger; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.ProjectHelper; +import org.apache.tools.bzip2.CBZip2InputStream; +import org.apache.tools.tar.TarEntry; +import org.apache.tools.tar.TarInputStream; +import org.vafer.jdeb.ar.NonClosingInputStream; + +/** + * @author Emmanuel Bourg + */ +public final class DebAntTaskTestCase extends TestCase { + + private Project project; + + protected void setUp() throws Exception { + project = new Project(); + project.setCoreLoader(getClass().getClassLoader()); + project.init(); + + File buildFile = new File("target/test-classes/testbuild.xml"); + project.setBaseDir(buildFile.getParentFile()); + + final ProjectHelper helper = ProjectHelper.getProjectHelper(); + helper.parse(project, buildFile); + + // remove the package previously build + File deb = new File("target/test.deb"); + if (deb.exists()) { + assertTrue("Unable to remove the test archive", deb.delete()); + } + } + + public void testMissingControl() { + try { + project.executeTarget("missing-control"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testInvalidControl() { + try { + project.executeTarget("invalid-control"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testMissingDestFile() { + try { + project.executeTarget("missing-destfile"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testEmptyPackage() { + try { + project.executeTarget("empty-package"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testPackageWithArchive() { + project.executeTarget("with-archive"); + + assertTrue("package not build", new File("target/test-classes/test.deb").exists()); + } + + public void testPackageWithMissingArchive() { + try { + project.executeTarget("with-missing-archive"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testPackageWithDirectory() { + project.executeTarget("with-directory"); + + assertTrue("package not build", new File("target/test-classes/test.deb").exists()); + } + + public void testPackageWithMissingDirectory() { + try { + project.executeTarget("with-missing-directory"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + /** + * Redirects the Ant output to the specified stream. + */ + private void redirectOutput( OutputStream out ) { + DefaultLogger logger = new DefaultLogger(); + logger.setOutputPrintStream(new PrintStream(out)); + logger.setMessageOutputLevel(Project.MSG_INFO); + project.addBuildListener(logger); + } + + public void testVerboseEnabled() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + redirectOutput(out); + + project.executeTarget("verbose-enabled"); + + assertTrue(out.toString().contains("Total size")); + } + + public void testVerboseDisabled() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + redirectOutput(out); + + project.executeTarget("verbose-disabled"); + + assertTrue(!out.toString().contains("Total size")); + } + + public void testMissingDataType() { + try { + project.executeTarget("missing-data-type"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testUnknownDataType() { + try { + project.executeTarget("unknown-data-type"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testFileSet() { + project.executeTarget("fileset"); + + assertTrue("package not build", new File("target/test-classes/test.deb").exists()); + } + + public void testTarFileSet() throws Exception { + project.executeTarget("tarfileset"); + + File deb = new File("target/test-classes/test.deb"); + assertTrue("package not build", deb.exists()); + + ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); + ArArchiveEntry entry; + while ((entry = in.getNextArEntry()) != null) { + if (entry.getName().equals("data.tar.gz")) { + TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(in))); + TarEntry tarentry; + while ((tarentry = tar.getNextEntry()) != null) { + assertTrue("prefix", tarentry.getName().startsWith("./foo/")); + if (tarentry.isDirectory()) { + assertEquals("directory mode (" + tarentry.getName() + ")", 040700, tarentry.getMode()); + } else { + assertEquals("file mode (" + tarentry.getName() + ")", 0100600, tarentry.getMode()); + } + assertEquals("user", "ebourg", tarentry.getUserName()); + assertEquals("group", "ebourg", tarentry.getGroupName()); + } + tar.close(); + } else { + // skip to the next entry + long skip = entry.getLength(); + while (skip > 0) { + long skipped = in.skip(skip); + if (skipped == -1) { + throw new IOException("Failed to skip"); + } + skip -= skipped; + } + } + } + in.close(); + } + + public void testUnkownCompression() throws Exception { + try { + project.executeTarget("unknown-compression"); + fail("No exception thrown"); + } catch (BuildException e) { + // expected + } + } + + public void testBZip2Compression() throws Exception { + project.executeTarget("bzip2-compression"); + + File deb = new File("target/test-classes/test.deb"); + assertTrue("package not build", deb.exists()); + + boolean found = false; + + ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); + ArArchiveEntry entry; + while ((entry = in.getNextArEntry()) != null) { + if (entry.getName().equals("data.tar.bz2")) { + found = true; + + assertEquals("header 0", (byte) 'B', in.read()); + assertEquals("header 1", (byte) 'Z', in.read()); + + TarInputStream tar = new TarInputStream(new CBZip2InputStream(in)); + while ((tar.getNextEntry()) != null) { + ; + } + tar.close(); + break; + } else { + // skip to the next entry + long skip = entry.getLength(); + while (skip > 0) { + long skipped = in.skip(skip); + if (skipped == -1) { + throw new IOException("Failed to skip"); + } + skip -= skipped; + } + } + } + in.close(); + + assertTrue("bz2 file not found", found); + } + + public void testNoCompression() throws Exception { + project.executeTarget("no-compression"); + + File deb = new File("target/test-classes/test.deb"); + assertTrue("package not build", deb.exists()); + + boolean found = false; + + ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); + ArArchiveEntry entry; + while ((entry = in.getNextArEntry()) != null) { + if (entry.getName().equals("data.tar")) { + found = true; + + TarInputStream tar = new TarInputStream(new NonClosingInputStream(in)); + while ((tar.getNextEntry()) != null) { + ; + } + tar.close(); + } else { + // skip to the next entry + long skip = entry.getLength(); + while (skip > 0) { + long skipped = in.skip(skip); + if (skipped == -1) { + throw new IOException("Failed to skip"); + } + skip -= skipped; + } + } + } + in.close(); + + assertTrue("tar file not found", found); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.compress.archivers.ar.ArArchiveInputStream` acquired by call to `new()` at line 236 is not released after line 257. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DebAntTaskTestCase.testBZip2Compression() + +### Procedure Id: +org.vafer.jdeb.ant.DebAntTaskTestCase.testBZip2Compression():void.f7bad500b7005e050281940ebb002e08 + +### File: +src/test/java/org/vafer/jdeb/ant/DebAntTaskTestCase.java + +### Key: +DebAntTaskTestCase.java|testBZip2Compression|RESOURCE_LEAK + +### Node Key: +99f813e1b01bd7111afa5cb643a24406 + +### Hash: +cc371551d7552afaeba9b57b2355d496 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10622/instruction.md b/inferredbugs-10622/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..28113f522490223e566f905e7ddc5e3b9aa2c416 --- /dev/null +++ b/inferredbugs-10622/instruction.md @@ -0,0 +1,271 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jdeb +**Bug ID:** 29 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2013 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.vafer.jdeb; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.zip.GZIPInputStream; + +import junit.framework.TestCase; +import org.apache.commons.compress.archivers.ar.ArArchiveEntry; +import org.apache.commons.compress.archivers.ar.ArArchiveInputStream; +import org.apache.commons.compress.utils.IOUtils; +import org.apache.commons.io.output.NullOutputStream; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.tar.TarEntry; +import org.apache.tools.tar.TarInputStream; +import org.vafer.jdeb.ar.NonClosingInputStream; +import org.vafer.jdeb.producers.DataProducerFileSet; +import org.vafer.jdeb.utils.InformationInputStream; +import org.vafer.jdeb.utils.MapVariableResolver; + +public class ProcessorTestCase extends TestCase { + + /** + * Checks if the file paths in the md5sums file use only unix file separators + * (this test can only fail on Windows) + */ + public void testBuildDataWithFileSet() throws Exception { + Processor processor = new Processor(new NullConsole(), null); + + Project project = new Project(); + project.setCoreLoader(getClass().getClassLoader()); + project.init(); + + FileSet fileset = new FileSet(); + fileset.setDir(new File(getClass().getResource("deb/data").toURI())); + fileset.setIncludes("**/*"); + fileset.setProject(project); + + StringBuilder md5s = new StringBuilder(); + processor.buildData(new DataProducer[] { new DataProducerFileSet(fileset) }, new File("target/data.tar"), md5s, Compression.GZIP); + + assertTrue("empty md5 file", md5s.length() > 0); + assertFalse("windows path separator found", md5s.indexOf("\\") != -1); + } + + public void testControlFilesPermissions() throws Exception { + File deb = new File("target/test-classes/test-control.deb"); + if (deb.exists() && !deb.delete()) { + fail("Couldn't delete " + deb); + } + + Processor processor = new Processor(new NullConsole(), new MapVariableResolver(Collections.emptyMap())); + + File controlDir = new File("target/test-classes/org/vafer/jdeb/deb/control"); + DataProducer[] producers = {new EmptyDataProducer()}; + + processor.createDeb(controlDir.listFiles(), producers, deb, Compression.NONE); + + // now reopen the package and check the control files + assertTrue("package not build", deb.exists()); + + boolean controlFound = false; + + ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); + try { + ArArchiveEntry entry; + while ((entry = in.getNextArEntry()) != null) { + if (entry.getName().equals("control.tar.gz")) { + TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(in))); + TarEntry tarentry; + while ((tarentry = tar.getNextEntry()) != null) { + controlFound = true; + + assertFalse("directory found in the control archive", tarentry.isDirectory()); + assertTrue("prefix", tarentry.getName().startsWith("./")); + + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + tar.copyEntryContents(bout); + + InformationInputStream infoStream = new InformationInputStream(new ByteArrayInputStream(bout.toByteArray())); + IOUtils.copy(infoStream, NullOutputStream.NULL_OUTPUT_STREAM); + + if (infoStream.isShell()) { + assertTrue("Permissions on " + tarentry.getName() + " should be 755", tarentry.getMode() == 0755); + } else { + assertTrue("Permissions on " + tarentry.getName() + " should be 644", tarentry.getMode() == 0644); + } + + assertTrue(tarentry.getName() + " doesn't have Unix line endings", infoStream.hasUnixLineEndings()); + + assertEquals("user", "root", tarentry.getUserName()); + assertEquals("group", "root", tarentry.getGroupName()); + } + tar.close(); + } else { + // skip to the next entry + long skip = entry.getLength(); + while (skip > 0) { + long skipped = in.skip(skip); + if (skipped == -1) { + throw new IOException("Failed to skip"); + } + skip -= skipped; + } + } + } + } finally { + in.close(); + } + + assertTrue("Control files not found in the package", controlFound); + } + + public void testControlFilesVariables() throws Exception { + File deb = new File("target/test-classes/test-control.deb"); + if (deb.exists() && !deb.delete()) { + fail("Couldn't delete " + deb); + } + + Map variables = new HashMap(); + variables.put("name", "jdeb"); + variables.put("version", "1.0"); + + Processor processor = new Processor(new NullConsole(), new MapVariableResolver(variables)); + + File controlDir = new File("target/test-classes/org/vafer/jdeb/deb/control"); + DataProducer[] producers = {new EmptyDataProducer()}; + + processor.createDeb(controlDir.listFiles(), producers, deb, Compression.NONE); + + // now reopen the package and check the control files + assertTrue("package not build", deb.exists()); + + boolean controlFound = false; + + ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); + try { + ArArchiveEntry entry; + while ((entry = in.getNextArEntry()) != null) { + if (entry.getName().equals("control.tar.gz")) { + TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(in))); + TarEntry tarentry; + while ((tarentry = tar.getNextEntry()) != null) { + controlFound = true; + + if (tarentry.getName().contains("postinst") || tarentry.getName().contains("prerm")) { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + tar.copyEntryContents(bout); + + String content = bout.toString("ISO-8859-1"); + + assertFalse("Variables not replaced in the control file " + tarentry.getName(), content.contains("[[name]] [[version]]")); + assertTrue("Expected variables not found in the control file " + tarentry.getName(), content.contains("jdeb 1.0")); + } + } + tar.close(); + } else { + // skip to the next entry + long skip = entry.getLength(); + while (skip > 0) { + long skipped = in.skip(skip); + if (skipped == -1) { + throw new IOException("Failed to skip"); + } + skip -= skipped; + } + } + } + } finally { + in.close(); + } + + assertTrue("Control files not found in the package", controlFound); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.vafer.jdeb.ar.NonClosingInputStream` acquired by call to `new()` at line 91 is not released after line 91. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ProcessorTestCase.testControlFilesPermissions() + +### Procedure Id: +org.vafer.jdeb.ProcessorTestCase.testControlFilesPermissions():void.2315024aac08080e21cb90537bcffbf8 + +### File: +src/test/java/org/vafer/jdeb/ProcessorTestCase.java + +### Key: +ProcessorTestCase.java|testControlFilesPermissions|RESOURCE_LEAK + +### Node Key: +f9dc00977db8917f52efafc2c101ca9a + +### Hash: +88f2e5fbeda628166ecb06a110396277 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10624/instruction.md b/inferredbugs-10624/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1a5b82658b53d1a9c657252eeee64d0fb4afaa86 --- /dev/null +++ b/inferredbugs-10624/instruction.md @@ -0,0 +1,286 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jdeb +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2005 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.vafer.jdeb.ant; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.Collection; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.taskdefs.MatchingTask; +import org.apache.tools.ant.taskdefs.Tar; +import org.apache.tools.ant.types.FileSet; +import org.vafer.jdeb.Console; +import org.vafer.jdeb.DataProducer; +import org.vafer.jdeb.Processor; +import org.vafer.jdeb.changes.TextfileChangesProvider; +import org.vafer.jdeb.descriptors.PackageDescriptor; + +/** + * AntTask for creating debian archives. + * Even supports signed changes files. + * + * @author tcurdt + */ + +public class DebAntTask extends MatchingTask { + + /** The Debian package produced */ + private File deb; + + /** The directory containing the control files to build the package */ + private File control; + + private File keyring; + private File changesIn; + private File changesOut; + private File changesSave; + private String key; + private String passphrase; + private boolean verbose; + + private Collection dataProducers = new ArrayList(); + + + public void setDestfile( File deb ) { + this.deb = deb; + } + + public void setControl( File control ) { + this.control = control; + } + + public void setChangesIn( File changes ) { + this.changesIn = changes; + } + + public void setChangesOut( File changes ) { + this.changesOut = changes; + } + + public void setChangesSave( File changes ) { + this.changesSave = changes; + } + + public void setKeyring( File keyring ) { + this.keyring = keyring; + } + + public void setKey( String key ) { + this.key = key; + } + + public void setPassphrase( String passphrase ) { + this.passphrase = passphrase; + } + + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + public void addFileSet(FileSet fileset) { + dataProducers.add(new FileSetDataProducer(fileset)); + } + + public void addTarFileSet(Tar.TarFileSet fileset) { + dataProducers.add(new FileSetDataProducer(fileset)); + } + + public void addData( Data data ) { + dataProducers.add(data); + } + + private boolean isPossibleOutput( File file ) { + + if (file.exists()) { + return file.isFile() && file.canWrite(); + } + + return true; + } + + public void execute() { + + if (control == null || !control.isDirectory()) { + throw new BuildException("You need to point the 'control' attribute to the control directory."); + } + + if (changesIn != null) { + + if (!changesIn.isFile() || !changesIn.canRead()) { + throw new BuildException("The 'changesIn' attribute needs to point to a readable file. " + changesIn + " was not found/readable."); + } + + if (changesOut == null) { + throw new BuildException("A 'changesIn' without a 'changesOut' does not make much sense."); + } + + if (!isPossibleOutput(changesOut)) { + throw new BuildException("Cannot write the output for 'changesOut' to " + changesOut); + } + + if (changesSave != null && !isPossibleOutput(changesSave)) { + throw new BuildException("Cannot write the output for 'changesSave' to " + changesSave); + } + + } else { + if (changesOut != null || changesSave != null) { + throw new BuildException("The 'changesOut' or 'changesSave' attributes may only be used when there is a 'changesIn' specified."); + } + } + + if (dataProducers.size() == 0) { + throw new BuildException("You need to provide at least one reference to a tgz or directory with data."); + } + + if (deb == null) { + throw new BuildException("You need to point the 'destfile' attribute to where the deb is supposed to be created."); + } + + final File[] controlFiles = control.listFiles(); + + final DataProducer[] data = new DataProducer[dataProducers.size()]; + dataProducers.toArray(data); + + final Processor processor = new Processor(new Console() { + public void println(String s) { + if (verbose) { + log(s); + } + } + }, null); + + final PackageDescriptor packageDescriptor; + try { + + packageDescriptor = processor.createDeb(controlFiles, data, deb); + + log("Created " + deb); + + } catch (Exception e) { + throw new BuildException("Failed to create debian package " + deb, e); + } + + final TextfileChangesProvider changesProvider; + + try { + if (changesOut == null) { + return; + } + + // for now only support reading the changes form a textfile provider + changesProvider = new TextfileChangesProvider(new FileInputStream(changesIn), packageDescriptor); + + processor.createChanges(packageDescriptor, changesProvider, (keyring!=null)?new FileInputStream(keyring):null, key, passphrase, new FileOutputStream(changesOut)); + + log("Created changes file " + changesOut); + + } catch (Exception e) { + throw new BuildException("Failed to create debian changes file " + changesOut, e); + } + + try { + if (changesSave == null) { + return; + } + + changesProvider.save(new FileOutputStream(changesSave)); + + log("Saved changes to file " + changesSave); + + } catch (Exception e) { + throw new BuildException("Failed to save debian changes file " + changesSave, e); + } + + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired by call to `FileInputStream(...)` at line 189 is not released after line 193. +**Note**: potential exception at line 189 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DebAntTask.execute() + +### Procedure Id: +org.vafer.jdeb.ant.DebAntTask.execute():void.190b328fd317e66b248cf90e78db47d0 + +### File: +src/main/java/org/vafer/jdeb/ant/DebAntTask.java + +### Key: +DebAntTask.java|execute|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +a2a488c8334467c31bc49b720aa87066 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10625/instruction.md b/inferredbugs-10625/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c34f624a0dd0c269194390fcc864adab75784e4 --- /dev/null +++ b/inferredbugs-10625/instruction.md @@ -0,0 +1,176 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jdeb +**Bug ID:** 28 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2013 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.vafer.jdeb; + +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.zip.GZIPInputStream; + +import junit.framework.TestCase; +import org.apache.commons.compress.archivers.ar.ArArchiveEntry; +import org.apache.commons.compress.archivers.ar.ArArchiveInputStream; +import org.apache.tools.tar.TarEntry; +import org.apache.tools.tar.TarInputStream; +import org.vafer.jdeb.ar.NonClosingInputStream; +import org.vafer.jdeb.descriptors.PackageDescriptor; +import org.vafer.jdeb.producers.DataProducerArchive; +import org.vafer.jdeb.producers.DataProducerDirectory; +import org.vafer.jdeb.producers.DataProducerLink; + +public final class DataProducerTestCase extends TestCase { + + public void testCreation() throws Exception { + + final Processor processor = new Processor(new NullConsole(), null); + + final File control = new File(getClass().getResource("deb/control/control").toURI()); + final File archive1 = new File(getClass().getResource("deb/data.tgz").toURI()); + final File archive2 = new File(getClass().getResource("deb/data.tar.bz2").toURI()); + final File archive3 = new File(getClass().getResource("deb/data.zip").toURI()); + final File directory = new File(getClass().getResource("deb/data").toURI()); + + final DataProducer[] data = new DataProducer[] { + new DataProducerArchive(archive1, null, null, null), + new DataProducerArchive(archive2, null, null, null), + new DataProducerArchive(archive3, null, null, null), + new DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null), + new DataProducerLink("/link/path-element.ext", "/link/target-element.ext", true, null, null, null) + }; + + final File deb = File.createTempFile("jdeb", ".deb"); + + final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, Compression.GZIP); + + assertTrue(packageDescriptor.isValid()); + + final Map filesInDeb = new HashMap(); + + final ArArchiveInputStream ar = new ArArchiveInputStream(new FileInputStream(deb)); + while (true) { + final ArArchiveEntry arEntry = ar.getNextArEntry(); + if (arEntry == null) { + break; + } + + if ("data.tar.gz".equals(arEntry.getName())) { + + final TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(ar))); + + while (true) { + final TarEntry tarEntry = tar.getNextEntry(); + if (tarEntry == null) { + break; + } + + filesInDeb.put(tarEntry.getName(), tarEntry); + } + + tar.close(); + break; + } + for (int i = 0; i < arEntry.getLength(); i++) { + ar.read(); + } + } + + ar.close(); + + assertTrue("testfile wasn't found in the package", filesInDeb.containsKey("./test/testfile")); + assertTrue("testfile2 wasn't found in the package", filesInDeb.containsKey("./test/testfile2")); + assertTrue("testfile3 wasn't found in the package", filesInDeb.containsKey("./test/testfile3")); + assertTrue("testfile4 wasn't found in the package", filesInDeb.containsKey("./test/testfile4")); + assertTrue("/link/path-element.ext wasn't found in the package", filesInDeb.containsKey("./link/path-element.ext")); + assertEquals("/link/path-element.ext has wrong link target", "/link/target-element.ext", filesInDeb.get("./link/path-element.ext").getLinkName()); + + assertTrue("Cannot delete the file " + deb, deb.delete()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.vafer.jdeb.ar.NonClosingInputStream` acquired by call to `new()` at line 72 is not released after line 72. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DataProducerTestCase.testCreation() + +### Procedure Id: +org.vafer.jdeb.DataProducerTestCase.testCreation():void.7486e7b7cafaccd2e25306cfabd83372 + +### File: +src/test/java/org/vafer/jdeb/DataProducerTestCase.java + +### Key: +DataProducerTestCase.java|testCreation|RESOURCE_LEAK + +### Node Key: +f9dc00977db8917f52efafc2c101ca9a + +### Hash: +b0e1e66e40843c8dea8bfbc19feef125 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10647/instruction.md b/inferredbugs-10647/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f4025bfb64c8171158e0be2088bbb01f9a34ffdf --- /dev/null +++ b/inferredbugs-10647/instruction.md @@ -0,0 +1,501 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jdeb +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2005 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.vafer.jdeb; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigInteger; +import java.security.DigestOutputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.zip.GZIPOutputStream; + +import org.apache.tools.tar.TarEntry; +import org.apache.tools.tar.TarOutputStream; +import org.vafer.jdeb.ar.ArArchive; +import org.vafer.jdeb.ar.FileArEntry; +import org.vafer.jdeb.ar.StaticArEntry; +import org.vafer.jdeb.changes.ChangeSet; +import org.vafer.jdeb.changes.ChangesProvider; +import org.vafer.jdeb.descriptors.ChangesDescriptor; +import org.vafer.jdeb.descriptors.InvalidDescriptorException; +import org.vafer.jdeb.descriptors.PackageDescriptor; +import org.vafer.jdeb.mapping.Mapper; +import org.vafer.jdeb.signing.SigningUtils; +import org.vafer.jdeb.utils.InformationOutputStream; +import org.vafer.jdeb.utils.Utils; + +/** + * The processor does the actual work of building the deb related files. + * It is been used by the ant task and (later) the maven plugin. + * + * @author tcurdt + */ +public class Processor { + + private final Console console; + private final Mapper mapper; + + private static final class Total { + private BigInteger count = BigInteger.valueOf(0); + + public void add(long size) { + count = count.add(BigInteger.valueOf(size)); + } + + public String toString() { + return "" + count; + } + + public BigInteger toBigInteger() { + return count; + } + } + + public Processor( final Console pConsole ) { + this(pConsole, new Mapper() { + public TarEntry map( final TarEntry pEntry ) { + return pEntry; + } + + }); + + } + + public Processor( final Console pConsole, final Mapper pMapper ) { + console = pConsole; + mapper = pMapper; + } + + /** + * Create the debian archive with from the provided control files and data producers. + * + * @param pControlFiles + * @param pData + * @param pOutput + * @return PackageDescriptor + * @throws PackagingException + */ + public PackageDescriptor createDeb( final File[] pControlFiles, final DataProducer[] pData, final File pOutput ) throws PackagingException, InvalidDescriptorException { + + File tempData = null; + File tempControl = null; + + try { + tempData = File.createTempFile("deb", "data"); + tempControl = File.createTempFile("deb", "control"); + + console.println("Building data"); + final StringBuffer md5s = new StringBuffer(); + final BigInteger size = buildData(pData, tempData, md5s); + + console.println("Building control"); + final PackageDescriptor packageDescriptor = buildControl(pControlFiles, size, md5s, tempControl); + + if (!packageDescriptor.isValid()) { + throw new InvalidDescriptorException(packageDescriptor); + } + + final InformationOutputStream output = new InformationOutputStream(new FileOutputStream(pOutput), MessageDigest.getInstance("MD5")); + + final ArArchive ar = new ArArchive(output); + ar.add(new StaticArEntry("debian-binary", 0, 0, 33188, "2.0\n")); + ar.add(new FileArEntry(tempControl,"control.tar.gz", 0, 0, 33188)); + ar.add(new FileArEntry(tempData, "data.tar.gz", 0, 0, 33188)); + ar.close(); + + // intermediate values + packageDescriptor.set("MD5", output.getMd5()); + packageDescriptor.set("Size", "" + output.getSize()); + packageDescriptor.set("File", pOutput.getName()); + + return packageDescriptor; + + } catch(InvalidDescriptorException e) { + throw e; + } catch(Exception e) { + throw new PackagingException("Could not create deb package", e); + } finally { + if (tempData != null) { + tempData.delete(); + } + if (tempControl != null) { + tempControl.delete(); + } + } + } + + /** + * Create changes file based on the provided PackageDescriptor. + * If pRing, pKey and pPassphrase are provided the changes file will also be signed. + * It returns a ChangesDescriptor reflecting the changes + * @param pPackageDescriptor + * @param pChangeSets + * @param pRing + * @param pKey + * @param pPassphrase + * @param pOutput + * @return ChangesDescriptor + * @throws IOException + */ + public ChangesDescriptor createChanges( final PackageDescriptor pPackageDescriptor, final ChangesProvider pChangesProvider, final InputStream pRing, final String pKey, final String pPassphrase, final OutputStream pOutput ) throws IOException, InvalidDescriptorException { + + final ChangeSet[] changeSets = pChangesProvider.getChangesSets(); + final ChangesDescriptor changesDescriptor = new ChangesDescriptor(pPackageDescriptor, changeSets); + + changesDescriptor.set("Format", "1.7"); + + if (changesDescriptor.get("Binary") == null) { + changesDescriptor.set("Binary", changesDescriptor.get("Package")); + } + + if (changesDescriptor.get("Source") == null) { + changesDescriptor.set("Source", changesDescriptor.get("Package")); + } + + if (changesDescriptor.get("Description") == null) { + changesDescriptor.set("Description", "update to " + changesDescriptor.get("Version")); + } + + final StringBuffer files = new StringBuffer("\n"); + files.append(' ').append(changesDescriptor.get("MD5")); + files.append(' ').append(changesDescriptor.get("Size")); + files.append(' ').append(changesDescriptor.get("Section")); + files.append(' ').append(changesDescriptor.get("Priority")); + files.append(' ').append(changesDescriptor.get("File")); + changesDescriptor.set("Files", files.toString()); + + if (!changesDescriptor.isValid()) { + throw new InvalidDescriptorException(changesDescriptor); + } + + final String changes = changesDescriptor.toString(); + //console.println(changes); + + final byte[] changesBytes = changes.getBytes("UTF-8"); + + if (pRing == null || pKey == null || pPassphrase == null) { + pOutput.write(changesBytes); + pOutput.close(); + return changesDescriptor; + } + + console.println("Signing changes with key " + pKey); + + final InputStream input = new ByteArrayInputStream(changesBytes); + + try { + SigningUtils.clearSign(input, pRing, pKey, pPassphrase, pOutput); + } catch (Exception e) { + e.printStackTrace(); + } + + pOutput.close(); + + return changesDescriptor; + } + + /** + * Build control archive of the deb + * @param pControlFiles + * @param pDataSize + * @param pChecksums + * @param pOutput + * @return + * @throws FileNotFoundException + * @throws IOException + * @throws ParseException + */ + private PackageDescriptor buildControl( final File[] pControlFiles, final BigInteger pDataSize, final StringBuffer pChecksums, final File pOutput ) throws FileNotFoundException, IOException, ParseException { + + PackageDescriptor packageDescriptor = null; + + final TarOutputStream outputStream = new TarOutputStream(new GZIPOutputStream(new FileOutputStream(pOutput))); + outputStream.setLongFileMode(TarOutputStream.LONGFILE_GNU); + + for (int i = 0; i < pControlFiles.length; i++) { + final File file = pControlFiles[i]; + + if (file.isDirectory()) { + continue; + } + + final TarEntry entry = new TarEntry(file); + + final String name = file.getName(); + + entry.setName(name); + + if ("control".equals(name)) { + packageDescriptor = new PackageDescriptor(new FileInputStream(file)); + + if (packageDescriptor.get("Date") == null) { + packageDescriptor.set("Date", new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(new Date())); // Mon, 26 Mar 2007 11:44:04 +0200 + } + + if (packageDescriptor.get("Distribution") == null) { + packageDescriptor.set("Distribution", "unknown"); + } + + if (packageDescriptor.get("Urgency") == null) { + packageDescriptor.set("Urgency", "low"); + } + + if (packageDescriptor.get("Maintainer") == null) { + + final String debFullName = System.getenv("DEBFULLNAME"); + final String debEmail = System.getenv("DEBEMAIL"); + if (debFullName != null && debEmail != null) { + packageDescriptor.set("Maintainer", debFullName + " <" + debEmail + ">"); + } + } + + continue; + } + + final InputStream inputStream = new FileInputStream(file); + + outputStream.putNextEntry(entry); + + Utils.copy(inputStream, outputStream); + + outputStream.closeEntry(); + + inputStream.close(); + + } + + if (packageDescriptor == null) { + throw new FileNotFoundException("No control file in " + Arrays.toString(pControlFiles)); + } + + packageDescriptor.set("Installed-Size", pDataSize.toString()); + + addEntry("control", packageDescriptor.toString(), outputStream); + + addEntry("md5sums", pChecksums.toString(), outputStream); + + outputStream.close(); + + return packageDescriptor; + } + + /** + * Build the data archive of the deb from the provided DataProducers + * @param pData + * @param pOutput + * @param pChecksums + * @return + * @throws NoSuchAlgorithmException + * @throws IOException + */ + private BigInteger buildData( final DataProducer[] pData, final File pOutput, final StringBuffer pChecksums ) throws NoSuchAlgorithmException, IOException { + + final TarOutputStream outputStream = new TarOutputStream(new GZIPOutputStream(new FileOutputStream(pOutput))); + outputStream.setLongFileMode(TarOutputStream.LONGFILE_GNU); + + final MessageDigest digest = MessageDigest.getInstance("MD5"); + + final Total dataSize = new Total(); + + final DataConsumer receiver = new DataConsumer() { + public void onEachDir( String dirname, String linkname, String user, int uid, String group, int gid, int mode, long size ) throws IOException { + + if (!dirname.endsWith("/")) { + dirname = dirname + "/"; + } + + if (!dirname.startsWith("/")) { + dirname = "/" + dirname; + } + + TarEntry entry = new TarEntry(dirname); + + // FIXME: link is in the constructor + entry.setUserName(user); + entry.setUserId(uid); + entry.setUserName(group); + entry.setGroupId(gid); + entry.setMode(mode); + entry.setSize(0); + + entry = mapper.map(entry); + + outputStream.putNextEntry(entry); + + console.println("dir: " + dirname); + + outputStream.closeEntry(); + } + + public void onEachFile( InputStream inputStream, String filename, String linkname, String user, int uid, String group, int gid, int mode, long size ) throws IOException { + + if (!filename.startsWith("/")) { + filename = "/" + filename; + } + + TarEntry entry = new TarEntry(filename); + + // FIXME: link is in the constructor + entry.setUserName(user); + entry.setUserId(uid); + entry.setUserName(group); + entry.setGroupId(gid); + entry.setMode(mode); + entry.setSize(size); + + entry = mapper.map(entry); + + outputStream.putNextEntry(entry); + + dataSize.add(size); + + digest.reset(); + + Utils.copy(inputStream, new DigestOutputStream(outputStream, digest)); + + final String md5 = Utils.toHex(digest.digest()); + + outputStream.closeEntry(); + + console.println( + "file:" + entry.getName() + + " size:" + entry.getSize() + + " mode:" + entry.getMode() + + " linkname:" + entry.getLinkName() + + " username:" + entry.getUserName() + + " userid:" + entry.getUserId() + + " groupname:" + entry.getGroupName() + + " groupid:" + entry.getGroupId() + + " modtime:" + entry.getModTime() + + " md5: " + md5 + ); + + pChecksums.append(md5).append(" ").append(entry.getName()).append('\n'); + + } + }; + + for (int i = 0; i < pData.length; i++) { + final DataProducer data = pData[i]; + data.produce(receiver); + } + + outputStream.close(); + + console.println("Total size: " + dataSize); + + return dataSize.count; + } + + private static void addEntry( final String pName, final String pContent, final TarOutputStream pOutput ) throws IOException { + final byte[] data = pContent.getBytes("UTF-8"); + + final TarEntry entry = new TarEntry(pName); + entry.setSize(data.length); + + pOutput.putNextEntry(entry); + pOutput.write(data); + pOutput.closeEntry(); + } + + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired by call to `FileInputStream(...)` at line 253 is not released after line 253. +**Note**: potential exception at line 253 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +PackageDescriptor Processor.buildControl(java.io.File[],BigInteger,StringBuffer,File) + +### Procedure Id: +org.vafer.jdeb.Processor.buildControl(java.io.File[],java.math.BigInteger,java.lang.StringBuffer,jav.019254bdeca21a8e102835a56dcb9704 + +### File: +src/main/java/org/vafer/jdeb/Processor.java + +### Key: +Processor.java|buildControl|RESOURCE_LEAK + +### Node Key: +da6943b6ed41aef54880409d2b07047d + +### Hash: +e558871a56330eed1e45ca5ffd1556df + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10649/instruction.md b/inferredbugs-10649/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4a1ad441471ac6cdda6b706b8d106b4610a12075 --- /dev/null +++ b/inferredbugs-10649/instruction.md @@ -0,0 +1,239 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jdeb +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2005 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.vafer.jdeb.descriptors; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.LineNumberReader; +import java.io.StringReader; +import java.text.ParseException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.vafer.jdeb.utils.Utils; +import org.vafer.jdeb.utils.VariableResolver; + +/** + * A descriptor holds the usual key value pairs + * + * @author tcurdt + */ +public abstract class AbstractDescriptor { + + private final Map values = new HashMap(); + private final VariableResolver resolver; + + public AbstractDescriptor( final VariableResolver pResolver ) { + resolver = pResolver; + } + + public AbstractDescriptor( final AbstractDescriptor pDescriptor ) { + values.putAll(pDescriptor.values); + resolver = pDescriptor.resolver; + } + + protected void parse( final InputStream pInput ) throws IOException, ParseException { + final BufferedReader br = new BufferedReader(new InputStreamReader(pInput)); + StringBuffer buffer = new StringBuffer(); + String key = null; + int linenr = 0; + while(true) { + final String line = br.readLine(); + + if (line == null) { + if (buffer.length() > 0) { + // flush value of previous key + set(key, buffer.toString()); + buffer = null; + } + break; + } + + linenr++; + + final char first = line.charAt(0); + if (Character.isLetter(first)) { + + // new key + + if (buffer.length() > 0) { + // flush value of previous key + set(key, buffer.toString()); + buffer = new StringBuffer(); + } + + + final int i = line.indexOf(':'); + + if (i < 0) { + throw new ParseException("Line misses ':' delimitter", linenr); + } + + key = line.substring(0, i); + buffer.append(line.substring(i+1).trim()); + + continue; + } + + // continuing old value + buffer.append('\n').append(line.substring(1)); + } + br.close(); + + } + + public void set( final String pKey, final String pValue ) { + + if (resolver != null) { + try { + values.put(pKey, Utils.replaceVariables(resolver, pValue, "[[", "]]")); + return; + } catch (ParseException e) { + // FIXME maybe throw an Exception? + } + } + + values.put(pKey, pValue); + } + + public String get( final String pKey ) { + return (String)values.get(pKey); + } + + public abstract String[] getMandatoryKeys(); + + public boolean isValid() { + return invalidKeys().size() == 0; + } + + public Set invalidKeys() { + final Set invalid = new HashSet(); + + final String[] mk = getMandatoryKeys(); + for (int i = 0; i < mk.length; i++) { + if (get(mk[i]) == null) { + invalid.add(mk[i]); + } + } + + return invalid; + } + + String toString( final String[] pKeys ) { + final StringBuffer s = new StringBuffer(); + for (int i = 0; i < pKeys.length; i++) { + final String key = pKeys[i]; + final String value = (String) values.get(key); + if (value != null) { + s.append(key).append(": "); + + try { + LineNumberReader reader = new LineNumberReader(new StringReader(value)); + String line; + while ((line = reader.readLine()) != null) { + if (reader.getLineNumber() > 0 && line.length() != 0 && !Character.isWhitespace(line.charAt(0))) { + // indent the line with a white space + s.append(' '); + } + + s.append(line).append('\n'); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return s.toString(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.LineNumberReader` acquired to `reader` by call to `new()` at line 148 is not released after line 150. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String AbstractDescriptor.toString(java.lang.String[]) + +### Procedure Id: +org.vafer.jdeb.descriptors.AbstractDescriptor.toString(java.lang.String[]):java.lang.String.7d0620f83405963676f7b7b1b4cdc194 + +### File: +src/main/java/org/vafer/jdeb/descriptors/AbstractDescriptor.java + +### Key: +AbstractDescriptor.java|toString|RESOURCE_LEAK + +### Node Key: +a6fc1bef9f435059cdc11fa7028c0a42 + +### Hash: +acf51c65bdbbb245b705007a7dd901d9 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10671/instruction.md b/inferredbugs-10671/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1ec4e6bc6a34ac0685914b1737bec8f1a8ac2e7 --- /dev/null +++ b/inferredbugs-10671/instruction.md @@ -0,0 +1,795 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** biweekly +**Bug ID:** 42 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package biweekly.io.text; + +import static biweekly.util.TestUtils.assertRegex; +import static biweekly.util.TestUtils.assertWarnings; +import static biweekly.util.TestUtils.buildTimezone; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.io.StringWriter; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.TimeZone; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import biweekly.ICalendar; +import biweekly.component.DaylightSavingsTime; +import biweekly.component.ICalComponent; +import biweekly.component.StandardTime; +import biweekly.component.VAlarm; +import biweekly.component.VEvent; +import biweekly.component.VFreeBusy; +import biweekly.component.VJournal; +import biweekly.component.VTimezone; +import biweekly.component.VTodo; +import biweekly.component.marshaller.ICalComponentMarshaller; +import biweekly.io.SkipMeException; +import biweekly.parameter.CalendarUserType; +import biweekly.parameter.ICalParameters; +import biweekly.parameter.ParticipationStatus; +import biweekly.parameter.Role; +import biweekly.property.Attachment; +import biweekly.property.Attendee; +import biweekly.property.Classification; +import biweekly.property.FreeBusy; +import biweekly.property.ICalProperty; +import biweekly.property.Status; +import biweekly.property.Trigger; +import biweekly.property.Version; +import biweekly.property.marshaller.ICalPropertyMarshaller; +import biweekly.util.Duration; +import biweekly.util.IOUtils; + +/* + Copyright (c) 2013, Michael Angstadt + 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 COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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. + */ + +/** + * @author Michael Angstadt + */ +public class ICalWriterTest { + private static TimeZone defaultTz; + private final DateFormat utcFormatter; + { + utcFormatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); + utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); + } + private final DateFormat usEasternFormatter; + { + usEasternFormatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); + usEasternFormatter.setTimeZone(TimeZone.getTimeZone("America/New_York")); + } + private final DateFormat localFormatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); + + @BeforeClass + public static void beforeClass() { + //change the default timezone because my timezone is "American/New_York", which is what the example jCal documents use + defaultTz = TimeZone.getDefault(); + TimeZone.setDefault(buildTimezone(1, 0)); + } + + @AfterClass + public static void afterClass() { + TimeZone.setDefault(defaultTz); + } + + @Test + public void basic() throws Exception { + ICalendar ical = new ICalendar(); + + VEvent event = new VEvent(); + event.setSummary("summary"); + ical.addEvent(event); + + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "BEGIN:VCALENDAR\r\n" + + "VERSION:2\\.0\r\n" + + "PRODID:.*?\r\n" + + "BEGIN:VEVENT\r\n" + + "UID:.*?\r\n" + + "DTSTAMP:.*?\r\n" + + "SUMMARY:summary\r\n" + + "END:VEVENT\r\n" + + "END:VCALENDAR\r\n"; + //@formatter:on + + String actual = sw.toString(); + assertRegex(expected, actual); + } + + @Test + public void escape_newlines() throws Exception { + ICalendar ical = new ICalendar(); + + VEvent event = new VEvent(); + event.setSummary("summary\nof event"); + ical.addEvent(event); + + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "BEGIN:VCALENDAR\r\n" + + "VERSION:2\\.0\r\n" + + "PRODID:.*?\r\n" + + "BEGIN:VEVENT\r\n" + + "UID:.*?\r\n" + + "DTSTAMP:.*?\r\n" + + "SUMMARY:summary\\\\nof event\r\n" + + "END:VEVENT\r\n" + + "END:VCALENDAR\r\n"; + //@formatter:on + + String actual = sw.toString(); + assertRegex(expected, actual); + } + + @Test + public void bad_parameter_value_chars() throws Exception { + ICalendar ical = new ICalendar(); + ical.getProductId().addParameter("X-TEST", "\"test\""); + + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "BEGIN:VCALENDAR\r\n" + + "VERSION:2\\.0\r\n" + + "PRODID;X-TEST='test':.*?\r\n" + + "END:VCALENDAR\r\n"; + //@formatter:on + + String actual = sw.toString(); + assertRegex(expected, actual); + } + + @Test + public void caret_encoding() throws Exception { + ICalendar ical = new ICalendar(); + ical.getProductId().addParameter("X-TEST", "\"test\""); + + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw); + writer.setCaretEncodingEnabled(true); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "BEGIN:VCALENDAR\r\n" + + "VERSION:2\\.0\r\n" + + "PRODID;X-TEST=\\^'test\\^':.*?\r\n" + + "END:VCALENDAR\r\n"; + //@formatter:on + + String actual = sw.toString(); + assertRegex(expected, actual); + } + + @Test + public void multiple() throws Exception { + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw); + writer.write(new ICalendar()); + writer.write(new ICalendar()); + writer.close(); + + //@formatter:off + String expected = + "BEGIN:VCALENDAR\r\n" + + "VERSION:2\\.0\r\n" + + "PRODID:.*?\r\n" + + "END:VCALENDAR\r\n" + + "BEGIN:VCALENDAR\r\n" + + "VERSION:2\\.0\r\n" + + "PRODID:.*?\r\n" + + "END:VCALENDAR\r\n"; + //@formatter:on + + String actual = sw.toString(); + assertRegex(expected, actual); + } + + @Test(expected = IllegalArgumentException.class) + public void no_property_marshaller() throws Exception { + ICalendar ical = new ICalendar(); + ical.addProperty(new TestProperty("value")); + + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw); + writer.write(ical); + } + + @Test(expected = IllegalArgumentException.class) + public void no_component_marshaller() throws Exception { + ICalendar ical = new ICalendar(); + ical.addComponent(new Party()); + + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw); + writer.write(ical); + } + + @Test(expected = IllegalArgumentException.class) + public void bad_property_name() throws Exception { + ICalendar ical = new ICalendar(); + ical.addProperty(new TestProperty("value")); + + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw); + writer.registerMarshaller(new BadNameMarshaller()); + writer.write(ical); + } + + @Test + public void skipMeException() throws Exception { + ICalendar ical = new ICalendar(); + ical.addProperty(new TestProperty("value")); + + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw); + writer.registerMarshaller(new SkipMeMarshaller()); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "BEGIN:VCALENDAR\r\n" + + "VERSION:2\\.0\r\n" + + "PRODID:.*?\r\n" + + "END:VCALENDAR\r\n"; + //@formatter:on + + String actual = sw.toString(); + assertRegex(expected, actual); + } + + @Test + public void override_marshaller() throws Exception { + ICalendar ical = new ICalendar(); + + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw); + writer.registerMarshaller(new MyVersionMarshaller()); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "BEGIN:VCALENDAR\r\n" + + "VERSION:2\\.0 \\(beta\\)\r\n" + + "PRODID:.*?\r\n" + + "END:VCALENDAR\r\n"; + //@formatter:on + + String actual = sw.toString(); + assertRegex(expected, actual); + } + + @Test + public void experimental_property() throws Exception { + ICalendar ical = new ICalendar(); + ical.addExperimentalProperty("X-NUMBER", "1"); + ical.addExperimentalProperty("X-NUMBER", "2"); + + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "BEGIN:VCALENDAR\r\n" + + "VERSION:2\\.0\r\n" + + "PRODID:.*?\r\n" + + "X-NUMBER:1\r\n" + + "X-NUMBER:2\r\n" + + "END:VCALENDAR\r\n"; + //@formatter:on + + String actual = sw.toString(); + assertRegex(expected, actual); + } + + @Test + public void experimental_property_marshaller() throws Exception { + ICalendar ical = new ICalendar(); + ical.addProperty(new TestProperty("one")); + ical.addProperty(new TestProperty("two")); + + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw); + writer.registerMarshaller(new TestPropertyMarshaller()); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "BEGIN:VCALENDAR\r\n" + + "VERSION:2\\.0\r\n" + + "PRODID:.*?\r\n" + + "X-TEST:one\r\n" + + "X-TEST:two\r\n" + + "END:VCALENDAR\r\n"; + //@formatter:on + + String actual = sw.toString(); + assertRegex(expected, actual); + } + + @Test + public void experimental_component() throws Exception { + ICalendar ical = new ICalendar(); + ical.addExperimentalComponent("X-VPARTY"); + + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "BEGIN:VCALENDAR\r\n" + + "VERSION:2\\.0\r\n" + + "PRODID:.*?\r\n" + + "BEGIN:X-VPARTY\r\n" + + "END:X-VPARTY\r\n" + + "END:VCALENDAR\r\n"; + //@formatter:on + + String actual = sw.toString(); + assertRegex(expected, actual); + } + + @Test + public void experimental_component_marshaller() throws Exception { + ICalendar ical = new ICalendar(); + ical.addComponent(new Party()); + + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw); + writer.registerMarshaller(new PartyMarshaller()); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "BEGIN:VCALENDAR\r\n" + + "VERSION:2\\.0\r\n" + + "PRODID:.*?\r\n" + + "BEGIN:X-VPARTY\r\n" + + "END:X-VPARTY\r\n" + + "END:VCALENDAR\r\n"; + //@formatter:on + + String actual = sw.toString(); + assertRegex(expected, actual); + } + + @Test + public void example1() throws Throwable { + ICalendar ical = new ICalendar(); + ical.getProperties().clear(); + ical.setProductId("-//xyz Corp//NONSGML PDA Calendar Version 1.0//EN"); + ical.setVersion(Version.v2_0()); + { + VEvent event = new VEvent(); + event.getProperties().clear(); + event.setDateTimeStamp(utcFormatter.parse("19960704T120000")); + event.setUid("uid1@example.com"); + event.setOrganizer("jsmith@example.com"); + event.setDateStart(utcFormatter.parse("19960918T143000")); + event.setDateEnd(utcFormatter.parse("19960920T220000")); + event.setStatus(Status.confirmed()); + event.addCategories("CONFERENCE"); + event.setSummary("Networld+Interop Conference"); + event.setDescription("Networld+Interop Conferenceand Exhibit\nAtlanta World Congress Center\nAtlanta, Georgia"); + ical.addEvent(event); + } + + assertWarnings(0, ical.validate()); + assertExample(ical, "rfc5545-example1.ics"); + } + + @Test + public void example2() throws Throwable { + VTimezone usEasternTz; + ICalendar ical = new ICalendar(); + ical.getProperties().clear(); + ical.setProductId("-//RDU Software//NONSGML HandCal//EN"); + ical.setVersion(Version.v2_0()); + { + usEasternTz = new VTimezone(null); + usEasternTz.setTimezoneId("America/New_York"); + { + StandardTime standard = new StandardTime(); + standard.setDateStart(localFormatter.parse("19981025T020000")).setLocalTime(true); + standard.setTimezoneOffsetFrom(-4, 0); + standard.setTimezoneOffsetTo(-5, 0); + standard.addTimezoneName("EST"); + usEasternTz.addStandardTime(standard); + } + { + DaylightSavingsTime daylight = new DaylightSavingsTime(); + daylight.setDateStart(localFormatter.parse("19990404T020000")).setLocalTime(true); + daylight.setTimezoneOffsetFrom(-5, 0); + daylight.setTimezoneOffsetTo(-4, 0); + daylight.addTimezoneName("EDT"); + usEasternTz.addDaylightSavingsTime(daylight); + } + ical.addTimezone(usEasternTz); + } + { + VEvent event = new VEvent(); + event.setDateTimeStamp(utcFormatter.parse("19980309T231000")); + event.setUid("guid-1.example.com"); + event.setOrganizer("mrbig@example.com"); + + Attendee attendee = Attendee.email("employee-A@example.com"); + attendee.setRsvp(true); + attendee.setRole(Role.REQ_PARTICIPANT); + attendee.setCalendarUserType(CalendarUserType.GROUP); + event.addAttendee(attendee); + + event.setDescription("Project XYZ Review Meeting"); + event.addCategories("MEETING"); + event.setClassification(Classification.public_()); + event.setCreated(utcFormatter.parse("19980309T130000")); + event.setSummary("XYZ Project Review"); + event.setDateStart(usEasternFormatter.parse("19980312T083000")).setTimezone(usEasternTz); + event.setDateEnd(usEasternFormatter.parse("19980312T093000")).setTimezone(usEasternTz); + event.setLocation("1CP Conference Room 4350"); + ical.addEvent(event); + } + + assertWarnings(0, ical.validate()); + assertExample(ical, "rfc5545-example2.ics"); + } + + @Test + public void example3() throws Throwable { + ICalendar ical = new ICalendar(); + ical.getProperties().clear(); + ical.setMethod("xyz"); + ical.setVersion(Version.v2_0()); + ical.setProductId("-//ABC Corporation//NONSGML My Product//EN"); + { + VEvent event = new VEvent(); + event.getProperties().clear(); + event.setDateTimeStamp(utcFormatter.parse("19970324T120000")); + event.setSequence(0); + event.setUid("uid3@example.com"); + event.setOrganizer("jdoe@example.com"); + + Attendee attendee = Attendee.email("jsmith@example.com"); + attendee.setRsvp(true); + event.addAttendee(attendee); + + event.setDateStart(utcFormatter.parse("19970324T123000")); + event.setDateEnd(utcFormatter.parse("19970324T210000")); + event.addCategories("MEETING", "PROJECT"); + event.setClassification(Classification.public_()); + event.setSummary("Calendaring Interoperability Planning Meeting"); + event.setDescription("Discuss how we can test c&s interoperability\nusing iCalendar and other IETF standards."); + event.setLocation("LDB Lobby"); + + Attachment attach = new Attachment("application/postscript", "ftp://example.com/pub/conf/bkgrnd.ps"); + event.addAttachment(attach); + + ical.addEvent(event); + } + + assertWarnings(0, ical.validate()); + assertExample(ical, "rfc5545-example3.ics"); + } + + @Test + public void example4() throws Throwable { + ICalendar ical = new ICalendar(); + ical.getProperties().clear(); + ical.setVersion(Version.v2_0()); + ical.setProductId("-//ABC Corporation//NONSGML My Product//EN"); + { + VTodo todo = new VTodo(); + todo.getProperties().clear(); + todo.setDateTimeStamp(utcFormatter.parse("19980130T134500")); + todo.setSequence(2); + todo.setUid("uid4@example.com"); + todo.setOrganizer("unclesam@example.com"); + + Attendee attendee = Attendee.email("jqpublic@example.com"); + attendee.setParticipationStatus(ParticipationStatus.ACCEPTED); + todo.addAttendee(attendee); + + todo.setDateDue(localFormatter.parse("19980415T000000")).setLocalTime(true); + todo.setStatus(Status.needsAction()); + todo.setSummary("Submit Income Taxes"); + { + Trigger trigger = new Trigger(utcFormatter.parse("19980403T120000")); + Attachment attach = new Attachment("audio/basic", "http://example.com/pub/audio-files/ssbanner.aud"); + VAlarm alarm = VAlarm.audio(trigger, attach); + alarm.setRepeat(4); + alarm.setDuration(new Duration.Builder().hours(1).build()); + todo.addAlarm(alarm); + } + + ical.addTodo(todo); + } + + assertWarnings(0, ical.validate()); + assertExample(ical, "rfc5545-example4.ics"); + } + + @Test + public void example5() throws Throwable { + ICalendar ical = new ICalendar(); + ical.getProperties().clear(); + ical.setVersion(Version.v2_0()); + ical.setProductId("-//ABC Corporation//NONSGML My Product//EN"); + { + VJournal journal = new VJournal(); + journal.getProperties().clear(); + journal.setDateTimeStamp(utcFormatter.parse("19970324T120000")); + journal.setUid("uid5@example.com"); + journal.setOrganizer("jsmith@example.com"); + journal.setStatus(Status.draft()); + journal.setClassification(Classification.public_()); + journal.addCategories("Project Report", "XYZ", "Weekly Meeting"); + journal.addDescription("Project xyz Review Meeting Minutes\nAgenda\n1. Review of project version 1.0 requirements.\n2.Definitionof project processes.\n3. Review of project schedule.\nParticipants: John Smith, Jane Doe, Jim Dandy\n-It wasdecided that the requirements need to be signed off byproduct marketing.\n-Project processes were accepted.\n-Project schedule needs to account for scheduled holidaysand employee vacation time. Check with HR for specificdates.\n-New schedule will be distributed by Friday.\n-Next weeks meeting is cancelled. No meeting until 3/23."); + ical.addJournal(journal); + } + + assertWarnings(0, ical.validate()); + assertExample(ical, "rfc5545-example5.ics"); + } + + @Test + public void example6() throws Throwable { + ICalendar ical = new ICalendar(); + ical.getProperties().clear(); + ical.setVersion(Version.v2_0()); + ical.setProductId("-//RDU Software//NONSGML HandCal//EN"); + { + VFreeBusy freebusy = new VFreeBusy(); + freebusy.getProperties().clear(); + freebusy.setOrganizer("jsmith@example.com"); + freebusy.setDateStart(utcFormatter.parse("19980313T141711")); + freebusy.setDateEnd(utcFormatter.parse("19980410T141711")); + + FreeBusy fb = new FreeBusy(); + fb.addValue(utcFormatter.parse("19980314T233000"), utcFormatter.parse("19980315T003000")); + freebusy.addFreeBusy(fb); + + fb = new FreeBusy(); + fb.addValue(utcFormatter.parse("19980316T153000"), utcFormatter.parse("19980316T163000")); + freebusy.addFreeBusy(fb); + + fb = new FreeBusy(); + fb.addValue(utcFormatter.parse("19980318T030000"), utcFormatter.parse("19980318T040000")); + freebusy.addFreeBusy(fb); + + freebusy.setUrl("http://www.example.com/calendar/busytime/jsmith.ifb"); + ical.addFreeBusy(freebusy); + } + + assertWarnings(2, ical.validate()); //UID and DTSTAMP missing + assertExample(ical, "rfc5545-example6.ics"); + } + + private void assertExample(ICalendar ical, String exampleFileName) throws IOException { + StringWriter sw = new StringWriter(); + ICalWriter writer = new ICalWriter(sw, null); + writer.write(ical); + writer.close(); + + String expected = new String(IOUtils.toByteArray(getClass().getResourceAsStream(exampleFileName))); + expected = expected.replaceAll("([^\r])\n", "$1\r\n"); //replace \n with \r\n + expected = expected.replaceAll("\r\n ", ""); //unfold folded lines + + String actual = sw.toString(); + + assertEquals(expected, actual); + } + + private class TestProperty extends ICalProperty { + private String value; + + public TestProperty(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + } + + private class TestPropertyMarshaller extends ICalPropertyMarshaller { + public TestPropertyMarshaller() { + super(TestProperty.class, "X-TEST"); + } + + @Override + protected String _writeText(TestProperty property) { + return property.getValue(); + } + + @Override + protected TestProperty _parseText(String value, ICalParameters parameters, List warnings) { + return new TestProperty(value); + } + } + + private class BadNameMarshaller extends ICalPropertyMarshaller { + public BadNameMarshaller() { + super(TestProperty.class, "BAD*NAME"); + } + + @Override + protected String _writeText(TestProperty property) { + return property.getValue(); + } + + @Override + protected TestProperty _parseText(String value, ICalParameters parameters, List warnings) { + return new TestProperty(value); + } + } + + private class SkipMeMarshaller extends ICalPropertyMarshaller { + public SkipMeMarshaller() { + super(TestProperty.class, "NAME"); + } + + @Override + protected String _writeText(TestProperty property) { + throw new SkipMeException("Skipped"); + } + + @Override + protected TestProperty _parseText(String value, ICalParameters parameters, List warnings) { + return new TestProperty(value); + } + } + + private class MyVersionMarshaller extends ICalPropertyMarshaller { + public MyVersionMarshaller() { + super(Version.class, "VERSION"); + } + + @Override + protected String _writeText(Version property) { + return property.getMaxVersion() + " (beta)"; + } + + @Override + protected Version _parseText(String value, ICalParameters parameters, List warnings) { + return new Version(value); + } + } + + private class PartyMarshaller extends ICalComponentMarshaller { + public PartyMarshaller() { + super(Party.class, "X-VPARTY"); + } + + @Override + protected Party _newInstance() { + return new Party(); + } + } + + private class Party extends ICalComponent { + //empty + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `standard.setDateStart(ICalWriterTest.localFormatter.parse("19981025T020000"))` could be null and is dereferenced at line 443. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ICalWriterTest.example2() + +### Procedure Id: +biweekly.io.text.ICalWriterTest.example2():void.7f1d996efa5ade50f23ea7d94754b460 + +### File: +src/test/java/biweekly/io/text/ICalWriterTest.java + +### Key: +ICalWriterTest.java|example2|NULL_DEREFERENCE + +### Node Key: +f748d9ffd849bf00ecfc267a3683e52c + +### Hash: +19e5a31154fa8be92938248f0c49400e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10676/instruction.md b/inferredbugs-10676/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c823866dd305c33504c04cbd5716cde6c79ab7f8 --- /dev/null +++ b/inferredbugs-10676/instruction.md @@ -0,0 +1,315 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** biweekly +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package biweekly.property.marshaller; + +import static biweekly.util.TestUtils.assertWarnings; +import static biweekly.util.TestUtils.xcalProperty; +import static biweekly.util.TestUtils.xcalPropertyElement; +import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import biweekly.io.CannotParseException; +import biweekly.parameter.ICalParameters; +import biweekly.property.Geo; +import biweekly.property.marshaller.ICalPropertyMarshaller.Result; +import biweekly.util.XmlUtils; + +/* + Copyright (c) 2013, Michael Angstadt + 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 COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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. + */ + +/** + * @author Michael Angstadt + */ +public class GeoMarshallerTest { + private final GeoMarshaller marshaller = new GeoMarshaller(); + + @Test + public void writeText() { + Geo prop = new Geo(12.34, 56.78); + + String actual = marshaller.writeText(prop); + + String expected = "12.34;56.78"; + assertEquals(expected, actual); + } + + @Test + public void writeText_missing_latitude() { + Geo prop = new Geo(null, 56.78); + String actual = marshaller.writeText(prop); + String expected = ";56.78"; + assertEquals(expected, actual); + } + + @Test + public void writeText_missing_longitude() { + Geo prop = new Geo(12.34, null); + String actual = marshaller.writeText(prop); + String expected = "12.34;"; + assertEquals(expected, actual); + } + + @Test + public void writeText_missing_both() { + Geo prop = new Geo(null, null); + String actual = marshaller.writeText(prop); + String expected = ";"; + assertEquals(expected, actual); + } + + @Test + public void parseText() { + String value = "12.34;56.78"; + ICalParameters params = new ICalParameters(); + + Result result = marshaller.parseText(value, params); + + Geo prop = result.getValue(); + assertEquals(12.34, prop.getLatitude(), 0.001); + assertEquals(56.78, prop.getLongitude(), 0.001); + assertWarnings(0, result.getWarnings()); + } + + @Test(expected = CannotParseException.class) + public void parseText_no_longitude() { + String value = "12.34"; + ICalParameters params = new ICalParameters(); + + marshaller.parseText(value, params); + } + + @Test(expected = CannotParseException.class) + public void parseText_empty() { + String value = ""; + ICalParameters params = new ICalParameters(); + + marshaller.parseText(value, params); + } + + @Test(expected = CannotParseException.class) + public void parseText_bad_latitude() { + String value = "bad;56.78"; + ICalParameters params = new ICalParameters(); + + marshaller.parseText(value, params); + } + + @Test(expected = CannotParseException.class) + public void parseText_bad_longitude() { + String value = "12.34;bad"; + ICalParameters params = new ICalParameters(); + + marshaller.parseText(value, params); + } + + @Test + public void writeXml() { + Geo prop = new Geo(12.34, 56.78); + + Document actual = xcalProperty(marshaller); + marshaller.writeXml(prop, XmlUtils.getRootElement(actual)); + + Document expected = xcalProperty(marshaller, "12.3456.78"); + assertXMLEqual(expected, actual); + } + + @Test + public void writeXml_missing_latitude() { + Geo prop = new Geo(null, 56.78); + + Document actual = xcalProperty(marshaller); + marshaller.writeXml(prop, XmlUtils.getRootElement(actual)); + + Document expected = xcalProperty(marshaller, "56.78"); + assertXMLEqual(expected, actual); + } + + @Test + public void writeXml_missing_longitude() { + Geo prop = new Geo(12.34, null); + + Document actual = xcalProperty(marshaller); + marshaller.writeXml(prop, XmlUtils.getRootElement(actual)); + + Document expected = xcalProperty(marshaller, "12.34"); + assertXMLEqual(expected, actual); + } + + @Test + public void writeXml_missing_both() { + Geo prop = new Geo(null, null); + + Document actual = xcalProperty(marshaller); + marshaller.writeXml(prop, XmlUtils.getRootElement(actual)); + + Document expected = xcalProperty(marshaller, ""); + assertXMLEqual(expected, actual); + } + + @Test + public void parseXml() { + ICalParameters params = new ICalParameters(); + + Element element = xcalPropertyElement(marshaller, "12.3456.78"); + Result result = marshaller.parseXml(element, params); + + Geo prop = result.getValue(); + assertEquals(12.34, prop.getLatitude(), 0.001); + assertEquals(56.78, prop.getLongitude(), 0.001); + assertWarnings(0, result.getWarnings()); + } + + @Test + public void parseXml_missing_latitude() { + ICalParameters params = new ICalParameters(); + + Element element = xcalPropertyElement(marshaller, "56.78"); + Result result = marshaller.parseXml(element, params); + + Geo prop = result.getValue(); + assertNull(prop.getLatitude()); + assertEquals(56.78, prop.getLongitude(), 0.001); + assertWarnings(0, result.getWarnings()); + } + + @Test + public void parseXml_missing_longitude() { + ICalParameters params = new ICalParameters(); + + Element element = xcalPropertyElement(marshaller, "12.34"); + Result result = marshaller.parseXml(element, params); + + Geo prop = result.getValue(); + assertEquals(12.34, prop.getLatitude(), 0.001); + assertNull(prop.getLongitude()); + assertWarnings(0, result.getWarnings()); + } + + @Test + public void parseXml_missing_both() { + ICalParameters params = new ICalParameters(); + + Element element = xcalPropertyElement(marshaller, ""); + Result result = marshaller.parseXml(element, params); + + Geo prop = result.getValue(); + assertNull(prop.getLatitude()); + assertNull(prop.getLongitude()); + assertWarnings(0, result.getWarnings()); + } + + @Test(expected = CannotParseException.class) + public void parseXml_bad_latitude() { + ICalParameters params = new ICalParameters(); + + Element element = xcalPropertyElement(marshaller, "bad56.78"); + marshaller.parseXml(element, params); + } + + @Test(expected = CannotParseException.class) + public void parseXml_bad_longitude() { + ICalParameters params = new ICalParameters(); + + Element element = xcalPropertyElement(marshaller, "12.34bad"); + marshaller.parseXml(element, params); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getRootElement(actual)` could be null and is dereferenced by call to `writeXml(...)` at line 157. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GeoMarshallerTest.writeXml_missing_longitude() + +### Procedure Id: +biweekly.property.marshaller.GeoMarshallerTest.writeXml_missing_longitude():void.a9a295cb76062bfc1525399622af7424 + +### File: +src/test/java/biweekly/property/marshaller/GeoMarshallerTest.java + +### Key: +GeoMarshallerTest.java|writeXml_missing_longitude|NULL_DEREFERENCE + +### Node Key: +d0ec784a9a07b2ee980cc56c82eecd21 + +### Hash: +b665daf877c4f4bcf9d573a8bf4bf48e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10678/instruction.md b/inferredbugs-10678/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..530f8d7ab11a1fe8fe02c437e7fe30083c08b715 --- /dev/null +++ b/inferredbugs-10678/instruction.md @@ -0,0 +1,235 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** biweekly +**Bug ID:** 26 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package biweekly.property.marshaller; + +import static biweekly.util.TestUtils.assertWarnings; +import static biweekly.util.TestUtils.xcalProperty; +import static biweekly.util.TestUtils.xcalPropertyElement; +import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import biweekly.parameter.ICalParameters; +import biweekly.parameter.Value; +import biweekly.property.TextProperty; +import biweekly.property.marshaller.ICalPropertyMarshaller.Result; +import biweekly.util.XmlUtils; + +/* + Copyright (c) 2013, Michael Angstadt + 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 COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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. + */ + +/** + * @author Michael Angstadt + */ +public class TextPropertyMarshallerTest { + private final TextPropertyMarshallerImpl marshaller = new TextPropertyMarshallerImpl(); + + @Test + public void writeText() { + TextPropertyImpl prop = new TextPropertyImpl("the;text"); + + String actual = marshaller.writeText(prop); + + String expected = "the\\;text"; + assertEquals(expected, actual); + } + + @Test + public void writeText_null() { + TextPropertyImpl prop = new TextPropertyImpl(null); + + String actual = marshaller.writeText(prop); + + String expected = ""; + assertEquals(expected, actual); + } + + @Test + public void parseText() { + String value = "the\\;text"; + ICalParameters params = new ICalParameters(); + + Result result = marshaller.parseText(value, params); + + TextPropertyImpl prop = result.getValue(); + assertEquals("the;text", prop.getValue()); + assertWarnings(0, result.getWarnings()); + } + + @Test + public void writeXml() { + TextPropertyImpl prop = new TextPropertyImpl("text"); + + Document actual = xcalProperty(marshaller); + marshaller.writeXml(prop, XmlUtils.getRootElement(actual)); + + Document expected = xcalProperty(marshaller, "text"); + assertXMLEqual(expected, actual); + } + + @Test + public void writeXml_null() { + TextPropertyImpl prop = new TextPropertyImpl(null); + + Document actual = xcalProperty(marshaller); + marshaller.writeXml(prop, XmlUtils.getRootElement(actual)); + + Document expected = xcalProperty(marshaller, ""); + assertXMLEqual(expected, actual); + } + + @Test + public void writeXml_data_type() { + TextPropertyMarshallerImpl marshaller = new TextPropertyMarshallerImpl(Value.CAL_ADDRESS); + TextPropertyImpl prop = new TextPropertyImpl("mailto:johndoe@example.com"); + + Document actual = xcalProperty(marshaller); + marshaller.writeXml(prop, XmlUtils.getRootElement(actual)); + + Document expected = xcalProperty(marshaller, "mailto:johndoe@example.com"); + assertXMLEqual(expected, actual); + } + + @Test + public void parseXml() { + ICalParameters params = new ICalParameters(); + + Element element = xcalPropertyElement(marshaller, "text"); + Result result = marshaller.parseXml(element, params); + + TextPropertyImpl prop = result.getValue(); + assertEquals("text", prop.getValue()); + assertWarnings(0, result.getWarnings()); + } + + @Test + public void parseXml_data_type() { + TextPropertyMarshallerImpl marshaller = new TextPropertyMarshallerImpl(Value.CAL_ADDRESS); + ICalParameters params = new ICalParameters(); + + Element element = xcalPropertyElement(marshaller, "mailto:johndoe@example.com"); + Result result = marshaller.parseXml(element, params); + + TextPropertyImpl prop = result.getValue(); + assertEquals("mailto:johndoe@example.com", prop.getValue()); + assertWarnings(0, result.getWarnings()); + } + + private class TextPropertyMarshallerImpl extends TextPropertyMarshaller { + public TextPropertyMarshallerImpl() { + super(TextPropertyImpl.class, "TEXT"); + } + + public TextPropertyMarshallerImpl(Value dataType) { + super(TextPropertyImpl.class, "TEXT", dataType); + } + + @Override + protected TextPropertyImpl newInstance(String value) { + return new TextPropertyImpl(value); + } + } + + private class TextPropertyImpl extends TextProperty { + public TextPropertyImpl(String value) { + super(value); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getRootElement(actual)` could be null and is dereferenced by call to `writeXml(...)` at line 98. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TextPropertyMarshallerTest.writeXml_null() + +### Procedure Id: +biweekly.property.marshaller.TextPropertyMarshallerTest.writeXml_null():void.36c584607b182b381f61fed1d8a6658f + +### File: +src/test/java/biweekly/property/marshaller/TextPropertyMarshallerTest.java + +### Key: +TextPropertyMarshallerTest.java|writeXml_null|NULL_DEREFERENCE + +### Node Key: +d0ec784a9a07b2ee980cc56c82eecd21 + +### Hash: +6f20b9b5cc025658b75566e8a991dd94 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10685/instruction.md b/inferredbugs-10685/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..46c10dd93ccaf2b4d78ec9328382a4a08a94b80e --- /dev/null +++ b/inferredbugs-10685/instruction.md @@ -0,0 +1,791 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** biweekly +**Bug ID:** 30 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package biweekly.io.json; + +import static biweekly.util.TestUtils.assertWarnings; +import static biweekly.util.TestUtils.buildTimezone; +import static org.junit.Assert.assertEquals; + +import java.io.StringWriter; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.List; +import java.util.TimeZone; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import biweekly.ICalendar; +import biweekly.component.DaylightSavingsTime; +import biweekly.component.ICalComponent; +import biweekly.component.StandardTime; +import biweekly.component.VEvent; +import biweekly.component.VTimezone; +import biweekly.component.marshaller.ICalComponentMarshaller; +import biweekly.io.SkipMeException; +import biweekly.parameter.ICalParameters; +import biweekly.parameter.Value; +import biweekly.property.CalendarScale; +import biweekly.property.DateStart; +import biweekly.property.ICalProperty; +import biweekly.property.RawProperty; +import biweekly.property.RecurrenceDates; +import biweekly.property.RecurrenceRule; +import biweekly.property.RecurrenceRule.DayOfWeek; +import biweekly.property.RecurrenceRule.Frequency; +import biweekly.property.Version; +import biweekly.property.marshaller.ICalPropertyMarshaller; +import biweekly.util.Duration; +import biweekly.util.IOUtils; +import biweekly.util.Period; + +/* + Copyright (c) 2013, Michael Angstadt + 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 COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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. + */ + +/** + * @author Michael Angstadt + */ +public class JCalWriterTest { + private static TimeZone defaultTz; + private final DateFormat utcFormatter; + { + utcFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); + } + private final DateFormat usEasternFormatter; + { + usEasternFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + usEasternFormatter.setTimeZone(TimeZone.getTimeZone("US/Eastern")); + } + private final DateFormat localFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + private final DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd"); + + @BeforeClass + public static void beforeClass() { + //change the default timezone because my timezone is "US/Eastern", which is what the example jCal documents use + defaultTz = TimeZone.getDefault(); + TimeZone.setDefault(buildTimezone(1, 0)); + } + + @AfterClass + public static void afterClass() { + TimeZone.setDefault(defaultTz); + } + + @Test + public void basic() throws Throwable { + ICalendar ical = new ICalendar(); + ical.setProductId("prodid"); + + VEvent event = new VEvent(); + event.getProperties().clear(); + event.setSummary("summary"); + ical.addEvent(event); + + StringWriter sw = new StringWriter(); + JCalWriter writer = new JCalWriter(sw); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "[\"vcalendar\"," + + "[" + + "[\"version\",{},\"text\",\"2.0\"]," + + "[\"prodid\",{},\"text\",\"prodid\"]" + + "]," + + "[" + + "[\"vevent\"," + + "[" + + "[\"summary\",{},\"text\",\"summary\"]" + + "]," + + "[" + + "]" + + "]" + + "]" + + "]"; + //@formatter:on + String actual = sw.toString(); + assertEquals(expected, actual); + assertWarnings(0, writer.getWarnings()); + } + + @Test + public void write_multiple() throws Throwable { + ICalendar ical1 = new ICalendar(); + ical1.setProductId("prodid1"); + + VEvent event = new VEvent(); + event.getProperties().clear(); + event.setSummary("summary1"); + ical1.addEvent(event); + + ICalendar ical2 = new ICalendar(); + ical2.setProductId("prodid2"); + + event = new VEvent(); + event.getProperties().clear(); + event.setSummary("summary2"); + ical2.addEvent(event); + + StringWriter sw = new StringWriter(); + JCalWriter writer = new JCalWriter(sw, true); + writer.write(ical1); + writer.write(ical2); + writer.close(); + + //@formatter:off + String expected = + "[" + + "[\"vcalendar\"," + + "[" + + "[\"version\",{},\"text\",\"2.0\"]," + + "[\"prodid\",{},\"text\",\"prodid1\"]" + + "]," + + "[" + + "[\"vevent\"," + + "[" + + "[\"summary\",{},\"text\",\"summary1\"]" + + "]," + + "[" + + "]" + + "]" + + "]" + + "]," + + "[\"vcalendar\"," + + "[" + + "[\"version\",{},\"text\",\"2.0\"]," + + "[\"prodid\",{},\"text\",\"prodid2\"]" + + "]," + + "[" + + "[\"vevent\"," + + "[" + + "[\"summary\",{},\"text\",\"summary2\"]" + + "]," + + "[" + + "]" + + "]" + + "]" + + "]" + + "]"; + //@formatter:on + String actual = sw.toString(); + assertEquals(expected, actual); + } + + @Test + public void write_multiple_components() throws Throwable { + ICalendar ical = new ICalendar(); + ical.setProductId("prodid"); + + VEvent event = new VEvent(); + event.getProperties().clear(); + event.setSummary("summary1"); + ical.addEvent(event); + + event = new VEvent(); + event.getProperties().clear(); + event.setSummary("summary2"); + ical.addEvent(event); + + StringWriter sw = new StringWriter(); + JCalWriter writer = new JCalWriter(sw); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "[\"vcalendar\"," + + "[" + + "[\"version\",{},\"text\",\"2.0\"]," + + "[\"prodid\",{},\"text\",\"prodid\"]" + + "]," + + "[" + + "[\"vevent\"," + + "[" + + "[\"summary\",{},\"text\",\"summary1\"]" + + "]," + + "[" + + "]" + + "]," + + "[\"vevent\"," + + "[" + + "[\"summary\",{},\"text\",\"summary2\"]" + + "]," + + "[" + + "]" + + "]" + + "]" + + "]"; + //@formatter:on + String actual = sw.toString(); + assertEquals(expected, actual); + assertWarnings(0, writer.getWarnings()); + } + + @Test + public void write_empty() throws Throwable { + ICalendar ical = new ICalendar(); + ical.getProperties().clear(); + + StringWriter sw = new StringWriter(); + JCalWriter writer = new JCalWriter(sw); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "[\"vcalendar\"," + + "[" + + "]," + + "[" + + "]" + + "]"; + //@formatter:on + String actual = sw.toString(); + assertEquals(expected, actual); + assertWarnings(0, writer.getWarnings()); + } + + @Test + public void no_property_marshaller() throws Throwable { + ICalendar ical = new ICalendar(); + ical.setProductId("prodid"); + ical.addProperty(new TestProperty("value")); + + StringWriter sw = new StringWriter(); + JCalWriter writer = new JCalWriter(sw); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "[\"vcalendar\"," + + "[" + + "[\"version\",{},\"text\",\"2.0\"]," + + "[\"prodid\",{},\"text\",\"prodid\"]" + + "]," + + "[" + + "]" + + "]"; + //@formatter:on + String actual = sw.toString(); + assertEquals(expected, actual); + assertWarnings(1, writer.getWarnings()); + } + + @Test + public void no_component_marshaller() throws Throwable { + ICalendar ical = new ICalendar(); + ical.setProductId("prodid"); + ical.addComponent(new Party()); + + StringWriter sw = new StringWriter(); + JCalWriter writer = new JCalWriter(sw); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "[\"vcalendar\"," + + "[" + + "[\"version\",{},\"text\",\"2.0\"]," + + "[\"prodid\",{},\"text\",\"prodid\"]" + + "]," + + "[" + + "]" + + "]"; + //@formatter:on + String actual = sw.toString(); + assertEquals(expected, actual); + assertWarnings(1, writer.getWarnings()); + } + + @Test + public void skipMeException() throws Throwable { + ICalendar ical = new ICalendar(); + ical.setProductId("prodid"); + ical.addProperty(new TestProperty("value")); + + StringWriter sw = new StringWriter(); + JCalWriter writer = new JCalWriter(sw); + writer.registerMarshaller(new SkipMeMarshaller()); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "[\"vcalendar\"," + + "[" + + "[\"version\",{},\"text\",\"2.0\"]," + + "[\"prodid\",{},\"text\",\"prodid\"]" + + "]," + + "[" + + "]" + + "]"; + //@formatter:on + String actual = sw.toString(); + assertEquals(expected, actual); + assertWarnings(1, writer.getWarnings()); + } + + @Test + public void override_marshaller() throws Throwable { + ICalendar ical = new ICalendar(); + ical.setProductId("prodid"); + + StringWriter sw = new StringWriter(); + JCalWriter writer = new JCalWriter(sw); + writer.registerMarshaller(new MyVersionMarshaller()); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "[\"vcalendar\"," + + "[" + + "[\"version\",{},\"text\",\"2.0 (beta)\"]," + + "[\"prodid\",{},\"text\",\"prodid\"]" + + "]," + + "[" + + "]" + + "]"; + //@formatter:on + String actual = sw.toString(); + assertEquals(expected, actual); + assertWarnings(0, writer.getWarnings()); + } + + @Test + public void experimental_property() throws Throwable { + ICalendar ical = new ICalendar(); + ical.setProductId("prodid"); + ical.addExperimentalProperty("X-NUMBER", "1"); + RawProperty prop = ical.addExperimentalProperty("X-NUMBER", "2"); + prop.getParameters().setValue(Value.INTEGER); + + StringWriter sw = new StringWriter(); + JCalWriter writer = new JCalWriter(sw); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "[\"vcalendar\"," + + "[" + + "[\"version\",{},\"text\",\"2.0\"]," + + "[\"prodid\",{},\"text\",\"prodid\"]," + + "[\"x-number\",{},\"unknown\",\"1\"]," + + "[\"x-number\",{},\"integer\",\"2\"]" + + "]," + + "[" + + "]" + + "]"; + //@formatter:on + String actual = sw.toString(); + assertEquals(expected, actual); + assertWarnings(0, writer.getWarnings()); + } + + @Test + public void experimental_property_marshaller() throws Throwable { + ICalendar ical = new ICalendar(); + ical.setProductId("prodid"); + ical.addProperty(new TestProperty("one")); + ical.addProperty(new TestProperty("two")); + + StringWriter sw = new StringWriter(); + JCalWriter writer = new JCalWriter(sw); + writer.registerMarshaller(new TestPropertyMarshaller()); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "[\"vcalendar\"," + + "[" + + "[\"version\",{},\"text\",\"2.0\"]," + + "[\"prodid\",{},\"text\",\"prodid\"]," + + "[\"x-test\",{},\"text\",\"one\"]," + + "[\"x-test\",{},\"text\",\"two\"]" + + "]," + + "[" + + "]" + + "]"; + //@formatter:on + String actual = sw.toString(); + assertEquals(expected, actual); + assertWarnings(0, writer.getWarnings()); + } + + @Test + public void experimental_component() throws Throwable { + ICalendar ical = new ICalendar(); + ical.setProductId("prodid"); + ical.addExperimentalComponent("X-VPARTY"); + + StringWriter sw = new StringWriter(); + JCalWriter writer = new JCalWriter(sw); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "[\"vcalendar\"," + + "[" + + "[\"version\",{},\"text\",\"2.0\"]," + + "[\"prodid\",{},\"text\",\"prodid\"]" + + "]," + + "[" + + "[\"x-vparty\"," + + "[" + + "]," + + "[" + + "]" + + "]" + + "]" + + "]"; + //@formatter:on + String actual = sw.toString(); + assertEquals(expected, actual); + assertWarnings(0, writer.getWarnings()); + } + + @Test + public void experimental_component_marshaller() throws Throwable { + ICalendar ical = new ICalendar(); + ical.setProductId("prodid"); + ical.addComponent(new Party()); + + StringWriter sw = new StringWriter(); + JCalWriter writer = new JCalWriter(sw); + writer.registerMarshaller(new PartyMarshaller()); + writer.write(ical); + writer.close(); + + //@formatter:off + String expected = + "[\"vcalendar\"," + + "[" + + "[\"version\",{},\"text\",\"2.0\"]," + + "[\"prodid\",{},\"text\",\"prodid\"]" + + "]," + + "[" + + "[\"x-vparty\"," + + "[" + + "]," + + "[" + + "]" + + "]" + + "]" + + "]"; + //@formatter:on + String actual = sw.toString(); + assertEquals(expected, actual); + assertWarnings(0, writer.getWarnings()); + } + + @Test + public void jcal_draft_example1() throws Throwable { + //see: http://tools.ietf.org/html/draft-ietf-jcardcal-jcal-05#page-25 + //Note: all whitespace is removed from the expected JSON string it easier to compare it with the actual result + ICalendar ical = new ICalendar(); + ical.getProperties().clear(); + ical.setCalendarScale(CalendarScale.gregorian()); + ical.setProductId("-//ExampleInc.//ExampleCalendar//EN"); + ical.setVersion(Version.v2_0()); + { + VEvent event = new VEvent(); + event.getProperties().clear(); + event.setDateTimeStamp(utcFormatter.parse("2008-02-05T19:12:24")); + event.setDateStart(new DateStart(dateFormatter.parse("2008-10-06"), false)); + event.setSummary("Planningmeeting"); + event.setUid("4088E990AD89CB3DBB484909"); + ical.addEvent(event); + } + + assertWarnings(0, ical.validate()); + + StringWriter sw = new StringWriter(); + JCalWriter writer = new JCalWriter(sw); + writer.write(ical); + writer.close(); + + String expected = new String(IOUtils.toByteArray(getClass().getResourceAsStream("jcal-draft-example1.json"))); + expected = expected.replaceAll("\\s", ""); + String actual = sw.toString(); + assertEquals(expected, actual); + } + + @Test + public void jcal_draft_example2() throws Throwable { + //see: http://tools.ietf.org/html/draft-ietf-jcardcal-jcal-05#page-27 + //Note: all whitespace is removed from the expected JSON string it easier to compare it with the actual result + VTimezone usEasternTz; + ICalendar ical = new ICalendar(); + ical.getProperties().clear(); + ical.setProductId("-//ExampleCorp.//ExampleClient//EN"); + ical.setVersion(Version.v2_0()); + { + usEasternTz = new VTimezone(null); + usEasternTz.setLastModified(utcFormatter.parse("2004-01-10T03:28:45")); + usEasternTz.setTimezoneId("US/Eastern"); + { + DaylightSavingsTime daylight = new DaylightSavingsTime(); + daylight.setDateStart(localFormatter.parse("2000-04-04T02:00:00")).setLocalTime(true); + + RecurrenceRule rrule = new RecurrenceRule(Frequency.YEARLY); + rrule.addByDay(1, DayOfWeek.SUNDAY); + rrule.addByMonth(4); + daylight.setRecurrenceRule(rrule); + + daylight.addTimezoneName("EDT"); + daylight.setTimezoneOffsetFrom(-5, 0); + daylight.setTimezoneOffsetTo(-4, 0); + + usEasternTz.addDaylightSavingsTime(daylight); + } + { + StandardTime standard = new StandardTime(); + standard.setDateStart(localFormatter.parse("2000-10-26T02:00:00")).setLocalTime(true); + + RecurrenceRule rrule = new RecurrenceRule(Frequency.YEARLY); + rrule.addByDay(1, DayOfWeek.SUNDAY); + rrule.addByMonth(10); + standard.setRecurrenceRule(rrule); + + standard.addTimezoneName("EST"); + standard.setTimezoneOffsetFrom(-4, 0); + standard.setTimezoneOffsetTo(-5, 0); + + usEasternTz.addStandardTime(standard); + } + ical.addTimezone(usEasternTz); + } + { + VEvent event = new VEvent(); + event.setDateTimeStamp(utcFormatter.parse("2006-02-06T00:11:21")); + event.setDateStart(usEasternFormatter.parse("2006-01-02T12:00:00")).setTimezone(usEasternTz); + event.setDuration(new Duration.Builder().hours(1).build()); + + RecurrenceRule rrule = new RecurrenceRule(Frequency.DAILY); + rrule.setCount(5); + event.setRecurrenceRule(rrule); + + RecurrenceDates rdate = new RecurrenceDates(Arrays.asList(new Period(usEasternFormatter.parse("2006-01-02T15:00:00"), new Duration.Builder().hours(2).build()))); + rdate.setTimezone(usEasternTz); + event.addRecurrenceDates(rdate); + + event.setSummary("Event#2"); + event.setDescription("Wearehavingameetingallthisweekat12pmforonehour,withanadditionalmeetingonthefirstday2hourslong.\nPleasebringyourownlunchforthe12pmmeetings."); + event.setUid("00959BC664CA650E933C892C@example.com"); + ical.addEvent(event); + } + { + VEvent event = new VEvent(); + event.setDateTimeStamp(utcFormatter.parse("2006-02-06T00:11:21")); + event.setDateStart(usEasternFormatter.parse("2006-01-02T14:00:00")).setTimezone(usEasternTz); + event.setDuration(new Duration.Builder().hours(1).build()); + + event.setRecurrenceId(usEasternFormatter.parse("2006-01-04T12:00:00")).setTimezone(usEasternTz); + + event.setSummary("Event#2"); + event.setUid("00959BC664CA650E933C892C@example.com"); + ical.addEvent(event); + } + + assertWarnings(0, ical.validate()); + + StringWriter sw = new StringWriter(); + JCalWriter writer = new JCalWriter(sw); + writer.write(ical); + writer.close(); + + String expected = new String(IOUtils.toByteArray(getClass().getResourceAsStream("jcal-draft-example2.json"))); + expected = expected.replaceAll("\\s", ""); + String actual = sw.toString(); + assertEquals(expected, actual); + } + + private class TestProperty extends ICalProperty { + private String value; + + public TestProperty(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + } + + private class TestPropertyMarshaller extends ICalPropertyMarshaller { + public TestPropertyMarshaller() { + super(TestProperty.class, "X-TEST"); + } + + @Override + protected String _writeText(TestProperty property) { + return property.getValue(); + } + + @Override + protected TestProperty _parseText(String value, ICalParameters parameters, List warnings) { + return new TestProperty(value); + } + + @Override + protected JCalValue _writeJson(TestProperty property) { + return JCalValue.single(Value.TEXT, _writeText(property)); + } + } + + private class SkipMeMarshaller extends ICalPropertyMarshaller { + public SkipMeMarshaller() { + super(TestProperty.class, "NAME"); + } + + @Override + protected String _writeText(TestProperty property) { + throw new SkipMeException("Skipped"); + } + + @Override + protected TestProperty _parseText(String value, ICalParameters parameters, List warnings) { + return new TestProperty(value); + } + } + + private class MyVersionMarshaller extends ICalPropertyMarshaller { + public MyVersionMarshaller() { + super(Version.class, "VERSION"); + } + + @Override + protected String _writeText(Version property) { + return property.getMaxVersion() + " (beta)"; + } + + @Override + protected Version _parseText(String value, ICalParameters parameters, List warnings) { + return new Version(value); + } + + @Override + protected JCalValue _writeJson(Version property) { + return JCalValue.single(Value.TEXT, _writeText(property)); + } + } + + private class PartyMarshaller extends ICalComponentMarshaller { + public PartyMarshaller() { + super(Party.class, "X-VPARTY"); + } + + @Override + protected Party _newInstance() { + return new Party(); + } + } + + private class Party extends ICalComponent { + //empty + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `biweekly.io.json.JCalWriter` acquired to `writer` by call to `JCalWriter(...)` at line 532 is not released after line 540. +**Note**: potential exception at line 533 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JCalWriterTest.jcal_draft_example1() + +### Procedure Id: +biweekly.io.json.JCalWriterTest.jcal_draft_example1():void.e8dd9a85d3ab25d93f7868f5f62cbf48 + +### File: +src/test/java/biweekly/io/json/JCalWriterTest.java + +### Key: +JCalWriterTest.java|jcal_draft_example1|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +ca91ee1de5615af689e20e5b52c97599 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1071/instruction.md b/inferredbugs-1071/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9707203d492f7555478755cbea11ebe8a7e67032 --- /dev/null +++ b/inferredbugs-1071/instruction.md @@ -0,0 +1,373 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Nancy +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace Nancy.Tests.Unit +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using FakeItEasy; + using Nancy.Extensions; + using Nancy.Routing; + using Nancy.Tests.Fakes; + using Xunit; + using Xunit.Extensions; + + public class NancyEngineFixture + { + private readonly INancyEngine engine; + private readonly IRouteResolver resolver; + private readonly INancyModuleLocator locator; + private readonly IEnumerable modules; + + public NancyEngineFixture() + { + this.modules = new[] { new FakeNancyModuleWithBasePath() }; + this.locator = A.Fake(); + this.resolver = A.Fake(); + this.engine = new NancyEngine(this.locator, this.resolver); + } + + [Fact] + public void Should_throw_argumentnullexception_when_created_with_null_locator() + { + // Given, When + var exception = + Record.Exception(() => new NancyEngine(null, A.Fake())); + + // Then + exception.ShouldBeOfType(); + } + + [Fact] + public void Should_throw_argumentnullexception_when_created_with_null_resolver() + { + // Given, When + var exception = + Record.Exception(() => new NancyEngine(A.Fake(), null)); + + // Then + exception.ShouldBeOfType(); + } + + [Fact] + public void Should_retrieve_modules_from_locator_when_handling_request() + { + // Given + var request = new Request("GET", "/", new Dictionary>(), new MemoryStream()); + + // When + this.engine.HandleRequest(request); + + // Then + A.CallTo(() => this.locator.GetModules()).MustHaveHappened(); + } + + [Fact] + public void Should_return_not_found_response_when_no_nancy_modules_could_be_found() + { + // Given + var request = new Request("GET", "/", new Dictionary>(), new MemoryStream()); + + A.CallTo(() => this.locator.GetModules()).Returns(Enumerable.Empty()); + + // When + var response = this.engine.HandleRequest(request); + + // Then + response.StatusCode.ShouldEqual(HttpStatusCode.NotFound); + } + + [Fact] + public void Should_pass_all_registered_route_handlers_for_get_request_to_route_resolver() + { + // Given + var request = new Request("GET", "/", new Dictionary>(), new MemoryStream()); + var descriptions = GetRouteDescriptions(request, this.modules); + + A.CallTo(() => this.locator.GetModules()).Returns(modules); + + // When + this.engine.HandleRequest(request); + + // Then + A.CallTo(() => this.resolver.GetRoute(A.Ignored.Argument, + A>.That.Matches(x => x.SequenceEqual(descriptions)).Argument)).MustHaveHappened(); + } + + [Theory] + [InlineData("get")] + [InlineData("GeT")] + [InlineData("PoSt")] + [InlineData("post")] + [InlineData("puT")] + [InlineData("PUT")] + [InlineData("DelETe")] + [InlineData("DELete")] + public void Should_ignore_case_of_request_verb_when_resolving_route_handlers(string verb) + { + // Given + var request = new Request(verb, "/", new Dictionary>(), new MemoryStream()); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + // When + this.engine.HandleRequest(request); + + // Then + A.CallTo(() => this.resolver.GetRoute(A.Ignored.Argument, + A>.Ignored.Argument)).MustHaveHappened(); + } + + [Fact] + public void Should_pass_all_registered_route_handlers_for_delete_request_to_route_resolver() + { + // Given + var request = new Request("DELETE", "/", new Dictionary>(), new MemoryStream()); + var descriptions = GetRouteDescriptions(request, this.modules); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + // When + this.engine.HandleRequest(request); + + // Then + A.CallTo(() => this.resolver.GetRoute(A.Ignored.Argument, A>.That.Matches(x => x.SequenceEqual(descriptions)).Argument)).MustHaveHappened(); + } + + [Fact] + public void Should_call_route_resolver_with_all_route_handlers() + { + // Given + var request = new Request("PUT", "/", new Dictionary>(), new MemoryStream()); + var descriptions = GetRouteDescriptions(request, this.modules); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + A.CallTo(() => this.resolver.GetRoute(request, descriptions)).Returns(null); + + // When + this.engine.HandleRequest(request); + + // Then + A.CallTo(() => this.resolver.GetRoute(A.Ignored.Argument, A>.That.Matches(x => x.SequenceEqual(descriptions)).Argument)).MustHaveHappened(); + } + + [Fact] + public void Should_call_route_resolver_with_request() + { + // Given + var request = new Request("GET", "/", new Dictionary>(), new MemoryStream()); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + // When + this.engine.HandleRequest(request); + + // Then + A.CallTo(() => this.resolver.GetRoute(request, + A>.Ignored.Argument)).MustHaveHappened(); + } + + [Fact] + public void Should_return_not_found_response_when_no_route_could_be_matched_for_the_request_verb() + { + // Given + var request = new Request("NOTVALID", "/", new Dictionary>(), new MemoryStream()); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + // When + var response = this.engine.HandleRequest(request); + + // Then + response.StatusCode.ShouldEqual(HttpStatusCode.NotFound); + } + + [Fact] + public void Should_throw_argumentnullexception_when_handling_null_request() + { + // Given, When + var exception = + Record.Exception(() => this.engine.HandleRequest(null)); + + // Then + exception.ShouldBeOfType(); + } + + [Fact] + public void Should_invoke_resolved_route() + { + // Given + var route = A.Fake(); + var request = new Request("GET", "/", new Dictionary>(), new MemoryStream()); + var descriptions = GetRouteDescriptions(request, this.modules); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + A.CallTo(() => this.resolver.GetRoute(request, A>.That.Matches(x => x.SequenceEqual(descriptions)).Argument)).Returns(route); + + // When + this.engine.HandleRequest(request); + + // Then + A.CallTo(() => route.Invoke()).MustHaveHappened(); + } + + [Fact] + public void Should_return_response_generated_by_route() + { + // Given + var expectedResponse = new Response(); + var route = A.Fake(); + var request = new Request("GET", "/", new Dictionary>(), new MemoryStream()); + var descriptions = GetRouteDescriptions(request, this.modules); + + A.CallTo(() => route.Invoke()).Returns(expectedResponse); + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + A.CallTo(() => this.resolver.GetRoute(request, A>.That.Matches(x => x.SequenceEqual(descriptions)).Argument)).Returns(route); + + // When + var response = this.engine.HandleRequest(request); + + // Then + response.ShouldBeSameAs(expectedResponse); + } + + [Fact] + public void Should_set_base_route_on_descriptions_that_are_passed_to_resolver() + { + // Given + var request = new Request("POST", "/", new Dictionary>(), new MemoryStream()); + + var r = new FakeRouteResolver(); + var e = new NancyEngine(this.locator, r); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + // When + e.HandleRequest(request); + + // Then + r.ModulePath.ShouldEqual("/fake"); + } + + [Fact] + public void Should_set_path_on_descriptions_that_are_passed_to_resolver() + { + // Given + var request = new Request("POST", "/", new Dictionary>(), new MemoryStream()); + + var r = new FakeRouteResolver(); + var e = new NancyEngine(this.locator, r); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + // When + e.HandleRequest(request); + + // Then + r.Path.ShouldEqual("/"); + } + + [Fact] + public void Should_set_action_on_descriptions_that_are_passed_to_resolver() + { + // Given + var request = new Request("POST", "/", new Dictionary>(), new MemoryStream()); + + var r = new FakeRouteResolver(); + var e = new NancyEngine(this.locator, r); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + var expectedAction = + (new FakeNancyModuleWithBasePath()).Post["/"]; + + // When + e.HandleRequest(request); + + // Then + r.Action.ShouldBeSameAs(expectedAction); + } + + [Fact] + public void Should_set_request_property_of_loaded_modules() + { + // Given + var request = new Request("GET", "/", new Dictionary>(), new MemoryStream()); + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + // When + this.engine.HandleRequest(request); + + // Then + this.modules.First().Request.ShouldNotBeNull(); + } + + private static IEnumerable GetRouteDescriptions(IRequest request, IEnumerable modules) + { + return modules.SelectMany(x => x.GetRouteDescription(request)); + } + + private static IRequest ManufactureGETRequest(string route) + { + return new Request("GET", route, new Dictionary>(), new MemoryStream()); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource request of type Nancy.Request, Leaked resource (output of System.IO.MemoryStream::.ctor() at Line 295) of type System.IO.MemoryStream in method "Void NancyEngineFixture.Should_set_request_property_of_loaded_modules()". + +### Severity: +ERROR + +### Procedure: +Void NancyEngineFixture.Should_set_request_property_of_loaded_modules() + +### File: +src/Nancy.Tests/Unit/NancyEngineFixture.cs + +### Key: +NancyEngineFixture.cs|Should_set_request_property_of_loaded_modules|DOTNET_RESOURCE_LEAK + +### Hash: +8b8bdebda635261b73cbc332400b34a1 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10757/instruction.md b/inferredbugs-10757/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d7ea5ee04858bb4f042c4c6c5b7373ed3ecd113b --- /dev/null +++ b/inferredbugs-10757/instruction.md @@ -0,0 +1,181 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** docker-maven-plugin +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.jolokia.docker.maven.service; + +import org.apache.maven.execution.MavenSession; +import org.apache.maven.plugin.BuildPluginManager; +import org.apache.maven.project.MavenProject; +import org.jolokia.docker.maven.access.DockerAccess; +import org.jolokia.docker.maven.assembly.DockerAssemblyManager; +import org.jolokia.docker.maven.log.LogOutputSpecFactory; +import org.jolokia.docker.maven.util.Logger; + +/** + * A service hub responsible for creating and managing service which are used by + * Mojos for calling to the docker backend. The docker backend (DAO) is injected from the outside. + */ +public class ServiceHub { + + // Track started containers + private final ContainerTracker containerTracker = new ContainerTracker(); + + /** @component **/ + protected BuildPluginManager pluginManager; + + /** @component */ + protected DockerAssemblyManager dockerAssemblyManager; + + /** @component */ + protected MavenProject project; + + /** @component */ + protected MavenSession session; + + // Services managed by this hub + private MojoExecutionService mojoExecutionService; + private QueryService queryService; + private RunService runService; + private LogOutputSpecFactory logOutputSpecFactory; + + private BuildService buildService; + // initialization flag preventing multiple initializations + private boolean initDone = false; + + /** + * Lifecycle method called early in order to build up the services. It can be called multiple + * times but will run only once. + * + * @param dockerAccess the docker access object + * @param log logger to use + */ + public synchronized void init(DockerAccess dockerAccess, Logger log, LogOutputSpecFactory logOutputSpecFactory) { + if (!initDone) { + this.logOutputSpecFactory = logOutputSpecFactory; + mojoExecutionService = new MojoExecutionService(project, session, pluginManager); + queryService = new QueryService(dockerAccess, log); + runService = new RunService(dockerAccess, queryService, containerTracker, logOutputSpecFactory, log); + buildService = new BuildService(dockerAccess, queryService, dockerAssemblyManager, log); + initDone = true; + } + } + + /** + * Get a service for executing goals on other Maven mojos + * + * @return service for calling other mojos + */ + public MojoExecutionService getMojoExecutionService() { + checkInitialization(); + return mojoExecutionService; + } + + public BuildService getBuildService() { + checkInitialization(); + return buildService; + } + + /** + * Get the query service for obtaining information about containers and images + * + * @return query service + */ + public QueryService getQueryService() { + checkInitialization(); + return queryService; + } + + /** + * The run service is responsible for creating and starting up containers + * + * @return the run service + */ + public RunService getRunService() { + checkInitialization(); + return runService; + } + + // =========================================================== + + private synchronized void checkInitialization() { + if (!initDone) { + throw new IllegalStateException("Service hub not yet initialized"); + } + } + + public LogOutputSpecFactory getLogOutputSpecFactory() { + return logOutputSpecFactory; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.jolokia.docker.maven.service.ServiceHub.getQueryService` reads without synchronization from `this.org.jolokia.docker.maven.service.ServiceHub.queryService`. Potentially races with write in method `ServiceHub.init(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +QueryService ServiceHub.getQueryService() + +### Procedure Id: +org.jolokia.docker.maven.service.ServiceHub.getQueryService():org.jolokia.docker.maven.service.Query.20f2dc7282f79dd878bbc21c3d4c3dd2 + +### File: +src/main/java/org/jolokia/docker/maven/service/ServiceHub.java + +### Key: +ServiceHub.java|getQueryService|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +805a36fde236cac30a3c8d401a122fac + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10759/instruction.md b/inferredbugs-10759/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..db88f50793148f3172ba008af6668150235d79a7 --- /dev/null +++ b/inferredbugs-10759/instruction.md @@ -0,0 +1,623 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** docker-maven-plugin +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.jolokia.docker.maven.access; + +import java.io.*; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.mashape.unirest.http.*; +import com.mashape.unirest.http.exceptions.UnirestException; +import com.mashape.unirest.http.options.Options; +import com.mashape.unirest.http.utils.ClientFactory; +import com.mashape.unirest.http.utils.URLParamEncoder; +import com.mashape.unirest.request.BaseRequest; +import com.mashape.unirest.request.HttpRequest; +import com.mashape.unirest.request.body.Body; +import org.apache.http.HttpEntity; +import org.apache.http.StatusLine; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIUtils; +import org.apache.http.entity.FileEntity; +import org.apache.maven.plugin.MojoExecutionException; +import org.jolokia.docker.maven.util.*; +import org.json.*; + +/** + * Implementation for a DockerAccess based on the Unirest + * REST access library. + * + * @author roland + * @since 26.03.14 + */ +public class DockerAccessUnirest implements DockerAccess { + + // Used Docker API + private final static String DOCKER_API_VERSION = "v1.10"; + + // Logging + private final LogHandler log; + + // Base Docker URL + private final String url; + + /** + * Create a new access for the given URL + * + * @param url base URL for accessing the docker Daemon + * @param log a log handler for printing out logging information + */ + public DockerAccessUnirest(String url, LogHandler log) { + this.url = stripSlash(url) + "/" + DOCKER_API_VERSION; + this.log = log; + Unirest.setDefaultHeader("accept", "application/json"); + } + + /** {@inheritDoc} */ + public boolean hasImage(String image) throws MojoExecutionException { + try { + Matcher matcher = Pattern.compile("^(.*?):([^:]+)?$").matcher(image); + String base, tag; + if (matcher.matches()) { + base = matcher.group(1); + tag = matcher.group(2); + } else { + base = image; + } + BaseRequest req = Unirest.get(url + "/images/json?filter={image}") + .routeParam("image", base); + HttpResponse resp = request(req); + checkReturnCode("Checking for image '" + image + "'", resp, 200); + JSONArray array = new JSONArray(resp.getBody()); + return array.length() > 0; + } catch (UnirestException e) { + throw new MojoExecutionException("Cannot list images for '" + image + "'", e); + } + } + + /** {@inheritDoc} */ + public String createContainer(String image, Set ports, String command, Map env) throws MojoExecutionException { + try { + BaseRequest req = Unirest.post(url + "/containers/create") + .header("Accept", "*/*") + .header("Content-Type", "application/json") + .body(getContainerConfig(image, ports, command, env)); + HttpResponse resp = request(req); + checkReturnCode("Creating container for image '" + image + "'", resp, 201); + JSONObject json = new JSONObject(resp.getBody()); + logWarnings(json); + return json.getString("Id"); + } catch (UnirestException e) { + throw new MojoExecutionException("Cannot create container for '" + image + "'", e); + } + } + + /** {@inheritDoc} */ + public void startContainer(String containerId, Map ports, String volumesFrom) throws MojoExecutionException { + try { + BaseRequest req = Unirest.post(url + "/containers/{id}/start") + .header("Accept", "*/*") + .header("Content-Type", "application/json") + .routeParam("id", containerId) + .body(getStartConfig(ports, volumesFrom)); + HttpResponse resp = request(req); + checkReturnCode("Starting container with id " + containerId, resp, 204); + } catch (UnirestException e) { + throw new MojoExecutionException("Cannot start container " + containerId, e); + } + } + + /** {@inheritDoc} */ + public void stopContainer(String containerId) throws MojoExecutionException { + try { + BaseRequest req = Unirest.post(url + "/containers/{id}/stop") + .header("Accept", "*/*") + .routeParam("id", containerId); + HttpResponse resp = request(req); + checkReturnCode("Stopping container with id " + containerId, resp, 204); + + } catch (UnirestException e) { + throw new MojoExecutionException("Cannot stop container " + containerId, e); + } + } + + /** {@inheritDoc} */ + public Map queryContainerPortMapping(String containerId) throws MojoExecutionException { + try { + BaseRequest req = Unirest.get(url + "/containers/{id}/json") + .header("Accept", "*/*") + .routeParam("id", containerId); + HttpResponse resp = request(req); + checkReturnCode("Getting container information for " + containerId, resp, 200); + return extractPorts(new JSONObject(resp.getBody())); + } catch (UnirestException e) { + throw new MojoExecutionException("Cannot fetch information for container " + containerId, e); + } + } + + /** {@inheritDoc} */ + private Map extractPorts(JSONObject info) { + Map ret = new HashMap(); + + JSONObject networkSettings = info.getJSONObject("NetworkSettings"); + if (networkSettings != null) { + JSONObject ports = networkSettings.getJSONObject("Ports"); + if (ports != null) { + for (Object portSpecO : ports.keySet()) { + String portSpec = portSpecO.toString(); + if (!ports.isNull(portSpec)) { + JSONArray hostSpecs = ports.getJSONArray(portSpec); + if (hostSpecs != null && hostSpecs.length() > 0) { + // We take only the first + JSONObject hostSpec = hostSpecs.getJSONObject(0); + Object hostPortO = hostSpec.get("HostPort"); + if (hostPortO != null) { + try { + Integer hostPort = (Integer.parseInt(hostPortO.toString())); + int idx = portSpec.indexOf('/'); + String p = idx > 0 ? portSpec.substring(0, idx) : portSpec; + Integer containerPort = Integer.parseInt(p); + ret.put(containerPort, hostPort); + } catch (NumberFormatException exp) { + log.warn("Cannot parse " + hostPortO + " or " + portSpec + " as a port number. Ignoring in mapping"); + } + } + } + } + } + } + } + return ret; + } + + /** {@inheritDoc} */ + public List getContainersForImage(String image) throws MojoExecutionException { + try { + List ret = new ArrayList(); + BaseRequest req = Unirest.get(url + "/containers/json?limit=100") + .header("Accept", "*/*"); + HttpResponse resp = null; + resp = request(req); + checkReturnCode("Fetching container information", resp, 200); + JSONArray configs = new JSONArray(resp.getBody()); + for (int i = 0; i < configs.length(); i ++) { + JSONObject config = configs.getJSONObject(i); + String containerImage = config.getString("Image"); + + if (image.equals(containerImage)) { + ret.add(config.getString("Id")); + } + } + return ret; + } catch (UnirestException e) { + throw new MojoExecutionException("Cannot get container information", e); + } + } + + /** {@inheritDoc} */ + public void removeContainer(String containerId) throws MojoExecutionException { + try { + BaseRequest req = Unirest.delete(url + "/containers/{id}") + .header("Accept", "*/*") + .routeParam("id", containerId); + HttpResponse resp = request(req); + checkReturnCode("Stopping container with id " + containerId, resp, 204); + + } catch (UnirestException e) { + throw new MojoExecutionException("Cannot remove container " + containerId, e); + } + } + + /** {@inheritDoc} */ + public void pullImage(String image,AuthConfig authConfig) throws MojoExecutionException { + ImageName name = new ImageName(image); + String pullUrl = url + "/images/create?fromImage=" + URLParamEncoder.encode(name.getRepository()); + pullUrl = addTagAndRegistry(pullUrl, name); + pullOrPushImage(image,pullUrl,"pulling",authConfig); + } + + /** {@inheritDoc} */ + public void pushImage(String image, AuthConfig authConfig) throws MojoExecutionException { + ImageName name = new ImageName(image); + String pushUrl = url + "/images/" + URLParamEncoder.encode(name.getRepository()) + "/push"; + pushUrl = addTagAndRegistry(pushUrl,name); + pullOrPushImage(image,pushUrl,"pushing",authConfig); + } + + private void pullOrPushImage(String image, String uriString, String what, AuthConfig authConfig) + throws MojoExecutionException { + try { + HttpClient client = ClientFactory.getHttpClient(); + URI uri = new URI(uriString); + HttpPost post = new HttpPost(uri); + if (authConfig != null) { + post.addHeader("X-Registry-Auth",authConfig.toHeaderValue()); + } + + processPullOrPushResponse(image, client.execute(URIUtils.extractHost(uri), post), what); + } catch (IOException | URISyntaxException e) { + throw new MojoExecutionException("Error while " + what + " " + image + ": ",e); + } + } + + private String addTagAndRegistry(String url, ImageName name) { + List params = new ArrayList<>(); + if (name.getTag() != null) { + params.add("tag=" + name.getTag()); + } + if (name.getRegistry() != null) { + params.add("registry=" + name.getRegistry()); + } + if (params.size() > 0) { + StringBuilder addOn = new StringBuilder(); + + for (int i = 0; i < params.size(); i ++) { + addOn.append(params.get(i)); + if (i < params.size() - 1) { + addOn.append("&"); + } + } + return url + (url.contains("?") ? "&" : "?") + addOn.toString(); + } else { + return url; + } + } + + /** {@inheritDoc} */ + public void removeImage(String image) throws MojoExecutionException { + try { + BaseRequest req = Unirest.delete(url + "/images/{id}") + .header("Accept", "*/*") + .routeParam("id", image); + + HttpResponse resp = request(req); + checkReturnCode("Removing image " + image, resp, 200); + if (log.isDebugEnabled()) { + logRemoveResponse(resp.getBody()); + } + } catch (UnirestException e) { + throw new MojoExecutionException("Cannot remove image " + image,e); + } + } + + /** {@inheritDoc} */ + public void start() { + Options.refresh(); + } + + /** {@inheritDoc} */ + public void shutdown() { + try { + Unirest.shutdown(); + } catch (IOException e) { + log.warn("Couldnt properly shutdown rest interface: " + e); + } + } + + /** {@inheritDoc} */ + public void buildImage(String image, File dockerArchive) throws MojoExecutionException { + try { + HttpClient client = ClientFactory.getHttpClient(); + URI buildUrl = new URI(url + "/build?rm=true" + (image != null ? "&t=" + URLParamEncoder.encode(image) : "")); + HttpPost post = new HttpPost(buildUrl); + post.setEntity(new FileEntity(dockerArchive)); + processBuildResponse(image, client.execute(URIUtils.extractHost(buildUrl), post)); + } catch (IOException e) { + throw new MojoExecutionException("Cannot build image " + image + " from " + dockerArchive,e); + } catch (URISyntaxException e) { + throw new MojoExecutionException("Cannot build image " + image + " from " + dockerArchive,e); + } + } + + // =========================================================================================================== + + private HttpResponse request(BaseRequest req) throws UnirestException { + if (log.isDebugEnabled()) { + dump(req); + } + HttpResponse resp = req.asString(); + if (log.isDebugEnabled()) { + dump(resp); + } + return resp; + } + + private String getContainerConfig(String image, Set ports, String command, Map env) { + JSONObject ret = new JSONObject(); + ret.put("Image",image); + if (ports != null && ports.size() > 0) { + JSONObject exposedPorts = new JSONObject(); + for (Integer port : ports) { + exposedPorts.put(port.toString() + "/tcp", new JSONObject()); + } + ret.put("ExposedPorts", exposedPorts); + } + if (command != null) { + JSONArray a = new JSONArray(); + for (String s : command.split("\\s+")) { + a.put(s); + } + ret.put("Cmd",a); + } + if (env != null && env.size() > 0) { + JSONArray a = new JSONArray(); + for (Map.Entry entry : env.entrySet()) { + a.put(entry.getKey() + "=" + entry.getValue()); + } + ret.put("Env",a); + } + log.debug("Container create config: " + ret.toString()); + return ret.toString(); + } + + private String getStartConfig(Map ports, String volumesFrom) { + JSONObject ret = new JSONObject(); + if (ports != null && ports.size() > 0) { + JSONObject c = new JSONObject(); + for (Integer containerPort : ports.keySet()) { + Integer port = ports.get(containerPort); + JSONArray a = new JSONArray(); + JSONObject o = new JSONObject(); + o.put("HostPort",port != null ? port.toString() : ""); + a.put(o); + c.put(containerPort + "/tcp",a); + } + ret.put("PortBindings", c); + } + if (volumesFrom != null) { + JSONArray a = new JSONArray(); + a.put(volumesFrom); + ret.put("VolumesFrom", a); + } + log.debug("Container start config: " + ret.toString()); + return ret.toString(); + } + + // ====================================================================================================== + + private void dump(HttpResponse resp) { + String body = resp.getBody(); + log.debug("<<<< " + (body != null ? body : "[empty]")); + } + + private void dump(BaseRequest req) { + HttpRequest hReq = req.getHttpRequest(); + log.debug(">>>> " + hReq.getUrl()); + Map> headers = hReq.getHeaders(); + if (headers != null) { + for (String h : headers.keySet()) { + log.debug("|||| " + h + "=" + headers.get(h)); + } + } + if (hReq.getHttpMethod() == HttpMethod.POST) { + Body body = hReq.getBody(); + log.debug("---- " + (body != null ? convert(body.getEntity()) : "[empty]")); + } + } + + private String convert(HttpEntity entity) { + try { + if (entity.isStreaming()) { + return entity.toString(); + } + InputStreamReader is = new InputStreamReader(entity.getContent()); + StringBuilder sb = new StringBuilder(); + BufferedReader br = new BufferedReader(is); + String read = br.readLine(); + + while (read != null) { + //System.out.println(read); + sb.append(read); + read = br.readLine(); + } + return sb.toString(); + } catch (IOException e) { + return "[error serializing inputstream for debugging]"; + } + } + private void processPullOrPushResponse(final String image, org.apache.http.HttpResponse resp, final String action) throws IOException, MojoExecutionException { + processChunkedResponse(resp, new ChunkedCallback() { + + private boolean downloadInProgress = false; + + public void process(JSONObject json) { + if (json.has("progressDetail")) { + JSONObject details = json.getJSONObject("progressDetail"); + if (details.has("total")) { + if (!downloadInProgress) { + log.progressStart(details.getInt("total")); + } + log.progressUpdate(details.getInt("current")); + downloadInProgress = true; + return; + } else { + if (downloadInProgress) { + log.progressFinished(); + } + downloadInProgress = false; + } + } + if (json.has("error")) { + String msg = json.getString("error").trim(); + String details = json.getJSONObject("errorDetail").getString("message").trim(); + log.error("!!! " + msg + (msg.equals(details) ? "" : "(" + details + ")")); + } else { + log.info("... " + (json.has("id") ? json.getString("id") + ": " : "") + json.getString("status")); + } + } + + public String getErrorMessage(StatusLine status) { + return "Error while " + action + " image '" + image + "' (code: " + status.getStatusCode() + ", " + status.getReasonPhrase() + ")"; + } + }); + } + + private void processBuildResponse(final String image, org.apache.http.HttpResponse resp) throws IOException, MojoExecutionException { + + processChunkedResponse(resp, new ChunkedCallback() { + public void process(JSONObject json) { + if (json.has("error")) { + log.error("Error building image: " + json.get("error")); + if (json.has("errorDetail")) { + JSONObject details = json.getJSONObject("errorDetail"); + log.error(details.getString("message")); + } + } else if (json.has("stream")) { + String message = json.getString("stream"); + while (message.endsWith("\n")) { + message = message.substring(0,message.length() - 1); + } + log.debug(message); + } + } + + public String getErrorMessage(StatusLine status) { + return "Error while building image '" + image + "' (code: " + status.getStatusCode() + + ", " + status.getReasonPhrase() + ")"; + } + }); + + } + + private void processChunkedResponse(org.apache.http.HttpResponse resp, ChunkedCallback cb) throws IOException, MojoExecutionException { + InputStream is = resp.getEntity().getContent(); + int len; + int size = 8129; + byte[] buf = new byte[size]; + // Data comes in chunkwise + while ((len = is.read(buf, 0, size)) != -1) { + String txt = new String(buf,0,len); + try { + JSONObject json = new JSONObject(txt); + cb.process(json); + } catch (JSONException exp) { + log.warn("Couldn't parse answer chunk '" + txt + "': " + exp); + } + } + StatusLine status = resp.getStatusLine(); + if (status.getStatusCode() != 200) { + throw new MojoExecutionException(cb.getErrorMessage(status)); + } + } + + private void logWarnings(JSONObject body) { + Object warningsObj = body.get("Warnings"); + if (warningsObj != JSONObject.NULL) { + JSONArray warnings = (JSONArray) warningsObj; + for (int i = 0; i < warnings.length(); i++) { + log.warn(warnings.getString(i)); + } + } + } + + private void checkReturnCode(String msg, HttpResponse resp, int expectedCode) throws MojoExecutionException { + if (resp.getCode() != expectedCode) { + throw new MojoExecutionException("Error while calling docker: " + msg + " (code: " + resp.getCode() + ", " + + resp.getBody().toString().trim() + ")"); + + } + } + + private String stripSlash(String url) { + String ret = url; + while (ret.endsWith("/")) { + ret = ret.substring(0, ret.length() - 1); + } + return ret; + } + + // Callback for processing response chunks + private void logRemoveResponse(String pResp) { + JSONArray logElements = new JSONArray(pResp); + for (int i = 0; i < logElements.length(); i++) { + JSONObject entry = logElements.getJSONObject(i); + for (Object key : entry.keySet()) { + log.debug(key + ": " + entry.get(key.toString())); + } + } + } + + // ================================================================================================ + + private interface ChunkedCallback { + public void process(JSONObject json); + String getErrorMessage(StatusLine status); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 405 is not released after line 416. +**Note**: potential exception at line 408 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String DockerAccessUnirest.convert(HttpEntity) + +### Procedure Id: +org.jolokia.docker.maven.access.DockerAccessUnirest.convert(org.apache.http.HttpEntity):java.lang.St.e3cff1698da7986436ea117106b16669 + +### File: +src/main/java/org/jolokia/docker/maven/access/DockerAccessUnirest.java + +### Key: +DockerAccessUnirest.java|convert|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +c803f9571f9f649bbc583774949fb3a3 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1076/instruction.md b/inferredbugs-1076/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..85b08cc3cff192e2791f1b9939f4cb41493882c4 --- /dev/null +++ b/inferredbugs-1076/instruction.md @@ -0,0 +1,101 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Nancy +**Bug ID:** 13 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace Nancy.Tests.Specifications +{ + using System.Collections.Generic; + using System.IO; + using Nancy.Routing; + + public abstract class RequestSpec + { + protected static INancyEngine engine; + protected static IRequest request; + protected static Response response; + + protected RequestSpec() + { + engine = new NancyEngine(new AppDomainModuleLocator(), new RouteResolver()); + } + + protected static IRequest ManufactureGETRequestForRoute(string route) + { + return new Request("GET", route, new Dictionary>(), new MemoryStream()); + } + + protected static IRequest ManufacturePOSTRequestForRoute(string route) + { + return new Request("POST", route, new Dictionary>(), new MemoryStream()); + } + + protected static IRequest ManufactureDELETERequestForRoute(string route) + { + return new Request("DELETE", route, new Dictionary>(), new MemoryStream()); + } + + protected static IRequest ManufacturePUTRequestForRoute(string route) + { + return new Request("PUT", route, new Dictionary>(), new MemoryStream()); + } + + protected static IRequest ManufactureHEADRequestForRoute(string route) + { + return new Request("HEAD", route, new Dictionary>(), new MemoryStream()); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type Nancy.Request, Leaked resource (output of System.IO.MemoryStream::.ctor() at Line 35) of type System.IO.MemoryStream in method "IRequest RequestSpec.ManufacturePUTRequestForRoute(String)". + +### Severity: +ERROR + +### Procedure: +IRequest RequestSpec.ManufacturePUTRequestForRoute(String) + +### File: +src/Nancy.Tests/Specifications/RequestSpec.cs + +### Key: +RequestSpec.cs|ManufacturePUTRequestForRoute|DOTNET_RESOURCE_LEAK + +### Hash: +694ab89718f2b30be68d25480cd9d610 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10761/instruction.md b/inferredbugs-10761/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c974aeb9b47056bde57cf76e0421617807861e12 --- /dev/null +++ b/inferredbugs-10761/instruction.md @@ -0,0 +1,133 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** docker-maven-plugin +**Bug ID:** 19 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package io.fabric8.maven.docker.log;/* + * + * Copyright 2014 Roland Huss + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.FileNotFoundException; +import java.util.*; + +import io.fabric8.maven.docker.access.DockerAccess; +import io.fabric8.maven.docker.access.log.LogGetHandle; + +/** + * @author roland + * @since 25/11/14 + */ +public class LogDispatcher { + + private Map logHandles; + + private DockerAccess dockerAccess; + + public LogDispatcher(DockerAccess dockerAccess) { + this.dockerAccess = dockerAccess; + logHandles = new HashMap<>(); + } + + public synchronized void trackContainerLog(String containerId, LogOutputSpec spec) throws FileNotFoundException { + LogGetHandle handle = dockerAccess.getLogAsync(containerId, new DefaultLogCallback(spec)); + logHandles.put(containerId, handle); + } + + public synchronized void fetchContainerLog(String containerId, LogOutputSpec spec) throws FileNotFoundException { + dockerAccess.getLogSync(containerId, new DefaultLogCallback(spec)); + } + + public synchronized void untrackAllContainerLogs() { + for (String key : logHandles.keySet()) { + LogGetHandle handle = logHandles.get(key); + handle.finish(); + } + logHandles.clear(); + } + + // ======================================================================================= + + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PrintStream` acquired by call to `DefaultLogCallback(...)` at line 40 is not released after line 40. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void LogDispatcher.trackContainerLog(String,LogOutputSpec) + +### Procedure Id: +io.fabric8.maven.docker.log.LogDispatcher.trackContainerLog(java.lang.String,io.fabric8.maven.docker.655d9639a21e6f74650a64d9dbcbbad8 + +### File: +src/main/java/io/fabric8/maven/docker/log/LogDispatcher.java + +### Key: +LogDispatcher.java|trackContainerLog|RESOURCE_LEAK + +### Node Key: +4e7de1e5fcafaa5a87717af4c7942de7 + +### Hash: +53182f7f8ca315f03dac56d744fca274 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10766/instruction.md b/inferredbugs-10766/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9f9e949909d09c71ad57a61f610f9862de2b1b40 --- /dev/null +++ b/inferredbugs-10766/instruction.md @@ -0,0 +1,314 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** docker-maven-plugin +**Bug ID:** 23 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package io.fabric8.maven.docker.access.log;/* + * + * Copyright 2014 Roland Huss + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.google.common.base.Charsets; +import com.google.common.io.ByteStreams; +import io.fabric8.maven.docker.access.DockerAccessException; +import io.fabric8.maven.docker.access.UrlBuilder; +import io.fabric8.maven.docker.access.util.RequestUtil; +import io.fabric8.maven.docker.util.Timestamp; +import org.apache.commons.codec.binary.Hex; +import org.apache.http.HttpResponse; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.impl.client.CloseableHttpClient; + +/** + * Extractor for parsing the response of a log request + * + * @author roland + * @since 28/11/14 + */ +public class LogRequestor extends Thread implements LogGetHandle { + // Patter for matching log entries + static final Pattern LOG_LINE = Pattern.compile("^\\[?(?[^\\s\\]]*)]? (?.*?)\\s*$", Pattern.DOTALL); + private final CloseableHttpClient client; + + private final String containerId; + + // callback called for each line extracted + private LogCallback callback; + + private DockerAccessException exception; + + // Remember for asynchronous handling so that the request can be aborted from the outside + private HttpUriRequest request; + + private final UrlBuilder urlBuilder; + + // Lock for synchronizing closing of requests + private final Object lock = new Object(); + + /** + * Create a helper object for requesting log entries synchronously ({@link #fetchLogs()}) or asynchronously ({@link #start()}. + * + * @param client HTTP client to use for requesting the docker host + * @param urlBuilder builder that creates docker urls + * @param containerId container for which to fetch the host + * @param callback callback to call for each line received + */ + public LogRequestor(CloseableHttpClient client, UrlBuilder urlBuilder, String containerId, LogCallback callback) { + this.client = client; + this.containerId = containerId; + + this.urlBuilder = urlBuilder; + + this.callback = callback; + this.exception = null; + } + + /** + * Get logs and feed a callback with the content + */ + public void fetchLogs() { + try { + callback.open(); + this.request = getLogRequest(false); + final HttpResponse respone = client.execute(request); + parseResponse(respone); + } catch (LogCallback.DoneException e) { + finish(); + } catch (IOException exp) { + callback.error(exp.getMessage()); + } finally { + callback.close(); + } + } + + // Fetch log asynchronously as stream and follow stream + public void run() { + synchronized (lock) { + try { + callback.open(); + + this.request = getLogRequest(true); + final HttpResponse response = client.execute(request); + parseResponse(response); + } catch (LogCallback.DoneException e) { + finish(); + } catch (IOException e) { + callback.error("IO Error while requesting logs: " + e + " " + Thread.currentThread().getName()); + } finally { + callback.close(); + } + } + } + + private static class NoBytesReadException extends IOException { + public NoBytesReadException() { + } + } + + /** + * This is a copy of ByteStreams.readFully(), with the slight change that it throws + * NoBytesReadException if zero bytes are read. Otherwise it is identical. + * + * @param in + * @param bytes + * @throws IOException + */ + private void readFully(InputStream in, byte[] bytes) throws IOException { + int read = ByteStreams.read(in, bytes, 0, bytes.length); + if (read == 0) { + throw new NoBytesReadException(); + } else if (read != bytes.length) { + throw new EOFException("reached end of stream after reading " + + read + " bytes; " + bytes.length + " bytes expected"); + } + } + + private boolean readStreamFrame(InputStream is) throws IOException, LogCallback.DoneException { + // Read the header, which is composed of eight bytes. The first byte is an integer + // indicating the stream type (0 = stdin, 1 = stdout, 2 = stderr), the next three are thrown + // out, and the final four are the size of the remaining stream as an integer. + ByteBuffer headerBuffer = ByteBuffer.allocate(8); + headerBuffer.order(ByteOrder.BIG_ENDIAN); + try { + this.readFully(is, headerBuffer.array()); + } catch (NoBytesReadException e) { + // Not bytes read for stream. Return false to stop consuming stream. + return false; + } catch (EOFException e) { + throw new IOException("Failed to read log header. Could not read all 8 bytes. " + e.getMessage(), e); + } + + // Grab the stream type (stdout, stderr, stdin) from first byte and throw away other 3 bytes. + int type = headerBuffer.get(); + + // Skip three bytes, then read size from remaining four bytes. + int size = headerBuffer.getInt(4); + + // Ignore empty messages and keep reading. + if (size <= 0) { + return true; + } + + // Read the actual message + ByteBuffer payload = ByteBuffer.allocate(size); + try { + ByteStreams.readFully(is, payload.array()); + } catch (EOFException e) { + throw new IOException("Failed to read log message. Could not read all " + size + " bytes. " + e.getMessage() + + " [ Header: " + Hex.encodeHexString(headerBuffer.array()) + "]", e); + } + + String message = Charsets.UTF_8.newDecoder().decode(payload).toString(); + callLogCallback(type, message); + return true; + } + + private void parseResponse(HttpResponse response) throws LogCallback.DoneException, IOException { + final StatusLine status = response.getStatusLine(); + if (status.getStatusCode() != 200) { + exception = new DockerAccessException("Error while reading logs (" + status + ")"); + throw new LogCallback.DoneException(); + } + + final InputStream is = response.getEntity().getContent(); + + try { + while (true) { + if (!readStreamFrame(is)) { + return; + } + } + } finally { + if ((is != null) && (is.available() > 0)) { + is.close(); + } + } + } + + private void callLogCallback(int type, String txt) throws LogCallback.DoneException { + Matcher matcher = LOG_LINE.matcher(txt); + if (!matcher.matches()) { + callback.error(String.format("Invalid log format for '%s' (expected: \" \") [%04x %04x]", + txt,(int) (txt.toCharArray())[0],(int) (txt.toCharArray())[1])); + throw new LogCallback.DoneException(); + } + Timestamp ts = new Timestamp(matcher.group("timestamp")); + String logTxt = matcher.group("entry"); + callback.log(type, ts, logTxt); + } + + private HttpUriRequest getLogRequest(boolean follow) { + return RequestUtil.newGet(urlBuilder.containerLogs(containerId, follow)); + } + + @Override + public void finish() { + synchronized (lock) { + if (request != null) { + request.abort(); + request = null; + } + } + } + + @Override + public boolean isError() { + return exception != null; + } + + @Override + public DockerAccessException getException() { + return exception; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `io.fabric8.maven.docker.access.log.LogRequestor.fetchLogs` reads without synchronization from `this.io.fabric8.maven.docker.access.log.LogRequestor.request`. Potentially races with write in method `LogRequestor.run()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void LogRequestor.fetchLogs() + +### Procedure Id: +io.fabric8.maven.docker.access.log.LogRequestor.fetchLogs():void.c419ee4a8d354b6aff9a49f0b49bde19 + +### File: +src/main/java/io/fabric8/maven/docker/access/log/LogRequestor.java + +### Key: +LogRequestor.java|fetchLogs|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +6b004dde0a5fbdcb5efb6f378575b501 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1078/instruction.md b/inferredbugs-1078/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3ea6e39eefc69d352bddae15978194f18aabd5e2 --- /dev/null +++ b/inferredbugs-1078/instruction.md @@ -0,0 +1,101 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Nancy +**Bug ID:** 14 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace Nancy.Tests.Specifications +{ + using System.Collections.Generic; + using System.IO; + using Nancy.Routing; + + public abstract class RequestSpec + { + protected static INancyEngine engine; + protected static IRequest request; + protected static Response response; + + protected RequestSpec() + { + engine = new NancyEngine(new AppDomainModuleLocator(), new RouteResolver()); + } + + protected static IRequest ManufactureGETRequestForRoute(string route) + { + return new Request("GET", route, new Dictionary>(), new MemoryStream()); + } + + protected static IRequest ManufacturePOSTRequestForRoute(string route) + { + return new Request("POST", route, new Dictionary>(), new MemoryStream()); + } + + protected static IRequest ManufactureDELETERequestForRoute(string route) + { + return new Request("DELETE", route, new Dictionary>(), new MemoryStream()); + } + + protected static IRequest ManufacturePUTRequestForRoute(string route) + { + return new Request("PUT", route, new Dictionary>(), new MemoryStream()); + } + + protected static IRequest ManufactureHEADRequestForRoute(string route) + { + return new Request("HEAD", route, new Dictionary>(), new MemoryStream()); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type Nancy.Request, Leaked resource (output of System.IO.MemoryStream::.ctor() at Line 30) of type System.IO.MemoryStream in method "IRequest RequestSpec.ManufactureDELETERequestForRoute(String)". + +### Severity: +ERROR + +### Procedure: +IRequest RequestSpec.ManufactureDELETERequestForRoute(String) + +### File: +src/Nancy.Tests/Specifications/RequestSpec.cs + +### Key: +RequestSpec.cs|ManufactureDELETERequestForRoute|DOTNET_RESOURCE_LEAK + +### Hash: +da5696e6479e343467ce700602fd8338 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1079/instruction.md b/inferredbugs-1079/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2a5b589a6ac3e789437aee311a2d74e5cdb3cfeb --- /dev/null +++ b/inferredbugs-1079/instruction.md @@ -0,0 +1,373 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Nancy +**Bug ID:** 22 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace Nancy.Tests.Unit +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using FakeItEasy; + using Nancy.Extensions; + using Nancy.Routing; + using Nancy.Tests.Fakes; + using Xunit; + using Xunit.Extensions; + + public class NancyEngineFixture + { + private readonly INancyEngine engine; + private readonly IRouteResolver resolver; + private readonly INancyModuleLocator locator; + private readonly IEnumerable modules; + + public NancyEngineFixture() + { + this.modules = new[] { new FakeNancyModuleWithBasePath() }; + this.locator = A.Fake(); + this.resolver = A.Fake(); + this.engine = new NancyEngine(this.locator, this.resolver); + } + + [Fact] + public void Should_throw_argumentnullexception_when_created_with_null_locator() + { + // Given, When + var exception = + Record.Exception(() => new NancyEngine(null, A.Fake())); + + // Then + exception.ShouldBeOfType(); + } + + [Fact] + public void Should_throw_argumentnullexception_when_created_with_null_resolver() + { + // Given, When + var exception = + Record.Exception(() => new NancyEngine(A.Fake(), null)); + + // Then + exception.ShouldBeOfType(); + } + + [Fact] + public void Should_retrieve_modules_from_locator_when_handling_request() + { + // Given + var request = new Request("GET", "/", new Dictionary>(), new MemoryStream()); + + // When + this.engine.HandleRequest(request); + + // Then + A.CallTo(() => this.locator.GetModules()).MustHaveHappened(); + } + + [Fact] + public void Should_return_not_found_response_when_no_nancy_modules_could_be_found() + { + // Given + var request = new Request("GET", "/", new Dictionary>(), new MemoryStream()); + + A.CallTo(() => this.locator.GetModules()).Returns(Enumerable.Empty()); + + // When + var response = this.engine.HandleRequest(request); + + // Then + response.StatusCode.ShouldEqual(HttpStatusCode.NotFound); + } + + [Fact] + public void Should_pass_all_registered_route_handlers_for_get_request_to_route_resolver() + { + // Given + var request = new Request("GET", "/", new Dictionary>(), new MemoryStream()); + var descriptions = GetRouteDescriptions(request, this.modules); + + A.CallTo(() => this.locator.GetModules()).Returns(modules); + + // When + this.engine.HandleRequest(request); + + // Then + A.CallTo(() => this.resolver.GetRoute(A.Ignored.Argument, + A>.That.Matches(x => x.SequenceEqual(descriptions)).Argument)).MustHaveHappened(); + } + + [Theory] + [InlineData("get")] + [InlineData("GeT")] + [InlineData("PoSt")] + [InlineData("post")] + [InlineData("puT")] + [InlineData("PUT")] + [InlineData("DelETe")] + [InlineData("DELete")] + public void Should_ignore_case_of_request_verb_when_resolving_route_handlers(string verb) + { + // Given + var request = new Request(verb, "/", new Dictionary>(), new MemoryStream()); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + // When + this.engine.HandleRequest(request); + + // Then + A.CallTo(() => this.resolver.GetRoute(A.Ignored.Argument, + A>.Ignored.Argument)).MustHaveHappened(); + } + + [Fact] + public void Should_pass_all_registered_route_handlers_for_delete_request_to_route_resolver() + { + // Given + var request = new Request("DELETE", "/", new Dictionary>(), new MemoryStream()); + var descriptions = GetRouteDescriptions(request, this.modules); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + // When + this.engine.HandleRequest(request); + + // Then + A.CallTo(() => this.resolver.GetRoute(A.Ignored.Argument, A>.That.Matches(x => x.SequenceEqual(descriptions)).Argument)).MustHaveHappened(); + } + + [Fact] + public void Should_call_route_resolver_with_all_route_handlers() + { + // Given + var request = new Request("PUT", "/", new Dictionary>(), new MemoryStream()); + var descriptions = GetRouteDescriptions(request, this.modules); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + A.CallTo(() => this.resolver.GetRoute(request, descriptions)).Returns(null); + + // When + this.engine.HandleRequest(request); + + // Then + A.CallTo(() => this.resolver.GetRoute(A.Ignored.Argument, A>.That.Matches(x => x.SequenceEqual(descriptions)).Argument)).MustHaveHappened(); + } + + [Fact] + public void Should_call_route_resolver_with_request() + { + // Given + var request = new Request("GET", "/", new Dictionary>(), new MemoryStream()); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + // When + this.engine.HandleRequest(request); + + // Then + A.CallTo(() => this.resolver.GetRoute(request, + A>.Ignored.Argument)).MustHaveHappened(); + } + + [Fact] + public void Should_return_not_found_response_when_no_route_could_be_matched_for_the_request_verb() + { + // Given + var request = new Request("NOTVALID", "/", new Dictionary>(), new MemoryStream()); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + // When + var response = this.engine.HandleRequest(request); + + // Then + response.StatusCode.ShouldEqual(HttpStatusCode.NotFound); + } + + [Fact] + public void Should_throw_argumentnullexception_when_handling_null_request() + { + // Given, When + var exception = + Record.Exception(() => this.engine.HandleRequest(null)); + + // Then + exception.ShouldBeOfType(); + } + + [Fact] + public void Should_invoke_resolved_route() + { + // Given + var route = A.Fake(); + var request = new Request("GET", "/", new Dictionary>(), new MemoryStream()); + var descriptions = GetRouteDescriptions(request, this.modules); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + A.CallTo(() => this.resolver.GetRoute(request, A>.That.Matches(x => x.SequenceEqual(descriptions)).Argument)).Returns(route); + + // When + this.engine.HandleRequest(request); + + // Then + A.CallTo(() => route.Invoke()).MustHaveHappened(); + } + + [Fact] + public void Should_return_response_generated_by_route() + { + // Given + var expectedResponse = new Response(); + var route = A.Fake(); + var request = new Request("GET", "/", new Dictionary>(), new MemoryStream()); + var descriptions = GetRouteDescriptions(request, this.modules); + + A.CallTo(() => route.Invoke()).Returns(expectedResponse); + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + A.CallTo(() => this.resolver.GetRoute(request, A>.That.Matches(x => x.SequenceEqual(descriptions)).Argument)).Returns(route); + + // When + var response = this.engine.HandleRequest(request); + + // Then + response.ShouldBeSameAs(expectedResponse); + } + + [Fact] + public void Should_set_base_route_on_descriptions_that_are_passed_to_resolver() + { + // Given + var request = new Request("POST", "/", new Dictionary>(), new MemoryStream()); + + var r = new FakeRouteResolver(); + var e = new NancyEngine(this.locator, r); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + // When + e.HandleRequest(request); + + // Then + r.ModulePath.ShouldEqual("/fake"); + } + + [Fact] + public void Should_set_path_on_descriptions_that_are_passed_to_resolver() + { + // Given + var request = new Request("POST", "/", new Dictionary>(), new MemoryStream()); + + var r = new FakeRouteResolver(); + var e = new NancyEngine(this.locator, r); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + // When + e.HandleRequest(request); + + // Then + r.Path.ShouldEqual("/"); + } + + [Fact] + public void Should_set_action_on_descriptions_that_are_passed_to_resolver() + { + // Given + var request = new Request("POST", "/", new Dictionary>(), new MemoryStream()); + + var r = new FakeRouteResolver(); + var e = new NancyEngine(this.locator, r); + + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + var expectedAction = + (new FakeNancyModuleWithBasePath()).Post["/"]; + + // When + e.HandleRequest(request); + + // Then + r.Action.ShouldBeSameAs(expectedAction); + } + + [Fact] + public void Should_set_request_property_of_loaded_modules() + { + // Given + var request = new Request("GET", "/", new Dictionary>(), new MemoryStream()); + A.CallTo(() => this.locator.GetModules()).Returns(this.modules); + + // When + this.engine.HandleRequest(request); + + // Then + this.modules.First().Request.ShouldNotBeNull(); + } + + private static IEnumerable GetRouteDescriptions(IRequest request, IEnumerable modules) + { + return modules.SelectMany(x => x.GetRouteDescription(request)); + } + + private static IRequest ManufactureGETRequest(string route) + { + return new Request("GET", route, new Dictionary>(), new MemoryStream()); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource e of type Nancy.NancyEngine, Leaked resource request of type Nancy.Request, Leaked resource (output of System.IO.MemoryStream::.ctor() at Line 256) of type System.IO.MemoryStream in method "Void NancyEngineFixture.Should_set_path_on_descriptions_that_are_passed_to_resolver()". + +### Severity: +ERROR + +### Procedure: +Void NancyEngineFixture.Should_set_path_on_descriptions_that_are_passed_to_resolver() + +### File: +src/Nancy.Tests/Unit/NancyEngineFixture.cs + +### Key: +NancyEngineFixture.cs|Should_set_path_on_descriptions_that_are_passed_to_resolver|DOTNET_RESOURCE_LEAK + +### Hash: +44545520cfdd60c776703911abb33725 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10792/instruction.md b/inferredbugs-10792/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9c8e131b0d57bd68d66a3ec454ec2513db58a984 --- /dev/null +++ b/inferredbugs-10792/instruction.md @@ -0,0 +1,281 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rocketmq +**Bug ID:** 32 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.rocketmq.broker.transaction.queue; + +import org.apache.rocketmq.broker.BrokerController; +import org.apache.rocketmq.client.consumer.PullResult; +import org.apache.rocketmq.client.consumer.PullStatus; +import org.apache.rocketmq.common.BrokerConfig; +import org.apache.rocketmq.common.MixAll; +import org.apache.rocketmq.common.message.MessageAccessor; +import org.apache.rocketmq.common.message.MessageConst; +import org.apache.rocketmq.common.message.MessageExt; +import org.apache.rocketmq.common.message.MessageQueue; +import org.apache.rocketmq.remoting.netty.NettyClientConfig; +import org.apache.rocketmq.remoting.netty.NettyServerConfig; +import org.apache.rocketmq.store.AppendMessageResult; +import org.apache.rocketmq.store.AppendMessageStatus; +import org.apache.rocketmq.store.GetMessageResult; +import org.apache.rocketmq.store.GetMessageStatus; +import org.apache.rocketmq.store.MessageExtBrokerInner; +import org.apache.rocketmq.store.MessageFilter; +import org.apache.rocketmq.store.MessageStore; +import org.apache.rocketmq.store.PutMessageResult; +import org.apache.rocketmq.store.PutMessageStatus; +import org.apache.rocketmq.store.config.MessageStoreConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Map; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class TransactionalMessageBridgeTest { + + private TransactionalMessageBridge transactionBridge; + + @Spy + private BrokerController brokerController = new BrokerController(new BrokerConfig(), new NettyServerConfig(), + new NettyClientConfig(), new MessageStoreConfig()); + + @Mock + private MessageStore messageStore; + + @Before + public void init() { + brokerController.setMessageStore(messageStore); + transactionBridge = new TransactionalMessageBridge(brokerController, messageStore); + } + + @Test + public void testPutOpMessage() { + boolean isSuccess = transactionBridge.putOpMessage(createMessageBrokerInner(), TransactionalMessageUtil.REMOVETAG); + assertThat(isSuccess).isTrue(); + } + + @Test + public void testPutHalfMessage() { + when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult + (PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK))); + PutMessageResult result = transactionBridge.putHalfMessage(createMessageBrokerInner()); + assertThat(result.getPutMessageStatus()).isEqualTo(PutMessageStatus.PUT_OK); + } + + @Test + public void testFetchMessageQueues() { + Set messageQueues = transactionBridge.fetchMessageQueues(MixAll.RMQ_SYS_TRANS_HALF_TOPIC); + assertThat(messageQueues.size()).isEqualTo(1); + } + + @Test + public void testFetchConsumeOffset() { + MessageQueue mq = new MessageQueue(TransactionalMessageUtil.buildOpTopic(), this.brokerController.getBrokerConfig().getBrokerName(), + 0); + long offset = transactionBridge.fetchConsumeOffset(mq); + assertThat(offset).isGreaterThan(-1); + } + + @Test + public void updateConsumeOffset() { + MessageQueue mq = new MessageQueue(TransactionalMessageUtil.buildOpTopic(), this.brokerController.getBrokerConfig().getBrokerName(), + 0); + transactionBridge.updateConsumeOffset(mq, 0); + } + + @Test + public void testGetHalfMessage() { + when(messageStore.getMessage(anyString(), anyString(), anyInt(), anyLong(), anyInt(), ArgumentMatchers.nullable(MessageFilter.class))).thenReturn(createGetMessageResult(GetMessageStatus.NO_MESSAGE_IN_QUEUE)); + PullResult result = transactionBridge.getHalfMessage(0, 0, 1); + assertThat(result.getPullStatus()).isEqualTo(PullStatus.NO_NEW_MSG); + } + + @Test + public void testGetOpMessage() { + when(messageStore.getMessage(anyString(), anyString(), anyInt(), anyLong(), anyInt(), ArgumentMatchers.nullable(MessageFilter.class))).thenReturn(createGetMessageResult(GetMessageStatus.NO_MESSAGE_IN_QUEUE)); + PullResult result = transactionBridge.getOpMessage(0, 0, 1); + assertThat(result.getPullStatus()).isEqualTo(PullStatus.NO_NEW_MSG); + } + + @Test + public void testPutMessageReturnResult() { + when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult + (PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK))); + PutMessageResult result = transactionBridge.putMessageReturnResult(createMessageBrokerInner()); + assertThat(result.getPutMessageStatus()).isEqualTo(PutMessageStatus.PUT_OK); + } + + @Test + public void testPutMessage() { + when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult + (PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK))); + Boolean success = transactionBridge.putMessage(createMessageBrokerInner()); + assertThat(success).isEqualTo(true); + } + + @Test + public void testRenewImmunityHalfMessageInner() { + MessageExt messageExt = createMessageBrokerInner(); + final String offset = "123456789"; + MessageExtBrokerInner msgInner = transactionBridge.renewImmunityHalfMessageInner(messageExt); + MessageAccessor.putProperty(msgInner, MessageConst.PROPERTY_TRANSACTION_PREPARED_QUEUE_OFFSET,offset); + assertThat(msgInner).isNotNull(); + Map properties = msgInner.getProperties(); + assertThat(properties).isNotNull(); + String resOffset = properties.get(MessageConst.PROPERTY_TRANSACTION_PREPARED_QUEUE_OFFSET); + assertThat(resOffset).isEqualTo(offset); + } + + + @Test + public void testRenewHalfMessageInner() { + MessageExt messageExt = new MessageExt(); + long bornTimeStamp = messageExt.getBornTimestamp(); + MessageExt messageExtRes = transactionBridge.renewHalfMessageInner(messageExt); + assertThat( messageExtRes.getBornTimestamp()).isEqualTo(bornTimeStamp); + } + + @Test + public void testLookMessageByOffset(){ + when(messageStore.lookMessageByOffset(anyLong())).thenReturn(new MessageExt()); + MessageExt messageExt = transactionBridge.lookMessageByOffset(123); + assertThat(messageExt).isNotNull(); + } + + @Test + public void testGetHalfMessageStatusFound() { + when(messageStore + .getMessage(anyString(), anyString(), anyInt(), anyLong(), anyInt(), ArgumentMatchers.nullable(MessageFilter.class))) + .thenReturn(createGetMessageResult(GetMessageStatus.FOUND)); + PullResult result = transactionBridge.getHalfMessage(0, 0, 1); + assertThat(result.getPullStatus()).isEqualTo(PullStatus.FOUND); + } + + @Test + public void testGetHalfMessageNull() { + when(messageStore + .getMessage(anyString(), anyString(), anyInt(), anyLong(), anyInt(), ArgumentMatchers.nullable(MessageFilter.class))) + .thenReturn(null); + PullResult result = transactionBridge.getHalfMessage(0, 0, 1); + assertThat(result.getPullStatus()).isNull(); + } + + private GetMessageResult createGetMessageResult(GetMessageStatus status) { + GetMessageResult getMessageResult = new GetMessageResult(); + getMessageResult.setStatus(status); + getMessageResult.setMinOffset(100); + getMessageResult.setMaxOffset(1024); + getMessageResult.setNextBeginOffset(516); + return getMessageResult; + } + + private MessageExtBrokerInner createMessageBrokerInner() { + MessageExtBrokerInner inner = new MessageExtBrokerInner(); + inner.setTransactionId("12342123444"); + inner.setBornTimestamp(System.currentTimeMillis()); + inner.setBody("prepare".getBytes()); + inner.setMsgId("123456-123"); + inner.setQueueId(0); + inner.setTopic("hello"); + return inner; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `result` last assigned on line 184 could be null and is dereferenced at line 185. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TransactionalMessageBridgeTest.testGetHalfMessageNull() + +### Procedure Id: +org.apache.rocketmq.broker.transaction.queue.TransactionalMessageBridgeTest.testGetHalfMessageNull().ba45c55a33d7fd26379497c55a559b1b + +### File: +broker/src/test/java/org/apache/rocketmq/broker/transaction/queue/TransactionalMessageBridgeTest.java + +### Key: +TransactionalMessageBridgeTest.java|testGetHalfMessageNull|NULL_DEREFERENCE + +### Node Key: +9140dff8bf7cd03886d368c0c0c52aa5 + +### Hash: +b58b6607ad56e1709351b5a697b5e241 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10795/instruction.md b/inferredbugs-10795/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..80c0bf7e4649d1712f2dd8f6d32709b4bfb8b6b8 --- /dev/null +++ b/inferredbugs-10795/instruction.md @@ -0,0 +1,183 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rocketmq +**Bug ID:** 33 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.rocketmq.broker.client; + +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import java.lang.reflect.Field; +import java.util.HashMap; +import org.apache.rocketmq.remoting.protocol.LanguageCode; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ProducerManagerTest { + private ProducerManager producerManager; + private String group = "FooBar"; + private ClientChannelInfo clientInfo; + + @Mock + private Channel channel; + + @Before + public void init() { + producerManager = new ProducerManager(); + clientInfo = new ClientChannelInfo(channel, "clientId", LanguageCode.JAVA, 0); + } + + @Test + public void scanNotActiveChannel() throws Exception { + producerManager.registerProducer(group, clientInfo); + assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNotNull(); + assertThat(producerManager.findChannel("clientId")).isNotNull(); + Field field = ProducerManager.class.getDeclaredField("CHANNEL_EXPIRED_TIMEOUT"); + field.setAccessible(true); + long CHANNEL_EXPIRED_TIMEOUT = field.getLong(producerManager); + clientInfo.setLastUpdateTimestamp(System.currentTimeMillis() - CHANNEL_EXPIRED_TIMEOUT - 10); + when(channel.close()).thenReturn(mock(ChannelFuture.class)); + producerManager.scanNotActiveChannel(); + assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNull(); + assertThat(producerManager.findChannel("clientId")).isNull(); + } + + @Test + public void doChannelCloseEvent() throws Exception { + producerManager.registerProducer(group, clientInfo); + assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNotNull(); + assertThat(producerManager.findChannel("clientId")).isNotNull(); + producerManager.doChannelCloseEvent("127.0.0.1", channel); + assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNull(); + assertThat(producerManager.findChannel("clientId")).isNull(); + } + + @Test + public void testRegisterProducer() throws Exception { + producerManager.registerProducer(group, clientInfo); + HashMap channelMap = producerManager.getGroupChannelTable().get(group); + Channel channel1 = producerManager.findChannel("clientId"); + assertThat(channelMap).isNotNull(); + assertThat(channel1).isNotNull(); + assertThat(channelMap.get(channel)).isEqualTo(clientInfo); + assertThat(channel1).isEqualTo(channel); + } + + @Test + public void unregisterProducer() throws Exception { + producerManager.registerProducer(group, clientInfo); + HashMap channelMap = producerManager.getGroupChannelTable().get(group); + assertThat(channelMap).isNotNull(); + assertThat(channelMap.get(channel)).isEqualTo(clientInfo); + Channel channel1 = producerManager.findChannel("clientId"); + assertThat(channel1).isNotNull(); + assertThat(channel1).isEqualTo(channel); + producerManager.unregisterProducer(group, clientInfo); + channelMap = producerManager.getGroupChannelTable().get(group); + channel1 = producerManager.findChannel("clientId"); + assertThat(channelMap).isNull(); + assertThat(channel1).isNull(); + + } + + @Test + public void testGetGroupChannelTable() throws Exception { + producerManager.registerProducer(group, clientInfo); + HashMap oldMap = producerManager.getGroupChannelTable().get(group); + + producerManager.unregisterProducer(group, clientInfo); + assertThat(oldMap.size()).isNotEqualTo(0); + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `channelMap` last assigned on line 77 could be null and is dereferenced at line 81. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ProducerManagerTest.testRegisterProducer() + +### Procedure Id: +org.apache.rocketmq.broker.client.ProducerManagerTest.testRegisterProducer():void.32baffadfb3780626205e6796166058b + +### File: +broker/src/test/java/org/apache/rocketmq/broker/client/ProducerManagerTest.java + +### Key: +ProducerManagerTest.java|testRegisterProducer|NULL_DEREFERENCE + +### Node Key: +57d951b6f33cf70bde10c0b2bb9d2d1c + +### Hash: +0b48d8b28e9af1aaa6bf9fbcd7d2742d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10823/instruction.md b/inferredbugs-10823/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1077b814d2abf148e7acae593682ebd694f40afe --- /dev/null +++ b/inferredbugs-10823/instruction.md @@ -0,0 +1,139 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rocketmq +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.rocketmq.tools.command.message; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.apache.rocketmq.common.UtilAll; +import org.apache.rocketmq.common.message.MessageClientIDSetter; +import org.apache.rocketmq.remoting.RPCHook; +import org.apache.rocketmq.tools.command.SubCommand; +import org.apache.rocketmq.tools.command.SubCommandException; + +public class DecodeMessageIdCommond implements SubCommand { + @Override + public String commandName() { + return "DecodeMessageId"; + } + + @Override + public String commandDesc() { + return "decode unique message ID"; + } + + @Override + public Options buildCommandlineOptions(Options options) { + Option opt = new Option("i", "messageId", true, "unique message ID"); + opt.setRequired(false); + options.addOption(opt); + return options; + } + + @Override + public void execute(final CommandLine commandLine, final Options options, + RPCHook rpcHook) throws SubCommandException { + String messageId = commandLine.getOptionValue('i').trim(); + + try { + System.out.printf("ip=" + MessageClientIDSetter.getIPStrFromID(messageId)); + } catch (Exception e) { + e.printStackTrace(); + } + + try { + String date = UtilAll.formatDate(MessageClientIDSetter.getNearlyTimeFromID(messageId), UtilAll.YYYY_MM_DD_HH_MM_SS_SSS); + System.out.printf("date=" + date); + } catch (Exception e) { + throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +CHECKERS_PRINTF_ARGS + +### Qualifier: +Format string must be string literal. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DecodeMessageIdCommond.execute(CommandLine,Options,RPCHook) + +### Procedure Id: +org.apache.rocketmq.tools.command.message.DecodeMessageIdCommond.execute(org.apache.commons.cli.Comm.800771a951557d622f704049585f7a9d + +### File: +tools/src/main/java/org/apache/rocketmq/tools/command/message/DecodeMessageIdCommond.java + +### Key: +DecodeMessageIdCommond.java|execute|CHECKERS_PRINTF_ARGS + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +5a6e696dd6715e3843e7c4cc27849c2e + +### Bug Type Hum: +Checkers Printf Args + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1083/instruction.md b/inferredbugs-1083/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1fc90f740ab7edcf26d477d5c8438155b604040f --- /dev/null +++ b/inferredbugs-1083/instruction.md @@ -0,0 +1,154 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Aeron.NET +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/* + * Copyright 2014 - 2017 Adaptive Financial Consulting Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using Adaptive.Aeron.Command; +using Adaptive.Agrona.Concurrent; +using Adaptive.Agrona.Concurrent.RingBuffer; +using NUnit.Framework; + +namespace Adaptive.Aeron.Tests +{ + public class DriverProxyTest + { + [SetUp] + public void Setup() + { + conductorBuffer = new ManyToOneRingBuffer(new UnsafeBuffer(new byte[RingBufferDescriptor.TrailerLength + 1024])); + conductor = new DriverProxy(conductorBuffer, CLIENT_ID); + } + + public const string CHANNEL = "aeron:udp?interface=localhost:40123|endpoint=localhost:40124"; + + private const int STREAM_ID = 1; + private const long CORRELATION_ID = 3; + private const long CLIENT_ID = 7; + private IRingBuffer conductorBuffer; + private DriverProxy conductor; + + [Test] + public void ThreadSendsAddChannelMessage() + { + ThreadSendsChannelMessage(() => conductor.AddPublication(CHANNEL, STREAM_ID), ControlProtocolEvents.ADD_PUBLICATION); + } + + [Test] + public void ThreadSendsRemoveChannelMessage() + { + conductor.RemovePublication(CORRELATION_ID); + AssertReadsOneMessage((msgTypeId, buffer, index, length) => + { + RemoveMessageFlyweight message = new RemoveMessageFlyweight(); + message.Wrap(buffer, index); + Assert.That(msgTypeId, Is.EqualTo(ControlProtocolEvents.REMOVE_PUBLICATION)); + Assert.That(message.RegistrationId(), Is.EqualTo(CORRELATION_ID)); + }); + } + + private void ThreadSendsChannelMessage(Action sendMessage, int expectedMsgTypeId) + { + sendMessage(); + + AssertReadsOneMessage((msgTypeId, buffer, index, length) => + { + PublicationMessageFlyweight publicationMessage = new PublicationMessageFlyweight(); + publicationMessage.Wrap(buffer, index); + Assert.That(msgTypeId, Is.EqualTo(expectedMsgTypeId)); + Assert.That(publicationMessage.Channel(), Is.EqualTo(CHANNEL)); + Assert.That(publicationMessage.StreamId(), Is.EqualTo(STREAM_ID)); + }); + } + + [Test] + public void ThreadSendsRemoveSubscriberMessage() + { + conductor.RemoveSubscription(CORRELATION_ID); + + AssertReadsOneMessage((msgTypeId, buffer, index, length) => + { + RemoveMessageFlyweight removeMessage = new RemoveMessageFlyweight(); + removeMessage.Wrap(buffer, index); + Assert.That(msgTypeId, Is.EqualTo(ControlProtocolEvents.REMOVE_SUBSCRIPTION)); + Assert.That(removeMessage.RegistrationId(), Is.EqualTo(CORRELATION_ID)); + }); + } + + private void AssertReadsOneMessage(MessageHandler handler) + { + int messageCount = conductorBuffer.Read(handler); + Assert.That(messageCount, Is.EqualTo(1)); + } + } + +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Adaptive.Agrona.Concurrent.UnsafeBuffer::.ctor() at Line 30) of type Adaptive.Agrona.Concurrent.UnsafeBuffer in method "Void DriverProxyTest.Setup()". + +### Severity: +ERROR + +### Procedure: +Void DriverProxyTest.Setup() + +### File: +src/Adaptive.Aeron.Tests/DriverProxyTests.cs + +### Key: +DriverProxyTests.cs|Setup|DOTNET_RESOURCE_LEAK + +### Hash: +159f9591cd81a69565f074748f599bb9 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10840/instruction.md b/inferredbugs-10840/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b0569abbc103b3905b29f530452b5e4b7cb077e7 --- /dev/null +++ b/inferredbugs-10840/instruction.md @@ -0,0 +1,229 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** Metanome +**Bug ID:** 21 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 by the Metanome project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.metanome.frontend.client.results; + + +import com.google.gwt.junit.client.GWTTestCase; +import com.google.gwt.user.client.Timer; +import com.google.gwt.user.client.ui.Label; +import com.google.gwt.user.client.ui.TabLayoutPanel; + +import de.metanome.backend.results_db.Execution; +import de.metanome.frontend.client.BasePage; +import de.metanome.frontend.client.TabWrapper; +import de.metanome.frontend.client.TestHelper; + +public class GwtTestResultsPage extends GWTTestCase { + + /** + * Test method for {@link de.metanome.frontend.client.results.ResultsPage#ResultsPage(de.metanome.frontend.client.BasePage)} + */ + public void testResultTable() { + // Set up + TestHelper.resetDatabaseSync(); + + BasePage parent = new BasePage(); + + // Expected Values + // Execute + ResultsPage page = new ResultsPage(parent); + + // Check + assertNotNull(page.basePage); + assertTrue(page.getWidget(0) instanceof Label); + + // Cleanup + TestHelper.resetDatabaseSync(); + } + + /** + * Test method for {@link ResultsPage#startPolling(boolean)} + */ + public void testStartPolling() { + // Set up + TestHelper.resetDatabaseSync(); + + BasePage parent = new BasePage(); + ResultsPage page = new ResultsPage(parent); + + page.setExecutionParameter("identifier", "name"); + + // Expected Values + // Execute + page.startPolling(true); + + // Check + assertEquals(5, page.getWidgetCount()); + assertNotNull(page.runningIndicator); + assertNotNull(page.progressBar); + assertNotNull(page.algorithmLabel); + assertNotNull(page.executionTimePanel); + + // Cleanup + TestHelper.resetDatabaseSync(); + } + + + /** + * Test method for {@link ResultsPage#updateOnError(String)} + */ + public void testUpdateOnError() { + // Set up + TestHelper.resetDatabaseSync(); + + BasePage parent = new BasePage(); + ResultsPage page = new ResultsPage(parent); + page.setMessageReceiver(new TabWrapper()); + page.executionTimeTimer = new Timer() { + @Override + public void run() { + } + }; + + // Expected Values + // Execute + page.updateOnError("message"); + + // Check + assertTrue(page.messageReceiver.isInError()); + assertEquals(0, page.getWidgetCount()); + + // Cleanup + TestHelper.resetDatabaseSync(); + } + + /** + * Test method for {@link ResultsPage#updateOnSuccess(de.metanome.backend.results_db.Execution)} + */ + public void testUpdateOnSuccess() { + // Set up + TestHelper.resetDatabaseSync(); + + Execution execution = new Execution(null, 12); + execution.setEnd(2345); + + BasePage parent = new BasePage(); + ResultsPage page = new ResultsPage(parent); + page.setMessageReceiver(new TabWrapper()); + page.setExecutionParameter("identifier", "name"); + + page.startPolling(true); + + // Expected Values + // Execute + page.updateOnSuccess(null); + + // Check + assertEquals(2, page.getWidgetCount()); + assertTrue(page.getWidget(1) instanceof TabLayoutPanel); + assertEquals(2, ((TabLayoutPanel) page.getWidget(1)).getWidgetCount()); + + // Cleanup + TestHelper.resetDatabaseSync(); + } + + public void testTimeConversion() { + BasePage parent = new BasePage(); + ResultsPage page = new ResultsPage(parent); + + String timeStr = "01:30:40"; + int timeInt = 5440; + + assertEquals(timeStr, page.toTimeString(timeInt)); + assertEquals(timeInt, page.toTimeInt(timeStr)); + } + + @Override + public String getModuleName() { + return "de.metanome.frontend.MetanomeTest"; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `updateOnSuccess(...)` at line 128. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GwtTestResultsPage.testUpdateOnSuccess() + +### Procedure Id: +de.metanome.frontend.client.results.GwtTestResultsPage.testUpdateOnSuccess():void.1d3574e4cd318104c21fab466137482a + +### File: +frontend/src/test/java/de/metanome/frontend/client/results/GwtTestResultsPage.java + +### Key: +GwtTestResultsPage.java|testUpdateOnSuccess|NULL_DEREFERENCE + +### Node Key: +bcbf527556430e212619bbf95454ee16 + +### Hash: +59e43dbe4e5c0dc6a3bba2f79490b23a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10846/instruction.md b/inferredbugs-10846/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..83f00c442d8c709b89015ee40bc68ea9ff7f79c1 --- /dev/null +++ b/inferredbugs-10846/instruction.md @@ -0,0 +1,238 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** Metanome +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.uni_potsdam.hpi.metanome.frontend.server; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.UnsupportedEncodingException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; + +import com.google.gwt.user.server.rpc.RemoteServiceServlet; + +import de.uni_potsdam.hpi.metanome.algorithm_execution.TempFileGenerator; +import de.uni_potsdam.hpi.metanome.algorithm_integration.AlgorithmConfigurationException; +import de.uni_potsdam.hpi.metanome.algorithm_integration.AlgorithmExecutionException; +import de.uni_potsdam.hpi.metanome.algorithm_integration.algorithm_execution.FileGenerator; +import de.uni_potsdam.hpi.metanome.algorithm_integration.configuration.ConfigurationValue; +import de.uni_potsdam.hpi.metanome.algorithm_integration.configuration.ConfigurationValueBoolean; +import de.uni_potsdam.hpi.metanome.algorithm_integration.configuration.ConfigurationValueSQLInputGenerator; +import de.uni_potsdam.hpi.metanome.algorithm_integration.configuration.ConfigurationValueRelationalInputGenerator; +import de.uni_potsdam.hpi.metanome.algorithm_integration.configuration.ConfigurationValueString; +import de.uni_potsdam.hpi.metanome.algorithm_integration.input.SQLInputGenerator; +import de.uni_potsdam.hpi.metanome.algorithm_integration.result_receiver.FunctionalDependencyResultReceiver; +import de.uni_potsdam.hpi.metanome.algorithm_integration.result_receiver.InclusionDependencyResultReceiver; +import de.uni_potsdam.hpi.metanome.algorithm_integration.result_receiver.UniqueColumnCombinationResultReceiver; +import de.uni_potsdam.hpi.metanome.algorithm_loading.AlgorithmExecutor; +import de.uni_potsdam.hpi.metanome.algorithm_loading.AlgorithmLoadingException; +import de.uni_potsdam.hpi.metanome.frontend.client.parameter.InputParameter; +import de.uni_potsdam.hpi.metanome.frontend.client.parameter.InputParameterBoolean; +import de.uni_potsdam.hpi.metanome.frontend.client.parameter.InputParameterCsvFile; +import de.uni_potsdam.hpi.metanome.frontend.client.parameter.InputParameterSQLIterator; +import de.uni_potsdam.hpi.metanome.frontend.client.parameter.InputParameterString; +import de.uni_potsdam.hpi.metanome.frontend.client.services.ExecutionService; +import de.uni_potsdam.hpi.metanome.input.csv.CsvFileGenerator; +import de.uni_potsdam.hpi.metanome.input.sql.SqlIteratorGenerator; +import de.uni_potsdam.hpi.metanome.result_receiver.FunctionalDependencyPrinter; +import de.uni_potsdam.hpi.metanome.result_receiver.InclusionDependencyPrinter; +import de.uni_potsdam.hpi.metanome.result_receiver.UniqueColumnCombinationPrinter; + +/** + * Service Implementation for service that triggers algorithm execution + */ +public class ExecutionServiceImpl extends RemoteServiceServlet implements ExecutionService { + + private static final long serialVersionUID = -2758103927345131933L; + + /** + * TODO docs + * + * @param algorithmName + * @return + * @throws FileNotFoundException + * @throws UnsupportedEncodingException + */ + protected AlgorithmExecutor buildExecutor(String algorithmName) throws FileNotFoundException, UnsupportedEncodingException { + FunctionalDependencyResultReceiver fdResultReceiver = + new FunctionalDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); + InclusionDependencyResultReceiver indResultReceiver = + new InclusionDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); + UniqueColumnCombinationResultReceiver uccResultReceiver = + new UniqueColumnCombinationPrinter(getResultFileName(algorithmName), getResultDirectoryName()); + FileGenerator fileGenerator = new TempFileGenerator(); + + return new AlgorithmExecutor(fdResultReceiver, indResultReceiver, uccResultReceiver, fileGenerator); + } + + private List convertInputParameters( + List parameters) throws AlgorithmConfigurationException { + List configValuesList = new LinkedList(); + for (InputParameter parameter : parameters){ + ConfigurationValue configValue = convertToConfigurationValue(parameter); + configValuesList.add(configValue); + } + return configValuesList; + } + + /** + * TODO docs + * + * @param parameter + * @return + * @throws AlgorithmConfigurationException + */ + public ConfigurationValue convertToConfigurationValue( + InputParameter parameter) throws AlgorithmConfigurationException { + //TODO all types of ConfigurationValues + if (parameter instanceof InputParameterString) + return new ConfigurationValueString(parameter.getIdentifier(), + ((InputParameterString) parameter).getValue()); + + else if (parameter instanceof InputParameterBoolean) + return new ConfigurationValueBoolean(parameter.getIdentifier(), + ((InputParameterBoolean) parameter).getValue()); + + else if (parameter instanceof InputParameterCsvFile) + return new ConfigurationValueRelationalInputGenerator(parameter.getIdentifier(), + buildCsvFileGenerator((InputParameterCsvFile) parameter)); + + else if (parameter instanceof InputParameterSQLIterator) + return new ConfigurationValueSQLInputGenerator(parameter.getIdentifier(), + buildSQLInputGenerator((InputParameterSQLIterator) parameter)); + + else + return null; + } + + /** + * TODO docs + * + * @param parameter + * @return + * @throws AlgorithmConfigurationException + */ + private SQLInputGenerator buildSQLInputGenerator( + InputParameterSQLIterator parameter) throws AlgorithmConfigurationException { + return new SqlIteratorGenerator(parameter.getDbUrl(), parameter.getUserName(), parameter.getPassword()); + } + + /** + * TODO docs + * + * @param param + * @return + * @throws AlgorithmConfigurationException + */ + protected CsvFileGenerator buildCsvFileGenerator(InputParameterCsvFile param) throws AlgorithmConfigurationException { + //TODO advanced CsvFileGenerator construction + try { + if (param.isAdvanced()) + return new CsvFileGenerator(new File(param.getFileNameValue()), param.getSeparatorChar(), + param.getQuoteChar(), param.getEscapeChar(), param.getLine(), + param.isStrictQuotes(), param.isIgnoreLeadingWhiteSpace()) ; + else + return new CsvFileGenerator(new File(param.getFileNameValue())); + } catch (FileNotFoundException e) { + throw new AlgorithmConfigurationException("Could not find specified CSV file."); + } + } + + @Override + public void executeAlgorithm(String algorithmName, List parameters) throws AlgorithmConfigurationException, AlgorithmLoadingException, AlgorithmExecutionException { + + List configs = convertInputParameters(parameters); + + try { + buildExecutor(algorithmName).executeAlgorithm(algorithmName, configs); + } catch (FileNotFoundException e) { + throw new AlgorithmExecutionException("Could not generate result file."); + } catch (UnsupportedEncodingException e) { + throw new AlgorithmExecutionException("Could not build temporary file generator."); + } + } + + protected String getResultDirectoryName() { + return "results"; + } + + protected String getResultFileName(String algorithmName) { + return algorithmName + new SimpleDateFormat("yyyy-MM-dd'T'HHmmss").format(new Date()) + ".txt"; + } + + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `de.uni_potsdam.hpi.metanome.result_receiver.UniqueColumnCombinationPrinter` acquired by call to `buildExecutor(...)` at line 146 is not released after line 146. +**Note**: potential exception at line 146 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExecutionServiceImpl.executeAlgorithm(String,List) + +### Procedure Id: +de.uni_potsdam.hpi.metanome.frontend.server.ExecutionServiceImpl.executeAlgorithm(java.lang.String,j.851c01fab5572bf27434b470d5c8b2ee + +### File: +frontend/src/main/java/de/uni_potsdam/hpi/metanome/frontend/server/ExecutionServiceImpl.java + +### Key: +ExecutionServiceImpl.java|executeAlgorithm|RESOURCE_LEAK + +### Node Key: +a3577a5bd798e4287b09e9b1fe068938 + +### Hash: +09d4233a9b44a4e118596e21039004c7 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10847/instruction.md b/inferredbugs-10847/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..79e96a2c77b5ae44259126d802d4b54235b89036 --- /dev/null +++ b/inferredbugs-10847/instruction.md @@ -0,0 +1,156 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** Metanome +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.uni_potsdam.hpi.metanome.algorithm_integration.input; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * Tests for {@link CsvFileGenerator} + */ +public class CsvFileGeneratorTest { + + protected CsvFileFixture csvFileFixture; + protected File expectedFile; + protected char expectedSeparator; + protected char expectedQuotechar; + protected char expectedEscape; + protected int expectedLine; + protected boolean expectedStrictQuotes; + protected boolean expectedIgnoreLeadingWhiteSpace; + protected CsvFileGenerator generator; + + @Before + public void setUp() throws Exception { + this.csvFileFixture = new CsvFileFixture(); + this.expectedFile = csvFileFixture.getTestDataPath("test.csv"); + this.expectedSeparator = CsvFileFixture.SEPARATOR; + this.expectedQuotechar = CsvFileFixture.QUOTE_CHAR; + this.expectedEscape = '\\'; + this.expectedLine = 0; + this.expectedStrictQuotes = true; + this.expectedIgnoreLeadingWhiteSpace = true; + this.generator = new CsvFileGenerator(expectedFile, expectedSeparator, expectedQuotechar, expectedEscape, expectedLine, expectedStrictQuotes, expectedIgnoreLeadingWhiteSpace); + } + + @After + public void tearDown() throws Exception { + + } + + /** + * The generator should store the file path correctly. + */ + @Test + public void testConstructor() { + // Check result + assertEquals(expectedFile, generator.inputFile); + assertEquals(expectedSeparator, generator.separator); + assertEquals(expectedQuotechar, generator.quotechar); + assertEquals(expectedEscape, generator.escape); + assertEquals(expectedLine, generator.line); + assertEquals(expectedStrictQuotes, generator.strictQuotes); + assertEquals(expectedIgnoreLeadingWhiteSpace, generator.ignoreLeadingWhiteSpace); + } + + /** + * The generator should generate fresh csv files iterable from the start. + * + * @throws IOException + */ + @Test + public void testGenerateNewCsvFile() throws IOException { + // Setup + SimpleRelationalInput csv = generator.generateNewCsvFile(); + + // Check result + // The csv should contain both lines and iterate through them with next. + assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); + assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); + // A new CsvFile should iterate from the start. + SimpleRelationalInput csv2 = generator.generateNewCsvFile(); + assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); + assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); + } + + + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `au.com.bytecode.opencsv.CSVReader` acquired by call to `generateNewCsvFile()` at line 75 is not released after line 77. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CsvFileGeneratorTest.testGenerateNewCsvFile() + +### Procedure Id: +de.uni_potsdam.hpi.metanome.algorithm_integration.input.CsvFileGeneratorTest.testGenerateNewCsvFile(.bd7d8431465d086a403952509f9982d0 + +### File: +algorithm_integration/src/test/java/de/uni_potsdam/hpi/metanome/algorithm_integration/input/CsvFileGeneratorTest.java + +### Key: +CsvFileGeneratorTest.java|testGenerateNewCsvFile|RESOURCE_LEAK + +### Node Key: +d350fd7be612547f956744870931a299 + +### Hash: +91152612a07cf148f5c2118423a62f1d + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10849/instruction.md b/inferredbugs-10849/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..be920422fa79218bf2e6c9e980aa08b21a1c2ead --- /dev/null +++ b/inferredbugs-10849/instruction.md @@ -0,0 +1,370 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** Metanome +**Bug ID:** 22 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 by the Metanome project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.metanome.backend.resources; + +import com.fasterxml.jackson.core.JsonProcessingException; + +import de.metanome.algorithm_integration.AlgorithmConfigurationException; +import de.metanome.algorithm_integration.algorithm_execution.FileGenerator; +import de.metanome.algorithm_integration.configuration.ConfigurationRequirement; +import de.metanome.algorithm_integration.configuration.ConfigurationSetting; +import de.metanome.algorithm_integration.configuration.ConfigurationSettingDatabaseConnection; +import de.metanome.algorithm_integration.configuration.ConfigurationSettingFileInput; +import de.metanome.algorithm_integration.configuration.ConfigurationSettingTableInput; +import de.metanome.algorithm_integration.configuration.ConfigurationValue; +import de.metanome.algorithm_integration.input.FileInputGenerator; +import de.metanome.algorithm_integration.input.RelationalInputGenerator; +import de.metanome.algorithm_integration.input.TableInputGenerator; +import de.metanome.algorithm_integration.results.JsonConverter; +import de.metanome.algorithm_integration.results.Result; +import de.metanome.backend.algorithm_execution.AlgorithmExecutor; +import de.metanome.backend.algorithm_execution.ProcessExecutor; +import de.metanome.backend.algorithm_execution.ProcessRegistry; +import de.metanome.backend.algorithm_execution.ProgressCache; +import de.metanome.backend.algorithm_execution.TempFileGenerator; +import de.metanome.backend.configuration.DefaultConfigurationFactory; +import de.metanome.backend.helper.FileInputGeneratorMixIn; +import de.metanome.backend.helper.RelationalInputGeneratorMixIn; +import de.metanome.backend.helper.TableInputGeneratorMixIn; +import de.metanome.backend.result_receiver.ResultCache; +import de.metanome.backend.result_receiver.ResultCounter; +import de.metanome.backend.result_receiver.ResultPrinter; +import de.metanome.backend.result_receiver.ResultReader; +import de.metanome.backend.result_receiver.ResultReceiver; +import de.metanome.backend.results_db.Algorithm; +import de.metanome.backend.results_db.EntityStorageException; +import de.metanome.backend.results_db.Execution; +import de.metanome.backend.results_db.ExecutionSetting; +import de.metanome.backend.results_db.HibernateUtil; +import de.metanome.backend.results_db.Input; +import de.metanome.backend.results_db.ResultType; + +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.LinkedList; +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; + +@Path("algorithm_execution") +public class AlgorithmExecutionResource { + + /** + * Executes an algorithm. + * @param params all parameters to execute the algorithm + * @return the resulting execution + */ + @POST + @Consumes("application/json") + @Produces("application/json") + public Execution executeAlgorithm(AlgorithmExecutionParams params) { + + String executionIdentifier = params.getExecutionIdentifier(); + ExecutionSetting executionSetting = buildExecutionSetting(params); + try { + HibernateUtil.store(executionSetting); + } catch (EntityStorageException e) { + throw new WebException(e, Response.Status.BAD_REQUEST); + } + HibernateUtil.shutdown(); + try { + Process + process = + ProcessExecutor.exec(AlgorithmExecutor.class, String.valueOf(params.getAlgorithmId()), + executionIdentifier, params.getMemory()); + ProcessRegistry.getInstance().put(executionIdentifier, + process); + InputStreamReader isr = new InputStreamReader(process.getInputStream()); + BufferedReader br = new BufferedReader(isr); + String lineRead; + while ((lineRead = br.readLine()) != null) { + System.out.println(lineRead); + } + System.out.println("hello Again!"); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + Execution execution = null; + try { + ArrayList criteria = new ArrayList<>(); + criteria.add(Restrictions.eq("identifier", executionIdentifier)); + execution = + (Execution) HibernateUtil + .queryCriteria(Execution.class, + criteria.toArray(new Criterion[criteria.size()])).get(0); + } catch (EntityStorageException | IndexOutOfBoundsException e) { + AlgorithmResource algorithmResource = new AlgorithmResource(); + Algorithm algorithm = algorithmResource.get(params.getAlgorithmId()); + execution = new Execution(algorithm).setExecutionSetting(executionSetting).setAborted(true); + ExecutionResource executionResource = new ExecutionResource(); + executionResource.store(execution); + } + return execution; + } + + @GET + @Path("/result_cache/{identifier}") + @Produces("application/json") + public List getCacheResults(@PathParam("identifier") String executionIdentifier) { + try { + return AlgorithmExecutionCache.getResultCache(executionIdentifier).fetchNewResults(); + } catch (Exception e) { + throw new WebException("Could not find any results to the given identifier", + Response.Status.BAD_REQUEST); + } + } + + @GET + @Path("/fetch_progress/{identifier}") + @Produces("application/json") + public float fetchProgress(@PathParam("identifier") String executionIdentifier) { + try { + return AlgorithmExecutionCache.getProgressCache(executionIdentifier).getProgress(); + } catch (Exception e) { + throw new WebException("Could not find any progress to the given identifier", + Response.Status.BAD_REQUEST); + } + } + + @GET + @Path("/result_counter/{identifier}") + @Produces("application/json") + public EnumMap getCounterResults(@PathParam("identifier") String executionIdentifier) { + try { + return AlgorithmExecutionCache.getResultCounter(executionIdentifier).getResults(); + } catch (Exception e) { + throw new WebException("Could not find any progress to the given identifier", + Response.Status.BAD_REQUEST); + } + } + + @GET + @Path("/result_printer/{identifier}") + @Produces("application/json") + public List getPrinterResults(@PathParam("identifier") String executionIdentifier) { + try { + return AlgorithmExecutionCache.getResultPrinter(executionIdentifier).getResults(); + } catch (Exception e) { + throw new WebException("Could not find any progress to the given identifier", + Response.Status.BAD_REQUEST); + } + } + + @GET + @Path("/read_result/{file_name}/{type}") + @Produces("application/json") + public List readResultFromFile(@PathParam("file_name") String fileName, @PathParam("type") String type) { + try { + return ResultReader.readResultsFromFile(fileName, type); + } catch (Exception e) { + throw new WebException("Could not read result file", + Response.Status.BAD_REQUEST); + } + } + + protected ExecutionSetting buildExecutionSetting(AlgorithmExecutionParams params) { + ExecutionSetting executionSetting = null; + try { + DefaultConfigurationFactory configurationFactory = new DefaultConfigurationFactory(); + List parameterValues = new LinkedList<>(); + List inputs = new ArrayList<>(); + FileInputResource fileInputResource = new FileInputResource(); + TableInputResource tableInputResource = new TableInputResource(); + DatabaseConnectionResource databaseConnectionResource = new DatabaseConnectionResource(); + + for (ConfigurationRequirement requirement : params.getRequirements()) { + parameterValues.add(requirement.build(configurationFactory)); + + for (ConfigurationSetting setting : requirement.getSettings()) { + if (setting instanceof ConfigurationSettingFileInput) { + inputs.add(fileInputResource.get(((ConfigurationSettingFileInput) setting).getId())); + } else if (setting instanceof ConfigurationSettingDatabaseConnection) { + inputs.add(databaseConnectionResource + .get(((ConfigurationSettingDatabaseConnection) setting).getId())); + } else if (setting instanceof ConfigurationSettingTableInput) { + inputs.add(tableInputResource.get(((ConfigurationSettingTableInput) setting).getId())); + } + } + } + //Todo: designated Method + JsonConverter jsonConverter = new JsonConverter(); + jsonConverter.addMixIn(FileInputGenerator.class, FileInputGeneratorMixIn.class); + jsonConverter.addMixIn(TableInputGenerator.class, TableInputGeneratorMixIn.class); + jsonConverter.addMixIn(RelationalInputGenerator.class, RelationalInputGeneratorMixIn.class); + List parameterValuesJson = new ArrayList(); + try { + for(ConfigurationValue config : parameterValues){ + parameterValuesJson.add(jsonConverter.toJsonString(config)); + } + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + + List inputsJson = new ArrayList(); + JsonConverter jsonConverterInput = new JsonConverter(); + for(Input input: inputs){ + try { + inputsJson.add(jsonConverterInput.toJsonString(input)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + } + inputsJson = inputsJson; + executionSetting = new ExecutionSetting(parameterValuesJson, inputsJson, params.getExecutionIdentifier()); + } catch (AlgorithmConfigurationException e) { + e.printStackTrace(); + } + return executionSetting; + } + + @GET + @Path("/stop/{identifier}") + @Produces("application/json") + public void stopExecution(@PathParam("identifier") String executionIdentifier) { + Process process = ProcessRegistry.getInstance().get(executionIdentifier); + ProcessRegistry.getInstance().remove(executionIdentifier); + process.destroy(); + } + + + /** + * Builds an {@link de.metanome.backend.algorithm_execution.AlgorithmExecutor} with stacked {@link de.metanome.algorithm_integration.result_receiver.OmniscientResultReceiver}s to write + * result files and cache results for the frontend. + * + * @param params all parameters for executing the algorithm + * @return an {@link de.metanome.backend.algorithm_execution.AlgorithmExecutor} + * @throws java.io.FileNotFoundException when the result files cannot be opened + * @throws java.io.UnsupportedEncodingException when the temp files cannot be opened + */ + protected AlgorithmExecutor buildExecutor(AlgorithmExecutionParams params) + throws FileNotFoundException, UnsupportedEncodingException { + String identifier = params.getExecutionIdentifier(); + FileGenerator fileGenerator = new TempFileGenerator(); + ProgressCache progressCache = new ProgressCache(); + + ResultReceiver resultReceiver = null; + if (params.getCacheResults()) { + resultReceiver = new ResultCache(identifier); + AlgorithmExecutionCache.add(identifier, (ResultCache) resultReceiver); + } else if (params.getCountResults()) { + resultReceiver = new ResultCounter(identifier); + AlgorithmExecutionCache.add(identifier, (ResultCounter) resultReceiver); + } else if (params.getWriteResults()) { + resultReceiver = new ResultPrinter(identifier); + AlgorithmExecutionCache.add(identifier, (ResultPrinter) resultReceiver); + } + + AlgorithmExecutionCache.add(identifier, progressCache); + + AlgorithmExecutor executor = new AlgorithmExecutor(resultReceiver, progressCache, fileGenerator); + executor.setResultPathPrefix(resultReceiver.getOutputFilePathPrefix()); + + return executor; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getResultCounter(executionIdentifier)` could be null and is dereferenced at line 165. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +EnumMap AlgorithmExecutionResource.getCounterResults(String) + +### Procedure Id: +de.metanome.backend.resources.AlgorithmExecutionResource.getCounterResults(java.lang.String):java.ut.c3a5339cf758596038db11734a662845 + +### File: +backend/src/main/java/de/metanome/backend/resources/AlgorithmExecutionResource.java + +### Key: +AlgorithmExecutionResource.java|getCounterResults|NULL_DEREFERENCE + +### Node Key: +3534744d3537de8ddf14c788351b1bdd + +### Hash: +a8b0230321919718bf7064f2fb364a1e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10870/instruction.md b/inferredbugs-10870/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0f8347af90d34be917ac018a36e42fbf6c4b5f01 --- /dev/null +++ b/inferredbugs-10870/instruction.md @@ -0,0 +1,2432 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rxjava2-jdbc +**Bug ID:** 69 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.davidmoten.rx.jdbc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLSyntaxErrorException; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.log4j.Level; +import org.apache.log4j.LogManager; +import org.davidmoten.rx.jdbc.annotations.Column; +import org.davidmoten.rx.jdbc.annotations.Index; +import org.davidmoten.rx.jdbc.annotations.Query; +import org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.AutomappedInterfaceInaccessibleException; +import org.davidmoten.rx.jdbc.exceptions.ColumnIndexOutOfRangeException; +import org.davidmoten.rx.jdbc.exceptions.ColumnNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.MoreColumnsRequestedThanExistException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterFoundButSqlDoesNotHaveNamesException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterMissingException; +import org.davidmoten.rx.jdbc.exceptions.QueryAnnotationMissingException; +import org.davidmoten.rx.jdbc.pool.DatabaseCreator; +import org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool; +import org.davidmoten.rx.jdbc.pool.Pools; +import org.davidmoten.rx.jdbc.tuple.Tuple2; +import org.davidmoten.rx.jdbc.tuple.Tuple3; +import org.davidmoten.rx.jdbc.tuple.Tuple4; +import org.davidmoten.rx.jdbc.tuple.Tuple5; +import org.davidmoten.rx.jdbc.tuple.Tuple6; +import org.davidmoten.rx.jdbc.tuple.Tuple7; +import org.davidmoten.rx.jdbc.tuple.TupleN; +import org.davidmoten.rx.pool.PoolClosedException; +import org.h2.jdbc.JdbcSQLException; +import org.hsqldb.jdbc.JDBCBlobFile; +import org.hsqldb.jdbc.JDBCClobFile; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.davidmoten.guavamini.Lists; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Observable; +import io.reactivex.Scheduler; +import io.reactivex.Single; +import io.reactivex.functions.Predicate; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subscribers.TestSubscriber; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class DatabaseTest { + + private static final long FRED_REGISTERED_TIME = 1442515672690L; + private static final int NAMES_COUNT_BIG = 5163; + private static final Logger log = LoggerFactory.getLogger(DatabaseTest.class); + private static final int TIMEOUT_SECONDS = 2; + + private static Database db() { + return DatabaseCreator.create(1); + } + + private static Database blocking() { + return DatabaseCreator.createBlocking(); + } + + private static Database db(int poolSize) { + return DatabaseCreator.create(poolSize); + } + + private static Database big(int poolSize) { + return DatabaseCreator.create(poolSize, true, Schedulers.computation()); + } + + @Test + public void testSelectUsingQuestionMark() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNamedParameterList() { + try (Database db = db()) { + db.select("select score from person where name=:name") // + .parameters(Parameter.named("name", "FRED").value("JOSEPH").list()) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameters() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterStream(Flowable.just("FRED", "JOSEPH")) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersInLists() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED"), Arrays.asList("JOSEPH"))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testDrivingSelectWithoutParametersUsingParameterStream() { + try (Database db = db()) { + db.select("select count(*) from person") // + .parameters(1, 2, 3) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterStream(Flowable.just("FRED", 21, "JOSEPH", 34)) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameterListsTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED", 21), Arrays.asList("JOSEPH", 34))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkWithPublicTestingDatabase() { + try (Database db = Database.test()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSize() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(2) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSizeZero() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(0) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectWithFetchSizeNegative() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(-1); + } + } + + @Test + public void testSelectUsingNonBlockingBuilder() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(1, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES) // + .checkoutRetryInterval(1, TimeUnit.SECONDS) // + .healthy(c -> c.prepareStatement("select 1").execute()) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) // + .maxPoolSize(3) // + .build(); + + try (Database db = Database.from(pool)) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test(timeout = 40000) + public void testSelectUsingNonBlockingBuilderConcurrencyTest() + throws InterruptedException, TimeoutException { + info(); + try { + try (Database db = db(3)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(50)); + int n = 10000; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } else { + // log.debug(iCopy + " succeeded"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + } + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test(timeout = 5000) + public void testSelectConcurrencyTest() throws InterruptedException, TimeoutException { + debug(); + try { + try (Database db = db(1)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(2)); + int n = 2; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + log.info("submitted " + i); + } + if (!latch.await(5000, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test + public void testDatabaseClose() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingName() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNameNotGiven() { + try (Database db = db()) { + db // + .select("select score from person where name=:name and name<>:name2") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterMissingException.class) // + .assertNoValues(); + } + } + + @Test + public void testSelectUsingParameterNameNullNameWhenSqlHasNoNames() { + db() // + .select("select score from person where name=?") // + .parameter(Parameter.create("name", "FRED")) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterFoundButSqlDoesNotHaveNamesException.class) // + .assertNoValues(); + } + + @Test + public void testUpdateWithNull() { + try (Database db = db()) { + db // + .update("update person set date_of_birth = :dob") // + .parameter(Parameter.create("dob", null)) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithNull() { + try (Database db = db()) { + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", Database.NULL_CLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithClob() throws SQLException { + try (Database db = db()) { + Clob clob = new JDBCClobFile(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", clob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithReader() throws FileNotFoundException { + try (Database db = db()) { + Reader reader = new FileReader(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", reader) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithBlob() throws SQLException { + try (Database db = db()) { + Blob blob = new JDBCBlobFile(new File("src/test/resources/big.txt")); + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", blob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithNull() { + try (Database db = db()) { + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", Database.NULL_BLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test(expected = NullPointerException.class) + public void testSelectUsingNullNameInParameter() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter(null, "FRED"); // + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameDoesNotExist() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameters("nam", "FRED"); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameters("FRED", "JOSEPH"); + } + } + + @Test + public void testSelectTransacted() { + try (Database db = db()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .getAs(Integer.class) // + .doOnNext(tx -> log + .debug(tx.isComplete() ? "complete" : String.valueOf(tx.value()))) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedAnnotatedTransacted() { + try (Database db = db()) { + db // + .select(Person10.class) // + .transacted() // + .valuesOnly() // + .get().test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedTransactedValuesOnly() { + try (Database db = db()) { + db // + .select("select name, score from person") // + .transacted() // + .valuesOnly() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedTransacted() { + try (Database db = db()) { + db // + .select("select name, score from person") // + .transacted() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + } + + @Test + public void testSelectTransactedTuple2() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + } + } + + @Test + public void testSelectTransactedTuple3() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + } + } + + @Test + public void testSelectTransactedTuple4() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + } + } + + @Test + public void testSelectTransactedTuple5() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + } + } + + @Test + public void testSelectTransactedTuple6() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + } + } + + @Test + public void testSelectTransactedTuple7() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + assertEquals("FRED", t.value()._7()); + } + } + + @Test + public void testSelectTransactedTupleN() { + List>> list = db() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getTupleN() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertEquals("FRED", list.get(0).value().values().get(0)); + assertEquals(21, (int) list.get(0).value().values().get(1)); + assertTrue(list.get(1).isComplete()); + assertEquals(2, list.size()); + } + + @Test + public void testSelectTransactedCount() { + db() // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAs() { + db() // + .select("select name from person") // + .transacted() // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAsOptional() { + List>> list = db() // + .select("select name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAsOptional(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertTrue(list.get(0).isValue()); + assertEquals("FRED", list.get(0).value().get()); + assertTrue(list.get(1).isComplete()); + } + + @Test + public void testDatabaseFrom() { + Database.from(DatabaseCreator.nextUrl(), 3) // + .select("select name from person") // + .getAs(String.class) // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(JdbcSQLException.class); + } + + @Test + public void testSelectTransactedChained() throws Exception { + Database db = db(); + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .transactedValuesOnly() // + .getAs(Integer.class) // + .doOnNext( + tx -> log.debug(tx.isComplete() ? "complete" : String.valueOf(tx.value())))// + .flatMap(tx -> tx // + .select("select name from person where score = ?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + @Test + public void databaseIsAutoCloseable() { + try (Database db = db()) { + log.debug(db.toString()); + } + } + + @Test + public void testSelectChained() { + try (Database db = db(1)) { + // we can do this with 1 connection only! + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .doOnNext(System.out::println) // + .concatMap(score -> { + log.info("score={}", score); + return db // + .select("select name from person where score = ?") // + .parameter(score) // + .getAs(String.class) // + .doOnComplete( + () -> log.info("completed select where score=" + score)); + }) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); // + } + } + + @Test + @SuppressFBWarnings + public void testReadMeFragment1() { + try (Database db = db()) { + db.select("select name from person") // + .getAs(String.class) // + .forEach(System.out::println); + } + } + + @Test + public void testReadMeFragmentColumnDoesNotExistEmitsSqlSyntaxErrorException() { + try (Database db = Database.test()) { + db.select("select nam from person") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(SQLSyntaxErrorException.class); + } + } + + @Test + public void testReadMeFragmentDerbyHealthCheck() { + try (Database db = Database.test()) { + db.select("select 'a' from sysibm.sysdummy1") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("a") // + .assertComplete(); + } + } + + @Test + @SuppressFBWarnings + public void testTupleSupport() { + try (Database db = db()) { + db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .forEach(System.out::println); + } + } + + @Test + public void testDelayedCallsAreNonBlocking() throws InterruptedException { + List list = new CopyOnWriteArrayList(); + try (Database db = db(1)) { // + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> Thread.sleep(1000)) // + .subscribeOn(Schedulers.io()) // + .subscribe(); + Thread.sleep(100); + CountDownLatch latch = new CountDownLatch(1); + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> list.add("emitted")) // + .doOnNext(x -> log.debug("emitted on " + Thread.currentThread().getName())) // + .doOnNext(x -> latch.countDown()) // + .subscribe(); + list.add("subscribed"); + assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + assertEquals(Arrays.asList("subscribed", "emitted"), list); + } + } + + @Test + public void testAutoMapToInterface() { + try (Database db = db()) { + db // + .select("select name from person") // + .autoMap(Person.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithoutAnnotationstsError() { + try (Database db = db()) { + db // + .select("select name from person") // + .autoMap(PersonNoAnnotation.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(AnnotationsNotFoundException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithTwoMethods() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person2.class) // + .firstOrError() // + .map(Person2::score) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnName() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person3.class) // + .firstOrError() // + .map(Person3::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person4.class) // + .firstOrError() // + .map(Person4::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnNotFoundException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithIndex() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person5.class) // + .firstOrError() // + .map(Person5::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithIndexTooLarge() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person6.class) // + .firstOrError() // + .map(Person6::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithIndexTooSmall() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person7.class) // + .firstOrError() // + .map(Person7::examScore) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + } + + @Test + public void testAutoMapWithUnmappableColumnType() { + try (Database db = db()) { + db // + .select("select name from person order by name") // + .autoMap(Person8.class) // + .map(p -> p.name()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ClassCastException.class); + } + } + + @Test + public void testAutoMapWithMixIndexAndName() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person9.class) // + .firstOrError() // + .map(Person9::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapWithQueryInAnnotation() { + try (Database db = db()) { + db.select(Person10.class) // + .get() // + .firstOrError() // + .map(Person10::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + @Ignore + public void testAutoMapForReadMe() { + Database // + .test() // + .select(Person10.class) // + .get(Person10::name) // + .blockingForEach(System.out::println); + } + + @Test(expected = QueryAnnotationMissingException.class) + public void testAutoMapWithoutQueryInAnnotation() { + try (Database db = db()) { + db.select(Person.class); + } + } + + @Test + public void testSelectWithoutWhereClause() { + try (Database db = db()) { + Assert.assertEquals(3, (long) db.select("select name from person") // + .count() // + .blockingGet()); + } + } + + @Test + public void testTuple3() { + try (Database db = db()) { + db // + .select("select name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple3.create("FRED", 21, "FRED")); // + } + } + + @Test + public void testTuple4() { + try (Database db = db()) { + db // + .select("select name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple4.create("FRED", 21, "FRED", 21)); // + } + } + + @Test + public void testTuple5() { + db() // + .select("select name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple5.create("FRED", 21, "FRED", 21, "FRED")); // + } + + @Test + public void testTuple6() { + db() // + .select("select name, score, name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21)); // + } + + @Test + public void testTuple7() { + db() // + .select("select name, score, name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() + .assertValue(Tuple7.create("FRED", 21, "FRED", 21, "FRED", 21, "FRED")); // + } + + @Test + public void testTupleN() { + db() // + .select("select name, score, name from person order by name") // + .getTupleN() // + .firstOrError().test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(TupleN.create("FRED", 21, "FRED")); // + } + + @Test + public void testHealthCheck() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + return !once.compareAndSet(true, false); + }); + } + + @Test + public void testHealthCheckThatThrows() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + if (!once.compareAndSet(true, false)) + return true; + else + throw new RuntimeException("health check failed"); + }); + } + + @Test + public void testUpdateOneRow() { + db().update("update person set score=20 where name='FRED'") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateThreeRows() { + db().update("update person set score=20") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + + @Test + public void testUpdateWithParameter() { + db().update("update person set score=20 where name=?") // + .parameter("FRED").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateWithParameterTwoRuns() { + db().update("update person set score=20 where name=?") // + .parameters("FRED", "JOSEPH").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + } + + @Test + public void testUpdateAllWithParameterFourRuns() { + db().update("update person set score=?") // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testUpdateWithBatchSize2() { + db().update("update person set score=?") // + .batchSize(2) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testUpdateWithBatchSize3GreaterThanNumRecords() { + db().update("update person set score=?") // + .batchSize(3) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testInsert() { + Database db = db(); + db.update("insert into person(name, score) values(?,?)") // + .parameters("DAVE", 12, "ANNE", 18) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + List> list = db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .toList() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingGet(); + assertTrue(list.contains(Tuple2.create("DAVE", 12))); + assertTrue(list.contains(Tuple2.create("ANNE", 18))); + } + + @Test + public void testReturnGeneratedKeys() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + + @Test + public void testReturnGeneratedKeysDerby() { + Database db = DatabaseCreator.createDerby(1); + + // note is a table with auto increment + db.update("insert into note2(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors().assertValues(1, 3) // + .assertComplete(); + + db.update("insert into note2(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(5, 7) // + .assertComplete(); + } + + @Test(expected = IllegalArgumentException.class) + public void testReturnGeneratedKeysWithBatchSizeShouldThrow() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .batchSize(2) // + .returnGeneratedKeys(); + } + + @Test + public void testTransactedReturnGeneratedKeys() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + + @Test + public void testTransactedReturnGeneratedKeys2() { + Database db = db(); + // note is a table with auto increment + Flowable a = db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .startWith(a) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2, 3, 4) // + .assertComplete(); + } + + @Test + public void testUpdateWithinTransaction() { + db() // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnFlowable() { + Database db = db(); + Flowable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnObservable() { + Database db = db(); + Observable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().toObservable(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnOnSingle() { + Database db = db(); + Single a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().count(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnCompletable() { + Database db = db(); + Completable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().ignoreElements(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testUpdateWithinTransactionBatchSize0() { + db() // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(0) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + + private static void info() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + private static void debug() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + @Test + public void testCreateBig() { + info(); + big(5).select("select count(*) from person") // + .getAs(Integer.class) // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue(5163) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBig() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBigInputBatchSize2000() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(2000) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testInsertNullClobAndReadClobAsString() { + Database db = db(); + insertNullClob(db); + db.select("select document from person_clob where name='FRED'") // + .getAsOptional(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Optional.empty()) // + .assertComplete(); + } + + private static void insertNullClob(Database db) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", Database.NULL_CLOB) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testClobMethod() { + assertEquals(Database.NULL_CLOB, Database.clob(null)); + } + + @Test + public void testBlobMethod() { + assertEquals(Database.NULL_BLOB, Database.blob(null)); + } + + @Test + public void testClobMethodPresent() { + assertEquals("a", Database.clob("a")); + } + + @Test + public void testBlobMethodPresent() { + byte[] b = new byte[1]; + assertEquals(b, Database.blob(b)); + } + + @Test + public void testDateOfBirthNullableForReadMe() { + Database.test() // + .select("select date_of_birth from person where name='FRED'") // + .getAsOptional(Instant.class) // + .blockingForEach(System.out::println); + } + + @Test + public void testInsertNullClobAndReadClobAsTuple2() { + Database db = db(); + insertNullClob(db); + db.select("select document, document from person_clob where name='FRED'") // + .getAs(String.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Tuple2.create(null, null)) // + .assertComplete(); + } + + @Test + public void testInsertClobAndReadClobAsString() { + Database db = db(); + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue("some + // text + // here") + // // + .assertComplete(); + } + + @Test + public void testInsertClobAndReadClobUsingReader() { + Database db = db(); + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(Reader.class) // + .map(r -> read(r)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsByteArray() { + Database db = db(); + insertPersonBlob(db); + db.select("select document from person_blob where name='FRED'") // + .getAs(byte[].class) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + private static void insertPersonBlob(Database db) { + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", bytes) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsInputStream() { + Database db = db(); + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", new ByteArrayInputStream(bytes)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_blob where name='FRED'") // + .getAs(InputStream.class) // + .map(is -> read(is)) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + private static String read(Reader reader) throws IOException { + StringBuffer s = new StringBuffer(); + char[] ch = new char[128]; + int n = 0; + while ((n = reader.read(ch)) != -1) { + s.append(ch, 0, n); + } + reader.close(); + return s.toString(); + } + + private static byte[] read(InputStream is) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] b = new byte[128]; + int n = 0; + while ((n = is.read(b)) != -1) { + bytes.write(b, 0, n); + } + is.close(); + return bytes.toByteArray(); + } + + private void testHealthCheck(Predicate healthy) throws InterruptedException { + TestScheduler scheduler = new TestScheduler(); + + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(10, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) // + .healthy(healthy) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) // + .scheduler(scheduler) // + .maxPoolSize(1) // + .build(); + + try (Database db = Database.from(pool)) { + TestSubscriber ts0 = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test(); + ts0.assertValueCount(0) // + .assertNotComplete(); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + ts0.assertValueCount(1) // + .assertComplete(); + TestSubscriber ts = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test() // + .assertValueCount(0); + log.debug("done2"); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + Thread.sleep(200); + ts.assertValueCount(1); + Thread.sleep(200); + ts.assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testShutdownBeforeUse() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .scheduler(Schedulers.io()) // + .maxPoolSize(1) // + .build(); + pool.close(); + Database.from(pool) // + .select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(PoolClosedException.class); + } + + @Test + public void testFewerColumnsMappedThanAvailable() { + db().select("select name, score from person where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues("FRED") // + .assertComplete(); + } + + @Test + public void testMoreColumnsMappedThanAvailable() { + db() // + .select("select name, score from person where name='FRED'") // + .getAs(String.class, Integer.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(MoreColumnsRequestedThanExistException.class); + } + + @Test + public void testSelectTimestamp() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsDate() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Date.class) // + .map(d -> d.getTime()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsInstant() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Instant.class) // + .map(d -> d.toEpochMilli()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateCalendarParameter() { + Calendar c = GregorianCalendar.from(ZonedDateTime.parse("2017-03-25T15:37Z")); + Database db = db(); + db.update("update person set registered=?") // + .parameter(c) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(c.getTimeInMillis()) // + .assertComplete(); + } + + @Test + public void testUpdateTimeParameter() { + Database db = db(); + Time t = new Time(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampParameter() { + Database db = db(); + Timestamp t = new Timestamp(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateSqlDateParameter() { + Database db = db(); + java.sql.Date t = new java.sql.Date(1234); + + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS * 10000, TimeUnit.SECONDS) // + // TODO make a more accurate comparison using the current TZ + .assertValue(x -> Math.abs(x - 1234) <= TimeUnit.HOURS.toMillis(24)) // + .assertComplete(); + } + + @Test + public void testUpdateUtilDateParameter() { + Database db = db(); + Date d = new Date(1234); + db.update("update person set registered=?") // + .parameter(d) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampAsInstant() { + Database db = db(); + db.update("update person set registered=? where name='FRED'") // + .parameter(Instant.ofEpochMilli(FRED_REGISTERED_TIME)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampAsZonedDateTime() { + Database db = db(); + db.update("update person set registered=? where name='FRED'") // + .parameter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(FRED_REGISTERED_TIME), + ZoneOffset.UTC.normalized())) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testCompleteCompletes() { + Database db = db(1); + db // + .update("update person set score=-3 where name='FRED'") // + .complete() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingAwait(); + + int score = db.select("select score from person where name='FRED'") // + .getAs(Integer.class) // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingFirst(); + assertEquals(-3, score); + } + + @Test + public void testComplete() throws InterruptedException { + Database db = db(1); + Completable a = db // + .update("update person set score=-3 where name='FRED'") // + .complete(); + db.update("update person set score=-4 where score = -3") // + .dependsOn(a) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testCountsOnlyInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .countsOnly() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3) // + .assertComplete(); + } + + @Test + public void testCountsInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .counts() // + .doOnNext(System.out::println) // + .toList() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3 + && list.get(1).isComplete() && list.size() == 2) // + .assertComplete(); + } + + @Test + public void testTx() throws InterruptedException { + Database db = db(3); + Single> transaction = db // + .update("update person set score=-3 where name='FRED'") // + .transaction(); + + transaction // + .doOnDispose(() -> log.debug("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + log.debug("flatmapping"); + return tx // + .update("update person set score = -4 where score = -3") // + .countsOnly() // + .doOnSubscribe(s -> log.debug("subscribed")) // + .doOnNext(num -> log.debug("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testTxAfterSelect() { + Database db = db(3); + Single> transaction = db // + .select("select score from person where name='FRED'") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .firstOrError(); + + transaction // + .doOnDispose(() -> log.debug("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + log.debug("flatmapping"); + return tx // + .update("update person set score = -4 where score = ?") // + .parameter(tx.value()) // + .countsOnly() // + .doOnSubscribe(s -> log.debug("subscribed")) // + .doOnNext(num -> log.debug("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testSingleFlatMap() { + Single.just(1).flatMapPublisher(n -> Flowable.just(1)).test(1).assertValue(1) + .assertComplete(); + } + + @Test + public void testAutomappedInstanceHasMeaningfulToStringMethod() { + info(); + String s = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.toString()) // + .blockingSingle(); + assertEquals("Person2[name=FRED, score=21]", s); + } + + @Test + public void testAutomappedEquals() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(x)) // + .blockingSingle(); + assertTrue(b); + } + + @Test + public void testAutomappedDoesNotEqualNull() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(null)) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedDoesNotEqual() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(new Object())) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedHashCode() { + Person2 p = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .blockingSingle(); + assertTrue(p.hashCode() != 0); + } + + @Test + public void testAutomappedWithParametersThatProvokesMoreThanOneQuery() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(2) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsAndHashCodeIsDistinctOnValues() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .distinct() // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsDifferentiatesDifferentInterfacesWithSameMethodNamesAndValues() { + PersonDistinct1 p1 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct1.class) // + .blockingFirst(); + + PersonDistinct2 p2 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct2.class) // + .blockingFirst(); + + assertNotEquals(p1, p2); + } + + @Test + public void testAutomappedObjectsWhenDefaultMethodInvoked() { + PersonWithDefaultMethod p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethod.class) // + .blockingFirst(); + assertEquals("fred", p.nameLower()); + } + + // @Test + // public void testDefaultMethod() throws NoSuchMethodException, + // IllegalAccessException { + // MethodHandles.lookup().findSpecial(PersonWithDefaultMethod.class, + // "nameLower", + // MethodType.methodType(String.class, new Class[] {}), + // PersonWithDefaultMethod.class) + //// .bindTo(x); + // } + + @Test(expected = AutomappedInterfaceInaccessibleException.class) + public void testAutomappedObjectsWhenDefaultMethodInvokedAndIsNonPublicThrows() { + PersonWithDefaultMethodNonPublic p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethodNonPublic.class) // + .blockingFirst(); + p.nameLower(); + } + + @Test + public void testBlockingDatabase() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransacted() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .map(x -> x.value()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransactedNested() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .flatMap(tx -> tx.select("select name from person where score=?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + public interface PersonWithDefaultMethod { + @Column + String name(); + + @Column + int score(); + + public default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonWithDefaultMethodNonPublic { + @Column + String name(); + + @Column + int score(); + + default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonDistinct1 { + @Column + String name(); + + @Column + int score(); + + } + + interface PersonDistinct2 { + @Column + String name(); + + @Column + int score(); + + } + + interface Score { + @Column + int score(); + } + + interface Person { + @Column + String name(); + } + + interface Person2 { + @Column + String name(); + + @Column + int score(); + } + + interface Person3 { + @Column("name") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person4 { + @Column("namez") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person5 { + @Index(1) + String fullName(); + + @Index(2) + int examScore(); + } + + interface Person6 { + @Index(1) + String fullName(); + + @Index(3) + int examScore(); + } + + interface Person7 { + @Index(1) + String fullName(); + + @Index(0) + int examScore(); + } + + interface Person8 { + @Column + int name(); + } + + interface Person9 { + @Column + String name(); + + @Index(2) + int score(); + } + + interface PersonNoAnnotation { + String name(); + } + + @Query("select name, score from person order by name") + interface Person10 { + + @Column + String name(); + + @Column + int score(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.davidmoten.rx.jdbc.Database` acquired by call to `db()` at line 1281 is not released after line 1293. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DatabaseTest.testReturnGeneratedKeys() + +### Procedure Id: +org.davidmoten.rx.jdbc.DatabaseTest.testReturnGeneratedKeys():void.f84200f62e0e80aef84def189e859b23 + +### File: +src/test/java/org/davidmoten/rx/jdbc/DatabaseTest.java + +### Key: +DatabaseTest.java|testReturnGeneratedKeys|RESOURCE_LEAK + +### Node Key: +b1e1d2e868cbf5fb020e794c7723980b + +### Hash: +93e1dc204c75e0b0f549225a753b4136 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10871/instruction.md b/inferredbugs-10871/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bf1eda1729ed9aa04f0625dbb24f4d38063e191e --- /dev/null +++ b/inferredbugs-10871/instruction.md @@ -0,0 +1,2410 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rxjava2-jdbc +**Bug ID:** 56 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.davidmoten.rx.jdbc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLSyntaxErrorException; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.log4j.Level; +import org.apache.log4j.LogManager; +import org.davidmoten.rx.jdbc.annotations.Column; +import org.davidmoten.rx.jdbc.annotations.Index; +import org.davidmoten.rx.jdbc.annotations.Query; +import org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.AutomappedInterfaceInaccessibleException; +import org.davidmoten.rx.jdbc.exceptions.ColumnIndexOutOfRangeException; +import org.davidmoten.rx.jdbc.exceptions.ColumnNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.MoreColumnsRequestedThanExistException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterFoundButSqlDoesNotHaveNamesException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterMissingException; +import org.davidmoten.rx.jdbc.exceptions.QueryAnnotationMissingException; +import org.davidmoten.rx.jdbc.pool.DatabaseCreator; +import org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool; +import org.davidmoten.rx.jdbc.pool.Pools; +import org.davidmoten.rx.jdbc.tuple.Tuple2; +import org.davidmoten.rx.jdbc.tuple.Tuple3; +import org.davidmoten.rx.jdbc.tuple.Tuple4; +import org.davidmoten.rx.jdbc.tuple.Tuple5; +import org.davidmoten.rx.jdbc.tuple.Tuple6; +import org.davidmoten.rx.jdbc.tuple.Tuple7; +import org.davidmoten.rx.jdbc.tuple.TupleN; +import org.davidmoten.rx.pool.PoolClosedException; +import org.h2.jdbc.JdbcSQLException; +import org.hsqldb.jdbc.JDBCBlobFile; +import org.hsqldb.jdbc.JDBCClobFile; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.davidmoten.guavamini.Lists; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Observable; +import io.reactivex.Scheduler; +import io.reactivex.Single; +import io.reactivex.functions.Predicate; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subscribers.TestSubscriber; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class DatabaseTest { + + private static final long FRED_REGISTERED_TIME = 1442515672690L; + private static final int NAMES_COUNT_BIG = 5163; + private static final Logger log = LoggerFactory.getLogger(DatabaseTest.class); + private static final int TIMEOUT_SECONDS = 2; + + private static Database db() { + return DatabaseCreator.create(1); + } + + private static Database blocking() { + return DatabaseCreator.createBlocking(); + } + + private static Database db(int poolSize) { + return DatabaseCreator.create(poolSize); + } + + private static Database big(int poolSize) { + return DatabaseCreator.create(poolSize, true, Schedulers.computation()); + } + + @Test + public void testSelectUsingQuestionMark() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNamedParameterList() { + try (Database db = db()) { + db.select("select score from person where name=:name") // + .parameters(Parameter.named("name", "FRED").value("JOSEPH").list()) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameters() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterStream(Flowable.just("FRED", "JOSEPH")) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersInLists() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED"), Arrays.asList("JOSEPH"))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testDrivingSelectWithoutParametersUsingParameterStream() { + try (Database db = db()) { + db.select("select count(*) from person") // + .parameters(1, 2, 3) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterStream(Flowable.just("FRED", 21, "JOSEPH", 34)) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameterListsTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED", 21), Arrays.asList("JOSEPH", 34))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkWithPublicTestingDatabase() { + try (Database db = Database.test()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSize() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(2) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSizeZero() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(0) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectWithFetchSizeNegative() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(-1); + } + } + + @Test + public void testSelectUsingNonBlockingBuilder() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(1, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES) // + .checkoutRetryInterval(1, TimeUnit.SECONDS) // + .healthy(c -> c.prepareStatement("select 1").execute()) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) // + .maxPoolSize(3) // + .build(); + + try (Database db = Database.from(pool)) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test(timeout = 40000) + public void testSelectUsingNonBlockingBuilderConcurrencyTest() + throws InterruptedException, TimeoutException { + info(); + try { + try (Database db = db(3)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(50)); + int n = 10000; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } else { + // log.debug(iCopy + " succeeded"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + } + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test(timeout = 5000) + public void testSelectConcurrencyTest() throws InterruptedException, TimeoutException { + debug(); + try { + try (Database db = db(1)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(2)); + int n = 2; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + log.info("submitted " + i); + } + if (!latch.await(5000, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test + public void testDatabaseClose() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingName() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNameNotGiven() { + try (Database db = db()) { + db // + .select("select score from person where name=:name and name<>:name2") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterMissingException.class) // + .assertNoValues(); + } + } + + @Test + public void testSelectUsingParameterNameNullNameWhenSqlHasNoNames() { + db() // + .select("select score from person where name=?") // + .parameter(Parameter.create("name", "FRED")) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterFoundButSqlDoesNotHaveNamesException.class) // + .assertNoValues(); + } + + @Test + public void testUpdateWithNull() { + try (Database db = db()) { + db // + .update("update person set date_of_birth = :dob") // + .parameter(Parameter.create("dob", null)) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithNull() { + try (Database db = db()) { + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", Database.NULL_CLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithClob() throws SQLException { + try (Database db = db()) { + Clob clob = new JDBCClobFile(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", clob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithReader() throws FileNotFoundException { + try (Database db = db()) { + Reader reader = new FileReader(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", reader) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithBlob() throws SQLException { + try (Database db = db()) { + Blob blob = new JDBCBlobFile(new File("src/test/resources/big.txt")); + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", blob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithNull() { + try (Database db = db()) { + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", Database.NULL_BLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test(expected = NullPointerException.class) + public void testSelectUsingNullNameInParameter() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter(null, "FRED"); // + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameDoesNotExist() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameters("nam", "FRED"); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameters("FRED", "JOSEPH"); + } + } + + @Test + public void testSelectTransacted() { + try (Database db = db()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .getAs(Integer.class) // + .doOnNext(tx -> log + .debug(tx.isComplete() ? "complete" : String.valueOf(tx.value()))) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedAnnotatedTransacted() { + try (Database db = db()) { + db // + .select(Person10.class) // + .transacted() // + .valuesOnly() // + .get().test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedTransactedValuesOnly() { + try (Database db = db()) { + db // + .select("select name, score from person") // + .transacted() // + .valuesOnly() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedTransacted() { + try (Database db = db()) { + db // + .select("select name, score from person") // + .transacted() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + } + + @Test + public void testSelectTransactedTuple2() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + } + } + + @Test + public void testSelectTransactedTuple3() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + } + } + + @Test + public void testSelectTransactedTuple4() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + } + } + + @Test + public void testSelectTransactedTuple5() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + } + } + + @Test + public void testSelectTransactedTuple6() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + } + } + + @Test + public void testSelectTransactedTuple7() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + assertEquals("FRED", t.value()._7()); + } + } + + @Test + public void testSelectTransactedTupleN() { + List>> list = db() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getTupleN() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertEquals("FRED", list.get(0).value().values().get(0)); + assertEquals(21, (int) list.get(0).value().values().get(1)); + assertTrue(list.get(1).isComplete()); + assertEquals(2, list.size()); + } + + @Test + public void testSelectTransactedCount() { + db() // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAs() { + db() // + .select("select name from person") // + .transacted() // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAsOptional() { + List>> list = db() // + .select("select name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAsOptional(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertTrue(list.get(0).isValue()); + assertEquals("FRED", list.get(0).value().get()); + assertTrue(list.get(1).isComplete()); + } + + @Test + public void testDatabaseFrom() { + Database.from(DatabaseCreator.nextUrl(), 3) // + .select("select name from person") // + .getAs(String.class) // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(JdbcSQLException.class); + } + + @Test + public void testSelectTransactedChained() throws Exception { + Database db = db(); + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .transactedValuesOnly() // + .getAs(Integer.class) // + .doOnNext( + tx -> log.debug(tx.isComplete() ? "complete" : String.valueOf(tx.value())))// + .flatMap(tx -> tx // + .select("select name from person where score = ?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + @Test + public void databaseIsAutoCloseable() { + try (Database db = db()) { + log.debug(db.toString()); + } + } + + @Test + public void testSelectChained() { + try (Database db = db(1)) { + // we can do this with 1 connection only! + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .doOnNext(System.out::println) // + .concatMap(score -> { + log.info("score={}", score); + return db // + .select("select name from person where score = ?") // + .parameter(score) // + .getAs(String.class) // + .doOnComplete( + () -> log.info("completed select where score=" + score)); + }) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); // + } + } + + @Test + @SuppressFBWarnings + public void testReadMeFragment1() { + try (Database db = db()) { + db.select("select name from person") // + .getAs(String.class) // + .forEach(System.out::println); + } + } + + @Test + public void testReadMeFragmentColumnDoesNotExistEmitsSqlSyntaxErrorException() { + try (Database db = Database.test()) { + db.select("select nam from person") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(SQLSyntaxErrorException.class); + } + } + + @Test + public void testReadMeFragmentDerbyHealthCheck() { + try (Database db = Database.test()) { + db.select("select 'a' from sysibm.sysdummy1") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("a") // + .assertComplete(); + } + } + + @Test + @SuppressFBWarnings + public void testTupleSupport() { + try (Database db = db()) { + db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .forEach(System.out::println); + } + } + + @Test + public void testDelayedCallsAreNonBlocking() throws InterruptedException { + List list = new CopyOnWriteArrayList(); + try (Database db = db(1)) { // + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> Thread.sleep(1000)) // + .subscribeOn(Schedulers.io()) // + .subscribe(); + Thread.sleep(100); + CountDownLatch latch = new CountDownLatch(1); + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> list.add("emitted")) // + .doOnNext(x -> log.debug("emitted on " + Thread.currentThread().getName())) // + .doOnNext(x -> latch.countDown()) // + .subscribe(); + list.add("subscribed"); + assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + assertEquals(Arrays.asList("subscribed", "emitted"), list); + } + } + + @Test + public void testAutoMapToInterface() { + try (Database db = db()) { + db // + .select("select name from person") // + .autoMap(Person.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithoutAnnotationstsError() { + try (Database db = db()) { + db // + .select("select name from person") // + .autoMap(PersonNoAnnotation.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(AnnotationsNotFoundException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithTwoMethods() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person2.class) // + .firstOrError() // + .map(Person2::score) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnName() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person3.class) // + .firstOrError() // + .map(Person3::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person4.class) // + .firstOrError() // + .map(Person4::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnNotFoundException.class); + } + + @Test + public void testAutoMapToInterfaceWithIndex() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person5.class) // + .firstOrError() // + .map(Person5::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapToInterfaceWithIndexTooLarge() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person6.class) // + .firstOrError() // + .map(Person6::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + + @Test + public void testAutoMapToInterfaceWithIndexTooSmall() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person7.class) // + .firstOrError() // + .map(Person7::examScore) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + + @Test + public void testAutoMapWithUnmappableColumnType() { + db() // + .select("select name from person order by name") // + .autoMap(Person8.class) // + .map(p -> p.name()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ClassCastException.class); + } + + @Test + public void testAutoMapWithMixIndexAndName() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person9.class) // + .firstOrError() // + .map(Person9::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapWithQueryInAnnotation() { + db().select(Person10.class) // + .get() // + .firstOrError() // + .map(Person10::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + @Ignore + public void testAutoMapForReadMe() { + Database // + .test() // + .select(Person10.class) // + .get(Person10::name) // + .blockingForEach(System.out::println); + } + + @Test(expected = QueryAnnotationMissingException.class) + public void testAutoMapWithoutQueryInAnnotation() { + db().select(Person.class); + } + + @Test + public void testSelectWithoutWhereClause() { + Assert.assertEquals(3, (long) db().select("select name from person") // + .count() // + .blockingGet()); + } + + @Test + public void testTuple3() { + db() // + .select("select name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple3.create("FRED", 21, "FRED")); // + } + + @Test + public void testTuple4() { + db() // + .select("select name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple4.create("FRED", 21, "FRED", 21)); // + } + + @Test + public void testTuple5() { + db() // + .select("select name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple5.create("FRED", 21, "FRED", 21, "FRED")); // + } + + @Test + public void testTuple6() { + db() // + .select("select name, score, name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21)); // + } + + @Test + public void testTuple7() { + db() // + .select("select name, score, name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() + .assertValue(Tuple7.create("FRED", 21, "FRED", 21, "FRED", 21, "FRED")); // + } + + @Test + public void testTupleN() { + db() // + .select("select name, score, name from person order by name") // + .getTupleN() // + .firstOrError().test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(TupleN.create("FRED", 21, "FRED")); // + } + + @Test + public void testHealthCheck() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + return !once.compareAndSet(true, false); + }); + } + + @Test + public void testHealthCheckThatThrows() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + if (!once.compareAndSet(true, false)) + return true; + else + throw new RuntimeException("health check failed"); + }); + } + + @Test + public void testUpdateOneRow() { + db().update("update person set score=20 where name='FRED'") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateThreeRows() { + db().update("update person set score=20") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + + @Test + public void testUpdateWithParameter() { + db().update("update person set score=20 where name=?") // + .parameter("FRED").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateWithParameterTwoRuns() { + db().update("update person set score=20 where name=?") // + .parameters("FRED", "JOSEPH").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + } + + @Test + public void testUpdateAllWithParameterFourRuns() { + db().update("update person set score=?") // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testUpdateWithBatchSize2() { + db().update("update person set score=?") // + .batchSize(2) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testUpdateWithBatchSize3GreaterThanNumRecords() { + db().update("update person set score=?") // + .batchSize(3) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testInsert() { + Database db = db(); + db.update("insert into person(name, score) values(?,?)") // + .parameters("DAVE", 12, "ANNE", 18) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + List> list = db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .toList() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingGet(); + assertTrue(list.contains(Tuple2.create("DAVE", 12))); + assertTrue(list.contains(Tuple2.create("ANNE", 18))); + } + + @Test + public void testReturnGeneratedKeys() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + + @Test + public void testReturnGeneratedKeysDerby() { + Database db = DatabaseCreator.createDerby(1); + + // note is a table with auto increment + db.update("insert into note2(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors().assertValues(1, 3) // + .assertComplete(); + + db.update("insert into note2(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(5, 7) // + .assertComplete(); + } + + @Test(expected = IllegalArgumentException.class) + public void testReturnGeneratedKeysWithBatchSizeShouldThrow() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .batchSize(2) // + .returnGeneratedKeys(); + } + + @Test + public void testTransactedReturnGeneratedKeys() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + + @Test + public void testTransactedReturnGeneratedKeys2() { + Database db = db(); + // note is a table with auto increment + Flowable a = db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .startWith(a) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2, 3, 4) // + .assertComplete(); + } + + @Test + public void testUpdateWithinTransaction() { + db() // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnFlowable() { + Database db = db(); + Flowable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnObservable() { + Database db = db(); + Observable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().toObservable(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnOnSingle() { + Database db = db(); + Single a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().count(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnCompletable() { + Database db = db(); + Completable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().ignoreElements(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testUpdateWithinTransactionBatchSize0() { + db() // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(0) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + + private static void info() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + private static void debug() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + @Test + public void testCreateBig() { + info(); + big(5).select("select count(*) from person") // + .getAs(Integer.class) // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue(5163) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBig() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBigInputBatchSize2000() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(2000) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testInsertNullClobAndReadClobAsString() { + Database db = db(); + insertNullClob(db); + db.select("select document from person_clob where name='FRED'") // + .getAsOptional(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Optional.empty()) // + .assertComplete(); + } + + private static void insertNullClob(Database db) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", Database.NULL_CLOB) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testClobMethod() { + assertEquals(Database.NULL_CLOB, Database.clob(null)); + } + + @Test + public void testBlobMethod() { + assertEquals(Database.NULL_BLOB, Database.blob(null)); + } + + @Test + public void testClobMethodPresent() { + assertEquals("a", Database.clob("a")); + } + + @Test + public void testBlobMethodPresent() { + byte[] b = new byte[1]; + assertEquals(b, Database.blob(b)); + } + + @Test + public void testDateOfBirthNullableForReadMe() { + Database.test() // + .select("select date_of_birth from person where name='FRED'") // + .getAsOptional(Instant.class) // + .blockingForEach(System.out::println); + } + + @Test + public void testInsertNullClobAndReadClobAsTuple2() { + Database db = db(); + insertNullClob(db); + db.select("select document, document from person_clob where name='FRED'") // + .getAs(String.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Tuple2.create(null, null)) // + .assertComplete(); + } + + @Test + public void testInsertClobAndReadClobAsString() { + Database db = db(); + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue("some + // text + // here") + // // + .assertComplete(); + } + + @Test + public void testInsertClobAndReadClobUsingReader() { + Database db = db(); + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(Reader.class) // + .map(r -> read(r)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsByteArray() { + Database db = db(); + insertPersonBlob(db); + db.select("select document from person_blob where name='FRED'") // + .getAs(byte[].class) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + private static void insertPersonBlob(Database db) { + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", bytes) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsInputStream() { + Database db = db(); + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", new ByteArrayInputStream(bytes)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_blob where name='FRED'") // + .getAs(InputStream.class) // + .map(is -> read(is)) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + private static String read(Reader reader) throws IOException { + StringBuffer s = new StringBuffer(); + char[] ch = new char[128]; + int n = 0; + while ((n = reader.read(ch)) != -1) { + s.append(ch, 0, n); + } + reader.close(); + return s.toString(); + } + + private static byte[] read(InputStream is) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] b = new byte[128]; + int n = 0; + while ((n = is.read(b)) != -1) { + bytes.write(b, 0, n); + } + is.close(); + return bytes.toByteArray(); + } + + private void testHealthCheck(Predicate healthy) throws InterruptedException { + TestScheduler scheduler = new TestScheduler(); + + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(10, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) // + .healthy(healthy) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) // + .scheduler(scheduler) // + .maxPoolSize(1) // + .build(); + + try (Database db = Database.from(pool)) { + TestSubscriber ts0 = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test(); + ts0.assertValueCount(0) // + .assertNotComplete(); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + ts0.assertValueCount(1) // + .assertComplete(); + TestSubscriber ts = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test() // + .assertValueCount(0); + log.debug("done2"); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + Thread.sleep(200); + ts.assertValueCount(1); + Thread.sleep(200); + ts.assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testShutdownBeforeUse() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .scheduler(Schedulers.io()) // + .maxPoolSize(1) // + .build(); + pool.close(); + Database.from(pool) // + .select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(PoolClosedException.class); + } + + @Test + public void testFewerColumnsMappedThanAvailable() { + db().select("select name, score from person where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues("FRED") // + .assertComplete(); + } + + @Test + public void testMoreColumnsMappedThanAvailable() { + db() // + .select("select name, score from person where name='FRED'") // + .getAs(String.class, Integer.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(MoreColumnsRequestedThanExistException.class); + } + + @Test + public void testSelectTimestamp() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsDate() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Date.class) // + .map(d -> d.getTime()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsInstant() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Instant.class) // + .map(d -> d.toEpochMilli()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateCalendarParameter() { + Calendar c = GregorianCalendar.from(ZonedDateTime.parse("2017-03-25T15:37Z")); + Database db = db(); + db.update("update person set registered=?") // + .parameter(c) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(c.getTimeInMillis()) // + .assertComplete(); + } + + @Test + public void testUpdateTimeParameter() { + Database db = db(); + Time t = new Time(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampParameter() { + Database db = db(); + Timestamp t = new Timestamp(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateSqlDateParameter() { + Database db = db(); + java.sql.Date t = new java.sql.Date(1234); + + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS * 10000, TimeUnit.SECONDS) // + // TODO make a more accurate comparison using the current TZ + .assertValue(x -> Math.abs(x - 1234) <= TimeUnit.HOURS.toMillis(24)) // + .assertComplete(); + } + + @Test + public void testUpdateUtilDateParameter() { + Database db = db(); + Date d = new Date(1234); + db.update("update person set registered=?") // + .parameter(d) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampAsInstant() { + Database db = db(); + db.update("update person set registered=? where name='FRED'") // + .parameter(Instant.ofEpochMilli(FRED_REGISTERED_TIME)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampAsZonedDateTime() { + Database db = db(); + db.update("update person set registered=? where name='FRED'") // + .parameter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(FRED_REGISTERED_TIME), + ZoneOffset.UTC.normalized())) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testCompleteCompletes() { + Database db = db(1); + db // + .update("update person set score=-3 where name='FRED'") // + .complete() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingAwait(); + + int score = db.select("select score from person where name='FRED'") // + .getAs(Integer.class) // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingFirst(); + assertEquals(-3, score); + } + + @Test + public void testComplete() throws InterruptedException { + Database db = db(1); + Completable a = db // + .update("update person set score=-3 where name='FRED'") // + .complete(); + db.update("update person set score=-4 where score = -3") // + .dependsOn(a) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testCountsOnlyInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .countsOnly() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3) // + .assertComplete(); + } + + @Test + public void testCountsInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .counts() // + .doOnNext(System.out::println) // + .toList() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3 + && list.get(1).isComplete() && list.size() == 2) // + .assertComplete(); + } + + @Test + public void testTx() throws InterruptedException { + Database db = db(3); + Single> transaction = db // + .update("update person set score=-3 where name='FRED'") // + .transaction(); + + transaction // + .doOnDispose(() -> log.debug("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + log.debug("flatmapping"); + return tx // + .update("update person set score = -4 where score = -3") // + .countsOnly() // + .doOnSubscribe(s -> log.debug("subscribed")) // + .doOnNext(num -> log.debug("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testTxAfterSelect() { + Database db = db(3); + Single> transaction = db // + .select("select score from person where name='FRED'") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .firstOrError(); + + transaction // + .doOnDispose(() -> log.debug("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + log.debug("flatmapping"); + return tx // + .update("update person set score = -4 where score = ?") // + .parameter(tx.value()) // + .countsOnly() // + .doOnSubscribe(s -> log.debug("subscribed")) // + .doOnNext(num -> log.debug("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testSingleFlatMap() { + Single.just(1).flatMapPublisher(n -> Flowable.just(1)).test(1).assertValue(1) + .assertComplete(); + } + + @Test + public void testAutomappedInstanceHasMeaningfulToStringMethod() { + info(); + String s = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.toString()) // + .blockingSingle(); + assertEquals("Person2[name=FRED, score=21]", s); + } + + @Test + public void testAutomappedEquals() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(x)) // + .blockingSingle(); + assertTrue(b); + } + + @Test + public void testAutomappedDoesNotEqualNull() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(null)) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedDoesNotEqual() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(new Object())) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedHashCode() { + Person2 p = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .blockingSingle(); + assertTrue(p.hashCode() != 0); + } + + @Test + public void testAutomappedWithParametersThatProvokesMoreThanOneQuery() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(2) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsAndHashCodeIsDistinctOnValues() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .distinct() // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsDifferentiatesDifferentInterfacesWithSameMethodNamesAndValues() { + PersonDistinct1 p1 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct1.class) // + .blockingFirst(); + + PersonDistinct2 p2 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct2.class) // + .blockingFirst(); + + assertNotEquals(p1, p2); + } + + @Test + public void testAutomappedObjectsWhenDefaultMethodInvoked() { + PersonWithDefaultMethod p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethod.class) // + .blockingFirst(); + assertEquals("fred", p.nameLower()); + } + + // @Test + // public void testDefaultMethod() throws NoSuchMethodException, + // IllegalAccessException { + // MethodHandles.lookup().findSpecial(PersonWithDefaultMethod.class, + // "nameLower", + // MethodType.methodType(String.class, new Class[] {}), + // PersonWithDefaultMethod.class) + //// .bindTo(x); + // } + + @Test(expected = AutomappedInterfaceInaccessibleException.class) + public void testAutomappedObjectsWhenDefaultMethodInvokedAndIsNonPublicThrows() { + PersonWithDefaultMethodNonPublic p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethodNonPublic.class) // + .blockingFirst(); + p.nameLower(); + } + + @Test + public void testBlockingDatabase() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransacted() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .map(x -> x.value()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransactedNested() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .flatMap(tx -> tx.select("select name from person where score=?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + public interface PersonWithDefaultMethod { + @Column + String name(); + + @Column + int score(); + + public default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonWithDefaultMethodNonPublic { + @Column + String name(); + + @Column + int score(); + + default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonDistinct1 { + @Column + String name(); + + @Column + int score(); + + } + + interface PersonDistinct2 { + @Column + String name(); + + @Column + int score(); + + } + + interface Score { + @Column + int score(); + } + + interface Person { + @Column + String name(); + } + + interface Person2 { + @Column + String name(); + + @Column + int score(); + } + + interface Person3 { + @Column("name") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person4 { + @Column("namez") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person5 { + @Index(1) + String fullName(); + + @Index(2) + int examScore(); + } + + interface Person6 { + @Index(1) + String fullName(); + + @Index(3) + int examScore(); + } + + interface Person7 { + @Index(1) + String fullName(); + + @Index(0) + int examScore(); + } + + interface Person8 { + @Column + int name(); + } + + interface Person9 { + @Column + String name(); + + @Index(2) + int score(); + } + + interface PersonNoAnnotation { + String name(); + } + + @Query("select name, score from person order by name") + interface Person10 { + + @Column + String name(); + + @Column + int score(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.davidmoten.rx.jdbc.Database` acquired by call to `db()` at line 1098 is not released after line 1100. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DatabaseTest.testTuple4() + +### Procedure Id: +org.davidmoten.rx.jdbc.DatabaseTest.testTuple4():void.3e72ab5404511eaf5f4008024145b715 + +### File: +src/test/java/org/davidmoten/rx/jdbc/DatabaseTest.java + +### Key: +DatabaseTest.java|testTuple4|RESOURCE_LEAK + +### Node Key: +42f56fda1ad408e362508b93a175bb0c + +### Hash: +8c30d0aab3d55cb80cf5a480e91c5931 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10876/instruction.md b/inferredbugs-10876/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a44c8f0d4c48d95229454a8f1bbb55c0c2773747 --- /dev/null +++ b/inferredbugs-10876/instruction.md @@ -0,0 +1,2482 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rxjava2-jdbc +**Bug ID:** 93 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.davidmoten.rx.jdbc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLSyntaxErrorException; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.log4j.Level; +import org.apache.log4j.LogManager; +import org.davidmoten.rx.jdbc.annotations.Column; +import org.davidmoten.rx.jdbc.annotations.Index; +import org.davidmoten.rx.jdbc.annotations.Query; +import org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.AutomappedInterfaceInaccessibleException; +import org.davidmoten.rx.jdbc.exceptions.ColumnIndexOutOfRangeException; +import org.davidmoten.rx.jdbc.exceptions.ColumnNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.MoreColumnsRequestedThanExistException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterFoundButSqlDoesNotHaveNamesException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterMissingException; +import org.davidmoten.rx.jdbc.exceptions.QueryAnnotationMissingException; +import org.davidmoten.rx.jdbc.pool.DatabaseCreator; +import org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool; +import org.davidmoten.rx.jdbc.pool.Pools; +import org.davidmoten.rx.jdbc.tuple.Tuple2; +import org.davidmoten.rx.jdbc.tuple.Tuple3; +import org.davidmoten.rx.jdbc.tuple.Tuple4; +import org.davidmoten.rx.jdbc.tuple.Tuple5; +import org.davidmoten.rx.jdbc.tuple.Tuple6; +import org.davidmoten.rx.jdbc.tuple.Tuple7; +import org.davidmoten.rx.jdbc.tuple.TupleN; +import org.davidmoten.rx.pool.PoolClosedException; +import org.h2.jdbc.JdbcSQLException; +import org.hsqldb.jdbc.JDBCBlobFile; +import org.hsqldb.jdbc.JDBCClobFile; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.davidmoten.guavamini.Lists; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Observable; +import io.reactivex.Scheduler; +import io.reactivex.Single; +import io.reactivex.functions.Predicate; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subscribers.TestSubscriber; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class DatabaseTest { + + private static final long FRED_REGISTERED_TIME = 1442515672690L; + private static final int NAMES_COUNT_BIG = 5163; + private static final Logger log = LoggerFactory.getLogger(DatabaseTest.class); + private static final int TIMEOUT_SECONDS = 2; + + private static Database db() { + return DatabaseCreator.create(1); + } + + private static Database blocking() { + return DatabaseCreator.createBlocking(); + } + + private static Database db(int poolSize) { + return DatabaseCreator.create(poolSize); + } + + private static Database big(int poolSize) { + return DatabaseCreator.create(poolSize, true, Schedulers.computation()); + } + + @Test + public void testSelectUsingQuestionMark() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNamedParameterList() { + try (Database db = db()) { + db.select("select score from person where name=:name") // + .parameters(Parameter.named("name", "FRED").value("JOSEPH").list()) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameters() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterStream(Flowable.just("FRED", "JOSEPH")) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersInLists() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED"), Arrays.asList("JOSEPH"))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testDrivingSelectWithoutParametersUsingParameterStream() { + try (Database db = db()) { + db.select("select count(*) from person") // + .parameters(1, 2, 3) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterStream(Flowable.just("FRED", 21, "JOSEPH", 34)) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameterListsTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED", 21), Arrays.asList("JOSEPH", 34))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkWithPublicTestingDatabase() { + try (Database db = Database.test()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSize() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(2) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSizeZero() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(0) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectWithFetchSizeNegative() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(-1); + } + } + + @Test + public void testSelectUsingNonBlockingBuilder() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(1, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES) // + .checkoutRetryInterval(1, TimeUnit.SECONDS) // + .healthy(c -> c.prepareStatement("select 1").execute()) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) // + .maxPoolSize(3) // + .build(); + + try (Database db = Database.from(pool)) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test(timeout = 40000) + public void testSelectUsingNonBlockingBuilderConcurrencyTest() + throws InterruptedException, TimeoutException { + info(); + try { + try (Database db = db(3)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(50)); + int n = 10000; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } else { + // log.debug(iCopy + " succeeded"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + } + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test(timeout = 5000) + public void testSelectConcurrencyTest() throws InterruptedException, TimeoutException { + debug(); + try { + try (Database db = db(1)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(2)); + int n = 2; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + log.info("submitted " + i); + } + if (!latch.await(5000, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test + public void testDatabaseClose() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingName() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNameNotGiven() { + try (Database db = db()) { + db // + .select("select score from person where name=:name and name<>:name2") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterMissingException.class) // + .assertNoValues(); + } + } + + @Test + public void testSelectUsingParameterNameNullNameWhenSqlHasNoNames() { + db() // + .select("select score from person where name=?") // + .parameter(Parameter.create("name", "FRED")) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterFoundButSqlDoesNotHaveNamesException.class) // + .assertNoValues(); + } + + @Test + public void testUpdateWithNull() { + try (Database db = db()) { + db // + .update("update person set date_of_birth = :dob") // + .parameter(Parameter.create("dob", null)) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithNull() { + try (Database db = db()) { + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", Database.NULL_CLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithClob() throws SQLException { + try (Database db = db()) { + Clob clob = new JDBCClobFile(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", clob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithReader() throws FileNotFoundException { + try (Database db = db()) { + Reader reader = new FileReader(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", reader) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithBlob() throws SQLException { + try (Database db = db()) { + Blob blob = new JDBCBlobFile(new File("src/test/resources/big.txt")); + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", blob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithNull() { + try (Database db = db()) { + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", Database.NULL_BLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test(expected = NullPointerException.class) + public void testSelectUsingNullNameInParameter() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter(null, "FRED"); // + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameDoesNotExist() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameters("nam", "FRED"); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameters("FRED", "JOSEPH"); + } + } + + @Test + public void testSelectTransacted() { + try (Database db = db()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .getAs(Integer.class) // + .doOnNext(tx -> log + .debug(tx.isComplete() ? "complete" : String.valueOf(tx.value()))) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedAnnotatedTransacted() { + try (Database db = db()) { + db // + .select(Person10.class) // + .transacted() // + .valuesOnly() // + .get().test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedTransactedValuesOnly() { + try (Database db = db()) { + db // + .select("select name, score from person") // + .transacted() // + .valuesOnly() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedTransacted() { + try (Database db = db()) { + db // + .select("select name, score from person") // + .transacted() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + } + + @Test + public void testSelectTransactedTuple2() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + } + } + + @Test + public void testSelectTransactedTuple3() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + } + } + + @Test + public void testSelectTransactedTuple4() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + } + } + + @Test + public void testSelectTransactedTuple5() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + } + } + + @Test + public void testSelectTransactedTuple6() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + } + } + + @Test + public void testSelectTransactedTuple7() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + assertEquals("FRED", t.value()._7()); + } + } + + @Test + public void testSelectTransactedTupleN() { + List>> list = db() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getTupleN() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertEquals("FRED", list.get(0).value().values().get(0)); + assertEquals(21, (int) list.get(0).value().values().get(1)); + assertTrue(list.get(1).isComplete()); + assertEquals(2, list.size()); + } + + @Test + public void testSelectTransactedCount() { + db() // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAs() { + db() // + .select("select name from person") // + .transacted() // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAsOptional() { + List>> list = db() // + .select("select name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAsOptional(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertTrue(list.get(0).isValue()); + assertEquals("FRED", list.get(0).value().get()); + assertTrue(list.get(1).isComplete()); + } + + @Test + public void testDatabaseFrom() { + Database.from(DatabaseCreator.nextUrl(), 3) // + .select("select name from person") // + .getAs(String.class) // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(JdbcSQLException.class); + } + + @Test + public void testSelectTransactedChained() throws Exception { + try (Database db = db()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .transactedValuesOnly() // + .getAs(Integer.class) // + .doOnNext(tx -> log + .debug(tx.isComplete() ? "complete" : String.valueOf(tx.value())))// + .flatMap(tx -> tx // + .select("select name from person where score = ?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + } + + @Test + public void databaseIsAutoCloseable() { + try (Database db = db()) { + log.debug(db.toString()); + } + } + + @Test + public void testSelectChained() { + try (Database db = db(1)) { + // we can do this with 1 connection only! + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .doOnNext(System.out::println) // + .concatMap(score -> { + log.info("score={}", score); + return db // + .select("select name from person where score = ?") // + .parameter(score) // + .getAs(String.class) // + .doOnComplete( + () -> log.info("completed select where score=" + score)); + }) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); // + } + } + + @Test + @SuppressFBWarnings + public void testReadMeFragment1() { + try (Database db = db()) { + db.select("select name from person") // + .getAs(String.class) // + .forEach(System.out::println); + } + } + + @Test + public void testReadMeFragmentColumnDoesNotExistEmitsSqlSyntaxErrorException() { + try (Database db = Database.test()) { + db.select("select nam from person") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(SQLSyntaxErrorException.class); + } + } + + @Test + public void testReadMeFragmentDerbyHealthCheck() { + try (Database db = Database.test()) { + db.select("select 'a' from sysibm.sysdummy1") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("a") // + .assertComplete(); + } + } + + @Test + @SuppressFBWarnings + public void testTupleSupport() { + try (Database db = db()) { + db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .forEach(System.out::println); + } + } + + @Test + public void testDelayedCallsAreNonBlocking() throws InterruptedException { + List list = new CopyOnWriteArrayList(); + try (Database db = db(1)) { // + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> Thread.sleep(1000)) // + .subscribeOn(Schedulers.io()) // + .subscribe(); + Thread.sleep(100); + CountDownLatch latch = new CountDownLatch(1); + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> list.add("emitted")) // + .doOnNext(x -> log.debug("emitted on " + Thread.currentThread().getName())) // + .doOnNext(x -> latch.countDown()) // + .subscribe(); + list.add("subscribed"); + assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + assertEquals(Arrays.asList("subscribed", "emitted"), list); + } + } + + @Test + public void testAutoMapToInterface() { + try (Database db = db()) { + db // + .select("select name from person") // + .autoMap(Person.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithoutAnnotationstsError() { + try (Database db = db()) { + db // + .select("select name from person") // + .autoMap(PersonNoAnnotation.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(AnnotationsNotFoundException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithTwoMethods() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person2.class) // + .firstOrError() // + .map(Person2::score) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnName() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person3.class) // + .firstOrError() // + .map(Person3::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person4.class) // + .firstOrError() // + .map(Person4::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnNotFoundException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithIndex() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person5.class) // + .firstOrError() // + .map(Person5::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithIndexTooLarge() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person6.class) // + .firstOrError() // + .map(Person6::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithIndexTooSmall() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person7.class) // + .firstOrError() // + .map(Person7::examScore) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + } + + @Test + public void testAutoMapWithUnmappableColumnType() { + try (Database db = db()) { + db // + .select("select name from person order by name") // + .autoMap(Person8.class) // + .map(p -> p.name()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ClassCastException.class); + } + } + + @Test + public void testAutoMapWithMixIndexAndName() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person9.class) // + .firstOrError() // + .map(Person9::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapWithQueryInAnnotation() { + try (Database db = db()) { + db.select(Person10.class) // + .get() // + .firstOrError() // + .map(Person10::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + @Ignore + public void testAutoMapForReadMe() { + Database // + .test() // + .select(Person10.class) // + .get(Person10::name) // + .blockingForEach(System.out::println); + } + + @Test(expected = QueryAnnotationMissingException.class) + public void testAutoMapWithoutQueryInAnnotation() { + try (Database db = db()) { + db.select(Person.class); + } + } + + @Test + public void testSelectWithoutWhereClause() { + try (Database db = db()) { + Assert.assertEquals(3, (long) db.select("select name from person") // + .count() // + .blockingGet()); + } + } + + @Test + public void testTuple3() { + try (Database db = db()) { + db // + .select("select name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple3.create("FRED", 21, "FRED")); // + } + } + + @Test + public void testTuple4() { + try (Database db = db()) { + db // + .select("select name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple4.create("FRED", 21, "FRED", 21)); // + } + } + + @Test + public void testTuple5() { + try (Database db = db()) { + db // + .select("select name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple5.create("FRED", 21, "FRED", 21, "FRED")); // + } + } + + @Test + public void testTuple6() { + try (Database db = db()) { + db // + .select("select name, score, name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() + .assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21)); // + } + } + + @Test + public void testTuple7() { + try (Database db = db()) { + db // + .select("select name, score, name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() + .assertValue(Tuple7.create("FRED", 21, "FRED", 21, "FRED", 21, "FRED")); // + } + } + + @Test + public void testTupleN() { + try (Database db = db()) { + db // + .select("select name, score, name from person order by name") // + .getTupleN() // + .firstOrError().test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(TupleN.create("FRED", 21, "FRED")); // + } + } + + @Test + public void testHealthCheck() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + return !once.compareAndSet(true, false); + }); + } + + @Test + public void testHealthCheckThatThrows() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + if (!once.compareAndSet(true, false)) + return true; + else + throw new RuntimeException("health check failed"); + }); + } + + @Test + public void testUpdateOneRow() { + try (Database db = db()) { + db.update("update person set score=20 where name='FRED'") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateThreeRows() { + try (Database db = db()) { + db.update("update person set score=20") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithParameter() { + try (Database db = db()) { + db.update("update person set score=20 where name=?") // + .parameter("FRED").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithParameterTwoRuns() { + try (Database db = db()) { + db.update("update person set score=20 where name=?") // + .parameters("FRED", "JOSEPH").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + } + } + + @Test + public void testUpdateAllWithParameterFourRuns() { + try (Database db = db()) { + db.update("update person set score=?") // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithBatchSize2() { + try (Database db = db()) { + db.update("update person set score=?") // + .batchSize(2) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithBatchSize3GreaterThanNumRecords() { + try (Database db = db()) { + db.update("update person set score=?") // + .batchSize(3) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testInsert() { + try (Database db = db()) { + db.update("insert into person(name, score) values(?,?)") // + .parameters("DAVE", 12, "ANNE", 18) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + List> list = db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .toList() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingGet(); + assertTrue(list.contains(Tuple2.create("DAVE", 12))); + assertTrue(list.contains(Tuple2.create("ANNE", 18))); + } + } + + @Test + public void testReturnGeneratedKeys() { + try (Database db = db()) { + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + } + + @Test + public void testReturnGeneratedKeysDerby() { + Database db = DatabaseCreator.createDerby(1); + + // note is a table with auto increment + db.update("insert into note2(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors().assertValues(1, 3) // + .assertComplete(); + + db.update("insert into note2(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(5, 7) // + .assertComplete(); + } + + @Test(expected = IllegalArgumentException.class) + public void testReturnGeneratedKeysWithBatchSizeShouldThrow() { + try (Database db = db()) { + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .batchSize(2) // + .returnGeneratedKeys(); + } + } + + @Test + public void testTransactedReturnGeneratedKeys() { + try (Database db = db()) { + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + } + + @Test + public void testTransactedReturnGeneratedKeys2() { + try (Database db = db()) { + // note is a table with auto increment + Flowable a = db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .startWith(a) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2, 3, 4) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithinTransaction() { + try (Database db = db()) { + db // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + } + + @Test + public void testSelectDependsOnFlowable() { + try (Database db = db()) { + Flowable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + } + + @Test + public void testSelectDependsOnObservable() { + try (Database db = db()) { + Observable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().toObservable(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + } + + @Test + public void testSelectDependsOnOnSingle() { + try (Database db = db()) { + Single a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().count(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + } + + @Test + public void testSelectDependsOnCompletable() { + try (Database db = db()) { + Completable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().ignoreElements(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithinTransactionBatchSize0() { + try (Database db = db()) { + db // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(0) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + } + + private static void info() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + private static void debug() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + @Test + public void testCreateBig() { + info(); + big(5).select("select count(*) from person") // + .getAs(Integer.class) // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue(5163) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBig() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBigInputBatchSize2000() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(2000) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testInsertNullClobAndReadClobAsString() { + try (Database db = db()) { + insertNullClob(db); + db.select("select document from person_clob where name='FRED'") // + .getAsOptional(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Optional.empty()) // + .assertComplete(); + } + } + + private static void insertNullClob(Database db) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", Database.NULL_CLOB) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testClobMethod() { + assertEquals(Database.NULL_CLOB, Database.clob(null)); + } + + @Test + public void testBlobMethod() { + assertEquals(Database.NULL_BLOB, Database.blob(null)); + } + + @Test + public void testClobMethodPresent() { + assertEquals("a", Database.clob("a")); + } + + @Test + public void testBlobMethodPresent() { + byte[] b = new byte[1]; + assertEquals(b, Database.blob(b)); + } + + @Test + public void testDateOfBirthNullableForReadMe() { + Database.test() // + .select("select date_of_birth from person where name='FRED'") // + .getAsOptional(Instant.class) // + .blockingForEach(System.out::println); + } + + @Test + public void testInsertNullClobAndReadClobAsTuple2() { + try (Database db = db()) { + insertNullClob(db); + db.select("select document, document from person_clob where name='FRED'") // + .getAs(String.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Tuple2.create(null, null)) // + .assertComplete(); + } + } + + @Test + public void testInsertClobAndReadClobAsString() { + try (Database db = db()) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue("some + // text + // here") + // // + .assertComplete(); + } + } + + @Test + public void testInsertClobAndReadClobUsingReader() { + try (Database db = db()) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(Reader.class) // + .map(r -> read(r)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + } + + @Test + public void testInsertBlobAndReadBlobAsByteArray() { + try (Database db = db()) { + insertPersonBlob(db); + db.select("select document from person_blob where name='FRED'") // + .getAs(byte[].class) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + } + + private static void insertPersonBlob(Database db) { + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", bytes) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsInputStream() { + try (Database db = db()) { + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", new ByteArrayInputStream(bytes)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_blob where name='FRED'") // + .getAs(InputStream.class) // + .map(is -> read(is)) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + } + + private static String read(Reader reader) throws IOException { + StringBuffer s = new StringBuffer(); + char[] ch = new char[128]; + int n = 0; + while ((n = reader.read(ch)) != -1) { + s.append(ch, 0, n); + } + reader.close(); + return s.toString(); + } + + private static byte[] read(InputStream is) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] b = new byte[128]; + int n = 0; + while ((n = is.read(b)) != -1) { + bytes.write(b, 0, n); + } + is.close(); + return bytes.toByteArray(); + } + + private void testHealthCheck(Predicate healthy) throws InterruptedException { + TestScheduler scheduler = new TestScheduler(); + + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(10, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) // + .healthy(healthy) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) // + .scheduler(scheduler) // + .maxPoolSize(1) // + .build(); + + try (Database db = Database.from(pool)) { + TestSubscriber ts0 = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test(); + ts0.assertValueCount(0) // + .assertNotComplete(); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + ts0.assertValueCount(1) // + .assertComplete(); + TestSubscriber ts = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test() // + .assertValueCount(0); + log.debug("done2"); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + Thread.sleep(200); + ts.assertValueCount(1); + Thread.sleep(200); + ts.assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testShutdownBeforeUse() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .scheduler(Schedulers.io()) // + .maxPoolSize(1) // + .build(); + pool.close(); + Database.from(pool) // + .select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(PoolClosedException.class); + } + + @Test + public void testFewerColumnsMappedThanAvailable() { + db().select("select name, score from person where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues("FRED") // + .assertComplete(); + } + + @Test + public void testMoreColumnsMappedThanAvailable() { + db() // + .select("select name, score from person where name='FRED'") // + .getAs(String.class, Integer.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(MoreColumnsRequestedThanExistException.class); + } + + @Test + public void testSelectTimestamp() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsDate() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Date.class) // + .map(d -> d.getTime()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsInstant() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Instant.class) // + .map(d -> d.toEpochMilli()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateCalendarParameter() { + Calendar c = GregorianCalendar.from(ZonedDateTime.parse("2017-03-25T15:37Z")); + try (Database db = db()) { + db.update("update person set registered=?") // + .parameter(c) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(c.getTimeInMillis()) // + .assertComplete(); + } + } + + @Test + public void testUpdateTimeParameter() { + try (Database db = db()) { + Time t = new Time(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + } + + @Test + public void testUpdateTimestampParameter() { + try (Database db = db()) { + Timestamp t = new Timestamp(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + } + + @Test + public void testUpdateSqlDateParameter() { + try (Database db = db()) { + java.sql.Date t = new java.sql.Date(1234); + + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS * 10000, TimeUnit.SECONDS) // + // TODO make a more accurate comparison using the current TZ + .assertValue(x -> Math.abs(x - 1234) <= TimeUnit.HOURS.toMillis(24)) // + .assertComplete(); + } + } + + @Test + public void testUpdateUtilDateParameter() { + try (Database db = db()) { + Date d = new Date(1234); + db.update("update person set registered=?") // + .parameter(d) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + } + + @Test + public void testUpdateTimestampAsInstant() { + try (Database db = db()) { + db.update("update person set registered=? where name='FRED'") // + .parameter(Instant.ofEpochMilli(FRED_REGISTERED_TIME)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + } + + @Test + public void testUpdateTimestampAsZonedDateTime() { + try (Database db = db()) { + db.update("update person set registered=? where name='FRED'") // + .parameter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(FRED_REGISTERED_TIME), + ZoneOffset.UTC.normalized())) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + } + + @Test + public void testCompleteCompletes() { + Database db = db(1); + db // + .update("update person set score=-3 where name='FRED'") // + .complete() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingAwait(); + + int score = db.select("select score from person where name='FRED'") // + .getAs(Integer.class) // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingFirst(); + assertEquals(-3, score); + } + + @Test + public void testComplete() throws InterruptedException { + Database db = db(1); + Completable a = db // + .update("update person set score=-3 where name='FRED'") // + .complete(); + db.update("update person set score=-4 where score = -3") // + .dependsOn(a) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testCountsOnlyInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .countsOnly() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3) // + .assertComplete(); + } + + @Test + public void testCountsInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .counts() // + .doOnNext(System.out::println) // + .toList() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3 + && list.get(1).isComplete() && list.size() == 2) // + .assertComplete(); + } + + @Test + public void testTx() throws InterruptedException { + Database db = db(3); + Single> transaction = db // + .update("update person set score=-3 where name='FRED'") // + .transaction(); + + transaction // + .doOnDispose(() -> log.debug("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + log.debug("flatmapping"); + return tx // + .update("update person set score = -4 where score = -3") // + .countsOnly() // + .doOnSubscribe(s -> log.debug("subscribed")) // + .doOnNext(num -> log.debug("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testTxAfterSelect() { + Database db = db(3); + Single> transaction = db // + .select("select score from person where name='FRED'") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .firstOrError(); + + transaction // + .doOnDispose(() -> log.debug("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + log.debug("flatmapping"); + return tx // + .update("update person set score = -4 where score = ?") // + .parameter(tx.value()) // + .countsOnly() // + .doOnSubscribe(s -> log.debug("subscribed")) // + .doOnNext(num -> log.debug("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testSingleFlatMap() { + Single.just(1).flatMapPublisher(n -> Flowable.just(1)).test(1).assertValue(1) + .assertComplete(); + } + + @Test + public void testAutomappedInstanceHasMeaningfulToStringMethod() { + info(); + String s = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.toString()) // + .blockingSingle(); + assertEquals("Person2[name=FRED, score=21]", s); + } + + @Test + public void testAutomappedEquals() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(x)) // + .blockingSingle(); + assertTrue(b); + } + + @Test + public void testAutomappedDoesNotEqualNull() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(null)) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedDoesNotEqual() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(new Object())) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedHashCode() { + Person2 p = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .blockingSingle(); + assertTrue(p.hashCode() != 0); + } + + @Test + public void testAutomappedWithParametersThatProvokesMoreThanOneQuery() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(2) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsAndHashCodeIsDistinctOnValues() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .distinct() // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsDifferentiatesDifferentInterfacesWithSameMethodNamesAndValues() { + PersonDistinct1 p1 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct1.class) // + .blockingFirst(); + + PersonDistinct2 p2 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct2.class) // + .blockingFirst(); + + assertNotEquals(p1, p2); + } + + @Test + public void testAutomappedObjectsWhenDefaultMethodInvoked() { + PersonWithDefaultMethod p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethod.class) // + .blockingFirst(); + assertEquals("fred", p.nameLower()); + } + + // @Test + // public void testDefaultMethod() throws NoSuchMethodException, + // IllegalAccessException { + // MethodHandles.lookup().findSpecial(PersonWithDefaultMethod.class, + // "nameLower", + // MethodType.methodType(String.class, new Class[] {}), + // PersonWithDefaultMethod.class) + //// .bindTo(x); + // } + + @Test(expected = AutomappedInterfaceInaccessibleException.class) + public void testAutomappedObjectsWhenDefaultMethodInvokedAndIsNonPublicThrows() { + PersonWithDefaultMethodNonPublic p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethodNonPublic.class) // + .blockingFirst(); + p.nameLower(); + } + + @Test + public void testBlockingDatabase() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransacted() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .map(x -> x.value()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransactedNested() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .flatMap(tx -> tx.select("select name from person where score=?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + public interface PersonWithDefaultMethod { + @Column + String name(); + + @Column + int score(); + + public default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonWithDefaultMethodNonPublic { + @Column + String name(); + + @Column + int score(); + + default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonDistinct1 { + @Column + String name(); + + @Column + int score(); + + } + + interface PersonDistinct2 { + @Column + String name(); + + @Column + int score(); + + } + + interface Score { + @Column + int score(); + } + + interface Person { + @Column + String name(); + } + + interface Person2 { + @Column + String name(); + + @Column + int score(); + } + + interface Person3 { + @Column("name") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person4 { + @Column("namez") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person5 { + @Index(1) + String fullName(); + + @Index(2) + int examScore(); + } + + interface Person6 { + @Index(1) + String fullName(); + + @Index(3) + int examScore(); + } + + interface Person7 { + @Index(1) + String fullName(); + + @Index(0) + int examScore(); + } + + interface Person8 { + @Column + int name(); + } + + interface Person9 { + @Column + String name(); + + @Index(2) + int score(); + } + + interface PersonNoAnnotation { + String name(); + } + + @Query("select name, score from person order by name") + interface Person10 { + + @Column + String name(); + + @Column + int score(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.davidmoten.rx.jdbc.Database` acquired by call to `db()` at line 727 is not released after line 729. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DatabaseTest.testSelectTransactedTupleN() + +### Procedure Id: +org.davidmoten.rx.jdbc.DatabaseTest.testSelectTransactedTupleN():void.32b1d400a6dc798ed681f24deb9444f1 + +### File: +src/test/java/org/davidmoten/rx/jdbc/DatabaseTest.java + +### Key: +DatabaseTest.java|testSelectTransactedTupleN|RESOURCE_LEAK + +### Node Key: +b1e1d2e868cbf5fb020e794c7723980b + +### Hash: +8254a0d2d334264c6f5557276e5331f2 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10877/instruction.md b/inferredbugs-10877/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e947bab7b1b2d365e53c90d301ec86bc1444fa95 --- /dev/null +++ b/inferredbugs-10877/instruction.md @@ -0,0 +1,2482 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rxjava2-jdbc +**Bug ID:** 94 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.davidmoten.rx.jdbc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLSyntaxErrorException; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.log4j.Level; +import org.apache.log4j.LogManager; +import org.davidmoten.rx.jdbc.annotations.Column; +import org.davidmoten.rx.jdbc.annotations.Index; +import org.davidmoten.rx.jdbc.annotations.Query; +import org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.AutomappedInterfaceInaccessibleException; +import org.davidmoten.rx.jdbc.exceptions.ColumnIndexOutOfRangeException; +import org.davidmoten.rx.jdbc.exceptions.ColumnNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.MoreColumnsRequestedThanExistException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterFoundButSqlDoesNotHaveNamesException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterMissingException; +import org.davidmoten.rx.jdbc.exceptions.QueryAnnotationMissingException; +import org.davidmoten.rx.jdbc.pool.DatabaseCreator; +import org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool; +import org.davidmoten.rx.jdbc.pool.Pools; +import org.davidmoten.rx.jdbc.tuple.Tuple2; +import org.davidmoten.rx.jdbc.tuple.Tuple3; +import org.davidmoten.rx.jdbc.tuple.Tuple4; +import org.davidmoten.rx.jdbc.tuple.Tuple5; +import org.davidmoten.rx.jdbc.tuple.Tuple6; +import org.davidmoten.rx.jdbc.tuple.Tuple7; +import org.davidmoten.rx.jdbc.tuple.TupleN; +import org.davidmoten.rx.pool.PoolClosedException; +import org.h2.jdbc.JdbcSQLException; +import org.hsqldb.jdbc.JDBCBlobFile; +import org.hsqldb.jdbc.JDBCClobFile; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.davidmoten.guavamini.Lists; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Observable; +import io.reactivex.Scheduler; +import io.reactivex.Single; +import io.reactivex.functions.Predicate; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subscribers.TestSubscriber; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class DatabaseTest { + + private static final long FRED_REGISTERED_TIME = 1442515672690L; + private static final int NAMES_COUNT_BIG = 5163; + private static final Logger log = LoggerFactory.getLogger(DatabaseTest.class); + private static final int TIMEOUT_SECONDS = 2; + + private static Database db() { + return DatabaseCreator.create(1); + } + + private static Database blocking() { + return DatabaseCreator.createBlocking(); + } + + private static Database db(int poolSize) { + return DatabaseCreator.create(poolSize); + } + + private static Database big(int poolSize) { + return DatabaseCreator.create(poolSize, true, Schedulers.computation()); + } + + @Test + public void testSelectUsingQuestionMark() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNamedParameterList() { + try (Database db = db()) { + db.select("select score from person where name=:name") // + .parameters(Parameter.named("name", "FRED").value("JOSEPH").list()) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameters() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterStream(Flowable.just("FRED", "JOSEPH")) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersInLists() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED"), Arrays.asList("JOSEPH"))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testDrivingSelectWithoutParametersUsingParameterStream() { + try (Database db = db()) { + db.select("select count(*) from person") // + .parameters(1, 2, 3) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterStream(Flowable.just("FRED", 21, "JOSEPH", 34)) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameterListsTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED", 21), Arrays.asList("JOSEPH", 34))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkWithPublicTestingDatabase() { + try (Database db = Database.test()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSize() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(2) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSizeZero() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(0) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectWithFetchSizeNegative() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(-1); + } + } + + @Test + public void testSelectUsingNonBlockingBuilder() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(1, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES) // + .checkoutRetryInterval(1, TimeUnit.SECONDS) // + .healthy(c -> c.prepareStatement("select 1").execute()) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) // + .maxPoolSize(3) // + .build(); + + try (Database db = Database.from(pool)) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test(timeout = 40000) + public void testSelectUsingNonBlockingBuilderConcurrencyTest() + throws InterruptedException, TimeoutException { + info(); + try { + try (Database db = db(3)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(50)); + int n = 10000; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } else { + // log.debug(iCopy + " succeeded"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + } + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test(timeout = 5000) + public void testSelectConcurrencyTest() throws InterruptedException, TimeoutException { + debug(); + try { + try (Database db = db(1)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(2)); + int n = 2; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + log.info("submitted " + i); + } + if (!latch.await(5000, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test + public void testDatabaseClose() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingName() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNameNotGiven() { + try (Database db = db()) { + db // + .select("select score from person where name=:name and name<>:name2") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterMissingException.class) // + .assertNoValues(); + } + } + + @Test + public void testSelectUsingParameterNameNullNameWhenSqlHasNoNames() { + db() // + .select("select score from person where name=?") // + .parameter(Parameter.create("name", "FRED")) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterFoundButSqlDoesNotHaveNamesException.class) // + .assertNoValues(); + } + + @Test + public void testUpdateWithNull() { + try (Database db = db()) { + db // + .update("update person set date_of_birth = :dob") // + .parameter(Parameter.create("dob", null)) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithNull() { + try (Database db = db()) { + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", Database.NULL_CLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithClob() throws SQLException { + try (Database db = db()) { + Clob clob = new JDBCClobFile(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", clob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithReader() throws FileNotFoundException { + try (Database db = db()) { + Reader reader = new FileReader(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", reader) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithBlob() throws SQLException { + try (Database db = db()) { + Blob blob = new JDBCBlobFile(new File("src/test/resources/big.txt")); + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", blob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithNull() { + try (Database db = db()) { + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", Database.NULL_BLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test(expected = NullPointerException.class) + public void testSelectUsingNullNameInParameter() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter(null, "FRED"); // + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameDoesNotExist() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameters("nam", "FRED"); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameters("FRED", "JOSEPH"); + } + } + + @Test + public void testSelectTransacted() { + try (Database db = db()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .getAs(Integer.class) // + .doOnNext(tx -> log + .debug(tx.isComplete() ? "complete" : String.valueOf(tx.value()))) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedAnnotatedTransacted() { + try (Database db = db()) { + db // + .select(Person10.class) // + .transacted() // + .valuesOnly() // + .get().test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedTransactedValuesOnly() { + try (Database db = db()) { + db // + .select("select name, score from person") // + .transacted() // + .valuesOnly() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedTransacted() { + try (Database db = db()) { + db // + .select("select name, score from person") // + .transacted() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + } + + @Test + public void testSelectTransactedTuple2() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + } + } + + @Test + public void testSelectTransactedTuple3() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + } + } + + @Test + public void testSelectTransactedTuple4() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + } + } + + @Test + public void testSelectTransactedTuple5() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + } + } + + @Test + public void testSelectTransactedTuple6() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + } + } + + @Test + public void testSelectTransactedTuple7() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + assertEquals("FRED", t.value()._7()); + } + } + + @Test + public void testSelectTransactedTupleN() { + List>> list = db() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getTupleN() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertEquals("FRED", list.get(0).value().values().get(0)); + assertEquals(21, (int) list.get(0).value().values().get(1)); + assertTrue(list.get(1).isComplete()); + assertEquals(2, list.size()); + } + + @Test + public void testSelectTransactedCount() { + db() // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAs() { + db() // + .select("select name from person") // + .transacted() // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAsOptional() { + List>> list = db() // + .select("select name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAsOptional(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertTrue(list.get(0).isValue()); + assertEquals("FRED", list.get(0).value().get()); + assertTrue(list.get(1).isComplete()); + } + + @Test + public void testDatabaseFrom() { + Database.from(DatabaseCreator.nextUrl(), 3) // + .select("select name from person") // + .getAs(String.class) // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(JdbcSQLException.class); + } + + @Test + public void testSelectTransactedChained() throws Exception { + try (Database db = db()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .transactedValuesOnly() // + .getAs(Integer.class) // + .doOnNext(tx -> log + .debug(tx.isComplete() ? "complete" : String.valueOf(tx.value())))// + .flatMap(tx -> tx // + .select("select name from person where score = ?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + } + + @Test + public void databaseIsAutoCloseable() { + try (Database db = db()) { + log.debug(db.toString()); + } + } + + @Test + public void testSelectChained() { + try (Database db = db(1)) { + // we can do this with 1 connection only! + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .doOnNext(System.out::println) // + .concatMap(score -> { + log.info("score={}", score); + return db // + .select("select name from person where score = ?") // + .parameter(score) // + .getAs(String.class) // + .doOnComplete( + () -> log.info("completed select where score=" + score)); + }) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); // + } + } + + @Test + @SuppressFBWarnings + public void testReadMeFragment1() { + try (Database db = db()) { + db.select("select name from person") // + .getAs(String.class) // + .forEach(System.out::println); + } + } + + @Test + public void testReadMeFragmentColumnDoesNotExistEmitsSqlSyntaxErrorException() { + try (Database db = Database.test()) { + db.select("select nam from person") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(SQLSyntaxErrorException.class); + } + } + + @Test + public void testReadMeFragmentDerbyHealthCheck() { + try (Database db = Database.test()) { + db.select("select 'a' from sysibm.sysdummy1") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("a") // + .assertComplete(); + } + } + + @Test + @SuppressFBWarnings + public void testTupleSupport() { + try (Database db = db()) { + db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .forEach(System.out::println); + } + } + + @Test + public void testDelayedCallsAreNonBlocking() throws InterruptedException { + List list = new CopyOnWriteArrayList(); + try (Database db = db(1)) { // + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> Thread.sleep(1000)) // + .subscribeOn(Schedulers.io()) // + .subscribe(); + Thread.sleep(100); + CountDownLatch latch = new CountDownLatch(1); + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> list.add("emitted")) // + .doOnNext(x -> log.debug("emitted on " + Thread.currentThread().getName())) // + .doOnNext(x -> latch.countDown()) // + .subscribe(); + list.add("subscribed"); + assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + assertEquals(Arrays.asList("subscribed", "emitted"), list); + } + } + + @Test + public void testAutoMapToInterface() { + try (Database db = db()) { + db // + .select("select name from person") // + .autoMap(Person.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithoutAnnotationstsError() { + try (Database db = db()) { + db // + .select("select name from person") // + .autoMap(PersonNoAnnotation.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(AnnotationsNotFoundException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithTwoMethods() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person2.class) // + .firstOrError() // + .map(Person2::score) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnName() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person3.class) // + .firstOrError() // + .map(Person3::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person4.class) // + .firstOrError() // + .map(Person4::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnNotFoundException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithIndex() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person5.class) // + .firstOrError() // + .map(Person5::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithIndexTooLarge() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person6.class) // + .firstOrError() // + .map(Person6::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithIndexTooSmall() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person7.class) // + .firstOrError() // + .map(Person7::examScore) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + } + + @Test + public void testAutoMapWithUnmappableColumnType() { + try (Database db = db()) { + db // + .select("select name from person order by name") // + .autoMap(Person8.class) // + .map(p -> p.name()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ClassCastException.class); + } + } + + @Test + public void testAutoMapWithMixIndexAndName() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person9.class) // + .firstOrError() // + .map(Person9::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapWithQueryInAnnotation() { + try (Database db = db()) { + db.select(Person10.class) // + .get() // + .firstOrError() // + .map(Person10::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + @Ignore + public void testAutoMapForReadMe() { + Database // + .test() // + .select(Person10.class) // + .get(Person10::name) // + .blockingForEach(System.out::println); + } + + @Test(expected = QueryAnnotationMissingException.class) + public void testAutoMapWithoutQueryInAnnotation() { + try (Database db = db()) { + db.select(Person.class); + } + } + + @Test + public void testSelectWithoutWhereClause() { + try (Database db = db()) { + Assert.assertEquals(3, (long) db.select("select name from person") // + .count() // + .blockingGet()); + } + } + + @Test + public void testTuple3() { + try (Database db = db()) { + db // + .select("select name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple3.create("FRED", 21, "FRED")); // + } + } + + @Test + public void testTuple4() { + try (Database db = db()) { + db // + .select("select name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple4.create("FRED", 21, "FRED", 21)); // + } + } + + @Test + public void testTuple5() { + try (Database db = db()) { + db // + .select("select name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple5.create("FRED", 21, "FRED", 21, "FRED")); // + } + } + + @Test + public void testTuple6() { + try (Database db = db()) { + db // + .select("select name, score, name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() + .assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21)); // + } + } + + @Test + public void testTuple7() { + try (Database db = db()) { + db // + .select("select name, score, name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() + .assertValue(Tuple7.create("FRED", 21, "FRED", 21, "FRED", 21, "FRED")); // + } + } + + @Test + public void testTupleN() { + try (Database db = db()) { + db // + .select("select name, score, name from person order by name") // + .getTupleN() // + .firstOrError().test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(TupleN.create("FRED", 21, "FRED")); // + } + } + + @Test + public void testHealthCheck() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + return !once.compareAndSet(true, false); + }); + } + + @Test + public void testHealthCheckThatThrows() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + if (!once.compareAndSet(true, false)) + return true; + else + throw new RuntimeException("health check failed"); + }); + } + + @Test + public void testUpdateOneRow() { + try (Database db = db()) { + db.update("update person set score=20 where name='FRED'") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateThreeRows() { + try (Database db = db()) { + db.update("update person set score=20") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithParameter() { + try (Database db = db()) { + db.update("update person set score=20 where name=?") // + .parameter("FRED").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithParameterTwoRuns() { + try (Database db = db()) { + db.update("update person set score=20 where name=?") // + .parameters("FRED", "JOSEPH").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + } + } + + @Test + public void testUpdateAllWithParameterFourRuns() { + try (Database db = db()) { + db.update("update person set score=?") // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithBatchSize2() { + try (Database db = db()) { + db.update("update person set score=?") // + .batchSize(2) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithBatchSize3GreaterThanNumRecords() { + try (Database db = db()) { + db.update("update person set score=?") // + .batchSize(3) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testInsert() { + try (Database db = db()) { + db.update("insert into person(name, score) values(?,?)") // + .parameters("DAVE", 12, "ANNE", 18) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + List> list = db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .toList() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingGet(); + assertTrue(list.contains(Tuple2.create("DAVE", 12))); + assertTrue(list.contains(Tuple2.create("ANNE", 18))); + } + } + + @Test + public void testReturnGeneratedKeys() { + try (Database db = db()) { + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + } + + @Test + public void testReturnGeneratedKeysDerby() { + Database db = DatabaseCreator.createDerby(1); + + // note is a table with auto increment + db.update("insert into note2(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors().assertValues(1, 3) // + .assertComplete(); + + db.update("insert into note2(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(5, 7) // + .assertComplete(); + } + + @Test(expected = IllegalArgumentException.class) + public void testReturnGeneratedKeysWithBatchSizeShouldThrow() { + try (Database db = db()) { + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .batchSize(2) // + .returnGeneratedKeys(); + } + } + + @Test + public void testTransactedReturnGeneratedKeys() { + try (Database db = db()) { + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + } + + @Test + public void testTransactedReturnGeneratedKeys2() { + try (Database db = db()) { + // note is a table with auto increment + Flowable a = db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .startWith(a) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2, 3, 4) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithinTransaction() { + try (Database db = db()) { + db // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + } + + @Test + public void testSelectDependsOnFlowable() { + try (Database db = db()) { + Flowable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + } + + @Test + public void testSelectDependsOnObservable() { + try (Database db = db()) { + Observable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().toObservable(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + } + + @Test + public void testSelectDependsOnOnSingle() { + try (Database db = db()) { + Single a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().count(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + } + + @Test + public void testSelectDependsOnCompletable() { + try (Database db = db()) { + Completable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().ignoreElements(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithinTransactionBatchSize0() { + try (Database db = db()) { + db // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(0) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + } + + private static void info() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + private static void debug() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + @Test + public void testCreateBig() { + info(); + big(5).select("select count(*) from person") // + .getAs(Integer.class) // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue(5163) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBig() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBigInputBatchSize2000() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(2000) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testInsertNullClobAndReadClobAsString() { + try (Database db = db()) { + insertNullClob(db); + db.select("select document from person_clob where name='FRED'") // + .getAsOptional(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Optional.empty()) // + .assertComplete(); + } + } + + private static void insertNullClob(Database db) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", Database.NULL_CLOB) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testClobMethod() { + assertEquals(Database.NULL_CLOB, Database.clob(null)); + } + + @Test + public void testBlobMethod() { + assertEquals(Database.NULL_BLOB, Database.blob(null)); + } + + @Test + public void testClobMethodPresent() { + assertEquals("a", Database.clob("a")); + } + + @Test + public void testBlobMethodPresent() { + byte[] b = new byte[1]; + assertEquals(b, Database.blob(b)); + } + + @Test + public void testDateOfBirthNullableForReadMe() { + Database.test() // + .select("select date_of_birth from person where name='FRED'") // + .getAsOptional(Instant.class) // + .blockingForEach(System.out::println); + } + + @Test + public void testInsertNullClobAndReadClobAsTuple2() { + try (Database db = db()) { + insertNullClob(db); + db.select("select document, document from person_clob where name='FRED'") // + .getAs(String.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Tuple2.create(null, null)) // + .assertComplete(); + } + } + + @Test + public void testInsertClobAndReadClobAsString() { + try (Database db = db()) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue("some + // text + // here") + // // + .assertComplete(); + } + } + + @Test + public void testInsertClobAndReadClobUsingReader() { + try (Database db = db()) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(Reader.class) // + .map(r -> read(r)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + } + + @Test + public void testInsertBlobAndReadBlobAsByteArray() { + try (Database db = db()) { + insertPersonBlob(db); + db.select("select document from person_blob where name='FRED'") // + .getAs(byte[].class) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + } + + private static void insertPersonBlob(Database db) { + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", bytes) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsInputStream() { + try (Database db = db()) { + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", new ByteArrayInputStream(bytes)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_blob where name='FRED'") // + .getAs(InputStream.class) // + .map(is -> read(is)) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + } + + private static String read(Reader reader) throws IOException { + StringBuffer s = new StringBuffer(); + char[] ch = new char[128]; + int n = 0; + while ((n = reader.read(ch)) != -1) { + s.append(ch, 0, n); + } + reader.close(); + return s.toString(); + } + + private static byte[] read(InputStream is) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] b = new byte[128]; + int n = 0; + while ((n = is.read(b)) != -1) { + bytes.write(b, 0, n); + } + is.close(); + return bytes.toByteArray(); + } + + private void testHealthCheck(Predicate healthy) throws InterruptedException { + TestScheduler scheduler = new TestScheduler(); + + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(10, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) // + .healthy(healthy) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) // + .scheduler(scheduler) // + .maxPoolSize(1) // + .build(); + + try (Database db = Database.from(pool)) { + TestSubscriber ts0 = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test(); + ts0.assertValueCount(0) // + .assertNotComplete(); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + ts0.assertValueCount(1) // + .assertComplete(); + TestSubscriber ts = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test() // + .assertValueCount(0); + log.debug("done2"); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + Thread.sleep(200); + ts.assertValueCount(1); + Thread.sleep(200); + ts.assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testShutdownBeforeUse() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .scheduler(Schedulers.io()) // + .maxPoolSize(1) // + .build(); + pool.close(); + Database.from(pool) // + .select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(PoolClosedException.class); + } + + @Test + public void testFewerColumnsMappedThanAvailable() { + db().select("select name, score from person where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues("FRED") // + .assertComplete(); + } + + @Test + public void testMoreColumnsMappedThanAvailable() { + db() // + .select("select name, score from person where name='FRED'") // + .getAs(String.class, Integer.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(MoreColumnsRequestedThanExistException.class); + } + + @Test + public void testSelectTimestamp() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsDate() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Date.class) // + .map(d -> d.getTime()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsInstant() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Instant.class) // + .map(d -> d.toEpochMilli()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateCalendarParameter() { + Calendar c = GregorianCalendar.from(ZonedDateTime.parse("2017-03-25T15:37Z")); + try (Database db = db()) { + db.update("update person set registered=?") // + .parameter(c) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(c.getTimeInMillis()) // + .assertComplete(); + } + } + + @Test + public void testUpdateTimeParameter() { + try (Database db = db()) { + Time t = new Time(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + } + + @Test + public void testUpdateTimestampParameter() { + try (Database db = db()) { + Timestamp t = new Timestamp(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + } + + @Test + public void testUpdateSqlDateParameter() { + try (Database db = db()) { + java.sql.Date t = new java.sql.Date(1234); + + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS * 10000, TimeUnit.SECONDS) // + // TODO make a more accurate comparison using the current TZ + .assertValue(x -> Math.abs(x - 1234) <= TimeUnit.HOURS.toMillis(24)) // + .assertComplete(); + } + } + + @Test + public void testUpdateUtilDateParameter() { + try (Database db = db()) { + Date d = new Date(1234); + db.update("update person set registered=?") // + .parameter(d) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + } + + @Test + public void testUpdateTimestampAsInstant() { + try (Database db = db()) { + db.update("update person set registered=? where name='FRED'") // + .parameter(Instant.ofEpochMilli(FRED_REGISTERED_TIME)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + } + + @Test + public void testUpdateTimestampAsZonedDateTime() { + try (Database db = db()) { + db.update("update person set registered=? where name='FRED'") // + .parameter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(FRED_REGISTERED_TIME), + ZoneOffset.UTC.normalized())) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + } + + @Test + public void testCompleteCompletes() { + Database db = db(1); + db // + .update("update person set score=-3 where name='FRED'") // + .complete() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingAwait(); + + int score = db.select("select score from person where name='FRED'") // + .getAs(Integer.class) // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingFirst(); + assertEquals(-3, score); + } + + @Test + public void testComplete() throws InterruptedException { + Database db = db(1); + Completable a = db // + .update("update person set score=-3 where name='FRED'") // + .complete(); + db.update("update person set score=-4 where score = -3") // + .dependsOn(a) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testCountsOnlyInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .countsOnly() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3) // + .assertComplete(); + } + + @Test + public void testCountsInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .counts() // + .doOnNext(System.out::println) // + .toList() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3 + && list.get(1).isComplete() && list.size() == 2) // + .assertComplete(); + } + + @Test + public void testTx() throws InterruptedException { + Database db = db(3); + Single> transaction = db // + .update("update person set score=-3 where name='FRED'") // + .transaction(); + + transaction // + .doOnDispose(() -> log.debug("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + log.debug("flatmapping"); + return tx // + .update("update person set score = -4 where score = -3") // + .countsOnly() // + .doOnSubscribe(s -> log.debug("subscribed")) // + .doOnNext(num -> log.debug("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testTxAfterSelect() { + Database db = db(3); + Single> transaction = db // + .select("select score from person where name='FRED'") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .firstOrError(); + + transaction // + .doOnDispose(() -> log.debug("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + log.debug("flatmapping"); + return tx // + .update("update person set score = -4 where score = ?") // + .parameter(tx.value()) // + .countsOnly() // + .doOnSubscribe(s -> log.debug("subscribed")) // + .doOnNext(num -> log.debug("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testSingleFlatMap() { + Single.just(1).flatMapPublisher(n -> Flowable.just(1)).test(1).assertValue(1) + .assertComplete(); + } + + @Test + public void testAutomappedInstanceHasMeaningfulToStringMethod() { + info(); + String s = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.toString()) // + .blockingSingle(); + assertEquals("Person2[name=FRED, score=21]", s); + } + + @Test + public void testAutomappedEquals() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(x)) // + .blockingSingle(); + assertTrue(b); + } + + @Test + public void testAutomappedDoesNotEqualNull() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(null)) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedDoesNotEqual() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(new Object())) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedHashCode() { + Person2 p = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .blockingSingle(); + assertTrue(p.hashCode() != 0); + } + + @Test + public void testAutomappedWithParametersThatProvokesMoreThanOneQuery() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(2) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsAndHashCodeIsDistinctOnValues() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .distinct() // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsDifferentiatesDifferentInterfacesWithSameMethodNamesAndValues() { + PersonDistinct1 p1 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct1.class) // + .blockingFirst(); + + PersonDistinct2 p2 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct2.class) // + .blockingFirst(); + + assertNotEquals(p1, p2); + } + + @Test + public void testAutomappedObjectsWhenDefaultMethodInvoked() { + PersonWithDefaultMethod p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethod.class) // + .blockingFirst(); + assertEquals("fred", p.nameLower()); + } + + // @Test + // public void testDefaultMethod() throws NoSuchMethodException, + // IllegalAccessException { + // MethodHandles.lookup().findSpecial(PersonWithDefaultMethod.class, + // "nameLower", + // MethodType.methodType(String.class, new Class[] {}), + // PersonWithDefaultMethod.class) + //// .bindTo(x); + // } + + @Test(expected = AutomappedInterfaceInaccessibleException.class) + public void testAutomappedObjectsWhenDefaultMethodInvokedAndIsNonPublicThrows() { + PersonWithDefaultMethodNonPublic p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethodNonPublic.class) // + .blockingFirst(); + p.nameLower(); + } + + @Test + public void testBlockingDatabase() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransacted() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .map(x -> x.value()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransactedNested() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .flatMap(tx -> tx.select("select name from person where score=?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + public interface PersonWithDefaultMethod { + @Column + String name(); + + @Column + int score(); + + public default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonWithDefaultMethodNonPublic { + @Column + String name(); + + @Column + int score(); + + default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonDistinct1 { + @Column + String name(); + + @Column + int score(); + + } + + interface PersonDistinct2 { + @Column + String name(); + + @Column + int score(); + + } + + interface Score { + @Column + int score(); + } + + interface Person { + @Column + String name(); + } + + interface Person2 { + @Column + String name(); + + @Column + int score(); + } + + interface Person3 { + @Column("name") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person4 { + @Column("namez") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person5 { + @Index(1) + String fullName(); + + @Index(2) + int examScore(); + } + + interface Person6 { + @Index(1) + String fullName(); + + @Index(3) + int examScore(); + } + + interface Person7 { + @Index(1) + String fullName(); + + @Index(0) + int examScore(); + } + + interface Person8 { + @Column + int name(); + } + + interface Person9 { + @Column + String name(); + + @Index(2) + int score(); + } + + interface PersonNoAnnotation { + String name(); + } + + @Query("select name, score from person order by name") + interface Person10 { + + @Column + String name(); + + @Column + int score(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.davidmoten.rx.jdbc.Database` acquired by call to `db()` at line 745 is not released after line 747. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DatabaseTest.testSelectTransactedCount() + +### Procedure Id: +org.davidmoten.rx.jdbc.DatabaseTest.testSelectTransactedCount():void.a330b89cb4153f27bcbdc56e36f4a482 + +### File: +src/test/java/org/davidmoten/rx/jdbc/DatabaseTest.java + +### Key: +DatabaseTest.java|testSelectTransactedCount|RESOURCE_LEAK + +### Node Key: +b1e1d2e868cbf5fb020e794c7723980b + +### Hash: +41b025f2c9bd60ec3bea1934b7b1db50 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10878/instruction.md b/inferredbugs-10878/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0732b32d5c0d04984e19eb69117a5abeae93e67b --- /dev/null +++ b/inferredbugs-10878/instruction.md @@ -0,0 +1,2432 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rxjava2-jdbc +**Bug ID:** 60 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.davidmoten.rx.jdbc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLSyntaxErrorException; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.log4j.Level; +import org.apache.log4j.LogManager; +import org.davidmoten.rx.jdbc.annotations.Column; +import org.davidmoten.rx.jdbc.annotations.Index; +import org.davidmoten.rx.jdbc.annotations.Query; +import org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.AutomappedInterfaceInaccessibleException; +import org.davidmoten.rx.jdbc.exceptions.ColumnIndexOutOfRangeException; +import org.davidmoten.rx.jdbc.exceptions.ColumnNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.MoreColumnsRequestedThanExistException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterFoundButSqlDoesNotHaveNamesException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterMissingException; +import org.davidmoten.rx.jdbc.exceptions.QueryAnnotationMissingException; +import org.davidmoten.rx.jdbc.pool.DatabaseCreator; +import org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool; +import org.davidmoten.rx.jdbc.pool.Pools; +import org.davidmoten.rx.jdbc.tuple.Tuple2; +import org.davidmoten.rx.jdbc.tuple.Tuple3; +import org.davidmoten.rx.jdbc.tuple.Tuple4; +import org.davidmoten.rx.jdbc.tuple.Tuple5; +import org.davidmoten.rx.jdbc.tuple.Tuple6; +import org.davidmoten.rx.jdbc.tuple.Tuple7; +import org.davidmoten.rx.jdbc.tuple.TupleN; +import org.davidmoten.rx.pool.PoolClosedException; +import org.h2.jdbc.JdbcSQLException; +import org.hsqldb.jdbc.JDBCBlobFile; +import org.hsqldb.jdbc.JDBCClobFile; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.davidmoten.guavamini.Lists; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Observable; +import io.reactivex.Scheduler; +import io.reactivex.Single; +import io.reactivex.functions.Predicate; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subscribers.TestSubscriber; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class DatabaseTest { + + private static final long FRED_REGISTERED_TIME = 1442515672690L; + private static final int NAMES_COUNT_BIG = 5163; + private static final Logger log = LoggerFactory.getLogger(DatabaseTest.class); + private static final int TIMEOUT_SECONDS = 2; + + private static Database db() { + return DatabaseCreator.create(1); + } + + private static Database blocking() { + return DatabaseCreator.createBlocking(); + } + + private static Database db(int poolSize) { + return DatabaseCreator.create(poolSize); + } + + private static Database big(int poolSize) { + return DatabaseCreator.create(poolSize, true, Schedulers.computation()); + } + + @Test + public void testSelectUsingQuestionMark() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNamedParameterList() { + try (Database db = db()) { + db.select("select score from person where name=:name") // + .parameters(Parameter.named("name", "FRED").value("JOSEPH").list()) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameters() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterStream(Flowable.just("FRED", "JOSEPH")) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersInLists() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED"), Arrays.asList("JOSEPH"))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testDrivingSelectWithoutParametersUsingParameterStream() { + try (Database db = db()) { + db.select("select count(*) from person") // + .parameters(1, 2, 3) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterStream(Flowable.just("FRED", 21, "JOSEPH", 34)) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameterListsTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED", 21), Arrays.asList("JOSEPH", 34))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkWithPublicTestingDatabase() { + try (Database db = Database.test()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSize() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(2) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSizeZero() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(0) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectWithFetchSizeNegative() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(-1); + } + } + + @Test + public void testSelectUsingNonBlockingBuilder() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(1, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES) // + .checkoutRetryInterval(1, TimeUnit.SECONDS) // + .healthy(c -> c.prepareStatement("select 1").execute()) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) // + .maxPoolSize(3) // + .build(); + + try (Database db = Database.from(pool)) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test(timeout = 40000) + public void testSelectUsingNonBlockingBuilderConcurrencyTest() + throws InterruptedException, TimeoutException { + info(); + try { + try (Database db = db(3)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(50)); + int n = 10000; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } else { + // log.debug(iCopy + " succeeded"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + } + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test(timeout = 5000) + public void testSelectConcurrencyTest() throws InterruptedException, TimeoutException { + debug(); + try { + try (Database db = db(1)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(2)); + int n = 2; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + log.info("submitted " + i); + } + if (!latch.await(5000, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test + public void testDatabaseClose() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingName() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNameNotGiven() { + try (Database db = db()) { + db // + .select("select score from person where name=:name and name<>:name2") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterMissingException.class) // + .assertNoValues(); + } + } + + @Test + public void testSelectUsingParameterNameNullNameWhenSqlHasNoNames() { + db() // + .select("select score from person where name=?") // + .parameter(Parameter.create("name", "FRED")) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterFoundButSqlDoesNotHaveNamesException.class) // + .assertNoValues(); + } + + @Test + public void testUpdateWithNull() { + try (Database db = db()) { + db // + .update("update person set date_of_birth = :dob") // + .parameter(Parameter.create("dob", null)) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithNull() { + try (Database db = db()) { + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", Database.NULL_CLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithClob() throws SQLException { + try (Database db = db()) { + Clob clob = new JDBCClobFile(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", clob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithReader() throws FileNotFoundException { + try (Database db = db()) { + Reader reader = new FileReader(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", reader) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithBlob() throws SQLException { + try (Database db = db()) { + Blob blob = new JDBCBlobFile(new File("src/test/resources/big.txt")); + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", blob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithNull() { + try (Database db = db()) { + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", Database.NULL_BLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test(expected = NullPointerException.class) + public void testSelectUsingNullNameInParameter() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter(null, "FRED"); // + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameDoesNotExist() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameters("nam", "FRED"); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameters("FRED", "JOSEPH"); + } + } + + @Test + public void testSelectTransacted() { + try (Database db = db()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .getAs(Integer.class) // + .doOnNext(tx -> log + .debug(tx.isComplete() ? "complete" : String.valueOf(tx.value()))) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedAnnotatedTransacted() { + try (Database db = db()) { + db // + .select(Person10.class) // + .transacted() // + .valuesOnly() // + .get().test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedTransactedValuesOnly() { + try (Database db = db()) { + db // + .select("select name, score from person") // + .transacted() // + .valuesOnly() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedTransacted() { + try (Database db = db()) { + db // + .select("select name, score from person") // + .transacted() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + } + + @Test + public void testSelectTransactedTuple2() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + } + } + + @Test + public void testSelectTransactedTuple3() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + } + } + + @Test + public void testSelectTransactedTuple4() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + } + } + + @Test + public void testSelectTransactedTuple5() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + } + } + + @Test + public void testSelectTransactedTuple6() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + } + } + + @Test + public void testSelectTransactedTuple7() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + assertEquals("FRED", t.value()._7()); + } + } + + @Test + public void testSelectTransactedTupleN() { + List>> list = db() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getTupleN() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertEquals("FRED", list.get(0).value().values().get(0)); + assertEquals(21, (int) list.get(0).value().values().get(1)); + assertTrue(list.get(1).isComplete()); + assertEquals(2, list.size()); + } + + @Test + public void testSelectTransactedCount() { + db() // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAs() { + db() // + .select("select name from person") // + .transacted() // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAsOptional() { + List>> list = db() // + .select("select name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAsOptional(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertTrue(list.get(0).isValue()); + assertEquals("FRED", list.get(0).value().get()); + assertTrue(list.get(1).isComplete()); + } + + @Test + public void testDatabaseFrom() { + Database.from(DatabaseCreator.nextUrl(), 3) // + .select("select name from person") // + .getAs(String.class) // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(JdbcSQLException.class); + } + + @Test + public void testSelectTransactedChained() throws Exception { + Database db = db(); + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .transactedValuesOnly() // + .getAs(Integer.class) // + .doOnNext( + tx -> log.debug(tx.isComplete() ? "complete" : String.valueOf(tx.value())))// + .flatMap(tx -> tx // + .select("select name from person where score = ?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + @Test + public void databaseIsAutoCloseable() { + try (Database db = db()) { + log.debug(db.toString()); + } + } + + @Test + public void testSelectChained() { + try (Database db = db(1)) { + // we can do this with 1 connection only! + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .doOnNext(System.out::println) // + .concatMap(score -> { + log.info("score={}", score); + return db // + .select("select name from person where score = ?") // + .parameter(score) // + .getAs(String.class) // + .doOnComplete( + () -> log.info("completed select where score=" + score)); + }) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); // + } + } + + @Test + @SuppressFBWarnings + public void testReadMeFragment1() { + try (Database db = db()) { + db.select("select name from person") // + .getAs(String.class) // + .forEach(System.out::println); + } + } + + @Test + public void testReadMeFragmentColumnDoesNotExistEmitsSqlSyntaxErrorException() { + try (Database db = Database.test()) { + db.select("select nam from person") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(SQLSyntaxErrorException.class); + } + } + + @Test + public void testReadMeFragmentDerbyHealthCheck() { + try (Database db = Database.test()) { + db.select("select 'a' from sysibm.sysdummy1") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("a") // + .assertComplete(); + } + } + + @Test + @SuppressFBWarnings + public void testTupleSupport() { + try (Database db = db()) { + db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .forEach(System.out::println); + } + } + + @Test + public void testDelayedCallsAreNonBlocking() throws InterruptedException { + List list = new CopyOnWriteArrayList(); + try (Database db = db(1)) { // + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> Thread.sleep(1000)) // + .subscribeOn(Schedulers.io()) // + .subscribe(); + Thread.sleep(100); + CountDownLatch latch = new CountDownLatch(1); + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> list.add("emitted")) // + .doOnNext(x -> log.debug("emitted on " + Thread.currentThread().getName())) // + .doOnNext(x -> latch.countDown()) // + .subscribe(); + list.add("subscribed"); + assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + assertEquals(Arrays.asList("subscribed", "emitted"), list); + } + } + + @Test + public void testAutoMapToInterface() { + try (Database db = db()) { + db // + .select("select name from person") // + .autoMap(Person.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithoutAnnotationstsError() { + try (Database db = db()) { + db // + .select("select name from person") // + .autoMap(PersonNoAnnotation.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(AnnotationsNotFoundException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithTwoMethods() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person2.class) // + .firstOrError() // + .map(Person2::score) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnName() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person3.class) // + .firstOrError() // + .map(Person3::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person4.class) // + .firstOrError() // + .map(Person4::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnNotFoundException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithIndex() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person5.class) // + .firstOrError() // + .map(Person5::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithIndexTooLarge() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person6.class) // + .firstOrError() // + .map(Person6::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithIndexTooSmall() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person7.class) // + .firstOrError() // + .map(Person7::examScore) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + } + + @Test + public void testAutoMapWithUnmappableColumnType() { + try (Database db = db()) { + db // + .select("select name from person order by name") // + .autoMap(Person8.class) // + .map(p -> p.name()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ClassCastException.class); + } + } + + @Test + public void testAutoMapWithMixIndexAndName() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person9.class) // + .firstOrError() // + .map(Person9::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapWithQueryInAnnotation() { + try (Database db = db()) { + db.select(Person10.class) // + .get() // + .firstOrError() // + .map(Person10::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + @Ignore + public void testAutoMapForReadMe() { + Database // + .test() // + .select(Person10.class) // + .get(Person10::name) // + .blockingForEach(System.out::println); + } + + @Test(expected = QueryAnnotationMissingException.class) + public void testAutoMapWithoutQueryInAnnotation() { + try (Database db = db()) { + db.select(Person.class); + } + } + + @Test + public void testSelectWithoutWhereClause() { + try (Database db = db()) { + Assert.assertEquals(3, (long) db.select("select name from person") // + .count() // + .blockingGet()); + } + } + + @Test + public void testTuple3() { + try (Database db = db()) { + db // + .select("select name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple3.create("FRED", 21, "FRED")); // + } + } + + @Test + public void testTuple4() { + try (Database db = db()) { + db // + .select("select name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple4.create("FRED", 21, "FRED", 21)); // + } + } + + @Test + public void testTuple5() { + db() // + .select("select name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple5.create("FRED", 21, "FRED", 21, "FRED")); // + } + + @Test + public void testTuple6() { + db() // + .select("select name, score, name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21)); // + } + + @Test + public void testTuple7() { + db() // + .select("select name, score, name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() + .assertValue(Tuple7.create("FRED", 21, "FRED", 21, "FRED", 21, "FRED")); // + } + + @Test + public void testTupleN() { + db() // + .select("select name, score, name from person order by name") // + .getTupleN() // + .firstOrError().test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(TupleN.create("FRED", 21, "FRED")); // + } + + @Test + public void testHealthCheck() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + return !once.compareAndSet(true, false); + }); + } + + @Test + public void testHealthCheckThatThrows() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + if (!once.compareAndSet(true, false)) + return true; + else + throw new RuntimeException("health check failed"); + }); + } + + @Test + public void testUpdateOneRow() { + db().update("update person set score=20 where name='FRED'") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateThreeRows() { + db().update("update person set score=20") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + + @Test + public void testUpdateWithParameter() { + db().update("update person set score=20 where name=?") // + .parameter("FRED").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateWithParameterTwoRuns() { + db().update("update person set score=20 where name=?") // + .parameters("FRED", "JOSEPH").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + } + + @Test + public void testUpdateAllWithParameterFourRuns() { + db().update("update person set score=?") // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testUpdateWithBatchSize2() { + db().update("update person set score=?") // + .batchSize(2) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testUpdateWithBatchSize3GreaterThanNumRecords() { + db().update("update person set score=?") // + .batchSize(3) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testInsert() { + Database db = db(); + db.update("insert into person(name, score) values(?,?)") // + .parameters("DAVE", 12, "ANNE", 18) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + List> list = db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .toList() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingGet(); + assertTrue(list.contains(Tuple2.create("DAVE", 12))); + assertTrue(list.contains(Tuple2.create("ANNE", 18))); + } + + @Test + public void testReturnGeneratedKeys() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + + @Test + public void testReturnGeneratedKeysDerby() { + Database db = DatabaseCreator.createDerby(1); + + // note is a table with auto increment + db.update("insert into note2(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors().assertValues(1, 3) // + .assertComplete(); + + db.update("insert into note2(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(5, 7) // + .assertComplete(); + } + + @Test(expected = IllegalArgumentException.class) + public void testReturnGeneratedKeysWithBatchSizeShouldThrow() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .batchSize(2) // + .returnGeneratedKeys(); + } + + @Test + public void testTransactedReturnGeneratedKeys() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + + @Test + public void testTransactedReturnGeneratedKeys2() { + Database db = db(); + // note is a table with auto increment + Flowable a = db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .startWith(a) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2, 3, 4) // + .assertComplete(); + } + + @Test + public void testUpdateWithinTransaction() { + db() // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnFlowable() { + Database db = db(); + Flowable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnObservable() { + Database db = db(); + Observable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().toObservable(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnOnSingle() { + Database db = db(); + Single a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().count(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnCompletable() { + Database db = db(); + Completable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().ignoreElements(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testUpdateWithinTransactionBatchSize0() { + db() // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(0) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + + private static void info() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + private static void debug() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + @Test + public void testCreateBig() { + info(); + big(5).select("select count(*) from person") // + .getAs(Integer.class) // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue(5163) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBig() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBigInputBatchSize2000() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(2000) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testInsertNullClobAndReadClobAsString() { + Database db = db(); + insertNullClob(db); + db.select("select document from person_clob where name='FRED'") // + .getAsOptional(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Optional.empty()) // + .assertComplete(); + } + + private static void insertNullClob(Database db) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", Database.NULL_CLOB) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testClobMethod() { + assertEquals(Database.NULL_CLOB, Database.clob(null)); + } + + @Test + public void testBlobMethod() { + assertEquals(Database.NULL_BLOB, Database.blob(null)); + } + + @Test + public void testClobMethodPresent() { + assertEquals("a", Database.clob("a")); + } + + @Test + public void testBlobMethodPresent() { + byte[] b = new byte[1]; + assertEquals(b, Database.blob(b)); + } + + @Test + public void testDateOfBirthNullableForReadMe() { + Database.test() // + .select("select date_of_birth from person where name='FRED'") // + .getAsOptional(Instant.class) // + .blockingForEach(System.out::println); + } + + @Test + public void testInsertNullClobAndReadClobAsTuple2() { + Database db = db(); + insertNullClob(db); + db.select("select document, document from person_clob where name='FRED'") // + .getAs(String.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Tuple2.create(null, null)) // + .assertComplete(); + } + + @Test + public void testInsertClobAndReadClobAsString() { + Database db = db(); + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue("some + // text + // here") + // // + .assertComplete(); + } + + @Test + public void testInsertClobAndReadClobUsingReader() { + Database db = db(); + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(Reader.class) // + .map(r -> read(r)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsByteArray() { + Database db = db(); + insertPersonBlob(db); + db.select("select document from person_blob where name='FRED'") // + .getAs(byte[].class) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + private static void insertPersonBlob(Database db) { + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", bytes) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsInputStream() { + Database db = db(); + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", new ByteArrayInputStream(bytes)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_blob where name='FRED'") // + .getAs(InputStream.class) // + .map(is -> read(is)) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + private static String read(Reader reader) throws IOException { + StringBuffer s = new StringBuffer(); + char[] ch = new char[128]; + int n = 0; + while ((n = reader.read(ch)) != -1) { + s.append(ch, 0, n); + } + reader.close(); + return s.toString(); + } + + private static byte[] read(InputStream is) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] b = new byte[128]; + int n = 0; + while ((n = is.read(b)) != -1) { + bytes.write(b, 0, n); + } + is.close(); + return bytes.toByteArray(); + } + + private void testHealthCheck(Predicate healthy) throws InterruptedException { + TestScheduler scheduler = new TestScheduler(); + + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(10, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) // + .healthy(healthy) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) // + .scheduler(scheduler) // + .maxPoolSize(1) // + .build(); + + try (Database db = Database.from(pool)) { + TestSubscriber ts0 = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test(); + ts0.assertValueCount(0) // + .assertNotComplete(); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + ts0.assertValueCount(1) // + .assertComplete(); + TestSubscriber ts = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test() // + .assertValueCount(0); + log.debug("done2"); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + Thread.sleep(200); + ts.assertValueCount(1); + Thread.sleep(200); + ts.assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testShutdownBeforeUse() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .scheduler(Schedulers.io()) // + .maxPoolSize(1) // + .build(); + pool.close(); + Database.from(pool) // + .select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(PoolClosedException.class); + } + + @Test + public void testFewerColumnsMappedThanAvailable() { + db().select("select name, score from person where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues("FRED") // + .assertComplete(); + } + + @Test + public void testMoreColumnsMappedThanAvailable() { + db() // + .select("select name, score from person where name='FRED'") // + .getAs(String.class, Integer.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(MoreColumnsRequestedThanExistException.class); + } + + @Test + public void testSelectTimestamp() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsDate() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Date.class) // + .map(d -> d.getTime()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsInstant() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Instant.class) // + .map(d -> d.toEpochMilli()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateCalendarParameter() { + Calendar c = GregorianCalendar.from(ZonedDateTime.parse("2017-03-25T15:37Z")); + Database db = db(); + db.update("update person set registered=?") // + .parameter(c) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(c.getTimeInMillis()) // + .assertComplete(); + } + + @Test + public void testUpdateTimeParameter() { + Database db = db(); + Time t = new Time(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampParameter() { + Database db = db(); + Timestamp t = new Timestamp(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateSqlDateParameter() { + Database db = db(); + java.sql.Date t = new java.sql.Date(1234); + + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS * 10000, TimeUnit.SECONDS) // + // TODO make a more accurate comparison using the current TZ + .assertValue(x -> Math.abs(x - 1234) <= TimeUnit.HOURS.toMillis(24)) // + .assertComplete(); + } + + @Test + public void testUpdateUtilDateParameter() { + Database db = db(); + Date d = new Date(1234); + db.update("update person set registered=?") // + .parameter(d) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampAsInstant() { + Database db = db(); + db.update("update person set registered=? where name='FRED'") // + .parameter(Instant.ofEpochMilli(FRED_REGISTERED_TIME)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampAsZonedDateTime() { + Database db = db(); + db.update("update person set registered=? where name='FRED'") // + .parameter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(FRED_REGISTERED_TIME), + ZoneOffset.UTC.normalized())) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testCompleteCompletes() { + Database db = db(1); + db // + .update("update person set score=-3 where name='FRED'") // + .complete() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingAwait(); + + int score = db.select("select score from person where name='FRED'") // + .getAs(Integer.class) // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingFirst(); + assertEquals(-3, score); + } + + @Test + public void testComplete() throws InterruptedException { + Database db = db(1); + Completable a = db // + .update("update person set score=-3 where name='FRED'") // + .complete(); + db.update("update person set score=-4 where score = -3") // + .dependsOn(a) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testCountsOnlyInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .countsOnly() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3) // + .assertComplete(); + } + + @Test + public void testCountsInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .counts() // + .doOnNext(System.out::println) // + .toList() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3 + && list.get(1).isComplete() && list.size() == 2) // + .assertComplete(); + } + + @Test + public void testTx() throws InterruptedException { + Database db = db(3); + Single> transaction = db // + .update("update person set score=-3 where name='FRED'") // + .transaction(); + + transaction // + .doOnDispose(() -> log.debug("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + log.debug("flatmapping"); + return tx // + .update("update person set score = -4 where score = -3") // + .countsOnly() // + .doOnSubscribe(s -> log.debug("subscribed")) // + .doOnNext(num -> log.debug("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testTxAfterSelect() { + Database db = db(3); + Single> transaction = db // + .select("select score from person where name='FRED'") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .firstOrError(); + + transaction // + .doOnDispose(() -> log.debug("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + log.debug("flatmapping"); + return tx // + .update("update person set score = -4 where score = ?") // + .parameter(tx.value()) // + .countsOnly() // + .doOnSubscribe(s -> log.debug("subscribed")) // + .doOnNext(num -> log.debug("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testSingleFlatMap() { + Single.just(1).flatMapPublisher(n -> Flowable.just(1)).test(1).assertValue(1) + .assertComplete(); + } + + @Test + public void testAutomappedInstanceHasMeaningfulToStringMethod() { + info(); + String s = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.toString()) // + .blockingSingle(); + assertEquals("Person2[name=FRED, score=21]", s); + } + + @Test + public void testAutomappedEquals() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(x)) // + .blockingSingle(); + assertTrue(b); + } + + @Test + public void testAutomappedDoesNotEqualNull() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(null)) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedDoesNotEqual() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(new Object())) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedHashCode() { + Person2 p = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .blockingSingle(); + assertTrue(p.hashCode() != 0); + } + + @Test + public void testAutomappedWithParametersThatProvokesMoreThanOneQuery() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(2) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsAndHashCodeIsDistinctOnValues() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .distinct() // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsDifferentiatesDifferentInterfacesWithSameMethodNamesAndValues() { + PersonDistinct1 p1 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct1.class) // + .blockingFirst(); + + PersonDistinct2 p2 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct2.class) // + .blockingFirst(); + + assertNotEquals(p1, p2); + } + + @Test + public void testAutomappedObjectsWhenDefaultMethodInvoked() { + PersonWithDefaultMethod p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethod.class) // + .blockingFirst(); + assertEquals("fred", p.nameLower()); + } + + // @Test + // public void testDefaultMethod() throws NoSuchMethodException, + // IllegalAccessException { + // MethodHandles.lookup().findSpecial(PersonWithDefaultMethod.class, + // "nameLower", + // MethodType.methodType(String.class, new Class[] {}), + // PersonWithDefaultMethod.class) + //// .bindTo(x); + // } + + @Test(expected = AutomappedInterfaceInaccessibleException.class) + public void testAutomappedObjectsWhenDefaultMethodInvokedAndIsNonPublicThrows() { + PersonWithDefaultMethodNonPublic p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethodNonPublic.class) // + .blockingFirst(); + p.nameLower(); + } + + @Test + public void testBlockingDatabase() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransacted() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .map(x -> x.value()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransactedNested() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .flatMap(tx -> tx.select("select name from person where score=?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + public interface PersonWithDefaultMethod { + @Column + String name(); + + @Column + int score(); + + public default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonWithDefaultMethodNonPublic { + @Column + String name(); + + @Column + int score(); + + default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonDistinct1 { + @Column + String name(); + + @Column + int score(); + + } + + interface PersonDistinct2 { + @Column + String name(); + + @Column + int score(); + + } + + interface Score { + @Column + int score(); + } + + interface Person { + @Column + String name(); + } + + interface Person2 { + @Column + String name(); + + @Column + int score(); + } + + interface Person3 { + @Column("name") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person4 { + @Column("namez") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person5 { + @Index(1) + String fullName(); + + @Index(2) + int examScore(); + } + + interface Person6 { + @Index(1) + String fullName(); + + @Index(3) + int examScore(); + } + + interface Person7 { + @Index(1) + String fullName(); + + @Index(0) + int examScore(); + } + + interface Person8 { + @Column + int name(); + } + + interface Person9 { + @Column + String name(); + + @Index(2) + int score(); + } + + interface PersonNoAnnotation { + String name(); + } + + @Query("select name, score from person order by name") + interface Person10 { + + @Column + String name(); + + @Column + int score(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.davidmoten.rx.jdbc.Database` acquired by call to `db()` at line 1164 is not released after line 1166. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DatabaseTest.testTupleN() + +### Procedure Id: +org.davidmoten.rx.jdbc.DatabaseTest.testTupleN():void.5f90ad2a3d1595dab199601458cf6012 + +### File: +src/test/java/org/davidmoten/rx/jdbc/DatabaseTest.java + +### Key: +DatabaseTest.java|testTupleN|RESOURCE_LEAK + +### Node Key: +42f56fda1ad408e362508b93a175bb0c + +### Hash: +5ca8411f27dbeb97d59bfea555cf274c + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10882/instruction.md b/inferredbugs-10882/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..87ade892b6d436d155aba3fdd10bf299347a95c6 --- /dev/null +++ b/inferredbugs-10882/instruction.md @@ -0,0 +1,2334 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rxjava2-jdbc +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.davidmoten.rx.jdbc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLSyntaxErrorException; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.log4j.Level; +import org.apache.log4j.LogManager; +import org.davidmoten.rx.jdbc.annotations.Column; +import org.davidmoten.rx.jdbc.annotations.Index; +import org.davidmoten.rx.jdbc.annotations.Query; +import org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.AutomappedInterfaceInaccessibleException; +import org.davidmoten.rx.jdbc.exceptions.ColumnIndexOutOfRangeException; +import org.davidmoten.rx.jdbc.exceptions.ColumnNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.MoreColumnsRequestedThanExistException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterFoundButSqlDoesNotHaveNamesException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterMissingException; +import org.davidmoten.rx.jdbc.exceptions.QueryAnnotationMissingException; +import org.davidmoten.rx.jdbc.pool.DatabaseCreator; +import org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool; +import org.davidmoten.rx.jdbc.pool.Pools; +import org.davidmoten.rx.jdbc.tuple.Tuple2; +import org.davidmoten.rx.jdbc.tuple.Tuple3; +import org.davidmoten.rx.jdbc.tuple.Tuple4; +import org.davidmoten.rx.jdbc.tuple.Tuple5; +import org.davidmoten.rx.jdbc.tuple.Tuple6; +import org.davidmoten.rx.jdbc.tuple.Tuple7; +import org.davidmoten.rx.jdbc.tuple.TupleN; +import org.davidmoten.rx.pool.PoolClosedException; +import org.h2.jdbc.JdbcSQLException; +import org.hsqldb.jdbc.JDBCBlobFile; +import org.hsqldb.jdbc.JDBCClobFile; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.davidmoten.guavamini.Lists; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Observable; +import io.reactivex.Scheduler; +import io.reactivex.Single; +import io.reactivex.functions.Predicate; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subscribers.TestSubscriber; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class DatabaseTest { + + private static final long FRED_REGISTERED_TIME = 1442515672690L; + private static final int NAMES_COUNT_BIG = 5163; + private static final Logger log = LoggerFactory.getLogger(DatabaseTest.class); + private static final int TIMEOUT_SECONDS = 2; + + private static Database db() { + return DatabaseCreator.create(1); + } + + private static Database blocking() { + return DatabaseCreator.createBlocking(); + } + + private static Database db(int poolSize) { + return DatabaseCreator.create(poolSize); + } + + private static Database big(int poolSize) { + return DatabaseCreator.create(poolSize, true, Schedulers.computation()); + } + + @Test + public void testSelectUsingQuestionMark() { + db().select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testSelectUsingNamedParameterList() { + db().select("select score from person where name=:name") // + .parameters(Parameter.named("name", "FRED").value("JOSEPH").list()) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameters() { + db().select("select score from person where name=?") // + .parameterStream(Flowable.just("FRED", "JOSEPH")) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersInLists() { + db().select("select score from person where name=?") // + .parameterListStream(Flowable.just(Arrays.asList("FRED"), Arrays.asList("JOSEPH"))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testDrivingSelectWithoutParametersUsingParameterStream() { + db().select("select count(*) from person") // + .parameters(1, 2, 3) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3) // + .assertComplete(); + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersTwoParametersPerQuery() { + db().select("select score from person where name=? and score = ?") // + .parameterStream(Flowable.just("FRED", 21, "JOSEPH", 34)) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameterListsTwoParametersPerQuery() { + db().select("select score from person where name=? and score = ?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED", 21), Arrays.asList("JOSEPH", 34))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testSelectUsingQuestionMarkWithPublicTestingDatabase() { + Database.test() // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testSelectWithFetchSize() { + db().select("select score from person order by name") // + .fetchSize(2) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + + @Test + public void testSelectWithFetchSizeZero() { + db().select("select score from person order by name") // + .fetchSize(0) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectWithFetchSizeNegative() { + db().select("select score from person order by name") // + .fetchSize(-1); + } + + @Test + public void testSelectUsingNonBlockingBuilder() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(1, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES) // + .checkoutRetryInterval(1, TimeUnit.SECONDS) // + .healthy(c -> c.prepareStatement("select 1").execute()) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) // + .maxPoolSize(3) // + .build(); + + try (Database db = Database.from(pool)) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test(timeout = 40000) + public void testSelectUsingNonBlockingBuilderConcurrencyTest() + throws InterruptedException, TimeoutException { + info(); + try { + try (Database db = db(3)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(50)); + int n = 10000; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } else { + // System.out.println(iCopy + " succeeded"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + } + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test(timeout = 5000) + public void testSelectConcurrencyTest() throws InterruptedException, TimeoutException { + debug(); + try { + try (Database db = db(1)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(2)); + int n = 2; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + log.info("submitted " + i); + } + if (!latch.await(5000, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test + public void testDatabaseClose() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingName() { + db() // + .select("select score from person where name=:name") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testSelectUsingNameNotGiven() { + db() // + .select("select score from person where name=:name and name<>:name2") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterMissingException.class) // + .assertNoValues(); + } + + @Test + public void testSelectUsingParameterNameNullNameWhenSqlHasNoNames() { + db() // + .select("select score from person where name=?") // + .parameter(Parameter.create("name", "FRED")) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterFoundButSqlDoesNotHaveNamesException.class) // + .assertNoValues(); + } + + @Test + public void testUpdateWithNull() { + db() // + .update("update person set date_of_birth = :dob") // + .parameter(Parameter.create("dob", null)) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + + @Test + public void testUpdateClobWithNull() { + Database db = db(); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", Database.NULL_CLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateClobWithClob() throws SQLException { + Database db = db(); + Clob clob = new JDBCClobFile(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", clob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateClobWithReader() throws FileNotFoundException { + Database db = db(); + Reader reader = new FileReader(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", reader) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateBlobWithBlob() throws SQLException { + Database db = db(); + Blob blob = new JDBCBlobFile(new File("src/test/resources/big.txt")); + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", blob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateBlobWithNull() { + Database db = db(); + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", Database.NULL_BLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test(expected = NullPointerException.class) + public void testSelectUsingNullNameInParameter() { + db() // + .select("select score from person where name=:name") // + .parameter(null, "FRED"); // + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameDoesNotExist() { + db() // + .select("select score from person where name=:name") // + .parameters("nam", "FRED"); + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() { + db() // + .select("select score from person where name=:name") // + .parameters("FRED", "JOSEPH"); + } + + @Test + public void testSelectTransacted() { + System.out.println("testSelectTransacted"); + db() // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .getAs(Integer.class) // + .doOnNext(tx -> System.out.println(tx.isComplete() ? "complete" : tx.value())) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + + @Test + public void testSelectAutomappedAnnotatedTransacted() { + db() // + .select(Person10.class) // + .transacted() // + .valuesOnly() // + .get().test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + + @Test + public void testSelectAutomappedTransactedValuesOnly() { + db() // + .select("select name, score from person") // + .transacted() // + .valuesOnly() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + + @Test + public void testSelectAutomappedTransacted() { + db() // + .select("select name, score from person") // + .transacted() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + + @Test + public void testSelectTransactedTuple2() { + Tx> t = db() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + } + + @Test + public void testSelectTransactedTuple3() { + Tx> t = db() // + .select("select name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + } + + @Test + public void testSelectTransactedTuple4() { + Tx> t = db() // + .select("select name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + } + + @Test + public void testSelectTransactedTuple5() { + Tx> t = db() // + .select("select name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + } + + @Test + public void testSelectTransactedTuple6() { + Tx> t = db() // + .select("select name, score, name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + } + + @Test + public void testSelectTransactedTuple7() { + Tx> t = db() // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + assertEquals("FRED", t.value()._7()); + } + + @Test + public void testSelectTransactedTupleN() { + List>> list = db() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getTupleN() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertEquals("FRED", list.get(0).value().values().get(0)); + assertEquals(21, (int) list.get(0).value().values().get(1)); + assertTrue(list.get(1).isComplete()); + assertEquals(2, list.size()); + } + + @Test + public void testSelectTransactedCount() { + db() // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAs() { + db() // + .select("select name from person") // + .transacted() // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAsOptional() { + List>> list = db() // + .select("select name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAsOptional(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertTrue(list.get(0).isValue()); + assertEquals("FRED", list.get(0).value().get()); + assertTrue(list.get(1).isComplete()); + } + + @Test + public void testDatabaseFrom() { + Database.from(DatabaseCreator.nextUrl(), 3) // + .select("select name from person") // + .getAs(String.class) // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(JdbcSQLException.class); + } + + @Test + public void testSelectTransactedChained() throws Exception { + Database db = db(); + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .transactedValuesOnly() // + .getAs(Integer.class) // + .doOnNext(tx -> System.out.println(tx.isComplete() ? "complete" : tx.value()))// + .flatMap(tx -> tx // + .select("select name from person where score = ?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + @Test + public void databaseIsAutoCloseable() { + try (Database db = db()) { + log.debug(db.toString()); + } + } + + @Test + public void testSelectChained() { + System.out.println("testSelectChained"); + // we can do this with 1 connection only! + Database db = db(1); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .doOnNext(System.out::println) // + .concatMap(score -> { + log.info("score={}", score); + return db // + .select("select name from person where score = ?") // + .parameter(score) // + .getAs(String.class) // + .doOnComplete(() -> log.info("completed select where score=" + score)); + }) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); // + } + + @Test + @SuppressFBWarnings + public void testReadMeFragment1() { + Database db = Database.test(); + db.select("select name from person") // + .getAs(String.class) // + .forEach(System.out::println); + } + + @Test + public void testReadMeFragmentColumnDoesNotExistEmitsSqlSyntaxErrorException() { + Database db = Database.test(); + db.select("select nam from person") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(SQLSyntaxErrorException.class); + } + + @Test + public void testReadMeFragmentDerbyHealthCheck() { + Database db = Database.test(); + db.select("select 'a' from sysibm.sysdummy1") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("a") // + .assertComplete(); + } + + @Test + @SuppressFBWarnings + public void testTupleSupport() { + db().select("select name, score from person") // + .getAs(String.class, Integer.class) // + .forEach(System.out::println); + } + + @Test + public void testDelayedCallsAreNonBlocking() throws InterruptedException { + List list = new CopyOnWriteArrayList(); + Database db = db(1); // + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> Thread.sleep(1000)) // + .subscribeOn(Schedulers.io()) // + .subscribe(); + Thread.sleep(100); + CountDownLatch latch = new CountDownLatch(1); + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> list.add("emitted")) // + .doOnNext(x -> System.out.println("emitted on " + Thread.currentThread().getName())) // + .doOnNext(x -> latch.countDown()) // + .subscribe(); + list.add("subscribed"); + assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + assertEquals(Arrays.asList("subscribed", "emitted"), list); + } + + @Test + public void testAutoMapToInterface() { + db() // + .select("select name from person") // + .autoMap(Person.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + + @Test + public void testAutoMapToInterfaceWithoutAnnotationsEmitsError() { + db() // + .select("select name from person") // + .autoMap(PersonNoAnnotation.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(AnnotationsNotFoundException.class); + } + + @Test + public void testAutoMapToInterfaceWithTwoMethods() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person2.class) // + .firstOrError() // + .map(Person2::score) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnName() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person3.class) // + .firstOrError() // + .map(Person3::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person4.class) // + .firstOrError() // + .map(Person4::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnNotFoundException.class); + } + + @Test + public void testAutoMapToInterfaceWithIndex() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person5.class) // + .firstOrError() // + .map(Person5::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapToInterfaceWithIndexTooLarge() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person6.class) // + .firstOrError() // + .map(Person6::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + + @Test + public void testAutoMapToInterfaceWithIndexTooSmall() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person7.class) // + .firstOrError() // + .map(Person7::examScore) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + + @Test + public void testAutoMapWithUnmappableColumnType() { + db() // + .select("select name from person order by name") // + .autoMap(Person8.class) // + .map(p -> p.name()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ClassCastException.class); + } + + @Test + public void testAutoMapWithMixIndexAndName() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person9.class) // + .firstOrError() // + .map(Person9::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapWithQueryInAnnotation() { + db().select(Person10.class) // + .get() // + .firstOrError() // + .map(Person10::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + @Ignore + public void testAutoMapForReadMe() { + Database // + .test() // + .select(Person10.class) // + .get(Person10::name) // + .blockingForEach(System.out::println); + } + + @Test(expected = QueryAnnotationMissingException.class) + public void testAutoMapWithoutQueryInAnnotation() { + db().select(Person.class); + } + + @Test + public void testSelectWithoutWhereClause() { + Assert.assertEquals(3, (long) db().select("select name from person") // + .count() // + .blockingGet()); + } + + @Test + public void testTuple3() { + db() // + .select("select name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple3.create("FRED", 21, "FRED")); // + } + + @Test + public void testTuple4() { + db() // + .select("select name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple4.create("FRED", 21, "FRED", 21)); // + } + + @Test + public void testTuple5() { + db() // + .select("select name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple5.create("FRED", 21, "FRED", 21, "FRED")); // + } + + @Test + public void testTuple6() { + db() // + .select("select name, score, name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21)); // + } + + @Test + public void testTuple7() { + db() // + .select("select name, score, name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() + .assertValue(Tuple7.create("FRED", 21, "FRED", 21, "FRED", 21, "FRED")); // + } + + @Test + public void testTupleN() { + db() // + .select("select name, score, name from person order by name") // + .getTupleN() // + .firstOrError().test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(TupleN.create("FRED", 21, "FRED")); // + } + + @Test + public void testHealthCheck() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + return !once.compareAndSet(true, false); + }); + } + + @Test + public void testHealthCheckThatThrows() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + if (!once.compareAndSet(true, false)) + return true; + else + throw new RuntimeException("health check failed"); + }); + } + + @Test + public void testUpdateOneRow() { + db().update("update person set score=20 where name='FRED'") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateThreeRows() { + db().update("update person set score=20") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + + @Test + public void testUpdateWithParameter() { + db().update("update person set score=20 where name=?") // + .parameter("FRED").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateWithParameterTwoRuns() { + db().update("update person set score=20 where name=?") // + .parameters("FRED", "JOSEPH").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + } + + @Test + public void testUpdateAllWithParameterFourRuns() { + db().update("update person set score=?") // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testUpdateWithBatchSize2() { + db().update("update person set score=?") // + .batchSize(2) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testUpdateWithBatchSize3GreaterThanNumRecords() { + db().update("update person set score=?") // + .batchSize(3) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testInsert() { + Database db = db(); + db.update("insert into person(name, score) values(?,?)") // + .parameters("DAVE", 12, "ANNE", 18) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + List> list = db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .toList() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingGet(); + assertTrue(list.contains(Tuple2.create("DAVE", 12))); + assertTrue(list.contains(Tuple2.create("ANNE", 18))); + } + + @Test + public void testReturnGeneratedKeys() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + + @Test + public void testReturnGeneratedKeysDerby() { + Database db = DatabaseCreator.createDerby(1); + + // note is a table with auto increment + db.update("insert into note2(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors().assertValues(1, 3) // + .assertComplete(); + + db.update("insert into note2(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(5, 7) // + .assertComplete(); + } + + @Test(expected = IllegalArgumentException.class) + public void testReturnGeneratedKeysWithBatchSizeShouldThrow() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .batchSize(2) // + .returnGeneratedKeys(); + } + + @Test + public void testTransactedReturnGeneratedKeys() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + + @Test + public void testTransactedReturnGeneratedKeys2() { + Database db = db(); + // note is a table with auto increment + Flowable a = db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .startWith(a) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2, 3, 4) // + .assertComplete(); + } + + @Test + public void testUpdateWithinTransaction() { + db() // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnFlowable() { + Database db = db(); + Flowable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnObservable() { + Database db = db(); + Observable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().toObservable(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnOnSingle() { + Database db = db(); + Single a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().count(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnCompletable() { + Database db = db(); + Completable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().ignoreElements(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testUpdateWithinTransactionBatchSize0() { + db() // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(0) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + + private static void info() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + private static void debug() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + @Test + public void testCreateBig() { + info(); + big(5).select("select count(*) from person") // + .getAs(Integer.class) // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue(5163) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBig() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBigInputBatchSize2000() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(2000) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testInsertNullClobAndReadClobAsString() { + Database db = db(); + insertNullClob(db); + db.select("select document from person_clob where name='FRED'") // + .getAsOptional(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Optional.empty()) // + .assertComplete(); + } + + private static void insertNullClob(Database db) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", Database.NULL_CLOB) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testClobMethod() { + assertEquals(Database.NULL_CLOB, Database.clob(null)); + } + + @Test + public void testBlobMethod() { + assertEquals(Database.NULL_BLOB, Database.blob(null)); + } + + @Test + public void testClobMethodPresent() { + assertEquals("a", Database.clob("a")); + } + + @Test + public void testBlobMethodPresent() { + byte[] b = new byte[1]; + assertEquals(b, Database.blob(b)); + } + + @Test + public void testDateOfBirthNullableForReadMe() { + Database.test() // + .select("select date_of_birth from person where name='FRED'") // + .getAsOptional(Instant.class) // + .blockingForEach(System.out::println); + } + + @Test + public void testInsertNullClobAndReadClobAsTuple2() { + Database db = db(); + insertNullClob(db); + db.select("select document, document from person_clob where name='FRED'") // + .getAs(String.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Tuple2.create(null, null)) // + .assertComplete(); + } + + @Test + public void testInsertClobAndReadClobAsString() { + Database db = db(); + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue("some + // text + // here") + // // + .assertComplete(); + } + + @Test + public void testInsertClobAndReadClobUsingReader() { + Database db = db(); + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(Reader.class) // + .map(r -> read(r)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsByteArray() { + Database db = db(); + insertPersonBlob(db); + db.select("select document from person_blob where name='FRED'") // + .getAs(byte[].class) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + private static void insertPersonBlob(Database db) { + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", bytes) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsInputStream() { + Database db = db(); + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", new ByteArrayInputStream(bytes)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_blob where name='FRED'") // + .getAs(InputStream.class) // + .map(is -> read(is)) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + private static String read(Reader reader) throws IOException { + StringBuffer s = new StringBuffer(); + char[] ch = new char[128]; + int n = 0; + while ((n = reader.read(ch)) != -1) { + s.append(ch, 0, n); + } + reader.close(); + return s.toString(); + } + + private static byte[] read(InputStream is) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] b = new byte[128]; + int n = 0; + while ((n = is.read(b)) != -1) { + bytes.write(b, 0, n); + } + is.close(); + return bytes.toByteArray(); + } + + private void testHealthCheck(Predicate healthy) throws InterruptedException { + TestScheduler scheduler = new TestScheduler(); + + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(10, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) // + .healthy(healthy) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) // + .scheduler(scheduler) // + .maxPoolSize(1) // + .build(); + + try (Database db = Database.from(pool)) { + TestSubscriber ts0 = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test(); + ts0.assertValueCount(0) // + .assertNotComplete(); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + ts0.assertValueCount(1) // + .assertComplete(); + TestSubscriber ts = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test() // + .assertValueCount(0); + System.out.println("done2"); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + Thread.sleep(200); + ts.assertValueCount(1); + Thread.sleep(200); + ts.assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testShutdownBeforeUse() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .scheduler(Schedulers.io()) // + .maxPoolSize(1) // + .build(); + pool.close(); + Database.from(pool) // + .select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(PoolClosedException.class); + } + + @Test + public void testFewerColumnsMappedThanAvailable() { + db().select("select name, score from person where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues("FRED") // + .assertComplete(); + } + + @Test + public void testMoreColumnsMappedThanAvailable() { + db() // + .select("select name, score from person where name='FRED'") // + .getAs(String.class, Integer.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(MoreColumnsRequestedThanExistException.class); + } + + @Test + public void testSelectTimestamp() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsDate() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Date.class) // + .map(d -> d.getTime()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsInstant() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Instant.class) // + .map(d -> d.toEpochMilli()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateCalendarParameter() { + Calendar c = GregorianCalendar.from(ZonedDateTime.parse("2017-03-25T15:37Z")); + Database db = db(); + db.update("update person set registered=?") // + .parameter(c) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(c.getTimeInMillis()) // + .assertComplete(); + } + + @Test + public void testUpdateTimeParameter() { + Database db = db(); + Time t = new Time(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampParameter() { + Database db = db(); + Timestamp t = new Timestamp(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateSqlDateParameter() { + Database db = db(); + java.sql.Date t = new java.sql.Date(1234); + + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS * 10000, TimeUnit.SECONDS) // + // TODO make a more accurate comparison using the current TZ + .assertValue(x -> Math.abs(x - 1234) <= TimeUnit.HOURS.toMillis(24)) // + .assertComplete(); + } + + @Test + public void testUpdateUtilDateParameter() { + Database db = db(); + Date d = new Date(1234); + db.update("update person set registered=?") // + .parameter(d) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampAsInstant() { + Database db = db(); + db.update("update person set registered=? where name='FRED'") // + .parameter(Instant.ofEpochMilli(FRED_REGISTERED_TIME)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampAsZonedDateTime() { + Database db = db(); + db.update("update person set registered=? where name='FRED'") // + .parameter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(FRED_REGISTERED_TIME), + ZoneOffset.UTC.normalized())) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testCompleteCompletes() { + Database db = db(1); + db // + .update("update person set score=-3 where name='FRED'") // + .complete() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingAwait(); + + int score = db.select("select score from person where name='FRED'") // + .getAs(Integer.class) // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingFirst(); + assertEquals(-3, score); + } + + @Test + public void testComplete() throws InterruptedException { + Database db = db(1); + Completable a = db // + .update("update person set score=-3 where name='FRED'") // + .complete(); + db.update("update person set score=-4 where score = -3") // + .dependsOn(a) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testCountsOnlyInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .countsOnly() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3) // + .assertComplete(); + } + + @Test + public void testCountsInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .counts() // + .doOnNext(System.out::println) // + .toList() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3 + && list.get(1).isComplete() && list.size() == 2) // + .assertComplete(); + } + + @Test + public void testTx() throws InterruptedException { + Database db = db(3); + Single> transaction = db // + .update("update person set score=-3 where name='FRED'") // + .transaction(); + + transaction // + .doOnDispose(() -> System.out.println("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + System.out.println("flatmapping"); + return tx // + .update("update person set score = -4 where score = -3") // + .countsOnly() // + .doOnSubscribe(s -> System.out.println("subscribed")) // + .doOnNext(num -> System.out.println("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testTxAfterSelect() { + Database db = db(3); + Single> transaction = db // + .select("select score from person where name='FRED'") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .firstOrError(); + + transaction // + .doOnDispose(() -> System.out.println("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + System.out.println("flatmapping"); + return tx // + .update("update person set score = -4 where score = ?") // + .parameter(tx.value()) // + .countsOnly() // + .doOnSubscribe(s -> System.out.println("subscribed")) // + .doOnNext(num -> System.out.println("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testSingleFlatMap() { + Single.just(1).flatMapPublisher(n -> Flowable.just(1)).test(1).assertValue(1) + .assertComplete(); + } + + @Test + public void testAutomappedInstanceHasMeaningfulToStringMethod() { + info(); + String s = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.toString()) // + .blockingSingle(); + assertEquals("Person2[name=FRED, score=21]", s); + } + + @Test + public void testAutomappedEquals() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(x)) // + .blockingSingle(); + assertTrue(b); + } + + @Test + public void testAutomappedDoesNotEqualNull() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(null)) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedDoesNotEqual() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(new Object())) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedHashCode() { + Person2 p = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .blockingSingle(); + assertTrue(p.hashCode() != 0); + } + + @Test + public void testAutomappedWithParametersThatProvokesMoreThanOneQuery() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(2) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsAndHashCodeIsDistinctOnValues() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .distinct() // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsDifferentiatesDifferentInterfacesWithSameMethodNamesAndValues() { + PersonDistinct1 p1 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct1.class) // + .blockingFirst(); + + PersonDistinct2 p2 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct2.class) // + .blockingFirst(); + + assertNotEquals(p1, p2); + } + + @Test + public void testAutomappedObjectsWhenDefaultMethodInvoked() { + PersonWithDefaultMethod p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethod.class) // + .blockingFirst(); + assertEquals("fred", p.nameLower()); + } + + // @Test + // public void testDefaultMethod() throws NoSuchMethodException, + // IllegalAccessException { + // MethodHandles.lookup().findSpecial(PersonWithDefaultMethod.class, + // "nameLower", + // MethodType.methodType(String.class, new Class[] {}), + // PersonWithDefaultMethod.class) + //// .bindTo(x); + // } + + @Test(expected = AutomappedInterfaceInaccessibleException.class) + public void testAutomappedObjectsWhenDefaultMethodInvokedAndIsNonPublicThrows() { + PersonWithDefaultMethodNonPublic p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethodNonPublic.class) // + .blockingFirst(); + p.nameLower(); + } + + @Test + public void testBlockingDatabase() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransacted() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .map(x -> x.value()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransactedNested() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .flatMap(tx -> tx.select("select name from person where score=?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + public interface PersonWithDefaultMethod { + @Column + String name(); + + @Column + int score(); + + public default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonWithDefaultMethodNonPublic { + @Column + String name(); + + @Column + int score(); + + default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonDistinct1 { + @Column + String name(); + + @Column + int score(); + + } + + interface PersonDistinct2 { + @Column + String name(); + + @Column + int score(); + + } + + interface Score { + @Column + int score(); + } + + interface Person { + @Column + String name(); + } + + interface Person2 { + @Column + String name(); + + @Column + int score(); + } + + interface Person3 { + @Column("name") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person4 { + @Column("namez") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person5 { + @Index(1) + String fullName(); + + @Index(2) + int examScore(); + } + + interface Person6 { + @Index(1) + String fullName(); + + @Index(3) + int examScore(); + } + + interface Person7 { + @Index(1) + String fullName(); + + @Index(0) + int examScore(); + } + + interface Person8 { + @Column + int name(); + } + + interface Person9 { + @Column + String name(); + + @Index(2) + int score(); + } + + interface PersonNoAnnotation { + String name(); + } + + @Query("select name, score from person order by name") + interface Person10 { + + @Column + String name(); + + @Column + int score(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.davidmoten.rx.jdbc.Database` acquired by call to `db()` at line 211 is not released after line 213. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DatabaseTest.testSelectWithFetchSize() + +### Procedure Id: +org.davidmoten.rx.jdbc.DatabaseTest.testSelectWithFetchSize():void.3dc88e3ad3f84467ebd1a8b6977f1f74 + +### File: +src/test/java/org/davidmoten/rx/jdbc/DatabaseTest.java + +### Key: +DatabaseTest.java|testSelectWithFetchSize|RESOURCE_LEAK + +### Node Key: +42f56fda1ad408e362508b93a175bb0c + +### Hash: +a2c7a411d2dbaa5b7c44e9e27506b000 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10883/instruction.md b/inferredbugs-10883/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6e0098cf10b8185bfc3d967df2c2d1393aba254a --- /dev/null +++ b/inferredbugs-10883/instruction.md @@ -0,0 +1,2367 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rxjava2-jdbc +**Bug ID:** 27 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.davidmoten.rx.jdbc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLSyntaxErrorException; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.log4j.Level; +import org.apache.log4j.LogManager; +import org.davidmoten.rx.jdbc.annotations.Column; +import org.davidmoten.rx.jdbc.annotations.Index; +import org.davidmoten.rx.jdbc.annotations.Query; +import org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.AutomappedInterfaceInaccessibleException; +import org.davidmoten.rx.jdbc.exceptions.ColumnIndexOutOfRangeException; +import org.davidmoten.rx.jdbc.exceptions.ColumnNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.MoreColumnsRequestedThanExistException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterFoundButSqlDoesNotHaveNamesException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterMissingException; +import org.davidmoten.rx.jdbc.exceptions.QueryAnnotationMissingException; +import org.davidmoten.rx.jdbc.pool.DatabaseCreator; +import org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool; +import org.davidmoten.rx.jdbc.pool.Pools; +import org.davidmoten.rx.jdbc.tuple.Tuple2; +import org.davidmoten.rx.jdbc.tuple.Tuple3; +import org.davidmoten.rx.jdbc.tuple.Tuple4; +import org.davidmoten.rx.jdbc.tuple.Tuple5; +import org.davidmoten.rx.jdbc.tuple.Tuple6; +import org.davidmoten.rx.jdbc.tuple.Tuple7; +import org.davidmoten.rx.jdbc.tuple.TupleN; +import org.davidmoten.rx.pool.PoolClosedException; +import org.h2.jdbc.JdbcSQLException; +import org.hsqldb.jdbc.JDBCBlobFile; +import org.hsqldb.jdbc.JDBCClobFile; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.davidmoten.guavamini.Lists; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Observable; +import io.reactivex.Scheduler; +import io.reactivex.Single; +import io.reactivex.functions.Predicate; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subscribers.TestSubscriber; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class DatabaseTest { + + private static final long FRED_REGISTERED_TIME = 1442515672690L; + private static final int NAMES_COUNT_BIG = 5163; + private static final Logger log = LoggerFactory.getLogger(DatabaseTest.class); + private static final int TIMEOUT_SECONDS = 2; + + private static Database db() { + return DatabaseCreator.create(1); + } + + private static Database blocking() { + return DatabaseCreator.createBlocking(); + } + + private static Database db(int poolSize) { + return DatabaseCreator.create(poolSize); + } + + private static Database big(int poolSize) { + return DatabaseCreator.create(poolSize, true, Schedulers.computation()); + } + + @Test + public void testSelectUsingQuestionMark() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNamedParameterList() { + try (Database db = db()) { + db.select("select score from person where name=:name") // + .parameters(Parameter.named("name", "FRED").value("JOSEPH").list()) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameters() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterStream(Flowable.just("FRED", "JOSEPH")) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersInLists() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED"), Arrays.asList("JOSEPH"))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testDrivingSelectWithoutParametersUsingParameterStream() { + try (Database db = db()) { + db.select("select count(*) from person") // + .parameters(1, 2, 3) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterStream(Flowable.just("FRED", 21, "JOSEPH", 34)) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameterListsTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED", 21), Arrays.asList("JOSEPH", 34))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkWithPublicTestingDatabase() { + try (Database db = Database.test()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSize() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(2) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSizeZero() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(0) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectWithFetchSizeNegative() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(-1); + } + } + + @Test + public void testSelectUsingNonBlockingBuilder() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(1, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES) // + .checkoutRetryInterval(1, TimeUnit.SECONDS) // + .healthy(c -> c.prepareStatement("select 1").execute()) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) // + .maxPoolSize(3) // + .build(); + + try (Database db = Database.from(pool)) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test(timeout = 40000) + public void testSelectUsingNonBlockingBuilderConcurrencyTest() + throws InterruptedException, TimeoutException { + info(); + try { + try (Database db = db(3)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(50)); + int n = 10000; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } else { + // System.out.println(iCopy + " succeeded"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + } + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test(timeout = 5000) + public void testSelectConcurrencyTest() throws InterruptedException, TimeoutException { + debug(); + try { + try (Database db = db(1)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(2)); + int n = 2; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + log.info("submitted " + i); + } + if (!latch.await(5000, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test + public void testDatabaseClose() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingName() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNameNotGiven() { + try (Database db = db()) { + db // + .select("select score from person where name=:name and name<>:name2") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterMissingException.class) // + .assertNoValues(); + } + } + + @Test + public void testSelectUsingParameterNameNullNameWhenSqlHasNoNames() { + db() // + .select("select score from person where name=?") // + .parameter(Parameter.create("name", "FRED")) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterFoundButSqlDoesNotHaveNamesException.class) // + .assertNoValues(); + } + + @Test + public void testUpdateWithNull() { + try (Database db = db()) { + db // + .update("update person set date_of_birth = :dob") // + .parameter(Parameter.create("dob", null)) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithNull() { + try (Database db = db()) { + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", Database.NULL_CLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithClob() throws SQLException { + try (Database db = db()) { + Clob clob = new JDBCClobFile(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", clob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithReader() throws FileNotFoundException { + try (Database db = db()) { + Reader reader = new FileReader(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", reader) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithBlob() throws SQLException { + try (Database db = db()) { + Blob blob = new JDBCBlobFile(new File("src/test/resources/big.txt")); + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", blob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithNull() { + Database db = db(); + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", Database.NULL_BLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test(expected = NullPointerException.class) + public void testSelectUsingNullNameInParameter() { + db() // + .select("select score from person where name=:name") // + .parameter(null, "FRED"); // + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameDoesNotExist() { + db() // + .select("select score from person where name=:name") // + .parameters("nam", "FRED"); + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() { + db() // + .select("select score from person where name=:name") // + .parameters("FRED", "JOSEPH"); + } + + @Test + public void testSelectTransacted() { + System.out.println("testSelectTransacted"); + db() // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .getAs(Integer.class) // + .doOnNext(tx -> System.out.println(tx.isComplete() ? "complete" : tx.value())) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + + @Test + public void testSelectAutomappedAnnotatedTransacted() { + db() // + .select(Person10.class) // + .transacted() // + .valuesOnly() // + .get().test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + + @Test + public void testSelectAutomappedTransactedValuesOnly() { + db() // + .select("select name, score from person") // + .transacted() // + .valuesOnly() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + + @Test + public void testSelectAutomappedTransacted() { + db() // + .select("select name, score from person") // + .transacted() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + + @Test + public void testSelectTransactedTuple2() { + Tx> t = db() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + } + + @Test + public void testSelectTransactedTuple3() { + Tx> t = db() // + .select("select name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + } + + @Test + public void testSelectTransactedTuple4() { + Tx> t = db() // + .select("select name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + } + + @Test + public void testSelectTransactedTuple5() { + Tx> t = db() // + .select("select name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + } + + @Test + public void testSelectTransactedTuple6() { + Tx> t = db() // + .select("select name, score, name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + } + + @Test + public void testSelectTransactedTuple7() { + Tx> t = db() // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + assertEquals("FRED", t.value()._7()); + } + + @Test + public void testSelectTransactedTupleN() { + List>> list = db() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getTupleN() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertEquals("FRED", list.get(0).value().values().get(0)); + assertEquals(21, (int) list.get(0).value().values().get(1)); + assertTrue(list.get(1).isComplete()); + assertEquals(2, list.size()); + } + + @Test + public void testSelectTransactedCount() { + db() // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAs() { + db() // + .select("select name from person") // + .transacted() // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAsOptional() { + List>> list = db() // + .select("select name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAsOptional(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertTrue(list.get(0).isValue()); + assertEquals("FRED", list.get(0).value().get()); + assertTrue(list.get(1).isComplete()); + } + + @Test + public void testDatabaseFrom() { + Database.from(DatabaseCreator.nextUrl(), 3) // + .select("select name from person") // + .getAs(String.class) // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(JdbcSQLException.class); + } + + @Test + public void testSelectTransactedChained() throws Exception { + Database db = db(); + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .transactedValuesOnly() // + .getAs(Integer.class) // + .doOnNext(tx -> System.out.println(tx.isComplete() ? "complete" : tx.value()))// + .flatMap(tx -> tx // + .select("select name from person where score = ?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + @Test + public void databaseIsAutoCloseable() { + try (Database db = db()) { + log.debug(db.toString()); + } + } + + @Test + public void testSelectChained() { + System.out.println("testSelectChained"); + // we can do this with 1 connection only! + Database db = db(1); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .doOnNext(System.out::println) // + .concatMap(score -> { + log.info("score={}", score); + return db // + .select("select name from person where score = ?") // + .parameter(score) // + .getAs(String.class) // + .doOnComplete(() -> log.info("completed select where score=" + score)); + }) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); // + } + + @Test + @SuppressFBWarnings + public void testReadMeFragment1() { + Database db = Database.test(); + db.select("select name from person") // + .getAs(String.class) // + .forEach(System.out::println); + } + + @Test + public void testReadMeFragmentColumnDoesNotExistEmitsSqlSyntaxErrorException() { + Database db = Database.test(); + db.select("select nam from person") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(SQLSyntaxErrorException.class); + } + + @Test + public void testReadMeFragmentDerbyHealthCheck() { + Database db = Database.test(); + db.select("select 'a' from sysibm.sysdummy1") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("a") // + .assertComplete(); + } + + @Test + @SuppressFBWarnings + public void testTupleSupport() { + db().select("select name, score from person") // + .getAs(String.class, Integer.class) // + .forEach(System.out::println); + } + + @Test + public void testDelayedCallsAreNonBlocking() throws InterruptedException { + List list = new CopyOnWriteArrayList(); + Database db = db(1); // + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> Thread.sleep(1000)) // + .subscribeOn(Schedulers.io()) // + .subscribe(); + Thread.sleep(100); + CountDownLatch latch = new CountDownLatch(1); + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> list.add("emitted")) // + .doOnNext(x -> System.out.println("emitted on " + Thread.currentThread().getName())) // + .doOnNext(x -> latch.countDown()) // + .subscribe(); + list.add("subscribed"); + assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + assertEquals(Arrays.asList("subscribed", "emitted"), list); + } + + @Test + public void testAutoMapToInterface() { + db() // + .select("select name from person") // + .autoMap(Person.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + + @Test + public void testAutoMapToInterfaceWithoutAnnotationsEmitsError() { + db() // + .select("select name from person") // + .autoMap(PersonNoAnnotation.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(AnnotationsNotFoundException.class); + } + + @Test + public void testAutoMapToInterfaceWithTwoMethods() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person2.class) // + .firstOrError() // + .map(Person2::score) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnName() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person3.class) // + .firstOrError() // + .map(Person3::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person4.class) // + .firstOrError() // + .map(Person4::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnNotFoundException.class); + } + + @Test + public void testAutoMapToInterfaceWithIndex() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person5.class) // + .firstOrError() // + .map(Person5::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapToInterfaceWithIndexTooLarge() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person6.class) // + .firstOrError() // + .map(Person6::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + + @Test + public void testAutoMapToInterfaceWithIndexTooSmall() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person7.class) // + .firstOrError() // + .map(Person7::examScore) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + + @Test + public void testAutoMapWithUnmappableColumnType() { + db() // + .select("select name from person order by name") // + .autoMap(Person8.class) // + .map(p -> p.name()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ClassCastException.class); + } + + @Test + public void testAutoMapWithMixIndexAndName() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person9.class) // + .firstOrError() // + .map(Person9::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapWithQueryInAnnotation() { + db().select(Person10.class) // + .get() // + .firstOrError() // + .map(Person10::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + @Ignore + public void testAutoMapForReadMe() { + Database // + .test() // + .select(Person10.class) // + .get(Person10::name) // + .blockingForEach(System.out::println); + } + + @Test(expected = QueryAnnotationMissingException.class) + public void testAutoMapWithoutQueryInAnnotation() { + db().select(Person.class); + } + + @Test + public void testSelectWithoutWhereClause() { + Assert.assertEquals(3, (long) db().select("select name from person") // + .count() // + .blockingGet()); + } + + @Test + public void testTuple3() { + db() // + .select("select name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple3.create("FRED", 21, "FRED")); // + } + + @Test + public void testTuple4() { + db() // + .select("select name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple4.create("FRED", 21, "FRED", 21)); // + } + + @Test + public void testTuple5() { + db() // + .select("select name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple5.create("FRED", 21, "FRED", 21, "FRED")); // + } + + @Test + public void testTuple6() { + db() // + .select("select name, score, name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21)); // + } + + @Test + public void testTuple7() { + db() // + .select("select name, score, name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() + .assertValue(Tuple7.create("FRED", 21, "FRED", 21, "FRED", 21, "FRED")); // + } + + @Test + public void testTupleN() { + db() // + .select("select name, score, name from person order by name") // + .getTupleN() // + .firstOrError().test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(TupleN.create("FRED", 21, "FRED")); // + } + + @Test + public void testHealthCheck() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + return !once.compareAndSet(true, false); + }); + } + + @Test + public void testHealthCheckThatThrows() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + if (!once.compareAndSet(true, false)) + return true; + else + throw new RuntimeException("health check failed"); + }); + } + + @Test + public void testUpdateOneRow() { + db().update("update person set score=20 where name='FRED'") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateThreeRows() { + db().update("update person set score=20") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + + @Test + public void testUpdateWithParameter() { + db().update("update person set score=20 where name=?") // + .parameter("FRED").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateWithParameterTwoRuns() { + db().update("update person set score=20 where name=?") // + .parameters("FRED", "JOSEPH").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + } + + @Test + public void testUpdateAllWithParameterFourRuns() { + db().update("update person set score=?") // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testUpdateWithBatchSize2() { + db().update("update person set score=?") // + .batchSize(2) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testUpdateWithBatchSize3GreaterThanNumRecords() { + db().update("update person set score=?") // + .batchSize(3) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testInsert() { + Database db = db(); + db.update("insert into person(name, score) values(?,?)") // + .parameters("DAVE", 12, "ANNE", 18) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + List> list = db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .toList() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingGet(); + assertTrue(list.contains(Tuple2.create("DAVE", 12))); + assertTrue(list.contains(Tuple2.create("ANNE", 18))); + } + + @Test + public void testReturnGeneratedKeys() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + + @Test + public void testReturnGeneratedKeysDerby() { + Database db = DatabaseCreator.createDerby(1); + + // note is a table with auto increment + db.update("insert into note2(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors().assertValues(1, 3) // + .assertComplete(); + + db.update("insert into note2(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(5, 7) // + .assertComplete(); + } + + @Test(expected = IllegalArgumentException.class) + public void testReturnGeneratedKeysWithBatchSizeShouldThrow() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .batchSize(2) // + .returnGeneratedKeys(); + } + + @Test + public void testTransactedReturnGeneratedKeys() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + + @Test + public void testTransactedReturnGeneratedKeys2() { + Database db = db(); + // note is a table with auto increment + Flowable a = db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .startWith(a) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2, 3, 4) // + .assertComplete(); + } + + @Test + public void testUpdateWithinTransaction() { + db() // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnFlowable() { + Database db = db(); + Flowable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnObservable() { + Database db = db(); + Observable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().toObservable(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnOnSingle() { + Database db = db(); + Single a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().count(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnCompletable() { + Database db = db(); + Completable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().ignoreElements(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testUpdateWithinTransactionBatchSize0() { + db() // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(0) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + + private static void info() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + private static void debug() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + @Test + public void testCreateBig() { + info(); + big(5).select("select count(*) from person") // + .getAs(Integer.class) // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue(5163) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBig() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBigInputBatchSize2000() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(2000) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testInsertNullClobAndReadClobAsString() { + Database db = db(); + insertNullClob(db); + db.select("select document from person_clob where name='FRED'") // + .getAsOptional(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Optional.empty()) // + .assertComplete(); + } + + private static void insertNullClob(Database db) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", Database.NULL_CLOB) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testClobMethod() { + assertEquals(Database.NULL_CLOB, Database.clob(null)); + } + + @Test + public void testBlobMethod() { + assertEquals(Database.NULL_BLOB, Database.blob(null)); + } + + @Test + public void testClobMethodPresent() { + assertEquals("a", Database.clob("a")); + } + + @Test + public void testBlobMethodPresent() { + byte[] b = new byte[1]; + assertEquals(b, Database.blob(b)); + } + + @Test + public void testDateOfBirthNullableForReadMe() { + Database.test() // + .select("select date_of_birth from person where name='FRED'") // + .getAsOptional(Instant.class) // + .blockingForEach(System.out::println); + } + + @Test + public void testInsertNullClobAndReadClobAsTuple2() { + Database db = db(); + insertNullClob(db); + db.select("select document, document from person_clob where name='FRED'") // + .getAs(String.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Tuple2.create(null, null)) // + .assertComplete(); + } + + @Test + public void testInsertClobAndReadClobAsString() { + Database db = db(); + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue("some + // text + // here") + // // + .assertComplete(); + } + + @Test + public void testInsertClobAndReadClobUsingReader() { + Database db = db(); + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(Reader.class) // + .map(r -> read(r)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsByteArray() { + Database db = db(); + insertPersonBlob(db); + db.select("select document from person_blob where name='FRED'") // + .getAs(byte[].class) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + private static void insertPersonBlob(Database db) { + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", bytes) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsInputStream() { + Database db = db(); + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", new ByteArrayInputStream(bytes)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_blob where name='FRED'") // + .getAs(InputStream.class) // + .map(is -> read(is)) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + private static String read(Reader reader) throws IOException { + StringBuffer s = new StringBuffer(); + char[] ch = new char[128]; + int n = 0; + while ((n = reader.read(ch)) != -1) { + s.append(ch, 0, n); + } + reader.close(); + return s.toString(); + } + + private static byte[] read(InputStream is) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] b = new byte[128]; + int n = 0; + while ((n = is.read(b)) != -1) { + bytes.write(b, 0, n); + } + is.close(); + return bytes.toByteArray(); + } + + private void testHealthCheck(Predicate healthy) throws InterruptedException { + TestScheduler scheduler = new TestScheduler(); + + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(10, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) // + .healthy(healthy) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) // + .scheduler(scheduler) // + .maxPoolSize(1) // + .build(); + + try (Database db = Database.from(pool)) { + TestSubscriber ts0 = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test(); + ts0.assertValueCount(0) // + .assertNotComplete(); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + ts0.assertValueCount(1) // + .assertComplete(); + TestSubscriber ts = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test() // + .assertValueCount(0); + System.out.println("done2"); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + Thread.sleep(200); + ts.assertValueCount(1); + Thread.sleep(200); + ts.assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testShutdownBeforeUse() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .scheduler(Schedulers.io()) // + .maxPoolSize(1) // + .build(); + pool.close(); + Database.from(pool) // + .select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(PoolClosedException.class); + } + + @Test + public void testFewerColumnsMappedThanAvailable() { + db().select("select name, score from person where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues("FRED") // + .assertComplete(); + } + + @Test + public void testMoreColumnsMappedThanAvailable() { + db() // + .select("select name, score from person where name='FRED'") // + .getAs(String.class, Integer.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(MoreColumnsRequestedThanExistException.class); + } + + @Test + public void testSelectTimestamp() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsDate() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Date.class) // + .map(d -> d.getTime()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsInstant() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Instant.class) // + .map(d -> d.toEpochMilli()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateCalendarParameter() { + Calendar c = GregorianCalendar.from(ZonedDateTime.parse("2017-03-25T15:37Z")); + Database db = db(); + db.update("update person set registered=?") // + .parameter(c) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(c.getTimeInMillis()) // + .assertComplete(); + } + + @Test + public void testUpdateTimeParameter() { + Database db = db(); + Time t = new Time(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampParameter() { + Database db = db(); + Timestamp t = new Timestamp(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateSqlDateParameter() { + Database db = db(); + java.sql.Date t = new java.sql.Date(1234); + + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS * 10000, TimeUnit.SECONDS) // + // TODO make a more accurate comparison using the current TZ + .assertValue(x -> Math.abs(x - 1234) <= TimeUnit.HOURS.toMillis(24)) // + .assertComplete(); + } + + @Test + public void testUpdateUtilDateParameter() { + Database db = db(); + Date d = new Date(1234); + db.update("update person set registered=?") // + .parameter(d) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampAsInstant() { + Database db = db(); + db.update("update person set registered=? where name='FRED'") // + .parameter(Instant.ofEpochMilli(FRED_REGISTERED_TIME)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampAsZonedDateTime() { + Database db = db(); + db.update("update person set registered=? where name='FRED'") // + .parameter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(FRED_REGISTERED_TIME), + ZoneOffset.UTC.normalized())) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testCompleteCompletes() { + Database db = db(1); + db // + .update("update person set score=-3 where name='FRED'") // + .complete() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingAwait(); + + int score = db.select("select score from person where name='FRED'") // + .getAs(Integer.class) // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingFirst(); + assertEquals(-3, score); + } + + @Test + public void testComplete() throws InterruptedException { + Database db = db(1); + Completable a = db // + .update("update person set score=-3 where name='FRED'") // + .complete(); + db.update("update person set score=-4 where score = -3") // + .dependsOn(a) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testCountsOnlyInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .countsOnly() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3) // + .assertComplete(); + } + + @Test + public void testCountsInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .counts() // + .doOnNext(System.out::println) // + .toList() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3 + && list.get(1).isComplete() && list.size() == 2) // + .assertComplete(); + } + + @Test + public void testTx() throws InterruptedException { + Database db = db(3); + Single> transaction = db // + .update("update person set score=-3 where name='FRED'") // + .transaction(); + + transaction // + .doOnDispose(() -> System.out.println("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + System.out.println("flatmapping"); + return tx // + .update("update person set score = -4 where score = -3") // + .countsOnly() // + .doOnSubscribe(s -> System.out.println("subscribed")) // + .doOnNext(num -> System.out.println("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testTxAfterSelect() { + Database db = db(3); + Single> transaction = db // + .select("select score from person where name='FRED'") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .firstOrError(); + + transaction // + .doOnDispose(() -> System.out.println("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + System.out.println("flatmapping"); + return tx // + .update("update person set score = -4 where score = ?") // + .parameter(tx.value()) // + .countsOnly() // + .doOnSubscribe(s -> System.out.println("subscribed")) // + .doOnNext(num -> System.out.println("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testSingleFlatMap() { + Single.just(1).flatMapPublisher(n -> Flowable.just(1)).test(1).assertValue(1) + .assertComplete(); + } + + @Test + public void testAutomappedInstanceHasMeaningfulToStringMethod() { + info(); + String s = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.toString()) // + .blockingSingle(); + assertEquals("Person2[name=FRED, score=21]", s); + } + + @Test + public void testAutomappedEquals() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(x)) // + .blockingSingle(); + assertTrue(b); + } + + @Test + public void testAutomappedDoesNotEqualNull() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(null)) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedDoesNotEqual() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(new Object())) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedHashCode() { + Person2 p = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .blockingSingle(); + assertTrue(p.hashCode() != 0); + } + + @Test + public void testAutomappedWithParametersThatProvokesMoreThanOneQuery() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(2) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsAndHashCodeIsDistinctOnValues() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .distinct() // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsDifferentiatesDifferentInterfacesWithSameMethodNamesAndValues() { + PersonDistinct1 p1 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct1.class) // + .blockingFirst(); + + PersonDistinct2 p2 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct2.class) // + .blockingFirst(); + + assertNotEquals(p1, p2); + } + + @Test + public void testAutomappedObjectsWhenDefaultMethodInvoked() { + PersonWithDefaultMethod p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethod.class) // + .blockingFirst(); + assertEquals("fred", p.nameLower()); + } + + // @Test + // public void testDefaultMethod() throws NoSuchMethodException, + // IllegalAccessException { + // MethodHandles.lookup().findSpecial(PersonWithDefaultMethod.class, + // "nameLower", + // MethodType.methodType(String.class, new Class[] {}), + // PersonWithDefaultMethod.class) + //// .bindTo(x); + // } + + @Test(expected = AutomappedInterfaceInaccessibleException.class) + public void testAutomappedObjectsWhenDefaultMethodInvokedAndIsNonPublicThrows() { + PersonWithDefaultMethodNonPublic p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethodNonPublic.class) // + .blockingFirst(); + p.nameLower(); + } + + @Test + public void testBlockingDatabase() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransacted() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .map(x -> x.value()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransactedNested() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .flatMap(tx -> tx.select("select name from person where score=?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + public interface PersonWithDefaultMethod { + @Column + String name(); + + @Column + int score(); + + public default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonWithDefaultMethodNonPublic { + @Column + String name(); + + @Column + int score(); + + default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonDistinct1 { + @Column + String name(); + + @Column + int score(); + + } + + interface PersonDistinct2 { + @Column + String name(); + + @Column + int score(); + + } + + interface Score { + @Column + int score(); + } + + interface Person { + @Column + String name(); + } + + interface Person2 { + @Column + String name(); + + @Column + int score(); + } + + interface Person3 { + @Column("name") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person4 { + @Column("namez") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person5 { + @Index(1) + String fullName(); + + @Index(2) + int examScore(); + } + + interface Person6 { + @Index(1) + String fullName(); + + @Index(3) + int examScore(); + } + + interface Person7 { + @Index(1) + String fullName(); + + @Index(0) + int examScore(); + } + + interface Person8 { + @Column + int name(); + } + + interface Person9 { + @Column + String name(); + + @Index(2) + int score(); + } + + interface PersonNoAnnotation { + String name(); + } + + @Query("select name, score from person order by name") + interface Person10 { + + @Column + String name(); + + @Column + int score(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.davidmoten.rx.jdbc.Database` acquired by call to `db()` at line 500 is not released after line 505. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DatabaseTest.testUpdateBlobWithNull() + +### Procedure Id: +org.davidmoten.rx.jdbc.DatabaseTest.testUpdateBlobWithNull():void.6bbd5415814b59652d5ad822b6e4f451 + +### File: +src/test/java/org/davidmoten/rx/jdbc/DatabaseTest.java + +### Key: +DatabaseTest.java|testUpdateBlobWithNull|RESOURCE_LEAK + +### Node Key: +a7e34068ba71f4238bb696ce5de4b213 + +### Hash: +d01cbcf3e38be7abb240b01b67f5a751 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10885/instruction.md b/inferredbugs-10885/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..28124b979fb292e3dd272ff0b078ea2f18921ecd --- /dev/null +++ b/inferredbugs-10885/instruction.md @@ -0,0 +1,2209 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rxjava2-jdbc +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.davidmoten.rx.jdbc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLSyntaxErrorException; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.log4j.Level; +import org.apache.log4j.LogManager; +import org.davidmoten.rx.jdbc.annotations.Column; +import org.davidmoten.rx.jdbc.annotations.Index; +import org.davidmoten.rx.jdbc.annotations.Query; +import org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.ColumnIndexOutOfRangeException; +import org.davidmoten.rx.jdbc.exceptions.ColumnNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.MethodCallNotSupportedException; +import org.davidmoten.rx.jdbc.exceptions.MoreColumnsRequestedThanExistException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterFoundButSqlDoesNotHaveNamesException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterMissingException; +import org.davidmoten.rx.jdbc.exceptions.QueryAnnotationMissingException; +import org.davidmoten.rx.jdbc.pool.DatabaseCreator; +import org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool2; +import org.davidmoten.rx.jdbc.pool.PoolClosedException; +import org.davidmoten.rx.jdbc.pool.Pools; +import org.davidmoten.rx.jdbc.tuple.Tuple2; +import org.davidmoten.rx.jdbc.tuple.Tuple3; +import org.davidmoten.rx.jdbc.tuple.Tuple4; +import org.davidmoten.rx.jdbc.tuple.Tuple5; +import org.davidmoten.rx.jdbc.tuple.Tuple6; +import org.davidmoten.rx.jdbc.tuple.Tuple7; +import org.davidmoten.rx.jdbc.tuple.TupleN; +import org.h2.jdbc.JdbcSQLException; +import org.hsqldb.jdbc.JDBCBlobFile; +import org.hsqldb.jdbc.JDBCClobFile; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.davidmoten.guavamini.Lists; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Observable; +import io.reactivex.Scheduler; +import io.reactivex.Single; +import io.reactivex.functions.Predicate; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subscribers.TestSubscriber; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class DatabaseTest { + + private static final long FRED_REGISTERED_TIME = 1442515672690L; + private static final int NAMES_COUNT_BIG = 5163; + private static final Logger log = LoggerFactory.getLogger(DatabaseTest.class); + private static final int TIMEOUT_SECONDS = 2; + + private static Database db() { + return DatabaseCreator.create(1); + } + + private static Database db(int poolSize) { + return DatabaseCreator.create(poolSize); + } + + private static Database big(int poolSize) { + return DatabaseCreator.create(poolSize, true, Schedulers.computation()); + } + + @Test + public void testSelectUsingQuestionMark() { + db().select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameters() { + db().select("select score from person where name=?") // + .parameterStream(Flowable.just("FRED", "JOSEPH")) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersInLists() { + db().select("select score from person where name=?") // + .parameterListStream(Flowable.just(Arrays.asList("FRED"), Arrays.asList("JOSEPH"))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testDrivingSelectWithoutParametersUsingParameterStream() { + db().select("select count(*) from person") // + .parameters(1, 2, 3) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3) // + .assertComplete(); + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersTwoParametersPerQuery() { + db().select("select score from person where name=? and score = ?") // + .parameterStream(Flowable.just("FRED", 21, "JOSEPH", 34)) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameterListsTwoParametersPerQuery() { + db().select("select score from person where name=? and score = ?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED", 21), Arrays.asList("JOSEPH", 34))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testSelectUsingQuestionMarkWithPublicTestingDatabase() { + Database.test() // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testSelectWithFetchSize() { + db().select("select score from person order by name") // + .fetchSize(2) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + + @Test + public void testSelectWithFetchSizeZero() { + db().select("select score from person order by name") // + .fetchSize(0) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectWithFetchSizeNegative() { + db().select("select score from person order by name") // + .fetchSize(-1); + } + + @Test + public void testSelectUsingNonBlockingBuilder() { + NonBlockingConnectionPool2 pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(1, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES) // + .healthy(c -> c.prepareStatement("select 1").execute()) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) // + .maxPoolSize(3) // + .build(); + + try (Database db = Database.from(pool)) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test(timeout = 40000) + public void testSelectUsingNonBlockingBuilderConcurrencyTest() + throws InterruptedException, TimeoutException { + info(); + try { + try (Database db = db(3)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(50)); + int n = 10000; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + } + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test(timeout = 5000) + public void testSelectConcurrencyTest() throws InterruptedException, TimeoutException { + debug(); + try { + try (Database db = db(1)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(2)); + int n = 2; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + log.info("submitted " + i); + } + if (!latch.await(5000, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test + public void testDatabaseClose() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingName() { + db() // + .select("select score from person where name=:name") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testSelectUsingNameNotGiven() { + db() // + .select("select score from person where name=:name and name<>:name2") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterMissingException.class) // + .assertNoValues(); + } + + @Test + public void testSelectUsingParameterNameNullNameWhenSqlHasNoNames() { + db() // + .select("select score from person where name=?") // + .parameter(Parameter.create("name", "FRED")) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterFoundButSqlDoesNotHaveNamesException.class) // + .assertNoValues(); + } + + @Test + public void testUpdateWithNull() { + db() // + .update("update person set date_of_birth = :dob") // + .parameter(Parameter.create("dob", null)) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + + @Test + public void testUpdateClobWithNull() { + Database db = db(); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", Database.NULL_CLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateClobWithClob() throws SQLException { + Database db = db(); + Clob clob = new JDBCClobFile(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", clob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateClobWithReader() throws FileNotFoundException { + Database db = db(); + Reader reader = new FileReader(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", reader) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateBlobWithBlob() throws SQLException { + Database db = db(); + Blob blob = new JDBCBlobFile(new File("src/test/resources/big.txt")); + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", blob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateBlobWithNull() { + Database db = db(); + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", Database.NULL_BLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test(expected = NullPointerException.class) + public void testSelectUsingNullNameInParameter() { + db() // + .select("select score from person where name=:name") // + .parameter(null, "FRED"); // + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameDoesNotExist() { + db() // + .select("select score from person where name=:name") // + .parameters("nam", "FRED"); + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() { + db() // + .select("select score from person where name=:name") // + .parameters("FRED", "JOSEPH"); + } + + @Test + public void testSelectTransacted() { + System.out.println("testSelectTransacted"); + db() // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .getAs(Integer.class) // + .doOnNext(tx -> System.out.println(tx.isComplete() ? "complete" : tx.value())) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + + @Test + public void testSelectAutomappedAnnotatedTransacted() { + db() // + .select(Person10.class) // + .transacted() // + .valuesOnly() // + .get().test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + + @Test + public void testSelectAutomappedTransactedValuesOnly() { + db() // + .select("select name, score from person") // + .transacted() // + .valuesOnly() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + + @Test + public void testSelectAutomappedTransacted() { + db() // + .select("select name, score from person") // + .transacted() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + + @Test + public void testSelectTransactedTuple2() { + Tx> t = db() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + } + + @Test + public void testSelectTransactedTuple3() { + Tx> t = db() // + .select("select name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + } + + @Test + public void testSelectTransactedTuple4() { + Tx> t = db() // + .select("select name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + } + + @Test + public void testSelectTransactedTuple5() { + Tx> t = db() // + .select("select name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + } + + @Test + public void testSelectTransactedTuple6() { + Tx> t = db() // + .select("select name, score, name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + } + + @Test + public void testSelectTransactedTuple7() { + Tx> t = db() // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + assertEquals("FRED", t.value()._7()); + } + + @Test + public void testSelectTransactedTupleN() { + List>> list = db() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getTupleN() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertEquals("FRED", list.get(0).value().values().get(0)); + assertEquals(21, (int) list.get(0).value().values().get(1)); + assertTrue(list.get(1).isComplete()); + assertEquals(2, list.size()); + } + + @Test + public void testSelectTransactedCount() { + db() // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAs() { + db() // + .select("select name from person") // + .transacted() // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAsOptional() { + List>> list = db() // + .select("select name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAsOptional(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertTrue(list.get(0).isValue()); + assertEquals("FRED", list.get(0).value().get()); + assertTrue(list.get(1).isComplete()); + } + + @Test + public void testDatabaseFrom() { + Database.from(DatabaseCreator.nextUrl(), 3) // + .select("select name from person") // + .getAs(String.class) // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(JdbcSQLException.class); + } + + @Test + public void testSelectTransactedChained() throws Exception { + Database db = db(); + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .transactedValuesOnly() // + .getAs(Integer.class) // + .doOnNext(tx -> System.out.println(tx.isComplete() ? "complete" : tx.value()))// + .flatMap(tx -> tx // + .select("select name from person where score = ?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + @Test + public void databaseIsAutoCloseable() { + try (Database db = db()) { + log.debug(db.toString()); + } + } + + @Test + public void testSelectChained() { + System.out.println("testSelectChained"); + // we can do this with 1 connection only! + Database db = db(1); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .doOnNext(System.out::println) // + .concatMap(score -> { + log.info("score={}", score); + return db // + .select("select name from person where score = ?") // + .parameter(score) // + .getAs(String.class) // + .doOnComplete(() -> log.info("completed select where score=" + score)); + }) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); // + } + + @Test + @SuppressFBWarnings + public void testReadMeFragment1() { + Database db = Database.test(); + db.select("select name from person") // + .getAs(String.class) // + .forEach(System.out::println); + } + + @Test + public void testReadMeFragmentColumnDoesNotExistEmitsSqlSyntaxErrorException() { + Database db = Database.test(); + db.select("select nam from person") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(SQLSyntaxErrorException.class); + } + + @Test + public void testReadMeFragmentDerbyHealthCheck() { + Database db = Database.test(); + db.select("select 'a' from sysibm.sysdummy1") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("a") // + .assertComplete(); + } + + @Test + @SuppressFBWarnings + public void testTupleSupport() { + db().select("select name, score from person") // + .getAs(String.class, Integer.class) // + .forEach(System.out::println); + } + + @Test + public void testDelayedCallsAreNonBlocking() throws InterruptedException { + List list = new CopyOnWriteArrayList(); + Database db = db(1); // + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> Thread.sleep(1000)) // + .subscribeOn(Schedulers.io()) // + .subscribe(); + Thread.sleep(100); + CountDownLatch latch = new CountDownLatch(1); + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> list.add("emitted")) // + .doOnNext(x -> System.out.println("emitted on " + Thread.currentThread().getName())) // + .doOnNext(x -> latch.countDown()) // + .subscribe(); + list.add("subscribed"); + assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + assertEquals(Arrays.asList("subscribed", "emitted"), list); + } + + @Test + public void testAutoMapToInterface() { + db() // + .select("select name from person") // + .autoMap(Person.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + + @Test + public void testAutoMapToInterfaceWithoutAnnotationsEmitsError() { + db() // + .select("select name from person") // + .autoMap(PersonNoAnnotation.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(AnnotationsNotFoundException.class); + } + + @Test + public void testAutoMapToInterfaceWithTwoMethods() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person2.class) // + .firstOrError() // + .map(Person2::score) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnName() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person3.class) // + .firstOrError() // + .map(Person3::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person4.class) // + .firstOrError() // + .map(Person4::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnNotFoundException.class); + } + + @Test + public void testAutoMapToInterfaceWithIndex() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person5.class) // + .firstOrError() // + .map(Person5::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapToInterfaceWithIndexTooLarge() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person6.class) // + .firstOrError() // + .map(Person6::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + + @Test + public void testAutoMapToInterfaceWithIndexTooSmall() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person7.class) // + .firstOrError() // + .map(Person7::examScore) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + + @Test + public void testAutoMapWithUnmappableColumnType() { + db() // + .select("select name from person order by name") // + .autoMap(Person8.class) // + .map(p -> p.name()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ClassCastException.class); + } + + @Test + public void testAutoMapWithMixIndexAndName() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person9.class) // + .firstOrError() // + .map(Person9::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapWithQueryInAnnotation() { + db().select(Person10.class) // + .get() // + .firstOrError() // + .map(Person10::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapForReadMe() { + Database // + .test() // + .select(Person10.class) // + .get(Person10::name) // + .blockingForEach(System.out::println); + } + + @Test(expected = QueryAnnotationMissingException.class) + public void testAutoMapWithoutQueryInAnnotation() { + db().select(Person.class); + } + + @Test + public void testSelectWithoutWhereClause() { + Assert.assertEquals(3, (long) db().select("select name from person") // + .count() // + .blockingGet()); + } + + @Test + public void testTuple3() { + db() // + .select("select name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple3.create("FRED", 21, "FRED")); // + } + + @Test + public void testTuple4() { + db() // + .select("select name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple4.create("FRED", 21, "FRED", 21)); // + } + + @Test + public void testTuple5() { + db() // + .select("select name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple5.create("FRED", 21, "FRED", 21, "FRED")); // + } + + @Test + public void testTuple6() { + db() // + .select("select name, score, name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21)); // + } + + @Test + public void testTuple7() { + db() // + .select("select name, score, name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() + .assertValue(Tuple7.create("FRED", 21, "FRED", 21, "FRED", 21, "FRED")); // + } + + @Test + public void testTupleN() { + db() // + .select("select name, score, name from person order by name") // + .getTupleN() // + .firstOrError().test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(TupleN.create("FRED", 21, "FRED")); // + } + + @Test + public void testHealthCheck() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + return !once.compareAndSet(true, false); + }); + } + + @Test + public void testHealthCheckThatThrows() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + if (!once.compareAndSet(true, false)) + return true; + else + throw new RuntimeException("health check failed"); + }); + } + + @Test + public void testUpdateOneRow() { + db().update("update person set score=20 where name='FRED'") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateThreeRows() { + db().update("update person set score=20") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + + @Test + public void testUpdateWithParameter() { + db().update("update person set score=20 where name=?") // + .parameter("FRED").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateWithParameterTwoRuns() { + db().update("update person set score=20 where name=?") // + .parameters("FRED", "JOSEPH").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + } + + @Test + public void testUpdateAllWithParameterFourRuns() { + db().update("update person set score=?") // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testUpdateWithBatchSize2() { + db().update("update person set score=?") // + .batchSize(2) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testUpdateWithBatchSize3GreaterThanNumRecords() { + db().update("update person set score=?") // + .batchSize(3) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testInsert() { + Database db = db(); + db.update("insert into person(name, score) values(?,?)") // + .parameters("DAVE", 12, "ANNE", 18) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + List> list = db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .toList() // + .blockingGet(); + assertTrue(list.contains(Tuple2.create("DAVE", 12))); + assertTrue(list.contains(Tuple2.create("ANNE", 18))); + } + + @Test + public void testReturnGeneratedKeys() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + + @Test + public void testReturnGeneratedKeysDerby() { + Database db = DatabaseCreator.createDerby(1); + + // note is a table with auto increment + db.update("insert into note2(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors().assertValues(1, 3) // + .assertComplete(); + + db.update("insert into note2(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(5, 7) // + .assertComplete(); + } + + @Test + public void testTransactedReturnGeneratedKeys() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + + @Test + public void testTransactedReturnGeneratedKeys2() { + Database db = db(); + // note is a table with auto increment + Flowable a = db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .startWith(a) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2, 3, 4) // + .assertComplete(); + } + + @Test + public void testUpdateWithinTransaction() { + db() // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnFlowable() { + Database db = db(); + Flowable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnObservable() { + Database db = db(); + Observable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().toObservable(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnOnSingle() { + Database db = db(); + Single a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().count(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnCompletable() { + Database db = db(); + Completable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().ignoreElements(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testUpdateWithinTransactionBatchSize0() { + db() // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(0) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + + private static void info() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + private static void debug() { + LogManager.getRootLogger().setLevel(Level.DEBUG); + } + + @Test + public void testCreateBig() { + info(); + big(5).select("select count(*) from person") // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(5163) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBig() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBigInputBatchSize2000() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(2000) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testInsertNullClobAndReadClobAsString() { + Database db = db(); + insertNullClob(db); + db.select("select document from person_clob where name='FRED'") // + .getAsOptional(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Optional.empty()) // + .assertComplete(); + } + + private static void insertNullClob(Database db) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", Database.NULL_CLOB) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testClobMethod() { + assertEquals(Database.NULL_CLOB, Database.clob(null)); + } + + @Test + public void testBlobMethod() { + assertEquals(Database.NULL_BLOB, Database.blob(null)); + } + + @Test + public void testClobMethodPresent() { + assertEquals("a", Database.clob("a")); + } + + @Test + public void testBlobMethodPresent() { + byte[] b = new byte[1]; + assertEquals(b, Database.blob(b)); + } + + @Test + public void testDateOfBirthNullableForReadMe() { + Database.test() // + .select("select date_of_birth from person where name='FRED'") // + .getAsOptional(Instant.class) // + .blockingForEach(System.out::println); + } + + @Test + public void testInsertNullClobAndReadClobAsTuple2() { + Database db = db(); + insertNullClob(db); + db.select("select document, document from person_clob where name='FRED'") // + .getAs(String.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Tuple2.create(null, null)) // + .assertComplete(); + } + + @Test + public void testInsertClobAndReadClobAsString() { + Database db = db(); + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue("some + // text + // here") + // // + .assertComplete(); + } + + @Test + public void testInsertClobAndReadClobUsingReader() { + Database db = db(); + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(Reader.class) // + .map(r -> read(r)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsByteArray() { + Database db = db(); + insertPersonBlob(db); + db.select("select document from person_blob where name='FRED'") // + .getAs(byte[].class) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + private static void insertPersonBlob(Database db) { + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", bytes) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsInputStream() { + Database db = db(); + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", new ByteArrayInputStream(bytes)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_blob where name='FRED'") // + .getAs(InputStream.class) // + .map(is -> read(is)) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + private static String read(Reader reader) throws IOException { + StringBuffer s = new StringBuffer(); + char[] ch = new char[128]; + int n = 0; + while ((n = reader.read(ch)) != -1) { + s.append(ch, 0, n); + } + reader.close(); + return s.toString(); + } + + private static byte[] read(InputStream is) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] b = new byte[128]; + int n = 0; + while ((n = is.read(b)) != -1) { + bytes.write(b, 0, n); + } + is.close(); + return bytes.toByteArray(); + } + + private void testHealthCheck(Predicate healthy) throws InterruptedException { + TestScheduler scheduler = new TestScheduler(); + + NonBlockingConnectionPool2 pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(10, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) // + .healthy(healthy) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) // + .scheduler(scheduler) // + .maxPoolSize(1) // + .build(); + + try (Database db = Database.from(pool)) { + TestSubscriber ts0 = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test(); + ts0.assertValueCount(0) // + .assertNotComplete(); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + ts0.assertValueCount(1) // + .assertComplete(); + TestSubscriber ts = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test() // + .assertValueCount(0); + System.out.println("done2"); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + Thread.sleep(200); + ts.assertValueCount(1); + Thread.sleep(200); + ts.assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testShutdownBeforeUse() { + NonBlockingConnectionPool2 pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .scheduler(Schedulers.io()) // + .maxPoolSize(1) // + .build(); + pool.close(); + Database.from(pool) // + .select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(PoolClosedException.class); + } + + @Test + public void testFewerColumnsMappedThanAvailable() { + db().select("select name, score from person where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues("FRED") // + .assertComplete(); + } + + @Test + public void testMoreColumnsMappedThanAvailable() { + db() // + .select("select name, score from person where name='FRED'") // + .getAs(String.class, Integer.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(MoreColumnsRequestedThanExistException.class); + } + + @Test + public void testSelectTimestamp() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsDate() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Date.class) // + .map(d -> d.getTime()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsInstant() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Instant.class) // + .map(d -> d.toEpochMilli()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateCalendarParameter() { + Calendar c = GregorianCalendar.from(ZonedDateTime.parse("2017-03-25T15:37Z")); + Database db = db(); + db.update("update person set registered=?") // + .parameter(c) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(c.getTimeInMillis()) // + .assertComplete(); + } + + @Test + public void testUpdateTimeParameter() { + Database db = db(); + Time t = new Time(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampParameter() { + Database db = db(); + Timestamp t = new Timestamp(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateSqlDateParameter() { + Database db = db(); + java.sql.Date t = new java.sql.Date(1234); + + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS * 10000, TimeUnit.SECONDS) // + // TODO make a more accurate comparison using the current TZ + .assertValue(x -> Math.abs(x - 1234) <= TimeUnit.HOURS.toMillis(24)) // + .assertComplete(); + } + + @Test + public void testUpdateUtilDateParameter() { + Database db = db(); + Date d = new Date(1234); + db.update("update person set registered=?") // + .parameter(d) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampAsInstant() { + Database db = db(); + db.update("update person set registered=? where name='FRED'") // + .parameter(Instant.ofEpochMilli(FRED_REGISTERED_TIME)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampAsZonedDateTime() { + Database db = db(); + db.update("update person set registered=? where name='FRED'") // + .parameter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(FRED_REGISTERED_TIME), + ZoneOffset.UTC.normalized())) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testComplete() throws InterruptedException { + Database db = db(1); + Completable a = db // + .update("update person set score=-3 where name='FRED'") // + .complete(); + db.update("update person set score=-4 where score = -3") // + .dependsOn(a) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testCountsOnlyInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .countsOnly() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3) // + .assertComplete(); + } + + @Test + public void testCountsInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .counts() // + .doOnNext(System.out::println) // + .toList() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3 + && list.get(1).isComplete() && list.size() == 2) // + .assertComplete(); + } + + @Test + public void testTx() throws InterruptedException { + Database db = db(3); + Single> transaction = db // + .update("update person set score=-3 where name='FRED'") // + .transaction(); + + transaction // + .doOnDispose(() -> System.out.println("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + System.out.println("flatmapping"); + return tx // + .update("update person set score = -4 where score = -3") // + .countsOnly() // + .doOnSubscribe(s -> System.out.println("subscribed")) // + .doOnNext(num -> System.out.println("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testTxAfterSelect() { + Database db = db(3); + Single> transaction = db // + .select("select score from person where name='FRED'") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .firstOrError(); + + transaction // + .doOnDispose(() -> System.out.println("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + System.out.println("flatmapping"); + return tx // + .update("update person set score = -4 where score = ?") // + .parameter(tx.value()) // + .countsOnly() // + .doOnSubscribe(s -> System.out.println("subscribed")) // + .doOnNext(num -> System.out.println("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testSingleFlatMap() { + Single.just(1).flatMapPublisher(n -> Flowable.just(1)).test(1).assertValue(1) + .assertComplete(); + } + + @Test + public void testAutomappedInstanceHasMeaningfulToStringMethod() { + info(); + String s = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.toString()) // + .blockingSingle(); + assertEquals("Person2[name=FRED, score=21]", s); + } + + @Test + public void testAutomappedEquals() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(x)) // + .blockingSingle(); + assertTrue(b); + } + + @Test + public void testAutomappedDoesNotEqualNull() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(null)) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedDoesNotEqual() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(new Object())) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedHashCode() { + Person2 p = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .blockingSingle(); + assertTrue(p.hashCode() != 0); + } + + @Test + public void testAutomappedWithParametersThatProvokesMoreThanOneQuery() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(2) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsAndHashCodeIsDistinctOnValues() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .distinct() // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsDifferentiatesDifferentInterfacesWithSameMethodNamesAndValues() { + PersonDistinct1 p1 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct1.class) // + .blockingFirst(); + + PersonDistinct2 p2 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct2.class) // + .blockingFirst(); + + assertNotEquals(p1, p2); + } + + @Test(expected = MethodCallNotSupportedException.class) + public void testAutomappedObjectsWhenDefaultMethodInvoked() { + PersonWithDefaultMethod p1 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethod.class) // + .blockingFirst(); + // TODO should not throw exception + p1.nameLower(); + } + + interface PersonWithDefaultMethod { + @Column + String name(); + + @Column + int score(); + + default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonDistinct1 { + @Column + String name(); + + @Column + int score(); + + } + + interface PersonDistinct2 { + @Column + String name(); + + @Column + int score(); + + } + + interface Score { + @Column + int score(); + } + + interface Person { + @Column + String name(); + } + + interface Person2 { + @Column + String name(); + + @Column + int score(); + } + + interface Person3 { + @Column("name") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person4 { + @Column("namez") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person5 { + @Index(1) + String fullName(); + + @Index(2) + int examScore(); + } + + interface Person6 { + @Index(1) + String fullName(); + + @Index(3) + int examScore(); + } + + interface Person7 { + @Index(1) + String fullName(); + + @Index(0) + int examScore(); + } + + interface Person8 { + @Column + int name(); + } + + interface Person9 { + @Column + String name(); + + @Index(2) + int score(); + } + + interface PersonNoAnnotation { + String name(); + } + + @Query("select name, score from person order by name") + interface Person10 { + + @Column + String name(); + + @Column + int score(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool2` acquired to `pool` by call to `build()` at line 1581 is not released after line 1583. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DatabaseTest.testHealthCheck(Predicate) + +### Procedure Id: +org.davidmoten.rx.jdbc.DatabaseTest.testHealthCheck(io.reactivex.functions.Predicate):void.6b7d441e1f8085c4886a880e979e4e3c + +### File: +src/test/java/org/davidmoten/rx/jdbc/DatabaseTest.java + +### Key: +DatabaseTest.java|testHealthCheck|RESOURCE_LEAK + +### Node Key: +e5960f4fbede3e43a358ccb7b3c94f25 + +### Hash: +6fe3ab7a8812cb59a1a333e68bdf3ae7 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10933/instruction.md b/inferredbugs-10933/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..84e40ca25277023c28a4889766fc3be040735463 --- /dev/null +++ b/inferredbugs-10933/instruction.md @@ -0,0 +1,256 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rxjava2-jdbc +**Bug ID:** 101 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.davidmoten.rx.jdbc.pool; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.commons.io.IOUtils; +import org.davidmoten.rx.jdbc.ConnectionProvider; +import org.davidmoten.rx.jdbc.Database; +import org.davidmoten.rx.jdbc.exceptions.SQLRuntimeException; + +import io.reactivex.Scheduler; +import io.reactivex.schedulers.Schedulers; + +public final class DatabaseCreator { + + private static final AtomicInteger dbNumber = new AtomicInteger(); + + public static Database createBlocking() { + return Database.fromBlocking(connectionProvider()); + } + + public static Database create(int maxSize) { + ExecutorService executor = Executors.newFixedThreadPool(maxSize); + Scheduler scheduler = new ExecutorScheduler(executor); + return create(maxSize, false, scheduler); + } + + public static Database create(int maxSize, Scheduler scheduler) { + return create(maxSize, false, scheduler); + } + + public static Database createDerby(int maxSize) { + return Database.from(Pools.nonBlocking() // + .connectionProvider(connectionProviderDerby(nextUrlDerby())) // + .maxPoolSize(maxSize) // + .scheduler(Schedulers.from(Executors.newFixedThreadPool(maxSize))) // + .build()); + } + + private static ConnectionProvider connectionProviderDerby(String url) { + Connection c; + try { + c = DriverManager.getConnection(url); + createDatabaseDerby(c); + } catch (SQLException e) { + throw new SQLRuntimeException(e); + } + return new ConnectionProvider() { + + @Override + public Connection get() { + try { + return DriverManager.getConnection(url); + } catch (SQLException e) { + throw new SQLRuntimeException(e); + } + } + + @Override + public void close() { + // + } + }; + } + + private static void createDatabaseDerby(Connection c) throws SQLException { + c.setAutoCommit(true); + exec(c, "create table note2(" + + "id integer not null generated always as identity (start with 1, increment by 2)," + + "text varchar(255) not null," // + + "constraint primary_key primary key (id)" + ")"); + } + + public static Database create(int maxSize, boolean big, Scheduler scheduler) { + return Database.from(Pools.nonBlocking() // + .connectionProvider(connectionProvider(nextUrl(), big)) // + .maxPoolSize(maxSize) // + .scheduler(scheduler) // + .build(), () -> scheduler.shutdown()); + } + + public static ConnectionProvider connectionProvider() { + return connectionProvider(nextUrl(), false); + } + + private static ConnectionProvider connectionProvider(String url, boolean big) { + return new ConnectionProvider() { + + private final AtomicBoolean once = new AtomicBoolean(false); + private final CountDownLatch latch = new CountDownLatch(1); + + @Override + public Connection get() { + try { + if (once.compareAndSet(false, true)) { + try { + Connection c = DriverManager.getConnection(url); + createDatabase(c, big); + return c; + } finally { + latch.countDown(); + } + } else { + if (latch.await(30, TimeUnit.SECONDS)) { + return DriverManager.getConnection(url); + } else { + throw new TimeoutException("big database timed out on creation"); + } + } + } catch (SQLException | InterruptedException | TimeoutException e) { + throw new SQLRuntimeException(e); + } + } + + @Override + public void close() { + // + } + }; + } + + public static String nextUrl() { + return "jdbc:h2:mem:test" + dbNumber.incrementAndGet() + ";DB_CLOSE_DELAY=-1"; + } + + private static String nextUrlDerby() { + return "jdbc:derby:memory:derbyUnitTest" + dbNumber.incrementAndGet() + ";create=true"; + } + + private static void createDatabase(Connection c, boolean big) { + try { + c.setAutoCommit(true); + c.prepareStatement( + "create table person (name varchar(50) primary key, score int not null, date_of_birth date, registered timestamp)") + .execute(); + if (big) { + List lines = IOUtils.readLines( + DatabaseCreator.class.getResourceAsStream("/big.txt"), + StandardCharsets.UTF_8); + lines.stream().map(line -> line.split("\t")).forEach(items -> { + try { + c.prepareStatement("insert into person(name,score) values('" + items[0] + + "'," + Integer.parseInt(items[1]) + ")").execute(); + } catch (SQLException e) { + throw new SQLRuntimeException(e); + } + }); + } else { + exec(c, "insert into person(name,score,registered) values('FRED',21, {ts '2015-09-17 18:47:52.69Z'})"); + exec(c, "insert into person(name,score) values('JOSEPH',34)"); + exec(c, "insert into person(name,score) values('MARMADUKE',25)"); + } + + exec(c, "create table person_clob (name varchar(50) not null, document clob)"); + exec(c, "create table person_blob (name varchar(50) not null, document blob)"); + + exec(c, "create table address (address_id int primary key, full_address varchar(255) not null)"); + exec(c, "insert into address(address_id, full_address) values(1,'57 Something St, El Barrio, Big Place')"); + exec(c, "create table note(id bigint auto_increment primary key, text varchar(255))"); + } catch (SQLException e) { + throw new SQLRuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static void exec(Connection c, String sql) throws SQLException { + c.prepareStatement(sql).execute(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool` acquired by call to `build()` at line 90 is not released after line 86. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Database DatabaseCreator.create(int,boolean,Scheduler) + +### Procedure Id: +org.davidmoten.rx.jdbc.pool.DatabaseCreator.create(int,boolean,io.reactivex.Scheduler):org.davidmote.2072be811d4df7f842dcb8fc96c3cf3f + +### File: +src/test/java/org/davidmoten/rx/jdbc/pool/DatabaseCreator.java + +### Key: +DatabaseCreator.java|create|RESOURCE_LEAK + +### Node Key: +3534744d3537de8ddf14c788351b1bdd + +### Hash: +688ae7ccbd1b72b53a751297e4ce7078 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-10934/instruction.md b/inferredbugs-10934/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1ad49acec864e773866f6fc815332ce84bc1b826 --- /dev/null +++ b/inferredbugs-10934/instruction.md @@ -0,0 +1,2410 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rxjava2-jdbc +**Bug ID:** 55 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.davidmoten.rx.jdbc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLSyntaxErrorException; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.log4j.Level; +import org.apache.log4j.LogManager; +import org.davidmoten.rx.jdbc.annotations.Column; +import org.davidmoten.rx.jdbc.annotations.Index; +import org.davidmoten.rx.jdbc.annotations.Query; +import org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.AutomappedInterfaceInaccessibleException; +import org.davidmoten.rx.jdbc.exceptions.ColumnIndexOutOfRangeException; +import org.davidmoten.rx.jdbc.exceptions.ColumnNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.MoreColumnsRequestedThanExistException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterFoundButSqlDoesNotHaveNamesException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterMissingException; +import org.davidmoten.rx.jdbc.exceptions.QueryAnnotationMissingException; +import org.davidmoten.rx.jdbc.pool.DatabaseCreator; +import org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool; +import org.davidmoten.rx.jdbc.pool.Pools; +import org.davidmoten.rx.jdbc.tuple.Tuple2; +import org.davidmoten.rx.jdbc.tuple.Tuple3; +import org.davidmoten.rx.jdbc.tuple.Tuple4; +import org.davidmoten.rx.jdbc.tuple.Tuple5; +import org.davidmoten.rx.jdbc.tuple.Tuple6; +import org.davidmoten.rx.jdbc.tuple.Tuple7; +import org.davidmoten.rx.jdbc.tuple.TupleN; +import org.davidmoten.rx.pool.PoolClosedException; +import org.h2.jdbc.JdbcSQLException; +import org.hsqldb.jdbc.JDBCBlobFile; +import org.hsqldb.jdbc.JDBCClobFile; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.davidmoten.guavamini.Lists; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Observable; +import io.reactivex.Scheduler; +import io.reactivex.Single; +import io.reactivex.functions.Predicate; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subscribers.TestSubscriber; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class DatabaseTest { + + private static final long FRED_REGISTERED_TIME = 1442515672690L; + private static final int NAMES_COUNT_BIG = 5163; + private static final Logger log = LoggerFactory.getLogger(DatabaseTest.class); + private static final int TIMEOUT_SECONDS = 2; + + private static Database db() { + return DatabaseCreator.create(1); + } + + private static Database blocking() { + return DatabaseCreator.createBlocking(); + } + + private static Database db(int poolSize) { + return DatabaseCreator.create(poolSize); + } + + private static Database big(int poolSize) { + return DatabaseCreator.create(poolSize, true, Schedulers.computation()); + } + + @Test + public void testSelectUsingQuestionMark() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNamedParameterList() { + try (Database db = db()) { + db.select("select score from person where name=:name") // + .parameters(Parameter.named("name", "FRED").value("JOSEPH").list()) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameters() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterStream(Flowable.just("FRED", "JOSEPH")) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersInLists() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED"), Arrays.asList("JOSEPH"))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testDrivingSelectWithoutParametersUsingParameterStream() { + try (Database db = db()) { + db.select("select count(*) from person") // + .parameters(1, 2, 3) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterStream(Flowable.just("FRED", 21, "JOSEPH", 34)) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameterListsTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED", 21), Arrays.asList("JOSEPH", 34))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkWithPublicTestingDatabase() { + try (Database db = Database.test()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSize() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(2) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSizeZero() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(0) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectWithFetchSizeNegative() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(-1); + } + } + + @Test + public void testSelectUsingNonBlockingBuilder() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(1, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES) // + .checkoutRetryInterval(1, TimeUnit.SECONDS) // + .healthy(c -> c.prepareStatement("select 1").execute()) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) // + .maxPoolSize(3) // + .build(); + + try (Database db = Database.from(pool)) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test(timeout = 40000) + public void testSelectUsingNonBlockingBuilderConcurrencyTest() + throws InterruptedException, TimeoutException { + info(); + try { + try (Database db = db(3)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(50)); + int n = 10000; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } else { + // log.debug(iCopy + " succeeded"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + } + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test(timeout = 5000) + public void testSelectConcurrencyTest() throws InterruptedException, TimeoutException { + debug(); + try { + try (Database db = db(1)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(2)); + int n = 2; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + log.info("submitted " + i); + } + if (!latch.await(5000, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test + public void testDatabaseClose() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingName() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNameNotGiven() { + try (Database db = db()) { + db // + .select("select score from person where name=:name and name<>:name2") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterMissingException.class) // + .assertNoValues(); + } + } + + @Test + public void testSelectUsingParameterNameNullNameWhenSqlHasNoNames() { + db() // + .select("select score from person where name=?") // + .parameter(Parameter.create("name", "FRED")) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterFoundButSqlDoesNotHaveNamesException.class) // + .assertNoValues(); + } + + @Test + public void testUpdateWithNull() { + try (Database db = db()) { + db // + .update("update person set date_of_birth = :dob") // + .parameter(Parameter.create("dob", null)) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithNull() { + try (Database db = db()) { + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", Database.NULL_CLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithClob() throws SQLException { + try (Database db = db()) { + Clob clob = new JDBCClobFile(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", clob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithReader() throws FileNotFoundException { + try (Database db = db()) { + Reader reader = new FileReader(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", reader) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithBlob() throws SQLException { + try (Database db = db()) { + Blob blob = new JDBCBlobFile(new File("src/test/resources/big.txt")); + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", blob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithNull() { + try (Database db = db()) { + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", Database.NULL_BLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test(expected = NullPointerException.class) + public void testSelectUsingNullNameInParameter() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter(null, "FRED"); // + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameDoesNotExist() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameters("nam", "FRED"); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameters("FRED", "JOSEPH"); + } + } + + @Test + public void testSelectTransacted() { + try (Database db = db()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .getAs(Integer.class) // + .doOnNext(tx -> log + .debug(tx.isComplete() ? "complete" : String.valueOf(tx.value()))) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedAnnotatedTransacted() { + try (Database db = db()) { + db // + .select(Person10.class) // + .transacted() // + .valuesOnly() // + .get().test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedTransactedValuesOnly() { + try (Database db = db()) { + db // + .select("select name, score from person") // + .transacted() // + .valuesOnly() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedTransacted() { + try (Database db = db()) { + db // + .select("select name, score from person") // + .transacted() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + } + + @Test + public void testSelectTransactedTuple2() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + } + } + + @Test + public void testSelectTransactedTuple3() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + } + } + + @Test + public void testSelectTransactedTuple4() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + } + } + + @Test + public void testSelectTransactedTuple5() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + } + } + + @Test + public void testSelectTransactedTuple6() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + } + } + + @Test + public void testSelectTransactedTuple7() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + assertEquals("FRED", t.value()._7()); + } + } + + @Test + public void testSelectTransactedTupleN() { + List>> list = db() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getTupleN() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertEquals("FRED", list.get(0).value().values().get(0)); + assertEquals(21, (int) list.get(0).value().values().get(1)); + assertTrue(list.get(1).isComplete()); + assertEquals(2, list.size()); + } + + @Test + public void testSelectTransactedCount() { + db() // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAs() { + db() // + .select("select name from person") // + .transacted() // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAsOptional() { + List>> list = db() // + .select("select name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAsOptional(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertTrue(list.get(0).isValue()); + assertEquals("FRED", list.get(0).value().get()); + assertTrue(list.get(1).isComplete()); + } + + @Test + public void testDatabaseFrom() { + Database.from(DatabaseCreator.nextUrl(), 3) // + .select("select name from person") // + .getAs(String.class) // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(JdbcSQLException.class); + } + + @Test + public void testSelectTransactedChained() throws Exception { + Database db = db(); + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .transactedValuesOnly() // + .getAs(Integer.class) // + .doOnNext( + tx -> log.debug(tx.isComplete() ? "complete" : String.valueOf(tx.value())))// + .flatMap(tx -> tx // + .select("select name from person where score = ?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + @Test + public void databaseIsAutoCloseable() { + try (Database db = db()) { + log.debug(db.toString()); + } + } + + @Test + public void testSelectChained() { + try (Database db = db(1)) { + // we can do this with 1 connection only! + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .doOnNext(System.out::println) // + .concatMap(score -> { + log.info("score={}", score); + return db // + .select("select name from person where score = ?") // + .parameter(score) // + .getAs(String.class) // + .doOnComplete( + () -> log.info("completed select where score=" + score)); + }) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); // + } + } + + @Test + @SuppressFBWarnings + public void testReadMeFragment1() { + try (Database db = db()) { + db.select("select name from person") // + .getAs(String.class) // + .forEach(System.out::println); + } + } + + @Test + public void testReadMeFragmentColumnDoesNotExistEmitsSqlSyntaxErrorException() { + try (Database db = Database.test()) { + db.select("select nam from person") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(SQLSyntaxErrorException.class); + } + } + + @Test + public void testReadMeFragmentDerbyHealthCheck() { + try (Database db = Database.test()) { + db.select("select 'a' from sysibm.sysdummy1") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("a") // + .assertComplete(); + } + } + + @Test + @SuppressFBWarnings + public void testTupleSupport() { + try (Database db = db()) { + db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .forEach(System.out::println); + } + } + + @Test + public void testDelayedCallsAreNonBlocking() throws InterruptedException { + List list = new CopyOnWriteArrayList(); + try (Database db = db(1)) { // + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> Thread.sleep(1000)) // + .subscribeOn(Schedulers.io()) // + .subscribe(); + Thread.sleep(100); + CountDownLatch latch = new CountDownLatch(1); + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> list.add("emitted")) // + .doOnNext(x -> log.debug("emitted on " + Thread.currentThread().getName())) // + .doOnNext(x -> latch.countDown()) // + .subscribe(); + list.add("subscribed"); + assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + assertEquals(Arrays.asList("subscribed", "emitted"), list); + } + } + + @Test + public void testAutoMapToInterface() { + try (Database db = db()) { + db // + .select("select name from person") // + .autoMap(Person.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithoutAnnotationstsError() { + try (Database db = db()) { + db // + .select("select name from person") // + .autoMap(PersonNoAnnotation.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(AnnotationsNotFoundException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithTwoMethods() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person2.class) // + .firstOrError() // + .map(Person2::score) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnName() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person3.class) // + .firstOrError() // + .map(Person3::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person4.class) // + .firstOrError() // + .map(Person4::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnNotFoundException.class); + } + + @Test + public void testAutoMapToInterfaceWithIndex() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person5.class) // + .firstOrError() // + .map(Person5::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapToInterfaceWithIndexTooLarge() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person6.class) // + .firstOrError() // + .map(Person6::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + + @Test + public void testAutoMapToInterfaceWithIndexTooSmall() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person7.class) // + .firstOrError() // + .map(Person7::examScore) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + + @Test + public void testAutoMapWithUnmappableColumnType() { + db() // + .select("select name from person order by name") // + .autoMap(Person8.class) // + .map(p -> p.name()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ClassCastException.class); + } + + @Test + public void testAutoMapWithMixIndexAndName() { + db() // + .select("select name, score from person order by name") // + .autoMap(Person9.class) // + .firstOrError() // + .map(Person9::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + public void testAutoMapWithQueryInAnnotation() { + db().select(Person10.class) // + .get() // + .firstOrError() // + .map(Person10::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + + @Test + @Ignore + public void testAutoMapForReadMe() { + Database // + .test() // + .select(Person10.class) // + .get(Person10::name) // + .blockingForEach(System.out::println); + } + + @Test(expected = QueryAnnotationMissingException.class) + public void testAutoMapWithoutQueryInAnnotation() { + db().select(Person.class); + } + + @Test + public void testSelectWithoutWhereClause() { + Assert.assertEquals(3, (long) db().select("select name from person") // + .count() // + .blockingGet()); + } + + @Test + public void testTuple3() { + db() // + .select("select name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple3.create("FRED", 21, "FRED")); // + } + + @Test + public void testTuple4() { + db() // + .select("select name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple4.create("FRED", 21, "FRED", 21)); // + } + + @Test + public void testTuple5() { + db() // + .select("select name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple5.create("FRED", 21, "FRED", 21, "FRED")); // + } + + @Test + public void testTuple6() { + db() // + .select("select name, score, name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21)); // + } + + @Test + public void testTuple7() { + db() // + .select("select name, score, name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() + .assertValue(Tuple7.create("FRED", 21, "FRED", 21, "FRED", 21, "FRED")); // + } + + @Test + public void testTupleN() { + db() // + .select("select name, score, name from person order by name") // + .getTupleN() // + .firstOrError().test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(TupleN.create("FRED", 21, "FRED")); // + } + + @Test + public void testHealthCheck() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + return !once.compareAndSet(true, false); + }); + } + + @Test + public void testHealthCheckThatThrows() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + if (!once.compareAndSet(true, false)) + return true; + else + throw new RuntimeException("health check failed"); + }); + } + + @Test + public void testUpdateOneRow() { + db().update("update person set score=20 where name='FRED'") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateThreeRows() { + db().update("update person set score=20") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + + @Test + public void testUpdateWithParameter() { + db().update("update person set score=20 where name=?") // + .parameter("FRED").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testUpdateWithParameterTwoRuns() { + db().update("update person set score=20 where name=?") // + .parameters("FRED", "JOSEPH").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + } + + @Test + public void testUpdateAllWithParameterFourRuns() { + db().update("update person set score=?") // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testUpdateWithBatchSize2() { + db().update("update person set score=?") // + .batchSize(2) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testUpdateWithBatchSize3GreaterThanNumRecords() { + db().update("update person set score=?") // + .batchSize(3) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + + @Test + public void testInsert() { + Database db = db(); + db.update("insert into person(name, score) values(?,?)") // + .parameters("DAVE", 12, "ANNE", 18) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + List> list = db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .toList() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingGet(); + assertTrue(list.contains(Tuple2.create("DAVE", 12))); + assertTrue(list.contains(Tuple2.create("ANNE", 18))); + } + + @Test + public void testReturnGeneratedKeys() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + + @Test + public void testReturnGeneratedKeysDerby() { + Database db = DatabaseCreator.createDerby(1); + + // note is a table with auto increment + db.update("insert into note2(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors().assertValues(1, 3) // + .assertComplete(); + + db.update("insert into note2(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(5, 7) // + .assertComplete(); + } + + @Test(expected = IllegalArgumentException.class) + public void testReturnGeneratedKeysWithBatchSizeShouldThrow() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .batchSize(2) // + .returnGeneratedKeys(); + } + + @Test + public void testTransactedReturnGeneratedKeys() { + Database db = db(); + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + + @Test + public void testTransactedReturnGeneratedKeys2() { + Database db = db(); + // note is a table with auto increment + Flowable a = db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .startWith(a) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2, 3, 4) // + .assertComplete(); + } + + @Test + public void testUpdateWithinTransaction() { + db() // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnFlowable() { + Database db = db(); + Flowable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnObservable() { + Database db = db(); + Observable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().toObservable(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnOnSingle() { + Database db = db(); + Single a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().count(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testSelectDependsOnCompletable() { + Database db = db(); + Completable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().ignoreElements(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + + @Test + public void testUpdateWithinTransactionBatchSize0() { + db() // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(0) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + + private static void info() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + private static void debug() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + @Test + public void testCreateBig() { + info(); + big(5).select("select count(*) from person") // + .getAs(Integer.class) // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue(5163) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBig() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBigInputBatchSize2000() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(2000) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testInsertNullClobAndReadClobAsString() { + Database db = db(); + insertNullClob(db); + db.select("select document from person_clob where name='FRED'") // + .getAsOptional(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Optional.empty()) // + .assertComplete(); + } + + private static void insertNullClob(Database db) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", Database.NULL_CLOB) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testClobMethod() { + assertEquals(Database.NULL_CLOB, Database.clob(null)); + } + + @Test + public void testBlobMethod() { + assertEquals(Database.NULL_BLOB, Database.blob(null)); + } + + @Test + public void testClobMethodPresent() { + assertEquals("a", Database.clob("a")); + } + + @Test + public void testBlobMethodPresent() { + byte[] b = new byte[1]; + assertEquals(b, Database.blob(b)); + } + + @Test + public void testDateOfBirthNullableForReadMe() { + Database.test() // + .select("select date_of_birth from person where name='FRED'") // + .getAsOptional(Instant.class) // + .blockingForEach(System.out::println); + } + + @Test + public void testInsertNullClobAndReadClobAsTuple2() { + Database db = db(); + insertNullClob(db); + db.select("select document, document from person_clob where name='FRED'") // + .getAs(String.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Tuple2.create(null, null)) // + .assertComplete(); + } + + @Test + public void testInsertClobAndReadClobAsString() { + Database db = db(); + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue("some + // text + // here") + // // + .assertComplete(); + } + + @Test + public void testInsertClobAndReadClobUsingReader() { + Database db = db(); + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(Reader.class) // + .map(r -> read(r)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsByteArray() { + Database db = db(); + insertPersonBlob(db); + db.select("select document from person_blob where name='FRED'") // + .getAs(byte[].class) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + private static void insertPersonBlob(Database db) { + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", bytes) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsInputStream() { + Database db = db(); + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", new ByteArrayInputStream(bytes)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_blob where name='FRED'") // + .getAs(InputStream.class) // + .map(is -> read(is)) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + + private static String read(Reader reader) throws IOException { + StringBuffer s = new StringBuffer(); + char[] ch = new char[128]; + int n = 0; + while ((n = reader.read(ch)) != -1) { + s.append(ch, 0, n); + } + reader.close(); + return s.toString(); + } + + private static byte[] read(InputStream is) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] b = new byte[128]; + int n = 0; + while ((n = is.read(b)) != -1) { + bytes.write(b, 0, n); + } + is.close(); + return bytes.toByteArray(); + } + + private void testHealthCheck(Predicate healthy) throws InterruptedException { + TestScheduler scheduler = new TestScheduler(); + + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(10, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) // + .healthy(healthy) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) // + .scheduler(scheduler) // + .maxPoolSize(1) // + .build(); + + try (Database db = Database.from(pool)) { + TestSubscriber ts0 = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test(); + ts0.assertValueCount(0) // + .assertNotComplete(); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + ts0.assertValueCount(1) // + .assertComplete(); + TestSubscriber ts = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test() // + .assertValueCount(0); + log.debug("done2"); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + Thread.sleep(200); + ts.assertValueCount(1); + Thread.sleep(200); + ts.assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testShutdownBeforeUse() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .scheduler(Schedulers.io()) // + .maxPoolSize(1) // + .build(); + pool.close(); + Database.from(pool) // + .select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(PoolClosedException.class); + } + + @Test + public void testFewerColumnsMappedThanAvailable() { + db().select("select name, score from person where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues("FRED") // + .assertComplete(); + } + + @Test + public void testMoreColumnsMappedThanAvailable() { + db() // + .select("select name, score from person where name='FRED'") // + .getAs(String.class, Integer.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(MoreColumnsRequestedThanExistException.class); + } + + @Test + public void testSelectTimestamp() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsDate() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Date.class) // + .map(d -> d.getTime()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsInstant() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Instant.class) // + .map(d -> d.toEpochMilli()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateCalendarParameter() { + Calendar c = GregorianCalendar.from(ZonedDateTime.parse("2017-03-25T15:37Z")); + Database db = db(); + db.update("update person set registered=?") // + .parameter(c) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(c.getTimeInMillis()) // + .assertComplete(); + } + + @Test + public void testUpdateTimeParameter() { + Database db = db(); + Time t = new Time(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampParameter() { + Database db = db(); + Timestamp t = new Timestamp(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateSqlDateParameter() { + Database db = db(); + java.sql.Date t = new java.sql.Date(1234); + + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS * 10000, TimeUnit.SECONDS) // + // TODO make a more accurate comparison using the current TZ + .assertValue(x -> Math.abs(x - 1234) <= TimeUnit.HOURS.toMillis(24)) // + .assertComplete(); + } + + @Test + public void testUpdateUtilDateParameter() { + Database db = db(); + Date d = new Date(1234); + db.update("update person set registered=?") // + .parameter(d) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampAsInstant() { + Database db = db(); + db.update("update person set registered=? where name='FRED'") // + .parameter(Instant.ofEpochMilli(FRED_REGISTERED_TIME)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateTimestampAsZonedDateTime() { + Database db = db(); + db.update("update person set registered=? where name='FRED'") // + .parameter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(FRED_REGISTERED_TIME), + ZoneOffset.UTC.normalized())) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testCompleteCompletes() { + Database db = db(1); + db // + .update("update person set score=-3 where name='FRED'") // + .complete() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingAwait(); + + int score = db.select("select score from person where name='FRED'") // + .getAs(Integer.class) // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingFirst(); + assertEquals(-3, score); + } + + @Test + public void testComplete() throws InterruptedException { + Database db = db(1); + Completable a = db // + .update("update person set score=-3 where name='FRED'") // + .complete(); + db.update("update person set score=-4 where score = -3") // + .dependsOn(a) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testCountsOnlyInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .countsOnly() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3) // + .assertComplete(); + } + + @Test + public void testCountsInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .counts() // + .doOnNext(System.out::println) // + .toList() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3 + && list.get(1).isComplete() && list.size() == 2) // + .assertComplete(); + } + + @Test + public void testTx() throws InterruptedException { + Database db = db(3); + Single> transaction = db // + .update("update person set score=-3 where name='FRED'") // + .transaction(); + + transaction // + .doOnDispose(() -> log.debug("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + log.debug("flatmapping"); + return tx // + .update("update person set score = -4 where score = -3") // + .countsOnly() // + .doOnSubscribe(s -> log.debug("subscribed")) // + .doOnNext(num -> log.debug("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testTxAfterSelect() { + Database db = db(3); + Single> transaction = db // + .select("select score from person where name='FRED'") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .firstOrError(); + + transaction // + .doOnDispose(() -> log.debug("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + log.debug("flatmapping"); + return tx // + .update("update person set score = -4 where score = ?") // + .parameter(tx.value()) // + .countsOnly() // + .doOnSubscribe(s -> log.debug("subscribed")) // + .doOnNext(num -> log.debug("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testSingleFlatMap() { + Single.just(1).flatMapPublisher(n -> Flowable.just(1)).test(1).assertValue(1) + .assertComplete(); + } + + @Test + public void testAutomappedInstanceHasMeaningfulToStringMethod() { + info(); + String s = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.toString()) // + .blockingSingle(); + assertEquals("Person2[name=FRED, score=21]", s); + } + + @Test + public void testAutomappedEquals() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(x)) // + .blockingSingle(); + assertTrue(b); + } + + @Test + public void testAutomappedDoesNotEqualNull() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(null)) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedDoesNotEqual() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(new Object())) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedHashCode() { + Person2 p = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .blockingSingle(); + assertTrue(p.hashCode() != 0); + } + + @Test + public void testAutomappedWithParametersThatProvokesMoreThanOneQuery() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(2) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsAndHashCodeIsDistinctOnValues() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .distinct() // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsDifferentiatesDifferentInterfacesWithSameMethodNamesAndValues() { + PersonDistinct1 p1 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct1.class) // + .blockingFirst(); + + PersonDistinct2 p2 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct2.class) // + .blockingFirst(); + + assertNotEquals(p1, p2); + } + + @Test + public void testAutomappedObjectsWhenDefaultMethodInvoked() { + PersonWithDefaultMethod p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethod.class) // + .blockingFirst(); + assertEquals("fred", p.nameLower()); + } + + // @Test + // public void testDefaultMethod() throws NoSuchMethodException, + // IllegalAccessException { + // MethodHandles.lookup().findSpecial(PersonWithDefaultMethod.class, + // "nameLower", + // MethodType.methodType(String.class, new Class[] {}), + // PersonWithDefaultMethod.class) + //// .bindTo(x); + // } + + @Test(expected = AutomappedInterfaceInaccessibleException.class) + public void testAutomappedObjectsWhenDefaultMethodInvokedAndIsNonPublicThrows() { + PersonWithDefaultMethodNonPublic p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethodNonPublic.class) // + .blockingFirst(); + p.nameLower(); + } + + @Test + public void testBlockingDatabase() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransacted() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .map(x -> x.value()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransactedNested() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .flatMap(tx -> tx.select("select name from person where score=?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + public interface PersonWithDefaultMethod { + @Column + String name(); + + @Column + int score(); + + public default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonWithDefaultMethodNonPublic { + @Column + String name(); + + @Column + int score(); + + default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonDistinct1 { + @Column + String name(); + + @Column + int score(); + + } + + interface PersonDistinct2 { + @Column + String name(); + + @Column + int score(); + + } + + interface Score { + @Column + int score(); + } + + interface Person { + @Column + String name(); + } + + interface Person2 { + @Column + String name(); + + @Column + int score(); + } + + interface Person3 { + @Column("name") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person4 { + @Column("namez") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person5 { + @Index(1) + String fullName(); + + @Index(2) + int examScore(); + } + + interface Person6 { + @Index(1) + String fullName(); + + @Index(3) + int examScore(); + } + + interface Person7 { + @Index(1) + String fullName(); + + @Index(0) + int examScore(); + } + + interface Person8 { + @Column + int name(); + } + + interface Person9 { + @Column + String name(); + + @Index(2) + int score(); + } + + interface PersonNoAnnotation { + String name(); + } + + @Query("select name, score from person order by name") + interface Person10 { + + @Column + String name(); + + @Column + int score(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.davidmoten.rx.jdbc.Database` acquired by call to `db()` at line 1087 is not released after line 1089. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DatabaseTest.testTuple3() + +### Procedure Id: +org.davidmoten.rx.jdbc.DatabaseTest.testTuple3():void.308788afa474cba26719aef2d47e34a3 + +### File: +src/test/java/org/davidmoten/rx/jdbc/DatabaseTest.java + +### Key: +DatabaseTest.java|testTuple3|RESOURCE_LEAK + +### Node Key: +42f56fda1ad408e362508b93a175bb0c + +### Hash: +5ee3c24b93ee316346d1d4677e3f1172 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11011/instruction.md b/inferredbugs-11011/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef5c525c07351a4ae4457187933b8eb88a9ac2df --- /dev/null +++ b/inferredbugs-11011/instruction.md @@ -0,0 +1,260 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** knife +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package burp; + +import java.net.URL; +import java.util.*; +import java.util.Map.Entry; + +public class Getter { + private static IExtensionHelpers helpers; + public Getter(IExtensionHelpers helpers) { + this.helpers = helpers; + } + + /* + * 获取header的字符串数组,是构造burp中请求需要的格式。 + */ + public List getHeaderList(boolean messageIsRequest,IHttpRequestResponse messageInfo) { + if(messageIsRequest) { + IRequestInfo analyzeRequest = helpers.analyzeRequest(messageInfo); + List headers = analyzeRequest.getHeaders(); + return headers; + }else { + IResponseInfo analyzeResponse = helpers.analyzeResponse(messageInfo.getResponse()); + List headers = analyzeResponse.getHeaders(); + return headers; + } + } + + /* + * 获取所有headers,当做一个string看待。 + * 主要用于判断是否包含某个特殊字符串 + * List getHeaders 调用toString()方法,得到如下格式:[111111, 2222] + * 就能满足上面的场景了 + */ + public String getHeaderString(boolean messageIsRequest,IHttpRequestResponse messageInfo) { + List headers =null; + StringBuilder headerString = new StringBuilder(); + if(messageIsRequest) { + IRequestInfo analyzeRequest = helpers.analyzeRequest(messageInfo); + headers = analyzeRequest.getHeaders(); + }else { + IResponseInfo analyzeResponse = helpers.analyzeResponse(messageInfo.getResponse()); + headers = analyzeResponse.getHeaders(); + } + + for (String header : headers) { + headerString.append(header); + } + + return headerString.toString(); + } + + /* + * 获取header的map格式,key:value形式 + * 这种方式可以用put函数轻松实现:如果有则update,如果无则add。 + * !!!注意:这个方法获取到的map,会少了协议头GET /cps.gec/limit/information.html HTTP/1.1 + */ + public LinkedHashMap getHeaderHashMap(boolean messageIsRequest,IHttpRequestResponse messageInfo) { + List headers=null; + LinkedHashMap result = new LinkedHashMap(); + if(messageIsRequest) { + IRequestInfo analyzeRequest = helpers.analyzeRequest(messageInfo); + headers = analyzeRequest.getHeaders(); + }else { + IResponseInfo analyzeResponse = helpers.analyzeResponse(messageInfo.getResponse()); + headers = analyzeResponse.getHeaders(); + } + + for (String header : headers) { + if(header.contains(": ")) {//to void trigger the Exception + try { + String headerName = header.split(": ", 0)[0]; + String headerValue = header.split(": ", 0)[1]; + //POST /login.pub HTTP/1.1 the first line of header will tirgger error here + result.put(headerName, headerValue); + } catch (Exception e) { + //e.printStackTrace(); + } + } + } + return result; + } + + public List MapToList(LinkedHashMap Headers){ + List result = new ArrayList(); + for (Entry header:Headers.entrySet()) { + String item = header.getKey()+": "+header.getValue(); + result.add(item); + } + return result; + } + + /* + * 获取某个header的值,如果没有此header,返回null。 + */ + public String getHeaderValueOf(boolean messageIsRequest,IHttpRequestResponse messageInfo, String headerName) { + List headers=null; + if(messageIsRequest) { + IRequestInfo analyzeRequest = helpers.analyzeRequest(messageInfo); + headers = analyzeRequest.getHeaders(); + }else { + IResponseInfo analyzeResponse = helpers.analyzeResponse(messageInfo.getResponse()); + headers = analyzeResponse.getHeaders(); + } + + + headerName = headerName.toLowerCase().replace(": ", ""); + for (String header : headers) { + if (header.toLowerCase().startsWith(headerName)) { + return header.split(": ", 0)[1]; + } + } + return null; + } + + + public byte[] getBody(boolean messageIsRequest,IHttpRequestResponse messageInfo) { + if (messageInfo == null){ + return null; + } + if(messageIsRequest) { + if (messageInfo.getRequest() ==null) { + return null; + } + IRequestInfo analyzeRequest = helpers.analyzeRequest(messageInfo); + int bodyOffset = analyzeRequest.getBodyOffset(); + byte[] byte_Request = messageInfo.getRequest(); + + byte[] byte_body = Arrays.copyOfRange(byte_Request, bodyOffset, byte_Request.length);//not length-1 + //String body = new String(byte_body); //byte[] to String + return byte_body; + }else { + if (messageInfo.getResponse() ==null) { + return null; + } + IResponseInfo analyzeResponse = helpers.analyzeResponse(messageInfo.getResponse()); + int bodyOffset = analyzeResponse.getBodyOffset(); + byte[] byte_Request = messageInfo.getResponse(); + + byte[] byte_body = Arrays.copyOfRange(byte_Request, bodyOffset, byte_Request.length);//not length-1 + return byte_body; + } + } + + public String getShortUrl(IHttpRequestResponse messageInfo) { + return messageInfo.getHttpService().toString(); + } + + public URL getURL(IHttpRequestResponse messageInfo){ + IRequestInfo analyzeRequest = helpers.analyzeRequest(messageInfo); + return analyzeRequest.getUrl(); + + //callbacks.getHelpers().analyzeRequest(baseRequestResponse).getUrl(); + } + + public String getHost(IHttpRequestResponse messageInfo) { + return messageInfo.getHttpService().getHost(); + } + + public short getStatusCode(IHttpRequestResponse messageInfo) { + IResponseInfo analyzedResponse = helpers.analyzeResponse(messageInfo.getResponse()); + return analyzedResponse.getStatusCode(); + } + public List getParas(IHttpRequestResponse messageInfo){ + IRequestInfo analyzeRequest = helpers.analyzeRequest(messageInfo); + return analyzeRequest.getParameters(); + } + + + public String getHTTPBasicCredentials(IHttpRequestResponse messageInfo) throws Exception{ + String authHeader = getHeaderValueOf(true, messageInfo, "Authorization").trim(); + String[] parts = authHeader.split("\\s"); + + if (parts.length != 2) + throw new Exception("Wrong number of HTTP Authorization header parts"); + + if (!parts[0].equalsIgnoreCase("Basic")) + throw new Exception("HTTP authentication must be Basic"); + + return parts[1]; + } + + public static void main(String args[]) { + String a= "xxxxx%s%bxxxxxxx"; + System.out.println(String.format(a, "111")); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getHeaderValueOf(1,messageInfo,"Authorization")` could be null and is dereferenced at line 170. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String Getter.getHTTPBasicCredentials(IHttpRequestResponse) + +### Procedure Id: +burp.Getter.getHTTPBasicCredentials(burp.IHttpRequestResponse):java.lang.String.d496b93c723c38ecf091095d2c764ef7 + +### File: +src/burp/Getter.java + +### Key: +Getter.java|getHTTPBasicCredentials|NULL_DEREFERENCE + +### Node Key: +07c4ca0274b2c82c8349f056d2a4ea49 + +### Hash: +f7c11b597aaacd1083256f4abc74a672 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11016/instruction.md b/inferredbugs-11016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eb3189d047e59df9949a59e787663bc37d1fbfc6 --- /dev/null +++ b/inferredbugs-11016/instruction.md @@ -0,0 +1,368 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** knife +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package burp; + +import java.awt.Component; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Proxy; +import java.net.URL; +import java.util.*; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import com.alibaba.fastjson.JSON; + +import U2C.U2CTab; +import config.Config; +import config.ConfigEntry; +import config.ConfigTable; +import config.ConfigTableModel; +import config.GUI; +import knife.AddHostToScopeMenu; +import knife.ChunkedEncodingMenu; +import knife.OpenWithBrowserMenu; +import knife.UpdateCookieMenu; +import knife.UpdateHeaderMenu; +import knife.UseCookieOfMenu; + +public class BurpExtender extends GUI implements IBurpExtender, IContextMenuFactory, IMessageEditorTabFactory, ITab, IHttpListener,IProxyListener { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public static IBurpExtenderCallbacks callbacks; + public IExtensionHelpers helpers; + public PrintWriter stdout; + public PrintWriter stderr; + public IContextMenuInvocation context; + public int proxyServerIndex=-1; + + + @Override + public void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks) { + BurpExtender.callbacks = callbacks; + this.helpers = callbacks.getHelpers(); + this.stdout = new PrintWriter(callbacks.getStdout(), true); + this.stderr = new PrintWriter(callbacks.getStderr(), true); + this.callbacks.setExtensionName(this.ExtensionName); + this.callbacks.registerContextMenuFactory(this);// for menus + this.callbacks.registerMessageEditorTabFactory(this);// for U2C + this.callbacks.addSuiteTab(BurpExtender.this); + this.callbacks.registerHttpListener(this); + + this.stdout.println(ExtensionName); + this.stdout.println(github); + + table = new ConfigTable(new ConfigTableModel()); + configPanel.setViewportView(table); + + String content = callbacks.loadExtensionSetting("knifeconfig"); + if (content!=null) { + config = JSON.parseObject(content, Config.class); + showToUI(config); + }else { + showToUI(JSON.parseObject(initConfig(), Config.class)); + } + table.setupTypeColumn();//call this function must after table data loaded !!!! + } + + + @Override + public List createMenuItems(IContextMenuInvocation invocation) { + this.context = invocation; + + ArrayList menu_list = new ArrayList(); + + + byte context = invocation.getInvocationContext(); + //只有当选中的内容是响应包的时候才显示U2C + + if (context == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST) { + menu_list.add(new UpdateCookieMenu(this)); + //menu_list.add(new UpdateCookieWithMenu(this)); + + } + + menu_list.add(new UseCookieOfMenu(this)); + + if (context == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST ) { + UpdateHeaderMenu uhmenu = new UpdateHeaderMenu(this); + List pHeaders = uhmenu.possibleHeaderNames(invocation); + /*menu_list.add(uhmenu);*/ + if(!pHeaders.isEmpty()) { + menu_list.add(uhmenu); + } + } + + menu_list.add(new AddHostToScopeMenu(this)); + menu_list.add(new OpenWithBrowserMenu(this)); + menu_list.add(new ChunkedEncodingMenu(this)); + + + JMenu Hack_Bar_Menu = new JMenu("^_^ Hack Bar++"); + Hack_Bar_Menu.add(new SQL_Menu(this)); + Hack_Bar_Menu.add(new SQL_Error(this)); + Hack_Bar_Menu.add(new SQli_LoginBypass(this)); + + Hack_Bar_Menu.add(new XSS_Menu(this)); + Hack_Bar_Menu.add(new XXE_Menu(this)); + Hack_Bar_Menu.add(new LFI_Menu(this));//learn from this + Hack_Bar_Menu.add(new SSTI_Menu(this)); + + Hack_Bar_Menu.add(new WebShell_Menu(this)); + Hack_Bar_Menu.add(new Reverse_Shell_Menu(this)); + + Hack_Bar_Menu.add(new File_Payload_Menu(this)); + Hack_Bar_Menu.add(new Custom_Payload_Menu(this)); + + menu_list.add(Hack_Bar_Menu); + return menu_list; + } + + //U2C + @Override + public IMessageEditorTab createNewInstance(IMessageEditorController controller, boolean editable) { + return new U2CTab(controller, false, helpers, callbacks); + } + + + @Override + public String getTabCaption() { + return ("Knife"); + } + + + @Override + public Component getUiComponent() { + return this.getContentPane(); + } + + public void saveConfigToExtension() { + callbacks.saveExtensionSetting("knifeconfig", getAllConfig()); + } + + @Override + public String initConfig() { + config = new Config("default"); + tableModel = new ConfigTableModel(); + return getAllConfig(); + } + + @Override + public void processProxyMessage(boolean messageIsRequest, IInterceptedProxyMessage message) { + //processHttpMessage(IBurpExtenderCallbacks.TOOL_PROXY,true,message.getMessageInfo()); + } + + @Override + public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo) { + synchronized (messageInfo) { + if (messageIsRequest) { + + boolean isRequestChanged = false; + MessageEditor editer = new MessageEditor(messageIsRequest, messageInfo, helpers); + + URL url = editer.getURL(); + String path = url.getPath(); + String host = editer.getHost(); + byte[] body = editer.getBody(); + LinkedHashMap headers = editer.getHeaderMap();//this will lost the first line + + + //remove header + List configEntries = tableModel.getConfigByType(ConfigEntry.Action_Remove_From_Headers); + for (ConfigEntry entry : configEntries) { + String key = entry.getKey(); + if (headers.remove(key) != null) { + isRequestChanged = true; + } + } + + if (config.getTmpMap().containsKey(host)) {//自动更新cookie + String cookieValue = config.getTmpMap().get(host); + String[] values = cookieValue.split("::::"); + String trueCookie = values[1]; + headers.put("Cookie", trueCookie); + isRequestChanged = true; + } + + //add/update/append header + if (toolFlag == (toolFlag & checkEnabledFor())) { + //if ((config.isOnlyForScope() && callbacks.isInScope(url))|| !config.isOnlyForScope()) { + if (!config.isOnlyForScope()||callbacks.isInScope(url)){ + try { + List updateOrAddEntries = tableModel.getConfigEntries(); + for (ConfigEntry entry : updateOrAddEntries) { + String key = entry.getKey(); + String value = entry.getValue(); + + if (value.contains("%host")) { + value = value.replaceAll("%host", host); + //stdout.println("3333"+value); + } + + if (value.toLowerCase().contains("%dnslogserver")) { + String dnslog = tableModel.getConfigByKey("DNSlogServer"); + Pattern p = Pattern.compile("(?u)%dnslogserver"); + Matcher m = p.matcher(value); + + while (m.find()) { + String found = m.group(0); + value = value.replaceAll(found, dnslog); + } + } + + if (entry.getType().equals(ConfigEntry.Action_Add_Or_Replace_Header) && entry.isEnable()) { + headers.put(key, value); + isRequestChanged = true; + + } else if (entry.getType().equals(ConfigEntry.Action_Append_To_header_value) && entry.isEnable()) { + value = headers.get(key) + value; + headers.put(key, value); + isRequestChanged = true; + //stdout.println("2222"+value); + } else if (entry.getKey().equalsIgnoreCase("Chunked-AutoEnable") && entry.isEnable()) { + headers.put("Transfer-Encoding", "chunked"); + isRequestChanged = true; + + try { + boolean useComment = false; + if (this.tableModel.getConfigByKey("Chunked-UseComment") != null) { + useComment = true; + } + String lenStr = this.tableModel.getConfigByKey("Chunked-Length"); + int len = 10; + if (lenStr != null) { + len = Integer.parseInt(lenStr); + } + body = Methods.encoding(body, len, useComment); + editer.setBody(body); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(stderr); + } + } + } + + + ///proxy function should be here + //reference https://support.portswigger.net/customer/portal/questions/17350102-burp-upstream-proxy-settings-and-sethttpservice + String proxy = this.tableModel.getConfigByKey("Proxy-ServerList"); + String mode = this.tableModel.getConfigByKey("Proxy-UseRandomMode"); + + if (proxy != null) {//if enable is false, will return null. + List proxyList = Arrays.asList(proxy.split(";"));//如果字符串是以;结尾,会被自动丢弃 + + if (mode != null) {//random mode + proxyServerIndex = (int) (Math.random() * proxyList.size()); + //proxyServerIndex = new Random().nextInt(proxyList.size()); + } else { + proxyServerIndex = (proxyServerIndex + 1) % proxyList.size(); + } + String proxyhost = proxyList.get(proxyServerIndex).split(":")[0].trim(); + int port = Integer.parseInt(proxyList.get(proxyServerIndex).split(":")[1].trim()); + editer.setService( + helpers.buildHttpService(proxyhost, port, messageInfo.getHttpService().getProtocol())); + String firstrline = editer.getFirstLineOfHeader().replaceFirst(path, url.toString().split("\\?",0)[0]); + editer.setFirstLineOfHeader(firstrline); + isRequestChanged = true; + //success or failed,need to check? + } + } catch (Exception e) { + e.printStackTrace(stderr); + } + } + } + //set final request + editer.setHeaderMap(headers); + messageInfo = editer.getMessageInfo(); + + if (isRequestChanged) { + //debug + List finalheaders = helpers.analyzeRequest(messageInfo).getHeaders(); + //List finalheaders = editer.getHeaderList();//error here:bodyOffset getted twice are different + stdout.println(System.lineSeparator() + "//////////edited request by knife//////////////" + System.lineSeparator()); + for (String entry : finalheaders) { + stdout.println(entry); + } + } + } + }//sync + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `headers` last assigned on line 172 could be null and is dereferenced at line 179. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BurpExtender.processHttpMessage(int,boolean,IHttpRequestResponse) + +### Procedure Id: +burp.BurpExtender.processHttpMessage(int,boolean,burp.IHttpRequestResponse):void.a0311fadb7f0fa1679f2dde3035e8a88 + +### File: +src/burp/BurpExtender.java + +### Key: +BurpExtender.java|processHttpMessage|NULL_DEREFERENCE + +### Node Key: +7e9fc31bc469440d6384630f8b346526 + +### Hash: +bc0beb78a32c46f8685c026dd7521520 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1102/instruction.md b/inferredbugs-1102/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8e52996659409469d18ee7bb04bc08f8455ce12b --- /dev/null +++ b/inferredbugs-1102/instruction.md @@ -0,0 +1,118 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Evolve +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Data; +using System.Diagnostics.CodeAnalysis; +using Npgsql; + +namespace Evolve.Tests.Infrastructure +{ + public class PostgreSqlContainer : IDbContainer + { + public const string ExposedPort = "5432"; + public const string HostPort = "5432"; + public const string DbName = "my_database"; + public const string DbPwd = "Password12!"; + public const string DbUser = "postgres"; + + private DockerContainer _container; + private bool _disposedValue = false; + + public string Id => _container?.Id; + public string CnxStr => $"Server=127.0.0.1;Port={HostPort};Database={DbName};User Id={DbUser};Password={DbPwd};"; + public int TimeOutInSec => 5; + + [SuppressMessage("Qualité du code", "IDE0068: Utilisez le modèle de suppression recommandé")] + public bool Start(bool fromScratch = false) + { + _container = new DockerContainerBuilder(new DockerContainerBuilderOptions + { + FromImage = "postgres", + Tag = "alpine", + Name = "postgres-evolve", + Env = new[] { $"POSTGRES_PASSWORD={DbPwd}", $"POSTGRES_DB={DbName}" }, + ExposedPort = $"{ExposedPort}/tcp", + HostPort = HostPort, + RemovePreviousContainer = fromScratch + }).Build(); + + return _container.Start(); + } + + public IDbConnection CreateDbConnection() => new NpgsqlConnection(CnxStr); + + protected virtual void Dispose(bool disposing) + { + if (!_disposedValue) + { + if (disposing) + { + _container?.Dispose(); + } + + _disposedValue = true; + } + } + + public void Dispose() + { + Dispose(true); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Evolve.Tests.Infrastructure.DockerContainerBuilder::.ctor() at Line 25) of type Evolve.Tests.Infrastructure.DockerContainerBuilder in method "Boolean PostgreSqlContainer.Start(Boolean)". + +### Severity: +ERROR + +### Procedure: +Boolean PostgreSqlContainer.Start(Boolean) + +### File: +test/Evolve.Tests/Infrastructure/PostgreSql/PostgreSqlContainer.cs + +### Key: +PostgreSqlContainer.cs|Start|DOTNET_RESOURCE_LEAK + +### Hash: +2db880932a759b5789382738bcfad287 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11027/instruction.md b/inferredbugs-11027/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..911489f4ad9d2dd282698fa72a9349c84e99a9d7 --- /dev/null +++ b/inferredbugs-11027/instruction.md @@ -0,0 +1,134 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** shiro +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jsecurity.web.filter.authz; + +import org.jsecurity.subject.Subject; + +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import java.io.IOException; +import java.util.Set; + +/** + * Filter that allows access if the current user has the roles specified by the mapped value, or denies access + * if the user does not have all of the roles specified. + * + * @author Les Hazlewood + * @author Jeremy Haile + * @since 0.9 + */ +public class RolesAuthorizationFilter extends AuthorizationFilter { + + @SuppressWarnings({"unchecked"}) + public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException { + + Subject subject = getSubject(request, response); + Set roles = (Set) mappedValue; + + boolean hasRoles = true; + if (roles != null && !roles.isEmpty()) { + if (roles.size() == 1) { + if (!subject.hasRole(roles.iterator().next())) { + hasRoles = false; + } + } else { + if (!subject.hasAllRoles(roles)) { + hasRoles = false; + } + } + } + + return hasRoles; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `subject` last assigned on line 41 could be null and is dereferenced at line 47. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean RolesAuthorizationFilter.isAccessAllowed(ServletRequest,ServletResponse,Object) + +### Procedure Id: +org.jsecurity.web.filter.authz.RolesAuthorizationFilter.isAccessAllowed(javax.servlet.ServletRequest.be6b6cb351185272845f81658ec21bbd + +### File: +src/org/jsecurity/web/filter/authz/RolesAuthorizationFilter.java + +### Key: +RolesAuthorizationFilter.java|isAccessAllowed|NULL_DEREFERENCE + +### Node Key: +81786aebecfb9e810bf5b2177f15eac4 + +### Hash: +e3ae93ad29ad94c459e5d15651712966 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11029/instruction.md b/inferredbugs-11029/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0dd69c3328843caf515d8adf6a8e7dee3e8f9c29 --- /dev/null +++ b/inferredbugs-11029/instruction.md @@ -0,0 +1,134 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** shiro +**Bug ID:** 17 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jsecurity.web.filter.authz; + +import org.jsecurity.subject.Subject; + +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import java.io.IOException; +import java.util.Set; + +/** + * Filter that allows access if the current user has the roles specified by the mapped value, or denies access + * if the user does not have all of the roles specified. + * + * @author Les Hazlewood + * @author Jeremy Haile + * @since 0.9 + */ +public class RolesAuthorizationFilter extends AuthorizationFilter { + + @SuppressWarnings({"unchecked"}) + public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException { + + Subject subject = getSubject(request, response); + Set roles = (Set) mappedValue; + + boolean hasRoles = true; + if (roles != null && !roles.isEmpty()) { + if (roles.size() == 1) { + if (!subject.hasRole(roles.iterator().next())) { + hasRoles = false; + } + } else { + if (!subject.hasAllRoles(roles)) { + hasRoles = false; + } + } + } + + return hasRoles; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `subject` last assigned on line 41 could be null and is dereferenced at line 51. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean RolesAuthorizationFilter.isAccessAllowed(ServletRequest,ServletResponse,Object) + +### Procedure Id: +org.jsecurity.web.filter.authz.RolesAuthorizationFilter.isAccessAllowed(javax.servlet.ServletRequest.be6b6cb351185272845f81658ec21bbd + +### File: +src/org/jsecurity/web/filter/authz/RolesAuthorizationFilter.java + +### Key: +RolesAuthorizationFilter.java|isAccessAllowed|NULL_DEREFERENCE + +### Node Key: +e4b22ed7a9dedac4f4f90048918948a2 + +### Hash: +e3ae93ad29ad94c459e5d15651712966 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1105/instruction.md b/inferredbugs-1105/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5be6b45f9f357ccf699653d78807ebe06ee44da5 --- /dev/null +++ b/inferredbugs-1105/instruction.md @@ -0,0 +1,1956 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** parser +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections; +using System.Linq; +using GraphQLParser.AST; +using GraphQLParser.Exceptions; +using Shouldly; +using Xunit; + +namespace GraphQLParser.Tests; + +public class ParserTests +{ + private static readonly string _nl = Environment.NewLine; + + [Fact] + public void Should_Throw_With_Deep_Query() + { + var count = 63; + var sb = new System.Text.StringBuilder(count * 3); + for (int i = 0; i < count; i++) + sb.Append("{a"); + sb.Append(new string('}', count)); + var query = sb.ToString(); + Should.Throw(() => query.Parse()); + } + + [Fact] + public void Should_Throw_With_Deep_Literal() + { + var count = 61; + var sb = new System.Text.StringBuilder(count * 4 + 10); + sb.Append("{a(b:"); + for (int i = 0; i < count; i++) + sb.Append("{c:"); + sb.Append("{}"); + sb.Append(new string('}', count)); + sb.Append(")}"); + var query = sb.ToString(); + Should.Throw(() => query.Parse()); + } + + [Fact] + public void Should_Parse_With_Almost_Deep_Query() + { + var count = 62; + var sb = new System.Text.StringBuilder(count * 3); + for (int i = 0; i < count; i++) + sb.Append("{a"); + sb.Append(new string('}', count)); + var query = sb.ToString(); + _ = query.Parse(); + } + + [Fact] + public void Should_Parse_With_Almost_Deep_Literal() + { + var count = 60; + var sb = new System.Text.StringBuilder(count * 4 + 10); + sb.Append("{a(b:"); + for (int i = 0; i < count; i++) + sb.Append("{c:"); + sb.Append("{}"); + sb.Append(new string('}', count)); + sb.Append(")}"); + var query = sb.ToString(); + _ = query.Parse(); + } + + [Fact] + public void Should_Parse_With_Shallow_Long_Query() + { + var count = 200; + var sb = new System.Text.StringBuilder(count * 5); + sb.Append('{'); + for (int i = 0; i < count; i++) + sb.Append(" a" + i); + sb.Append('}'); + var query = sb.ToString(); + _ = query.Parse(); + } + + [Fact] + public void Should_Throw_With_MaxDepth_0_On_SimpleQuery() + { + var query = "{a}"; + Should.Throw(() => Parser.Parse(query, new ParserOptions { MaxDepth = 0 })); + } + + [Fact] + public void Should_Throw_With_MaxDepth_2_On_TypeDefinition() + { + var query = "scalar Test"; + Should.Throw(() => Parser.Parse(query, new ParserOptions { MaxDepth = 2 })); + } + + [Fact] + public void Should_Throw_With_MaxDepth_4_On_SimpleQuery() + { + var query = "{a}"; + Should.Throw(() => Parser.Parse(query, new ParserOptions { MaxDepth = 4 })); + } + + [Fact] + public void Should_Parse_With_MaxDepth_3_On_TypeDefinition() + { + var query = "scalar Test"; + _ = Parser.Parse(query, new ParserOptions { MaxDepth = 3 }); + } + + [Fact] + public void Should_Parse_With_MaxDepth_5_On_SimpleQuery() + { + var query = "{a}"; + _ = Parser.Parse(query, new ParserOptions { MaxDepth = 5 }); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Extra_Comments_Should_Read_Correctly(IgnoreOptions options) + { + string query = "ExtraComments".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(1); + // query + var def = document.Definitions.First() as GraphQLOperationDefinition; + def.SelectionSet.Selections.Count.ShouldBe(2); + // person + var field = def.SelectionSet.Selections.First() as GraphQLField; + field.SelectionSet.Selections.Count.ShouldBe(1); + // name + var subField = field.SelectionSet.Selections.First() as GraphQLField; + subField.Comment.ShouldBeNull(); + // test + field = def.SelectionSet.Selections.Last() as GraphQLField; + field.SelectionSet.Selections.Count.ShouldBe(1); + field.Comment.ShouldNotBeNull().Value.ShouldBe("comment2"); + // alt + subField = field.SelectionSet.Selections.First() as GraphQLField; + subField.Comment.ShouldBeNull(); + // extra document comments + document.UnattachedComments.Count.ShouldBe(3); + document.UnattachedComments[0].Value.ShouldBe("comment1"); + document.UnattachedComments[1].Value.ShouldBe("comment3"); + document.UnattachedComments[2].Value.ShouldBe("comment4"); + } + + [Theory] + //[InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + //[InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Comments_Can_Be_Ignored(IgnoreOptions options) + { + const string query = @" +{ + #comment + person + # comment2 +}"; + + var document = query.Parse(new ParserOptions { Ignore = options }); + document.UnattachedComments.ShouldBeNull(); + document.Definitions.Count.ShouldBe(1); + var def = document.Definitions.First() as GraphQLOperationDefinition; + def.SelectionSet.Selections.Count.ShouldBe(1); + def.Comment.ShouldBeNull(); + var field = def.SelectionSet.Selections.First() as GraphQLField; + field.Comment.ShouldBeNull(); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_FragmentSpread_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnFragmentSpread".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(2); + var def = document.Definitions.First() as GraphQLOperationDefinition; + def.SelectionSet.Selections.Count.ShouldBe(1); + var field = def.SelectionSet.Selections.First() as GraphQLField; + field.SelectionSet.Selections.Count.ShouldBe(1); + var fragment = field.SelectionSet.Selections.First() as GraphQLFragmentSpread; + fragment.Comment.ShouldNotBeNull().Value.ShouldBe("comment"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_Values_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnValues".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(1); + var def = document.Definitions.First() as GraphQLOperationDefinition; + def.SelectionSet.Selections.Count.ShouldBe(1); + var field = def.SelectionSet.Selections.First() as GraphQLField; + field.SelectionSet.Selections.Count.ShouldBe(1); + field.Arguments.Count.ShouldBe(9); + + var boolValue = field.Arguments[0].Value.ShouldBeAssignableTo(); + boolValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for bool"); + + var nullValue = field.Arguments[1].Value.ShouldBeAssignableTo(); + nullValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for null"); + + var enumValue = field.Arguments[2].Value.ShouldBeAssignableTo(); + enumValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for enum"); + + var listValue = field.Arguments[3].Value.ShouldBeAssignableTo(); + listValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for list"); + + var objValue = field.Arguments[4].Value.ShouldBeAssignableTo(); + objValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for object"); + + var intValue = field.Arguments[5].Value.ShouldBeAssignableTo(); + intValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for int"); + + var floatValue = field.Arguments[6].Value.ShouldBeAssignableTo(); + floatValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for float"); + + var stringValue = field.Arguments[7].Value.ShouldBeAssignableTo(); + stringValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for string"); + + var varValue = field.Arguments[8].Value.ShouldBeAssignableTo(); + varValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for variable"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_FragmentInline_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnInlineFragment".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(1); + var def = document.Definitions.First() as GraphQLOperationDefinition; + def.SelectionSet.Selections.Count.ShouldBe(1); + var field = def.SelectionSet.Selections.First() as GraphQLField; + field.SelectionSet.Selections.Count.ShouldBe(1); + var fragment = field.SelectionSet.Selections.First() as GraphQLInlineFragment; + fragment.Comment.ShouldNotBeNull().Value.ShouldBe("comment"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_Arguments_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnArguments".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(1); + var def = document.Definitions[0] as GraphQLOperationDefinition; + def.SelectionSet.Selections.Count.ShouldBe(1); + var field = def.SelectionSet.Selections.First() as GraphQLField; + field.Arguments.Count.ShouldBe(2); + field.Arguments.Comment.ShouldNotBeNull().Value.ShouldBe("arguments comment"); + var obj = field.Arguments[1].Value.ShouldBeAssignableTo(); + obj.Fields.Count.ShouldBe(1); + obj.Fields[0].Name.Value.ShouldBe("z"); + obj.Fields[0].Comment.Value.ShouldBe("comment on object field"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_NamedTypes_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnNamedType".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(5); + + var def1 = document.Definitions[0] as GraphQLOperationDefinition; + var field = def1.SelectionSet.Selections[0] as GraphQLField; + var frag = field.SelectionSet.Selections[0] as GraphQLInlineFragment; + frag.TypeCondition.Type.Comment.Value.ShouldBe("comment for named type from TypeCondition"); + + var def2 = document.Definitions[1] as GraphQLObjectTypeDefinition; + def2.Interfaces[0].Comment.Value.ShouldBe("comment for named type from ImplementsInterfaces"); + + var def3 = document.Definitions[2] as GraphQLSchemaDefinition; + def3.OperationTypes[0].Type.Comment.Value.ShouldBe("comment for named type from RootOperationTypeDefinition"); + + var def4 = document.Definitions[3] as GraphQLObjectTypeDefinition; + def4.Fields[0].Type.Comment.Value.ShouldBe("comment for named type from Type"); + + var def5 = document.Definitions[4] as GraphQLUnionTypeDefinition; + def5.Types[1].Comment.Value.ShouldBe("comment for named type from UnionMemberTypes"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_SelectionSet_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnSelectionSet".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(1); + var def = document.Definitions[0] as GraphQLOperationDefinition; + def.SelectionSet.Comment.Value.ShouldBe("comment on selection set"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_RootOperationType_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnRootOperationType".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(1); + var def = document.Definitions[0] as GraphQLSchemaDefinition; + def.OperationTypes[0].Comment.Value.ShouldBe("comment for root operation type"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_Directive_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnDirective".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(1); + var def = document.Definitions[0] as GraphQLScalarTypeDefinition; + def.Directives[0].Comment.Value.ShouldBe("comment for directive"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_Type_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnType".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(3); + var def = document.Definitions[0] as GraphQLObjectTypeDefinition; + def.Comment.Value.ShouldBe("very good type"); + def.Interfaces.Comment.Value.ShouldBe("comment for implemented interfaces"); + def.Fields.Comment.Value.ShouldBe("comment for fields definition"); + def.Fields[0].Type.Comment.Value.ShouldBe("comment for named type"); + def.Fields[0].Arguments.Comment.Value.ShouldBe("comment for arguments definition"); + def.Fields[1].Type.Comment.Value.ShouldBe("comment for nonnull type"); + def.Fields[2].Type.Comment.Value.ShouldBe("comment for list type"); + (def.Fields[2].Type as GraphQLListType).Type.Comment.Value.ShouldBe("comment for item type"); + + var ext1 = document.Definitions[1] as GraphQLObjectTypeExtension; + ext1.Comment.Value.ShouldBe("forgot about address!"); + + var ext2 = document.Definitions[2] as GraphQLInterfaceTypeExtension; + ext2.Comment.Value.ShouldBe("forgot about vip!"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_Input_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnInput".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(2); + var def = document.Definitions[0] as GraphQLInputObjectTypeDefinition; + def.Comment.Value.ShouldBe("very good input"); + def.Fields.Comment.Value.ShouldBe("comment for input fields definition"); + def.Fields[0].Type.Comment.Value.ShouldBe("comment for named type"); + def.Fields[1].Type.Comment.Value.ShouldBe("comment for nonnull type"); + def.Fields[2].Type.Comment.Value.ShouldBe("comment for list type"); + (def.Fields[2].Type as GraphQLListType).Type.Comment.Value.ShouldBe("comment for item type"); + + var ext = document.Definitions[1] as GraphQLInputObjectTypeExtension; + ext.Comment.Value.ShouldBe("forgot about address!"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_Alias_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnAlias".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(1); + var def = document.Definitions[0] as GraphQLOperationDefinition; + def.SelectionSet.Selections.Count.ShouldBe(1); + var field = def.SelectionSet.Selections[0].ShouldBeAssignableTo(); + field.Name.Value.ShouldBe("name"); + field.Comment.Value.ShouldBe("field comment"); + field.Alias.Name.Value.ShouldBe("a"); + field.Alias.Comment.Value.ShouldBe("alias comment"); + + document.UnattachedComments.Count.ShouldBe(1); + document.UnattachedComments[0].Value.ShouldBe("colon comment"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_DirectiveDefinition_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnDirectiveDefinition".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(1); + var def = document.Definitions[0] as GraphQLDirectiveDefinition; + def.Comment.Value.ShouldBe("very good directive"); + def.Locations.Comment.Value.ShouldBe("comment for directive locations"); + + document.UnattachedComments.ShouldBeNull(); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_Enum_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnEnum".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(2); + var def = document.Definitions[0] as GraphQLEnumTypeDefinition; + def.Comment.Value.ShouldBe("very good colors"); + def.Values.Comment.Value.ShouldBe("values"); + def.Values[0].Comment.Value.ShouldBe("not green"); + def.Values[1].Comment.Value.ShouldBe("not red"); + + var ext = document.Definitions[1] as GraphQLEnumTypeExtension; + ext.Comment.Value.ShouldBe("forgot about orange!"); + + document.UnattachedComments.ShouldBeNull(); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_Schema_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnSchema".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(2); + var def = document.Definitions[0] as GraphQLSchemaDefinition; + def.Comment.Value.ShouldBe("very good schema"); + + var ext = document.Definitions[1] as GraphQLSchemaExtension; + ext.Comment.Value.ShouldBe("forgot about mutation!"); + + document.UnattachedComments.ShouldBeNull(); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_Scalar_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnScalar".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(2); + var def = document.Definitions[0] as GraphQLScalarTypeDefinition; + def.Comment.Value.ShouldBe("very good scalar"); + + var ext = document.Definitions[1] as GraphQLScalarTypeExtension; + ext.Comment.Value.ShouldBe("forgot about external!"); + + document.UnattachedComments.ShouldBeNull(); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_Union_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnUnion".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(2); + var def = document.Definitions[0] as GraphQLUnionTypeDefinition; + def.Comment.Value.ShouldBe("very good union"); + def.Types.Comment.Value.ShouldBe("comment for union members"); + + var ext = document.Definitions[1] as GraphQLUnionTypeExtension; + ext.Comment.Value.ShouldBe("forgot about C!"); + + document.UnattachedComments.ShouldBeNull(); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_on_Variable_Should_Read_Correctly(IgnoreOptions options) + { + string query = "CommentsOnVariables".ReadGraphQLFile(); + + using var document = query.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(1); + var def = document.Definitions.First() as GraphQLOperationDefinition; + def.Variables.Count.ShouldBe(3); + def.Variables.Comment.Value.ShouldBe("very good variables definition"); + def.Variables[0].Comment.ShouldNotBeNull().Value.ShouldBe("comment1"); + def.Variables.Skip(1).First().Comment.ShouldBeNull(); + def.Variables.Skip(2).First().Comment.ShouldNotBeNull().Value.ShouldBe("comment3"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_On_SelectionSet_Should_Read_Correctly(IgnoreOptions options) + { + using var document = @" +query { + # a comment below query + field1 + field2 + #second comment + field3 +} +".Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(1); + var def = document.Definitions.First() as GraphQLOperationDefinition; + def.SelectionSet.Selections.Count.ShouldBe(3); + def.SelectionSet.Selections.First().Comment.ShouldNotBeNull().Value.ShouldBe(" a comment below query"); + def.SelectionSet.Selections.Skip(1).First().Comment.ShouldBe(null); + def.SelectionSet.Selections.Skip(2).First().Comment.ShouldNotBeNull().Value.ShouldBe("second comment"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + //[InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Comments_On_Enum_Definitions_Should_Read_Correctly(IgnoreOptions options) + { + using var document = @" +# different animals +enum Animal { + #a cat + Cat + #a dog + Dog + Octopus + #bird is the word + Bird +} + +input Parameter { + #any value + Value: String +} + +scalar JSON +".Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(3); + var d1 = document.Definitions.First() as GraphQLEnumTypeDefinition; + d1.Name.Value.ShouldBe("Animal"); + d1.Comment.ShouldNotBeNull().Value.ShouldBe(" different animals"); + d1.Values[0].Name.Value.ShouldBe("Cat"); + d1.Values[0].Comment.ShouldNotBeNull(); + d1.Values[0].Comment.Value.ShouldBe("a cat"); + d1.Values.Skip(2).First().Name.Value.ShouldBe("Octopus"); + d1.Values.Skip(2).First().Comment.ShouldBeNull(); + + var d2 = document.Definitions.Skip(1).First() as GraphQLInputObjectTypeDefinition; + d2.Name.Value.ShouldBe("Parameter"); + d2.Comment.ShouldBeNull(); + d2.Fields.Count.ShouldBe(1); + d2.Fields[0].Comment.Value.ShouldBe("any value"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_Unicode_Char_At_EOF_Should_Throw(IgnoreOptions options) + { + Should.Throw(() => "{\"\\ue }".Parse(new ParserOptions { Ignore = options })); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + //[InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Parse_FieldInput_HasCorrectLocations(IgnoreOptions options) + { + // { field } + using var document = ParseGraphQLFieldSource(options); + + document.Location.ShouldBe(new GraphQLLocation(0, 9)); // { field } + document.Definitions.First().Location.ShouldBe(new GraphQLLocation(0, 9)); // { field } + (document.Definitions.First() as GraphQLOperationDefinition).SelectionSet.Location.ShouldBe(new GraphQLLocation(0, 9)); // { field } + (document.Definitions.First() as GraphQLOperationDefinition).SelectionSet.Selections.First().Location.ShouldBe(new GraphQLLocation(2, 7)); // field + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_FieldInput_HasOneOperationDefinition(IgnoreOptions options) + { + using var document = ParseGraphQLFieldSource(options); + + document.Definitions.First().Kind.ShouldBe(ASTNodeKind.OperationDefinition); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_FieldInput_NameIsNull(IgnoreOptions options) + { + using var document = ParseGraphQLFieldSource(options); + + GetSingleOperationDefinition(document).Name.ShouldBeNull(); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_FieldInput_OperationIsQuery(IgnoreOptions options) + { + using var document = ParseGraphQLFieldSource(options); + + GetSingleOperationDefinition(document).Operation.ShouldBe(OperationType.Query); + } + + [Fact] + public void Should_Throw_On_Unknown_OperationType() + { + var ex = Should.Throw(() => "superquery { a }".Parse()); + ex.Description.ShouldBe("Expected \"query/mutation/subscription/fragment/schema/scalar/type/interface/union/enum/input/extend/directive\", found Name \"superquery\""); + ex.Line.ShouldBe(1); + ex.Column.ShouldBe(1); + } + + [Theory] + [InlineData("enum E { true A }", "Unexpected Name \"true\"; enum values are represented as unquoted names but not 'true' or 'false' or 'null'.", 1, 10)] + [InlineData("enum E { B false }", "Unexpected Name \"false\"; enum values are represented as unquoted names but not 'true' or 'false' or 'null'.", 1, 12)] + [InlineData("enum E { A null B }", "Unexpected Name \"null\"; enum values are represented as unquoted names but not 'true' or 'false' or 'null'.", 1, 12)] + public void Should_Throw_On_Invalid_EnumValue(string query, string description, int line, int column) + { + var ex = Should.Throw(() => query.Parse()); + ex.Description.ShouldBe(description); + ex.Line.ShouldBe(line); + ex.Column.ShouldBe(column); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_FieldInput_ReturnsDocumentNode(IgnoreOptions options) + { + using var document = ParseGraphQLFieldSource(options); + + document.Kind.ShouldBe(ASTNodeKind.Document); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_FieldInput_SelectionSetContainsSingleField(IgnoreOptions options) + { + using var document = ParseGraphQLFieldSource(options); + + GetSingleSelection(document).Kind.ShouldBe(ASTNodeKind.Field); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + //[InlineData(IgnoreOptions.Locations)] + //[InlineData(IgnoreOptions.All)] + public void Parse_FieldWithOperationTypeAndNameInput_HasCorrectLocations(IgnoreOptions options) + { + // mutation Foo { field } + using var document = ParseGraphQLFieldWithOperationTypeAndNameSource(options); + + document.Location.ShouldBe(new GraphQLLocation(0, 22)); + document.Definitions.First().Location.ShouldBe(new GraphQLLocation(0, 22)); + (document.Definitions.First() as GraphQLOperationDefinition).Name.Location.ShouldBe(new GraphQLLocation(9, 12)); // Foo + (document.Definitions.First() as GraphQLOperationDefinition).SelectionSet.Location.ShouldBe(new GraphQLLocation(13, 22)); // { field } + (document.Definitions.First() as GraphQLOperationDefinition).SelectionSet.Selections.First().Location.ShouldBe(new GraphQLLocation(15, 20)); // field + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_FieldWithOperationTypeAndNameInput_HasOneOperationDefinition(IgnoreOptions options) + { + using var document = ParseGraphQLFieldWithOperationTypeAndNameSource(options); + + document.Definitions.First().Kind.ShouldBe(ASTNodeKind.OperationDefinition); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_FieldWithOperationTypeAndNameInput_NameIsNull(IgnoreOptions options) + { + using var document = ParseGraphQLFieldWithOperationTypeAndNameSource(options); + + GetSingleOperationDefinition(document).Name.Value.ShouldBe("Foo"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_FieldWithOperationTypeAndNameInput_OperationIsQuery(IgnoreOptions options) + { + using var document = ParseGraphQLFieldWithOperationTypeAndNameSource(options); + + GetSingleOperationDefinition(document).Operation.ShouldBe(OperationType.Mutation); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_FieldWithOperationTypeAndNameInput_ReturnsDocumentNode(IgnoreOptions options) + { + using var document = ParseGraphQLFieldWithOperationTypeAndNameSource(options); + + document.Kind.ShouldBe(ASTNodeKind.Document); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_FieldWithOperationTypeAndNameInput_SelectionSetContainsSingleFieldWithOperationTypeAndNameSelection(IgnoreOptions options) + { + using var document = ParseGraphQLFieldWithOperationTypeAndNameSource(options); + + GetSingleSelection(document).Kind.ShouldBe(ASTNodeKind.Field); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_KitchenSink_DoesNotThrowError(IgnoreOptions options) + { + using var document = "KitchenSink".ReadGraphQLFile().Parse(new ParserOptions { Ignore = options }); + + document.OperationsCount().ShouldBe(5); + document.FragmentsCount().ShouldBe(1); + document.FindFragmentDefinition("qwerty").ShouldBeNull(); + document.FindFragmentDefinition("frag").ShouldNotBeNull(); + + var typeDef = document.Definitions.OfType().First(d => d.Name.Value == "Foo"); + var fieldDef = typeDef.Fields.First(d => d.Name.Value == "three"); + if (options.HasFlag(IgnoreOptions.Comments)) + fieldDef.Comment.ShouldBeNull(); + else + fieldDef.Comment.ShouldNotBeNull().Value.ShouldBe($" multiline comments{_nl} with very importand description #{_nl} # and symbol # and ##"); + + // Schema description + // https://github.com/graphql/graphql-spec/pull/466 + var comment = document.Definitions.OfType().First().Comment; + if (options.HasFlag(IgnoreOptions.Comments)) + { + comment.ShouldBeNull(); + } + else + { + comment.ShouldNotBeNull(); + ((string)comment.Value).StartsWith(" Copyright (c) 2015, Facebook, Inc.").ShouldBeTrue(); + } + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_NullInput_EmptyDocument(IgnoreOptions options) + { + using var document = ((string)null).Parse(new ParserOptions { Ignore = options }); + + document.Definitions.ShouldBeEmpty(); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_VariableInlineValues_DoesNotThrowError(IgnoreOptions options) + { + using ("{ field(complex: { a: { b: [ $var ] } }) }".Parse(new ParserOptions { Ignore = options })) + { + } + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Should_Read_Directives_on_VariableDefinition(IgnoreOptions options) + { + using (var document = "query A($id: String @a @b(priority: 1, managed: true)) { name }".Parse(new ParserOptions { Ignore = options })) + { + document.Definitions.Count.ShouldBe(1); + var def = document.Definitions[0].ShouldBeAssignableTo(); + def.Variables.Count.ShouldBe(1); + def.Variables[0].Directives.Count.ShouldBe(2); + def.Variables[0].Directives[0].Name.Value.ShouldBe("a"); + def.Variables[0].Directives[1].Name.Value.ShouldBe("b"); + def.Variables[0].Directives[1].Arguments.Count.ShouldBe(2); + + // ASTListNode small test + def.Variables.GetEnumerator().ShouldBe(((IEnumerable)def.Variables).GetEnumerator()); + } + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_Empty_Field_Arguments_Should_Throw(IgnoreOptions options) + { + Should.Throw(() => "{ a() }".Parse(new ParserOptions { Ignore = options })); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_Empty_Directive_Arguments_Should_Throw(IgnoreOptions options) + { + Should.Throw(() => "directive @dir() on FIELD_DEFINITION".Parse(new ParserOptions { Ignore = options })); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_Empty_Enum_Values_Should_Throw(IgnoreOptions options) + { + Should.Throw(() => "enum Empty { }".Parse(new ParserOptions { Ignore = options })); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_Empty_SelectionSet_Should_Throw(IgnoreOptions options) + { + Should.Throw(() => "{ a { } }".Parse(new ParserOptions { Ignore = options })); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Parse_Empty_VariableDefinitions_Should_Throw(IgnoreOptions options) + { + Should.Throw(() => "query test() { a }".Parse(new ParserOptions { Ignore = options })); + } + + private static GraphQLOperationDefinition GetSingleOperationDefinition(GraphQLDocument document) + { + return (GraphQLOperationDefinition)document.Definitions.Single(); + } + + private static ASTNode GetSingleSelection(GraphQLDocument document) + { + return GetSingleOperationDefinition(document).SelectionSet.Selections.Single(); + } + + private static GraphQLDocument ParseGraphQLFieldSource(IgnoreOptions options) => "{ field }".Parse(new ParserOptions { Ignore = options }); + + private static GraphQLDocument ParseGraphQLFieldWithOperationTypeAndNameSource(IgnoreOptions options) => "mutation Foo { field }".Parse(new ParserOptions { Ignore = options }); + + [Theory] + [InlineData("directive @dir repeatable on FIELD_DEFINITION", true)] + [InlineData("directive @dir(a: Int) repeatable on FIELD_DEFINITION", true)] + [InlineData("directive @dir on FIELD_DEFINITION | ENUM_VALUE", false)] + [InlineData("directive @dir on | FIELD_DEFINITION | ENUM_VALUE", false)] + [InlineData(@"directive @dir on +FIELD_DEFINITION | ENUM_VALUE", false)] + [InlineData(@"directive @dir on +FIELD_DEFINITION +| ENUM_VALUE", false)] + [InlineData(@"directive @dir on +| FIELD_DEFINITION +| ENUM_VALUE", false)] + [InlineData(@"directive @dir on +| FIELD_DEFINITION +| ENUM_VALUE", false)] + public void Should_Parse_Directives(string text, bool repeatable) + { + using var document = text.Parse(); + document.ShouldNotBeNull(); + document.Definitions.Count.ShouldBe(1); + document.Definitions[0].ShouldBeAssignableTo().Repeatable.ShouldBe(repeatable); + } + + [Theory] + [InlineData("directive @dir repeatable on OOPS", 1, 30)] + [InlineData("directive @dir(a: Int) repeatable on OOPS", 1, 38)] + [InlineData("directive @dir on FIELD_DEFINITION | OOPS", 1, 38)] + [InlineData("directive @dir on | OOPS | ENUM_VALUE", 1, 21)] + [InlineData(@"directive @dir on +FIELD_DEFINITION | OOPS", 2, 20)] + [InlineData(@"directive @dir on +OOPS +| ENUM_VALUE", 2, 1)] + [InlineData(@"directive @dir on +| OOPS +| ENUM_VALUE", 2, 3)] + [InlineData(@"directive @dir on +| FIELD_DEFINITION +| OOPS", 3, 12)] + public void Should_Throw_On_Unknown_DirectiveLocation(string text, int line, int column) + { + var ex = Should.Throw(() => text.Parse()); + ex.Description.ShouldBe("Expected \"QUERY/MUTATION/SUBSCRIPTION/FIELD/FRAGMENT_DEFINITION/FRAGMENT_SPREAD/INLINE_FRAGMENT/VARIABLE_DEFINITION/SCHEMA/SCALAR/OBJECT/FIELD_DEFINITION/ARGUMENT_DEFINITION/INTERFACE/UNION/ENUM/ENUM_VALUE/INPUT_OBJECT/INPUT_FIELD_DEFINITION\", found Name \"OOPS\""); + ex.Line.ShouldBe(line); + ex.Column.ShouldBe(column); + } + + // http://spec.graphql.org/October2021/#sec--specifiedBy + [Fact] + public void Should_Parse_SpecifiedBy() + { + string text = @"scalar UUID @specifiedBy(url: ""https://tools.ietf.org/html/rfc4122"")"; + using var document = text.Parse(); + document.ShouldNotBeNull(); + document.Definitions.Count.ShouldBe(1); + var def = document.Definitions[0].ShouldBeAssignableTo(); + def.Directives.Count.ShouldBe(1); + def.Directives[0].Name.Value.ShouldBe("specifiedBy"); + def.Directives[0].Arguments.Count.ShouldBe(1); + def.Directives[0].Arguments[0].Name.Value.ShouldBe("url"); + var value = def.Directives[0].Arguments[0].Value.ShouldBeAssignableTo(); + value.Value.ShouldBe("https://tools.ietf.org/html/rfc4122"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Should_Fail_On_Empty_Fields(IgnoreOptions options) + { + string text = "interface Dog { }"; + Should.Throw(() => text.Parse(new ParserOptions { Ignore = options })).Message.ShouldContain("Expected Name, found }"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Should_Parse_Interfaces_Implemented_By_Interface(IgnoreOptions options) + { + string text = "InterfacesOnInterface".ReadGraphQLFile(); + + using var document = text.Parse(new ParserOptions { Ignore = options }); + document.Definitions.Count.ShouldBe(4); + var def1 = document.Definitions[0].ShouldBeAssignableTo(); + def1.Name.Value.ShouldBe("Dog"); + def1.Interfaces.ShouldBeNull(); + + var def2 = document.Definitions[1].ShouldBeAssignableTo(); + def2.Name.Value.ShouldBe("Dog"); + def2.Interfaces.Count.ShouldBe(1); + def2.Interfaces[0].Name.Value.ShouldBe("Eat"); + + var def3 = document.Definitions[2].ShouldBeAssignableTo(); + def3.Name.Value.ShouldBe("Dog"); + def3.Interfaces.Count.ShouldBe(2); + def3.Interfaces[0].Name.Value.ShouldBe("Eat"); + def3.Interfaces[1].Name.Value.ShouldBe("Sleep"); + + var def4 = document.Definitions[3].ShouldBeAssignableTo(); + def4.Name.Value.ShouldBe("Dog"); + def4.Interfaces.Count.ShouldBe(2); + def4.Interfaces[0].Name.Value.ShouldBe("Eat"); + def4.Interfaces[1].Name.Value.ShouldBe("Sleep"); + def4.Fields.Count.ShouldBe(1); + def4.Fields[0].Name.Value.ShouldBe("name"); + } + + [Theory] + [InlineData("directive @dir On FIELD_DEFINITION")] + [InlineData("directive @dir onn FIELD_DEFINITION")] + [InlineData("directive @dir Repeatable on FIELD_DEFINITION")] + [InlineData("directive @dir repeatablee on FIELD_DEFINITION")] + [InlineData("directive @dir repeatable On FIELD_DEFINITION")] + [InlineData("directive @dir repeatable onn FIELD_DEFINITION")] + public void Should_Throw_GraphQLSyntaxErrorException(string text) + { + Should.Throw(() => text.Parse()); + } + + [Theory] + [InlineData("union Animal = Cat | Dog")] + [InlineData("union Animal = | Cat | Dog")] + [InlineData(@"union Animal = +Cat | Dog")] + [InlineData(@"union Animal = +Cat +| Dog")] + [InlineData(@"union Animal = +| Cat +| Dog")] + [InlineData(@"union Animal = +| Cat +| Dog")] + public void Should_Parse_Unions(string text) + { + using var document = text.Parse(); + document.ShouldNotBeNull(); + } + + [Theory] + [InlineData("extend scalar Foo @exportable", ASTNodeKind.ScalarTypeExtension)] + [InlineData("extend type Foo implements Bar @exportable { a: String }", ASTNodeKind.ObjectTypeExtension)] + [InlineData("extend type Foo implements Bar @exportable", ASTNodeKind.ObjectTypeExtension)] + [InlineData("extend type Foo implements Bar { a: String }", ASTNodeKind.ObjectTypeExtension)] + [InlineData("extend type Foo implements Bar", ASTNodeKind.ObjectTypeExtension)] + [InlineData("extend type Foo { a: String }", ASTNodeKind.ObjectTypeExtension)] + [InlineData("extend interface Foo implements Bar @exportable { a: String }", ASTNodeKind.InterfaceTypeExtension)] + [InlineData("extend interface Foo implements Bar @exportable", ASTNodeKind.InterfaceTypeExtension)] + [InlineData("extend interface Foo implements Bar { a: String }", ASTNodeKind.InterfaceTypeExtension)] + [InlineData("extend interface Foo { a: String }", ASTNodeKind.InterfaceTypeExtension)] + [InlineData("extend interface Foo implements Bar", ASTNodeKind.InterfaceTypeExtension)] + [InlineData("extend union Foo @exportable = A | B", ASTNodeKind.UnionTypeExtension)] + [InlineData("extend union Foo = A | B", ASTNodeKind.UnionTypeExtension)] + [InlineData("extend union Foo @exportable", ASTNodeKind.UnionTypeExtension)] + [InlineData("extend enum Foo @exportable { ONE TWO }", ASTNodeKind.EnumTypeExtension)] + [InlineData("extend enum Foo { ONE TWO }", ASTNodeKind.EnumTypeExtension)] + [InlineData("extend enum Foo @exportable", ASTNodeKind.EnumTypeExtension)] + [InlineData("extend input Foo @exportable { a: String }", ASTNodeKind.InputObjectTypeExtension)] + [InlineData("extend input Foo { a: String }", ASTNodeKind.InputObjectTypeExtension)] + [InlineData("extend input Foo @exportable", ASTNodeKind.InputObjectTypeExtension)] + public void Should_Parse_Extensions(string text, ASTNodeKind kind) + { + using var document = text.Parse(); + document.ShouldNotBeNull(); + document.Definitions[0].Kind.ShouldBe(kind); + } + + [Theory] + [InlineData("extend", "Expected \"schema/scalar/type/interface/union/enum/input\", found EOF")] + [InlineData("extend variable", "Expected \"schema/scalar/type/interface/union/enum/input\", found Name \"variable\"")] + [InlineData("extend schema", "Unexpected EOF; for more information see http://spec.graphql.org/October2021/#SchemaExtension")] + [InlineData("extend schema A", "Unexpected Name \"A\"; for more information see http://spec.graphql.org/October2021/#SchemaExtension")] + [InlineData("extend scalar", "Expected Name, found EOF; for more information see http://spec.graphql.org/October2021/#ScalarTypeExtension")] + [InlineData("extend scalar A", "Unexpected EOF; for more information see http://spec.graphql.org/October2021/#ScalarTypeExtension")] + [InlineData("extend scalar A B", "Unexpected Name \"B\"; for more information see http://spec.graphql.org/October2021/#ScalarTypeExtension")] + [InlineData("extend type", "Expected Name, found EOF; for more information see http://spec.graphql.org/October2021/#ObjectTypeExtension")] + [InlineData("extend type A", "Unexpected EOF; for more information see http://spec.graphql.org/October2021/#ObjectTypeExtension")] + [InlineData("extend type A B", "Unexpected Name \"B\"; for more information see http://spec.graphql.org/October2021/#ObjectTypeExtension")] + [InlineData("extend interface", "Expected Name, found EOF; for more information see http://spec.graphql.org/October2021/#InterfaceTypeExtension")] + [InlineData("extend interface A", "Unexpected EOF; for more information see http://spec.graphql.org/October2021/#InterfaceTypeExtension")] + [InlineData("extend interface A B", "Unexpected Name \"B\"; for more information see http://spec.graphql.org/October2021/#InterfaceTypeExtension")] + [InlineData("extend union", "Expected Name, found EOF; for more information see http://spec.graphql.org/October2021/#UnionTypeExtension")] + [InlineData("extend union A", "Unexpected EOF; for more information see http://spec.graphql.org/October2021/#UnionTypeExtension")] + [InlineData("extend enum", "Expected Name, found EOF; for more information see http://spec.graphql.org/October2021/#EnumTypeExtension")] + [InlineData("extend enum A", "Unexpected EOF; for more information see http://spec.graphql.org/October2021/#EnumTypeExtension")] + [InlineData("extend input", "Expected Name, found EOF; for more information see http://spec.graphql.org/October2021/#InputObjectTypeExtension")] + [InlineData("extend input A", "Unexpected EOF; for more information see http://spec.graphql.org/October2021/#InputObjectTypeExtension")] + public void Should_Throw_Extensions(string text, string description) + { + var ex = Should.Throw(() => text.Parse()); + ex.Description.ShouldBe(description); + } + + [Theory] + [InlineData("scalar Empty", ASTNodeKind.ScalarTypeDefinition)] + [InlineData("union Empty", ASTNodeKind.UnionTypeDefinition)] + [InlineData("type Empty", ASTNodeKind.ObjectTypeDefinition)] + [InlineData("input Empty", ASTNodeKind.InputObjectTypeDefinition)] + [InlineData("interface Empty", ASTNodeKind.InterfaceTypeDefinition)] + [InlineData("enum Empty", ASTNodeKind.EnumTypeDefinition)] + public void Should_Parse_Empty_Types(string text, ASTNodeKind kind) + { + using var document = text.Parse(); + document.ShouldNotBeNull(); + document.Definitions[0].Kind.ShouldBe(kind); + } + + [Theory] + [InlineData("type Query { }", 1, 14)] + [InlineData("extend type Query { }", 1, 21)] + [InlineData("input Empty { }", 1, 15)] + [InlineData("interface Empty { }", 1, 19)] + [InlineData("enum Empty { }", 1, 14)] + [InlineData("extend type Type implements Interface { }", 1, 41)] + public void Should_Throw_On_Empty_Types_With_Braces(string text, int line, int column) + { + var ex = Should.Throw(() => text.Parse()); + ex.Line.ShouldBe(line); + ex.Column.ShouldBe(column); + ex.Message.ShouldContain("Expected Name, found }"); + } + + [Theory] + [InlineData(@" +""misplaced description"" +query { a }")] + [InlineData(@" +""misplaced description"" +mutation m { a }")] + [InlineData(@" +""misplaced description"" +subscription s { a }")] + [InlineData(@" +""misplaced description"" +fragment x on User { name }")] + [InlineData(@" +""misplaced description"" +extend type User implements Person")] + public void Should_Throw_If_Descriptions_Not_Allowed(string query) + { + var ex = Should.Throw(() => query.Parse()); + ex.Description.ShouldBe("Unexpected String \"misplaced description\""); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Descriptions_Should_Read_Correctly(IgnoreOptions options) + { + using var document = @" +""Super schema"" +schema { + query: String +} + +""A JSON scalar"" +scalar JSON + +"""""" +Human type +"""""" +type Human { + """""" + Name of human + """""" + name: String + + ""Test"" + test( + ""desc"" + arg: Int + ): Int +} + +""Test interface"" +interface TestInterface { + ""Object name"" + name: String +} + +"""""" +Test union +"""""" +union TestUnion = Test1 | Test2 + +""Example enum"" +enum Colors { + ""Red"" RED + ""Blue"" BLUE +} + +"""""" +This is an example input object +Line two of the description +"""""" +input TestInputObject { + """""" + The value of the input object + (any JSON value is accepted) + """""" + Value: JSON +} + +""Test directive"" +directive @TestDirective ( + ""Example"" + Value: Int +) on QUERY +".Parse(new ParserOptions { Ignore = options }); + var defs = document.Definitions; + defs.Count.ShouldBe(8); + + var schemaDef = defs.Single(x => x is GraphQLSchemaDefinition) as GraphQLSchemaDefinition; + schemaDef.Description.Value.ShouldBe("Super schema"); + + var scalarDef = defs.Single(x => x is GraphQLScalarTypeDefinition) as GraphQLScalarTypeDefinition; + scalarDef.Name.Value.ShouldBe("JSON"); + scalarDef.Description.Value.ShouldBe("A JSON scalar"); + + var objectDef = defs.Single(x => x is GraphQLObjectTypeDefinition) as GraphQLObjectTypeDefinition; + objectDef.Name.Value.ShouldBe("Human"); + objectDef.Description.Value.ShouldBe("Human type"); + objectDef.Fields.Count.ShouldBe(2); + objectDef.Fields[0].Name.Value.ShouldBe("name"); + objectDef.Fields[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("String"); + objectDef.Fields[0].Description.Value.ShouldBe("Name of human"); + objectDef.Fields[1].Name.Value.ShouldBe("test"); + objectDef.Fields[1].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("Int"); + objectDef.Fields[1].Description.Value.ShouldBe("Test"); + objectDef.Fields[1].Arguments.Count.ShouldBe(1); + objectDef.Fields[1].Arguments[0].Name.Value.ShouldBe("arg"); + objectDef.Fields[1].Arguments[0].Description.Value.ShouldBe("desc"); + objectDef.Fields[1].Arguments[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("Int"); + + var interfaceDef = defs.Single(x => x is GraphQLInterfaceTypeDefinition) as GraphQLInterfaceTypeDefinition; + interfaceDef.Name.Value.ShouldBe("TestInterface"); + interfaceDef.Description.Value.ShouldBe("Test interface"); + interfaceDef.Fields.Count.ShouldBe(1); + interfaceDef.Fields[0].Name.Value.ShouldBe("name"); + interfaceDef.Fields[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("String"); + interfaceDef.Fields[0].Description.Value.ShouldBe("Object name"); + + var unionDef = defs.Single(x => x is GraphQLUnionTypeDefinition) as GraphQLUnionTypeDefinition; + unionDef.Name.Value.ShouldBe("TestUnion"); + unionDef.Description.Value.ShouldBe("Test union"); + unionDef.Types.Count.ShouldBe(2); + unionDef.Types[0].Name.Value.ShouldBe("Test1"); + unionDef.Types[1].Name.Value.ShouldBe("Test2"); + + var enumDef = defs.Single(x => x is GraphQLEnumTypeDefinition) as GraphQLEnumTypeDefinition; + enumDef.Name.Value.ShouldBe("Colors"); + enumDef.Description.Value.ShouldBe("Example enum"); + enumDef.Values.Count.ShouldBe(2); + enumDef.Values[0].Name.Value.ShouldBe("RED"); + enumDef.Values[0].Description.Value.ShouldBe("Red"); + enumDef.Values[1].Name.Value.ShouldBe("BLUE"); + enumDef.Values[1].Description.Value.ShouldBe("Blue"); + + var inputDef = defs.Single(x => x is GraphQLInputObjectTypeDefinition) as GraphQLInputObjectTypeDefinition; + inputDef.Name.Value.ShouldBe("TestInputObject"); + inputDef.Description.Value.ShouldBe("This is an example input object\nLine two of the description"); + inputDef.Fields.Count.ShouldBe(1); + inputDef.Fields[0].Name.Value.ShouldBe("Value"); + inputDef.Fields[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("JSON"); + inputDef.Fields[0].Description.Value.ShouldBe("The value of the input object\n (any JSON value is accepted)"); + + var directiveDef = defs.Single(x => x is GraphQLDirectiveDefinition) as GraphQLDirectiveDefinition; + directiveDef.Name.Value.ShouldBe("TestDirective"); + directiveDef.Description.Value.ShouldBe("Test directive"); + directiveDef.Arguments.Count.ShouldBe(1); + directiveDef.Arguments[0].Name.Value.ShouldBe("Value"); + directiveDef.Arguments[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("Int"); + directiveDef.Arguments[0].Description.Value.ShouldBe("Example"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Descriptions_WithComments_Should_Read_Correctly_1(IgnoreOptions options) + { + using var document = @" +# comment -1 +""Super schema"" +# comment 0 +schema { + query: String +} + +# comment 1 +""A JSON scalar"" +# comment 2 +scalar JSON + +# comment 3 +"""""" +Human type +"""""" +# comment 4 +type Human { + # comment 5 + """""" + Name of human + """""" + # comment 6 + name: String + + # comment 7 + ""Test"" + # comment 8 + test( + # comment 9 + ""desc"" + # comment 10 + arg: Int + ): Int +} + +# comment 11 +""Test interface"" +# comment 12 +interface TestInterface { + # comment 13 + ""Object name"" + # comment 14 + name: String +} + +# comment 15 +"""""" +Test union +"""""" +# comment 16 +union TestUnion = Test1 | Test2 + +# comment 17 +""Example enum"" +# comment 18 +enum Colors { + # comment 19 + ""Red"" + # comment 20 + RED + # comment 21 + ""Blue"" + # comment 22 + BLUE +} + +# comment 23 +"""""" +This is an example input object +Line two of the description +"""""" +# comment 24 +input TestInputObject { + # comment 25 + """""" + The value of the input object + (any JSON value is accepted) + """""" + # comment 26 + Value: JSON +} + +# comment 27 +""Test directive"" +# comment 28 +directive @TestDirective ( + # comment 29 + ""Example"" + # comment 30 + Value: Int +) on QUERY +".Parse(new ParserOptions { Ignore = options }); + var defs = document.Definitions; + defs.Count.ShouldBe(8); + var parseComments = !options.HasFlag(IgnoreOptions.Comments); + + var schemaDef = defs.Single(x => x is GraphQLSchemaDefinition) as GraphQLSchemaDefinition; + schemaDef.Description.Value.ShouldBe("Super schema"); + if (parseComments) + schemaDef.Comment.Value.ShouldBe(" comment 0"); + + var scalarDef = defs.Single(x => x is GraphQLScalarTypeDefinition) as GraphQLScalarTypeDefinition; + scalarDef.Name.Value.ShouldBe("JSON"); + scalarDef.Description.Value.ShouldBe("A JSON scalar"); + if (parseComments) + scalarDef.Comment.Value.ShouldBe(" comment 2"); + + var objectDef = defs.Single(x => x is GraphQLObjectTypeDefinition) as GraphQLObjectTypeDefinition; + objectDef.Name.Value.ShouldBe("Human"); + objectDef.Description.Value.ShouldBe("Human type"); + if (parseComments) + objectDef.Comment.Value.ShouldBe(" comment 4"); + objectDef.Fields.Count.ShouldBe(2); + objectDef.Fields[0].Name.Value.ShouldBe("name"); + objectDef.Fields[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("String"); + objectDef.Fields[0].Description.Value.ShouldBe("Name of human"); + if (parseComments) + objectDef.Fields[0].Comment.Value.ShouldBe(" comment 6"); + objectDef.Fields[1].Name.Value.ShouldBe("test"); + objectDef.Fields[1].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("Int"); + objectDef.Fields[1].Description.Value.ShouldBe("Test"); + if (parseComments) + objectDef.Fields[1].Comment.Value.ShouldBe(" comment 8"); + objectDef.Fields[1].Arguments.Count.ShouldBe(1); + objectDef.Fields[1].Arguments[0].Name.Value.ShouldBe("arg"); + objectDef.Fields[1].Arguments[0].Description.Value.ShouldBe("desc"); + objectDef.Fields[1].Arguments[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("Int"); + if (parseComments) + objectDef.Fields[1].Arguments[0].Comment.Value.ShouldBe(" comment 10"); + + var interfaceDef = defs.Single(x => x is GraphQLInterfaceTypeDefinition) as GraphQLInterfaceTypeDefinition; + interfaceDef.Name.Value.ShouldBe("TestInterface"); + interfaceDef.Description.Value.ShouldBe("Test interface"); + if (parseComments) + interfaceDef.Comment.Value.ShouldBe(" comment 12"); + interfaceDef.Fields.Count.ShouldBe(1); + interfaceDef.Fields[0].Name.Value.ShouldBe("name"); + interfaceDef.Fields[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("String"); + interfaceDef.Fields[0].Description.Value.ShouldBe("Object name"); + if (parseComments) + interfaceDef.Fields[0].Comment.Value.ShouldBe(" comment 14"); + + var unionDef = defs.Single(x => x is GraphQLUnionTypeDefinition) as GraphQLUnionTypeDefinition; + unionDef.Name.Value.ShouldBe("TestUnion"); + unionDef.Description.Value.ShouldBe("Test union"); + if (parseComments) + unionDef.Comment.Value.ShouldBe(" comment 16"); + unionDef.Types.Count.ShouldBe(2); + unionDef.Types[0].Name.Value.ShouldBe("Test1"); + unionDef.Types[1].Name.Value.ShouldBe("Test2"); + + var enumDef = defs.Single(x => x is GraphQLEnumTypeDefinition) as GraphQLEnumTypeDefinition; + enumDef.Name.Value.ShouldBe("Colors"); + enumDef.Description.Value.ShouldBe("Example enum"); + if (parseComments) + enumDef.Comment.Value.ShouldBe(" comment 18"); + enumDef.Values.Count.ShouldBe(2); + enumDef.Values[0].Name.Value.ShouldBe("RED"); + enumDef.Values[0].Description.Value.ShouldBe("Red"); + if (parseComments) + enumDef.Values[0].Comment.Value.ShouldBe(" comment 20"); + enumDef.Values[1].Name.Value.ShouldBe("BLUE"); + enumDef.Values[1].Description.Value.ShouldBe("Blue"); + if (parseComments) + enumDef.Values[1].Comment.Value.ShouldBe(" comment 22"); + + var inputDef = defs.Single(x => x is GraphQLInputObjectTypeDefinition) as GraphQLInputObjectTypeDefinition; + inputDef.Name.Value.ShouldBe("TestInputObject"); + inputDef.Description.Value.ShouldBe("This is an example input object\nLine two of the description"); + if (parseComments) + inputDef.Comment.Value.ShouldBe(" comment 24"); + inputDef.Fields.Count.ShouldBe(1); + inputDef.Fields[0].Name.Value.ShouldBe("Value"); + inputDef.Fields[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("JSON"); + inputDef.Fields[0].Description.Value.ShouldBe("The value of the input object\n (any JSON value is accepted)"); + if (parseComments) + inputDef.Fields[0].Comment.Value.ShouldBe(" comment 26"); + + var directiveDef = defs.Single(x => x is GraphQLDirectiveDefinition) as GraphQLDirectiveDefinition; + directiveDef.Name.Value.ShouldBe("TestDirective"); + directiveDef.Description.Value.ShouldBe("Test directive"); + if (parseComments) + directiveDef.Comment.Value.ShouldBe(" comment 28"); + directiveDef.Arguments.Count.ShouldBe(1); + directiveDef.Arguments[0].Name.Value.ShouldBe("Value"); + directiveDef.Arguments[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("Int"); + directiveDef.Arguments[0].Description.Value.ShouldBe("Example"); + if (parseComments) + directiveDef.Arguments[0].Comment.Value.ShouldBe(" comment 30"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Descriptions_WithComments_Should_Read_Correctly_2(IgnoreOptions options) + { + using var document = @" +""Super schema"" +# comment 1 +schema { + query: String +} + +""A JSON scalar"" +# comment 2 +scalar JSON + +"""""" +Human type +"""""" +# comment 4 +type Human { + """""" + Name of human + """""" + # comment 6 + name: String + + ""Test"" + # comment 8 + test( + ""desc"" + # comment 10 + arg: Int + ): Int +} + +""Test interface"" +# comment 12 +interface TestInterface { + ""Object name"" + # comment 14 + name: String +} + +"""""" +Test union +"""""" +# comment 16 +union TestUnion = Test1 | Test2 + +""Example enum"" +# comment 18 +enum Colors { + ""Red"" + # comment 20 + RED + ""Blue"" + # comment 22 + BLUE +} + +"""""" +This is an example input object +Line two of the description +"""""" +# comment 24 +input TestInputObject { + """""" + The value of the input object + (any JSON value is accepted) + """""" + # comment 26 + Value: JSON +} + +""Test directive"" +# comment 28 +directive @TestDirective ( + ""Example"" + # comment 30 + Value: Int +) on QUERY +".Parse(new ParserOptions { Ignore = options }); + var defs = document.Definitions; + defs.Count.ShouldBe(8); + var parseComments = !options.HasFlag(IgnoreOptions.Comments); + + var schemaDef = defs.Single(x => x is GraphQLSchemaDefinition) as GraphQLSchemaDefinition; + schemaDef.Description.Value.ShouldBe("Super schema"); + if (parseComments) + schemaDef.Comment.Value.ShouldBe(" comment 1"); + + var scalarDef = defs.Single(x => x is GraphQLScalarTypeDefinition) as GraphQLScalarTypeDefinition; + scalarDef.Name.Value.ShouldBe("JSON"); + scalarDef.Description.Value.ShouldBe("A JSON scalar"); + if (parseComments) + scalarDef.Comment.Value.ShouldBe(" comment 2"); + + var objectDef = defs.Single(x => x is GraphQLObjectTypeDefinition) as GraphQLObjectTypeDefinition; + objectDef.Name.Value.ShouldBe("Human"); + objectDef.Description.Value.ShouldBe("Human type"); + if (parseComments) + objectDef.Comment.Value.ShouldBe(" comment 4"); + objectDef.Fields.Count.ShouldBe(2); + objectDef.Fields[0].Name.Value.ShouldBe("name"); + objectDef.Fields[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("String"); + objectDef.Fields[0].Description.Value.ShouldBe("Name of human"); + if (parseComments) + objectDef.Fields[0].Comment.Value.ShouldBe(" comment 6"); + objectDef.Fields[1].Name.Value.ShouldBe("test"); + objectDef.Fields[1].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("Int"); + objectDef.Fields[1].Description.Value.ShouldBe("Test"); + if (parseComments) + objectDef.Fields[1].Comment.Value.ShouldBe(" comment 8"); + objectDef.Fields[1].Arguments.Count.ShouldBe(1); + objectDef.Fields[1].Arguments[0].Name.Value.ShouldBe("arg"); + objectDef.Fields[1].Arguments[0].Description.Value.ShouldBe("desc"); + objectDef.Fields[1].Arguments[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("Int"); + if (parseComments) + objectDef.Fields[1].Arguments[0].Comment.Value.ShouldBe(" comment 10"); + + var interfaceDef = defs.Single(x => x is GraphQLInterfaceTypeDefinition) as GraphQLInterfaceTypeDefinition; + interfaceDef.Name.Value.ShouldBe("TestInterface"); + interfaceDef.Description.Value.ShouldBe("Test interface"); + if (parseComments) + interfaceDef.Comment.Value.ShouldBe(" comment 12"); + interfaceDef.Fields.Count.ShouldBe(1); + interfaceDef.Fields[0].Name.Value.ShouldBe("name"); + interfaceDef.Fields[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("String"); + interfaceDef.Fields[0].Description.Value.ShouldBe("Object name"); + if (parseComments) + interfaceDef.Fields[0].Comment.Value.ShouldBe(" comment 14"); + + var unionDef = defs.Single(x => x is GraphQLUnionTypeDefinition) as GraphQLUnionTypeDefinition; + unionDef.Name.Value.ShouldBe("TestUnion"); + unionDef.Description.Value.ShouldBe("Test union"); + if (parseComments) + unionDef.Comment.Value.ShouldBe(" comment 16"); + unionDef.Types.Count.ShouldBe(2); + unionDef.Types[0].Name.Value.ShouldBe("Test1"); + unionDef.Types[1].Name.Value.ShouldBe("Test2"); + + var enumDef = defs.Single(x => x is GraphQLEnumTypeDefinition) as GraphQLEnumTypeDefinition; + enumDef.Name.Value.ShouldBe("Colors"); + enumDef.Description.Value.ShouldBe("Example enum"); + if (parseComments) + enumDef.Comment.Value.ShouldBe(" comment 18"); + enumDef.Values.Count.ShouldBe(2); + enumDef.Values[0].Name.Value.ShouldBe("RED"); + enumDef.Values[0].Description.Value.ShouldBe("Red"); + if (parseComments) + enumDef.Values[0].Comment.Value.ShouldBe(" comment 20"); + enumDef.Values[1].Name.Value.ShouldBe("BLUE"); + enumDef.Values[1].Description.Value.ShouldBe("Blue"); + if (parseComments) + enumDef.Values[1].Comment.Value.ShouldBe(" comment 22"); + + var inputDef = defs.Single(x => x is GraphQLInputObjectTypeDefinition) as GraphQLInputObjectTypeDefinition; + inputDef.Name.Value.ShouldBe("TestInputObject"); + inputDef.Description.Value.ShouldBe("This is an example input object\nLine two of the description"); + if (parseComments) + inputDef.Comment.Value.ShouldBe(" comment 24"); + inputDef.Fields.Count.ShouldBe(1); + inputDef.Fields[0].Name.Value.ShouldBe("Value"); + inputDef.Fields[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("JSON"); + inputDef.Fields[0].Description.Value.ShouldBe("The value of the input object\n (any JSON value is accepted)"); + if (parseComments) + inputDef.Fields[0].Comment.Value.ShouldBe(" comment 26"); + + var directiveDef = defs.Single(x => x is GraphQLDirectiveDefinition) as GraphQLDirectiveDefinition; + directiveDef.Name.Value.ShouldBe("TestDirective"); + directiveDef.Description.Value.ShouldBe("Test directive"); + if (parseComments) + directiveDef.Comment.Value.ShouldBe(" comment 28"); + directiveDef.Arguments.Count.ShouldBe(1); + directiveDef.Arguments[0].Name.Value.ShouldBe("Value"); + directiveDef.Arguments[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("Int"); + directiveDef.Arguments[0].Description.Value.ShouldBe("Example"); + if (parseComments) + directiveDef.Arguments[0].Comment.Value.ShouldBe(" comment 30"); + } + + [Theory] + [InlineData(IgnoreOptions.None)] + [InlineData(IgnoreOptions.Comments)] + [InlineData(IgnoreOptions.Locations)] + [InlineData(IgnoreOptions.All)] + public void Descriptions_WithComments_Should_Read_Correctly_3(IgnoreOptions options) + { + using var document = @" +# comment 0 +""Super schema"" +schema { + query: String +} + +# comment 1 +""A JSON scalar"" +scalar JSON + +# comment 3 +"""""" +Human type +"""""" +type Human { + # comment 5 + """""" + Name of human + """""" + name: String + + # comment 7 + ""Test"" + test( + # comment 9 + ""desc"" + arg: Int + ): Int +} + +# comment 11 +""Test interface"" +interface TestInterface { + # comment 13 + ""Object name"" + name: String +} + +# comment 15 +"""""" +Test union +"""""" +union TestUnion = Test1 | Test2 + +# comment 17 +""Example enum"" +enum Colors { + # comment 19 + ""Red"" + RED + # comment 21 + ""Blue"" + BLUE +} + +# comment 23 +"""""" +This is an example input object +Line two of the description +"""""" +input TestInputObject { + # comment 25 + """""" + The value of the input object + (any JSON value is accepted) + """""" + Value: JSON +} + +# comment 27 +""Test directive"" +directive @TestDirective ( + # comment 29 + ""Example"" + Value: Int +) on QUERY +".Parse(new ParserOptions { Ignore = options }); + var defs = document.Definitions; + defs.Count.ShouldBe(8); + var parseComments = !options.HasFlag(IgnoreOptions.Comments); + + var schemaDef = defs.Single(x => x is GraphQLSchemaDefinition) as GraphQLSchemaDefinition; + schemaDef.Description.Value.ShouldBe("Super schema"); + if (parseComments) + schemaDef.Comment.Value.ShouldBe(" comment 0"); + + var scalarDef = defs.Single(x => x is GraphQLScalarTypeDefinition) as GraphQLScalarTypeDefinition; + scalarDef.Name.Value.ShouldBe("JSON"); + scalarDef.Description.Value.ShouldBe("A JSON scalar"); + if (parseComments) + scalarDef.Comment.Value.ShouldBe(" comment 1"); + + var objectDef = defs.Single(x => x is GraphQLObjectTypeDefinition) as GraphQLObjectTypeDefinition; + objectDef.Name.Value.ShouldBe("Human"); + objectDef.Description.Value.ShouldBe("Human type"); + if (parseComments) + objectDef.Comment.Value.ShouldBe(" comment 3"); + objectDef.Fields.Count.ShouldBe(2); + objectDef.Fields[0].Name.Value.ShouldBe("name"); + objectDef.Fields[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("String"); + objectDef.Fields[0].Description.Value.ShouldBe("Name of human"); + if (parseComments) + objectDef.Fields[0].Comment.Value.ShouldBe(" comment 5"); + objectDef.Fields[1].Name.Value.ShouldBe("test"); + objectDef.Fields[1].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("Int"); + objectDef.Fields[1].Description.Value.ShouldBe("Test"); + if (parseComments) + objectDef.Fields[1].Comment.Value.ShouldBe(" comment 7"); + objectDef.Fields[1].Arguments.Count.ShouldBe(1); + objectDef.Fields[1].Arguments[0].Name.Value.ShouldBe("arg"); + objectDef.Fields[1].Arguments[0].Description.Value.ShouldBe("desc"); + objectDef.Fields[1].Arguments[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("Int"); + if (parseComments) + objectDef.Fields[1].Arguments[0].Comment.Value.ShouldBe(" comment 9"); + + var interfaceDef = defs.Single(x => x is GraphQLInterfaceTypeDefinition) as GraphQLInterfaceTypeDefinition; + interfaceDef.Name.Value.ShouldBe("TestInterface"); + interfaceDef.Description.Value.ShouldBe("Test interface"); + if (parseComments) + interfaceDef.Comment.Value.ShouldBe(" comment 11"); + interfaceDef.Fields.Count.ShouldBe(1); + interfaceDef.Fields[0].Name.Value.ShouldBe("name"); + interfaceDef.Fields[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("String"); + interfaceDef.Fields[0].Description.Value.ShouldBe("Object name"); + if (parseComments) + interfaceDef.Fields[0].Comment.Value.ShouldBe(" comment 13"); + + var unionDef = defs.Single(x => x is GraphQLUnionTypeDefinition) as GraphQLUnionTypeDefinition; + unionDef.Name.Value.ShouldBe("TestUnion"); + unionDef.Description.Value.ShouldBe("Test union"); + if (parseComments) + unionDef.Comment.Value.ShouldBe(" comment 15"); + unionDef.Types.Count.ShouldBe(2); + unionDef.Types[0].Name.Value.ShouldBe("Test1"); + unionDef.Types[1].Name.Value.ShouldBe("Test2"); + + var enumDef = defs.Single(x => x is GraphQLEnumTypeDefinition) as GraphQLEnumTypeDefinition; + enumDef.Name.Value.ShouldBe("Colors"); + enumDef.Description.Value.ShouldBe("Example enum"); + if (parseComments) + enumDef.Comment.Value.ShouldBe(" comment 17"); + enumDef.Values.Count.ShouldBe(2); + enumDef.Values[0].Name.Value.ShouldBe("RED"); + enumDef.Values[0].Description.Value.ShouldBe("Red"); + if (parseComments) + enumDef.Values[0].Comment.Value.ShouldBe(" comment 19"); + enumDef.Values[1].Name.Value.ShouldBe("BLUE"); + enumDef.Values[1].Description.Value.ShouldBe("Blue"); + if (parseComments) + enumDef.Values[1].Comment.Value.ShouldBe(" comment 21"); + + var inputDef = defs.Single(x => x is GraphQLInputObjectTypeDefinition) as GraphQLInputObjectTypeDefinition; + inputDef.Name.Value.ShouldBe("TestInputObject"); + inputDef.Description.Value.ShouldBe("This is an example input object\nLine two of the description"); + if (parseComments) + inputDef.Comment.Value.ShouldBe(" comment 23"); + inputDef.Fields.Count.ShouldBe(1); + inputDef.Fields[0].Name.Value.ShouldBe("Value"); + inputDef.Fields[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("JSON"); + inputDef.Fields[0].Description.Value.ShouldBe("The value of the input object\n (any JSON value is accepted)"); + if (parseComments) + inputDef.Fields[0].Comment.Value.ShouldBe(" comment 25"); + + var directiveDef = defs.Single(x => x is GraphQLDirectiveDefinition) as GraphQLDirectiveDefinition; + directiveDef.Name.Value.ShouldBe("TestDirective"); + directiveDef.Description.Value.ShouldBe("Test directive"); + if (parseComments) + directiveDef.Comment.Value.ShouldBe(" comment 27"); + directiveDef.Arguments.Count.ShouldBe(1); + directiveDef.Arguments[0].Name.Value.ShouldBe("Value"); + directiveDef.Arguments[0].Type.ShouldBeAssignableTo().Name.Value.ShouldBe("Int"); + directiveDef.Arguments[0].Description.Value.ShouldBe("Example"); + if (parseComments) + directiveDef.Arguments[0].Comment.Value.ShouldBe(" comment 29"); + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `field` last assigned on line 188 could be null and is dereferenced at line 189, column 9. + +### Severity: +ERROR + +### Procedure: +Void ParserTests.Comments_on_FragmentSpread_Should_Read_Correctly(IgnoreOptions) + +### File: +src/GraphQLParser.Tests/ParserTests.cs + +### Key: +ParserTests.cs|Comments_on_FragmentSpread_Should_Read_Correctly|NULL_DEREFERENCE + +### Node Key: +5f6bc9a45b87a0bd98569135266c4d99 + +### Hash: +89fa621f365ea4b35db4798ff753004e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11101/instruction.md b/inferredbugs-11101/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3d15383b18493b00e0aadc557a31e621ff699855 --- /dev/null +++ b/inferredbugs-11101/instruction.md @@ -0,0 +1,383 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** brpc-java +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2019 Baidu, Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.baidu.brpc.client; + +import com.baidu.brpc.*; +import com.baidu.brpc.exceptions.RpcException; +import com.baidu.brpc.protocol.NamingOptions; +import com.baidu.brpc.protocol.Protocol; +import com.baidu.brpc.protocol.Request; +import com.baidu.brpc.protocol.Response; +import com.baidu.brpc.protocol.nshead.NSHead; +import com.baidu.brpc.protocol.nshead.NSHeadMeta; +import com.baidu.brpc.protocol.push.SPHead; +import com.baidu.brpc.protocol.push.ServerPushProtocol; +import com.baidu.brpc.utils.ProtobufUtils; +import lombok.extern.slf4j.Slf4j; +import net.sf.cglib.proxy.Enhancer; +import net.sf.cglib.proxy.MethodInterceptor; +import net.sf.cglib.proxy.MethodProxy; + +import java.lang.reflect.Method; +import java.util.*; +import java.util.concurrent.Future; + +/** + * Created by huwenwei on 2017/4/25. + */ +@SuppressWarnings("unchecked") +@Slf4j +public class BrpcProxy implements MethodInterceptor { + + private static final Set notProxyMethodSet = new HashSet(); + + static { + notProxyMethodSet.add("getClass"); + notProxyMethodSet.add("hashCode"); + notProxyMethodSet.add("equals"); + notProxyMethodSet.add("clone"); + notProxyMethodSet.add("toString"); + notProxyMethodSet.add("notify"); + notProxyMethodSet.add("notifyAll"); + notProxyMethodSet.add("wait"); + notProxyMethodSet.add("finalize"); + } + + private RpcClient rpcClient; + + private Map rpcMethodMap = new HashMap(); + + /** + * 初始化时提前解析好method信息,在rpc交互时会更快。 + * + * @param rpcClient rpc client对象 + * @param clazz rpc接口类 + */ + protected BrpcProxy(RpcClient rpcClient, Class clazz) { + this.rpcClient = rpcClient; + Method[] methods = clazz.getMethods(); + for (Method method : methods) { + if (notProxyMethodSet.contains(method.getName())) { + log.debug("{}:{} does not need to proxy", + method.getDeclaringClass().getName(), method.getName()); + continue; + } + + Class[] parameterTypes = method.getParameterTypes(); + int paramLength = parameterTypes.length; + if (paramLength >= 1 + && Future.class.isAssignableFrom(method.getReturnType()) + && !RpcCallback.class.isAssignableFrom(parameterTypes[paramLength - 1])) { + throw new IllegalArgumentException("returnType is Future, but last argument is not RpcCallback"); + } + + Method syncMethod = method; + if (paramLength > 1) { + int startIndex = 0; + int endIndex = paramLength - 1; + // has callback, async rpc + if (RpcCallback.class.isAssignableFrom(parameterTypes[paramLength - 1])) { + endIndex--; + paramLength--; + } + Class[] actualParameterTypes = new Class[paramLength]; + for (int i = 0; startIndex <= endIndex; i++) { + actualParameterTypes[i] = parameterTypes[startIndex++]; + } + try { + syncMethod = method.getDeclaringClass().getMethod( + method.getName(), actualParameterTypes); + } catch (NoSuchMethodException ex) { + throw new IllegalArgumentException("can not find sync method:" + method.getName()); + } + } + + RpcMethodInfo methodInfo; + ProtobufUtils.MessageType messageType = ProtobufUtils.getMessageType(syncMethod); + if (messageType == ProtobufUtils.MessageType.PROTOBUF) { + methodInfo = new ProtobufRpcMethodInfo(syncMethod); + } else if (messageType == ProtobufUtils.MessageType.JPROTOBUF) { + methodInfo = new JprotobufRpcMethodInfo(syncMethod); + } else { + methodInfo = new RpcMethodInfo(syncMethod); + } + + rpcMethodMap.put(method.getName(), methodInfo); + log.debug("client serviceName={}, methodName={}", + method.getDeclaringClass().getName(), method.getName()); + } + } + + public static T getProxy(RpcClient rpcClient, Class clazz) { + return getProxy(rpcClient, clazz, null); + } + + public static T getProxy(RpcClient rpcClient, Class clazz, NamingOptions namingOptions) { + rpcClient.setServiceInterface(clazz, namingOptions); + Enhancer en = new Enhancer(); + en.setSuperclass(clazz); + en.setCallback(new BrpcProxy(rpcClient, clazz)); + return (T) en.create(); + } + + /** + * 调用用户接口时候, 实际执行的方法 + * + * @param obj + * @param method + * @param args + * @param proxy + * + * @return + * + * @throws Throwable + */ + @Override + public Object intercept(Object obj, Method method, Object[] args, + MethodProxy proxy) throws Throwable { + String methodName = method.getName(); + RpcMethodInfo rpcMethodInfo = rpcMethodMap.get(methodName); + if (rpcMethodInfo == null) { + log.debug("{}:{} does not need to proxy", + method.getDeclaringClass().getName(), methodName); + return proxy.invokeSuper(obj, args); + } + Request request = null; + int readTimeout = 10 * 1000; + int writeTimeout = 10 * 1000; + + Protocol protocol = rpcClient.getCommunicationOptions().getProtocol(); + request = protocol.createRequest(); + if (protocol instanceof ServerPushProtocol) { + SPHead spHead = ((ServerPushProtocol) protocol).createSPHead(); + spHead.setType(SPHead.TYPE_REQUEST); + request.setSpHead(spHead); + } + + request.setCompressType(rpcClient.getRpcClientOptions().getCompressType().getNumber()); + request.setSubscribeInfo(rpcClient.getNamingServiceProcessor().getSubscribeInfo()); + readTimeout = rpcClient.getRpcClientOptions().getReadTimeoutMillis(); + writeTimeout = rpcClient.getRpcClientOptions().getWriteTimeoutMillis(); + + try { + request.setTarget(obj); + request.setRpcMethodInfo(rpcMethodInfo); + request.setTargetMethod(rpcMethodInfo.getMethod()); + request.setServiceName(rpcMethodInfo.getServiceName()); + request.setMethodName(rpcMethodInfo.getMethodName()); + NSHeadMeta nsHeadMeta = rpcMethodInfo.getNsHeadMeta(); + NSHead nsHead = nsHeadMeta == null ? new NSHead() : new NSHead(0, nsHeadMeta.id(), nsHeadMeta.version(), + nsHeadMeta.provider(), 0); + request.setNsHead(nsHead); + + // parse request params + RpcCallback callback = null; + int argLength = args.length; + if (argLength > 1) { + int startIndex = 0; + int endIndex = argLength - 1; + // 异步调用 + if (args[endIndex] instanceof RpcCallback) { + callback = (RpcCallback) args[endIndex]; + endIndex -= 1; + argLength -= 1; + } + + if (argLength <= 0) { + throw new RpcException(RpcException.UNKNOWN_EXCEPTION, "invalid params"); + } + + Object[] sendArgs = new Object[argLength]; + for (int i = 0; startIndex <= endIndex; i++) { + sendArgs[i] = args[startIndex++]; + } + request.setArgs(sendArgs); + request.setCallback(callback); + } else { + // sync call + request.setArgs(args); + } + + if (RpcContext.isSet()) { + RpcContext rpcContext = RpcContext.getContext(); + // attachment + if (rpcContext.getRequestKvAttachment() != null) { + request.setKvAttachment(rpcContext.getRequestKvAttachment()); + } + if (rpcContext.getRequestBinaryAttachment() != null) { + request.setBinaryAttachment(rpcContext.getRequestBinaryAttachment()); + } + if (rpcContext.getLogId() != null) { + request.getNsHead().logId = rpcContext.getLogId(); + request.setLogId(rpcContext.getLogId()); + } + if (rpcContext.getServiceTag() != null) { + request.setServiceTag(rpcContext.getServiceTag()); + } + if (rpcContext.getReadTimeoutMillis() != null) { + request.setReadTimeoutMillis(rpcContext.getReadTimeoutMillis()); + } + if (rpcContext.getWriteTimeoutMillis() != null) { + request.setWriteTimeoutMillis(rpcContext.getWriteTimeoutMillis()); + } + rpcContext.reset(); + } + + if (request.getReadTimeoutMillis() == null) { + request.setReadTimeoutMillis(readTimeout); + } + if (request.getWriteTimeoutMillis() == null) { + request.setWriteTimeoutMillis(writeTimeout); + } + + try { + Response response = executeWithRetry(request); + if (request.getCallback() != null) { + return response.getRpcFuture(); + } else { + return response.getResult(); + } + } catch (RpcException ex) { + log.error("exception :", ex); + throw ex; + } + } finally { + if (request != null) { + // release send buffer because we retain send buffer when send request. + request.release(); + } + } + } + + public Response executeWithRetry(Request request) { + Response response = null; + RpcException exception = null; + int currentTryTimes = 0; + int maxTryTimes = rpcClient.getRpcClientOptions().getMaxTryTimes(); + while (currentTryTimes < maxTryTimes) { + try { + // if it is a retry request, add the last selected instance to request, + // so that load balance strategy can exclude the selected instance. + // if it is the initial request, not init HashSet, so it is more fast. + // therefore, it need LoadBalanceStrategy to judge if selectInstances is null. + if (currentTryTimes > 0) { + if (request.getChannel() != null) { + if (request.getSelectedInstances() == null) { + request.setSelectedInstances(new HashSet(maxTryTimes - 1)); + } + request.getSelectedInstances().add(request.getCommunicationClient()); + } + } + response = rpcClient.execute(request, rpcClient.getCommunicationOptions()); + break; + } catch (RpcException ex) { + exception = ex; + if (exception.getCode() == RpcException.INTERCEPT_EXCEPTION) { + break; + } + } finally { + currentTryTimes++; + } + } + + if (response.getResult() == null && response.getRpcFuture() == null) { + if (exception == null) { + exception = new RpcException(RpcException.UNKNOWN_EXCEPTION, "unknown error"); + } + throw exception; + } + return response; + } + + public Map getRpcMethodMap() { + return rpcMethodMap; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `response` last assigned on line 267 could be null and is dereferenced at line 297. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Response BrpcProxy.executeWithRetry(Request) + +### Procedure Id: +com.baidu.brpc.client.BrpcProxy.executeWithRetry(com.baidu.brpc.protocol.Request):com.baidu.brpc.pro.90a4069c0c0612d9510609c71df0bbb9 + +### File: +brpc-java-governance/src/main/java/com/baidu/brpc/client/BrpcProxy.java + +### Key: +BrpcProxy.java|executeWithRetry|NULL_DEREFERENCE + +### Node Key: +5890b2fe24d6c2716b9c7c0ba8964dea + +### Hash: +3caaab7335b031f5dd44a3d64b0bb022 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11106/instruction.md b/inferredbugs-11106/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e3043d4e3cd6a94aeed4feb6ee920810741281cc --- /dev/null +++ b/inferredbugs-11106/instruction.md @@ -0,0 +1,273 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** itext7 +**Bug ID:** 32 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.itextpdf.model; + +import com.itextpdf.basics.image.ImageFactory; +import com.itextpdf.core.pdf.PdfDocument; +import com.itextpdf.core.pdf.PdfWriter; +import com.itextpdf.core.pdf.xobject.PdfImageXObject; +import com.itextpdf.core.testutils.CompareTool; +import com.itextpdf.model.element.Image; +import com.itextpdf.model.element.Paragraph; +import com.itextpdf.model.element.Text; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.*; + +public class ImageTest { + + static final public String sourceFolder = "./src/test/resources/com/itextpdf/model/ImageTest/"; + static final public String destinationFolder = "./target/test/com/itextpdf/model/ImageTest/"; + + @BeforeClass + static public void beforeClass() { + new File(destinationFolder).mkdirs(); + } + + @Test + public void imageTest01() throws IOException, InterruptedException { + + String outFileName = destinationFolder + "imageTest01.pdf"; + String cmpFileName = sourceFolder + "cmp_imageTest01.pdf"; + + FileOutputStream file = new FileOutputStream(outFileName); + + PdfWriter writer = new PdfWriter(file); + + PdfDocument pdfDoc = new PdfDocument(writer); + + Document doc = new Document(pdfDoc); + + PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL())); + Image image = new Image(xObject, 100); + + doc.add(new Paragraph(new Text("First Line"))); + Paragraph p = new Paragraph(); + p.add(image); + doc.add(p); + doc.add(new Paragraph(new Text("Second Line"))); + + doc.close(); + + Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); + } + + @Test + public void imageTest02() throws IOException, InterruptedException { + + String outFileName = destinationFolder + "imageTest02.pdf"; + String cmpFileName = sourceFolder + "cmp_imageTest02.pdf"; + + FileOutputStream file = new FileOutputStream(outFileName); + + PdfWriter writer = new PdfWriter(file); + + PdfDocument pdfDoc = new PdfDocument(writer); + + Document doc = new Document(pdfDoc); + + PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL())); + Image image = new Image(xObject, 100); + + Paragraph p = new Paragraph(); + p.add(new Text("before image")); + p.add(image); + p.add(new Text("after image")); + doc.add(p); + + doc.close(); + + Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); + } + + @Test + public void imageTest03() throws IOException, InterruptedException { + + String outFileName = destinationFolder + "imageTest03.pdf"; + String cmpFileName = sourceFolder + "cmp_imageTest03.pdf"; + + FileOutputStream file = new FileOutputStream(outFileName); + + PdfWriter writer = new PdfWriter(file); + + PdfDocument pdfDoc = new PdfDocument(writer); + + Document doc = new Document(pdfDoc); + + PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL())); + Image image = new Image(xObject, 100); + + doc.add(new Paragraph(new Text("First Line"))); + Paragraph p = new Paragraph(); + p.add(image); + image.setRotationAngle(Math.PI / 6); + doc.add(p); + doc.add(new Paragraph(new Text("Second Line"))); + + doc.close(); + + Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); + } + + @Test + public void imageTest04() throws IOException, InterruptedException { + + String outFileName = destinationFolder + "imageTest04.pdf"; + String cmpFileName = sourceFolder + "cmp_imageTest04.pdf"; + + FileOutputStream file = new FileOutputStream(outFileName); + + PdfWriter writer = new PdfWriter(file); + + PdfDocument pdfDoc = new PdfDocument(writer); + + Document doc = new Document(pdfDoc); + + PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL())); + Image image = new Image(xObject, 100); + + Paragraph p = new Paragraph(); + p.add(new Text("before image")); + p.add(image); + image.setRotationAngle(Math.PI / 6); + p.add(new Text("after image")); + doc.add(p); + + doc.close(); + + Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); + } + + @Test + public void imageTest05() throws IOException, InterruptedException { + + String outFileName = destinationFolder + "imageTest05.pdf"; + String cmpFileName = sourceFolder + "cmp_imageTest05.pdf"; + + FileOutputStream file = new FileOutputStream(outFileName); + + PdfWriter writer = new PdfWriter(file); + + PdfDocument pdfDoc = new PdfDocument(writer); + + Document doc = new Document(pdfDoc); + + PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL())); + Image image = new Image(xObject, 100); + + doc.add(new Paragraph(new Text("First Line"))); + Paragraph p = new Paragraph(); + p.add(image); + image.scale(1, 0.5f); + doc.add(p); + doc.add(new Paragraph(new Text("Second Line"))); + + doc.close(); + + Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); + } + + @Test + public void imageTest06() throws IOException, InterruptedException { + + String outFileName = destinationFolder + "imageTest06.pdf"; + String cmpFileName = sourceFolder + "cmp_imageTest06.pdf"; + + FileOutputStream file = new FileOutputStream(outFileName); + + PdfWriter writer = new PdfWriter(file); + + PdfDocument pdfDoc = new PdfDocument(writer); + + Document doc = new Document(pdfDoc); + + PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL())); + Image image = new Image(xObject, 100); + + doc.add(new Paragraph(new Text("First Line"))); + Paragraph p = new Paragraph(); + p.add(image); + image.setTranslationDistance(100, -100); + doc.add(p); + doc.add(new Paragraph(new Text("Second Line"))); + + doc.close(); + + Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.itextpdf.core.pdf.PdfWriter` acquired by call to `new()` at line 91 is not released after line 110. +**Note**: potential exception at line 97 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ImageTest.imageTest03() + +### Procedure Id: +com.itextpdf.model.ImageTest.imageTest03():void.1981dacbed0b589ab20de937c26b1d3a + +### File: +model/src/test/java/com/itextpdf/model/ImageTest.java + +### Key: +ImageTest.java|imageTest03|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +0cb78925d17909e5a2c8b4f25e4f3d86 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11108/instruction.md b/inferredbugs-11108/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..272d16ae1694910e8405d84985987bc7b9256510 --- /dev/null +++ b/inferredbugs-11108/instruction.md @@ -0,0 +1,273 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** itext7 +**Bug ID:** 34 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.itextpdf.model; + +import com.itextpdf.basics.image.ImageFactory; +import com.itextpdf.core.pdf.PdfDocument; +import com.itextpdf.core.pdf.PdfWriter; +import com.itextpdf.core.pdf.xobject.PdfImageXObject; +import com.itextpdf.core.testutils.CompareTool; +import com.itextpdf.model.element.Image; +import com.itextpdf.model.element.Paragraph; +import com.itextpdf.model.element.Text; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.*; + +public class ImageTest { + + static final public String sourceFolder = "./src/test/resources/com/itextpdf/model/ImageTest/"; + static final public String destinationFolder = "./target/test/com/itextpdf/model/ImageTest/"; + + @BeforeClass + static public void beforeClass() { + new File(destinationFolder).mkdirs(); + } + + @Test + public void imageTest01() throws IOException, InterruptedException { + + String outFileName = destinationFolder + "imageTest01.pdf"; + String cmpFileName = sourceFolder + "cmp_imageTest01.pdf"; + + FileOutputStream file = new FileOutputStream(outFileName); + + PdfWriter writer = new PdfWriter(file); + + PdfDocument pdfDoc = new PdfDocument(writer); + + Document doc = new Document(pdfDoc); + + PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL())); + Image image = new Image(xObject, 100); + + doc.add(new Paragraph(new Text("First Line"))); + Paragraph p = new Paragraph(); + p.add(image); + doc.add(p); + doc.add(new Paragraph(new Text("Second Line"))); + + doc.close(); + + Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); + } + + @Test + public void imageTest02() throws IOException, InterruptedException { + + String outFileName = destinationFolder + "imageTest02.pdf"; + String cmpFileName = sourceFolder + "cmp_imageTest02.pdf"; + + FileOutputStream file = new FileOutputStream(outFileName); + + PdfWriter writer = new PdfWriter(file); + + PdfDocument pdfDoc = new PdfDocument(writer); + + Document doc = new Document(pdfDoc); + + PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL())); + Image image = new Image(xObject, 100); + + Paragraph p = new Paragraph(); + p.add(new Text("before image")); + p.add(image); + p.add(new Text("after image")); + doc.add(p); + + doc.close(); + + Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); + } + + @Test + public void imageTest03() throws IOException, InterruptedException { + + String outFileName = destinationFolder + "imageTest03.pdf"; + String cmpFileName = sourceFolder + "cmp_imageTest03.pdf"; + + FileOutputStream file = new FileOutputStream(outFileName); + + PdfWriter writer = new PdfWriter(file); + + PdfDocument pdfDoc = new PdfDocument(writer); + + Document doc = new Document(pdfDoc); + + PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL())); + Image image = new Image(xObject, 100); + + doc.add(new Paragraph(new Text("First Line"))); + Paragraph p = new Paragraph(); + p.add(image); + image.setRotationAngle(Math.PI / 6); + doc.add(p); + doc.add(new Paragraph(new Text("Second Line"))); + + doc.close(); + + Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); + } + + @Test + public void imageTest04() throws IOException, InterruptedException { + + String outFileName = destinationFolder + "imageTest04.pdf"; + String cmpFileName = sourceFolder + "cmp_imageTest04.pdf"; + + FileOutputStream file = new FileOutputStream(outFileName); + + PdfWriter writer = new PdfWriter(file); + + PdfDocument pdfDoc = new PdfDocument(writer); + + Document doc = new Document(pdfDoc); + + PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL())); + Image image = new Image(xObject, 100); + + Paragraph p = new Paragraph(); + p.add(new Text("before image")); + p.add(image); + image.setRotationAngle(Math.PI / 6); + p.add(new Text("after image")); + doc.add(p); + + doc.close(); + + Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); + } + + @Test + public void imageTest05() throws IOException, InterruptedException { + + String outFileName = destinationFolder + "imageTest05.pdf"; + String cmpFileName = sourceFolder + "cmp_imageTest05.pdf"; + + FileOutputStream file = new FileOutputStream(outFileName); + + PdfWriter writer = new PdfWriter(file); + + PdfDocument pdfDoc = new PdfDocument(writer); + + Document doc = new Document(pdfDoc); + + PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL())); + Image image = new Image(xObject, 100); + + doc.add(new Paragraph(new Text("First Line"))); + Paragraph p = new Paragraph(); + p.add(image); + image.scale(1, 0.5f); + doc.add(p); + doc.add(new Paragraph(new Text("Second Line"))); + + doc.close(); + + Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); + } + + @Test + public void imageTest06() throws IOException, InterruptedException { + + String outFileName = destinationFolder + "imageTest06.pdf"; + String cmpFileName = sourceFolder + "cmp_imageTest06.pdf"; + + FileOutputStream file = new FileOutputStream(outFileName); + + PdfWriter writer = new PdfWriter(file); + + PdfDocument pdfDoc = new PdfDocument(writer); + + Document doc = new Document(pdfDoc); + + PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL())); + Image image = new Image(xObject, 100); + + doc.add(new Paragraph(new Text("First Line"))); + Paragraph p = new Paragraph(); + p.add(image); + image.setTranslationDistance(100, -100); + doc.add(p); + doc.add(new Paragraph(new Text("Second Line"))); + + doc.close(); + + Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.itextpdf.core.pdf.PdfWriter` acquired by call to `new()` at line 149 is not released after line 168. +**Note**: potential exception at line 155 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ImageTest.imageTest05() + +### Procedure Id: +com.itextpdf.model.ImageTest.imageTest05():void.85d97be0739b2ee6cec8243879f2ae23 + +### File: +model/src/test/java/com/itextpdf/model/ImageTest.java + +### Key: +ImageTest.java|imageTest05|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +8bfcc18f6d096c949749d23f3e698f34 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11130/instruction.md b/inferredbugs-11130/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..69060bdf72aaaae2ead63ede127301f9a1ffcc68 --- /dev/null +++ b/inferredbugs-11130/instruction.md @@ -0,0 +1,285 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** itext7 +**Bug ID:** 30 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.itextpdf.model.renderer; + +import com.itextpdf.basics.geom.AffineTransform; +import com.itextpdf.basics.geom.Point2D; +import com.itextpdf.canvas.PdfCanvas; +import com.itextpdf.core.geom.Rectangle; +import com.itextpdf.core.pdf.PdfDocument; +import com.itextpdf.core.pdf.PdfName; +import com.itextpdf.core.pdf.xobject.PdfFormXObject; +import com.itextpdf.core.pdf.xobject.PdfImageXObject; +import com.itextpdf.core.pdf.xobject.PdfXObject; +import com.itextpdf.model.Property; +import com.itextpdf.model.element.Image; +import com.itextpdf.model.layout.LayoutArea; +import com.itextpdf.model.layout.LayoutContext; +import com.itextpdf.model.layout.LayoutPosition; +import com.itextpdf.model.layout.LayoutResult; + +public class ImageRenderer extends AbstractRenderer { + + float height; + Float width; + Float fixedXPosition; + Float fixedYPosition; + float pivotY; + float imageWidth; + float imageHeight; + + float[] matrix = new float[6]; + + public ImageRenderer(Image image) { + super(image); + } + + @Override + public LayoutResult layout(LayoutContext layoutContext) { + LayoutArea area = layoutContext.getArea(); + Rectangle layoutBox = area.getBBox(); + occupiedArea = new LayoutArea(area.getPageNumber(), new Rectangle(layoutBox.getX(), layoutBox.getY() + layoutBox.getHeight(), 0, 0)); + + width = getPropertyAsFloat(Property.WIDTH); + Float angle = getPropertyAsFloat(Property.IMAGE_ROTATION_ANGLE); + + PdfXObject xObject = ((Image) (getModelElement())).getXObject(); + if (xObject instanceof PdfImageXObject) { + imageWidth = ((PdfImageXObject)xObject).getWidth(); + imageHeight = ((PdfImageXObject)xObject).getHeight(); + } else { + imageWidth = xObject.getPdfObject().getAsArray(PdfName.BBox).getAsFloat(2); + imageHeight = xObject.getPdfObject().getAsArray(PdfName.BBox).getAsFloat(3); + } + + width = width == null ? imageWidth : width; + height = width / imageWidth * imageHeight; + + fixedXPosition = getPropertyAsFloat(Property.X); + fixedYPosition = getPropertyAsFloat(Property.Y); + + Float horizontalScaling = getPropertyAsFloat(Property.HORIZONTAL_SCALING); + Float verticalScaling = getPropertyAsFloat(Property.VERTICAL_SCALING); + + AffineTransform t = new AffineTransform(); + + if (xObject instanceof PdfFormXObject && width != imageWidth) { + horizontalScaling *= width / imageWidth; + verticalScaling *= height / imageHeight; + } + + if (horizontalScaling != 1) { + if (xObject instanceof PdfFormXObject) { + t.scale(horizontalScaling, 1); + } + width *= horizontalScaling; + } + if (verticalScaling != 1) { + if (xObject instanceof PdfFormXObject) { + t.scale(1, verticalScaling); + } + height *= verticalScaling; + } + + float imageItselfScaledWidth = width; + float imageItselfScaledHeight = height; + + if (angle != null) { + t.rotate(angle); + adjustPositionAfterRotation(angle); + } + + getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight); + + if (width > layoutBox.getWidth()){ + return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this); + } + if (height > layoutBox.getHeight()){ + return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this); + } + + occupiedArea.getBBox().moveDown(height); + occupiedArea.getBBox().setHeight(height); + occupiedArea.getBBox().setWidth(width); + + Float mx = getProperty(Property.X_DISTANCE); + Float my = getProperty(Property.Y_DISTANCE); + if (mx != null && my != null) { + translateImage(mx, my, t); + getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight); + } + + if (fixedXPosition != null && fixedYPosition != null) { + occupiedArea.getBBox().setWidth(0); + occupiedArea.getBBox().setHeight(0); + } + + return new LayoutResult(LayoutResult.FULL, occupiedArea, null, null); + } + + private void getMatrix(AffineTransform t, float imageItselfScaledWidth, float imageItselfScaledHeight) { + t.getMatrix(matrix); + PdfXObject xObject = ((Image) (getModelElement())).getXObject(); + if (xObject instanceof PdfImageXObject) { + matrix[0] *= imageItselfScaledWidth; + matrix[1] *= imageItselfScaledWidth; + matrix[2] *= imageItselfScaledHeight; + matrix[3] *= imageItselfScaledHeight; + } + } + + @Override + public void draw(PdfDocument document, PdfCanvas canvas) { + super.draw(document, canvas); + + int position = getPropertyAsInteger(Property.POSITION); + if (position == LayoutPosition.RELATIVE) { + applyAbsolutePositioningTranslation(false); + } + + if (fixedYPosition == null) { + fixedYPosition = occupiedArea.getBBox().getY() + pivotY; + } + if (fixedXPosition == null) { + fixedXPosition = occupiedArea.getBBox().getX(); + } + + canvas.addXObject(((Image) (getModelElement())).getXObject(), matrix[0], matrix[1], matrix[2], matrix[3], + fixedXPosition, fixedYPosition); + + if (position == LayoutPosition.RELATIVE) { + applyAbsolutePositioningTranslation(true); + } + } + + protected ImageRenderer autoScale(LayoutArea area) { + if (width > area.getBBox().getWidth()) { + setProperty(Property.HEIGHT, area.getBBox().getWidth() / width * imageHeight); + setProperty(Property.WIDTH, area.getBBox().getWidth()); + } + + return this; + } + + private void adjustPositionAfterRotation(float angle) { + AffineTransform t = AffineTransform.getRotateInstance(angle); + Point2D p00 = t.transform(new Point2D.Float(0, 0), new Point2D.Float()); + Point2D p01 = t.transform(new Point2D.Float(0, height), new Point2D.Float()); + Point2D p10 = t.transform(new Point2D.Float(width, 0), new Point2D.Float()); + Point2D p11 = t.transform(new Point2D.Float(width, height), new Point2D.Float()); + + double[] xValues = {p01.getX(), p10.getX(), p11.getX()}; + double[] yValues = {p01.getY(), p10.getY(), p11.getY()}; + + double minX = p00.getX(); + double minY = p00.getY(); + double maxX = minX; + double maxY = minY; + + for (double x : xValues) { + minX = Math.min(minX, x); + maxX = Math.max(maxX, x); + } + for (double y : yValues) { + minY = Math.min(minY, y); + maxY = Math.max(maxY, y); + } + + pivotY = (float) (p00.getY() - minY); + + height = (float) (maxY - minY); + width = (float) (maxX - minX); + + if (occupiedArea.getBBox().getX() > minX) { + occupiedArea.getBBox().moveRight((float) -minX); + if (fixedXPosition != null) { + fixedXPosition -= (float)minX; + } + } + } + + private void translateImage(float xDistance, float yDistance, AffineTransform t) { + t.translate(xDistance, yDistance); + t.getMatrix(matrix); + if (fixedXPosition == null) { + fixedXPosition = occupiedArea.getBBox().getX(); + } + if (fixedYPosition == null) { + fixedYPosition = occupiedArea.getBBox().getY() + height; + } + fixedXPosition += t.getTranslateX(); + fixedYPosition += t.getTranslateY(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `xObject.getPdfObject().getAsArray(com.itextpdf.core.pdf.PdfName.BBox)` could be null and is dereferenced at line 50. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +LayoutResult ImageRenderer.layout(LayoutContext) + +### Procedure Id: +com.itextpdf.model.renderer.ImageRenderer.layout(com.itextpdf.model.layout.LayoutContext):com.itextp.a23334d42ab372a943e6a3c38edf5a76 + +### File: +model/src/main/java/com/itextpdf/model/renderer/ImageRenderer.java + +### Key: +ImageRenderer.java|layout|NULL_DEREFERENCE + +### Node Key: +34bcb0bafefd2b276ffa1330385c5b6d + +### Hash: +39731098b1df3a7b36d5259a48866d12 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11137/instruction.md b/inferredbugs-11137/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0667e57f35764a0e0dc3142614909f049a1893e5 --- /dev/null +++ b/inferredbugs-11137/instruction.md @@ -0,0 +1,112 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** itext7 +**Bug ID:** 12 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.itextpdf.core.pdf.navigation; + +import com.itextpdf.basics.PdfException; +import com.itextpdf.core.pdf.*; + +import java.util.HashMap; + +public class PdfNamedDestination extends PdfDestination { + + public PdfNamedDestination(String name) { + this(new PdfName(name)); + } + + public PdfNamedDestination(PdfName pdfObject) { + super(pdfObject); + } + + public PdfNamedDestination(PdfName pdfObject, PdfDocument pdfDocument) throws PdfException { + super(pdfObject, pdfDocument); + } + + @Override + public PdfObject getDestinationPage(final HashMap names) throws PdfException { + PdfArray array = (PdfArray) names.get(getPdfObject()); + + return array.get(0, false); + } + + @Override + public PdfDestination replaceNamedDestination(final HashMap names){ + + PdfArray array = (PdfArray) names.get(getPdfObject()); + if (array != null){ + return PdfDestination.makeDestination(array); + } + return null; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `array` last assigned on line 24 could be null and is dereferenced at line 26. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +PdfObject PdfNamedDestination.getDestinationPage(HashMap) + +### Procedure Id: +com.itextpdf.core.pdf.navigation.PdfNamedDestination.getDestinationPage(java.util.HashMap):com.itext.aef51e2c889b516be536da82d2c2fcb7 + +### File: +core/src/main/java/com/itextpdf/core/pdf/navigation/PdfNamedDestination.java + +### Key: +PdfNamedDestination.java|getDestinationPage|NULL_DEREFERENCE + +### Node Key: +3534744d3537de8ddf14c788351b1bdd + +### Hash: +bf7ee62afdfe4501424415e4fc454bf5 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11139/instruction.md b/inferredbugs-11139/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43b9d0dfda4c216f8efbefc091339d2470f51075 --- /dev/null +++ b/inferredbugs-11139/instruction.md @@ -0,0 +1,112 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** itext7 +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.itextpdf.core.pdf.navigation; + +import com.itextpdf.basics.PdfException; +import com.itextpdf.core.pdf.*; + +import java.util.HashMap; + +public class PdfStringDestination extends PdfDestination { + + public PdfStringDestination(String string) { + this(new PdfString(string)); + } + + public PdfStringDestination(PdfString pdfObject) { + super(pdfObject); + } + + public PdfStringDestination(PdfString pdfObject, PdfDocument pdfDocument) throws PdfException { + super(pdfObject, pdfDocument); + } + + @Override + public PdfObject getDestinationPage(HashMap names) throws PdfException { + PdfArray array = (PdfArray) names.get(getPdfObject().toUnicodeString()); + + return array.get(0, false); + } + + @Override + public PdfDestination replaceNamedDestination(final HashMap names) throws PdfException { + + PdfArray array = (PdfArray) names.get(getPdfObject().toUnicodeString()); + if (array != null){ + return PdfDestination.makeDestination(array); + } + return null; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `array` last assigned on line 24 could be null and is dereferenced at line 26. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +PdfObject PdfStringDestination.getDestinationPage(HashMap) + +### Procedure Id: +com.itextpdf.core.pdf.navigation.PdfStringDestination.getDestinationPage(java.util.HashMap):com.itex.440b2ff7d5601944ca1d3779c0c3257c + +### File: +core/src/main/java/com/itextpdf/core/pdf/navigation/PdfStringDestination.java + +### Key: +PdfStringDestination.java|getDestinationPage|NULL_DEREFERENCE + +### Node Key: +3534744d3537de8ddf14c788351b1bdd + +### Hash: +c97fc825d5c0ec8d80b656a2b858ee88 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11152/instruction.md b/inferredbugs-11152/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b8719904280b86fc035c74e04850675f97e9af80 --- /dev/null +++ b/inferredbugs-11152/instruction.md @@ -0,0 +1,136 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jeromq +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + Copyright (c) 2007-2014 Contributors as noted in the AUTHORS file + + This file is part of 0MQ. + + 0MQ 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. + + 0MQ 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 program. If not, see . +*/ + +package guide; + +import org.zeromq.ZMQ; + +// +// Reading from multiple sockets in Java +// This version uses a simple recv loop +// +public class msreader { + + public static void main (String[] args) throws Exception { + // Prepare our context and sockets + ZMQ.Context context = ZMQ.context(1); + + // Connect to task ventilator + ZMQ.Socket receiver = context.socket(ZMQ.PULL); + receiver.connect("tcp://localhost:5557"); + + // Connect to weather server + ZMQ.Socket subscriber = context.socket(ZMQ.SUB); + subscriber.connect("tcp://localhost:5556"); + subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET)); + + // Process messages from both sockets + // We prioritize traffic from the task ventilator + while (!Thread.currentThread ().isInterrupted ()) { + // Process any waiting tasks + byte[] task; + while((task = receiver.recv(ZMQ.DONTWAIT)) != null) { + System.out.println("process task"); + } + // Process any waiting weather updates + byte[] update; + while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) { + System.out.println("process weather update"); + } + // No activity, so sleep for 1 msec + Thread.sleep(1000); + } + subscriber.close (); + context.term (); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.zeromq.ZMQ$Socket` acquired by call to `socket(...)` at line 35 is not released after line 59. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void msreader.main(java.lang.String[]) + +### Procedure Id: +guide.msreader.main(java.lang.String[]):void.52579c6e9b48396f1c2def9f106336e1 + +### File: +src/test/java/guide/msreader.java + +### Key: +msreader.java|main|RESOURCE_LEAK + +### Node Key: +6508d5d8afc7791075e471b62b4a3ccb + +### Hash: +380eb13eebbd5a07dff3fccf258cb67e + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11153/instruction.md b/inferredbugs-11153/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1a5d6d22c4b832700730b00855f86aeb36b766c1 --- /dev/null +++ b/inferredbugs-11153/instruction.md @@ -0,0 +1,137 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jeromq +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + Copyright (c) 2007-2014 Contributors as noted in the AUTHORS file + + This file is part of 0MQ. + + 0MQ 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. + + 0MQ 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 program. If not, see . +*/ + +package guide; + +import org.zeromq.ZMQ; + +// +// Reading from multiple sockets in Java +// This version uses a simple recv loop +// +public class msreader { + + public static void main (String[] args) throws Exception { + // Prepare our context and sockets + ZMQ.Context context = ZMQ.context(1); + + // Connect to task ventilator + ZMQ.Socket receiver = context.socket(ZMQ.PULL); + receiver.connect("tcp://localhost:5557"); + + // Connect to weather server + ZMQ.Socket subscriber = context.socket(ZMQ.SUB); + subscriber.connect("tcp://localhost:5556"); + subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET)); + + // Process messages from both sockets + // We prioritize traffic from the task ventilator + while (!Thread.currentThread ().isInterrupted ()) { + // Process any waiting tasks + byte[] task; + while((task = receiver.recv(ZMQ.DONTWAIT)) != null) { + System.out.println("process task"); + } + // Process any waiting weather updates + byte[] update; + while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) { + System.out.println("process weather update"); + } + // No activity, so sleep for 1 msec + Thread.sleep(1000); + } + subscriber.close (); + context.term (); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.zeromq.ZMQ$Socket` acquired to `subscriber` by call to `socket(...)` at line 39 is not released after line 61. +**Note**: potential exception at line 48 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void msreader.main(java.lang.String[]) + +### Procedure Id: +guide.msreader.main(java.lang.String[]):void.52579c6e9b48396f1c2def9f106336e1 + +### File: +src/test/java/guide/msreader.java + +### Key: +msreader.java|main|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +034ce763740d2b1385a4ffcffa67e2b2 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11154/instruction.md b/inferredbugs-11154/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..44c94c1ff3078cf0946901a43ccaf9f95a31cb16 --- /dev/null +++ b/inferredbugs-11154/instruction.md @@ -0,0 +1,570 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jeromq +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + Copyright (c) 2007-2014 Contributors as noted in the AUTHORS file + + This file is part of 0MQ. + + 0MQ 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. + + 0MQ 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 program. If not, see . +*/ + +package org.zeromq; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.CharacterCodingException; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.zeromq.ZMQ.Context; +import org.zeromq.ZMQ.Socket; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class TestZMQ +{ + static class Client extends Thread + { + private Socket s = null; + public Client(Context ctx) + { + s = ctx.socket(ZMQ.PULL); + } + + @Override + public void run() + { + System.out.println("Start client thread "); + s.connect("tcp://127.0.0.1:6669"); + s.recv(0); + + s.close(); + System.out.println("Stop client thread "); + } + } + + @Test + public void testPollerPollout() throws Exception + { + ZMQ.Context context = ZMQ.context(1); + Client client = new Client(context); + + // Socket to send messages to + ZMQ.Socket sender = context.socket(ZMQ.PUSH); + sender.bind("tcp://127.0.0.1:6669"); + + ZMQ.Poller outItems; + outItems = context.poller(); + outItems.register(sender, ZMQ.Poller.POLLOUT); + + while (!Thread.currentThread().isInterrupted()) { + outItems.poll(1000); + if (outItems.pollout(0)) { + sender.send("OK", 0); + System.out.println("ok"); + break; + } + else { + System.out.println("not writable"); + client.start(); + } + } + client.join(); + sender.close(); + context.term(); + } + + @Test + public void testByteBufferSend() throws InterruptedException + { + ZMQ.Context context = ZMQ.context(1); + ByteBuffer bb = ByteBuffer.allocate(4).order(ByteOrder.nativeOrder()); + ZMQ.Socket push = null; + ZMQ.Socket pull = null; + try { + push = context.socket(ZMQ.PUSH); + pull = context.socket(ZMQ.PULL); + pull.bind("tcp://*:12344"); + push.connect("tcp://localhost:12344"); + bb.put("PING".getBytes(ZMQ.CHARSET)); + bb.flip(); + push.sendByteBuffer(bb, 0); + String actual = new String(pull.recv(), ZMQ.CHARSET); + assertEquals("PING", actual); + } + finally { + try { + push.close(); + } + catch (Exception ignore) { + } + try { + pull.close(); + } + catch (Exception ignore) { + } + try { + context.term(); + } + catch (Exception ignore) { + } + } + } + + @Test + public void testByteBufferRecv() throws InterruptedException, CharacterCodingException + { + ZMQ.Context context = ZMQ.context(1); + ByteBuffer bb = ByteBuffer.allocate(6).order(ByteOrder.nativeOrder()); + ZMQ.Socket push = null; + ZMQ.Socket pull = null; + try { + push = context.socket(ZMQ.PUSH); + pull = context.socket(ZMQ.PULL); + pull.bind("tcp://*:12345"); + push.connect("tcp://localhost:12345"); + push.send("PING".getBytes(ZMQ.CHARSET), 0); + pull.recvByteBuffer(bb, 0); + bb.flip(); + byte[] b = new byte[bb.remaining()]; + bb.duplicate().get(b); + assertEquals("PING", new String(b, ZMQ.CHARSET)); + } + finally { + try { + push.close(); + } + catch (Exception ignore) { + ignore.printStackTrace(); + } + try { + pull.close(); + } + catch (Exception ignore) { + ignore.printStackTrace(); + } + try { + context.term(); + } + catch (Exception ignore) { + ignore.printStackTrace(); + } + } + + } + + @Test(expected = ZMQException.class) + public void testBindSameAddress() + { + ZMQ.Context context = ZMQ.context(1); + + ZMQ.Socket socket1 = context.socket(ZMQ.REQ); + ZMQ.Socket socket2 = context.socket(ZMQ.REQ); + socket1.bind("tcp://*:12346"); + try { + socket2.bind("tcp://*:12346"); + fail("Exception not thrown"); + } + catch (ZMQException e) { + assertEquals(e.getErrorCode(), ZMQ.Error.EADDRINUSE.getCode()); + throw e; + } + finally { + socket1.close(); + socket2.close(); + + context.term(); + } + } + + @Test(expected = ZMQException.class) + public void testBindInprocSameAddress() + { + ZMQ.Context context = ZMQ.context(1); + + ZMQ.Socket socket1 = context.socket(ZMQ.REQ); + ZMQ.Socket socket2 = context.socket(ZMQ.REQ); + socket1.bind("inproc://address.already.in.use"); + try { + socket2.bind("inproc://address.already.in.use"); + fail("Exception not thrown"); + } + catch (ZMQException e) { + assertEquals(e.getErrorCode(), ZMQ.Error.EADDRINUSE.getCode()); + throw e; + } + finally { + socket1.close(); + socket2.close(); + + context.term(); + } + } + + @Test + public void testEventConnected() + { + Context context = ZMQ.context(1); + ZMQ.Event event; + + Socket helper = context.socket(ZMQ.REQ); + int port = helper.bindToRandomPort("tcp://127.0.0.1"); + + Socket socket = context.socket(ZMQ.REP); + Socket monitor = context.socket(ZMQ.PAIR); + monitor.setReceiveTimeOut(100); + + assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_CONNECTED)); + monitor.connect("inproc://monitor.socket"); + + socket.connect("tcp://127.0.0.1:" + port); + event = ZMQ.Event.recv(monitor); + assertNotNull("No event was received", event); + assertEquals(ZMQ.EVENT_CONNECTED, event.getEvent()); + + helper.close(); + socket.close(); + monitor.close(); + context.term(); + } + + @Test + public void testEventConnectDelayed() + { + Context context = ZMQ.context(1); + ZMQ.Event event; + + Socket socket = context.socket(ZMQ.REP); + Socket monitor = context.socket(ZMQ.PAIR); + monitor.setReceiveTimeOut(100); + + assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_CONNECT_DELAYED)); + monitor.connect("inproc://monitor.socket"); + + socket.connect("tcp://127.0.0.1:6751"); + event = ZMQ.Event.recv(monitor); + assertNotNull("No event was received", event); + assertEquals(ZMQ.EVENT_CONNECT_DELAYED, event.getEvent()); + + socket.close(); + monitor.close(); + context.term(); + } + + @Test + public void testEventConnectRetried() + { + Context context = ZMQ.context(1); + ZMQ.Event event; + + Socket socket = context.socket(ZMQ.REP); + Socket monitor = context.socket(ZMQ.PAIR); + monitor.setReceiveTimeOut(100); + + assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_CONNECT_RETRIED)); + monitor.connect("inproc://monitor.socket"); + + socket.connect("tcp://127.0.0.1:6752"); + event = ZMQ.Event.recv(monitor); + assertNotNull("No event was received", event); + assertEquals(ZMQ.EVENT_CONNECT_RETRIED, event.getEvent()); + + socket.close(); + monitor.close(); + context.term(); + } + + @Test + public void testEventListening() + { + Context context = ZMQ.context(1); + ZMQ.Event event; + + Socket socket = context.socket(ZMQ.REP); + Socket monitor = context.socket(ZMQ.PAIR); + monitor.setReceiveTimeOut(100); + + assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_LISTENING)); + monitor.connect("inproc://monitor.socket"); + + socket.bindToRandomPort("tcp://127.0.0.1"); + event = ZMQ.Event.recv(monitor); + assertNotNull("No event was received", event); + assertEquals(ZMQ.EVENT_LISTENING, event.getEvent()); + + socket.close(); + monitor.close(); + context.term(); + } + + @Test + public void testEventBindFailed() + { + Context context = ZMQ.context(1); + ZMQ.Event event; + + Socket helper = context.socket(ZMQ.REP); + int port = helper.bindToRandomPort("tcp://127.0.0.1"); + + Socket socket = context.socket(ZMQ.REP); + Socket monitor = context.socket(ZMQ.PAIR); + monitor.setReceiveTimeOut(100); + + assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_BIND_FAILED)); + monitor.connect("inproc://monitor.socket"); + + try { + socket.bind("tcp://127.0.0.1:" + port); + } + catch (ZMQException ex) { + } + event = ZMQ.Event.recv(monitor); + assertNotNull("No event was received", event); + assertEquals(ZMQ.EVENT_BIND_FAILED, event.getEvent()); + + helper.close(); + socket.close(); + monitor.close(); + context.term(); + } + + @Test + public void testEventAccepted() + { + Context context = ZMQ.context(1); + ZMQ.Event event; + + Socket socket = context.socket(ZMQ.REP); + Socket monitor = context.socket(ZMQ.PAIR); + Socket helper = context.socket(ZMQ.REQ); + monitor.setReceiveTimeOut(100); + + assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_ACCEPTED)); + monitor.connect("inproc://monitor.socket"); + + int port = socket.bindToRandomPort("tcp://127.0.0.1"); + + helper.connect("tcp://127.0.0.1:" + port); + event = ZMQ.Event.recv(monitor); + assertNotNull("No event was received", event); + assertEquals(ZMQ.EVENT_ACCEPTED, event.getEvent()); + + helper.close(); + socket.close(); + monitor.close(); + context.term(); + } + + @Test + public void testEventClosed() + { + Context context = ZMQ.context(1); + ZMQ.Event event; + + Socket socket = context.socket(ZMQ.REP); + Socket monitor = context.socket(ZMQ.PAIR); + monitor.setReceiveTimeOut(100); + + socket.bindToRandomPort("tcp://127.0.0.1"); + + assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_CLOSED)); + monitor.connect("inproc://monitor.socket"); + + socket.close(); + event = ZMQ.Event.recv(monitor); + assertNotNull("No event was received", event); + assertEquals(ZMQ.EVENT_CLOSED, event.getEvent()); + + monitor.close(); + context.term(); + } + + @Test + public void testEventDisconnected() + { + Context context = ZMQ.context(1); + ZMQ.Event event; + + Socket socket = context.socket(ZMQ.REP); + Socket monitor = context.socket(ZMQ.PAIR); + Socket helper = context.socket(ZMQ.REQ); + monitor.setReceiveTimeOut(100); + + int port = socket.bindToRandomPort("tcp://127.0.0.1"); + helper.connect("tcp://127.0.0.1:" + port); + + assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_DISCONNECTED)); + monitor.connect("inproc://monitor.socket"); + + helper.close(); + event = ZMQ.Event.recv(monitor); + assertNotNull("No event was received", event); + assertEquals(ZMQ.EVENT_DISCONNECTED, event.getEvent()); + + socket.close(); + monitor.close(); + context.term(); + } + + @Test + public void testEventMonitorStopped() + { + Context context = ZMQ.context(1); + ZMQ.Event event; + + Socket socket = context.socket(ZMQ.REP); + Socket monitor = context.socket(ZMQ.PAIR); + monitor.setReceiveTimeOut(100); + + assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_MONITOR_STOPPED)); + monitor.connect("inproc://monitor.socket"); + + socket.monitor(null, 0); + event = ZMQ.Event.recv(monitor); + assertNotNull("No event was received", event); + assertEquals(ZMQ.EVENT_MONITOR_STOPPED, event.getEvent()); + + socket.close(); + monitor.close(); + context.term(); + } + + @Test + public void testSocketUnbind() + { + Context context = ZMQ.context(1); + + Socket push = context.socket(ZMQ.PUSH); + Socket pull = context.socket(ZMQ.PULL); + pull.setReceiveTimeOut(50); + + int port = pull.bindToRandomPort("tcp://127.0.0.1"); + push.connect("tcp://127.0.0.1:" + port); + + byte[] data = "ABC".getBytes(); + + push.send(data); + assertArrayEquals(data, pull.recv()); + + pull.unbind("tcp://127.0.0.1:" + port); + + push.send(data); + assertNull(pull.recv()); + + push.close(); + pull.close(); + context.term(); + } + + @Test + public void testContextBlocky() + { + Context ctx = ZMQ.context(1); + Socket router = ctx.socket(ZMQ.ROUTER); + long rc = router.getLinger(); + assertEquals(-1, rc); + router.close(); + ctx.setBlocky(false); + router = ctx.socket(ZMQ.ROUTER); + rc = router.getLinger(); + assertEquals(0, rc); + router.close(); + ctx.term(); + } + + @Test(timeout = 1000) + public void testSocketDoubleClose() + { + Context ctx = ZMQ.context(1); + Socket socket = ctx.socket(ZMQ.PUSH); + socket.close(); + socket.close(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.zeromq.ZMQ$Context` acquired to `ctx` by call to `context(...)` at line 491 is not released after line 492. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestZMQ.testSocketDoubleClose() + +### Procedure Id: +org.zeromq.TestZMQ.testSocketDoubleClose():void.d67258662d1c6fab7f892107b67a6e71 + +### File: +src/test/java/org/zeromq/TestZMQ.java + +### Key: +TestZMQ.java|testSocketDoubleClose|RESOURCE_LEAK + +### Node Key: +65923eb2d407265462e0f3003a87c7a7 + +### Hash: +284d5b8c3fb17266f4c7ef8edb775103 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11155/instruction.md b/inferredbugs-11155/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e6020ad8e1790a82c3d563bd7f4a3cdbd0d608c6 --- /dev/null +++ b/inferredbugs-11155/instruction.md @@ -0,0 +1,328 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jeromq +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.zeromq; + +import java.io.Closeable; +import java.nio.channels.Selector; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.zeromq.ZMQ.Context; +import org.zeromq.ZMQ.Poller; +import org.zeromq.ZMQ.Socket; + +/** + * ZContext provides a high-level ZeroMQ context management class + * + * It manages open sockets in the context and automatically closes these before terminating the context. + * It provides a simple way to set the linger timeout on sockets, and configure contexts for number of I/O threads. + * Sets-up signal (interrupt) handling for the process. + * + */ + +public class ZContext implements Closeable +{ + /** + * Reference to underlying Context object + */ + private volatile Context context; // Created lazily, use getContext() to access. + + /** + * List of sockets managed by this ZContext + */ + private final List sockets; + + /** + * Number of io threads allocated to this context, default 1 + */ + private final int ioThreads; + + /** + * Linger timeout, default 0 + */ + private int linger; + + /** + * Indicates if context object is owned by main thread + * (useful for multi-threaded applications) + */ + private final boolean main; + + /** + * Class Constructor + */ + public ZContext() + { + this(1); + } + + public ZContext(int ioThreads) + { + this(null, true, ioThreads); + } + + private ZContext(Context context, boolean main, int ioThreads) + { + sockets = new CopyOnWriteArrayList<>(); + this.context = context; + this.ioThreads = ioThreads; + this.main = main; + linger = 0; + } + + /** + * Destructor. Call this to gracefully terminate context and close any managed 0MQ sockets + */ + public void destroy() + { + for (Socket socket : sockets) { + socket.setLinger(linger); + socket.close(); + } + sockets.clear(); + + // Only terminate context if we are on the main thread + if (isMain() && context != null) { + context.term(); + } + + synchronized (this) { + context = null; + } + } + + /** + * Creates a new managed socket within this ZContext instance. + * Use this to get automatic management of the socket at shutdown + * @param type + * socket type (see ZMQ static class members) + * @return + * Newly created Socket object + */ + public Socket createSocket(int type) + { + // Create and register socket + Socket socket = getContext().socket(type); + sockets.add(socket); + return socket; + } + + /** + * Destroys managed socket within this context + * and remove from sockets list + * @param s + * org.zeromq.Socket object to destroy + */ + public void destroySocket(Socket s) + { + if (s == null) { + return; + } + + if (sockets.remove(s)) { + s.setLinger(linger); + s.close(); + } + } + + public Selector createSelector() + { + return getContext().selector(); + } + + public Poller createPoller(int size) + { + return new Poller(getContext(), size); + } + + /** + * Creates new shadow context. + * Shares same underlying org.zeromq.Context instance but has own list + * of managed sockets, io thread count etc. + * @param ctx Original ZContext to create shadow of + * @return New ZContext + */ + public static ZContext shadow(ZContext ctx) + { + return new ZContext(ctx.getContext(), false, ctx.getIoThreads()); + } + + /** + * @return the ioThreads + */ + public int getIoThreads() + { + return ioThreads; + } + + /** + * @param ioThreads the number of ioThreads to set + * @deprecated This value should not be changed after the context is initialized. + */ + @Deprecated + public void setIoThreads(int ioThreads) + { + return; + } + + /** + * @return the linger + */ + public int getLinger() + { + return linger; + } + + /** + * @param linger the linger to set + */ + public void setLinger(int linger) + { + this.linger = linger; + } + + /** + * @return the main + */ + public boolean isMain() + { + return main; + } + + /** + * @param main whether or not the context is being set to main + * @deprecated This value should not be changed after the context is initialized. + */ + @Deprecated + public void setMain(boolean main) + { + return; + } + + /** + * @return the context + */ + public Context getContext() + { + Context result = context; + if (result == null) { + synchronized (this) { + result = context; + if (result == null) { + result = ZMQ.context(ioThreads); + context = result; + } + } + } + return result; + } + + /** + * @param ctx sets the underlying zmq.Context associated with this ZContext wrapper object + * @deprecated This value should not be changed after the ZContext is initialized. + */ + @Deprecated + public void setContext(Context ctx) + { + return; + } + + /** + * @return the sockets + */ + public List getSockets() + { + return sockets; + } + + @Override + public void close() + { + destroy(); + } + + public boolean isClosed() + { + synchronized (this) { + if (context == null) { + return true; + } + return context.isClosed(); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.zeromq.ZContext.destroy` indirectly writes to field `socket.org.zeromq.ZMQ$Socket.base.zmq.Own.options.zmq.Options.asServer` outside of synchronization. + Reporting because this access may occur on a background thread. + +Note that the prefix path socket has been contaminated during the execution, so the reported race on socket.org.zeromq.ZMQ$Socket.base.zmq.Own.options.zmq.Options.asServer might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ZContext.destroy() + +### Procedure Id: +org.zeromq.ZContext.destroy():void.4999bab718cfade53cdd45c591a6a11e + +### File: +src/main/java/org/zeromq/ZContext.java + +### Key: +ZContext.java|destroy|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +1871dfc4ff753fb6812bd54d3639c90a + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11162/instruction.md b/inferredbugs-11162/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..429f4314e0e78a3de56d703db82c7bca44645c5a --- /dev/null +++ b/inferredbugs-11162/instruction.md @@ -0,0 +1,318 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jeromq +**Bug ID:** 21 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.zeromq; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; + +import java.io.IOException; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; +import org.zeromq.ZMQ.Socket; +import org.zeromq.ZProxy.Plug; + +import zmq.util.Utils; + +public class XpubXsubZTest +{ + private AtomicReference testIssue476(final int front, final int back, final int max, + ExecutorService service, final ZContext ctx) + throws InterruptedException, ExecutionException + { + final AtomicInteger numberReceived = new AtomicInteger(0); + + Future subscriber = service.submit(new Runnable() + { + @Override + public void run() + { + Thread.currentThread().setName("Subscriber"); + final ZContext ctx = new ZContext(); + try { + final ZMQ.Socket requester = ctx.createSocket(SocketType.SUB); + requester.connect("tcp://localhost:" + back); + requester.subscribe("hello".getBytes(ZMQ.CHARSET)); + + while (numberReceived.get() < max) { + ZMsg.recvMsg(requester); + numberReceived.incrementAndGet(); + } + } + finally { + ctx.close(); + } + } + }); + + final AtomicReference error = new AtomicReference<>(); + service.submit(new Runnable() + { + @Override + public void run() + { + Thread.currentThread().setName("Publisher"); + try { + ZMQ.Socket pub = ctx.createSocket(SocketType.PUB); + pub.connect("tcp://localhost:" + front); + while (numberReceived.get() < max) { + ZMsg message = ZMsg.newStringMsg("hello", "world"); + boolean rc = message.send(pub); + assertThat(rc, is(true)); + ZMQ.msleep(5); + } + } + catch (Throwable ex) { + error.set(ex); + ex.printStackTrace(); + } + } + }); + + try { + subscriber.get(5, TimeUnit.SECONDS); + } + catch (TimeoutException e) { + System.err.println("Timeout waiting for subscriber to get " + max + " messages."); + error.set(e); + e.printStackTrace(); + + numberReceived.set(max + 1); // Make sure the threads will finish + } + + ZMQ.msleep(300); + return error; + } + + @Test + public void testIssue476() throws InterruptedException, IOException, ExecutionException + { + final int front = Utils.findOpenPort(); + final int back = Utils.findOpenPort(); + + final int max = 10; + + ExecutorService service = Executors.newFixedThreadPool(3); + final ZContext ctx = new ZContext(); + service.submit(new Runnable() + { + @Override + public void run() + { + Thread.currentThread().setName("Proxy"); + ZMQ.Socket xpub = ctx.createSocket(SocketType.XPUB); + xpub.bind("tcp://*:" + back); + ZMQ.Socket xsub = ctx.createSocket(SocketType.XSUB); + xsub.bind("tcp://*:" + front); + ZMQ.Socket ctrl = ctx.createSocket(SocketType.PAIR); + ctrl.bind("inproc://ctrl-proxy"); + ZMQ.proxy(xpub, xsub, null, ctrl); + } + }); + final AtomicReference error = testIssue476(front, back, max, service, ctx); + ZMQ.Socket ctrl = ctx.createSocket(SocketType.PAIR); + ctrl.connect("inproc://ctrl-proxy"); + ctrl.send(ZMQ.PROXY_TERMINATE); + ctrl.close(); + + service.shutdown(); + service.awaitTermination(2, TimeUnit.SECONDS); + + assertThat(error.get(), nullValue()); + + ctx.close(); + } + + @SuppressWarnings("deprecation") + @Test + public void testIssue476WithZProxy() throws InterruptedException, IOException, ExecutionException + { + final int front = Utils.findOpenPort(); + final int back = Utils.findOpenPort(); + + final int max = 10; + + ExecutorService service = Executors.newFixedThreadPool(3); + final ZContext ctx = new ZContext(); + + ZProxy.Proxy actor = new ZProxy.Proxy.SimpleProxy() + { + @Override + public Socket create(ZContext ctx, Plug place, Object... args) + { + if (place == Plug.FRONT) { + return ctx.createSocket(SocketType.XSUB); + } + if (place == Plug.BACK) { + return ctx.createSocket(SocketType.XPUB); + } + if (place == Plug.CAPTURE) { + return ctx.createSocket(SocketType.PUB); + } + return null; + } + + @Override + public boolean configure(Socket socket, Plug place, Object... args) throws IOException + { + if (place == Plug.FRONT) { + return socket.bind("tcp://*:" + front); + } + if (place == Plug.BACK) { + return socket.bind("tcp://*:" + back); + } + return true; + } + }; + ZProxy proxy = ZProxy.newZProxy(ctx, null, actor, UUID.randomUUID().toString()); + proxy.start(true); + final AtomicReference error = testIssue476(front, back, max, service, ctx); + + proxy.exit(false); + + service.shutdown(); + service.awaitTermination(2, TimeUnit.SECONDS); + + assertThat(error.get(), nullValue()); + + ctx.close(); + } + + @SuppressWarnings("deprecation") + @Test + public void testIssue476WithZProxyZmqPump() throws InterruptedException, IOException, ExecutionException + { + final int front = Utils.findOpenPort(); + final int back = Utils.findOpenPort(); + + final int max = 10; + + ExecutorService service = Executors.newFixedThreadPool(3); + final ZContext ctx = new ZContext(); + + ZProxy.Proxy actor = new ZProxy.Proxy.SimpleProxy() + { + @Override + public Socket create(ZContext ctx, Plug place, Object... args) + { + if (place == Plug.FRONT) { + return ctx.createSocket(SocketType.XSUB); + } + if (place == Plug.BACK) { + return ctx.createSocket(SocketType.XPUB); + } + if (place == Plug.CAPTURE) { + return ctx.createSocket(SocketType.PUB); + } + return null; + } + + @Override + public boolean configure(Socket socket, Plug place, Object... args) throws IOException + { + if (place == Plug.FRONT) { + return socket.bind("tcp://*:" + front); + } + if (place == Plug.BACK) { + return socket.bind("tcp://*:" + back); + } + return true; + } + }; + ZProxy proxy = ZProxy.newProxy(ctx, "XPub-XSub", actor, UUID.randomUUID().toString()); + proxy.start(true); + + final AtomicReference error = testIssue476(front, back, max, service, ctx); + proxy.exit(false); + + service.shutdown(); + service.awaitTermination(2, TimeUnit.SECONDS); + + assertThat(error.get(), nullValue()); + + ctx.close(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.zeromq.ZContext` acquired to `ctx` by call to `ZContext()` at line 104 is not released after line 132. +**Note**: potential exception at line 121 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void XpubXsubZTest.testIssue476() + +### Procedure Id: +org.zeromq.XpubXsubZTest.testIssue476():void.194b3a066db7b51d0b837d4674935d77 + +### File: +src/test/java/org/zeromq/XpubXsubZTest.java + +### Key: +XpubXsubZTest.java|testIssue476|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +f512776d4e338c43aafecf8e809a623b + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11164/instruction.md b/inferredbugs-11164/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1680c13e875dc458c899d6510db9621570d09b3b --- /dev/null +++ b/inferredbugs-11164/instruction.md @@ -0,0 +1,267 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jeromq +**Bug ID:** 23 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.zeromq; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.io.IOException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SocketChannel; + +import org.junit.Test; +import org.zeromq.ZMQ.Error; +import org.zeromq.ZMonitor.ProtocolCode; + +import zmq.Ctx; +import zmq.SocketBase; + +public class TestEventResolution +{ + private interface SendEvent + { + void send(SocketBase s, String addr); + } + + public ZMQ.Event make(SendEvent sender, int eventFilter) + { + Ctx ctx = new Ctx(); + @SuppressWarnings("deprecation") + SocketBase s = ctx.createSocket(ZMQ.PUB); + @SuppressWarnings("deprecation") + SocketBase m = ctx.createSocket(ZMQ.PAIR); + m.connect("inproc://TestEventResolution"); + s.monitor("inproc://TestEventResolution", eventFilter); + sender.send(s, "tcp://127.0.0.1:8000"); + zmq.ZMQ.Event ev = zmq.ZMQ.Event.read(m); + return new ZMQ.Event(ev.event, ev.arg, ev.addr); + } + + @Test(timeout = 1000) + public void testEventHandshakeFailedProtocol() + { + ZMQ.Event ev = make((s, a) -> s.eventHandshakeFailedProtocol(a, zmq.ZMQ.ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND), zmq.ZMQ.ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL); + ProtocolCode protocol = ev.resolveValue(); + assertThat(protocol, is(ProtocolCode.ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND)); + assertThat(ev.isError(), is(true)); + assertThat(ev.isWarn(), is(false)); + } + + @Test(timeout = 1000) + public void testEventHandshakeFailedAuth() + { + ZMQ.Event ev = make((s, a) -> s.eventHandshakeFailedAuth(a, 200), zmq.ZMQ.ZMQ_EVENT_HANDSHAKE_FAILED_AUTH); + int statusCode = ev.resolveValue(); + assertThat(statusCode, is(200)); + assertThat(ev.isError(), is(false)); + assertThat(ev.isWarn(), is(true)); + } + + @Test(timeout = 1000) + public void testEventDisconnected() throws IOException + { + SelectableChannel sc = SocketChannel.open(); + ZMQ.Event ev = make((s, a) -> s.eventDisconnected(a, sc), zmq.ZMQ.ZMQ_EVENT_DISCONNECTED); + Object value = ev.resolveValue(); + assertThat(value, nullValue()); + assertThat(ev.isError(), is(false)); + assertThat(ev.isWarn(), is(false)); + } + + @Test(timeout = 1000) + public void testEventClosed() throws IOException + { + SelectableChannel sc = SocketChannel.open(); + ZMQ.Event ev = make((s, a) -> s.eventClosed(a, sc), zmq.ZMQ.ZMQ_EVENT_CLOSED); + Object value = ev.resolveValue(); + assertThat(value, nullValue()); + assertThat(ev.isError(), is(false)); + assertThat(ev.isWarn(), is(false)); + } + + @Test(timeout = 1000) + public void testEventListening() throws IOException + { + SelectableChannel sc = SocketChannel.open(); + ZMQ.Event ev = make((s, a) -> s.eventListening(a, sc), zmq.ZMQ.ZMQ_EVENT_LISTENING); + Object value = ev.resolveValue(); + assertThat(value, nullValue()); + assertThat(ev.isError(), is(false)); + assertThat(ev.isWarn(), is(false)); + } + + @Test(timeout = 1000) + public void testEventConnected() throws IOException + { + SelectableChannel sc = SocketChannel.open(); + ZMQ.Event ev = make((s, a) -> s.eventConnected(a, sc), zmq.ZMQ.ZMQ_EVENT_CONNECTED); + Object value = ev.resolveValue(); + assertThat(value, nullValue()); + assertThat(ev.isError(), is(false)); + assertThat(ev.isWarn(), is(false)); + } + + @Test(timeout = 1000) + public void testEventAccepted() throws IOException + { + SelectableChannel sc = SocketChannel.open(); + ZMQ.Event ev = make((s, a) -> s.eventAccepted(a, sc), zmq.ZMQ.ZMQ_EVENT_ACCEPTED); + Object value = ev.resolveValue(); + assertThat(value, nullValue()); + assertThat(ev.isError(), is(false)); + assertThat(ev.isWarn(), is(false)); + } + + @Test(timeout = 1000) + public void testEventConnectDelayed() + { + ZMQ.Event ev = make((s, a) -> s.eventConnectDelayed(a, -1), zmq.ZMQ.ZMQ_EVENT_CONNECT_DELAYED); + Object value = ev.resolveValue(); + assertThat(value, nullValue()); + assertThat(ev.isError(), is(false)); + assertThat(ev.isWarn(), is(false)); + } + + @Test(timeout = 1000) + public void testEventConnectRetried() + { + ZMQ.Event ev = make((s, a) -> s.eventConnectRetried(a, 10), zmq.ZMQ.ZMQ_EVENT_CONNECT_RETRIED); + Object value = ev.resolveValue(); + assertThat(value, is(10)); + assertThat(ev.isError(), is(false)); + assertThat(ev.isWarn(), is(false)); + } + + @Test(timeout = 1000) + public void testEventCloseFailed() + { + ZMQ.Event ev = make((s, a) -> s.eventCloseFailed(a, Error.EINTR.getCode()), zmq.ZMQ.ZMQ_EVENT_CLOSE_FAILED); + Error err = ev.resolveValue(); + assertThat(err, is(Error.EINTR)); + assertThat(ev.isError(), is(true)); + assertThat(ev.isWarn(), is(false)); + } + + @Test(timeout = 1000) + public void testEventAcceptFailed() + { + ZMQ.Event ev = make((s, a) -> s.eventAcceptFailed(a, Error.EINTR.getCode()), zmq.ZMQ.ZMQ_EVENT_ACCEPT_FAILED); + Error err = ev.resolveValue(); + assertThat(err, is(Error.EINTR)); + assertThat(ev.isError(), is(true)); + assertThat(ev.isWarn(), is(false)); + } + + @Test(timeout = 1000) + public void testEventBindFailed() + { + ZMQ.Event ev = make((s, a) -> s.eventBindFailed(a, Error.EADDRNOTAVAIL.getCode()), zmq.ZMQ.ZMQ_EVENT_BIND_FAILED); + Error err = ev.resolveValue(); + assertThat(err, is(Error.EADDRNOTAVAIL)); + assertThat(ev.isError(), is(true)); + assertThat(ev.isWarn(), is(false)); + } + + @Test(timeout = 1000) + public void testEventHandshaken() + { + ZMQ.Event ev = make((s, a) -> s.eventHandshaken(a, -1), zmq.ZMQ.ZMQ_EVENT_HANDSHAKE_PROTOCOL); + int zmtp = ev.resolveValue(); + assertThat(zmtp, is(-1)); + assertThat(ev.isError(), is(false)); + assertThat(ev.isWarn(), is(false)); + } + + @Test(timeout = 1000) + public void testEventHandshakeSucceeded() + { + ZMQ.Event ev = make((s, a) -> s.eventHandshakeSucceeded(a, 0), zmq.ZMQ.ZMQ_EVENT_HANDSHAKE_SUCCEEDED); + Object value = ev.resolveValue(); + assertThat(value, nullValue()); + assertThat(ev.isError(), is(false)); + assertThat(ev.isWarn(), is(false)); + } + + @Test(timeout = 1000) + public void testEventHandshakeFailedNoDetail() + { + ZMQ.Event ev = make((s, a) -> s.eventHandshakeFailedNoDetail(a, 0), zmq.ZMQ.ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL); + Object value = ev.resolveValue(); + assertThat(value, nullValue()); + assertThat(ev.isError(), is(true)); + assertThat(ev.isWarn(), is(false)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `m` last assigned on line 31 could be null and is dereferenced at line 32. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +ZMQ$Event TestEventResolution.make(TestEventResolution$SendEvent,int) + +### Procedure Id: +org.zeromq.TestEventResolution.make(org.zeromq.TestEventResolution$SendEvent,int):org.zeromq.ZMQ$Eve.566e2271ea95fcaebc93c6d3fe7c6506 + +### File: +src/test/java/org/zeromq/TestEventResolution.java + +### Key: +TestEventResolution.java|make|NULL_DEREFERENCE + +### Node Key: +3677875e6aead27ee1320f16c80d8b0f + +### Hash: +9d1b384dd2131272aa7a1af2fc05b964 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-11165/instruction.md b/inferredbugs-11165/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b9e897cc280dd41843763efead47eb577dbf347d --- /dev/null +++ b/inferredbugs-11165/instruction.md @@ -0,0 +1,464 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jeromq +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + Copyright (c) 2012 iMatix Corporation + Copyright (c) 2009-2011 250bpm s.r.o. + Copyright (c) 2011 VMware, Inc. + Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file + + This file is part of 0MQ. + + 0MQ 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. + + 0MQ 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 program. If not, see . +*/ +package zmq; + +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +//TODO: This class uses O(n) scheduling. Rewrite it to use O(1) algorithm. +public class Router extends SocketBase { + + public static class RouterSession extends SessionBase { + public RouterSession(IOThread io_thread_, boolean connect_, + SocketBase socket_, final Options options_, + final Address addr_) { + super(io_thread_, connect_, socket_, options_, addr_); + } + } + + // Fair queueing object for inbound pipes. + private final FQ fq; + + // True iff there is a message held in the pre-fetch buffer. + private boolean prefetched; + + // If true, the receiver got the message part with + // the peer's identity. + private boolean identity_sent; + + // Holds the prefetched identity. + private Msg prefetched_id; + + // Holds the prefetched message. + private Msg prefetched_msg; + + // If true, more incoming message parts are expected. + private boolean more_in; + + class Outpipe + { + private Pipe pipe; + private boolean active; + + public Outpipe(Pipe pipe_, boolean active_) { + pipe = pipe_; + active = active_; + } + }; + + // We keep a set of pipes that have not been identified yet. + private final Set anonymous_pipes; + + // Outbound pipes indexed by the peer IDs. + private final Map outpipes; + + // The pipe we are currently writing to. + private Pipe current_out; + + // If true, more outgoing message parts are expected. + private boolean more_out; + + // Peer ID are generated. It's a simple increment and wrap-over + // algorithm. This value is the next ID to use (if not used already). + private int next_peer_id; + + // If true, report EHOSTUNREACH to the caller instead of silently dropping + // the message targeting an unknown peer. + private boolean mandatory; + + + public Router(Ctx parent_, int tid_, int sid_) { + super(parent_, tid_, sid_); + prefetched = false; + identity_sent = false; + more_in = false; + current_out = null; + more_out = false; + next_peer_id = Utils.generate_random (); + mandatory = false; + + options.type = ZMQ.ZMQ_ROUTER; + + + fq = new FQ(); + prefetched_id = new Msg(); + prefetched_msg = new Msg(); + + anonymous_pipes = new HashSet(); + outpipes = new HashMap(); + + // TODO: Uncomment the following line when ROUTER will become true ROUTER + // rather than generic router socket. + // If peer disconnect there's noone to send reply to anyway. We can drop + // all the outstanding requests from that peer. + // options.delay_on_disconnect = false; + + options.recv_identity = true; + + } + + + + @Override + public void xattach_pipe(Pipe pipe_, boolean icanhasall_) { + assert (pipe_ != null); + + boolean identity_ok = identify_peer (pipe_); + if (identity_ok) + fq.attach (pipe_); + else + anonymous_pipes.add (pipe_); + } + + @Override + public boolean xsetsockopt (int option_, Object optval_) + { + if (option_ != ZMQ.ZMQ_ROUTER_MANDATORY) { + return false; + } + mandatory = (Integer) optval_ == 1; + return true; + } + + + @Override + public void xterminated(Pipe pipe_) { + if (!anonymous_pipes.remove(pipe_)) { + + Outpipe old = outpipes.remove(pipe_.get_identity()); + assert(old != null); + + fq.terminated (pipe_); + if (pipe_ == current_out) + current_out = null; + } + } + + @Override + public void xread_activated (Pipe pipe_) + { + if (!anonymous_pipes.contains(pipe_)) + fq.activated (pipe_); + else { + boolean identity_ok = identify_peer (pipe_); + if (identity_ok) { + anonymous_pipes.remove(pipe_); + fq.attach (pipe_); + } + } + } + + @Override + public void xwrite_activated (Pipe pipe_) + { + for (Map.Entry it: outpipes.entrySet()) { + if (it.getValue().pipe == pipe_) { + assert (!it.getValue().active); + it.getValue().active = true; + break; + } + } + assert (false); + } + + @Override + protected boolean xsend(Msg msg_) + { + // If this is the first part of the message it's the ID of the + // peer to send the message to. + if (!more_out) { + assert (current_out == null); + + // If we have malformed message (prefix with no subsequent message) + // then just silently ignore it. + // TODO: The connections should be killed instead. + if (msg_.has_more()) { + + more_out = true; + + // Find the pipe associated with the identity stored in the prefix. + // If there's no such pipe just silently ignore the message, unless + // mandatory is set. + Blob identity = new Blob(msg_.data()); + Outpipe op = outpipes.get(identity); + + if (op != null) { + current_out = op.pipe; + if (!current_out.check_write ()) { + op.active = false; + current_out = null; + if (mandatory) { + more_out = false; + errno.set(ZError.EAGAIN); + return false; + } + } + } else if (mandatory) { + more_out = false; + errno.set(ZError.EHOSTUNREACH); + return false; + } + } + + return true; + } + + // Check whether this is the last part of the message. + more_out = msg_.has_more(); + + // Push the message into the pipe. If there's no out pipe, just drop it. + if (current_out != null) { + boolean ok = current_out.write (msg_); + if (!ok) + current_out = null; + else if (!more_out) { + current_out.flush (); + current_out = null; + } + } + + return true; + } + + + @Override + protected Msg xrecv() + { + Msg msg_ = null; + if (prefetched) { + if (!identity_sent) { + msg_ = prefetched_id; + prefetched_id = null; + identity_sent = true; + } + else { + msg_ = prefetched_msg; + prefetched_msg = null; + prefetched = false; + } + more_in = msg_.has_more(); + return msg_; + } + + ValueReference pipe = new ValueReference(); + msg_ = fq.recvpipe(errno, pipe); + + // It's possible that we receive peer's identity. That happens + // after reconnection. The current implementation assumes that + // the peer always uses the same identity. + // TODO: handle the situation when the peer changes its identity. + while (msg_ != null && msg_.is_identity()) + msg_ = fq.recvpipe(errno, pipe); + + if (msg_ == null) + return null; + + assert (pipe.get() != null); + + // If we are in the middle of reading a message, just return the next part. + if (more_in) + more_in = msg_.has_more(); + else { + // We are at the beginning of a message. + // Keep the message part we have in the prefetch buffer + // and return the ID of the peer instead. + prefetched_msg = msg_; + prefetched = true; + + Blob identity = pipe.get().get_identity(); + msg_ = new Msg(identity.data()); + msg_.set_flags(Msg.more); + identity_sent = true; + } + + return msg_; + } + + // Rollback any message parts that were sent but not yet flushed. + protected void rollback () { + + if (current_out != null) { + current_out.rollback (); + current_out = null; + more_out = false; + } + } + + @Override + protected boolean xhas_in () + { + // If we are in the middle of reading the messages, there are + // definitely more parts available. + if (more_in) + return true; + + // We may already have a message pre-fetched. + if (prefetched) + return true; + + // Try to read the next message. + // The message, if read, is kept in the pre-fetch buffer. + ValueReference pipe = new ValueReference(); + prefetched_msg = fq.recvpipe(errno, pipe); + + // It's possible that we receive peer's identity. That happens + // after reconnection. The current implementation assumes that + // the peer always uses the same identity. + // TODO: handle the situation when the peer changes its identity. + while (prefetched_msg != null && prefetched_msg.is_identity ()) + prefetched_msg = fq.recvpipe(errno, pipe); + + if (prefetched_msg == null) + return false; + + assert (pipe.get() != null); + + Blob identity = pipe.get().get_identity(); + prefetched_id = new Msg(identity.data()); + prefetched_id.set_flags (Msg.more); + + prefetched = true; + identity_sent = false; + + return true; + } + + @Override + protected boolean xhas_out () + { + // In theory, ROUTER socket is always ready for writing. Whether actual + // attempt to write succeeds depends on whitch pipe the message is going + // to be routed to. + return true; + } + + private boolean identify_peer(Pipe pipe_) + { + Blob identity; + + Msg msg = pipe_.read(); + if (msg == null) + return false; + + if (msg.size () == 0) { + // Fall back on the auto-generation + ByteBuffer buf = ByteBuffer.allocate(5); + buf.put((byte)0); + buf.putInt (next_peer_id++); + buf.flip(); + identity = new Blob(buf); + } + else { + identity = new Blob(msg.data ()); + + // Ignore peers with duplicate ID. + if (outpipes.containsKey(identity)) + return false; + } + + pipe_.set_identity (identity); + // Add the record into output pipes lookup table + Outpipe outpipe = new Outpipe(pipe_, true); + outpipes.put (identity, outpipe); + + return true; + } + + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `msg.data()` could be null and is dereferenced by call to `Blob(...)` at line 374. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean Router.identify_peer(Pipe) + +### Procedure Id: +zmq.Router.identify_peer(zmq.Pipe):boolean.04ea7a7de2a2bccee320c9ae343e3182 + +### File: +src/main/java/zmq/Router.java + +### Key: +Router.java|identify_peer|NULL_DEREFERENCE + +### Node Key: +0968bf39be2b03b8a96ca936f7302727 + +### Hash: +94351621415e7cb23b1d416444f23d37 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1211/instruction.md b/inferredbugs-1211/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ae4b9a654e2676d4395dc04aa22aff7c5bb8b20c --- /dev/null +++ b/inferredbugs-1211/instruction.md @@ -0,0 +1,130 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** QuestPDF +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Linq; +using QuestPDF.Drawing.SpacePlan; +using QuestPDF.Infrastructure; + +namespace QuestPDF.Elements +{ + internal class Constrained : ContainerElement + { + public float? MinWidth { get; set; } + public float? MaxWidth { get; set; } + + public float? MinHeight { get; set; } + public float? MaxHeight { get; set; } + + internal override ISpacePlan Measure(Size availableSpace) + { + if (MinWidth > availableSpace.Width + Size.Epsilon) + return new Wrap(); + + if (MinHeight > availableSpace.Height + Size.Epsilon) + return new Wrap(); + + var available = new Size( + MathHelpers.Min(MaxWidth, availableSpace.Width), + MathHelpers.Min(MaxHeight, availableSpace.Height)); + + var measurement = Child?.Measure(available) ?? new FullRender(Size.Zero); + var size = measurement as Size; + + if (measurement is Wrap) + return new Wrap(); + + var actualSize = new Size( + MathHelpers.Max(MinWidth, size.Width), + MathHelpers.Max(MinHeight, size.Height)); + + if (size is FullRender) + return new FullRender(actualSize); + + if (size is PartialRender) + return new PartialRender(actualSize); + + throw new NotSupportedException(); + } + + internal override void Draw(Size availableSpace) + { + var available = new Size( + MathHelpers.Min(MaxWidth, availableSpace.Width), + MathHelpers.Min(MaxHeight, availableSpace.Height)); + + Child?.Draw(available); + } + } + + static class MathHelpers + { + public static float Min(params float?[] values) + { + return values.Where(x => x.HasValue).Min().Value; + } + + public static float Max(params float?[] values) + { + return values.Where(x => x.HasValue).Max().Value; + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `size` last assigned on line 29 could be null and is dereferenced at line 34, column 13. + +### Severity: +ERROR + +### Procedure: +ISpacePlan Constrained.Measure(Size) + +### File: +QuestPDF/Elements/Constrained.cs + +### Key: +Constrained.cs|Measure|NULL_DEREFERENCE + +### Node Key: +9fa7d8fc250e72e14376cc143f667c2c + +### Hash: +780c62e5831489836300550a24306a0f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1216/instruction.md b/inferredbugs-1216/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..28b9d3cdf353be7c617ab772849d8dbc52801852 --- /dev/null +++ b/inferredbugs-1216/instruction.md @@ -0,0 +1,586 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Stardust +**Bug ID:** 7 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.NetworkInformation; +using System.Reflection; +using System.Threading.Tasks; +using NewLife; +using NewLife.Http; +using NewLife.Log; +using NewLife.Net; +using NewLife.Reflection; +using NewLife.Remoting; +using NewLife.Security; +using NewLife.Serialization; +using NewLife.Threading; +using Stardust.Models; +using Stardust.Services; + +namespace Stardust +{ + /// 星星客户端。每个设备节点有一个客户端连接服务端 + public class StarClient : ApiHttpClient + { + #region 属性 + /// 证书 + public String Code { get; set; } + + /// 密钥 + public String Secret { get; set; } + + /// 是否已登录 + public Boolean Logined { get; set; } + + /// 登录完成后触发 + public event EventHandler OnLogined; + + /// 最后一次登录成功后的消息 + public LoginResponse Info { get; private set; } + + /// 请求到服务端并返回的延迟时间。单位ms + public Int32 Delay { get; set; } + + /// 命令队列 + public IQueueService CommandQueue { get; } = new QueueService(); + #endregion + + #region 构造 + /// 实例化 + public StarClient() + { + Log = XTrace.Log; + + _task = MachineInfo.RegisterAsync(); + } + + /// 实例化 + /// + public StarClient(String urls) : this() + { + if (!urls.IsNullOrEmpty()) + { + var ss = urls.Split(","); + for (var i = 0; i < ss.Length; i++) + { + Add("service" + (i + 1), new Uri(ss[i])); + } + } + } + + /// 销毁 + /// + protected override void Dispose(Boolean disposing) + { + Logout(disposing ? "Dispose" : "GC").Wait(1_000); + + _timer.TryDispose(); + _timer = null; + + base.Dispose(disposing); + } + #endregion + + #region 方法 + /// 远程调用拦截,支持重新登录 + /// + /// + /// + /// + /// + /// + public override async Task InvokeAsync(HttpMethod method, String action, Object args = null, Action onRequest = null) + { + try + { + return await base.InvokeAsync(method, action, args, onRequest); + } + catch (Exception ex) + { + var ex2 = ex.GetTrue(); + if (ex2 is ApiException aex && (aex.Code == 402 || aex.Code == 403) && !action.EqualIgnoreCase("Node/Login", "Node/Logout")) + { + XTrace.WriteException(ex); + XTrace.WriteLine("重新登录!"); + await Login(); + + return await base.InvokeAsync(method, action, args, onRequest); + } + + throw; + } + } + #endregion + + #region 登录 + /// 登录 + /// + public async Task Login() + { + XTrace.WriteLine("登录:{0}", Code); + + var info = GetLoginInfo(); + + // 登录前清空令牌,避免服务端使用上一次信息 + Token = null; + Logined = false; + Info = null; + + var rs = Info = await LoginAsync(info); + if (rs != null && !rs.Code.IsNullOrEmpty()) + { + XTrace.WriteLine("下发证书:{0}/{1}", rs.Code, rs.Secret); + Code = rs.Code; + Secret = rs.Secret; + } + + // 登录后设置用于用户认证的token + Token = rs.Token; + Logined = true; + + OnLogined?.Invoke(this, EventArgs.Empty); + + if (Logined && _timer == null) + { + lock (this) + { + if (_timer == null) + { + _timer = new TimerX(s => Ping().Wait(), null, 5_000, 60_000, "Device") { Async = true }; + } + } + } + + return rs; + } + + /// 获取登录信息 + /// + public LoginInfo GetLoginInfo() + { + var di = GetNodeInfo(); + var ext = new LoginInfo + { + Code = Code, + Secret = Secret.IsNullOrEmpty() ? null : Secret.MD5(), + + Node = di, + }; + + return ext; + } + + private readonly Task _task; + /// 获取设备信息 + /// + public NodeInfo GetNodeInfo() + { + var mi = MachineInfo.Current ?? _task.Result; + + var asm = AssemblyX.Entry ?? AssemblyX.Create(Assembly.GetExecutingAssembly()); + //var ps = System.IO.Ports.SerialPort.GetPortNames(); + var mcs = NetHelper.GetMacs().Select(e => e.ToHex("-")).OrderBy(e => e).Join(","); + var driveInfo = new DriveInfo(Path.GetPathRoot(".".GetFullPath())); + var di = new NodeInfo + { + Version = asm?.FileVersion, + Compile = asm?.Compile ?? DateTime.MinValue, + + OSName = mi.OSName, + OSVersion = mi.OSVersion, + + MachineName = Environment.MachineName, + UserName = Environment.UserName, + IP = NetHelper.GetIPsWithCache().Where(ip => ip.IsIPv4() && !IPAddress.IsLoopback(ip) && ip.GetAddressBytes()[0] != 169).Join(), + + ProcessorCount = Environment.ProcessorCount, + Memory = mi.Memory, + AvailableMemory = mi.AvailableMemory, + TotalSize = (UInt64)driveInfo.TotalSize, + AvailableFreeSpace = (UInt64)driveInfo.AvailableFreeSpace, + + Processor = mi.Processor, + CpuID = mi.CpuID, + CpuRate = mi.CpuRate, + UUID = mi.UUID, + MachineGuid = mi.Guid, + DiskID = mi.DiskID, + + Macs = mcs, + //COMs = ps.Join(","), + + InstallPath = ".".GetFullPath(), + Runtime = Environment.Version + "", + + Time = DateTime.UtcNow, + }; + +#if !__CORE__ + try + { + // 收集屏幕相关信息。Mono+Linux无法获取 + var g = System.Drawing.Graphics.FromHwnd(IntPtr.Zero); + di.Dpi = $"{g.DpiX}*{g.DpiY}"; + var screen = System.Windows.Forms.Screen.PrimaryScreen; + di.Resolution = $"{screen.Bounds.Width}*{screen.Bounds.Height}"; + } + catch { } +#endif + + return di; + } + + /// 注销 + /// + /// + public async Task Logout(String reason) + { + if (!Logined) return null; + + XTrace.WriteLine("注销:{0} {1}", Code, reason); + + try + { + var rs = await LogoutAsync(reason); + if (rs != null) + { + // 更新令牌 + Token = rs.Token; + } + + _timer.TryDispose(); + _timer = null; + + Logined = false; + + return rs; + } + catch (Exception ex) + { + XTrace.WriteException(ex); + + return null; + } + } + + /// 登录 + /// 登录信息 + /// + private async Task LoginAsync(LoginInfo inf) => await PostAsync("Node/Login", inf); + + /// 注销 + /// + private async Task LogoutAsync(String reason) => await GetAsync("Node/Logout", new { reason }); + #endregion + + #region 心跳报告 + private readonly String[] _excludes = new[] { "Idle", "System", "Registry", "smss", "csrss", "lsass", "wininit", "services", "winlogon", "fontdrvhost", "dwm", "svchost", "dllhost", "conhost", "taskhostw", "explorer", "ctfmon", "ChsIME", "WmiPrvSE", "WUDFHost", "igfxCUIServiceN", "igfxEMN", "sihost", "RuntimeBroker", "StartMenuExperienceHost", "SecurityHealthSystray", "SecurityHealthService", "ShellExperienceHost", "PerfWatson2", "audiodg" }; + + /// 获取心跳信息 + public PingInfo GetHeartInfo() + { + var ps = Process.GetProcesses(); + var pcs = new List(); + foreach (var item in ps) + { + // 有些进程可能已退出,无法获取详细信息 + try + { + var name = item.ProcessName; + if (name.EqualIgnoreCase(_excludes)) continue; + + // 特殊处理dotnet + if (name == "dotnet") name = AppInfo.GetProcessName(item); + + if (!pcs.Contains(name)) pcs.Add(name); + } + catch { } + } + + var mi = MachineInfo.Current ?? _task.Result; + mi.Refresh(); + + var properties = IPGlobalProperties.GetIPGlobalProperties(); + var connections = properties.GetActiveTcpConnections(); + + var mcs = NetHelper.GetMacs().Select(e => e.ToHex("-")).OrderBy(e => e).Join(","); + var driveInfo = new DriveInfo(Path.GetPathRoot(".".GetFullPath())); + var ext = new PingInfo + { + AvailableMemory = mi.AvailableMemory, + AvailableFreeSpace = (UInt64)driveInfo.AvailableFreeSpace, + CpuRate = mi.CpuRate, + Temperature = mi.Temperature, + Battery = mi.Battery, + ProcessCount = ps.Length, + TcpConnections = connections.Count(e => e.State == TcpState.Established), + TcpTimeWait = connections.Count(e => e.State == TcpState.TimeWait), + TcpCloseWait = connections.Count(e => e.State == TcpState.CloseWait), + Uptime = Environment.TickCount / 1000, + + Macs = mcs, + //COMs = ps.Join(","), + + Processes = pcs.Join(), + + Time = DateTime.UtcNow.ToLong(), + Delay = Delay, + }; +#if __CORE__ + //ext.Uptime = Environment.TickCount64 / 1000; +#endif + // 开始时间 Environment.TickCount 很容易溢出,导致开机24天后变成负数。 + // 后来在 netcore3.0 增加了Environment.TickCount64 + // 现在借助 Stopwatch 来解决 + if (Stopwatch.IsHighResolution) ext.Uptime = (Int32)(Stopwatch.GetTimestamp() / Stopwatch.Frequency); + + return ext; + } + + private TimerX _timer; + /// 心跳 + /// + public async Task Ping() + { + try + { + var inf = GetHeartInfo(); + + var rs = await PingAsync(inf); + if (rs != null) + { + // 由服务器改变采样频率 + if (rs.Period > 0) _timer.Period = rs.Period * 1000; + + var dt = rs.Time.ToDateTime(); + if (dt.Year > 2000) + { + // 计算延迟 + var ts = DateTime.UtcNow - dt; + var ms = (Int32)ts.TotalMilliseconds; + if (Delay > 0) + Delay = (Delay + ms) / 2; + else + Delay = ms; + } + + // 推队列 + if (rs.Commands != null && rs.Commands.Length > 0) + { + foreach (var item in rs.Commands) + { + CommandQueue.Publish(item.Command, item); + } + } + } + + return rs; + } + catch (Exception ex) + { + var ex2 = ex.GetTrue(); + if (ex2 is ApiException aex && (aex.Code == 402 || aex.Code == 403)) + { + XTrace.WriteLine("重新登录"); + return Login(); + } + + //XTrace.WriteLine(inf.ToJson()); + XTrace.WriteLine("心跳异常 {0}", (String)ex.GetTrue().Message); + + throw; + } + } + + /// 心跳 + /// + /// + private async Task PingAsync(PingInfo inf) => await PostAsync("Node/Ping", inf); + + private TraceService _trace; + /// 使用追踪服务 + public void UseTrace() + { + _trace = new TraceService + { + Queue = CommandQueue, + Callback = (id, data) => ReportAsync(id, data).Wait(), + }; + _trace.Init(); + } + + /// 上报命令结果,如截屏、抓日志 + /// + /// + /// + private async Task ReportAsync(Int32 id, Byte[] data) => await PostAsync("Device/Report?Id=" + id, data); + #endregion + + #region 更新 + /// 获取更新信息 + /// + /// + public async Task Upgrade(String channel) + { + XTrace.WriteLine("检查更新:{0}", channel); + + // 清理 + var ug = new Upgrade { Log = XTrace.Log }; + ug.DeleteBackup("."); + + var rs = await UpgradeAsync(channel); + if (rs != null) + { + XTrace.WriteLine("发现更新:{0}", rs.ToJson(true)); + } + + return rs; + } + + /// 执行更新 + /// + /// + public Boolean ProcessUpgrade(UpgradeInfo ur) + { + XTrace.WriteLine("执行更新:{0} {1}", ur.Version, ur.Source); + + var dest = "."; + var url = ur.Source; + + try + { + // 需要下载更新包 + if (!url.IsNullOrEmpty()) + { + var fileName = Path.GetFileName(url); + if (!fileName.EndsWithIgnoreCase(".zip")) fileName = Rand.NextString(8) + ".zip"; + fileName = "Update".CombinePath(fileName).EnsureDirectory(true); + + // 清理 + //NewLife.Net.Upgrade.DeleteBuckup(dest); + var ug = new Upgrade { Log = XTrace.Log }; + ug.DeleteBackup(dest); + + // 下载 + var sw = Stopwatch.StartNew(); + var client = new HttpClient(); + client.DownloadFileAsync(url, fileName).Wait(); + + sw.Stop(); + XTrace.WriteLine("下载 {0} 到 {1} 完成,耗时 {2} 。", url, fileName, sw.Elapsed); + + // 解压 + var source = fileName.TrimEnd(".zip"); + if (Directory.Exists(source)) Directory.Delete(source, true); + source.EnsureDirectory(false); + fileName.AsFile().Extract(source, true); + + // 覆盖 + ug.CopyAndReplace(source, dest); + if (Directory.Exists(source)) Directory.Delete(source, true); + } + + // 升级处理命令,可选 + var cmd = ur.Executor?.Trim(); + if (!cmd.IsNullOrEmpty()) + { + XTrace.WriteLine("执行更新命令:{0}", cmd); + + var si = new ProcessStartInfo + { + UseShellExecute = true, + }; + var p = cmd.IndexOf(' '); + if (p < 0) + si.FileName = cmd; + else + { + si.FileName = cmd.Substring(0, p); + si.Arguments = cmd.Substring(p + 1); + } + + Process.Start(si); + } + + return true; + } + catch (Exception ex) + { + XTrace.WriteLine("更新失败!"); + XTrace.WriteException(ex); + + return false; + } + } + + /// 更新 + /// + /// + public async Task UpgradeAsync(String channel) => await GetAsync("Node/Upgrade", new { channel }); + #endregion + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `cmd` last assigned on line 508 could be null and is dereferenced at line 496, column 21. + +### Severity: +ERROR + +### Procedure: +Boolean StarClient.ProcessUpgrade(UpgradeInfo) + +### File: +Stardust/StarClient.cs + +### Key: +StarClient.cs|ProcessUpgrade|NULL_DEREFERENCE + +### Node Key: +8f23c407fab7524e0704ad6f3b90d75b + +### Hash: +491510d76f89d54db3b095a4a2964872 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1220/instruction.md b/inferredbugs-1220/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9a76bf2ec12972d56047d4cb6ac152adc394ac3a --- /dev/null +++ b/inferredbugs-1220/instruction.md @@ -0,0 +1,394 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Stardust +**Bug ID:** 8 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; +using NewLife; +using NewLife.Caching; +using NewLife.Log; +using NewLife.Serialization; +using NewLife.Threading; +using Stardust.Data.Models; +using Stardust.Data.Nodes; + +namespace Stardust.Server.Services +{ + public interface IRedisService + { + void TraceNode(RedisNode node); + + void TraceQueue(RedisMessageQueue queue); + } + + public class RedisService : IHostedService, IRedisService + { + /// 计算周期。默认60秒 + public Int32 Period { get; set; } = 60; + + private TimerX _traceNode; + private TimerX _traceQueue; + private readonly ICache _cache = new MemoryCache(); + private readonly ITracer _tracer; + + public RedisService(ITracer tracer) => _tracer = tracer; + + public Task StartAsync(CancellationToken cancellationToken) + { + // 初始化定时器 + _traceNode = new TimerX(DoTraceNode, null, 5_000, Period * 1000) { Async = true }; + _traceQueue = new TimerX(DoTraceQueue, null, 10_000, Period * 1000) { Async = true }; + + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) + { + _traceNode?.TryDispose(); + _traceQueue?.TryDispose(); + + return Task.CompletedTask; + } + + private void DoTraceNode(Object state) + { + var list = RedisNode.FindAllWithCache(); + foreach (var item in list) + { + if (item.Enable) + { + // 捕获异常,不要影响后续操作 + var key = $"DoTraceNode:{item.Id}"; + var errors = _cache.Get(key); + if (errors < 5) + { + try + { + TraceNode(item); + + _cache.Remove(key); + } + catch (Exception ex) + { + errors = _cache.Increment(key, 1); + if (errors <= 1) + _cache.SetExpire(key, TimeSpan.FromMinutes(10)); + + XTrace.WriteException(ex); + } + } + else + { + item.Enable = false; + item.SaveAsync(); + + _cache.Remove(key); + } + } + } + } + + private readonly IDictionary _servers = new Dictionary(); + private readonly IDictionary _servers2 = new Dictionary(); + + private FullRedis GetOrAdd(RedisNode node, Int32 db) + { + var key = $"{node.Id}-{db}"; + if (!_servers2.TryGetValue(key, out var rds)) _servers2[key] = rds = new FullRedis(); + + rds.Server = node.Server; + rds.Password = node.Password; + rds.Db = db; + rds.Tracer = _tracer; + + return rds; + } + + public void TraceNode(RedisNode node) + { + using var span = _tracer?.NewSpan($"RedisService-TraceNode", node); + + if (!_servers.TryGetValue(node.Id, out var rds)) _servers[node.Id] = rds = new FullRedis(); + + // 可能后面更新了服务器地址和密码 + rds.Server = node.Server; + rds.Password = node.Password; + rds.Tracer = _tracer; + + //var inf = rds.GetInfo(true); + var inf = rds.GetInfo(false); + node.Fill(inf); + node.SaveAsync(); + + var data = new RedisData + { + RedisId = node.Id, + Name = node.Name, + }; + var dbs = data.Fill(inf); + data.Insert(); + + // 扫描队列 + if (node.ScanQueue && dbs != null) ScanQueue(node, dbs); + } + + private void ScanQueue(RedisNode node, RedisDbEntry[] dbs) + { + var queues = RedisMessageQueue.FindAllByRedisId(node.Id); + + for (var i = 0; i < dbs.Length; i++) + { + if (dbs[i] == null) continue; + + var rds2 = GetOrAdd(node, i); + + // keys个数太大不支持扫描 + if (rds2.Count < 10000) + { + foreach (var item in rds2.Search("*:Status:*", 1000)) + { + var ss = item.Split(":"); + var topic = ss.Take(ss.Length - 2).Join(":"); + if (topic.IsNullOrEmpty()) continue; + + // 可信队列 + { + SaveQueue(node, i, queues, topic); + } + + // 延迟队列 + { + topic += ":Delay"; + if (rds2.ContainsKey(topic)) SaveQueue(node, i, queues, topic); + } + } + } + } + } + + private void SaveQueue(RedisNode node, Int32 i, IList queues, String topic) + { + var mq = queues.FirstOrDefault(e => e.Db == i && e.Topic == topic); + if (mq == null) + { + mq = new RedisMessageQueue + { + RedisId = node.Id, + Db = i, + Topic = topic, + Enable = true, + }; + + queues.Add(mq); + } + + mq.Enable = true; + if (mq.Name.IsNullOrEmpty()) mq.Name = topic; + if (mq.Category.IsNullOrEmpty()) mq.Category = node.Category; + if (mq.Type.IsNullOrEmpty()) + { + mq.Type = topic.EndsWithIgnoreCase(":Delay") ? "Delay" : "Queue"; + } + + mq.SaveAsync(); + } + + private void DoTraceQueue(Object state) + { + var list = RedisMessageQueue.FindAll(); + foreach (var item in list) + { + if (item.Enable && item.Redis != null) + { + // 捕获异常,不要影响后续操作 + var key = $"DoTraceQueue:{item.Id}"; + var errors = _cache.Get(key); + if (errors < 5) + { + try + { + TraceQueue(item); + + _cache.Remove(key); + } + catch (Exception ex) + { + errors = _cache.Increment(key, 1); + if (errors <= 1) + _cache.SetExpire(key, TimeSpan.FromMinutes(10)); + + XTrace.WriteException(ex); + } + } + else + { + item.Enable = false; + + _cache.Remove(key); + } + + item.SaveAsync(); + } + } + } + + public void TraceQueue(RedisMessageQueue queue) + { + if (queue.Topic.IsNullOrEmpty()) return; + + using var span = _tracer?.NewSpan($"RedisService-TraceQueue", queue); + + var rds = GetOrAdd(queue.Redis, queue.Db); + + switch (queue.Type?.ToLower()) + { + case "queue": + { + var mq = rds.GetQueue(queue.Topic); + queue.Messages = mq.Count; + + var cs = rds.Search($"{queue.Topic}:Status:*", 1000).ToArray(); + queue.Consumers = cs.Length; + + if (cs.Length > 0) + { + var sts = rds.GetAll(cs); + if (sts != null) + { + queue.Total = sts.Sum(e => e.Value.Consumes); + queue.FirstConsumer = sts.Min(e => e.Value.CreateTime); + queue.LastActive = sts.Max(e => e.Value.LastActive); + queue.Remark = sts.ToJson(); + } + } + else + { + queue.Enable = false; + } + } + break; + case "delay": + { + var mq = rds.GetDelayQueue(queue.Topic); + queue.Messages = mq.Count; + + var topic = queue.Topic.TrimEnd(":Delay"); + //var st = rds.Get(topic); + + var cs = rds.Search($"{topic}:Status:*", 1000).ToArray(); + queue.Consumers = cs.Length; + + if (cs.Length > 0) + { + var sts = rds.GetAll(cs); + if (sts != null) + { + queue.Total = sts.Sum(e => e.Value.Consumes); + queue.FirstConsumer = sts.Min(e => e.Value.CreateTime); + queue.LastActive = sts.Max(e => e.Value.LastActive); + queue.Remark = sts.ToJson(); + } + } + else + { + queue.Enable = false; + } + } + break; + case "stream": + { + var mq = rds.GetStream(queue.Topic); + //queue.Messages = mq.Count; + queue.Total = mq.Count; + + var gs = mq.GetGroups(); + if (gs != null) + { + queue.Consumers = gs.Sum(e => e.Consumers); + //queue.Remark = gs.ToJson(); + } + + var inf = mq.GetInfo(); + if (inf != null) + { + if (!inf.FirstId.IsNullOrEmpty()) + { + var p = inf.FirstId.IndexOf('-'); + var str = p > 0 ? inf.FirstId[..p] : inf.FirstId; + queue.FirstConsumer = str.ToLong().ToDateTime().ToLocalTime(); + } + if (!inf.LastId.IsNullOrEmpty()) + { + var p = inf.LastId.IndexOf('-'); + var str = p > 0 ? inf.LastId[..p] : inf.LastId; + queue.LastActive = str.ToLong().ToDateTime().ToLocalTime(); + } + + queue.Remark = inf.ToJson(); + } + } + break; + default: + break; + } + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource rds of type NewLife.Caching.FullRedis in method "Void RedisService.TraceNode(RedisNode)". + +### Severity: +ERROR + +### Procedure: +Void RedisService.TraceNode(RedisNode) + +### File: +Stardust.Server/Services/RedisService.cs + +### Key: +RedisService.cs|TraceNode|DOTNET_RESOURCE_LEAK + +### Hash: +8f4226a93118c3985743168503720ebf + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1227/instruction.md b/inferredbugs-1227/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a670f668bc79b6c4e2603fc364a98213780c077f --- /dev/null +++ b/inferredbugs-1227/instruction.md @@ -0,0 +1,84 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** DefaultDocumentation +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using DefaultDocumentation.Markdown.Extensions; +using DefaultDocumentation.Model; +using DefaultDocumentation.Model.Parameter; +using DefaultDocumentation.Writers; + +namespace DefaultDocumentation.Markdown.Sections +{ + public sealed class SummarySection : ISectionWriter + { + public string Name => "summary"; + + public void Write(IWriter writer) + { + writer + .EnsureLineStart() + .AppendLine() + .AppendAsMarkdown(writer.GetCurrentItem() switch + { + TypeParameterDocItem item => item.Documentation, + ParameterDocItem item => item.Documentation, + DocItem item => item.Documentation?.Element(Name) + }); + } + } +} + +``` + +### Bug Type: +PULSE_UNINITIALIZED_VALUE + +### Qualifier: +`%4` is read without initialization. + +### Severity: +ERROR + +### Procedure: +Void SummarySection.Write(IWriter) + +### File: +source/DefaultDocumentation.Markdown/Sections/SummarySection.cs + +### Key: +SummarySection.cs|Write|PULSE_UNINITIALIZED_VALUE + +### Hash: +5c2e4c5669940d1735a7ba7ed519fade + +### Bug Type Hum: +Uninitialized Value + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1229/instruction.md b/inferredbugs-1229/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4b2ecc84ce44acb7f21d955d7f1040b81c4deb8e --- /dev/null +++ b/inferredbugs-1229/instruction.md @@ -0,0 +1,892 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** WebSharp +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.ComponentModel; + +namespace PepperSharp +{ + public partial class Instance : NativeInstance + { + protected Instance() { throw new PlatformNotSupportedException("Can not create an instace of PPInstance"); } + protected Instance(IntPtr handle) : base(handle) { } + + /// + /// Event when the view information for the Instance has changed. + /// + public event EventHandler ViewChanged; + + /// + /// Event when an instance has gained or lost focus. + /// + public event EventHandler FocusChanged; + + /// + /// Event when the browser calls PostMessage() on the DOM element for the instance in JavaScript. + /// + public event EventHandler HandleMessage; + + /// + /// Event when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript. + /// + public event EventHandler InputEvents; + + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a MouseDown InputEvent. + /// + public event EventHandler MouseDown; + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a MouseUp InputEvent. + /// + public event EventHandler MouseUp; + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a MouseEnter InputEvent. + /// + public event EventHandler MouseEnter; + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a MouseLeave InputEvent. + /// + public event EventHandler MouseLeave; + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a MouseMove InputEvent. + /// + public event EventHandler MouseMove; + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a ContextMenu InputEvent. + /// + public event EventHandler ContextMenu; + + public class MouseEventArgs : EventArgs + { + public PPInputEventMouseButton Buttons { get; private set; } + public int Clicks { get; private set; } + public PPPoint Position { get; private set; } + public PPPoint Movement { get; private set; } + public double TimeStamp { get; private set; } + public PPInputEventModifier Modifiers { get; private set; } + public bool Handled { get; set; } = false; + public bool IsContextMenu { get; private set; } = false; + + public MouseEventArgs(PPInputEventMouseButton buttons, int clicks, PPPoint position, PPPoint movement, double timeStamp, PPInputEventModifier modifiers, bool isContextMenu = false ) + { + Buttons = buttons; + Clicks = clicks; + Position = position; + Movement = movement; + TimeStamp = timeStamp; + Modifiers = modifiers; + IsContextMenu = isContextMenu; + } + + } + + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a Wheel InputEvent. + /// + public event EventHandler Wheel; + + public class WheelEventArgs : EventArgs + { + public PPFloatPoint Delta { get; private set; } + public PPFloatPoint Ticks { get; private set; } + public bool IsScrollByPage { get; private set; } + public double TimeStamp { get; private set; } + public PPInputEventModifier Modifiers { get; private set; } + public bool Handled { get; set; } = false; + + public WheelEventArgs(PPFloatPoint delta, PPFloatPoint ticks, bool isScrollByPage, double timeStamp, PPInputEventModifier modifiers) + { + Delta = delta; + Ticks = ticks; + IsScrollByPage = isScrollByPage; + TimeStamp = timeStamp; + Modifiers = modifiers; + } + + } + + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a KeyboardInputEvent for KeyUp. + /// + public event EventHandler KeyUp; + + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a KeyboardInputEvent for KeyDown. + /// + public event EventHandler KeyDown; + + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a KeyboardInputEvent for Char. + /// + public event EventHandler KeyChar; + + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a KeyboardInputEvent for RawKeydown. + /// + public event EventHandler RawKeyDown; + + + public class KeyboardEventArgs : EventArgs + { + public uint KeyCode{ get; private set; } + public string CharacterText { get; private set; } + public string Code { get; private set; } + public double TimeStamp { get; private set; } + public PPInputEventModifier Modifiers { get; private set; } + public bool Handled { get; set; } = false; + + public KeyboardEventArgs(uint keyCode, string text, string code, double timeStamp, PPInputEventModifier modifiers) + { + KeyCode = keyCode; + CharacterText = text; + Code = code; + TimeStamp = timeStamp; + Modifiers = modifiers; + } + + } + + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a TouchInputEvent for TouchStart. + /// + public event EventHandler TouchStart; + + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a TouchInputEvent for TouchEnd. + /// + public event EventHandler TouchEnd; + + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a TouchInputEvent for TouchCancel. + /// + public event EventHandler TouchCancel; + + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a TouchInputEvent for TouchMove. + /// + public event EventHandler TouchMove; + + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a IMEInputEvent for CompositionEnd. + /// + public event EventHandler IMECompositionEnd; + + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a IMEInputEvent for CompositionStart. + /// + public event EventHandler IMECompositionStart; + + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a IMEInputEvent for CompositionUpdate. + /// + public event EventHandler IMECompositionUpdate; + + /// + /// Event raised when the browser calls HandleInputEvent on the DOM element for the instance in JavaScript + /// that represents a IMEInputEvent for Text. + /// + public event EventHandler IMEText; + + // Custom class to hold Initialize Cancelable Event event info + public class InitializeEventArgs : CancelEventArgs + { + public int Count { get; private set; } + public string[] Names { get; private set; } + public string[] Values { get; private set; } + + internal InitializeEventArgs(int argc, string[] argn, string[] argv) + { + Count = argc; + Names = argn; + Values = argv; + Cancel = false; + } + } + + /// + /// Event when the browser calls PostMessage() on the DOM element for the instance in JavaScript. + /// + public delegate void InitializeDelegateAndHandler(object sender, InitializeEventArgs args); + public event InitializeDelegateAndHandler Initialize; + + /// + /// Raise event to intialize the instance with the provided arguments. This + /// event will be raised immediately after the instance object is constructed. + /// + /// + /// The OnInitialize method also enables derived classes to handle the event without attaching + /// a delegate. This is the preferred technique for handling the event in a derived class. + /// + /// An instance of InitializeEventArgs that is cancelable + /// true if the event was not canceled and falce if the event was canceled for some reason. + protected virtual bool OnInitialize(InitializeEventArgs args) + { + var handler = Initialize; + if (handler != null) + { + bool cancel = false; + foreach (InitializeDelegateAndHandler subscriber in handler.GetInvocationList()) + { + subscriber.Invoke(this, args); + if (args.Cancel) + { + cancel = true; + break; + } + } + + return !cancel; + } + + return true; + } + + /// + /// This is the entry point of the Init call that just passes the information on to the event handler + /// + bool Init(int argc, string[] argn, string[] argv) + => OnInitialize(new InitializeEventArgs(argc, argn, argv)); + + /// + /// Raises the ViewChange event when the view information for the Instance + /// has changed. See the View object for information. + /// + /// Most implementations will want to check if the size and user visibility + /// changed, and either resize themselves or start/stop generating updates. + /// + /// + /// The OnViewChanged method also enables derived classes to handle the event without attaching + /// a delegate. This is the preferred technique for handling the event in a derived class. + /// + /// The view object that contains the new view properties + protected virtual void OnViewChanged(View view) + => ViewChanged?.Invoke(this, view); + + /// + /// Raises the FocusChanged event when an instance has gained or lost focus. + /// + /// Having focus means that keyboard events will be sent to the instance. An instance's default + /// condition is that it will not have focus. + /// + /// The focus flag takes into account both browser tab and window focus as well as focus of the plugin + /// element on the page. In order to be deemed to have focus, the browser window must be topmost, + /// the tab must be selected in the window, and the instance must be the focused element on the page. + /// + /// Note:Clicks on instances will give focus only if you handle the click event. + /// Return true from HandleInputEvent in InputEvent (or use unfiltered events) to signal that the + /// click event was handled. Otherwise, the browser will bubble the event and give focus to the element + /// on the page that actually did end up consuming it.If you're not getting focus, check to make sure + /// you're either requesting them via RequestInputEvents() (which implicitly marks all input events as + /// consumed) or via RequestFilteringInputEvents() and returning true from your event handler. + /// + /// + /// The OnFocusChanged method also enables derived classes to handle the event without attaching + /// a delegate. This is the preferred technique for handling the event in a derived class. + /// + /// Indicates the new focused state of the instance. + /// + protected virtual void OnFocusChanged(bool hasFocus) + => FocusChanged?.Invoke(this, hasFocus); + + /// + /// Raises the HandleInput event from the browser. + /// + /// The default implementation does nothing and returns false. + /// + /// In order to receive input events, you must register for them by calling RequestInputEvents() or + /// RequestFilteringInputEvents(). By default, no events are delivered. + /// + /// If the event was handled, it will not be forwarded to any default handlers.If it was not handled, + /// it may be dispatched to a default handler.So it is important that an instance respond accurately + /// with whether event propagation should continue. + /// + /// Event propagation also controls focus.If you handle an event like a mouse event, typically the + /// instance will be given focus. Returning false from a filtered event handler or not registering for + /// an event type means that the click will be given to a lower part of the page and your instance + /// will not receive focus.This allows an instance to be partially transparent, where clicks on the + /// transparent areas will behave like clicks to the underlying page. + /// + /// In general, you should try to keep input event handling short. Especially for filtered input events, + /// the browser or page may be blocked waiting for you to respond. + /// + /// The caller of this function will maintain a reference to the input event resource during this call. + /// Unless you take a reference to the resource to hold it for later, you don't need to release it. + /// + /// Note: If you're not receiving input events, make sure you register for the event classes you want + /// by calling RequestInputEvents or RequestFilteringInputEvents. If you're still not receiving + /// keyboard input events, make sure you're returning true (or using a non-filtered event handler) for + /// mouse events. Otherwise, the instance will not receive focus and keyboard events will not be sent. + /// + /// Refer to RequestInputEvents and RequestFilteringInputEvents for further information. + /// + /// + /// The OnInputEvents method also enables derived classes to handle the event without attaching + /// a delegate. This is the preferred technique for handling the event in a derived class. + /// + /// The event to handle. + /// true if the event was handled, false if not. If you have registered to filter this class of events by calling RequestFilteringInputEvents, and you return false, the event will be forwarded to the page (and eventually the browser) for the default handling. For non-filtered events, the return value will be ignored. + protected virtual bool OnInputEvents (InputEvent inputEvent) + { + + bool handled = false; + if (inputEvent is MouseInputEvent) + { + var mie = (MouseInputEvent)inputEvent; + var mieArgs = new MouseEventArgs(mie.Button, mie.ClickCount, mie.Position, mie.Movement, mie.TimeStamp, mie.Modifiers, inputEvent.EventType == PPInputEventType.Contextmenu); + switch (mie.EventType) + { + case PPInputEventType.Mousedown: + handled = OnMouseDown(mieArgs); + break; + case PPInputEventType.Mouseup: + handled = OnMouseUp(mieArgs); + break; + case PPInputEventType.Mouseenter: + handled = OnMouseEnter(mieArgs); + break; + case PPInputEventType.Mouseleave: + handled = OnMouseLeave(mieArgs); + break; + case PPInputEventType.Mousemove: + handled = OnMouseMove(mieArgs); + break; + case PPInputEventType.Contextmenu: + handled = OnContextMenu(mieArgs); + break; + } + inputEvent.Handled = handled; + } + else if (inputEvent is WheelInputEvent) + { + var wie = (WheelInputEvent)inputEvent; + var wieArgs = new WheelEventArgs(wie.Delta, wie.Ticks, wie.IsScrollByPage, wie.TimeStamp, wie.Modifiers); + handled = OnWheel(wieArgs); + inputEvent.Handled = handled; + } + else if (inputEvent is KeyboardInputEvent) + { + var kbie = (KeyboardInputEvent)inputEvent; + var kbieArgs = new KeyboardEventArgs(kbie.KeyCode, kbie.CharacterText, kbie.Code, kbie.TimeStamp, kbie.Modifiers); + switch (kbie.EventType) + { + case PPInputEventType.Keyup: + handled = OnKeyUp(kbieArgs); + break; + case PPInputEventType.Keydown: + handled = OnKeyDown(kbieArgs); + break; + case PPInputEventType.Char: + handled = OnKeyChar(kbieArgs); + break; + case PPInputEventType.Rawkeydown: + handled = OnRawKeyDown(kbieArgs); + break; + } + inputEvent.Handled = handled; + } + else if (inputEvent is TouchInputEvent) + { + var tie = (TouchInputEvent)inputEvent; + switch (tie.EventType) + { + case PPInputEventType.Touchstart: + handled = OnTouchStart(tie); + break; + case PPInputEventType.Touchend: + handled = OnTouchEnd(tie); + break; + case PPInputEventType.Touchmove: + handled = OnTouchMove(tie); + break; + case PPInputEventType.Touchcancel: + handled = OnTouchCancel(tie); + break; + } + inputEvent.Handled = handled; + } + else if (inputEvent is IMEInputEvent) + { + var imeie = (IMEInputEvent)inputEvent; + switch (imeie.EventType) + { + case PPInputEventType.ImeCompositionEnd: + handled = OnIMECompositionEnd(imeie); + break; + case PPInputEventType.ImeCompositionStart: + handled = OnIMECompositionStart(imeie); + break; + case PPInputEventType.ImeCompositionUpdate: + handled = OnIMECompositionUpdate(imeie); + break; + case PPInputEventType.ImeText: + handled = OnIMEText(imeie); + break; + } + inputEvent.Handled = handled; + } + + var handler = InputEvents; + if (handler != null) + { + foreach (EventHandler subscriber in handler.GetInvocationList()) + { + subscriber.Invoke(this, inputEvent); + if (inputEvent.Handled) + { + handled = true; + } + } + } + + return handled; + } + + protected virtual bool OnMouseDown(MouseEventArgs e) + { + MouseDown?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnMouseUp(MouseEventArgs e) + { + MouseUp?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnMouseEnter(MouseEventArgs e) + { + MouseEnter?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnMouseLeave(MouseEventArgs e) + { + MouseLeave?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnMouseMove (MouseEventArgs e) + { + MouseMove?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnContextMenu(MouseEventArgs e) + { + ContextMenu?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnWheel (WheelEventArgs e) + { + Wheel?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnKeyUp(KeyboardEventArgs e) + { + KeyUp?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnKeyDown(KeyboardEventArgs e) + { + KeyDown?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnKeyChar(KeyboardEventArgs e) + { + KeyChar?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnRawKeyDown(KeyboardEventArgs e) + { + RawKeyDown?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnTouchStart(TouchInputEvent e) + { + TouchStart?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnTouchEnd(TouchInputEvent e) + { + TouchEnd?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnTouchCancel(TouchInputEvent e) + { + TouchCancel?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnTouchMove(TouchInputEvent e) + { + TouchMove?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnIMECompositionStart(IMEInputEvent e) + { + IMECompositionStart?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnIMECompositionEnd(IMEInputEvent e) + { + IMECompositionEnd?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnIMECompositionUpdate(IMEInputEvent e) + { + IMECompositionUpdate?.Invoke(this, e); + return e.Handled; + } + + protected virtual bool OnIMEText(IMEInputEvent e) + { + IMEText?.Invoke(this, e); + return e.Handled; + } + + public virtual bool HandleDocumentLoad(PPResource urlLoader) + { + return false; + } + + /// + /// Raises the HandleMessage event when the browser calls PostMessage() on the DOM element for + /// the instance in JavaScript. + /// + /// Note that PostMessage() in the JavaScript interface is asynchronous, meaning JavaScript execution + /// will not be blocked while OnRecieveMessage is processing the message. + /// + /// When converting JavaScript arrays, any object properties whose name is not an array index are + /// ignored. When passing arrays and objects, the entire reference graph will be converted and + /// transferred. If the reference graph has cycles, the message will not be sent and an error will + /// be logged to the console. + /// + /// + /// The OnHandleMessage method also enables derived classes to handle the event without attaching + /// a delegate. This is the preferred technique for handling the event in a derived class. + /// + /// A Var which has been converted from a JavaScript value. JavaScript + /// array/object types are supported from Chrome M29 onward. All JavaScript values are copied + /// when passing them to the plugin. + /// + protected virtual void OnHandleMessage(Var message) + => HandleMessage?.Invoke(this, message); + + /// + /// BindGraphics() binds the given graphics as the current display surface. + /// + /// The contents of this device is what will be displayed in the instance's area on the web page. + /// The device must be a 2D or a 3D device. + /// + /// You can pass an is_null() (default constructed) Graphics2D as the device parameter to unbind all + /// devices from the given instance. The instance will then appear transparent. Re-binding the same + /// device will return true and will do nothing. + /// + /// Any previously-bound device will be released. It is an error to bind a device when it is already + /// bound to another instance. If you want to move a device between instances, first unbind it from + /// the old one, and then rebind it to the new one. + /// + /// Binding a device will invalidate that portion of the web page to flush the contents of the new + /// device to the screen. + /// + /// A Graphics2D to bind + /// true if bind was successful or false if the device was not the correct type. On success, a reference to the device will be held by the instance, so the caller can release its reference if it chooses. + public bool BindGraphics(PPResource graphics2d) + => PPBInstance.BindGraphics(this, graphics2d) == PPBool.True ? true : false; + + /// + /// asynchronously invokes any listeners for message events on the DOM element for the given instance. + /// + /// + public void PostMessage(object message) + { + if (message is Var) + PPBMessaging.PostMessage(this, (Var)message); + else + PPBMessaging.PostMessage(this, new Var(message)); + } + + PPInstance instance = new PPInstance(); + public PPInstance PPInstance + { + get + { + if (instance.ppinstance == 0) + { + instance.ppinstance = this.Handle.ToInt32(); + } + return instance; + } + } + + public static implicit operator PPInstance(Instance instance) + { + return instance.PPInstance; + } + + public void LogToConsole(PPLogLevel level, object value) + { + if (value is Var) + PPBConsole.Log(this, level, (Var)value); + else + PPBConsole.Log(this, level, new Var(value)); + } + + public void LogToConsoleWithSource(PPLogLevel level, + string source, + object value) + { + if (value is Var) + PPBConsole.LogWithSource(this, level, new Var(source), (Var)value); + else + PPBConsole.LogWithSource(this, level, new Var(source), new Var(value)); + } + + /// + /// RequestInputEvents() requests that input events corresponding to the given input events are delivered to the instance. + /// + /// By default, no input events are delivered.Call this function with the classes of events you are + /// interested in to have them be delivered to the instance. Calling this function will override any + /// previous setting for each specified class of input events(for example, if you previously called + /// RequestFilteringInputEvents(), this function will set those events to non-filtering mode). + /// + /// Input events may have high overhead, so you should only request input events that your plugin will + /// actually handle.For example, the browser may do optimizations for scroll or touch events that can + /// be processed substantially faster if it knows there are no non-default receivers for that message. + /// Requesting that such messages be delivered, even if they are processed very quickly, may have a + /// noticeable effect on the performance of the page. + /// + /// When requesting input events through this function, the events will be delivered and not bubbled + /// to the page.This means that even if you aren't interested in the message, no other parts of the + /// page will get the message. + /// + /// A combination of flags from PP_InputEvent_Class that identifies the classes of events the instance is requesting. The flags are combined by logically ORing their values. + /// PP_OK if the operation succeeded, PP_ERROR_BADARGUMENT if instance is invalid, or PP_ERROR_NOTSUPPORTED if one of the event class bits were illegal. In the case of an invalid bit, all valid bits will be applied and only the illegal bits will be ignored. + public PPError RequestInputEvents(PPInputEventClass eventClasses) + => (PPError)PPBInputEvent.RequestInputEvents(this, (uint)eventClasses); + + /// + /// RequestFilteringInputEvents() requests that input events corresponding to the given input events + /// are delivered to the instance for filtering. + /// + /// By default, no input events are delivered.In most cases you would register to receive events by + /// calling RequestInputEvents(). In some cases, however, you may wish to filter events such that + /// they can be bubbled up to the DOM.In this case, register for those classes of events using this + /// function instead of RequestInputEvents(). Keyboard events must always be registered in filtering + /// mode. + /// + /// Filtering input events requires significantly more overhead than just delivering them to the + /// instance. As such, you should only request filtering in those cases where it's absolutely + /// necessary. The reason is that it requires the browser to stop and block for the instance to + /// handle the input event, rather than sending the input event asynchronously. This can have + /// significant overhead. + /// + /// A combination of flags from PP_InputEvent_Class that identifies the classes of events the instance is requesting. The flags are combined by logically ORing their values. + /// OK if the operation succeeded, BADARGUMENT if instance is invalid, or NOTSUPPORTED if + /// one of the event class bits were illegal. In the case of an invalid bit, all valid bits will be + /// applied and only the illegal bits will be ignored. + /// + public PPError RequestFilteringInputEvents(PPInputEventClass eventClasses) + => (PPError)PPBInputEvent.RequestFilteringInputEvents(this, (uint)eventClasses); + + /// + /// IsFullFrame() determines if the instance is full-frame (repr). + /// + /// Such an instance represents the entire document in a frame rather than an embedded resource. + /// This can happen if the user does a top-level navigation or the page specifies an iframe to a + /// resource with a MIME type registered by the module. + /// + public bool IsFullFrame + => PPBInstance.IsFullFrame(this) == PPBool.True ? true : false; + + /// + /// ClearInputEventRequest() requests that input events corresponding to the given input classes no longer be delivered to the instance. + /// + /// By default, no input events are delivered.If you have previously requested input events using + /// RequestInputEvents() or RequestFilteringInputEvents(), this function will unregister handling + /// for the given instance.This will allow greater browser performance for those events. + /// + /// Note: You may still get some input events after clearing the flag if they were dispatched before the request was cleared. For example, if there are 3 mouse move events waiting to be delivered, and you clear the mouse event class during the processing of the first one, you'll still receive the next two. You just won't get more events generated. + /// + /// A combination of flags from PP_InputEvent_Class that identifies the classes of events the instance is no longer interested in. + public void ClearInputEventRequest(PPInputEventClass eventClasses) + => PPBInputEvent.ClearInputEventRequest(this, (uint)eventClasses); + + /// + /// Sets the given mouse cursor. The mouse cursor will be in effect whenever + /// the mouse is over the given instance until it is set again by another + /// call. Note that you can hide the mouse cursor by setting it to the + /// PPMouseCursorType type. + /// + /// This function allows setting both system defined mouse cursors and + /// custom cursors. To set a system-defined cursor, pass the type you want + /// and set the custom image to a default-constructor ImageData object. + /// To set a custom cursor, set the type to + /// PPMouseCursorType.CUSTOM and specify your image and hot + /// spot. + /// + /// A PPMouseCursorType identifying the type + /// of mouse cursor to show. + /// + /// A ImageData object identifying the + /// custom image to set when the type is + /// PPMouseCursorType.CUSTOM. The image must be less than 32 + /// pixels in each direction and must be of the system's native image format. + /// When you are specifying a predefined cursor, this parameter should be a + /// default-constructed ImageData. + /// + /// When setting a custom cursor, this identifies the + /// pixel position within the given image of the "hot spot" of the cursor. + /// When specifying a stock cursor, this parameter is ignored. + /// + /// true on success, or false if the instance or cursor type + /// was invalid or if the image was too large. + public bool SetCursor(PPMouseCursorType type, ImageData imageData = null, PPPoint? hotSpot = null) + { + var hs = PPPoint.Zero; + if (hotSpot.HasValue) + hs = hotSpot.Value; + if (imageData == null) + return PPBMouseCursor.SetCursor(this, type, PPResource.Empty, hs) == PPBool.True ? true : false; + else + return PPBMouseCursor.SetCursor(this, type, imageData, hs) == PPBool.True ? true : false; + } + + /// + /// Getter and Setter that checks whether the module instance is currently in + /// fullscreen mode or sets the instance to full screen mode. + /// + /// The setter switches the module instance to and from fullscreen + /// mode. + /// + /// The transition to and from fullscreen mode is asynchronous. During the + /// transition, IsFullscreen() will return the previous value and + /// no 2D or 3D device can be bound. The transition ends at DidChangeView() + /// when IsFullscreen() returns the new value. You might receive other + /// DidChangeView() calls while in transition. + /// + /// The transition to fullscreen mode can only occur while the browser is + /// processing a user gesture, even if true is returned. + /// + /// + /// + /// Throws InvalidOperationException if there was an error transitioning to or from + /// fullscreen mode. + /// + public bool IsFullScreen + { + get { return PPBFullscreen.IsFullscreen(this) == PPBool.True; } + set + { + if (PPBFullscreen.SetFullscreen(this, value ? PPBool.True : PPBool.False) == PPBool.False) + throw new InvalidOperationException("Setting full screen failed."); + } + } + + /// + /// Gets the size of the screen in pixels. The module instance + /// will be resized to this size when IsFullscreen is set to true to enter + /// fullscreen mode. + /// + /// + /// Throws InvalidOperationException if there was an error obtaining the screen size for + /// some reason. + /// + public PPSize ScreenSize + { + get + { + var outSize = PPSize.Zero; + if (PPBFullscreen.GetScreenSize(this, out outSize) == PPBool.False) + throw new InvalidOperationException("Obtaining screen size failed."); + return outSize; + } + } + + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of PepperSharp.Var::.ctor() at Line 632) of type PepperSharp.Var in method "Void Instance.PostMessage(Object)". + +### Severity: +ERROR + +### Procedure: +Void Instance.PostMessage(Object) + +### File: +PepperSharp/src/Instance.cs + +### Key: +Instance.cs|PostMessage|DOTNET_RESOURCE_LEAK + +### Hash: +25cdd3f022a8137d8604d38931d48bfc + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1243/instruction.md b/inferredbugs-1243/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9bc8736bfc9103a95e859e086c5143cb647cfc0a --- /dev/null +++ b/inferredbugs-1243/instruction.md @@ -0,0 +1,136 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** LinqToTwitter +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; + +namespace LinqToTwitter +{ + public class XAuthAuthorizer : OAuthAuthorizer, ITwitterAuthorizer + { + /// + /// Synchronous authorization + /// + public void Authorize() + { + if (IsAuthorized) + return; + + var request = new Request(OAuthAccessTokenUrl); + + var xauthCredentials = Credentials as XAuthCredentials; + var postData = new Dictionary(); + postData.Add("x_auth_username", xauthCredentials.UserName); + postData.Add("x_auth_password", xauthCredentials.Password); + postData.Add("x_auth_mode", "client_auth"); + + string screenName; + string userID; + OAuthTwitter.PostAccessToken(request, postData, out screenName, out userID); + + ScreenName = screenName; + UserId = userID; + + Credentials.OAuthToken = OAuthTwitter.OAuthToken; + Credentials.AccessToken = OAuthTwitter.OAuthTokenSecret; + Credentials.ScreenName = screenName; + Credentials.UserId = userID; + Credentials.Save(); + } + + /// + /// Asynchronously performs authorization for Silverlight apps + /// + /// Action you provide for when authorization completes. + public void BeginAuthorize(Action> authorizationCompleteCallback) + { + if (IsAuthorized) + return; + + var request = new Request(OAuthAccessTokenUrl); + + var xauthCredentials = Credentials as XAuthCredentials; + var postData = new Dictionary(); + postData.Add("x_auth_username", xauthCredentials.UserName); + postData.Add("x_auth_password", xauthCredentials.Password); + postData.Add("x_auth_mode", "client_auth"); + + OAuthTwitter.PostAccessTokenAsync( + request, + postData, + resp => + { + Credentials.OAuthToken = OAuthTwitter.OAuthToken; + Credentials.AccessToken = OAuthTwitter.OAuthTokenSecret; + UserIdentifier user = resp.State; + if (user != null) + { + Credentials.ScreenName = user.ScreenName; + Credentials.UserId = user.UserID; + } + Credentials.Save(); + + authorizationCompleteCallback(resp); + }); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `xauthCredentials` last assigned on line 18 could be null and is dereferenced at line 20, column 13. + +### Severity: +ERROR + +### Procedure: +Void XAuthAuthorizer.Authorize() + +### File: +LinqToTwitterAg/OAuth/XAuthAuthorizer.cs + +### Key: +XAuthAuthorizer.cs|Authorize|NULL_DEREFERENCE + +### Node Key: +18c00322eb7006423176408542ace89c + +### Hash: +c676f6c780551886fc0ff9a0b65674db + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1244/instruction.md b/inferredbugs-1244/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51030addaf084dd893bd4bdf7772d8de37a95c59 --- /dev/null +++ b/inferredbugs-1244/instruction.md @@ -0,0 +1,1101 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** LinqToTwitter +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Linq.Expressions; +using LinqToTwitter.Common; +using LinqToTwitter.Provider; +using LinqToTwitter.Tests.Common; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace LinqToTwitter.Tests.TweetTests +{ + [TestClass] + public class TweetRequestProcessorTests + { + const string BaseUrl2 = "https://api.twitter.com/2/"; + + public TweetRequestProcessorTests() + { + TestCulture.SetCulture(); + } + + [TestMethod] + public void GetParametersTest() + { + var target = new TweetRequestProcessor(); + + var endTime = new DateTime(2020, 8, 30); + var startTime = new DateTime(2020, 8, 1); + Expression> expression = + tweet => + tweet.Type == TweetType.Lookup && + tweet.EndTime == endTime && + tweet.Exclude == TweetExcludes.Replies && + tweet.Ids == "2,3" && + tweet.ID == "123" && + tweet.Expansions == "attachments.poll_ids,author_id" && + tweet.MaxResults == 99 && + tweet.MediaFields == "height,width" && + tweet.PaginationToken == "456" && + tweet.PlaceFields == "country" && + tweet.PollFields == "duration_minutes,end_datetime" && + tweet.SinceID == "789" && + tweet.SpaceID == "345" && + tweet.StartTime == startTime && + tweet.TweetFields == "author_id,created_at" && + tweet.UntilID == "012" && + tweet.UserFields == "created_at,verified"; + + var lambdaExpression = expression as LambdaExpression; + + Dictionary queryParams = target.GetParameters(lambdaExpression); + + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.Type), ((int)TweetType.Lookup).ToString(CultureInfo.InvariantCulture)))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.EndTime), "08/30/2020 00:00:00"))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.Exclude), TweetExcludes.Replies))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.Ids), "2,3"))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.ID), "123"))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.Expansions), "attachments.poll_ids,author_id"))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.MaxResults), "99"))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.MediaFields), "height,width"))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.PaginationToken), "456"))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.PlaceFields), "country"))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.PollFields), "duration_minutes,end_datetime"))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.SinceID), "789"))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.SpaceID), "345"))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.StartTime), "08/01/2020 00:00:00"))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.TweetFields), "author_id,created_at"))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.UntilID), "012"))); + Assert.IsTrue( + queryParams.Contains( + new KeyValuePair(nameof(TweetQuery.UserFields), "created_at,verified"))); + } + + [TestMethod] + public void BuildUrl_ForLookup_IncludesParameters() + { + const string ExpectedUrl = + BaseUrl2 + "tweets?" + + "ids=2%2C3&" + + "expansions=attachments.poll_ids%2Cauthor_id&" + + "media.fields=height%2Cwidth&" + + "place.fields=country&" + + "poll.fields=duration_minutes%2Cend_datetime&" + + "tweet.fields=author_id%2Ccreated_at&" + + "user.fields=created_at%2Cverified"; + var tweetReqProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + var parameters = + new Dictionary + { + { nameof(TweetQuery.Type), TweetType.Lookup.ToString() }, + { nameof(TweetQuery.Ids), "2,3" }, + { nameof(TweetQuery.Expansions), "attachments.poll_ids,author_id" }, + { nameof(TweetQuery.MediaFields), "height,width" }, + { nameof(TweetQuery.PlaceFields), "country" }, + { nameof(TweetQuery.PollFields), "duration_minutes,end_datetime" }, + { nameof(TweetQuery.TweetFields), "author_id,created_at" }, + { nameof(TweetQuery.UserFields), "created_at,verified" }, + }; + + Request req = tweetReqProc.BuildUrl(parameters); + + Assert.AreEqual(ExpectedUrl, req.FullUrl); + } + + [TestMethod] + public void BuildUrl_ForMentionsTimeline_IncludesParameters() + { + const string ExpectedUrl = + BaseUrl2 + "users/123/mentions?" + + "end_time=2021-01-01T12%3A59%3A59Z&" + + "exclude=replies%2Cretweets&" + + "max_results=50&" + + "pagination_token=456&" + + "since_id=789&" + + "start_time=2020-12-31T00%3A00%3A01Z&" + + "until_id=012&" + + "expansions=attachments.poll_ids%2Cauthor_id&" + + "media.fields=height%2Cwidth&" + + "place.fields=country&" + + "poll.fields=duration_minutes%2Cend_datetime&" + + "tweet.fields=author_id%2Ccreated_at&" + + "user.fields=created_at%2Cverified"; + var tweetReqProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + var parameters = + new Dictionary + { + { nameof(TweetQuery.Type), TweetType.MentionsTimeline.ToString() }, + { nameof(TweetQuery.EndTime), new DateTime(2021, 1, 1, 12, 59, 59).ToString() }, + { nameof(TweetQuery.Exclude), TweetExcludes.All }, + { nameof(TweetQuery.Expansions), "attachments.poll_ids,author_id" }, + { nameof(TweetQuery.ID), "123" }, + { nameof(TweetQuery.MaxResults), "50" }, + { nameof(TweetQuery.MediaFields), "height,width" }, + { nameof(TweetQuery.PaginationToken), "456" }, + { nameof(TweetQuery.PlaceFields), "country" }, + { nameof(TweetQuery.PollFields), "duration_minutes,end_datetime" }, + { nameof(TweetQuery.SinceID), "789" }, + { nameof(TweetQuery.StartTime), new DateTime(2020, 12, 31, 0, 0, 1).ToString() }, + { nameof(TweetQuery.TweetFields), "author_id,created_at" }, + { nameof(TweetQuery.UntilID), "012" }, + { nameof(TweetQuery.UserFields), "created_at,verified" }, + }; + + Request req = tweetReqProc.BuildUrl(parameters); + + Assert.AreEqual(ExpectedUrl, req.FullUrl); + } + + [TestMethod] + public void BuildUrl_ForUserTimeline_IncludesParameters() + { + const string ExpectedUrl = + BaseUrl2 + "users/123/tweets?" + + "end_time=2021-01-01T12%3A59%3A59Z&" + + "exclude=replies%2Cretweets&" + + "max_results=50&" + + "pagination_token=456&" + + "since_id=789&" + + "start_time=2020-12-31T00%3A00%3A01Z&" + + "until_id=012&" + + "expansions=attachments.poll_ids%2Cauthor_id&" + + "media.fields=height%2Cwidth&" + + "place.fields=country&" + + "poll.fields=duration_minutes%2Cend_datetime&" + + "tweet.fields=author_id%2Ccreated_at&" + + "user.fields=created_at%2Cverified"; + var tweetReqProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + var parameters = + new Dictionary + { + { nameof(TweetQuery.Type), TweetType.TweetsTimeline.ToString() }, + { nameof(TweetQuery.EndTime), new DateTime(2021, 1, 1, 12, 59, 59).ToString() }, + { nameof(TweetQuery.Exclude), TweetExcludes.All }, + { nameof(TweetQuery.Expansions), "attachments.poll_ids,author_id" }, + { nameof(TweetQuery.ID), "123" }, + { nameof(TweetQuery.MaxResults), "50" }, + { nameof(TweetQuery.MediaFields), "height,width" }, + { nameof(TweetQuery.PaginationToken), "456" }, + { nameof(TweetQuery.PlaceFields), "country" }, + { nameof(TweetQuery.PollFields), "duration_minutes,end_datetime" }, + { nameof(TweetQuery.SinceID), "789" }, + { nameof(TweetQuery.StartTime), new DateTime(2020, 12, 31, 0, 0, 1).ToString() }, + { nameof(TweetQuery.TweetFields), "author_id,created_at" }, + { nameof(TweetQuery.UntilID), "012" }, + { nameof(TweetQuery.UserFields), "created_at,verified" }, + }; + + Request req = tweetReqProc.BuildUrl(parameters); + + Assert.AreEqual(ExpectedUrl, req.FullUrl); + } + + [TestMethod] + public void BuildUrl_WithNullParameters_Throws() + { + var tweetReqProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + + L2TAssert.Throws(() => + { + tweetReqProc.BuildUrl(null); + }); + } + + [TestMethod] + public void BuildUrl_WithSpacesInFields_FixesSpaces() + { + const string ExpectedUrl = + BaseUrl2 + "tweets?" + + "ids=2%2C3&" + + "expansions=attachments.poll_ids%2Cauthor_id&" + + "media.fields=height%2Cwidth&" + + "place.fields=country&" + + "poll.fields=duration_minutes%2Cend_datetime&" + + "tweet.fields=author_id%2Ccreated_at&" + + "user.fields=created_at%2Cverified"; + var tweetReqProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + var parameters = + new Dictionary + { + { nameof(TweetQuery.Type), TweetType.Lookup.ToString() }, + { nameof(TweetQuery.Ids), "2, 3" }, + { nameof(TweetQuery.Expansions), "attachments.poll_ids, author_id" }, + { nameof(TweetQuery.MediaFields), "height, width" }, + { nameof(TweetQuery.PlaceFields), "country" }, + { nameof(TweetQuery.PollFields), "duration_minutes, end_datetime" }, + { nameof(TweetQuery.TweetFields), "author_id, created_at" }, + { nameof(TweetQuery.UserFields), "created_at, verified" }, + }; + + Request req = tweetReqProc.BuildUrl(parameters); + + Assert.AreEqual(ExpectedUrl, req.FullUrl); + } + + [TestMethod] + public void BuildUrl_ForList_IncludesParameters() + { + const string ExpectedUrl = + BaseUrl2 + "lists/12345/tweets?" + + "expansions=author_id&" + + "max_results=50&" + + "pagination_token=def&" + + "tweet.fields=author_id%2Ccreated_at&" + + "user.fields=created_at%2Cverified"; + var tweetReqProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + var parameters = + new Dictionary + { + { nameof(TweetQuery.Type), TweetType.List.ToString() }, + { nameof(TweetQuery.ListID), "12345" }, + { nameof(TweetQuery.Expansions), "author_id" }, + { nameof(TweetQuery.MaxResults), "50" }, + { nameof(TweetQuery.PaginationToken), "def" }, + { nameof(TweetQuery.TweetFields), "author_id,created_at" }, + { nameof(TweetQuery.UserFields), "created_at,verified" }, + }; + + Request req = tweetReqProc.BuildUrl(parameters); + + Assert.AreEqual(ExpectedUrl, req.FullUrl); + } + + [TestMethod] + public void BuildUrl_ForPinnedWithSpacesInFields_RemovesSpaces() + { + const string ExpectedUrl = + BaseUrl2 + "lists/12345/tweets?" + + "expansions=author_id&" + + "max_results=50&" + + "pagination_token=def&" + + "tweet.fields=author_id%2Ccreated_at&" + + "user.fields=created_at%2Cverified"; + var tweetReqProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + var parameters = + new Dictionary + { + { nameof(TweetQuery.Type), TweetType.List.ToString() }, + { nameof(TweetQuery.ListID), "12345" }, + { nameof(TweetQuery.Expansions), "author_id" }, + { nameof(TweetQuery.MaxResults), "50" }, + { nameof(TweetQuery.PaginationToken), "def" }, + { nameof(TweetQuery.TweetFields), "author_id, created_at" }, + { nameof(TweetQuery.UserFields), "created_at, verified" }, + }; + + Request req = tweetReqProc.BuildUrl(parameters); + + Assert.AreEqual(ExpectedUrl, req.FullUrl); + } + + [TestMethod] + public void BuildUrl_ForPinned_RequiresListID() + { + var tweetReqProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + var parameters = + new Dictionary + { + { nameof(TweetQuery.Type), TweetType.List.ToString() }, + //{ nameof(TweetQuery.ListID), "1234" }, + }; + + ArgumentException ex = + L2TAssert.Throws(() => + tweetReqProc.BuildUrl(parameters)); + + Assert.AreEqual(nameof(TweetQuery.ListID), ex.ParamName); + } + + [TestMethod] + public void BuildUrl_ForLookup_RequiresIds() + { + var tweetReqProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + var parameters = + new Dictionary + { + { nameof(TweetQuery.Type), TweetType.Lookup.ToString() }, + //{ nameof(Tweet.Ids), null } + }; + + ArgumentException ex = + L2TAssert.Throws(() => + tweetReqProc.BuildUrl(parameters)); + + Assert.AreEqual(nameof(TweetQuery.Ids), ex.ParamName); + } + + [TestMethod] + public void BuildUrl_ForUserTimeline_RequiresID() + { + var tweetReqProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + var parameters = + new Dictionary + { + { nameof(TweetQuery.Type), TweetType.TweetsTimeline.ToString() }, + //{ nameof(Tweet.ID), null } + }; + + ArgumentException ex = + L2TAssert.Throws(() => + tweetReqProc.BuildUrl(parameters)); + + Assert.AreEqual(nameof(TweetQuery.ID), ex.ParamName); + } + + [TestMethod] + public void BuildUrl_ForMentionsTimeline_RequiresID() + { + var tweetReqProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + var parameters = + new Dictionary + { + { nameof(TweetQuery.Type), TweetType.MentionsTimeline.ToString() }, + //{ nameof(Tweet.ID), null } + }; + + ArgumentException ex = + L2TAssert.Throws(() => + tweetReqProc.BuildUrl(parameters)); + + Assert.AreEqual(nameof(TweetQuery.ID), ex.ParamName); + } + + [TestMethod] + public void BuildUrl_ForSpaceTweets_ConstructsUrl() + { + const string ExpectedUrl = + BaseUrl2 + "spaces/345/tweets?" + + "expansions=attachments.poll_ids%2Cauthor_id&" + + "media.fields=height%2Cwidth&" + + "place.fields=country&" + + "poll.fields=duration_minutes%2Cend_datetime&" + + "tweet.fields=author_id%2Ccreated_at&" + + "user.fields=created_at%2Cverified"; + var reqProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + var parameters = + new Dictionary + { + { nameof(TweetQuery.Type), TweetType.SpaceTweets.ToString() }, + { nameof(TweetQuery.SpaceID), "345" }, + { nameof(TweetQuery.Expansions), "attachments.poll_ids,author_id" }, + { nameof(TweetQuery.MediaFields), "height,width" }, + { nameof(TweetQuery.PlaceFields), "country" }, + { nameof(TweetQuery.PollFields), "duration_minutes,end_datetime" }, + { nameof(TweetQuery.TweetFields), "author_id,created_at" }, + { nameof(TweetQuery.UserFields), "created_at,verified" } + }; + + Request req = reqProc.BuildUrl(parameters); + + Assert.AreEqual(ExpectedUrl, req.FullUrl); + } + + [TestMethod] + public void ProcessResults_Populates_Tweets() + { + var tweetProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + + List results = tweetProc.ProcessResults(SingleTweet); + + Assert.IsNotNull(results); + TweetQuery tweetQuery = results.SingleOrDefault(); + Assert.IsNotNull(tweetQuery); + List tweets = tweetQuery.Tweets; + Assert.IsNotNull(tweets); + Assert.AreEqual(1, tweets.Count); + Tweet tweet = tweets.FirstOrDefault(); + Assert.IsNotNull(tweet); + Assert.AreEqual("en", tweet.Language); + Assert.AreEqual("Thanks @github for approving sponsorship for LINQ to Twitter: https://t.co/jWeDEN07HN", tweet.Text); + Assert.AreEqual("1305895383260782593", tweet.ID); + Assert.AreEqual("15411837", tweet.AuthorID); + Assert.AreEqual(DateTime.Parse("2020-09-15T15:44:56.000Z").Date, tweet.CreatedAt?.Date); + Assert.AreEqual("1305895383260782593", tweet.ConversationID); + Assert.IsTrue(tweet.PossiblySensitive ?? false); + Assert.AreEqual(tweet.ReplySettings, TweetReplySettings.Everyone); + Assert.AreEqual("Twitter Web App", tweet.Source); + } + + [TestMethod] + public void ProcessResults_Populates_Entities() + { + var tweetProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + + List results = tweetProc.ProcessResults(SingleTweet); + + Assert.IsNotNull(results); + TweetQuery tweetQuery = results.SingleOrDefault(); + Assert.IsNotNull(tweetQuery); + + List tweets = tweetQuery.Tweets; + Assert.IsNotNull(tweets); + Assert.AreEqual(1, tweets.Count); + Tweet tweet = tweets.FirstOrDefault(); + Assert.IsNotNull(tweet); + TweetEntities entities = tweet.Entities; + Assert.IsNotNull(entities); + + TweetEntityAnnotation annotation = entities?.Annotations?.FirstOrDefault(); + Assert.IsNotNull(annotation); + Assert.AreEqual(53, annotation.Start); + Assert.AreEqual(59, annotation.End); + Assert.AreEqual(0.5865f, annotation.Probability); + Assert.AreEqual("Organization", annotation.Type); + Assert.AreEqual("Twitter", annotation.NormalizedText); + + TweetEntityMention mention = entities?.Mentions?.FirstOrDefault(); + Assert.IsNotNull(mention); + Assert.AreEqual(14, mention.End); + Assert.AreEqual("13334762", mention.ID); + Assert.AreEqual(7, mention.Start); + Assert.AreEqual("github", mention.Username); + + TweetEntityUrl url = entities?.Urls?.FirstOrDefault(); + Assert.IsNotNull(url); + Assert.AreEqual(62, url.Start); + Assert.AreEqual(85, url.End); + Assert.AreEqual("https://t.co/jWeDEN07HN", url.Url); + Assert.AreEqual("http://bit.ly/1b2wrHb", url.ExpandedUrl); + Assert.AreEqual("bit.ly/1b2wrHb", url.DisplayUrl); + Assert.AreEqual(200, url.Status); + Assert.AreEqual("GitHub - JoeMayo/LinqToTwitter: LINQ Provider for the Twitter API (C# Twitter Library)", url.Title); + Assert.AreEqual("LINQ Provider for the Twitter API (C# Twitter Library) - GitHub - JoeMayo/LinqToTwitter: LINQ Provider for the Twitter API (C# Twitter Library)", url.Description); + Assert.AreEqual("https://github.com/JoeMayo/LinqToTwitter", url.UnwoundUrl); + List images = url.Images; + Assert.IsNotNull(images); + Assert.AreEqual(2, images.Count); + TweetEntityImage image = images.First(); + Assert.AreEqual("https://pbs.twimg.com/news_img/1527013178009329664/f45coPtn?format=png&name=orig", image.Url); + Assert.AreEqual(200, image.Width); + Assert.AreEqual(200, image.Height); + } + + [TestMethod] + public void ProcessResults_Populates_ContextAnnotations() + { + var tweetProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + + List results = tweetProc.ProcessResults(SingleTweet); + + Assert.IsNotNull(results); + TweetQuery tweetQuery = results.SingleOrDefault(); + Assert.IsNotNull(tweetQuery); + List tweets = tweetQuery.Tweets; + Assert.IsNotNull(tweets); + Assert.AreEqual(1, tweets.Count); + Tweet tweet = tweets.FirstOrDefault(); + Assert.IsNotNull(tweet); + + List annotations = tweet.ContextAnnotations; + Assert.IsNotNull(annotations); + Assert.AreEqual(7, annotations.Count); + TweetContextAnnotation annotation = annotations.First(); + Assert.IsNotNull(annotation); + TweetContextAnnotationDetails domain = annotation.Domain; + Assert.IsNotNull(domain); + Assert.AreEqual("46", domain.ID); + Assert.AreEqual("Brand Category", domain.Name); + Assert.AreEqual("Categories within Brand Verticals that narrow down the scope of Brands", domain.Description); + TweetContextAnnotationDetails entity = annotation.Entity; + Assert.IsNotNull(entity); + Assert.AreEqual("781974596752842752", entity.ID); + Assert.AreEqual("Services", entity.Name); + } + + [TestMethod] + public void ProcessResults_Populates_PublicMetrics() + { + var tweetProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + + List results = tweetProc.ProcessResults(SingleTweet); + + Assert.IsNotNull(results); + TweetQuery tweetQuery = results.SingleOrDefault(); + Assert.IsNotNull(tweetQuery); + List tweets = tweetQuery.Tweets; + Assert.IsNotNull(tweets); + Assert.AreEqual(1, tweets.Count); + Tweet tweet = tweets.FirstOrDefault(); + Assert.IsNotNull(tweet); + + TweetPublicMetrics metrics = tweet.PublicMetrics; + Assert.IsNotNull(metrics); + Assert.AreEqual(1, metrics.RetweetCount); + Assert.AreEqual(1, metrics.ReplyCount); + Assert.AreEqual(1, metrics.LikeCount); + Assert.AreEqual(0, metrics.QuoteCount); + } + + [TestMethod] + public void ProcessResults_Populates_Includes() + { + var tweetProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + + List results = tweetProc.ProcessResults(SingleTweet); + + Assert.IsNotNull(results); + TweetQuery tweetQuery = results.SingleOrDefault(); + Assert.IsNotNull(tweetQuery); + TwitterInclude includes = tweetQuery.Includes; + Assert.IsNotNull(includes); + List users = includes.Users; + Assert.IsNotNull(users); + Assert.AreEqual(2, users.Count); + TwitterPoll poll = includes.Polls?.SingleOrDefault(); + Assert.IsNotNull(poll); + Assert.AreEqual(1440, poll.DurationMinutes); + Assert.AreEqual(DateTime.Parse("2019-11-28T20:26:41.000Z").ToUniversalTime(), poll.EndDateTime); + Assert.AreEqual("1199786642468413448", poll.ID); + Assert.AreEqual("closed", poll.VotingStatus); + List options = poll.Options; + Assert.IsNotNull(options); + Assert.AreEqual(2, options.Count); + TwitterPollOption option = options.FirstOrDefault(); + Assert.IsNotNull(option); + Assert.AreEqual(1, option.Position); + Assert.AreEqual("“C Sharp”", option.Label); + Assert.AreEqual(795, option.Votes); + } + + [TestMethod] + public void ProcessResults_Handles_Response_With_No_Results() + { + var tweetProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + + List results = tweetProc.ProcessResults(ErrorTweet); + + Assert.IsNotNull(results); + TweetQuery tweetQuery = results.SingleOrDefault(); + Assert.IsNotNull(tweetQuery); + List tweets = tweetQuery.Tweets; + Assert.IsNull(tweets); + } + + [TestMethod] + public void ProcessResults_PopulatesInputParameters() + { + var tweetProc = new TweetRequestProcessor() + { + BaseUrl = BaseUrl2, + Type = TweetType.MentionsTimeline, + ID = "567", + Ids = "123,456", + EndTime = new DateTime(2020, 12, 31), + Exclude = TweetExcludes.Retweets, + MaxResults = 73, + Expansions = "123", + MediaFields = "456", + PaginationToken = "567", + PlaceFields = "012", + PollFields = "345", + SinceID = "890", + SpaceID = "345", + StartTime = new DateTime(2020, 1, 1), + TweetFields = "678", + UntilID = "123", + UserFields = "234" + }; + + var results = tweetProc.ProcessResults(SingleTweet); + + Assert.IsNotNull(results); + Assert.AreEqual(1, results.Count); + var tweetQuery = results.Single(); + Assert.IsNotNull(tweetQuery); + Assert.AreEqual(TweetType.MentionsTimeline, tweetQuery.Type); + Assert.AreEqual(new DateTime(2020, 12, 31), tweetQuery.EndTime); + Assert.AreEqual(TweetExcludes.Retweets, tweetQuery.Exclude); + Assert.AreEqual("123", tweetQuery.Expansions); + Assert.AreEqual("567", tweetQuery.ID); + Assert.AreEqual("123,456", tweetQuery.Ids); + Assert.AreEqual(73, tweetQuery.MaxResults); + Assert.AreEqual("456", tweetQuery.MediaFields); + Assert.AreEqual("567", tweetQuery.PaginationToken); + Assert.AreEqual("012", tweetQuery.PlaceFields); + Assert.AreEqual("345", tweetQuery.PollFields); + Assert.AreEqual("890", tweetQuery.SinceID); + Assert.AreEqual("345", tweetQuery.SpaceID); + Assert.AreEqual(new DateTime(2020, 1, 1), tweetQuery.StartTime); + Assert.AreEqual("678", tweetQuery.TweetFields); + Assert.AreEqual("123", tweetQuery.UntilID); + Assert.AreEqual("234", tweetQuery.UserFields); + } + + [TestMethod] + public void ProcessResults_WithErrors_PopulatesErrorList() + { + var tweetProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + + List results = tweetProc.ProcessResults(ErrorTweet); + + Assert.IsNotNull(results); + TweetQuery tweetQuery = results.SingleOrDefault(); + Assert.IsNotNull(tweetQuery); + List errors = tweetQuery.Errors; + Assert.IsNotNull(errors); + Assert.AreEqual(1, errors.Count); + TwitterError error = errors.FirstOrDefault(); + Assert.IsNotNull(error); + Assert.AreEqual("Could not find tweet with ids: [1].", error.Detail); + Assert.AreEqual("Not Found Error", error.Title); + Assert.AreEqual("tweet", error.ResourceType); + Assert.AreEqual("ids", error.Parameter); + Assert.AreEqual("1", error.Value); + Assert.AreEqual("https://api.twitter.com/2/problems/resource-not-found", error.Type); + } + + [TestMethod] + public void ProcessResults_WithTimeline_PopulatesTweetsAndMeta() + { + var tweetProc = new TweetRequestProcessor { BaseUrl = BaseUrl2 }; + + List results = tweetProc.ProcessResults(TimelineTweets); + + TweetQuery tweetQuery = results?.SingleOrDefault(); + Assert.IsNotNull(tweetQuery); + List tweets = tweetQuery.Tweets; + Assert.IsNotNull(tweets); + Assert.AreEqual(10, tweets.Count); + TweetMeta meta = tweetQuery.Meta; + Assert.IsNotNull(meta); + Assert.AreEqual("7140dibdnow9c7btw421e9l0f3cacd5qxve3023jqz48g", meta.PreviousToken); + Assert.AreEqual("7140dibdnow9c7btw421e9l0f3cacd5qxve3023jqz48g", meta.NextToken); + Assert.AreEqual(10, meta.ResultCount); + Assert.AreEqual("1529568259011252224", meta.NewestID); + Assert.AreEqual("1527016962995343360", meta.OldestID); + } + + const string SingleTweet = @"{ + ""data"": [ + { + ""context_annotations"": [ + { + ""domain"": { + ""id"": ""46"", + ""name"": ""Brand Category"", + ""description"": ""Categories within Brand Verticals that narrow down the scope of Brands"" + }, + ""entity"": { + ""id"": ""781974596752842752"", + ""name"": ""Services"" + } + }, + { + ""domain"": { + ""id"": ""47"", + ""name"": ""Brand"", + ""description"": ""Brands and Companies"" + }, + ""entity"": { + ""id"": ""10045225402"", + ""name"": ""Twitter"" + } + }, + { + ""domain"": { + ""id"": ""30"", + ""name"": ""Entities [Entity Service]"", + ""description"": ""Entity Service top level domain, every item that is in Entity Service should be in this domain"" + }, + ""entity"": { + ""id"": ""848920371311001600"", + ""name"": ""Technology"", + ""description"": ""Technology and computing"" + } + }, + { + ""domain"": { + ""id"": ""66"", + ""name"": ""Interests and Hobbies Category"", + ""description"": ""A grouping of interests and hobbies entities, like Novelty Food or Destinations"" + }, + ""entity"": { + ""id"": ""848921413196984320"", + ""name"": ""Computer programming"", + ""description"": ""Computer programming"" + } + }, + { + ""domain"": { + ""id"": ""45"", + ""name"": ""Brand Vertical"", + ""description"": ""Top level entities that describe a Brands industry"" + }, + ""entity"": { + ""id"": ""781974597226799105"", + ""name"": ""B2B"" + } + }, + { + ""domain"": { + ""id"": ""46"", + ""name"": ""Brand Category"", + ""description"": ""Categories within Brand Verticals that narrow down the scope of Brands"" + }, + ""entity"": { + ""id"": ""781974597172203520"", + ""name"": ""Services"" + } + }, + { + ""domain"": { + ""id"": ""47"", + ""name"": ""Brand"", + ""description"": ""Brands and Companies"" + }, + ""entity"": { + ""id"": ""10040692468"", + ""name"": ""GitHub"" + } + } + ], + ""reply_settings"": ""everyone"", + ""id"": ""1305895383260782593"", + ""source"": ""Twitter Web App"", + ""public_metrics"": { + ""retweet_count"": 1, + ""reply_count"": 1, + ""like_count"": 1, + ""quote_count"": 0 + }, + ""lang"": ""en"", + ""entities"": { + ""annotations"": [ + { + ""start"": 53, + ""end"": 59, + ""probability"": 0.5865, + ""type"": ""Organization"", + ""normalized_text"": ""Twitter"" + } + ], + ""urls"": [ + { + ""start"": 62, + ""end"": 85, + ""url"": ""https://t.co/jWeDEN07HN"", + ""expanded_url"": ""http://bit.ly/1b2wrHb"", + ""display_url"": ""bit.ly/1b2wrHb"", + ""images"": [ + { + ""url"": ""https://pbs.twimg.com/news_img/1527013178009329664/f45coPtn?format=png&name=orig"", + ""width"": 200, + ""height"": 200 + }, + { + ""url"": ""https://pbs.twimg.com/news_img/1527013178009329664/f45coPtn?format=png&name=150x150"", + ""width"": 150, + ""height"": 150 + } + ], + ""status"": 200, + ""title"": ""GitHub - JoeMayo/LinqToTwitter: LINQ Provider for the Twitter API (C# Twitter Library)"", + ""description"": ""LINQ Provider for the Twitter API (C# Twitter Library) - GitHub - JoeMayo/LinqToTwitter: LINQ Provider for the Twitter API (C# Twitter Library)"", + ""unwound_url"": ""https://github.com/JoeMayo/LinqToTwitter"" + } + ], + ""mentions"": [ + { + ""start"": 7, + ""end"": 14, + ""username"": ""github"", + ""id"": ""13334762"" + } + ] + }, + ""text"": ""Thanks @github for approving sponsorship for LINQ to Twitter: https://t.co/jWeDEN07HN"", + ""conversation_id"": ""1305895383260782593"", + ""author_id"": ""15411837"", + ""possibly_sensitive"": true, + ""created_at"": ""2020-09-15T15:44:56.000Z"" + } + ], + ""includes"": { + ""polls"": [ + { + ""id"": ""1199786642468413448"", + ""voting_status"": ""closed"", + ""duration_minutes"": 1440, + ""options"": [ + { + ""position"": 1, + ""label"": ""“C Sharp”"", + ""votes"": 795 + + }, + { + ""position"": 2, + ""label"": ""“C Hashtag”"", + ""votes"": 156 + } + ], + ""end_datetime"": ""2019-11-28T20:26:41.000Z"" + } + ], + ""users"": [ + { + ""verified"": false, + ""username"": ""JoeMayo"", + ""created_at"": ""2008-07-13T04:35:50.000Z"", + ""description"": ""Author, Instructor, and Independent Consultant \n\nNewest Release: C# Cookbook (https://t.co/acNTiAe6HQ)\n\n#AI #Chatbots #CSharp #Linq2Twitter #NLP"", + ""public_metrics"": { + ""followers_count"": 10778, + ""following_count"": 4193, + ""tweet_count"": 4226, + ""listed_count"": 271 + }, + ""url"": ""https://t.co/Pd3XsnJwJU"", + ""pinned_tweet_id"": ""1516074915803254788"", + ""protected"": false, + ""name"": ""Joe Mayo"", + ""profile_image_url"": ""https://pbs.twimg.com/profile_images/1185764990403268613/8GoXoOtz_normal.jpg"", + ""location"": ""Las Vegas, NV"", + ""entities"": { + ""url"": { + ""urls"": [ + { + ""start"": 0, + ""end"": 23, + ""url"": ""https://t.co/Pd3XsnJwJU"", + ""expanded_url"": ""https://joemayo.medium.com"", + ""display_url"": ""joemayo.medium.com"" + } + ] + }, + ""description"": { + ""urls"": [ + { + ""start"": 78, + ""end"": 101, + ""url"": ""https://t.co/acNTiAe6HQ"", + ""expanded_url"": ""http://bit.ly/CSharpCookbook"", + ""display_url"": ""bit.ly/CSharpCookbook"" + } + ], + ""hashtags"": [ + { + ""start"": 104, + ""end"": 107, + ""tag"": ""AI"" + }, + { + ""start"": 108, + ""end"": 117, + ""tag"": ""Chatbots"" + }, + { + ""start"": 118, + ""end"": 125, + ""tag"": ""CSharp"" + }, + { + ""start"": 126, + ""end"": 139, + ""tag"": ""Linq2Twitter"" + }, + { + ""start"": 140, + ""end"": 144, + ""tag"": ""NLP"" + } + ] + } + }, + ""id"": ""15411837"" + }, + { + ""verified"": true, + ""username"": ""github"", + ""created_at"": ""2008-02-11T04:41:50.000Z"", + ""description"": ""How people build software. \n\nNeed help? Send us a message at https://t.co/aspNQGzzZH for support."", + ""public_metrics"": { + ""followers_count"": 2277687, + ""following_count"": 334, + ""tweet_count"": 7061, + ""listed_count"": 17306 + }, + ""url"": """", + ""protected"": false, + ""name"": ""GitHub"", + ""profile_image_url"": ""https://pbs.twimg.com/profile_images/1414990564408262661/r6YemvF9_normal.jpg"", + ""location"": ""San Francisco, CA"", + ""entities"": { + ""description"": { + ""urls"": [ + { + ""start"": 61, + ""end"": 84, + ""url"": ""https://t.co/aspNQGzzZH"", + ""expanded_url"": ""https://support.github.com"", + ""display_url"": ""support.github.com"" + } + ] + } + }, + ""id"": ""13334762"" + } + ] + } +}"; + + const string TimelineTweets = @"{ + ""data"": [ + { + ""id"": ""1529568259011252224"", + ""text"": ""RT @beeradmoore: HAHAHAHA I accidentally deployed a #dotnetmaui app to my Android watch and it just worked. https://t.co/Ral7om02o1"" + }, + { + ""id"": ""1529490697618763777"", + ""text"": ""@buhakmeh @alvinashcraft Whatever is the F5 default. Haven't had problems and will probably continue until I learn about a compelling reason to change."" + }, + { + ""id"": ""1529204113623330816"", + ""text"": ""That last presentation I did was using C# and .NET 6 on a MacBook Pro M1. With MAUI in GA, the x-plat story for .NET improves."" + }, + { + ""id"": ""1528511616882421760"", + ""text"": ""RT @jimwooley: Looks like I won't be able to attend the inaugural @ThatConference Austin due to flight issues. I'll still present the Stati…"" + }, + { + ""id"": ""1528511186790010880"", + ""text"": ""RT @techgirl1908: Decentralized Twitter has released early code\n\nhttps://t.co/OIgGFKUkov"" + }, + { + ""id"": ""1528181517393899521"", + ""text"": ""RT @J_aa_p: My new @TwitterDev @Linq2Twitr #Blazor WASM Twitter Client (Alpha ❗) now parses\n\n✅ Retweets\n✅ Quoted Retweets\n✅ Urls\n✅ Hashtags…"" + }, + { + ""id"": ""1528100853294301184"", + ""text"": ""RT @LauraViglioni: Finally... The GitHub bathroom https://t.co/A43IM1HUaF"" + }, + { + ""id"": ""1527401749329301504"", + ""text"": ""@RafaelH_us @tacobell https://t.co/VSO4CMu6Xa"" + }, + { + ""id"": ""1527371742343114752"", + ""text"": ""RT @jguadagno: @buhakmeh @terrajobst @mohdali If you are using C#, use the Linq2Twitter NuGet package by @JoeMayo . Its super easy to use.…"" + }, + { + ""id"": ""1527016962995343360"", + ""text"": ""Presentation slides and source code for my Intro to LINQ presentation for @DataScienceDojo today:\n\nhttps://t.co/hTx6u3RHmN"" + } + ], + ""meta"": { + ""previous_token"": ""7140dibdnow9c7btw421e9l0f3cacd5qxve3023jqz48g"", + ""next_token"": ""7140dibdnow9c7btw421e9l0f3cacd5qxve3023jqz48g"", + ""result_count"": 10, + ""newest_id"": ""1529568259011252224"", + ""oldest_id"": ""1527016962995343360"" + } +}"; + + const string ErrorTweet = @"{ + ""errors"": [ + { + ""detail"": ""Could not find tweet with ids: [1]."", + ""title"": ""Not Found Error"", + ""resource_type"": ""tweet"", + ""parameter"": ""ids"", + ""value"": ""1"", + ""type"": ""https://api.twitter.com/2/problems/resource-not-found"" + } + ] +}"; + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `annotation` last assigned on line 479 could be null and is dereferenced at line 472, column 4. + +### Severity: +ERROR + +### Procedure: +Void TweetRequestProcessorTests.ProcessResults_Populates_Entities() + +### File: +src/LinqToTwitter6/LinqToTwitter.Tests/TweetTests/TweetRequestProcessorTests.cs + +### Key: +TweetRequestProcessorTests.cs|ProcessResults_Populates_Entities|NULL_DEREFERENCE + +### Node Key: +a35c6d97ccef7486c04c7fb208054b5b + +### Hash: +6d16a650770adda1aba030408251842e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1272/instruction.md b/inferredbugs-1272/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..62951a27ba146f3a7aafa7cef5820cc8dae2c448 --- /dev/null +++ b/inferredbugs-1272/instruction.md @@ -0,0 +1,270 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** CAP +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// Copyright (c) .NET Core Community. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Amazon.SimpleNotificationService; +using Amazon.SimpleNotificationService.Model; +using Amazon.SQS; +using Amazon.SQS.Model; +using DotNetCore.CAP.Messages; +using DotNetCore.CAP.Transport; +using Microsoft.Extensions.Options; +using Headers = DotNetCore.CAP.Messages.Headers; + +namespace DotNetCore.CAP.AmazonSQS +{ + internal sealed class AmazonSQSConsumerClient : IConsumerClient + { + private static readonly SemaphoreSlim ConnectionLock = new SemaphoreSlim(initialCount: 1, maxCount: 1); + + private readonly string _groupId; + private readonly AmazonSQSOptions _amazonSQSOptions; + + private IAmazonSimpleNotificationService _snsClient; + private IAmazonSQS _sqsClient; + private string _queueUrl = string.Empty; + + public AmazonSQSConsumerClient(string groupId, IOptions options) + { + _groupId = groupId; + _amazonSQSOptions = options.Value; + } + + public event EventHandler OnMessageReceived; + + public event EventHandler OnLog; + + public BrokerAddress BrokerAddress => new BrokerAddress("AmazonSQS", _queueUrl); + + public void Subscribe(IEnumerable topics) + { + if (topics == null) + { + throw new ArgumentNullException(nameof(topics)); + } + + Connect(initSNS: true, initSQS: false); + + var topicArns = new List(); + foreach (var topic in topics) + { + var createTopicRequest = new CreateTopicRequest(topic.NormalizeForAws()); + + var createTopicResponse = _snsClient.CreateTopicAsync(createTopicRequest).GetAwaiter().GetResult(); + + topicArns.Add(createTopicResponse.TopicArn); + } + + Connect(initSNS: false, initSQS: true); + + _snsClient.SubscribeQueueToTopicsAsync(topicArns, _sqsClient, _queueUrl) + .GetAwaiter().GetResult(); + } + + public void Listening(TimeSpan timeout, CancellationToken cancellationToken) + { + Connect(); + + var request = new ReceiveMessageRequest(_queueUrl) + { + WaitTimeSeconds = 5, + MaxNumberOfMessages = 1 + }; + + while (true) + { + var response = _sqsClient.ReceiveMessageAsync(request, cancellationToken).GetAwaiter().GetResult(); + + if (response.Messages.Count == 1) + { + var messageObj = JsonSerializer.Deserialize(response.Messages[0].Body); + + var header = messageObj.MessageAttributes.ToDictionary(x => x.Key, x => x.Value.Value); + var body = messageObj.Message; + + var message = new TransportMessage(header, body != null ? Encoding.UTF8.GetBytes(body) : null); + + message.Headers.Add(Headers.Group, _groupId); + + OnMessageReceived?.Invoke(response.Messages[0].ReceiptHandle, message); + } + else + { + cancellationToken.ThrowIfCancellationRequested(); + cancellationToken.WaitHandle.WaitOne(timeout); + } + } + } + + public void Commit(object sender) + { + try + { + _sqsClient.DeleteMessageAsync(_queueUrl, (string)sender); + } + catch (InvalidIdFormatException ex) + { + InvalidIdFormatLog(ex.Message); + } + } + + public void Reject(object sender) + { + try + { + // Visible again in 3 seconds + _sqsClient.ChangeMessageVisibilityAsync(_queueUrl, (string)sender, 3); + } + catch (MessageNotInflightException ex) + { + MessageNotInflightLog(ex.Message); + } + } + + public void Dispose() + { + _sqsClient?.Dispose(); + _snsClient?.Dispose(); + } + + public void Connect(bool initSNS = true, bool initSQS = true) + { + if (_snsClient != null && _sqsClient != null) + { + return; + } + + if (_snsClient == null && initSNS) + { + ConnectionLock.Wait(); + + try + { + _snsClient = _amazonSQSOptions.Credentials != null + ? new AmazonSimpleNotificationServiceClient(_amazonSQSOptions.Credentials, _amazonSQSOptions.Region) + : new AmazonSimpleNotificationServiceClient(_amazonSQSOptions.Region); + } + finally + { + ConnectionLock.Release(); + } + } + + if (_sqsClient == null && initSQS) + { + ConnectionLock.Wait(); + + try + { + + _sqsClient = _amazonSQSOptions.Credentials != null + ? new AmazonSQSClient(_amazonSQSOptions.Credentials, _amazonSQSOptions.Region) + : new AmazonSQSClient(_amazonSQSOptions.Region); + + // If provide the name of an existing queue along with the exact names and values + // of all the queue's attributes, CreateQueue returns the queue URL for + // the existing queue. + _queueUrl = _sqsClient.CreateQueueAsync(_groupId.NormalizeForAws()).GetAwaiter().GetResult().QueueUrl; + } + finally + { + ConnectionLock.Release(); + } + } + } + + #region private methods + + private Task InvalidIdFormatLog(string exceptionMessage) + { + var logArgs = new LogMessageEventArgs + { + LogType = MqLogType.InvalidIdFormat, + Reason = exceptionMessage + }; + + OnLog?.Invoke(null, logArgs); + + return Task.CompletedTask; + } + + private Task MessageNotInflightLog(string exceptionMessage) + { + var logArgs = new LogMessageEventArgs + { + LogType = MqLogType.MessageNotInflight, + Reason = exceptionMessage + }; + + OnLog?.Invoke(null, logArgs); + + return Task.CompletedTask; + } + + #endregion + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource this.DotNetCore.CAP.AmazonSQS.AmazonSQSConsumerClient._snsClient of type Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient in method "Void AmazonSQSConsumerClient.Subscribe(IEnumerable`1)". + +### Severity: +ERROR + +### Procedure: +Void AmazonSQSConsumerClient.Subscribe(IEnumerable`1) + +### File: +src/DotNetCore.CAP.AmazonSQS/AmazonSQSConsumerClient.cs + +### Key: +AmazonSQSConsumerClient.cs|Subscribe|DOTNET_RESOURCE_LEAK + +### Hash: +a7625f8ed85d3db458da7f8b55a1db06 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1273/instruction.md b/inferredbugs-1273/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..487ac0682956373c875456c30137dc813dceda35 --- /dev/null +++ b/inferredbugs-1273/instruction.md @@ -0,0 +1,134 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** CAP +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Data; +using System.Data.SqlClient; +using System.Threading; +using Dapper; +using Microsoft.EntityFrameworkCore; + +namespace DotNetCore.CAP.SqlServer.Test +{ + public abstract class DatabaseTestHost : TestHost + { + private static bool _sqlObjectInstalled; + + protected override void PostBuildServices() + { + base.PostBuildServices(); + InitializeDatabase(); + } + + public override void Dispose() + { + DeleteAllData(); + base.Dispose(); + } + + private void InitializeDatabase() + { + if (!_sqlObjectInstalled) + { + using (CreateScope()) + { + var storage = GetService(); + var token = new CancellationTokenSource().Token; + CreateDatabase(); + storage.InitializeAsync(token).Wait(); + _sqlObjectInstalled = true; + } + } + } + + private void CreateDatabase() + { + var masterConn = ConnectionUtil.GetMasterConnectionString(); + var databaseName = ConnectionUtil.GetDatabaseName(); + using (var connection = ConnectionUtil.CreateConnection(masterConn)) + { + connection.Execute($@" +IF NOT EXISTS (SELECT * FROM sysdatabases WHERE name = N'{databaseName}') +CREATE DATABASE [{databaseName}];"); + } + } + + private void DeleteAllData() + { + using (CreateScope()) + { + var context = GetService(); + + var commands = new[] + { + "DISABLE TRIGGER ALL ON ?", + "ALTER TABLE ? NOCHECK CONSTRAINT ALL", + "DELETE FROM ?", + "ALTER TABLE ? CHECK CONSTRAINT ALL", + "ENABLE TRIGGER ALL ON ?" + }; + foreach (var command in commands) + { + context.Database.GetDbConnection().Execute( + "sp_MSforeachtable", + new { command1 = command }, + commandType: CommandType.StoredProcedure); + } + } + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of System.Threading.CancellationTokenSource::.ctor() at Line 32) of type System.Threading.CancellationTokenSource in method "Void DatabaseTestHost.InitializeDatabase()". + +### Severity: +ERROR + +### Procedure: +Void DatabaseTestHost.InitializeDatabase() + +### File: +test/DotNetCore.CAP.SqlServer.Test/DatabaseTestHost.cs + +### Key: +DatabaseTestHost.cs|InitializeDatabase|DOTNET_RESOURCE_LEAK + +### Hash: +48f61c63c7ac744905784525e84b2431 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1274/instruction.md b/inferredbugs-1274/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f381d616c57c0c788ea44a35129d4be0bee9f3a5 --- /dev/null +++ b/inferredbugs-1274/instruction.md @@ -0,0 +1,174 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** notifo +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// ========================================================================== +// Notifo.io +// ========================================================================== +// Copyright (c) Sebastian Stehle +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using System; +using System.Net.Http; + +namespace Notifo.SDK +{ + /// + /// Fluent builder to create a new instance of the class. + /// + public sealed class NotifoClientBuilder + { + private string apiKey; + private string apiUrl = "https://app.notifo.io"; + private TimeSpan timeout = TimeSpan.FromSeconds(10); + private HttpClient httpClient; + + private NotifoClientBuilder() + { + } + + /// + /// Create a new builder. + /// + /// The builder. + public static NotifoClientBuilder Create() + { + return new NotifoClientBuilder(); + } + + /// + /// Sets the api key to use. + /// + /// The api key. + /// The current instance. + public NotifoClientBuilder SetApiKey(string apiKey) + { + this.apiKey = apiKey; + + return this; + } + + /// + /// Sets the api URL to use. + /// + /// The api URL. Default: https://app.notifo.io. + /// The current instance. + public NotifoClientBuilder SetApiUrl(string apiUrl) + { + this.apiUrl = apiUrl; + + return this; + } + + /// + /// Sets the default request timeout. + /// + /// The HTTP request timeout. Default: 10 seconds. + /// The current instance. + public NotifoClientBuilder SetTimeout(TimeSpan timeout) + { + this.timeout = timeout; + + return this; + } + + /// + /// Sets a custom HTTP client. + /// + /// The HTTP client. + /// The current instance. + public NotifoClientBuilder SetClient(HttpClient httpClient) + { + this.httpClient = httpClient; + + return this; + } + + /// + /// Build a new instance of the class. + /// + /// The generated instance. + /// Configuration is not valid. + public INotifoClient Build() + { + if (string.IsNullOrWhiteSpace(apiKey)) + { + throw new InvalidOperationException("API Key not defined."); + } + + if (string.IsNullOrWhiteSpace(apiUrl)) + { + throw new InvalidOperationException("API URL not defined."); + } + + if (!Uri.IsWellFormedUriString(apiUrl, UriKind.Absolute)) + { + throw new InvalidOperationException("API URL is not a well defined absolute URL."); + } + + httpClient ??= new HttpClient(); + httpClient.Timeout = timeout; + httpClient.DefaultRequestHeaders.Add("ApiKey", apiKey); + + var client = new NotifoClient(httpClient, apiUrl); + + return client; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource this.Notifo.SDK.NotifoClientBuilder.httpClient of type System.Net.Http.HttpClient, Leaked resource (output of Notifo.SDK.Configuration.AuthenticatingHttpMessageHandler::.ctor() at Line 154) of type Notifo.SDK.Configuration.AuthenticatingHttpMessageHandler, Leaked resource (output of Notifo.SDK.Configuration.Authenticator::.ctor() at Line 154).Notifo.SDK.Configuration.Authenticator.httpClient of type System.Net.Http.HttpClient in method "INotifoClient NotifoClientBuilder.Build()". + +### Severity: +ERROR + +### Procedure: +INotifoClient NotifoClientBuilder.Build() + +### File: +backend/sdk/Notifo.SDK/NotifoClientBuilder.cs + +### Key: +NotifoClientBuilder.cs|Build|DOTNET_RESOURCE_LEAK + +### Hash: +840e8f6058e09af946e5d2c411dd0d09 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1275/instruction.md b/inferredbugs-1275/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8538e6db6beed3264ec9b54a8270b0870669277f --- /dev/null +++ b/inferredbugs-1275/instruction.md @@ -0,0 +1,84 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** notifo +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// ========================================================================== +// Notifo.io +// ========================================================================== +// Copyright (c) Sebastian Stehle +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Microsoft.Extensions.Configuration; +using Notifo.Domain.Channels.Email; +using Notifo.Domain.Integrations.Smtp; +using Xunit; + +namespace Notifo.Domain.Integrations.AmazonSES +{ + [Trait("Category", "Dependencies")] + public class AmazonSESEmailServerTests : EmailSenderTestBase + { + protected override IEmailSender CreateSender() + { + var options = TestHelpers.Configuration.GetSection("email:amazonSES").Get(); + + return new SmtpEmailSender(new SmtpEmailServer(options), Address, Address); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Notifo.Domain.Integrations.Smtp.SmtpEmailServer::.ctor() at Line 22) of type Notifo.Domain.Integrations.Smtp.SmtpEmailServer in method "IEmailSender AmazonSESEmailServerTests.CreateSender()". + +### Severity: +ERROR + +### Procedure: +IEmailSender AmazonSESEmailServerTests.CreateSender() + +### File: +backend/tests/Notifo.Domain.Tests/Integrations/AmazonSES/AmazonSESEmailServerTests.cs + +### Key: +AmazonSESEmailServerTests.cs|CreateSender|DOTNET_RESOURCE_LEAK + +### Hash: +04c12f23b09b8ced6526b6495b7ddb7f + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1280/instruction.md b/inferredbugs-1280/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..27c508a1cc4706431ae2239eb9dab4259dd25e20 --- /dev/null +++ b/inferredbugs-1280/instruction.md @@ -0,0 +1,114 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Stove +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Data; +using System.Reflection; + +using Autofac.Extras.IocManager; + +using NHibernate; +using NHibernate.Transaction; + +using Stove.Data; +using Stove.Extensions; +using Stove.NHibernate.Enrichments; + +namespace Stove.NHibernate +{ + public class NhActiveTransactionProvider : IActiveTransactionProvider, ITransientDependency + { + private readonly IScopeResolver _scope; + + public NhActiveTransactionProvider(IScopeResolver scope) + { + _scope = scope; + } + + public IDbTransaction GetActiveTransaction(ActiveTransactionProviderArgs args) + { + var adoTransaction = GetSession(args).Transaction.As(); + var dbTransaction = GetInstanceField(typeof(AdoTransaction), adoTransaction, "trans").As(); + return dbTransaction; + } + + public IDbConnection GetActiveConnection(ActiveTransactionProviderArgs args) + { + return GetSession(args).Connection; + } + + private object GetInstanceField(Type type, object instance, string fieldName) + { + return type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static) + ?.GetValue(instance); + } + + private ISession GetSession(ActiveTransactionProviderArgs args) + { + var sessionContextType = (Type)args["SessionContextType"]; + var sessionContextProvider = _scope.Resolve(); + MethodInfo method = sessionContextProvider.GetType() + .GetMethod(nameof(ISessionProvider.GetSession)) + ?.MakeGenericMethod(sessionContextType); + + var session = method.Invoke(sessionContextProvider, null).As(); + return session; + } + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`method` could be null (last assigned on line 53) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +ISession NhActiveTransactionProvider.GetSession(ActiveTransactionProviderArgs) + +### File: +src/Stove.NHibernate/NHibernate/NhActiveTransactionProvider.cs + +### Key: +NhActiveTransactionProvider.cs|GetSession|NULLPTR_DEREFERENCE + +### Hash: +6009982a628106b59ae468c9c618d1fa + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1281/instruction.md b/inferredbugs-1281/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e7fdf8577ae1a9eb1ffeda2f3e36943205e187ca --- /dev/null +++ b/inferredbugs-1281/instruction.md @@ -0,0 +1,738 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** bepuphysics1 +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using BEPUphysics.CollisionTests.Manifolds; + +using BEPUutilities; +using BEPUutilities.DataStructures; + +namespace BEPUphysics.CollisionShapes +{ + /// + /// The local space data needed by a Terrain collidable. + /// Contains the Heightmap and other information. + /// + public class TerrainShape : CollisionShape + { + private float[,] heights; + //note: changing heights in array does not fire OnShapeChanged automatically. + //Need to notify parent manually if you do it. + /// + /// Gets or sets the height field of the terrain shape. + /// + public float[,] Heights + { + get + { + return heights; + } + set + { + heights = value; + OnShapeChanged(); + } + } + + + + QuadTriangleOrganization quadTriangleOrganization; + /// + /// Gets or sets the quad triangle organization. + /// + public QuadTriangleOrganization QuadTriangleOrganization + { + get + { + return quadTriangleOrganization; + } + set + { + quadTriangleOrganization = value; + OnShapeChanged(); + } + } + + /// + /// Constructs a TerrainShape. + /// + ///Heights array used for the shape. + ///Triangle organization of each quad. + ///Thrown if the heights array has less than 2x2 vertices. + public TerrainShape(float[,] heights, QuadTriangleOrganization triangleOrganization) + { + if (heights.GetLength(0) <= 1 || heights.GetLength(1) <= 1) + { + throw new ArgumentException("Terrains must have a least 2x2 vertices (one quad)."); + } + this.heights = heights; + quadTriangleOrganization = triangleOrganization; + } + + /// + /// Constructs a TerrainShape. + /// + ///Heights array used for the shape. + public TerrainShape(float[,] heights) + : this(heights, QuadTriangleOrganization.BottomLeftUpperRight) + { + } + + + + /// + /// Constructs the bounding box of the terrain given a transform. + /// + ///Transform to apply to the terrain during the bounding box calculation. + ///Bounding box of the terrain shape when transformed. + public void GetBoundingBox(ref AffineTransform transform, out BoundingBox boundingBox) + { +#if !WINDOWS + boundingBox = new BoundingBox(); +#endif + float minX = float.MaxValue, maxX = -float.MaxValue, + minY = float.MaxValue, maxY = -float.MaxValue, + minZ = float.MaxValue, maxZ = -float.MaxValue; + Vector3 minXvertex = new Vector3(), + maxXvertex = new Vector3(), + minYvertex = new Vector3(), + maxYvertex = new Vector3(), + minZvertex = new Vector3(), + maxZvertex = new Vector3(); + + //Find the extreme locations. + for (int i = 0; i < heights.GetLength(0); i++) + { + for (int j = 0; j < heights.GetLength(1); j++) + { + var vertex = new Vector3(i, heights[i, j], j); + Matrix3x3.Transform(ref vertex, ref transform.LinearTransform, out vertex); + if (vertex.X < minX) + { + minX = vertex.X; + minXvertex = vertex; + } + else if (vertex.X > maxX) + { + maxX = vertex.X; + maxXvertex = vertex; + } + + if (vertex.Y < minY) + { + minY = vertex.Y; + minYvertex = vertex; + } + else if (vertex.Y > maxY) + { + maxY = vertex.Y; + maxYvertex = vertex; + } + + if (vertex.Z < minZ) + { + minZ = vertex.Z; + minZvertex = vertex; + } + else if (vertex.Z > maxZ) + { + maxZ = vertex.Z; + maxZvertex = vertex; + } + } + } + + //Shift the bounding box. + boundingBox.Min.X = minXvertex.X + transform.Translation.X; + boundingBox.Min.Y = minYvertex.Y + transform.Translation.Y; + boundingBox.Min.Z = minZvertex.Z + transform.Translation.Z; + boundingBox.Max.X = maxXvertex.X + transform.Translation.X; + boundingBox.Max.Y = maxYvertex.Y + transform.Translation.Y; + boundingBox.Max.Z = maxZvertex.Z + transform.Translation.Z; + } + + /// + /// Tests a ray against the terrain shape. + /// + ///Ray to test against the shape. + ///Maximum length of the ray in units of the ray direction's length. + ///Transform to apply to the terrain shape during the test. + ///Hit data of the ray cast, if any. + ///Whether or not the ray hit the transformed terrain shape. + public bool RayCast(ref Ray ray, float maximumLength, ref AffineTransform transform, out RayHit hit) + { + return RayCast(ref ray, maximumLength, ref transform, TriangleSidedness.Counterclockwise, out hit); + } + /// + /// Tests a ray against the terrain shape. + /// + ///Ray to test against the shape. + ///Maximum length of the ray in units of the ray direction's length. + ///Transform to apply to the terrain shape during the test. + ///Sidedness of the triangles to use when raycasting. + ///Hit data of the ray cast, if any. + ///Whether or not the ray hit the transformed terrain shape. + public bool RayCast(ref Ray ray, float maximumLength, ref AffineTransform transform, TriangleSidedness sidedness, out RayHit hit) + { + hit = new RayHit(); + //Put the ray into local space. + Ray localRay; + AffineTransform inverse; + AffineTransform.Invert(ref transform, out inverse); + Matrix3x3.Transform(ref ray.Direction, ref inverse.LinearTransform, out localRay.Direction); + AffineTransform.Transform(ref ray.Position, ref inverse, out localRay.Position); + + //Use rasterizey traversal. + //The origin is at 0,0,0 and the map goes +X, +Y, +Z. + //if it's before the origin and facing away, or outside the max and facing out, early out. + float maxX = heights.GetLength(0) - 1; + float maxZ = heights.GetLength(1) - 1; + + Vector3 progressingOrigin = localRay.Position; + float distance = 0; + //Check the outside cases first. + if (progressingOrigin.X < 0) + { + if (localRay.Direction.X > 0) + { + //Off the left side. + float timeToMinX = -progressingOrigin.X / localRay.Direction.X; + distance += timeToMinX; + Vector3 increment; + Vector3.Multiply(ref localRay.Direction, timeToMinX, out increment); + Vector3.Add(ref increment, ref progressingOrigin, out progressingOrigin); + } + else + return false; //Outside and pointing away from the terrain. + } + else if (progressingOrigin.X > maxX) + { + if (localRay.Direction.X < 0) + { + //Off the left side. + float timeToMinX = -(progressingOrigin.X - maxX) / localRay.Direction.X; + distance += timeToMinX; + Vector3 increment; + Vector3.Multiply(ref localRay.Direction, timeToMinX, out increment); + Vector3.Add(ref increment, ref progressingOrigin, out progressingOrigin); + } + else + return false; //Outside and pointing away from the terrain. + } + + if (progressingOrigin.Z < 0) + { + if (localRay.Direction.Z > 0) + { + float timeToMinZ = -progressingOrigin.Z / localRay.Direction.Z; + distance += timeToMinZ; + Vector3 increment; + Vector3.Multiply(ref localRay.Direction, timeToMinZ, out increment); + Vector3.Add(ref increment, ref progressingOrigin, out progressingOrigin); + } + else + return false; + } + else if (progressingOrigin.Z > maxZ) + { + if (localRay.Direction.Z < 0) + { + float timeToMinZ = -(progressingOrigin.Z - maxZ) / localRay.Direction.Z; + distance += timeToMinZ; + Vector3 increment; + Vector3.Multiply(ref localRay.Direction, timeToMinZ, out increment); + Vector3.Add(ref increment, ref progressingOrigin, out progressingOrigin); + } + else + return false; + } + + if (distance > maximumLength) + return false; + + + + //By now, we should be entering the main body of the terrain. + + int xCell = (int)progressingOrigin.X; + int zCell = (int)progressingOrigin.Z; + //If it's hitting the border and going in, then correct the index + //so that it will initially target a valid quad. + //Without this, a quad beyond the border would be tried and failed. + if (xCell == heights.GetLength(0) - 1 && localRay.Direction.X < 0) + xCell = heights.GetLength(0) - 2; + if (zCell == heights.GetLength(1) - 1 && localRay.Direction.Z < 0) + zCell = heights.GetLength(1) - 2; + + while (true) + { + //Check for a miss. + if (xCell < 0 || + zCell < 0 || + xCell >= heights.GetLength(0) - 1 || + zCell >= heights.GetLength(1) - 1) + return false; + + //Test the triangles of this cell. + Vector3 v1, v2, v3, v4; + // v3 v4 + // v1 v2 + GetLocalPosition(xCell, zCell, out v1); + GetLocalPosition(xCell + 1, zCell, out v2); + GetLocalPosition(xCell, zCell + 1, out v3); + GetLocalPosition(xCell + 1, zCell + 1, out v4); + RayHit hit1, hit2; + bool didHit1; + bool didHit2; + + //Don't bother doing ray intersection tests if the ray can't intersect it. + + float highest = v1.Y; + float lowest = v1.Y; + if (v2.Y > highest) + highest = v2.Y; + else if (v2.Y < lowest) + lowest = v2.Y; + if (v3.Y > highest) + highest = v3.Y; + else if (v3.Y < lowest) + lowest = v3.Y; + if (v4.Y > highest) + highest = v4.Y; + else if (v4.Y < lowest) + lowest = v4.Y; + + + if (!(progressingOrigin.Y > highest && localRay.Direction.Y > 0 || + progressingOrigin.Y < lowest && localRay.Direction.Y < 0)) + { + + + if (quadTriangleOrganization == QuadTriangleOrganization.BottomLeftUpperRight) + { + //Always perform the raycast as if Y+ in local space is the way the triangles are facing. + didHit1 = Toolbox.FindRayTriangleIntersection(ref localRay, maximumLength, sidedness, ref v1, ref v2, ref v3, out hit1); + didHit2 = Toolbox.FindRayTriangleIntersection(ref localRay, maximumLength, sidedness, ref v2, ref v4, ref v3, out hit2); + } + else //if (quadTriangleOrganization == CollisionShapes.QuadTriangleOrganization.BottomRightUpperLeft) + { + didHit1 = Toolbox.FindRayTriangleIntersection(ref localRay, maximumLength, sidedness, ref v1, ref v2, ref v4, out hit1); + didHit2 = Toolbox.FindRayTriangleIntersection(ref localRay, maximumLength, sidedness, ref v1, ref v4, ref v3, out hit2); + } + if (didHit1 && didHit2) + { + if (hit1.T < hit2.T) + { + Vector3.Multiply(ref ray.Direction, hit1.T, out hit.Location); + Vector3.Add(ref hit.Location, ref ray.Position, out hit.Location); + Matrix3x3.TransformTranspose(ref hit1.Normal, ref inverse.LinearTransform, out hit.Normal); + hit.T = hit1.T; + return true; + } + Vector3.Multiply(ref ray.Direction, hit2.T, out hit.Location); + Vector3.Add(ref hit.Location, ref ray.Position, out hit.Location); + Matrix3x3.TransformTranspose(ref hit2.Normal, ref inverse.LinearTransform, out hit.Normal); + hit.T = hit2.T; + return true; + } + else if (didHit1) + { + Vector3.Multiply(ref ray.Direction, hit1.T, out hit.Location); + Vector3.Add(ref hit.Location, ref ray.Position, out hit.Location); + Matrix3x3.TransformTranspose(ref hit1.Normal, ref inverse.LinearTransform, out hit.Normal); + hit.T = hit1.T; + return true; + } + else if (didHit2) + { + Vector3.Multiply(ref ray.Direction, hit2.T, out hit.Location); + Vector3.Add(ref hit.Location, ref ray.Position, out hit.Location); + Matrix3x3.TransformTranspose(ref hit2.Normal, ref inverse.LinearTransform, out hit.Normal); + hit.T = hit2.T; + return true; + } + } + + //Move to the next cell. + + float timeToX; + if (localRay.Direction.X < 0) + timeToX = -(progressingOrigin.X - xCell) / localRay.Direction.X; + else if (ray.Direction.X > 0) + timeToX = (xCell + 1 - progressingOrigin.X) / localRay.Direction.X; + else + timeToX = float.MaxValue; + + float timeToZ; + if (localRay.Direction.Z < 0) + timeToZ = -(progressingOrigin.Z - zCell) / localRay.Direction.Z; + else if (localRay.Direction.Z > 0) + timeToZ = (zCell + 1 - progressingOrigin.Z) / localRay.Direction.Z; + else + timeToZ = float.MaxValue; + + //Move to the next cell. + if (timeToX < timeToZ) + { + if (localRay.Direction.X < 0) + xCell--; + else + xCell++; + + distance += timeToX; + if (distance > maximumLength) + return false; + + Vector3 increment; + Vector3.Multiply(ref localRay.Direction, timeToX, out increment); + Vector3.Add(ref increment, ref progressingOrigin, out progressingOrigin); + } + else + { + if (localRay.Direction.Z < 0) + zCell--; + else + zCell++; + + distance += timeToZ; + if (distance > maximumLength) + return false; + + Vector3 increment; + Vector3.Multiply(ref localRay.Direction, timeToZ, out increment); + Vector3.Add(ref increment, ref progressingOrigin, out progressingOrigin); + } + + } + + + } + + /// + /// Gets the position of a vertex at the given indices in local space. + /// + ///Index in the first dimension. + ///Index in the second dimension. + ///Local space position at the given vertice.s + public void GetLocalPosition(int columnIndex, int rowIndex, out Vector3 v) + { +#if !WINDOWS + v = new Vector3(); +#endif + v.X = columnIndex; + v.Y = heights[columnIndex, rowIndex]; + v.Z = rowIndex; + } + + /// + /// Gets the world space position of a vertex in the terrain at the given indices. + /// + ///Index in the first dimension. + ///Index in the second dimension. + /// Transform to apply to the vertex. + /// Transformed position of the vertex at the given indices. + public void GetPosition(int columnIndex, int rowIndex, ref AffineTransform transform, out Vector3 position) + { + if (columnIndex <= 0) + columnIndex = 0; + else if (columnIndex >= heights.GetLength(0)) + columnIndex = heights.GetLength(0) - 1; + if (rowIndex <= 0) + rowIndex = 0; + else if (rowIndex >= heights.GetLength(1)) + rowIndex = heights.GetLength(1) - 1; +#if !WINDOWS + position = new Vector3(); +#endif + position.X = columnIndex; + position.Y = heights[columnIndex, rowIndex]; + position.Z = rowIndex; + AffineTransform.Transform(ref position, ref transform, out position); + + + } + + + /// + /// Gets the non-normalized local space vertex normal at the given indices. + /// + ///Vertex index in the first dimension. + ///Vertex index in the second dimension. + /// Non-normalized local space normal at the given indices. + public void GetLocalNormal(int columnIndex, int rowIndex, out Vector3 normal) + { + + float topHeight = heights[columnIndex, Math.Min(rowIndex + 1, heights.GetLength(1) - 1)]; + float bottomHeight = heights[columnIndex, Math.Max(rowIndex - 1, 0)]; + float rightHeight = heights[Math.Min(columnIndex + 1, heights.GetLength(0) - 1), rowIndex]; + float leftHeight = heights[Math.Max(columnIndex - 1, 0), rowIndex]; + + //Since the horizontal offsets are known to be 1 in local space, we can omit quite a few operations compared to a full Vector3 and cross product. + + //The implicit vectors are: + //var leftToRight = new Vector3(2, rightHeight - leftHeight, 0); + //var bottomToTop = new Vector3(0, topHeight - bottomHeight, 2); + //the result is then: + //Vector3.Cross(bottomToTop, leftToRight); + //Which is: + //float resultX = bottomToTop.Y * leftToRight.Z - bottomToTop.Z * leftToRight.Y; + //float resultY = bottomToTop.Z * leftToRight.X - bottomToTop.X * leftToRight.Z; + //float resultZ = bottomToTop.X * leftToRight.Y - bottomToTop.Y * leftToRight.X; + //Which becomes: + //float resultX = bottomToTop.Y * 0 - 2 * leftToRight.Y; + //float resultY = 2 * 2 - 0 * 0; + //float resultZ = 0 * leftToRight.Y - bottomToTop.Y * 2; + //Which becomes: + normal.X = rightHeight - leftHeight; + normal.Y = 2; + normal.Z = topHeight - bottomHeight; + + } + + + /// + /// Gets overlapped triangles with the terrain shape with a bounding box in the local space of the shape. + /// + ///Bounding box in the local space of the terrain shape. + ///Indices of triangles whose bounding boxes overlap the input bounding box. Encoded as 2 * (quadRowIndex * terrainWidthInQuads + quadColumnIndex) + isFirstTriangleOfQuad ? 0 : 1, where isFirstTriangleOfQuad refers to which of the two triangles in a quad is being requested. Matches the input of the TerrainShape.GetTriangle function. + ///Type of the list to fill with overlaps. + public bool GetOverlaps(BoundingBox localBoundingBox, ref T overlappedElements) where T : IList //Designed to work with value type ILists, hence anti-boxing interface constraint and ref. + { + int width = heights.GetLength(0); + int minX = Math.Max((int)localBoundingBox.Min.X, 0); + int minY = Math.Max((int)localBoundingBox.Min.Z, 0); + int maxX = Math.Min((int)localBoundingBox.Max.X, width - 2); + int maxY = Math.Min((int)localBoundingBox.Max.Z, heights.GetLength(1) - 2); + for (int i = minX; i <= maxX; i++) + { + for (int j = minY; j <= maxY; j++) + { + //Before adding a triangle to the list, make sure the object isn't too high or low from the quad. + float highest, lowest; + float y1 = heights[i, j]; + float y2 = heights[i + 1, j]; + float y3 = heights[i, j + 1]; + float y4 = heights[i + 1, j + 1]; + + highest = y1; + lowest = y1; + if (y2 > highest) + highest = y2; + else if (y2 < lowest) + lowest = y2; + if (y3 > highest) + highest = y3; + else if (y3 < lowest) + lowest = y3; + if (y4 > highest) + highest = y4; + else if (y4 < lowest) + lowest = y4; + + + if (localBoundingBox.Max.Y < lowest || + localBoundingBox.Min.Y > highest) + continue; + + //Now the local bounding box is very likely intersecting those of the triangles. + //Add the triangles to the list. + int quadIndex = (i + j * width) << 1; + overlappedElements.Add(quadIndex); + overlappedElements.Add(quadIndex | 1); + + + } + } + return overlappedElements.Count > 0; + } + + + /// + /// Gets the first triangle of the quad at the given indices in world space. + /// + ///Index of the triangle's quad in the first dimension. + ///Index of the triangle's quad in the second dimension. + ///Transform to apply to the triangle vertices. + ///First vertex of the triangle. + ///Second vertex of the triangle. + ///Third vertex of the triangle. + public void GetFirstTriangle(int columnIndex, int rowIndex, ref AffineTransform transform, out Vector3 a, out Vector3 b, out Vector3 c) + { + if (quadTriangleOrganization == QuadTriangleOrganization.BottomLeftUpperRight) + { + GetPosition(columnIndex, rowIndex, ref transform, out a); + GetPosition(columnIndex + 1, rowIndex, ref transform, out b); + GetPosition(columnIndex, rowIndex + 1, ref transform, out c); + } + else + { + GetPosition(columnIndex, rowIndex, ref transform, out a); + GetPosition(columnIndex + 1, rowIndex, ref transform, out b); + GetPosition(columnIndex + 1, rowIndex + 1, ref transform, out c); + } + } + + /// + /// Gets the second triangle of the quad at the given indices in world space. + /// + ///Index of the triangle's quad in the first dimension. + ///Index of the triangle's quad in the second dimension. + ///Transform to apply to the triangle vertices. + ///First vertex of the triangle. + ///Second vertex of the triangle. + ///Third vertex of the triangle. + public void GetSecondTriangle(int columnIndex, int rowIndex, ref AffineTransform transform, out Vector3 a, out Vector3 b, out Vector3 c) + { + if (quadTriangleOrganization == QuadTriangleOrganization.BottomLeftUpperRight) + { + GetPosition(columnIndex, rowIndex + 1, ref transform, out a); + GetPosition(columnIndex + 1, rowIndex + 1, ref transform, out b); + GetPosition(columnIndex + 1, rowIndex, ref transform, out c); + } + else + { + GetPosition(columnIndex, rowIndex, ref transform, out a); + GetPosition(columnIndex, rowIndex + 1, ref transform, out b); + GetPosition(columnIndex + 1, rowIndex + 1, ref transform, out c); + } + } + + + /// + /// Gets a world space triangle in the terrain at the given triangle index. + /// + ///Index of the triangle. Encoded as 2 * (quadRowIndex * terrainWidthInQuads + quadColumnIndex) + isFirstTriangleOfQuad ? 0 : 1, where isFirstTriangleOfQuad refers to which of the two triangles in a quad is being requested. Matches the output of the TerrainShape.GetOverlaps function. + ///Transform to apply to the triangle vertices. + ///First vertex of the triangle. + ///Second vertex of the triangle. + ///Third vertex of the triangle. + public void GetTriangle(int index, ref AffineTransform transform, out Vector3 a, out Vector3 b, out Vector3 c) + { + //Find the quad. + int quadIndex = index / 2; + //TODO: This division could be avoided if you're willing to get tricky or impose some size requirements. + int rowIndex = quadIndex / heights.GetLength(0); + int columnIndex = quadIndex - rowIndex * heights.GetLength(0); + if ((index & 1) == 0) //Check if this is the first or second triangle. + { + GetFirstTriangle(columnIndex, rowIndex, ref transform, out a, out b, out c); + } + else + { + GetSecondTriangle(columnIndex, rowIndex, ref transform, out a, out b, out c); + } + } + + + + internal void GetLocalIndices(int i, out TerrainVertexIndices a, out TerrainVertexIndices b, out TerrainVertexIndices c) + { + int quadIndex = i / 2; + //TODO: This division could be avoided if you're willing to get tricky or impose some size requirements. + int rowIndex = quadIndex / heights.GetLength(0); + int columnIndex = quadIndex - rowIndex * heights.GetLength(0); + if ((i & 1) == 0) //Check if this is the first or second triangle. + { + if (quadTriangleOrganization == QuadTriangleOrganization.BottomLeftUpperRight) + { + a = new TerrainVertexIndices { ColumnIndex = columnIndex, RowIndex = rowIndex }; + b = new TerrainVertexIndices { ColumnIndex = columnIndex + 1, RowIndex = rowIndex }; + c = new TerrainVertexIndices { ColumnIndex = columnIndex, RowIndex = rowIndex + 1 }; + } + else + { + a = new TerrainVertexIndices { ColumnIndex = columnIndex, RowIndex = rowIndex }; + b = new TerrainVertexIndices { ColumnIndex = columnIndex + 1, RowIndex = rowIndex }; + c = new TerrainVertexIndices { ColumnIndex = columnIndex + 1, RowIndex = rowIndex + 1 }; + } + } + else + { + if (quadTriangleOrganization == QuadTriangleOrganization.BottomLeftUpperRight) + { + a = new TerrainVertexIndices { ColumnIndex = columnIndex, RowIndex = rowIndex + 1 }; + c = new TerrainVertexIndices { ColumnIndex = columnIndex + 1, RowIndex = rowIndex + 1 }; + b = new TerrainVertexIndices { ColumnIndex = columnIndex + 1, RowIndex = rowIndex }; + } + else + { + a = new TerrainVertexIndices { ColumnIndex = columnIndex, RowIndex = rowIndex }; + b = new TerrainVertexIndices { ColumnIndex = columnIndex + 1, RowIndex = rowIndex + 1 }; + c = new TerrainVertexIndices { ColumnIndex = columnIndex, RowIndex = rowIndex + 1 }; + } + } + } + } + + /// + /// Defines how a Terrain organizes triangles in its quads. + /// + public enum QuadTriangleOrganization + { + /// + /// Triangle with a right angle at the (-i,-j) position and another at the (+i,+j) position. + /// + BottomLeftUpperRight, + /// + /// Triangle with a right angle at the (+i,-j) position and another at the high (-i,+j) position. + /// + BottomRightUpperLeft + } +} + +``` + +### Bug Type: +PULSE_UNINITIALIZED_VALUE + +### Qualifier: +`b.BEPUutilities.Vector3.X` is read without initialization during the call to `Vector3.Add(...)`. + +### Severity: +ERROR + +### Procedure: +Boolean TerrainShape.RayCast(Ray&,Single,AffineTransform&,TriangleSidedness,RayHit&) + +### File: +BEPUphysics/CollisionShapes/TerrainShape.cs + +### Key: +TerrainShape.cs|RayCast|PULSE_UNINITIALIZED_VALUE + +### Hash: +1a5c091fb9be3d7a0478fe38779043bf + +### Bug Type Hum: +Uninitialized Value + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1286/instruction.md b/inferredbugs-1286/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2cfc054e9152e4455df11c57e568b0e39dcf7c13 --- /dev/null +++ b/inferredbugs-1286/instruction.md @@ -0,0 +1,188 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** BeatSaber-IPA-Reloaded +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.Remoting.Messaging; +using System.Threading; +using IllusionPlugin; + +namespace IllusionPlugin { + public class Logger { + private readonly Queue _logQueue; + private readonly FileInfo _logFile; + private readonly Thread _watcherThread; + private bool _threadRunning; + + private string ModName; + + private logMessage oldLog; + + struct logMessage { + public WarningLevel WarningLevel; + public string Message; + + public logMessage(string msg, WarningLevel wl) { + Message = msg; + WarningLevel = wl; + } + } + + enum WarningLevel { + Log, Error, Exception, Warning + } + + public Logger(string modName = "Default") { + _logQueue = new Queue(); + _logFile = GetPath(modName); + _watcherThread = new Thread(QueueWatcher) {IsBackground = true}; + _threadRunning = true; + Start(); + } + + public Logger(IPlugin plugin) { + _logQueue = new Queue(); + _logFile = GetPath(plugin); + _watcherThread = new Thread(QueueWatcher) {IsBackground = true}; + _threadRunning = true; + Start(); + } + + public void Log(string msg) { + if(!_watcherThread.IsAlive) throw new Exception("Logger is Closed!"); + _logQueue.Enqueue(new logMessage($"[LOG @ {DateTime.Now:HH:mm:ss} | {ModName}] {msg}", WarningLevel.Log)); + } + + public void Error(string msg) { + if(!_watcherThread.IsAlive) throw new Exception("Logger is Closed!"); + _logQueue.Enqueue(new logMessage($"[ERROR @ {DateTime.Now:HH:mm:ss} | {ModName}] {msg}", WarningLevel.Error)); + } + + public void Exception(string msg) { + if(!_watcherThread.IsAlive) throw new Exception("Logger is Closed!"); + _logQueue.Enqueue(new logMessage($"[EXCEPTION @ {DateTime.Now:HH:mm:ss} | {ModName}] {msg}", WarningLevel.Exception)); + } + + public void Warning(string msg) { + if(!_watcherThread.IsAlive) throw new Exception("Logger is Closed!"); + _logQueue.Enqueue(new logMessage($"[WARNING @ {DateTime.Now:HH:mm:ss} | {ModName}] {msg}", WarningLevel.Warning)); + } + + void QueueWatcher() { + _logFile.Create().Close(); + while (_threadRunning) { + if (_logQueue.Count > 0) { + _watcherThread.IsBackground = false; + using (var f = _logFile.AppendText()) { + while (_logQueue.Count > 0) { + var d = _logQueue.Dequeue(); + if (d.Message == oldLog.Message) return; + oldLog = d; + f.WriteLine(d.Message); + Console.ForegroundColor = GetConsoleColour(d.WarningLevel); + Console.WriteLine(d.Message); + Console.ResetColor(); + } + } + + _watcherThread.IsBackground = true; + } + } + } + + void Start() => _watcherThread.Start(); + + public void Stop() { + _threadRunning = false; + _watcherThread.Join(); + } + + ConsoleColor GetConsoleColour(WarningLevel level) { + switch (level) { + case WarningLevel.Log: + return ConsoleColor.Green; + case WarningLevel.Error: + return ConsoleColor.Yellow; + case WarningLevel.Exception: + return ConsoleColor.Red; + case WarningLevel.Warning: + return ConsoleColor.Blue; + default: + return ConsoleColor.Gray; + } + } + + FileInfo GetPath(IPlugin plugin) => GetPath(plugin.Name); + FileInfo GetPath(string modName) { + ModName = modName; + var logsDir = new DirectoryInfo($"./Logs/{modName}/{DateTime.Now:dd-MM-yy}"); + logsDir.Create(); + return new FileInfo($"{logsDir.FullName}/{logsDir.GetFiles().Length}.txt"); + } + } + + public static class DebugExtensions { + public static Logger GetLogger(this IPlugin plugin) { + return new Logger(plugin); + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `f` last assigned on line 74 could be null and is dereferenced at line 79, column 29. + +### Severity: +ERROR + +### Procedure: +Void Logger.QueueWatcher() + +### File: +IllusionPlugin/Logger.cs + +### Key: +Logger.cs|QueueWatcher|NULL_DEREFERENCE + +### Node Key: +6ac572f395f06247af690f692a52fd7b + +### Hash: +bdb8d2fca1355e1405b6cf0bd106ce5d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1287/instruction.md b/inferredbugs-1287/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8d39506a54aa30affe4a7063a9a73434104ec770 --- /dev/null +++ b/inferredbugs-1287/instruction.md @@ -0,0 +1,189 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** BeatSaber-IPA-Reloaded +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.Remoting.Messaging; +using System.Threading; +using IllusionPlugin; + +namespace IllusionPlugin { + public class Logger { + private readonly Queue _logQueue; + private readonly FileInfo _logFile; + private readonly Thread _watcherThread; + private bool _threadRunning; + + private string ModName; + + private logMessage oldLog; + + struct logMessage { + public WarningLevel WarningLevel; + public string Message; + + public logMessage(string msg, WarningLevel wl) { + Message = msg; + WarningLevel = wl; + } + } + + enum WarningLevel { + Log, Error, Exception, Warning + } + + public Logger(string modName = "Default") { + _logQueue = new Queue(); + _logFile = GetPath(modName); + _watcherThread = new Thread(QueueWatcher) {IsBackground = true}; + _threadRunning = true; + Start(); + } + + public Logger(IPlugin plugin) { + _logQueue = new Queue(); + _logFile = GetPath(plugin); + _watcherThread = new Thread(QueueWatcher) {IsBackground = true}; + _threadRunning = true; + Start(); + } + + public void Log(string msg) { + if(!_watcherThread.IsAlive) throw new Exception("Logger is Closed!"); + _logQueue.Enqueue(new logMessage($"[LOG @ {DateTime.Now:HH:mm:ss} | {ModName}] {msg}", WarningLevel.Log)); + } + + public void Error(string msg) { + if(!_watcherThread.IsAlive) throw new Exception("Logger is Closed!"); + _logQueue.Enqueue(new logMessage($"[ERROR @ {DateTime.Now:HH:mm:ss} | {ModName}] {msg}", WarningLevel.Error)); + } + + public void Exception(string msg) { + if(!_watcherThread.IsAlive) throw new Exception("Logger is Closed!"); + _logQueue.Enqueue(new logMessage($"[EXCEPTION @ {DateTime.Now:HH:mm:ss} | {ModName}] {msg}", WarningLevel.Exception)); + } + + public void Warning(string msg) { + if(!_watcherThread.IsAlive) throw new Exception("Logger is Closed!"); + _logQueue.Enqueue(new logMessage($"[WARNING @ {DateTime.Now:HH:mm:ss} | {ModName}] {msg}", WarningLevel.Warning)); + } + + void QueueWatcher() { + _logFile.Create().Close(); + while (_threadRunning) { + if (_logQueue.Count > 0) { + _watcherThread.IsBackground = false; + using (var f = _logFile.AppendText()) { + while (_logQueue.Count > 0) { + var d = _logQueue.Dequeue(); + if (d.Message == oldLog.Message) return; + oldLog = d; + f.WriteLine(d.Message); + Console.ForegroundColor = GetConsoleColour(d.WarningLevel); + Console.WriteLine(d.Message); + Console.ResetColor(); + } + } + + _watcherThread.IsBackground = true; + } + } + Thread.Sleep(5); + } + + void Start() => _watcherThread.Start(); + + public void Stop() { + _threadRunning = false; + _watcherThread.Join(); + } + + ConsoleColor GetConsoleColour(WarningLevel level) { + switch (level) { + case WarningLevel.Log: + return ConsoleColor.Green; + case WarningLevel.Error: + return ConsoleColor.Yellow; + case WarningLevel.Exception: + return ConsoleColor.Red; + case WarningLevel.Warning: + return ConsoleColor.Blue; + default: + return ConsoleColor.Gray; + } + } + + FileInfo GetPath(IPlugin plugin) => GetPath(plugin.Name); + FileInfo GetPath(string modName) { + ModName = modName; + var logsDir = new DirectoryInfo($"./Logs/{modName}/{DateTime.Now:dd-MM-yy}"); + logsDir.Create(); + return new FileInfo($"{logsDir.FullName}/{logsDir.GetFiles().Length}.txt"); + } + } + + public static class DebugExtensions { + public static Logger GetLogger(this IPlugin plugin) { + return new Logger(plugin); + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `f` last assigned on line 74 could be null and is dereferenced at line 79, column 29. + +### Severity: +ERROR + +### Procedure: +Void Logger.QueueWatcher() + +### File: +IllusionPlugin/Logger.cs + +### Key: +Logger.cs|QueueWatcher|NULL_DEREFERENCE + +### Node Key: +6ac572f395f06247af690f692a52fd7b + +### Hash: +bdb8d2fca1355e1405b6cf0bd106ce5d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1288/instruction.md b/inferredbugs-1288/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..01d696b213ab0e7e14ef8c0e9fb71303c00cc864 --- /dev/null +++ b/inferredbugs-1288/instruction.md @@ -0,0 +1,437 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** StackExchange.Redis +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Threading; + +namespace StackExchange.Redis +{ + /// + /// A SocketManager monitors multiple sockets for availability of data; this is done using + /// the Socket.Select API and a dedicated reader-thread, which allows for fast responses + /// even when the system is under ambient load. + /// + public sealed class SocketManager : IDisposable + { + private readonly string name; + + /// + /// Creates a new (optionally named) SocketManager instance + /// + public SocketManager(string name = null) + { + if (string.IsNullOrWhiteSpace(name)) name = GetType().Name; + this.name = name; + } + + /// + /// Gets the name of this SocketManager instance + /// + public string Name { get { return name; } } + + bool isDisposed; + private readonly Dictionary socketLookup = new Dictionary(); + + struct SocketPair + { + public readonly Socket Socket; + public readonly ISocketCallback Callback; + public SocketPair(Socket socket, ISocketCallback callback) + { + this.Socket = socket; + this.Callback = callback; + } + } + + /// + /// Adds a new socket and callback to the manager + /// + private void AddRead(Socket socket, ISocketCallback callback) + { + if (socket == null) throw new ArgumentNullException("socket"); + if (callback == null) throw new ArgumentNullException("callback"); + + lock (socketLookup) + { + if (isDisposed) throw new ObjectDisposedException(name); + + var handle = socket.Handle; + if(handle == IntPtr.Zero) throw new ObjectDisposedException("socket"); + socketLookup.Add(handle, new SocketPair(socket, callback)); + if (socketLookup.Count == 1) + { + Monitor.PulseAll(socketLookup); + if (Interlocked.CompareExchange(ref readerCount, 0, 0) == 0) + StartReader(); + } + + } + } + + private void StartReader() + { + var thread = new Thread(read, 32 * 1024); // don't need a huge stack + thread.Name = name + ":Read"; + thread.IsBackground = true; + thread.Priority = ThreadPriority.AboveNormal; // time critical + thread.Start(this); + } + + private static ParameterizedThreadStart read = state => ((SocketManager)state).Read(); + private void Read() + { + bool weAreReader = false; + try + { + weAreReader = Interlocked.CompareExchange(ref readerCount, 1, 0) == 0; + if (weAreReader) ReadImpl(); + } + catch (Exception ex) + { + Debug.WriteLine(ex); + Trace.WriteLine(ex); + } + finally + { + if (weAreReader) Interlocked.Exchange(ref readerCount, 0); + } + } + + readonly Queue readQueue = new Queue(), errorQueue = new Queue(); + + static readonly IntPtr[] EmptyPointers = new IntPtr[0]; + private void ReadImpl() + { + List dead = null, active = new List(); + IntPtr[] readSockets = EmptyPointers, errorSockets = EmptyPointers; + while (true) + { + active.Clear(); + if (dead != null) dead.Clear(); + lock (socketLookup) + { + if (isDisposed) return; + + if (socketLookup.Count == 0) + { + // if empty, give it a few seconds chance before exiting + Monitor.Wait(socketLookup, TimeSpan.FromSeconds(20)); + if (socketLookup.Count == 0) return; // nothing new came in, so exit + } + foreach (var pair in socketLookup) + { + var socket = pair.Value.Socket; + if(socket.Handle == pair.Key && socket.Connected) + if (pair.Value.Socket.Connected) + { + active.Add(pair.Key); + } + else + { + (dead ?? (dead = new List())).Add(pair.Key); + } + } + if (dead != null && dead.Count != 0) + { + foreach (var socket in dead) socketLookup.Remove(socket); + } + } + int pollingSockets = active.Count; + if (pollingSockets == 0) + { + // nobody had actual sockets; just sleep + Thread.Sleep(10); + continue; + } + + if (readSockets.Length < active.Count + 1) + { + ConnectionMultiplexer.TraceWithoutContext("Resizing socket array for " + active.Count + " sockets"); + readSockets = new IntPtr[active.Count + 6]; // leave so space for growth + errorSockets = new IntPtr[active.Count + 6]; + } + readSockets[0] = errorSockets[0] = (IntPtr)active.Count; + active.CopyTo(readSockets, 1); + active.CopyTo(errorSockets, 1); + int ready; + try + { + var timeout = new TimeValue(100); + ready = select(0, readSockets, null, errorSockets, ref timeout); + if (ready <= 0) + { + continue; // -ve typically means a socket was disposed just before; just retry + } + + ConnectionMultiplexer.TraceWithoutContext((int)readSockets[0] != 0, "Read sockets: " + (int)readSockets[0]); + ConnectionMultiplexer.TraceWithoutContext((int)errorSockets[0] != 0, "Error sockets: " + (int)errorSockets[0]); + } + catch (Exception ex) + { // this typically means a socket was disposed just before; just retry + Trace.WriteLine(ex.Message); + continue; + } + + int queueCount = (int)readSockets[0]; + lock(readQueue) + { + for (int i = 1; i <= queueCount; i++) + { + readQueue.Enqueue(readSockets[i]); + } + } + queueCount = (int)errorSockets[0]; + lock (errorQueue) + { + for (int i = 1; i <= queueCount; i++) + { + errorQueue.Enqueue(errorSockets[i]); + } + } + + + if (ready >= 5) // number of sockets we should attempt to process by ourself before asking for help + { + // seek help, work in parallel, then synchronize + lock (QueueDrainSyncLock) + { + ThreadPool.QueueUserWorkItem(HelpProcessItems, this); + ProcessItems(); + Monitor.Wait(QueueDrainSyncLock); + } + } + else + { + // just do it ourself + ProcessItems(); + } + } + } + + [DllImport("ws2_32.dll", SetLastError = true)] + internal static extern int select([In] int ignoredParameter, [In, Out] IntPtr[] readfds, [In, Out] IntPtr[] writefds, [In, Out] IntPtr[] exceptfds, [In] ref TimeValue timeout); + + [StructLayout(LayoutKind.Sequential)] + internal struct TimeValue + { + public int Seconds; + public int Microseconds; + public TimeValue(int microSeconds) + { + Seconds = (int)(microSeconds / 1000000L); + Microseconds = (int)(microSeconds % 1000000L); + } + } + + internal void Shutdown(SocketToken token) + { + var socket = token.Socket; + if (socket != null) + { + lock (socketLookup) + { + socketLookup.Remove(socket.Handle); + } + try { socket.Shutdown(SocketShutdown.Both); } catch { } + try { socket.Close(); } catch { } + try { socket.Dispose(); } catch { } + } + } + + private readonly object QueueDrainSyncLock = new object(); + static readonly WaitCallback HelpProcessItems = state => + { + var mgr = (SocketManager)state; + mgr.ProcessItems(); + lock (mgr.QueueDrainSyncLock) + { + Monitor.PulseAll(mgr.QueueDrainSyncLock); + } + }; + + private void ProcessItems() + { + ProcessItems(socketLookup, readQueue, CallbackOperation.Read); + ProcessItems(socketLookup, errorQueue, CallbackOperation.Error); + } + + private static void ProcessItems(Dictionary socketLookup, Queue queue, CallbackOperation operation) + + { + if (queue == null) return; + while (true) + { + // get the next item (note we could be competing with a worker here, hence lock) + IntPtr handle; + lock (queue) + { + if (queue.Count == 0) break; + handle = queue.Dequeue(); + } + SocketPair pair; + lock (socketLookup) + { + if (!socketLookup.TryGetValue(handle, out pair)) continue; + } + var callback = pair.Callback; + if (callback != null) + { +#if VERBOSE + var watch = Stopwatch.StartNew(); +#endif + switch (operation) + { + case CallbackOperation.Read: callback.Read(); break; + case CallbackOperation.Error: callback.Error(); break; + } +#if VERBOSE + watch.Stop(); + ConnectionMultiplexer.TraceWithoutContext(string.Format("{0}: {1}ms on {2}", operation, watch.ElapsedMilliseconds, callback)); +#endif + } + } + } + + private enum CallbackOperation + { + Read, + Error + } + + private int readerCount; + + /// + /// Releases all resources associated with this instance + /// + public void Dispose() + { + lock (socketLookup) + { + isDisposed = true; + socketLookup.Clear(); + Monitor.PulseAll(socketLookup); + } + } + + internal SocketToken BeginConnect(EndPoint endpoint, ISocketCallback callback) + { + var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + socket.NoDelay = true; + socket.BeginConnect(endpoint, EndConnect, Tuple.Create(socket, callback)); + return new SocketToken(socket); + } + private void EndConnect(IAsyncResult ar) + { + Tuple tuple = null; + try + { + tuple = (Tuple)ar.AsyncState; + var socket = tuple.Item1; + var callback = tuple.Item2; + socket.EndConnect(ar); + AddRead(socket, callback); + var netStream = new NetworkStream(socket, false); + callback.Connected(netStream); + } + catch + { + if (tuple != null) + { + tuple.Item2.Error(); + } + } + } + } + /// + /// Allows callbacks from SocketManager as work is discovered + /// + internal interface ISocketCallback + { + /// + /// Indicates that a socket has connected + /// + void Connected(Stream stream); + /// + /// Indicates that data is available on the socket, and that the consumer should read from the socket + /// + void Read(); + /// + /// Indicates that the socket has signalled an error condition + /// + void Error(); + } + + internal struct SocketToken + { + internal readonly Socket Socket; + public SocketToken(Socket socket) + { + this.Socket = socket; + } + public int Available { get { return Socket == null ? 0 : Socket.Available; } } + + public bool HasValue { get { return Socket != null; } } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource netStream of type System.Net.Sockets.NetworkStream in method "Void SocketManager.EndConnect(IAsyncResult)". + +### Severity: +ERROR + +### Procedure: +Void SocketManager.EndConnect(IAsyncResult) + +### File: +StackExchange.Redis/StackExchange/Redis/SocketManager.cs + +### Key: +SocketManager.cs|EndConnect|DOTNET_RESOURCE_LEAK + +### Hash: +5e32d264c327235bd6339d817d435072 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1289/instruction.md b/inferredbugs-1289/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63d8be46612754aa9f4dcaa966fe01d27a98f9d6 --- /dev/null +++ b/inferredbugs-1289/instruction.md @@ -0,0 +1,171 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** bUnit +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Threading.Tasks; +using Bunit.Extensions; +using Bunit.JSInterop; +using Bunit.RazorTesting; +using Bunit.Rendering; +using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.JSInterop; + +namespace Bunit +{ + /// + /// A component used to create snapshot tests. + /// Snapshot tests takes two child inputs, a TestInput section and a ExpectedOutput section. + /// It then compares the result of rendering both using semantic HTML comparison. + /// + public class SnapshotTest : RazorTestBase + { + /// + /// Gets bUnits JSInterop, that allows setting up handlers for invocations + /// that components under tests will issue during testing. It also makes it possible to verify that the invocations has happened as expected. + /// + public BunitJSInterop JSInterop { get; } = new BunitJSInterop(); + + /// + public override string? DisplayName => Description; + + /// + /// Sets the setup action to perform before the and + /// is rendered and compared. + /// + [Parameter] public Action? Setup { get; set; } + + /// + /// Sets the setup action to perform before the and + /// is rendered and compared. + /// + [Parameter] public Func? SetupAsync { get; set; } + + /// + /// Gets or sets the input to the snapshot test. + /// + [Parameter] public RenderFragment? TestInput { get; set; } + + /// + /// Gets or sets the expected output of the snapshot test. + /// + [Parameter] public RenderFragment? ExpectedOutput { get; set; } + + /// + /// Creates an instance of the type. + /// + public SnapshotTest() + { + JSInterop.AddBuiltInJSRuntimeInvocationHandlers(); + Services.AddSingleton(JSInterop.JSRuntime); + Services.AddDefaultTestContextServices(); + } + + /// + protected override async Task Run() + { + Validate(); + + if (Setup is not null) + TryRun(Setup, this); + if (SetupAsync is not null) + await TryRunAsync(SetupAsync, this).ConfigureAwait(false); + + var renderedTestInput = this.RenderInsideRenderTree(TestInput!); + var inputHtml = renderedTestInput.Markup; + + var renderedExpectedRender = this.RenderInsideRenderTree(ExpectedOutput!); + var expectedHtml = renderedExpectedRender.Markup; + + VerifySnapshot(inputHtml, expectedHtml); + } + + private void VerifySnapshot(string inputHtml, string expectedHtml) + { + using var parser = new BunitHtmlParser(); + var inputNodes = parser.Parse(inputHtml); + var expectedNodes = parser.Parse(expectedHtml); + + var diffs = inputNodes.CompareTo(expectedNodes); + + if (diffs.Count > 0) + throw new HtmlEqualException(diffs, expectedNodes, inputNodes, Description ?? "Snapshot test failed."); + } + + /// + public override Task SetParametersAsync(ParameterView parameters) + { + Setup = parameters.GetValueOrDefault>(nameof(Setup)); + SetupAsync = parameters.GetValueOrDefault>(nameof(SetupAsync)); + TestInput = parameters.GetValueOrDefault(nameof(TestInput)); + ExpectedOutput = parameters.GetValueOrDefault(nameof(ExpectedOutput)); + return base.SetParametersAsync(parameters); + } + + /// + public override void Validate() + { + base.Validate(); + if (TestInput is null) + throw new ArgumentException($"No {nameof(TestInput)} specified in the {nameof(SnapshotTest)} component."); + if (ExpectedOutput is null) + throw new ArgumentException($"No {nameof(ExpectedOutput)} specified in the {nameof(SnapshotTest)} component."); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource parser of type Bunit.Rendering.BunitHtmlParser in method "Void SnapshotTest.VerifySnapshot(String,String)". + +### Severity: +ERROR + +### Procedure: +Void SnapshotTest.VerifySnapshot(String,String) + +### File: +src/bunit.web/RazorTesting/SnapshotTest.cs + +### Key: +SnapshotTest.cs|VerifySnapshot|DOTNET_RESOURCE_LEAK + +### Hash: +f95dfa79cbf8f72f7786a699baca01b0 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1308/instruction.md b/inferredbugs-1308/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2cd08bfc741f18c03df060cc61ba18ffc6c904a5 --- /dev/null +++ b/inferredbugs-1308/instruction.md @@ -0,0 +1,1235 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** MagicalLife +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// RTree.java +// Java Spatial Index Library +// Copyright (C) 2002 Infomatiq Limited +// Copyright (C) 2008 Aled Morris aled@sourceforge.net +// +// 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 + +// Ported to C# By Dror Gluska, April 9th, 2009 + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; + +namespace MagicalLifeAPI.DataTypes.R +{ + /// + /// This is a lightweight RTree implementation, specifically designed + /// for the following features (in order of importance): + /// + /// Fast intersection query performance. To achieve this, the RTree + /// uses only main memory to store entries. Obviously this will only improve + /// performance if there is enough physical memory to avoid paging. + /// Low memory requirements. + /// Fast add performance. + /// + /// + /// The main reason for the high speed of this RTree implementation is the + /// avoidance of the creation of unnecessary objects, mainly achieved by using + /// primitive collections from the trove4j library. + /// author aled@sourceforge.net + /// version 1.0b2p1 + /// Ported to C# By Dror Gluska, April 9th, 2009 + /// + /// + public class RTree + { + private const int locking_timeout = 10000; + + private ReaderWriterLock locker = new ReaderWriterLock(); + private const string version = "1.0b2p2"; + + // parameters of the tree + private const int DEFAULT_MAX_NODE_ENTRIES = 10; + + internal int maxNodeEntries; + private int minNodeEntries; + + // map of nodeId -> Node<T> object + // [x] TODO eliminate this map - it should not be needed. Nodes + // can be found by traversing the tree. + //private TIntObjectHashMap nodeMap = new TIntObjectHashMap(); + private Dictionary> nodeMap = new Dictionary>(); + + // internal consistency checking - set to true if debugging tree corruption + public bool INTERNAL_CONSISTENCY_CHECKING = false; + + // used to mark the status of entries during a Node<T> split + private const int ENTRY_STATUS_ASSIGNED = 0; + + private const int ENTRY_STATUS_UNASSIGNED = 1; + private byte[] entryStatus = null; + private byte[] initialEntryStatus = null; + + // stacks used to store nodeId and entry index of each Node<T> + // from the root down to the leaf. Enables fast lookup + // of nodes when a split is propagated up the tree. + //private TIntStack parents = new TIntStack(); + private Stack parents = new Stack(); + + //private TIntStack parentsEntry = new TIntStack(); + private Stack parentsEntry = new Stack(); + + // initialisation + private int treeHeight = 1; // leaves are always level 1 + + private int rootNodeId = 0; + private int msize = 0; + + // Enables creation of new nodes + //private int highestUsedNodeId = rootNodeId; + private int highestUsedNodeId = 0; + + // Deleted Node<T> objects are retained in the nodeMap, + // so that they can be reused. Store the IDs of nodes + // which can be reused. + //private TIntStack deletedNodeIds = new TIntStack(); + private Stack deletedNodeIds = new Stack(); + + // List of nearest rectangles. Use a member variable to + // avoid recreating the object each time nearest() is called. + //private TIntArrayList nearestIds = new TIntArrayList(); + //List nearestIds = new List(); + + //Added dictionaries to support generic objects.. + //possibility to change the code to support objects without dictionaries. + private Dictionary IdsToItems = new Dictionary(); + + private Dictionary ItemsToIds = new Dictionary(); + private volatile int idcounter = int.MinValue; + + /// + /// Initialize implementation dependent properties of the RTree. + /// + public RTree() + { + init(); + } + + /// + /// Initialize implementation dependent properties of the RTree. + /// + /// his specifies the maximum number of entries + ///in a node. The default value is 10, which is used if the property is + ///not specified, or is less than 2. + /// This specifies the minimum number of entries + ///in a node. The default value is half of the MaxNodeEntries value (rounded + ///down), which is used if the property is not specified or is less than 1. + /// + public RTree(int MaxNodeEntries, int MinNodeEntries) + { + minNodeEntries = MinNodeEntries; + maxNodeEntries = MaxNodeEntries; + init(); + } + + private void init() + { + locker.AcquireWriterLock(locking_timeout); + // Obviously a Node<T> with less than 2 entries cannot be split. + // The Node<T> splitting algorithm will work with only 2 entries + // per node, but will be inefficient. + if (maxNodeEntries < 2) + { + Debug.WriteLine($"Invalid MaxNodeEntries = {maxNodeEntries} Resetting to default value of {DEFAULT_MAX_NODE_ENTRIES}"); + maxNodeEntries = DEFAULT_MAX_NODE_ENTRIES; + } + + // The MinNodeEntries must be less than or equal to (int) (MaxNodeEntries / 2) + if (minNodeEntries < 1 || minNodeEntries > maxNodeEntries / 2) + { + Debug.WriteLine("MinNodeEntries must be between 1 and MaxNodeEntries / 2"); + minNodeEntries = maxNodeEntries / 2; + } + + entryStatus = new byte[maxNodeEntries]; + initialEntryStatus = new byte[maxNodeEntries]; + + for (int i = 0; i < maxNodeEntries; i++) + { + initialEntryStatus[i] = ENTRY_STATUS_UNASSIGNED; + } + + Node root = new Node(rootNodeId, 1, maxNodeEntries); + nodeMap.Add(rootNodeId, root); + + Debug.WriteLine($"init() MaxNodeEntries = {maxNodeEntries}, MinNodeEntries = {minNodeEntries}"); + locker.ReleaseWriterLock(); + } + + /// + /// Adds an item to the spatial index + /// + /// + /// + public void Add(Rectangle r, T item) + { + locker.AcquireWriterLock(locking_timeout); + idcounter++; + int id = idcounter; + + IdsToItems.Add(id, item); + ItemsToIds.Add(item, id); + + add(r, id); + locker.ReleaseWriterLock(); + } + + private void add(Rectangle r, int id) + { + Debug.WriteLine($"Adding rectangle {r}, id {id}"); + + add(r.copy(), id, 1); + + msize++; + } + + /// + /// Adds a new entry at a specified level in the tree + /// + /// + /// + /// + private void add(Rectangle r, int id, int level) + { + // I1 [Find position for new record] Invoke ChooseLeaf to select a + // leaf Node<T> L in which to place r + Node n = chooseNode(r, level); + Node newLeaf = null; + + // I2 [Add record to leaf node] If L has room for another entry, + // install E. Otherwise invoke SplitNode to obtain L and LL containing + // E and all the old entries of L + if (n.entryCount < maxNodeEntries) + { + n.addEntryNoCopy(r, id); + } + else + { + newLeaf = splitNode(n, r, id); + } + + // I3 [Propagate changes upwards] Invoke AdjustTree on L, also passing LL + // if a split was performed + Node newNode = adjustTree(n, newLeaf); + + // I4 [Grow tree taller] If Node<T> split propagation caused the root to + // split, create a new root whose children are the two resulting nodes. + if (newNode != null) + { + int oldRootNodeId = rootNodeId; + Node oldRoot = getNode(oldRootNodeId); + + rootNodeId = getNextNodeId(); + treeHeight++; + Node root = new Node(rootNodeId, treeHeight, maxNodeEntries); + root.addEntry(newNode.mbr, newNode.nodeId); + root.addEntry(oldRoot.mbr, oldRoot.nodeId); + nodeMap.Add(rootNodeId, root); + } + + if (INTERNAL_CONSISTENCY_CHECKING) + { + checkConsistency(rootNodeId, treeHeight, null); + } + } + + /// + /// Deletes an item from the spatial index + /// + /// + /// + /// + public bool Delete(Rectangle r, T item) + { + locker.AcquireWriterLock(locking_timeout); + int id = ItemsToIds[item]; + + bool success = delete(r, id); + if (success == true) + { + IdsToItems.Remove(id); + ItemsToIds.Remove(item); + } + locker.ReleaseWriterLock(); + return success; + } + + private bool delete(Rectangle r, int id) + { + // FindLeaf algorithm inlined here. Note the "official" algorithm + // searches all overlapping entries. This seems inefficient to me, + // as an entry is only worth searching if it contains (NOT overlaps) + // the rectangle we are searching for. + // + // Also the algorithm has been changed so that it is not recursive. + + // FL1 [Search subtrees] If root is not a leaf, check each entry + // to determine if it contains r. For each entry found, invoke + // findLeaf on the Node<T> pointed to by the entry, until r is found or + // all entries have been checked. + parents.Clear(); + parents.Push(rootNodeId); + + parentsEntry.Clear(); + parentsEntry.Push(-1); + Node n = null; + int foundIndex = -1; // index of entry to be deleted in leaf + + while (foundIndex == -1 && parents.Count > 0) + { + n = getNode(parents.Peek()); + int startIndex = parentsEntry.Peek() + 1; + + if (!n.isLeaf()) + { + Debug.WriteLine($"searching Node {n.nodeId}, from index {startIndex}"); + bool contains = false; + for (int i = startIndex; i < n.entryCount; i++) + { + if (n.entries[i].contains(r)) + { + parents.Push(n.ids[i]); + parentsEntry.Pop(); + parentsEntry.Push(i); // this becomes the start index when the child has been searched + parentsEntry.Push(-1); + contains = true; + break; // ie go to next iteration of while() + } + } + if (contains) + { + continue; + } + } + else + { + foundIndex = n.findEntry(r, id); + } + + parents.Pop(); + parentsEntry.Pop(); + } // while not found + + if (foundIndex != -1) + { + n.deleteEntry(foundIndex, minNodeEntries); + condenseTree(n); + msize--; + } + + // shrink the tree if possible (i.e. if root Node<T%gt; has exactly one entry,and that + // entry is not a leaf node, delete the root (it's entry becomes the new root) + Node root = getNode(rootNodeId); + while (root.entryCount == 1 && treeHeight > 1) + { + root.entryCount = 0; + rootNodeId = root.ids[0]; + treeHeight--; + root = getNode(rootNodeId); + } + + return (foundIndex != -1); + } + + /// + /// Retrieve nearest items to a point in radius furthestDistance + /// + /// Point of origin + /// maximum distance + /// List of items + public List Nearest(Point p, float furthestDistance) + { + List retval = new List(); + locker.AcquireReaderLock(locking_timeout); + nearest(p, (int id) => + { + retval.Add(IdsToItems[id]); + }, furthestDistance); + locker.ReleaseReaderLock(); + return retval; + } + + private void nearest(Point p, Action v, float furthestDistance) + { + Node rootNode = getNode(rootNodeId); + + List nearestIds = new List(); + + nearest(p, rootNode, nearestIds, furthestDistance); + + foreach (int id in nearestIds) + { + v(id); + } + + nearestIds.Clear(); + } + + /// + /// Retrieve items which intersect with Rectangle r + /// + /// + /// + public List Intersects(Rectangle r) + { + List retval = new List(); + locker.AcquireReaderLock(locking_timeout); + intersects(r, (int id) => + { + retval.Add(IdsToItems[id]); + }); + locker.ReleaseReaderLock(); + return retval; + } + + private void intersects(Rectangle r, Action v) + { + Node rootNode = getNode(rootNodeId); + intersects(r, v, rootNode); + } + + /// + /// find all rectangles in the tree that are contained by the passed rectangle + /// written to be non-recursive (should model other searches on this?) + /// + /// + public List Contains(Rectangle r) + { + List retval = new List(); + locker.AcquireReaderLock(locking_timeout); + contains(r, (int id) => + { + retval.Add(IdsToItems[id]); + }); + + locker.ReleaseReaderLock(); + return retval; + } + + private void contains(Rectangle r, Action v) + { + Stack _parents = new Stack(); + //private TIntStack parentsEntry = new TIntStack(); + Stack _parentsEntry = new Stack(); + + // find all rectangles in the tree that are contained by the passed rectangle + // written to be non-recursive (should model other searches on this?) + + _parents.Clear(); + _parents.Push(rootNodeId); + + _parentsEntry.Clear(); + _parentsEntry.Push(-1); + + // TODO: possible shortcut here - could test for intersection with the + // MBR of the root node. If no intersection, return immediately. + + while (_parents.Count > 0) + { + Node n = getNode(_parents.Peek()); + int startIndex = _parentsEntry.Peek() + 1; + + if (!n.isLeaf()) + { + // go through every entry in the index Node to check + // if it intersects the passed rectangle. If so, it + // could contain entries that are contained. + bool intersects = false; + for (int i = startIndex; i < n.entryCount; i++) + { + if (r.intersects(n.entries[i])) + { + _parents.Push(n.ids[i]); + _parentsEntry.Pop(); + _parentsEntry.Push(i); // this becomes the start index when the child has been searched + _parentsEntry.Push(-1); + intersects = true; + break; // ie go to next iteration of while() + } + } + if (intersects) + { + continue; + } + } + else + { + // go through every entry in the leaf to check if + // it is contained by the passed rectangle + for (int i = 0; i < n.entryCount; i++) + { + if (r.contains(n.entries[i])) + { + v(n.ids[i]); + } + } + } + _parents.Pop(); + _parentsEntry.Pop(); + } + } + + /// + /// Returns the bounds of all the entries in the spatial index, or null if there are no entries. + /// + public Rectangle getBounds() + { + Rectangle bounds = null; + + locker.AcquireReaderLock(locking_timeout); + Node n = getNode(getRootNodeId()); + if (n != null && n.getMBR() != null) + { + bounds = n.getMBR().copy(); + } + locker.ReleaseReaderLock(); + return bounds; + } + + /// + /// Returns a string identifying the type of spatial index, and the version number + /// + public string getVersion() + { + return "RTree-" + version; + } + + //------------------------------------------------------------------------- + // end of SpatialIndex methods + //------------------------------------------------------------------------- + + /// + /// Get the next available Node<T> ID. Reuse deleted Node<T> IDs if + /// possible + /// + private int getNextNodeId() + { + if (deletedNodeIds.Count > 0) + { + return deletedNodeIds.Pop(); + } + else + { + return 1 + highestUsedNodeId++; + } + } + + /// + /// Get a Node<T> object, given the ID of the node. + /// + /// + /// + private Node getNode(int index) + { + return (Node)nodeMap[index]; + } + + /// + /// Get the highest used Node<T> ID + /// + /// + private int getHighestUsedNodeId() + { + return highestUsedNodeId; + } + + /// + /// Get the root Node<T> ID + /// + /// + public int getRootNodeId() + { + return rootNodeId; + } + + /// + /// Split a node. Algorithm is taken pretty much verbatim from + /// Guttman's original paper. + /// + /// + /// + /// + /// return new Node<T> object. + private Node splitNode(Node n, Rectangle newRect, int newId) + { + // [Pick first entry for each group] Apply algorithm pickSeeds to + // choose two entries to be the first elements of the groups. Assign + // each to a group. + + // debug code +#if DEBUG + float initialArea = 0; + Rectangle union = n.mbr.union(newRect); + initialArea = union.area(); +#endif + + System.Array.Copy(initialEntryStatus, 0, entryStatus, 0, maxNodeEntries); + + Node newNode = null; + newNode = new Node(getNextNodeId(), n.level, maxNodeEntries); + nodeMap.Add(newNode.nodeId, newNode); + + pickSeeds(n, newRect, newId, newNode); // this also sets the entryCount to 1 + + // [Check if done] If all entries have been assigned, stop. If one + // group has so few entries that all the rest must be assigned to it in + // order for it to have the minimum number m, assign them and stop. + while (n.entryCount + newNode.entryCount < maxNodeEntries + 1) + { + if (maxNodeEntries + 1 - newNode.entryCount == minNodeEntries) + { + // assign all remaining entries to original node + for (int i = 0; i < maxNodeEntries; i++) + { + if (entryStatus[i] == ENTRY_STATUS_UNASSIGNED) + { + entryStatus[i] = ENTRY_STATUS_ASSIGNED; + n.mbr.add(n.entries[i]); + n.entryCount++; + } + } + break; + } + if (maxNodeEntries + 1 - n.entryCount == minNodeEntries) + { + // assign all remaining entries to new node + for (int i = 0; i < maxNodeEntries; i++) + { + if (entryStatus[i] == ENTRY_STATUS_UNASSIGNED) + { + entryStatus[i] = ENTRY_STATUS_ASSIGNED; + newNode.addEntryNoCopy(n.entries[i], n.ids[i]); + n.entries[i] = null; + } + } + break; + } + + // [Select entry to assign] Invoke algorithm pickNext to choose the + // next entry to assign. Add it to the group whose covering rectangle + // will have to be enlarged least to accommodate it. Resolve ties + // by adding the entry to the group with smaller area, then to the + // the one with fewer entries, then to either. Repeat from S2 + pickNext(n, newNode); + } + + n.reorganize(this); + + // check that the MBR stored for each Node<T> is correct. + if (INTERNAL_CONSISTENCY_CHECKING) + { + if (!n.mbr.Equals(calculateMBR(n))) + { + Debug.WriteLine("Error: splitNode old Node MBR wrong"); + } + + if (!newNode.mbr.Equals(calculateMBR(newNode))) + { + Debug.WriteLine("Error: splitNode new Node MBR wrong"); + } + } + + // debug code +#if DEBUG + float newArea = n.mbr.area() + newNode.mbr.area(); + float percentageIncrease = (100 * (newArea - initialArea)) / initialArea; + Debug.WriteLine($"Node { n.nodeId} split. New area increased by {percentageIncrease}%"); +#endif + + return newNode; + } + + /// + /// Pick the seeds used to split a node. + /// Select two entries to be the first elements of the groups + /// + /// + /// + /// + /// + private void pickSeeds(Node n, Rectangle newRect, int newId, Node newNode) + { + // Find extreme rectangles along all dimension. Along each dimension, + // find the entry whose rectangle has the highest low side, and the one + // with the lowest high side. Record the separation. + float maxNormalizedSeparation = 0; + int highestLowIndex = 0; + int lowestHighIndex = 0; + + // for the purposes of picking seeds, take the MBR of the Node<T> to include + // the new rectangle aswell. + n.mbr.add(newRect); + + Debug.WriteLine($"pickSeeds(): NodeId = {n.nodeId}, newRect = {newRect}"); + + for (int d = 0; d < Rectangle.DIMENSIONS; d++) + { + float tempHighestLow = newRect.min[d]; + int tempHighestLowIndex = -1; // -1 indicates the new rectangle is the seed + + float tempLowestHigh = newRect.max[d]; + int tempLowestHighIndex = -1; + + for (int i = 0; i < n.entryCount; i++) + { + float tempLow = n.entries[i].min[d]; + if (tempLow >= tempHighestLow) + { + tempHighestLow = tempLow; + tempHighestLowIndex = i; + } + else + { // ensure that the same index cannot be both lowestHigh and highestLow + float tempHigh = n.entries[i].max[d]; + if (tempHigh <= tempLowestHigh) + { + tempLowestHigh = tempHigh; + tempLowestHighIndex = i; + } + } + + // PS2 [Adjust for shape of the rectangle cluster] Normalize the separations + // by dividing by the widths of the entire set along the corresponding + // dimension + float normalizedSeparation = (tempHighestLow - tempLowestHigh) / (n.mbr.max[d] - n.mbr.min[d]); + + if (normalizedSeparation > 1 || normalizedSeparation < -1) + { + Debug.WriteLine("Invalid normalized separation"); + } + + Debug.WriteLine($"Entry {i}, dimension {d}: HighestLow = {tempHighestLow} (index {tempHighestLowIndex})" + ", LowestHigh = " + + tempLowestHigh + $" (index {tempLowestHighIndex}, NormalizedSeparation = {normalizedSeparation}"); + + // PS3 [Select the most extreme pair] Choose the pair with the greatest + // normalized separation along any dimension. + if (normalizedSeparation > maxNormalizedSeparation) + { + maxNormalizedSeparation = normalizedSeparation; + highestLowIndex = tempHighestLowIndex; + lowestHighIndex = tempLowestHighIndex; + } + } + } + + // highestLowIndex is the seed for the new node. + if (highestLowIndex == -1) + { + newNode.addEntry(newRect, newId); + } + else + { + newNode.addEntryNoCopy(n.entries[highestLowIndex], n.ids[highestLowIndex]); + n.entries[highestLowIndex] = null; + + // move the new rectangle into the space vacated by the seed for the new node + n.entries[highestLowIndex] = newRect; + n.ids[highestLowIndex] = newId; + } + + // lowestHighIndex is the seed for the original node. + if (lowestHighIndex == -1) + { + lowestHighIndex = highestLowIndex; + } + + entryStatus[lowestHighIndex] = ENTRY_STATUS_ASSIGNED; + n.entryCount = 1; + n.mbr.set(n.entries[lowestHighIndex].min, n.entries[lowestHighIndex].max); + } + + /// + /// Pick the next entry to be assigned to a group during a Node<T> split. + /// [Determine cost of putting each entry in each group] For each + /// entry not yet in a group, calculate the area increase required + /// in the covering rectangles of each group + /// + /// + /// + /// + private int pickNext(Node n, Node newNode) + { + float maxDifference = float.NegativeInfinity; + int next = 0; + int nextGroup = 0; + + maxDifference = float.NegativeInfinity; + + Debug.WriteLine("pickNext()"); + + for (int i = 0; i < maxNodeEntries; i++) + { + if (entryStatus[i] == ENTRY_STATUS_UNASSIGNED) + { + if (n.entries[i] == null) + { + Debug.WriteLine($"Error: Node {n.nodeId}, entry {i} is null"); + } + + float nIncrease = n.mbr.enlargement(n.entries[i]); + float newNodeIncrease = newNode.mbr.enlargement(n.entries[i]); + float difference = Math.Abs(nIncrease - newNodeIncrease); + + if (difference > maxDifference) + { + next = i; + + if (nIncrease < newNodeIncrease) + { + nextGroup = 0; + } + else if (newNodeIncrease < nIncrease) + { + nextGroup = 1; + } + else if (n.mbr.area() < newNode.mbr.area()) + { + nextGroup = 0; + } + else if (newNode.mbr.area() < n.mbr.area()) + { + nextGroup = 1; + } + else if (newNode.entryCount < maxNodeEntries / 2) + { + nextGroup = 0; + } + else + { + nextGroup = 1; + } + maxDifference = difference; + } + + Debug.WriteLine($"Entry {i} group0 increase = {nIncrease}, group1 increase = {newNodeIncrease}, diff = " + + difference + $", MaxDiff = {maxDifference} (entry {next})"); + } + } + + entryStatus[next] = ENTRY_STATUS_ASSIGNED; + + if (nextGroup == 0) + { + n.mbr.add(n.entries[next]); + n.entryCount++; + } + else + { + // move to new node. + newNode.addEntryNoCopy(n.entries[next], n.ids[next]); + n.entries[next] = null; + } + + return next; + } + + /// + /// Recursively searches the tree for the nearest entry. Other queries + /// call execute() on an IntProcedure when a matching entry is found; + /// however nearest() must store the entry Ids as it searches the tree, + /// in case a nearer entry is found. + /// Uses the member variable nearestIds to store the nearest + /// entry IDs. + /// + /// TODO rewrite this to be non-recursive? + /// + /// + /// + /// + private float nearest(Point p, Node n, List nearestIds, float nearestDistance) + { + for (int i = 0; i < n.entryCount; i++) + { + float tempDistance = n.entries[i].distance(p); + if (n.isLeaf()) + { // for leaves, the distance is an actual nearest distance + if (tempDistance < nearestDistance) + { + nearestDistance = tempDistance; + nearestIds.Clear(); + } + if (tempDistance <= nearestDistance) + { + nearestIds.Add(n.ids[i]); + } + } + else + { // for index nodes, only go into them if they potentially could have + // a rectangle nearer than actualNearest + if (tempDistance <= nearestDistance) + { + // search the child node + nearestDistance = nearest(p, getNode(n.ids[i]), nearestIds, nearestDistance); + } + } + } + return nearestDistance; + } + + /// + /// Recursively searches the tree for all intersecting entries. + /// Immediately calls execute() on the passed IntProcedure when + /// a matching entry is found. + /// [x] TODO rewrite this to be non-recursive? Make sure it + /// doesn't slow it down. + /// + /// + /// + /// + private void intersects(Rectangle r, Action v, Node n) + { + for (int i = 0; i < n.entryCount; i++) + { + if (r.intersects(n.entries[i])) + { + if (n.isLeaf()) + { + v(n.ids[i]); + } + else + { + Node childNode = getNode(n.ids[i]); + intersects(r, v, childNode); + } + } + } + } + + private Rectangle oldRectangle = new Rectangle(0, 0, 0, 0); + + /// + /// Used by delete(). Ensures that all nodes from the passed node + /// up to the root have the minimum number of entries. + /// + /// Note that the parent and parentEntry stacks are expected to + /// contain the nodeIds of all parents up to the root. + /// + /// + private void condenseTree(Node l) + { + // CT1 [Initialize] Set n=l. Set the list of eliminated + // nodes to be empty. + Node n = l; + Node parent = null; + int parentEntry = 0; + + //TIntStack eliminatedNodeIds = new TIntStack(); + Stack eliminatedNodeIds = new Stack(); + + // CT2 [Find parent entry] If N is the root, go to CT6. Otherwise + // let P be the parent of N, and let En be N's entry in P + while (n.level != treeHeight) + { + parent = getNode(parents.Pop()); + parentEntry = parentsEntry.Pop(); + + // CT3 [Eliminiate under-full node] If N has too few entries, + // delete En from P and add N to the list of eliminated nodes + if (n.entryCount < minNodeEntries) + { + parent.deleteEntry(parentEntry, minNodeEntries); + eliminatedNodeIds.Push(n.nodeId); + } + else + { + // CT4 [Adjust covering rectangle] If N has not been eliminated, + // adjust EnI to tightly contain all entries in N + if (!n.mbr.Equals(parent.entries[parentEntry])) + { + oldRectangle.set(parent.entries[parentEntry].min, parent.entries[parentEntry].max); + parent.entries[parentEntry].set(n.mbr.min, n.mbr.max); + parent.recalculateMBR(oldRectangle); + } + } + // CT5 [Move up one level in tree] Set N=P and repeat from CT2 + n = parent; + } + + // CT6 [Reinsert orphaned entries] Reinsert all entries of nodes in set Q. + // Entries from eliminated leaf nodes are reinserted in tree leaves as in + // Insert(), but entries from higher level nodes must be placed higher in + // the tree, so that leaves of their dependent subtrees will be on the same + // level as leaves of the main tree + while (eliminatedNodeIds.Count > 0) + { + Node e = getNode(eliminatedNodeIds.Pop()); + for (int j = 0; j < e.entryCount; j++) + { + add(e.entries[j], e.ids[j], e.level); + e.entries[j] = null; + } + e.entryCount = 0; + deletedNodeIds.Push(e.nodeId); + nodeMap.Remove(e.nodeId); + } + } + + /// + /// Used by add(). Chooses a leaf to add the rectangle to. + /// + private Node chooseNode(Rectangle r, int level) + { + // CL1 [Initialize] Set N to be the root node + Node n = getNode(rootNodeId); + parents.Clear(); + parentsEntry.Clear(); + + // CL2 [Leaf check] If N is a leaf, return N + while (true) + { + if (n == null) + { + Debug.WriteLine($"Could not get root Node ({rootNodeId})"); + } + + if (n.level == level) + { + return n; + } + + // CL3 [Choose subtree] If N is not at the desired level, let F be the entry in N + // whose rectangle FI needs least enlargement to include EI. Resolve + // ties by choosing the entry with the rectangle of smaller area. + float leastEnlargement = n.getEntry(0).enlargement(r); + int index = 0; // index of rectangle in subtree + for (int i = 1; i < n.entryCount; i++) + { + Rectangle tempRectangle = n.getEntry(i); + float tempEnlargement = tempRectangle.enlargement(r); + if ((tempEnlargement < leastEnlargement) || + ((tempEnlargement == leastEnlargement) && + (tempRectangle.area() < n.getEntry(index).area()))) + { + index = i; + leastEnlargement = tempEnlargement; + } + } + + parents.Push(n.nodeId); + parentsEntry.Push(index); + + // CL4 [Descend until a leaf is reached] Set N to be the child Node<T> + // pointed to by Fp and repeat from CL2 + n = getNode(n.ids[index]); + } + } + + /// + /// Ascend from a leaf Node<T> L to the root, adjusting covering rectangles and + /// propagating Node<T> splits as necessary. + /// + private Node adjustTree(Node n, Node nn) + { + // AT1 [Initialize] Set N=L. If L was split previously, set NN to be + // the resulting second node. + + // AT2 [Check if done] If N is the root, stop + while (n.level != treeHeight) + { + // AT3 [Adjust covering rectangle in parent entry] Let P be the parent + // Node of N, and let En be N's entry in P. Adjust EnI so that it tightly + // encloses all entry rectangles in N. + Node parent = getNode(parents.Pop()); + int entry = parentsEntry.Pop(); + + if (parent.ids[entry] != n.nodeId) + { + Debug.WriteLine($"Error: entry {entry} in Node {parent.nodeId} should point to Node {n.nodeId}; actually points to Node {parent.ids[entry]}"); + } + + if (!parent.entries[entry].Equals(n.mbr)) + { + parent.entries[entry].set(n.mbr.min, n.mbr.max); + parent.mbr.set(parent.entries[0].min, parent.entries[0].max); + for (int i = 1; i < parent.entryCount; i++) + { + parent.mbr.add(parent.entries[i]); + } + } + + // AT4 [Propagate Node split upward] If N has a partner NN resulting from + // an earlier split, create a new entry Enn with Ennp pointing to NN and + // Enni enclosing all rectangles in NN. Add Enn to P if there is room. + // Otherwise, invoke splitNode to produce P and PP containing Enn and + // all P's old entries. + Node newNode = null; + if (nn != null) + { + if (parent.entryCount < maxNodeEntries) + { + parent.addEntry(nn.mbr, nn.nodeId); + } + else + { + newNode = splitNode(parent, nn.mbr.copy(), nn.nodeId); + } + } + + // AT5 [Move up to next level] Set N = P and set NN = PP if a split + // occurred. Repeat from AT2 + n = parent; + nn = newNode; + + parent = null; + newNode = null; + } + + return nn; + } + + /// + /// Check the consistency of the tree. + /// + private void checkConsistency(int nodeId, int expectedLevel, Rectangle expectedMBR) + { + // go through the tree, and check that the internal data structures of + // the tree are not corrupted. + Node n = getNode(nodeId); + + if (n == null) + { + Debug.WriteLine($"Error: Could not read Node {nodeId}"); + } + + if (n.level != expectedLevel) + { + Debug.WriteLine($"Error: Node {nodeId}, expected level {expectedLevel}, actual level {n.level}"); + } + + Rectangle calculatedMBR = calculateMBR(n); + + if (!n.mbr.Equals(calculatedMBR)) + { + Debug.WriteLine($"Error: Node {nodeId}, calculated MBR does not equal stored MBR"); + } + + if (expectedMBR != null && !n.mbr.Equals(expectedMBR)) + { + Debug.WriteLine($"Error: Node {nodeId}, expected MBR (from parent) does not equal stored MBR"); + } + + // Check for corruption where a parent entry is the same object as the child MBR + if (expectedMBR != null && n.mbr.sameObject(expectedMBR)) + { + Debug.WriteLine($"Error: Node {nodeId} MBR using same rectangle object as parent's entry"); + } + + for (int i = 0; i < n.entryCount; i++) + { + if (n.entries[i] == null) + { + Debug.WriteLine($"Error: Node {nodeId}, Entry {i} is null"); + } + + if (n.level > 1) + { // if not a leaf + checkConsistency(n.ids[i], n.level - 1, n.entries[i]); + } + } + } + + /// + /// Given a Node object, calculate the Node MBR from it's entries. + /// Used in consistency checking + /// + private Rectangle calculateMBR(Node n) + { + Rectangle mbr = new Rectangle(n.entries[0].min, n.entries[0].max); + + for (int i = 1; i < n.entryCount; i++) + { + mbr.add(n.entries[i]); + } + return mbr; + } + + public int Count + { + get + { + locker.AcquireReaderLock(locking_timeout); + + int size = this.msize; + + locker.ReleaseReaderLock(); + + return size; + } + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `tempRectangle` last assigned on line 1011 could be null and is dereferenced at line 1012, column 21. + +### Severity: +ERROR + +### Procedure: +Node`1 RTree`1.chooseNode(Rectangle,Int32) + +### File: +MagicalLifeAPIStandard/DataTypes/R-Tree/RTree.cs + +### Key: +RTree.cs|chooseNode|NULL_DEREFERENCE + +### Node Key: +8ac51a8e85f0456c5b35f5ed10b22112 + +### Hash: +371168f4e49c5dfd2d957de94845a104 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1330/instruction.md b/inferredbugs-1330/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..41276f83888788548fb8281fb08d11892344eabc --- /dev/null +++ b/inferredbugs-1330/instruction.md @@ -0,0 +1,235 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** PowerApps-Language-Tooling +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.AppMagic.Authoring.Persistence; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace PAModel.PAConvert.Parser +{ + public class Parser + { + private string _content; + private TokenStream _tokenizer; + private Dictionary _controlStates; + private Dictionary _templates; + + public Parser(string contents, Dictionary controlStates, Dictionary templates) + { + var header = "//! PAFile:0.1"; + + if (!contents.StartsWith(header)) + { + throw new InvalidOperationException($"Illegal pa source file. Missing header"); + } + _content = contents.Substring(header.Length+1); + _tokenizer = new TokenStream(_content); + + _controlStates = controlStates; + _templates = templates; + } + + internal ControlInfoJson.Item ParseControl(string parent = "", bool isComponent = false) + { + if (parent == string.Empty) + { + var token = _tokenizer.GetNextToken(); + if (token.Kind != TokenKind.Control) + throw new InvalidOperationException($"Unexpected token {token.Kind}, expected {TokenKind.Control}"); + isComponent = token.Content == PAConstants.ComponentKeyword; + } + + var identToken = _tokenizer.GetNextToken(); + if (identToken.Kind != TokenKind.Identifier) + throw new InvalidOperationException($"Unexpected token {identToken.Kind}, expected {TokenKind.Identifier}"); + + var name = identToken.Content; + if (!_controlStates.TryGetValue(name, out var control)) + control = new ControlInfoJson.Item(); // Should have an arg for defaults maybe? + + control.Name = name; + if (parent != string.Empty) + control.Parent = parent; + + + var templateSeparator = _tokenizer.GetNextToken(); + if (templateSeparator.Kind != TokenKind.TemplateSeparator) + throw new InvalidOperationException($"Unexpected token {templateSeparator.Kind}, expected {TokenKind.TemplateSeparator}"); + + var templateToken = _tokenizer.GetNextToken(); + if (templateToken.Kind != TokenKind.Identifier) + throw new InvalidOperationException($"Unexpected token {templateToken.Kind}, expected {TokenKind.Identifier}"); + + if (!_templates.TryGetValue(templateToken.Content, out var template)) + { + template = new ControlInfoJson.Template(); // This seems like a problem, maybe we can't recreate templates without npm ref? + template.Name = templateToken.Content; + } + else + { + template = new ControlInfoJson.Template(template); + } + + control.Template = template; + if (isComponent && control.Template.IsComponentDefinition != null) + { + control.Template.IsComponentDefinition = true; + control.Template.ComponentDefinitionInfo = null; + } + + var next = _tokenizer.GetNextToken(); + if (next.Kind == TokenKind.VariantSeparator) + { + var variantToken = _tokenizer.GetNextToken(); + if (variantToken.Kind != TokenKind.Identifier) + throw new InvalidOperationException($"Unexpected token {variantToken.Kind}, expected {TokenKind.Identifier}"); + control.VariantName = variantToken.Content; + + next = _tokenizer.GetNextToken(); + } + + if (next.Kind != TokenKind.Indent) + { + // Handle empty control special case + if (next.Kind == TokenKind.Control) + { + _tokenizer.ReplaceToken(next); + control.Children = new ControlInfoJson.Item[0]; + foreach (var rule in control.Rules) + rule.InvariantScript = string.Empty; + } + + return control; + } + + next = _tokenizer.GetNextToken(); + + var paRules = new Dictionary(); + var children = new List(); + + while (!_tokenizer.Eof && next.Kind != TokenKind.Dedent) + { + switch (next.Kind) + { + case TokenKind.Identifier: + var rule = ParseRule(next.Content); + paRules.Add(rule.propertyName, rule.script); + break; + case TokenKind.Control: + var child = ParseControl(parent: control.Name, next.Content == PAConstants.ComponentKeyword); + children.Add(child); + break; + default: + throw new InvalidOperationException($"Unexpected token {next.Kind}"); + } + + next = _tokenizer.GetNextToken(); + } + + control.Children = children.ToArray(); + + foreach (var rule in control.Rules) + { + if (paRules.TryGetValue(rule.Property, out var script)) + { + rule.InvariantScript = script; + paRules.Remove(rule.Property); + } + else + { + rule.InvariantScript = string.Empty; + } + } + if (paRules.Any()) + { + var rulesList = control.Rules.ToList(); + foreach (var rulePair in paRules) + { + // Needs sensible defaults for other props (maybe from template + rulesList.Add(new ControlInfoJson.RuleEntry() { Property = rulePair.Key, InvariantScript = rulePair.Value }); + } + control.Rules = rulesList.ToArray(); + } + + return control; + } + + private (string propertyName, string script) ParseRule(string propertyName) + { + var propertySeparator = _tokenizer.GetNextToken(); + if (propertySeparator.Kind != TokenKind.PropertyStart) + throw new InvalidOperationException($"Unexpected token {propertySeparator.Kind}, expected {TokenKind.PropertyStart}"); + + var ruleScript = _tokenizer.GetNextToken(expectedExpression: true); + if (ruleScript.Kind != TokenKind.PAExpression) + throw new InvalidOperationException($"Unexpected token {ruleScript.Kind}, expected {TokenKind.PAExpression}"); + + return (propertyName, ruleScript.Content); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `ruleScript` last assigned on line 166 could be null and is dereferenced at line 167, column 13. + +### Severity: +ERROR + +### Procedure: +ValueTuple`2 Parser.ParseRule(String) + +### File: +src/PAModel/PAConvert/Parser/Parser.cs + +### Key: +Parser.cs|ParseRule|NULL_DEREFERENCE + +### Node Key: +90535029835413c6e5d1bdebbf52bdf9 + +### Hash: +de1aff5200da4a22cf968f2b8272c0fd + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1337/instruction.md b/inferredbugs-1337/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9a5cf1aa6d4a826008b263e5b7a5e655a32ad086 --- /dev/null +++ b/inferredbugs-1337/instruction.md @@ -0,0 +1,76 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** OpenCoreMMO +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using NeoServer.Game.Effects.Magical; + +namespace NeoServer.Game.Effects.Parsers +{ + public class AreaTypeParser + { + + public static byte[,] Parse(string areaType) + { + return areaType switch + { + "AREA_CIRCLE3x3" => AreaEffect.Circle3x3, + "AREA_SQUARE1x1" => AreaEffect.Square1x1, + }; + } + } +} + +``` + +### Bug Type: +PULSE_UNINITIALIZED_VALUE + +### Qualifier: +`%0` is read without initialization. + +### Severity: +ERROR + +### Procedure: +AreaType AreaTypeParser.Parse(String) + +### File: +src/NeoServer.Game.Parsers/Parsers/AreaTypeParser.cs + +### Key: +AreaTypeParser.cs|Parse|PULSE_UNINITIALIZED_VALUE + +### Hash: +4eb8555edd74e8a057eef9d7c2ec11d1 + +### Bug Type Hum: +Uninitialized Value + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1412/instruction.md b/inferredbugs-1412/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..770c787edda05d3f8e79aedee1431520b71232ac --- /dev/null +++ b/inferredbugs-1412/instruction.md @@ -0,0 +1,166 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** AniAPI +**Bug ID:** 8 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Commons.Filters; +using MongoDB.Bson; +using MongoDB.Driver; +using MongoService; +using System; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Commons.Collections +{ + public class AnimeSongCollection : ICollection + { + protected override string CollectionName => "anime_song"; + + public override void Add(ref AnimeSong document) + { + base.Add(ref document); + + this.Collection.InsertOne(document); + } + + public override long Count() + { + return this.Collection.CountDocuments(Builders.Filter.Empty); + } + + public override void Delete(long id) + { + throw new NotImplementedException(); + } + + public override void Edit(ref AnimeSong document) + { + base.Edit(ref document); + + var filter = Builders.Filter.Eq("_id", document.Id); + this.Collection.ReplaceOne(filter, document); + } + + public override bool Exists(ref AnimeSong document, bool updateValues = true) + { + long animeID = document.AnimeID; + string title = document.Title; + string artist = document.Artist; + + AnimeSong reference = this.Collection.Find(x => x.Title == title && x.Artist == artist && x.AnimeID == animeID).FirstOrDefault(); + + if(reference != null) + { + if (updateValues) + { + document.Id = reference.Id; + document.CreationDate = reference.CreationDate; + document.UpdateDate = reference.UpdateDate; + } + + return true; + } + + return false; + } + + public override AnimeSong Get(long id) + { + return this.Collection.Find(x => x.Id == id).FirstOrDefault(); + } + + public override Paging GetList(IFilter filter) + { + AnimeSongFilter songFilter = filter as AnimeSongFilter; + + var builder = Builders.Filter; + FilterDefinition queryFilter = builder.Empty; + + if (songFilter.anime_id != null) + { + queryFilter &= builder.Eq("anime_id", songFilter.anime_id); + } + + if (!string.IsNullOrEmpty(songFilter.title)) + { + queryFilter &= builder.Regex("title", new BsonRegularExpression($".*{songFilter.title}.*", "i")); + } + + if(songFilter.year != null) + { + queryFilter &= builder.Eq("year", songFilter.year); + } + + if(songFilter.season != null) + { + queryFilter &= builder.Eq("season", songFilter.season); + } + + if(songFilter.type != null) + { + queryFilter &= builder.Eq("type", songFilter.type); + } + + return new Paging(this.Collection, songFilter.page, queryFilter, songFilter.per_page); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `songFilter` last assigned on line 71 could be null and is dereferenced at line 76, column 13. + +### Severity: +ERROR + +### Procedure: +Paging`1 AnimeSongCollection.GetList(IFilter`1) + +### File: +Commons/Collections/AnimeSongCollection.cs + +### Key: +AnimeSongCollection.cs|GetList|NULL_DEREFERENCE + +### Node Key: +c91b435e0ebdfa03be7f8c2adfdbfd87 + +### Hash: +7b383f7cce6b5b74d7d0505a278476b2 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1413/instruction.md b/inferredbugs-1413/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e884b355236b49e601839a066c6bb75d4d98de0a --- /dev/null +++ b/inferredbugs-1413/instruction.md @@ -0,0 +1,164 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** AniAPI +**Bug ID:** 21 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Commons.Filters; +using MongoDB.Driver; +using MongoService; +using System; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Commons.Collections +{ + public class UserStoryCollection : ICollection + { + protected override string CollectionName => "user_story"; + + public override void Add(ref UserStory document) + { + base.Add(ref document); + + this.Collection.InsertOne(document); + } + + public override long Count() + { + return this.Collection.CountDocuments(Builders.Filter.Empty); + } + + public override void Delete(long id) + { + throw new NotImplementedException(); + } + + public override void Edit(ref UserStory document) + { + base.Edit(ref document); + + var filter = Builders.Filter.Eq("_id", document.Id); + this.Collection.ReplaceOne(filter, document); + } + + public override bool Exists(ref UserStory document, bool updateValues = true) + { + long userId = document.UserID; + long animeId = document.AnimeID; + + UserStory reference = this.Collection.Find(x => x.UserID == userId && x.AnimeID == animeId).FirstOrDefault(); + + if(reference != null) + { + if (updateValues) + { + document.Id = reference.Id; + document.CreationDate = reference.CreationDate; + document.UpdateDate = reference.UpdateDate; + document.Synced = reference.Synced; + } + + return true; + } + + return false; + } + + public override UserStory Get(long id) + { + return this.Collection.Find(x => x.Id == id).FirstOrDefault(); + } + + public override Paging GetList(IFilter filter) + { + UserStoryFilter userStoryFilter = filter as UserStoryFilter; + + var builder = Builders.Filter; + FilterDefinition queryFilter = builder.Empty; + + userStoryFilter.ApplyBaseFilter(builder, ref queryFilter); + + if (userStoryFilter.user_id != null) + { + queryFilter &= builder.Eq("user_id", userStoryFilter.user_id); + } + + if (userStoryFilter.anime_id != null) + { + queryFilter &= builder.Eq("anime_id", userStoryFilter.anime_id); + } + + if(userStoryFilter.status != null) + { + queryFilter &= builder.Eq("status", userStoryFilter.status); + } + + if(userStoryFilter.synced != null) + { + queryFilter &= builder.Eq("synced", userStoryFilter.synced); + } + + SortDefinition sort = Builders.Sort.Descending(x => x.CreationDate); + + return new Paging(this.Collection, userStoryFilter.page, queryFilter, sort, userStoryFilter.per_page); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `userStoryFilter` last assigned on line 70 could be null and is dereferenced at line 75, column 13. + +### Severity: +ERROR + +### Procedure: +Paging`1 UserStoryCollection.GetList(IFilter`1) + +### File: +Commons/Collections/UserStoryCollection.cs + +### Key: +UserStoryCollection.cs|GetList|NULL_DEREFERENCE + +### Node Key: +3654aaa31bf6f5c66d4263b95a3f1706 + +### Hash: +3dbee0a59c1d282b1160c829d2e9af0d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1415/instruction.md b/inferredbugs-1415/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..655d423c2179e90fd919a00ce60ce0fdd977419c --- /dev/null +++ b/inferredbugs-1415/instruction.md @@ -0,0 +1,200 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** AniAPI +**Bug ID:** 30 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Commons.Filters; +using MongoDB.Bson; +using MongoDB.Driver; +using System; +using MongoService; +using Commons.Enums; + +namespace Commons.Collections +{ + public class AnimeCollection : ICollection + { + protected override string CollectionName => "anime"; + + public override void Add(ref Anime document) + { + base.Add(ref document); + + this.Collection.InsertOne(document); + } + + public override long Count() + { + return this.Collection.CountDocuments(Builders.Filter.Empty); + } + + public override void Delete(long id) + { + throw new NotImplementedException(); + } + + public override void Edit(ref Anime document) + { + base.Edit(ref document); + + var filter = Builders.Filter.Eq("_id", document.Id); + this.Collection.ReplaceOne(filter, document); + } + + public override Anime Get(long id) + { + return this.Collection.Find(x => x.Id == id).FirstOrDefault(); + } + + public override bool Exists(ref Anime document, bool updateValues = true) + { + int anilistId = document.AnilistId; + Anime reference = this.Collection.Find(x => x.AnilistId == anilistId).FirstOrDefault(); + + if(reference != null) + { + if (updateValues) + { + document.Id = reference.Id; + document.CreationDate = reference.CreationDate; + document.UpdateDate = reference.UpdateDate; + document.Titles = reference.Titles; + document.Descriptions = reference.Descriptions; + } + + return true; + } + + return false; + } + + public override Paging GetList(IFilter filter) + { + AnimeFilter animeFilter = filter as AnimeFilter; + + var builder = Builders.Filter; + FilterDefinition queryFilter = builder.Empty; + + animeFilter.ApplyBaseFilter(builder, ref queryFilter); + + if (!string.IsNullOrEmpty(animeFilter.title)) + { + queryFilter &= builder.Regex($"titles.{animeFilter.locale}", new BsonRegularExpression($".*{animeFilter.title}.*", "i")); + } + + if(animeFilter.anilist_id != null) + { + queryFilter &= builder.Eq("anilist_id", animeFilter.anilist_id); + } + + if(animeFilter.mal_id != null) + { + queryFilter &= builder.Eq("mal_id", animeFilter.mal_id); + } + + if(animeFilter.formats.Count > 0) + { + queryFilter &= builder.AnyIn("format", animeFilter.formats); + } + + if(animeFilter.status != null) + { + queryFilter &= builder.Eq("status", animeFilter.status); + } + + if(animeFilter.year != null) + { + queryFilter &= builder.Eq("season_year", animeFilter.year); + } + + if(animeFilter.season != null) + { + queryFilter &= builder.Eq("season_period", animeFilter.season); + } + + if(animeFilter.genres.Count > 0) + { + queryFilter &= builder.AnyIn("genres", animeFilter.genres); + } + + if(animeFilter.nsfw == true) + { + queryFilter &= builder.Nin("genres", new System.Collections.Generic.List { "Hentai" }); + } + + if (!string.IsNullOrEmpty(animeFilter.locale)) + { + queryFilter &= builder.Exists($"titles.{animeFilter.locale}"); + } + + SortDefinition sort = animeFilter.ApplySort( + new System.Collections.Generic.List + { + "score" + }, + new System.Collections.Generic.List + { + -1 + }); + + return new Paging(this.Collection, animeFilter.page, queryFilter, sort, animeFilter.per_page); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `animeFilter` last assigned on line 68 could be null and is dereferenced at line 73, column 13. + +### Severity: +ERROR + +### Procedure: +Paging`1 AnimeCollection.GetList(IFilter`1) + +### File: +Commons/Collections/AnimeCollection.cs + +### Key: +AnimeCollection.cs|GetList|NULL_DEREFERENCE + +### Node Key: +3654aaa31bf6f5c66d4263b95a3f1706 + +### Hash: +09ad9c07c8fd9e882e2a06404caa8361 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1422/instruction.md b/inferredbugs-1422/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7c343ffbb76eebfef0fac0e3fbd5cf1e56d6d2c8 --- /dev/null +++ b/inferredbugs-1422/instruction.md @@ -0,0 +1,148 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** AniAPI +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Commons.Filters; +using MongoDB.Bson; +using MongoDB.Driver; +using System; +using MongoService; + +namespace Commons.Collections +{ + public class AnimeCollection : ICollection + { + protected override string CollectionName => "anime"; + + public override void Add(ref Anime document) + { + document.Id = this.CalcNewId(); + document.CreationDate = DateTime.Now; + document.UpdateDate = null; + + this.Collection.InsertOne(document); + } + + public override long Count() + { + return this.Collection.CountDocuments(Builders.Filter.Empty); + } + + public override void Delete(long id) + { + throw new NotImplementedException(); + } + + public override void Edit(ref Anime document) + { + document.UpdateDate = DateTime.Now; + + var filter = Builders.Filter.Eq("_id", document.Id); + this.Collection.ReplaceOne(filter, document); + } + + public override Anime Get(long id) + { + return this.Collection.Find(x => x.Id == id).FirstOrDefault(); + } + + public override bool Exists(ref Anime document, bool updateValues = true) + { + int anilistId = document.AnilistId; + Anime reference = this.Collection.Find(x => x.AnilistId == anilistId).FirstOrDefault(); + + if(reference != null) + { + if (updateValues) + { + document.Id = reference.Id; + document.CreationDate = reference.CreationDate; + document.UpdateDate = reference.UpdateDate; + document.Ending = reference.Ending; + document.Opening = reference.Opening; + } + return true; + } + + return false; + } + + public override Paging GetList(IFilter filter) + { + AnimeFilter animeFilter = filter as AnimeFilter; + + var builder = Builders.Filter; + FilterDefinition queryFilter = builder.Empty; + + if (!string.IsNullOrEmpty(animeFilter.title)) + { + queryFilter = queryFilter & builder.Regex($"titles.{animeFilter.locale}", new BsonRegularExpression($".*{animeFilter.title}.*")); + } + + if(animeFilter.anilist_id != 0) + { + queryFilter = queryFilter & builder.Eq("anilist_id", animeFilter.anilist_id); + } + + return new Paging(this.Collection, animeFilter.page, queryFilter); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `animeFilter` last assigned on line 68 could be null and is dereferenced at line 73, column 13. + +### Severity: +ERROR + +### Procedure: +Paging`1 AnimeCollection.GetList(IFilter`1) + +### File: +Commons/Collections/AnimeCollection.cs + +### Key: +AnimeCollection.cs|GetList|NULL_DEREFERENCE + +### Node Key: +93735850e46a76bf26a8e51627647824 + +### Hash: +09ad9c07c8fd9e882e2a06404caa8361 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1423/instruction.md b/inferredbugs-1423/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5daf8998d727286c0a494ab4c7901c47ee3d75a6 --- /dev/null +++ b/inferredbugs-1423/instruction.md @@ -0,0 +1,168 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** AniAPI +**Bug ID:** 13 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Commons.Filters; +using MongoDB.Bson; +using MongoDB.Driver; +using MongoService; +using System; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Commons.Collections +{ + public class AnimeSongCollection : ICollection + { + protected override string CollectionName => "anime_song"; + + public override void Add(ref AnimeSong document) + { + base.Add(ref document); + + this.Collection.InsertOne(document); + } + + public override long Count() + { + return this.Collection.CountDocuments(Builders.Filter.Empty); + } + + public override void Delete(long id) + { + throw new NotImplementedException(); + } + + public override void Edit(ref AnimeSong document) + { + base.Edit(ref document); + + var filter = Builders.Filter.Eq("_id", document.Id); + this.Collection.ReplaceOne(filter, document); + } + + public override bool Exists(ref AnimeSong document, bool updateValues = true) + { + long animeID = document.AnimeID; + string title = document.Title; + string artist = document.Artist; + + AnimeSong reference = this.Collection.Find(x => x.Title == title && x.Artist == artist && x.AnimeID == animeID).FirstOrDefault(); + + if(reference != null) + { + if (updateValues) + { + document.Id = reference.Id; + document.CreationDate = reference.CreationDate; + document.UpdateDate = reference.UpdateDate; + } + + return true; + } + + return false; + } + + public override AnimeSong Get(long id) + { + return this.Collection.Find(x => x.Id == id).FirstOrDefault(); + } + + public override Paging GetList(IFilter filter) + { + AnimeSongFilter songFilter = filter as AnimeSongFilter; + + var builder = Builders.Filter; + FilterDefinition queryFilter = builder.Empty; + + if (songFilter.anime_id != null) + { + queryFilter &= builder.Eq("anime_id", songFilter.anime_id); + } + + if (!string.IsNullOrEmpty(songFilter.title)) + { + queryFilter &= builder.Regex("title", new BsonRegularExpression($".*{songFilter.title}.*", "i")); + } + + if(songFilter.year != null) + { + queryFilter &= builder.Eq("year", songFilter.year); + } + + if(songFilter.season != null) + { + queryFilter &= builder.Eq("season", songFilter.season); + } + + if(songFilter.type != null) + { + queryFilter &= builder.Eq("type", songFilter.type); + } + + SortDefinition sort = Builders.Sort.Descending(x => x.Year).Descending(x => x.Season); + + return new Paging(this.Collection, songFilter.page, queryFilter, sort, songFilter.per_page); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `songFilter` last assigned on line 71 could be null and is dereferenced at line 76, column 13. + +### Severity: +ERROR + +### Procedure: +Paging`1 AnimeSongCollection.GetList(IFilter`1) + +### File: +Commons/Collections/AnimeSongCollection.cs + +### Key: +AnimeSongCollection.cs|GetList|NULL_DEREFERENCE + +### Node Key: +c91b435e0ebdfa03be7f8c2adfdbfd87 + +### Hash: +7b383f7cce6b5b74d7d0505a278476b2 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1425/instruction.md b/inferredbugs-1425/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5acd6669e209d1c0c791597bf1b51afaa765041d --- /dev/null +++ b/inferredbugs-1425/instruction.md @@ -0,0 +1,156 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** AniAPI +**Bug ID:** 14 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Commons.Filters; +using MongoDB.Driver; +using MongoService; +using System; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Commons.Collections +{ + public class OAuthClientCollection : ICollection + { + protected override string CollectionName => "oauth_client"; + + public override void Add(ref OAuthClient document) + { + base.Add(ref document); + + do + { + document.ClientID = Guid.NewGuid(); + } + while (this.Exists(ref document, false) == true); + + this.Collection.InsertOne(document); + } + + public override long Count() + { + return this.Collection.CountDocuments(Builders.Filter.Empty); + } + + public override void Delete(long id) + { + this.Collection.DeleteOne(x => x.Id == id); + } + + public override void Edit(ref OAuthClient document) + { + base.Edit(ref document); + + var filter = Builders.Filter.Eq("_id", document.Id); + this.Collection.ReplaceOne(filter, document); + } + + public override bool Exists(ref OAuthClient document, bool updateValues = true) + { + Guid clientId = document.ClientID; + + OAuthClient reference = this.Collection.Find(x => x.ClientID == clientId).FirstOrDefault(); + + if(reference != null) + { + if (updateValues) + { + document.Id = reference.Id; + document.CreationDate = reference.CreationDate; + document.UpdateDate = reference.UpdateDate; + } + + return true; + } + + return false; + } + + public override OAuthClient Get(long id) + { + return this.Collection.Find(x => x.Id == id).FirstOrDefault(); + } + + public override Paging GetList(IFilter filter) + { + OAuthClientFilter oAuthClientFilter = filter as OAuthClientFilter; + + var builder = Builders.Filter; + FilterDefinition queryFilter = builder.Empty; + + if(oAuthClientFilter.user_id != null) + { + queryFilter &= builder.Eq("user_id", oAuthClientFilter.user_id); + } + + if(oAuthClientFilter.client_id != null) + { + queryFilter &= builder.Eq("client_id", oAuthClientFilter.client_id); + } + + SortDefinition sort = Builders.Sort.Ascending(x => x.Id); + + return new Paging(this.Collection, oAuthClientFilter.page, queryFilter, sort, oAuthClientFilter.per_page); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `oAuthClientFilter` last assigned on line 74 could be null and is dereferenced at line 79, column 13. + +### Severity: +ERROR + +### Procedure: +Paging`1 OAuthClientCollection.GetList(IFilter`1) + +### File: +Commons/Collections/OAuthClientCollection.cs + +### Key: +OAuthClientCollection.cs|GetList|NULL_DEREFERENCE + +### Node Key: +c91b435e0ebdfa03be7f8c2adfdbfd87 + +### Hash: +16b737af9e3000d1d901268be046d58f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1440/instruction.md b/inferredbugs-1440/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9fbed1366985df5c07121565b30bff230ec896da --- /dev/null +++ b/inferredbugs-1440/instruction.md @@ -0,0 +1,241 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cms +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Threading.Tasks; +using JR.Cms.Core; +using JR.Cms.ServiceDto; +using JR.Stand.Abstracts.Safety; +using JR.Stand.Abstracts.Web; + +namespace JR.Cms.Web.Portal.Comm +{ + /// + /// 内容门户控制器 + /// + public class PortalControllerHandler + { + /// + /// 获取真实的请求地址 + /// + /// + /// + /// + private string SubPath(String path,string appPath) + { + int len = appPath.Length; + if (len > 2) + { + if (path.Length < len) return ""; + return path.Substring(len); + } + return path; + } + + /// + /// 检查站点首页路径 + /// + /// + /// + /// + /// + private bool CheckSiteUrl(ICompatibleHttpContext ctx, SiteDto site) + { + // 跳转到自定义地址 + if (!String.IsNullOrEmpty(site.Location)) + { + ctx.Response.Redirect(site.Location,false); //302 + return false; + } + // 跳转到站点首页 + var path = ctx.Request.GetPath(); + if (!String.IsNullOrEmpty(site.AppPath) && path == "/") + { + ctx.Response.Redirect("/" + site.AppPath,false); + return false; + } + return true; + } + + /// + /// 首页 + /// + public Task Index(ICompatibleHttpContext context) + { + // bool eventResult = false; + // if (OnIndexRequest != null) + // { + // OnIndexRequest(base.OutputContext, ref eventResult); + // } + var ctx = Cms.Context; + SiteDto site = ctx.CurrentSite; + // 站点站点路径 + if (!this.CheckSiteUrl(context,site)) return SafetyTask.CompletedTask; + + //检测网站状态及其缓存 + if (ctx.CheckSiteState() && ctx.CheckAndSetClientCache()) + { + DefaultWebOuput.RenderIndex(ctx); + } + return SafetyTask.CompletedTask; + + + //如果返回false,则执行默认输出 + // if (!eventResult) + // { + // DefaultWebOuput.RenderIndex(base.OutputContext); + // } + } + + /// + /// 文档页 + /// + /// + public Task Archive(ICompatibleHttpContext context) + { + context.Response.ContentType("text/html;charset=utf-8"); + CmsContext ctx = Cms.Context; + //检测网站状态及其缓存 + if (ctx.CheckSiteState() && ctx.CheckAndSetClientCache()) + { + context.Response.ContentType("text/html;charset=utf-8"); + var path = context.Request.GetPath(); + String archivePath = this.SubPath(path, ctx.SiteAppPath); + archivePath = archivePath.Substring(0, archivePath.LastIndexOf(".", StringComparison.Ordinal)); + DefaultWebOuput.RenderArchive(ctx, archivePath); + } + return SafetyTask.CompletedTask; + + /* + bool eventResult = false; + if (OnArchiveRequest != null) + { + OnArchiveRequest(ctx, archivePath, ref eventResult); + } + + //如果返回false,则执行默认输出 + if (!eventResult) + { + DefaultWebOuput.RenderArchive(ctx, archivePath); + } + */ + } + + /// + /// 栏目页 + /// + /// + /// + public Task Category(ICompatibleHttpContext context) + { + context.Response.ContentType("text/html;charset=utf-8"); + CmsContext ctx = Cms.Context; + //检测网站状态及其缓存 + if (ctx.CheckSiteState() && ctx.CheckAndSetClientCache()) + { + var path = context.Request.GetPath(); + var sitePath = ctx.SiteAppPath; + // 验证是否为当前站点的首页 + if (path ==sitePath ) + { + return this.Index(context); + } + // 如果为"/site/",跳转到"/site" + if (path == sitePath+"/") + { + context.Response.Redirect(path.Substring(0, path.Length - 1), false); + return SafetyTask.CompletedTask; + + } + String catPath = this.SubPath(path, sitePath); + int page = 1; + //获取页码和tag + if (catPath.EndsWith(".html")) + { + var ls = catPath.LastIndexOf("/", StringComparison.Ordinal); + var len = catPath.Length; + var begin = ls + 1 + "list_".Length; + var ps = catPath.Substring(begin, len - begin - 5); + int.TryParse(ps, out page); + catPath = catPath.Substring(0, ls); + } + + + DefaultWebOuput.RenderCategory(ctx, catPath, page); + // //执行 + // bool eventResult = false; + // if (OnCategoryRequest != null) + // { + // OnCategoryRequest(ctx, catPath, page, ref eventResult); + // } + // + // //如果返回false,则执行默认输出 + // if (!eventResult) + // { + // DefaultWebOuput.RenderCategory(ctx, catPath, page); + // } + } + return SafetyTask.CompletedTask; + + + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `ctx` last assigned on line 191 could be null and is dereferenced at line 193, column 13. + +### Severity: +ERROR + +### Procedure: +Task PortalControllerHandler.Category(ICompatibleHttpContext) + +### File: +src/JR.Cms/Web/Portal/Comm/PortalController.cs + +### Key: +PortalController.cs|Category|NULL_DEREFERENCE + +### Node Key: +56203f4e21ecf9e860f6a12dc3683775 + +### Hash: +b8fc0464aa1b5a6bb9e2a7d1c6a91386 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1447/instruction.md b/inferredbugs-1447/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..78b3c0572ffc6452e95b4a0a450817509599ad38 --- /dev/null +++ b/inferredbugs-1447/instruction.md @@ -0,0 +1,214 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** SharpGLTF +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Text; + +using NUnit.Framework; + +namespace glTF2Sharp.Schema2 +{ + [TestFixture] + public class LoadModelTests + { + #region setup + + [OneTimeSetUp] + public void Setup() + { + TestFiles.CheckoutDataDirectories(); + } + + #endregion + + #region testing models of https://github.com/bghgary/glTF-Asset-Generator.git + + [Test] + public void GeneratedModelsLoadTest() + { + foreach (var f in TestFiles.GetGeneratedFilePaths()) + { + var model = _LoadModel(f); + + Assert.NotNull(model); + } + } + + + [TestCase(0)] + [TestCase(6)] + public void LoadCompatibilityModelTest(int idx) + { + var filePath = TestFiles.GetCompatibilityFilePath(idx); + + var model = _LoadModel(filePath); + + Assert.NotNull(model); + } + + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + public void LoadInvalidModelsTest(int idx) + { + var filePath = TestFiles.GetCompatibilityFilePath(idx); + + try + { + ModelRoot.Load(filePath); + Assert.Fail("Did not throw!"); + } + catch(ModelException ex) + { + TestContext.WriteLine($"{filePath} threw {ex.Message}"); + } + + } + + #endregion + + #region testing models of https://github.com/KhronosGroup/glTF-Sample-Models.git + + [Test] + public void SampleModelsLoadTest() + { + foreach (var f in TestFiles.GetSampleFilePaths()) + { + var root = _LoadModel(f); + Assert.NotNull(root); + + // var fileName = System.IO.Path.GetFileNameWithoutExtension(f); + + // root.DefaultScene._DumpWavefrontToTest(f); + } + } + + [Test] + public void MaterialSpecularGlossinessModelsLoadTest() + { + foreach (var f in TestFiles.GetFilePathsWithSpecularGlossinessPBR()) + { + var root = _LoadModel(f); + Assert.NotNull(root); + } + } + + #endregion + + #region test polly model + + [Test(Description ="Example of traversing the visual tree all the way to individual vertices and indices")] + public void TestLoadPolly() + { + var model = _LoadModel(TestFiles.GetPollyFilePath()); + + var scene = model.DefaultScene; + + var pollyNode = scene.FindNode("Polly_Display"); + + var pollyPrimitive = pollyNode.Mesh.Primitives[0]; + + var pollyIndices = pollyPrimitive.IndexAccessor.CastToIndicesAccessor(); + var pollyPositions = pollyPrimitive.VertexAccessors["POSITION"].CastToVector3Accessor(); + var pollyNormals = pollyPrimitive.VertexAccessors["NORMAL"].CastToVector3Accessor(); + + for (int i=0; i < pollyIndices.Count; i+=3) + { + var a = (int)pollyIndices[i + 0]; + var b = (int)pollyIndices[i + 1]; + var c = (int)pollyIndices[i + 2]; + + var ap = pollyPositions[a]; + var bp = pollyPositions[b]; + var cp = pollyPositions[c]; + + var an = pollyNormals[a]; + var bn = pollyNormals[b]; + var cn = pollyNormals[c]; + + TestContext.WriteLine($"Triangle {ap} {an} {bp} {bn} {cp} {cn}"); + } + } + + #endregion + + #region model loading + + public static ModelRoot _LoadModel(string filePath) + { + try + { + TestContext.Progress.WriteLine($"Loading {filePath.ToShortDisplayPath()}"); + + return ModelRoot.Load(filePath); + } + catch(ExtensionException eex) + { + TestContext.WriteLine($"{filePath} ERROR: {eex.Message}"); + + return null; + } + } + + #endregion + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +The call to `IntegerAccessor Accessor.CastToIndicesAccessor()` may trigger the following issue: ``BufferView Accessor.get_SourceBufferView()`` could be null (from the call to `Accessor.CastToIndicesAccessor()` on line 127) and is dereferenced in call to `Accessor.CastToIndicesAccessor()`. + +### Severity: +ERROR + +### Procedure: +Void LoadModelTests.TestLoadPolly() + +### File: +src/glTF2Sharp.Tests/Schema2/LoadModelTests.cs + +### Key: +LoadModelTests.cs|TestLoadPolly|NULLPTR_DEREFERENCE + +### Hash: +250afd25c28f074c2548e0676a7a8437 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1449/instruction.md b/inferredbugs-1449/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dc71842afa46d6afe632d3bfb7c32af5209d2e2a --- /dev/null +++ b/inferredbugs-1449/instruction.md @@ -0,0 +1,301 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** MongoFramework +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using MongoDB.Driver; +using System.Linq.Expressions; +using MongoFramework.Infrastructure; +using System.Collections; +using System.ComponentModel.DataAnnotations; +using MongoDB.Driver.Linq; +using MongoFramework.Infrastructure.Linq; +using MongoFramework.Infrastructure.Linq.Processors; + +namespace MongoFramework +{ + /// + /// Basic Mongo "DbSet", providing changeset support and attribute validation + /// + /// + public class MongoDbSet : IMongoDbSet + { + public IDbChangeTracker ChangeTracker { get; private set; } = new DbChangeTracker(); + + private IDbEntityChangeWriter dbWriter { get; set; } + private IDbEntityReader dbReader { get; set; } + + /// + /// Whether any entity validation is performed prior to saving changes. (Default is true) + /// + public bool PerformEntityValidation { get; set; } = true; + + public MongoDbSet() { } + + /// + /// Creates a new MongoDbSet using the connection string in the configuration that matches the specified connection name. + /// + /// The name of the connection string stored in the configuration. + public MongoDbSet(string connectionName) + { + var mongoUrl = MongoDbUtility.GetMongoUrlFromConfig(connectionName); + + if (mongoUrl == null) + { + throw new MongoConfigurationException("No connection string found with the name \'" + connectionName + "\'"); + } + + SetDatabase(MongoDbUtility.GetDatabase(mongoUrl)); + } + + /// + /// Creates a new MongoDbSet using the specified connection string and database combination. + /// + /// The connection string to the server + /// The database name on the server + public MongoDbSet(string connectionString, string databaseName) + { + SetDatabase(MongoDbUtility.GetDatabase(connectionString, databaseName)); + } + + /// + /// Creates a new MongoDbSet with the specified entity reader and writer. + /// + /// The reader to use for querying the database. + /// The writer to use for writing to the database. + public MongoDbSet(IDbEntityReader reader, IDbEntityChangeWriter writer) + { + dbReader = reader; + dbWriter = writer; + } + + /// + /// Initialise a new entity reader and writer to the specified database. + /// + /// + public void SetDatabase(IMongoDatabase database) + { + var entityMapper = new DbEntityMapper(); + dbWriter = new DbEntityWriter(database, entityMapper); + dbReader = new DbEntityReader(database, entityMapper); + } + + /// + /// Marks the entity for insertion into the database. + /// + /// + public virtual void Add(TEntity entity) + { + if (entity == null) + { + throw new ArgumentNullException("entity"); + } + + ChangeTracker.Update(entity, DbEntityEntryState.Added); + } + /// + /// Marks the collection of entities for insertion into the database. + /// + /// + public virtual void AddRange(IEnumerable entities) + { + if (entities == null) + { + throw new ArgumentNullException("entities"); + } + + ChangeTracker.UpdateRange(entities, DbEntityEntryState.Added); + } + + /// + /// Marks the entity for updating. + /// + /// + public virtual void Update(TEntity entity) + { + if (entity == null) + { + throw new ArgumentNullException("entity"); + } + + ChangeTracker.Update(entity, DbEntityEntryState.Updated); + } + /// + /// Marks the collection of entities for updating. + /// + /// + public virtual void UpdateRange(IEnumerable entities) + { + if (entities == null) + { + throw new ArgumentNullException("entities"); + } + + ChangeTracker.UpdateRange(entities, DbEntityEntryState.Updated); + } + + /// + /// Marks the entity for deletion. + /// + /// + public virtual void Remove(TEntity entity) + { + if (entity == null) + { + throw new ArgumentNullException("entity"); + } + + ChangeTracker.Update(entity, DbEntityEntryState.Deleted); + } + /// + /// Marks the collection of entities for deletion. + /// + /// + public virtual void RemoveRange(IEnumerable entities) + { + if (entities == null) + { + throw new ArgumentNullException("entities"); + } + + ChangeTracker.UpdateRange(entities, DbEntityEntryState.Deleted); + } + + /// + /// Writes all of the items in the changeset to the database. + /// + public virtual void SaveChanges() + { + if (dbWriter == null) + { + throw new InvalidOperationException("No IDbEntityWriter has been set."); + } + + ChangeTracker.DetectChanges(); + + if (PerformEntityValidation) + { + var savingEntities = ChangeTracker.GetEntries() + .Where(e => e.State == DbEntityEntryState.Added || e.State == DbEntityEntryState.Updated) + .Select(e => e.Entity); + + foreach (var savingEntity in savingEntities) + { + var validationContext = new ValidationContext(savingEntity); + Validator.ValidateObject(savingEntity, validationContext); + } + } + + dbWriter.WriteChanges(ChangeTracker); + } + + #region IQueryable Implementation + + private IQueryable GetQueryable() + { + if (dbReader == null) + { + throw new InvalidOperationException("No IDbEntityReader has been set."); + } + + var queryable = dbReader.AsQueryable() as IMongoFrameworkQueryable; + queryable.EntityProcessors.Add(new EntityTrackingProcessor(ChangeTracker)); + return queryable; + } + + public Expression Expression + { + get + { + return GetQueryable().Expression; + } + } + + public Type ElementType + { + get + { + return GetQueryable().ElementType; + } + } + + public IQueryProvider Provider + { + get + { + return GetQueryable().Provider; + } + } + + public IEnumerator GetEnumerator() + { + return GetQueryable().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + #endregion + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `queryable` last assigned on line 199 could be null and is dereferenced at line 200, column 4. + +### Severity: +ERROR + +### Procedure: +IQueryable`1 MongoDbSet`1.GetQueryable() + +### File: +MongoFramework/MongoDbSet.cs + +### Key: +MongoDbSet.cs|GetQueryable|NULL_DEREFERENCE + +### Node Key: +ccc9111d4a6f7419fa2b6a22807cb208 + +### Hash: +84ba42ac60b4d1d82b4d30cc71277078 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1471/instruction.md b/inferredbugs-1471/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..509f2638afd4c203779ec7327a361be83745d47a --- /dev/null +++ b/inferredbugs-1471/instruction.md @@ -0,0 +1,261 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** phosphorusfive +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/* + * Phosphorus Five, copyright 2014 - 2015, Thomas Hansen, phosphorusfive@gmail.com + * Phosphorus Five is licensed under the terms of the MIT license, see the enclosed LICENSE file for details. + */ + +using System; +using System.Collections.Generic; +using System.Web.UI; +using p5.ajax.core.internals; + +// This might look fuuny, but to document the namespace, such that Doxygen recognizes it, +// and can create documentation for it, we must do it like this. +/// +/// Contains all Ajax functionality in Phosphorus. +/// +/// Contains all the Ajax functionality in Phosphorus, such as its Widgets, AjaxPage and so on. p5.ajax is a C# ASP.NET WebControls +/// library, that can be used without bringing in any other dependencies from Phosphorus Five. In such a regard, p5.ajax is an alternative +/// to other Ajax Libraries, such as Anthem.NET and ASP.NET Ajax. +/// +/// If all you wish to to, is to have a nice Ajax library for your C# or VB.NET ASP.NET projects, then p5.ajax is a decent alternative. +/// If this is what you want, then the only project dll you need to reference inside of your own projects is "p5.ajax.dll". +/// +/// p5.ajax is a managed Ajax Library, and all JavaScript for the library is roughly 5KB when built in Release Build. In addition, +/// p5.ajax only sends the changes back from the server to your client, which means that the amount of bandwidth usage when using +/// p5.ajax is probably unmatched by other similar libraries. +/// +/// With p5.ajax, you have complete control over what HTML is rendered from your server. There are no "magic divs", or huge +/// JavaScript files being transfered. p5.ajax tries to fix what needs to be fixed, and leave the rest up to you. p5.ajax is +/// 100% perfectly compatible with all other major Ajax Libraries out there, such as jQuery and Prototype.js. +/// +/// With p5.ajax, you can create your WebControls, just like you would in a normal ASP.NET project, and let the Ajax parts, and updating +/// of your widget's properties, automtically be taken care of. While still retaining 100% control over what goes over the wire, and what HTML +/// is rendered. +/// +/// For examples of how to use p5.ajax, you can check out the example web project from the Phosphorus Five download called +/// "p5.ajax.samples". +/// +namespace p5.ajax +{ + /// + /// Contains all core functionality in p5.ajax. + /// + /// Contains all the core helper and supporting features in p5.ajax, such as the Manager, AjaxPage and so on. + /// Helps glue together the Ajax Widgets with your Page, and helps you handle ViewState, create Ajax WebMethods and so on. + /// + namespace core + { + /// + /// Helper class for implementing core Ajax functionality on your page. + /// + /// Inherit all your ASP.NET Pages from this class in your solution to allow for them to have Ajax functionality. + /// If you do not wish to inherit from this class, + /// you can implement the IAjaxPage interface on your page instead, + /// and create an instance of the yourself, during the + /// initialization of your page. + /// + public class AjaxPage : Page, IAjaxPage + { + private PageStatePersister _statePersister; + private List> _newJavaScriptObjects = new List> (); + private List _newCssFiles = new List (); + + /// + /// Maximum number of ViewState entries in Session. + /// + /// If this is zero, ViewState will not be stored in Session, + /// but sent back and forth between client and browser as usual. This might be a security issue for you, in + /// addition to that it increases the size of all your HTTP requests significantly. Unless you know what you are + /// doing, you should always store the ViewState on the server, having a positive value, as small as possible, + /// of this property. + /// + /// The higher this number is, the more memory your serer is going to consume. The lower this number is, the + /// less number of consecutive open windows the end user can have towards your application at the same time. + /// + /// If you set this number to "-1", then an infinite amount of state objects per session will be stored on your + /// server, which opens up your server to a whole range of difficulties, such as easily draining your server for + /// all its memory by simply pressing CTRL+R hundreds of times, etc. For some intranet sites though, this might + /// be a useful value, if you know you can trust your users not to sabotage your site. + /// + /// Useful and safe values for this property, probably ranges from anything from 5 to 20, depending upon the amount + /// of memory you have, and what type of site you're creating. If your site is a "single page Ajax application", then + /// having "1" as your value will be OK. If your site has no Ajax functionality almost at all, then you can also + /// probably come away with a value of "1" for your page. + /// + /// If your site however mixes Ajax functionality with multiple URLs, or your users frequently opens up more than + /// one window to your site, then you should probably increase this number beyond "1", since otherwise every time + /// a user opens up a new window to your site, he will invalidate the state for all previously opened windows, and + /// break their Ajax functionality as he does. + /// + /// I recommend "5" to "10" as a general rule of thumb for this value, unless you know what you're doing. + /// + /// The number of valid viewstate entries for each session. + public int ViewStateSessionEntries { get; set; } + + /// + /// Gets the page state persister. + /// + /// The page state persister. + protected override PageStatePersister PageStatePersister + { + get + { + if (ViewStateSessionEntries == 0) + return base.PageStatePersister; + return _statePersister ?? (_statePersister = new StatePersister (this, ViewStateSessionEntries)); + } + } + + /// + /// Returns the ajax manager for your page. + /// + /// the ajax manager + public Manager Manager { get; private set; } + + /// + /// Registers JavaScript file for page, that will be included on the client-side. + /// + /// url to JavaScript to register + public void RegisterJavaScriptFile (string url) + { + if (ViewState ["__p5_js_objects"] == null) + ViewState ["__p5_js_objects"] = new List> (); + var lst = ViewState ["__p5_js_objects"] as List>; + if (lst.Find (delegate (Tuple idx) { return idx.Item1 == url; }) == null) { + lst.Add (new Tuple(url, true)); + _newJavaScriptObjects.Add (new Tuple(url, true)); + } + } + + /// + /// Registers JavaScript for page, that will be included on the client-side. + /// + /// url to JavaScript to register + public void RegisterJavaScript (string script) + { + if (ViewState ["__p5_js_objects"] == null) + ViewState ["__p5_js_objects"] = new List> (); + var lst = ViewState ["__p5_js_objects"] as List>; + if (lst.Find (delegate (Tuple idx) { return idx.Item1 == script; }) == null) { + lst.Add (new Tuple(script, false)); + _newJavaScriptObjects.Add (new Tuple(script, true)); + } + } + + /// + /// Registers stylesheet file for page, that will be included on the client-side. + /// + /// url to stylesheet to register + public void RegisterStylesheetFile (string url) + { + if (ViewState ["__p5_css_files"] == null) + ViewState ["__p5_css_files"] = new List (); + var lst = ViewState ["__p5_css_files"] as List; + if (!lst.Contains (url)) { + lst.Add (url); + _newCssFiles.Add (url); + } + } + + /* + * returns the JavaScript file URL's we need to push to client during this request + */ + List> IAjaxPage.JavaScriptToPush + { + get { return ViewState ["__p5_js_objects"] as List>; } + } + + /* + * returns the JavaScript file URL's we need to push to client during this request + */ + List> IAjaxPage.NewJavaScriptToPush + { + get { return _newJavaScriptObjects; } + } + + /* + * returns the JavaScript file URL's we need to push to client during this request + */ + List IAjaxPage.StylesheetFilesToPush + { + get { return ViewState ["__p5_css_files"] as List; } + } + + /* + * returns the JavaScript file URL's we need to push to client during this request + */ + List IAjaxPage.NewStylesheetFilesToPush + { + get { return _newCssFiles; } + } + + protected override void OnPreInit (EventArgs e) + { + Manager = new Manager (this); + base.OnPreInit (e); + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `lst` last assigned on line 153 could be null and is dereferenced at line 154, column 17. + +### Severity: +ERROR + +### Procedure: +Void AjaxPage.RegisterStylesheetFile(String) + +### File: +core/p5.ajax/core/AjaxPage.cs + +### Key: +AjaxPage.cs|RegisterStylesheetFile|NULL_DEREFERENCE + +### Node Key: +552d43ca4ba53a966acfd00b187c48fd + +### Hash: +e1942d8c83dacd31cc4c09800d975d80 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1476/instruction.md b/inferredbugs-1476/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2bfb3983b72b7042f8aa57e596c49c93ccf085c6 --- /dev/null +++ b/inferredbugs-1476/instruction.md @@ -0,0 +1,100 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** msgraph-sdk-dotnet +**Bug ID:** 11 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace Microsoft.Graph.DotnetCore.Core.Test.Extensions +{ + using Microsoft.Graph.DotnetCore.Core.Test.Requests; + using System.Net.Http; + using Xunit; + public class BaseRequestExtensionsTests: RequestTestBase + { + string requestUrl = "https://foo.bar"; + + [Fact] + public void WithShouldRetry_ShouldDelegateToRetryOption() + { + HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); + var baseRequest = new BaseRequest(requestUrl, this.baseClient); + baseRequest.WithShouldRetry((response) => true); + + Assert.IsType(baseRequest.GetHttpRequestMessage().Properties[typeof(GraphRequestContext).ToString()]); + Assert.True(baseRequest.GetHttpRequestMessage().GetMiddlewareOption().ShouldRetry(httpResponseMessage)); + } + + [Fact] + public void WithMaxRetry_ShouldAddMaxRetryToRetryOption() + { + var baseRequest = new BaseRequest(requestUrl, this.baseClient); + baseRequest.WithMaxRetry(3); + + Assert.IsType(baseRequest.GetHttpRequestMessage().Properties[typeof(GraphRequestContext).ToString()]); + Assert.Equal(3, baseRequest.GetHttpRequestMessage().GetMiddlewareOption().MaxRetry); + } + + [Fact] + public void WithMaxRedirects_ShouldAddMaxRedirectsToRedirectOption() + { + var baseRequest = new BaseRequest(requestUrl, this.baseClient); + baseRequest.WithMaxRedirects(4); + + Assert.IsType(baseRequest.GetHttpRequestMessage().Properties[typeof(GraphRequestContext).ToString()]); + Assert.Equal(4, baseRequest.GetHttpRequestMessage().GetMiddlewareOption().MaxRedirects); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from System.Net.Http.HttpRequestMessage Microsoft.Graph.BaseRequest::GetHttpRequestMessage() at Line 28) of type System.Net.Http.HttpRequestMessage, Leaked resource (returned from System.Net.Http.HttpRequestMessage Microsoft.Graph.BaseRequest::GetHttpRequestMessage() at Line 27) of type System.Net.Http.HttpRequestMessage in method "Void BaseRequestExtensionsTests.WithMaxRetry_ShouldAddMaxRetryToRetryOption()". + +### Severity: +ERROR + +### Procedure: +Void BaseRequestExtensionsTests.WithMaxRetry_ShouldAddMaxRetryToRetryOption() + +### File: +tests/Microsoft.Graph.DotnetCore.Core.Test/Extensions/BaseRequestExtensionsTests.cs + +### Key: +BaseRequestExtensionsTests.cs|WithMaxRetry_ShouldAddMaxRetryToRetryOption|DOTNET_RESOURCE_LEAK + +### Hash: +13370891a3d639d104a8c2ebf7614d52 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1478/instruction.md b/inferredbugs-1478/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4b5312463efb94c229743d51ddc351314d32cca9 --- /dev/null +++ b/inferredbugs-1478/instruction.md @@ -0,0 +1,158 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** msgraph-sdk-dotnet +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace Microsoft.Graph.DotnetCore.Core.Test.Extensions +{ + using Microsoft.Graph.DotnetCore.Core.Test.Requests; + using System.Net.Http; + using Xunit; + public class BaseRequestExtensionsTests: RequestTestBase + { + string requestUrl = "https://foo.bar"; + BaseRequest baseRequest; + public BaseRequestExtensionsTests() + { + baseRequest = new BaseRequest(requestUrl, this.baseClient); + } + + [Fact] + public void WithScopes_ShouldAddScopesToAuthOption() + { + string[] scopes = new string[] { "foo.bar", "user.bar", "user.foo"}; + + baseRequest.WithScopes(scopes); + + Assert.IsType(baseRequest.GetHttpRequestMessage().Properties[typeof(RequestContext).ToString()]); + Assert.Same(scopes, baseRequest.GetHttpRequestMessage().GetMiddlewareOption().Scopes); + } + + [Fact] + public void WithScopes_ShouldOnlyAddScopesToExistingAuthOption() + { + string[] scopes = new string[] { "foo.bar", "user.bar", "user.foo" }; + + baseRequest + .WithForceRefresh(false) + .WithScopes(scopes); + + Assert.IsType(baseRequest.GetHttpRequestMessage().Properties[typeof(RequestContext).ToString()]); + Assert.Equal(false, baseRequest.GetHttpRequestMessage().GetMiddlewareOption().ForceRefresh); + Assert.Same(scopes, baseRequest.GetHttpRequestMessage().GetMiddlewareOption().Scopes); + } + + [Fact] + public void WithForceRefresh_ShouldAddForceRefreshToAuthOption() + { + string requestUrl = "https://foo.bar"; + var request = new BaseRequest(requestUrl, this.baseClient); + + request.WithForceRefresh(true); + + Assert.IsType(request.GetHttpRequestMessage().Properties[typeof(RequestContext).ToString()]); + Assert.True(request.GetHttpRequestMessage().GetMiddlewareOption().ForceRefresh); + } + + [Fact] + public void WithShouldRetry_ShouldDelegateToRetryOption() + { + HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); + + baseRequest.WithShouldRetry((response) => true); + + Assert.IsType(baseRequest.GetHttpRequestMessage().Properties[typeof(RequestContext).ToString()]); + Assert.True(baseRequest.GetHttpRequestMessage().GetMiddlewareOption().ShouldRetry(httpResponseMessage)); + } + + [Fact] + public void WithMaxRetry_ShouldAddMaxRetryToRetryOption() + { + baseRequest.WithMaxRetry(3); + + Assert.IsType(baseRequest.GetHttpRequestMessage().Properties[typeof(RequestContext).ToString()]); + Assert.Equal(3, baseRequest.GetHttpRequestMessage().GetMiddlewareOption().MaxRetry); + } + + [Fact] + public void WithMaxRedirects_ShouldAddMaxRedirectsToRedirectOption() + { + baseRequest.WithMaxRedirects(4); + + Assert.IsType(baseRequest.GetHttpRequestMessage().Properties[typeof(RequestContext).ToString()]); + Assert.Equal(4, baseRequest.GetHttpRequestMessage().GetMiddlewareOption().MaxRedirects); + } + + [Fact] + public void AddMiddlewareOptions_ShouldAddMiddlewareOptionsToTheRequestContext() + { + var request = new BaseRequest("http://localhost.bar", this.baseClient); + var middlewareOptions = new IMiddlewareOption[] + { + new RetryOption { MaxRetry = 10, ShouldRetry = (response) => true }, + new AuthOption { ForceRefresh = false, Scopes = new string[] { "foo.bar", "user.read" } }, + new RedirectOption { MaxRedirects = 6 } + }; + + request.AddMiddlewareOptions(middlewareOptions); + + Assert.IsType(request.GetHttpRequestMessage().Properties[typeof(RequestContext).ToString()]); + Assert.Equal(middlewareOptions.Length, request.GetHttpRequestMessage().GetRequestContext().MiddlewareOptions.Count); + Assert.Same(middlewareOptions[1], request.GetHttpRequestMessage().GetMiddlewareOption()); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from System.Net.Http.HttpRequestMessage Microsoft.Graph.BaseRequest::GetHttpRequestMessage() at Line 49) of type System.Net.Http.HttpRequestMessage, Leaked resource (returned from System.Net.Http.HttpRequestMessage Microsoft.Graph.BaseRequest::GetHttpRequestMessage() at Line 48) of type System.Net.Http.HttpRequestMessage in method "Void BaseRequestExtensionsTests.WithForceRefresh_ShouldAddForceRefreshToAuthOption()". + +### Severity: +ERROR + +### Procedure: +Void BaseRequestExtensionsTests.WithForceRefresh_ShouldAddForceRefreshToAuthOption() + +### File: +tests/Microsoft.Graph.DotnetCore.Core.Test/Extensions/BaseRequestExtensionsTests.cs + +### Key: +BaseRequestExtensionsTests.cs|WithForceRefresh_ShouldAddForceRefreshToAuthOption|DOTNET_RESOURCE_LEAK + +### Hash: +8955eb3af53ed1e9676271a18324b001 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1482/instruction.md b/inferredbugs-1482/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..33fc340069dff85da48fa4b540af0018739260af --- /dev/null +++ b/inferredbugs-1482/instruction.md @@ -0,0 +1,158 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** msgraph-sdk-dotnet +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace Microsoft.Graph.DotnetCore.Core.Test.Extensions +{ + using Microsoft.Graph.DotnetCore.Core.Test.Requests; + using System.Net.Http; + using Xunit; + public class BaseRequestExtensionsTests: RequestTestBase + { + string requestUrl = "https://foo.bar"; + BaseRequest baseRequest; + public BaseRequestExtensionsTests() + { + baseRequest = new BaseRequest(requestUrl, this.baseClient); + } + + [Fact] + public void WithScopes_ShouldAddScopesToAuthOption() + { + string[] scopes = new string[] { "foo.bar", "user.bar", "user.foo"}; + + baseRequest.WithScopes(scopes); + + Assert.IsType(baseRequest.GetHttpRequestMessage().Properties[typeof(RequestContext).ToString()]); + Assert.Same(scopes, baseRequest.GetHttpRequestMessage().GetMiddlewareOption().Scopes); + } + + [Fact] + public void WithScopes_ShouldOnlyAddScopesToExistingAuthOption() + { + string[] scopes = new string[] { "foo.bar", "user.bar", "user.foo" }; + + baseRequest + .WithForceRefresh(false) + .WithScopes(scopes); + + Assert.IsType(baseRequest.GetHttpRequestMessage().Properties[typeof(RequestContext).ToString()]); + Assert.Equal(false, baseRequest.GetHttpRequestMessage().GetMiddlewareOption().ForceRefresh); + Assert.Same(scopes, baseRequest.GetHttpRequestMessage().GetMiddlewareOption().Scopes); + } + + [Fact] + public void WithForceRefresh_ShouldAddForceRefreshToAuthOption() + { + string requestUrl = "https://foo.bar"; + var request = new BaseRequest(requestUrl, this.baseClient); + + request.WithForceRefresh(true); + + Assert.IsType(request.GetHttpRequestMessage().Properties[typeof(RequestContext).ToString()]); + Assert.True(request.GetHttpRequestMessage().GetMiddlewareOption().ForceRefresh); + } + + [Fact] + public void WithShouldRetry_ShouldDelegateToRetryOption() + { + HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); + + baseRequest.WithShouldRetry((response) => true); + + Assert.IsType(baseRequest.GetHttpRequestMessage().Properties[typeof(RequestContext).ToString()]); + Assert.True(baseRequest.GetHttpRequestMessage().GetMiddlewareOption().ShouldRetry(httpResponseMessage)); + } + + [Fact] + public void WithMaxRetry_ShouldAddMaxRetryToRetryOption() + { + baseRequest.WithMaxRetry(3); + + Assert.IsType(baseRequest.GetHttpRequestMessage().Properties[typeof(RequestContext).ToString()]); + Assert.Equal(3, baseRequest.GetHttpRequestMessage().GetMiddlewareOption().MaxRetry); + } + + [Fact] + public void WithMaxRedirects_ShouldAddMaxRedirectsToRedirectOption() + { + baseRequest.WithMaxRedirects(4); + + Assert.IsType(baseRequest.GetHttpRequestMessage().Properties[typeof(RequestContext).ToString()]); + Assert.Equal(4, baseRequest.GetHttpRequestMessage().GetMiddlewareOption().MaxRedirects); + } + + [Fact] + public void AddMiddlewareOptions_ShouldAddMiddlewareOptionsToTheRequestContext() + { + var request = new BaseRequest("http://localhost.bar", this.baseClient); + var middlewareOptions = new IMiddlewareOption[] + { + new RetryOption { MaxRetry = 10, ShouldRetry = (response) => true }, + new AuthOption { ForceRefresh = false, Scopes = new string[] { "foo.bar", "user.read" } }, + new RedirectOption { MaxRedirects = 6 } + }; + + request.AddMiddlewareOptions(middlewareOptions); + + Assert.IsType(request.GetHttpRequestMessage().Properties[typeof(RequestContext).ToString()]); + Assert.Equal(middlewareOptions.Length, request.GetHttpRequestMessage().GetRequestContext().MiddlewareOptions.Count); + Assert.Same(middlewareOptions[1], request.GetHttpRequestMessage().GetMiddlewareOption()); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from System.Net.Http.HttpRequestMessage Microsoft.Graph.BaseRequest::GetHttpRequestMessage() at Line 78) of type System.Net.Http.HttpRequestMessage, Leaked resource (returned from System.Net.Http.HttpRequestMessage Microsoft.Graph.BaseRequest::GetHttpRequestMessage() at Line 77) of type System.Net.Http.HttpRequestMessage in method "Void BaseRequestExtensionsTests.WithMaxRedirects_ShouldAddMaxRedirectsToRedirectOption()". + +### Severity: +ERROR + +### Procedure: +Void BaseRequestExtensionsTests.WithMaxRedirects_ShouldAddMaxRedirectsToRedirectOption() + +### File: +tests/Microsoft.Graph.DotnetCore.Core.Test/Extensions/BaseRequestExtensionsTests.cs + +### Key: +BaseRequestExtensionsTests.cs|WithMaxRedirects_ShouldAddMaxRedirectsToRedirectOption|DOTNET_RESOURCE_LEAK + +### Hash: +cb88a3ec2612ae2bf747394930d72dbe + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1485/instruction.md b/inferredbugs-1485/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f068d4408b0ed5a401a2903b9f0c77d96c9a5bb9 --- /dev/null +++ b/inferredbugs-1485/instruction.md @@ -0,0 +1,338 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** msgraph-sdk-dotnet +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.DotnetCore.Core.Test.Requests +{ + using Mocks; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Reflection; + using System.Threading; + using System.Threading.Tasks; + using System.Net; + using Xunit; + + public class GraphClientFactoryTests : IDisposable + { + private DelegatingHandler[] handlers = new DelegatingHandler[3]; + private MockRedirectHandler testHttpMessageHandler; + + + public GraphClientFactoryTests() + { + this.testHttpMessageHandler = new MockRedirectHandler(); + handlers[0] = new RetryHandler(); + handlers[1] = new RedirectHandler(); + handlers[2] = new AuthenticationHandler(); + } + + public void Dispose() + { + this.testHttpMessageHandler.Dispose(); + } + + [Fact] + public void CreatePipelineWithoutHttpMessageHandlerInput() + { + using (RetryHandler retryHandler = (RetryHandler)GraphClientFactory.CreatePipeline(null, handlers)) + using (RedirectHandler redirectHandler = (RedirectHandler)retryHandler.InnerHandler) + using (AuthenticationHandler authenticationHandler = (AuthenticationHandler)redirectHandler.InnerHandler) + using (HttpClientHandler innerMost = (HttpClientHandler)authenticationHandler.InnerHandler) + { + Assert.NotNull(retryHandler); + Assert.NotNull(redirectHandler); + Assert.NotNull(authenticationHandler); + Assert.NotNull(innerMost); + Assert.IsType(typeof(RetryHandler), retryHandler); + Assert.IsType(typeof(RedirectHandler), redirectHandler); + Assert.IsType(typeof(AuthenticationHandler), authenticationHandler); + Assert.IsType(typeof(HttpClientHandler), innerMost); + } + + } + + [Fact] + public void CreatePipelineWithHttpMessageHandlerInput() + { + using (RetryHandler retryHandler = (RetryHandler)GraphClientFactory.CreatePipeline(this.testHttpMessageHandler, handlers)) + using (RedirectHandler redirectHandler = (RedirectHandler)retryHandler.InnerHandler) + using (AuthenticationHandler authenticationHandler = (AuthenticationHandler)redirectHandler.InnerHandler) + using (MockRedirectHandler innerMost = (MockRedirectHandler)authenticationHandler.InnerHandler) + { + Assert.NotNull(retryHandler); + Assert.NotNull(redirectHandler); + Assert.NotNull(authenticationHandler); + Assert.NotNull(innerMost); + Assert.IsType(typeof(RetryHandler), retryHandler); + Assert.IsType(typeof(RedirectHandler), redirectHandler); + Assert.IsType(typeof(AuthenticationHandler), authenticationHandler); + Assert.IsType(typeof(MockRedirectHandler), innerMost); + } + } + + [Fact] + public void CreatePipelineWithoutPipeline() + { + using (MockRedirectHandler handler = (MockRedirectHandler)GraphClientFactory.CreatePipeline(this.testHttpMessageHandler, null)) + { + Assert.NotNull(handler); + Assert.IsType(typeof(MockRedirectHandler), handler); + } + } + + [Fact] + public void CreateClient_CustomHttpHandlingBehaviors() + { + var timeout = TimeSpan.FromSeconds(200); + var baseAddress = new Uri("https://localhost"); + var cacheHeader = new CacheControlHeaderValue(); + + using (HttpClient client = GraphClientFactory.CreateClient(handlers)) + { + GraphClientFactory.Configure(client, timeout, baseAddress, cacheHeader); + Assert.NotNull(client); + Assert.Equal(client.Timeout, timeout); + Assert.False(client.DefaultRequestHeaders.CacheControl.NoCache, "NoCache true."); + Assert.False(client.DefaultRequestHeaders.CacheControl.NoStore, "NoStore true."); + Assert.Equal(client.BaseAddress, baseAddress); + + } + } + + [Fact] + public void CreateClient_SelectedCloud() + { + GraphClientFactory.Version = "beta"; + using (HttpClient httpClient = GraphClientFactory.CreateClient(GraphClientFactory.Germany_Cloud, handlers)) + { + Assert.NotNull(httpClient); + Uri clouldEndpoint = new Uri("https://graph.microsoft.de/beta"); + Assert.Equal(httpClient.BaseAddress, clouldEndpoint); + Assert.Equal(httpClient.Timeout, TimeSpan.FromSeconds(100)); + } + } + + [Fact] + public void CreateClient_SelectedCloudWithExceptions() + { + string nation = "Canada"; + try + { + HttpClient httpClient = GraphClientFactory.CreateClient(nation, handlers); + } + catch (ArgumentException exception) + { + Assert.IsType(typeof(ArgumentException), exception); + Assert.Equal(exception.Message, String.Format("{0} is an unexpected national cloud.", nation)); + } + } + + [Fact] + public void CreateClient_WithInnerHandler() + { + + using (HttpClient httpClient = GraphClientFactory.CreateClient(this.testHttpMessageHandler, null)) + { + Assert.NotNull(httpClient); + Assert.True(httpClient.DefaultRequestHeaders.Contains(CoreConstants.Headers.SdkVersionHeaderName), "SDK version not set."); + Version assemblyVersion = typeof(GraphClientFactory).GetTypeInfo().Assembly.GetName().Version; + string value = string.Format( + CoreConstants.Headers.SdkVersionHeaderValueFormatString, + "Graph", + assemblyVersion.Major, + assemblyVersion.Minor, + assemblyVersion.Build); + IEnumerable values; + Assert.True(httpClient.DefaultRequestHeaders.TryGetValues(CoreConstants.Headers.SdkVersionHeaderName, out values), "SDK version value not set"); + Assert.Equal(values.Count(), 1); + Assert.Equal(values.First(), value); + } + } + + [Fact] + public void CreateClient_WithHandlers() + { + using (HttpClient client = GraphClientFactory.CreateClient(handlers)) + { + Assert.NotNull(client); + + } + + } + + [Fact] + public async Task SendRequest_Redirect() + { + var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://example.org/foo"); + var redirectResponse = new HttpResponseMessage(HttpStatusCode.MovedPermanently); + + redirectResponse.Headers.Location = new Uri("http://example.org/bar"); + var oKResponse = new HttpResponseMessage(HttpStatusCode.OK); + this.testHttpMessageHandler.SetHttpResponse(redirectResponse, oKResponse); + + using (HttpClient client = GraphClientFactory.CreateClient(this.testHttpMessageHandler, handlers)) + { + var response = await client.SendAsync(httpRequestMessage, new CancellationToken()); + Assert.Equal(response, oKResponse); + Assert.Equal(response.RequestMessage.Method, httpRequestMessage.Method); + Assert.NotSame(response.RequestMessage, httpRequestMessage); + } + + } + + [Fact] + public async Task SendRequest_Retry() + { + var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://example.org/foo"); + httpRequestMessage.Content = new StringContent("Hello World"); + + var retryResponse = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable); + retryResponse.Headers.TryAddWithoutValidation("Retry-After", 30.ToString()); + var response_2 = new HttpResponseMessage(HttpStatusCode.OK); + + this.testHttpMessageHandler.SetHttpResponse(retryResponse, response_2); + + using (HttpClient client = GraphClientFactory.CreateClient(this.testHttpMessageHandler, handlers)) + { + var response = await client.SendAsync(httpRequestMessage, new CancellationToken()); + Assert.Same(response, response_2); + IEnumerable values; + Assert.True(httpRequestMessage.Headers.TryGetValues("Retry-Attempt", out values), "Don't set Retry-Attemp Header"); + Assert.Equal(values.Count(), 1); + Assert.Equal(values.First(), 1.ToString()); + } + + } + + [Fact] + public async Task SendRequest_UnauthorizedWithNoAuthenticationProvider() + { + var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, "https://example.com/bar"); + httpRequestMessage.Content = new StringContent("Hello World"); + + var unauthorizedResponse = new HttpResponseMessage(HttpStatusCode.Unauthorized); + var okResponse = new HttpResponseMessage(HttpStatusCode.OK); + + testHttpMessageHandler.SetHttpResponse(unauthorizedResponse, okResponse); + + using (HttpClient client = GraphClientFactory.CreateClient(testHttpMessageHandler, handlers)) + { + var response = await client.SendAsync(httpRequestMessage, new CancellationToken()); + Assert.Same(response, unauthorizedResponse); + Assert.Same(response.RequestMessage, httpRequestMessage); + } + } + + [Fact] + public async Task SendRequest_UnauthorizedWithAuthenticationProvider() + { + var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, "https://example.com/bar"); + httpRequestMessage.Content = new StringContent("Hello World"); + + var unauthorizedResponse = new HttpResponseMessage(HttpStatusCode.Unauthorized); + var okResponse = new HttpResponseMessage(HttpStatusCode.OK); + + testHttpMessageHandler.SetHttpResponse(unauthorizedResponse, okResponse); + + handlers[2] = new AuthenticationHandler(new MockAuthenticationProvider().Object); + + using (HttpClient client = GraphClientFactory.CreateClient(testHttpMessageHandler, handlers)) + { + var response = await client.SendAsync(httpRequestMessage, new CancellationToken()); + Assert.Same(response, okResponse); + Assert.Same(response.RequestMessage, httpRequestMessage); + } + } + + [Fact] + public void CreateClient_WithHandlersHasExceptions() + { + handlers[handlers.Length - 1] = null; + try + { + HttpClient client = GraphClientFactory.CreateClient(handlers); + } + catch (ArgumentNullException exception) + { + Assert.IsType(typeof(ArgumentNullException), exception); + Assert.Equal(exception.ParamName, "handlers"); + } + + handlers[handlers.Length - 1] = new RetryHandler(this.testHttpMessageHandler); + try + { + HttpClient client = GraphClientFactory.CreateClient(handlers); + } + catch (ArgumentException exception) + { + Assert.IsType(typeof(ArgumentException), exception); + Assert.Equal(exception.Message, String.Format("DelegatingHandler array has unexpected InnerHandler. {0} has unexpected InnerHandler.", handlers[handlers.Length - 1])); + + } + + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource httpClient of type System.Net.Http.HttpClient in method "Void GraphClientFactoryTests.CreateClient_SelectedCloudWithExceptions()". + +### Severity: +ERROR + +### Procedure: +Void GraphClientFactoryTests.CreateClient_SelectedCloudWithExceptions() + +### File: +tests/Microsoft.Graph.DotnetCore.Core.Test/Requests/GraphClientFactoryTests.cs + +### Key: +GraphClientFactoryTests.cs|CreateClient_SelectedCloudWithExceptions|DOTNET_RESOURCE_LEAK + +### Hash: +f3c0397f28a821980044032e71013b94 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1559/instruction.md b/inferredbugs-1559/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6f0f2a737f8aa4851e7753f2e49db5f20a059acb --- /dev/null +++ b/inferredbugs-1559/instruction.md @@ -0,0 +1,303 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Procurement +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.IO; +using System.Net; +using System.Text; +using POEApi.Infrastructure; +using System.Security; +using POEApi.Infrastructure.Events; +using System.Text.RegularExpressions; + +namespace POEApi.Transport +{ + public class HttpTransport : ITransport + { + private string email; + private CookieContainer credentialCookies; + + private bool useProxy = false; + private string proxyUser; + private string proxyPassword; + private string proxyDomain; + + private enum HttpMethod { GET, POST } + + private const string loginURL = @"https://www.pathofexile.com/login"; + private const string characterURL = @"http://www.pathofexile.com/character-window/get-characters"; + private const string stashURL = @"http://www.pathofexile.com/character-window/get-stash-items?league={0}&tabs=1&tabIndex={1}"; + private const string inventoryURL = @"http://www.pathofexile.com/character-window/get-items?character={0}"; + private const string hashRegEx = "name=\\\"hash\\\" value=\\\"(?[a-zA-Z0-9]{1,})\\\""; + + private const string updateThreadHashEx = "name=\\\"forum_thread\\\" value=\\\"(?[a-zA-Z0-9]{1,})\\\""; + private const string bumpThreadHashEx = "name=\\\"forum_post\\\" value=\\\"(?[a-zA-Z0-9]{1,})\\\""; + + private const string updateShopURL = @"http://www.pathofexile.com/forum/edit-thread/{0}"; + private const string bumpShopURL = @"http://www.pathofexile.com/forum/post-reply/{0}"; + + public event ThottledEventHandler Throttled; + + public HttpTransport(string login) + { + credentialCookies = new CookieContainer(); + this.email = login; + RequestThrottle.Instance.Throttled += new ThottledEventHandler(instance_Throttled); + } + + public HttpTransport(string login, string proxyUser, string proxyPassword, string proxyDomain) + : this(login) + { + this.proxyUser = proxyUser; + this.proxyPassword = proxyPassword; + this.proxyDomain = proxyDomain; + this.useProxy = true; + } + + private void instance_Throttled(object sender, ThottledEventArgs e) + { + if (Throttled != null) + Throttled(this, e); + } + + public bool Authenticate(string email, SecureString password, bool useSessionID) + { + if (useSessionID) + { + credentialCookies.Add(new System.Net.Cookie("PHPSESSID", password.UnWrap(), "/", "www.pathofexile.com")); + HttpWebRequest confirmAuth = getHttpRequest(HttpMethod.GET, loginURL); + HttpWebResponse confirmAuthResponse = (HttpWebResponse)confirmAuth.GetResponse(); + + if (confirmAuthResponse.ResponseUri.ToString() == loginURL) + throw new LogonFailedException(); + return true; + } + + HttpWebRequest getHash = getHttpRequest(HttpMethod.GET, loginURL); + HttpWebResponse hashResponse = (HttpWebResponse)getHash.GetResponse(); + string loginResponse = Encoding.Default.GetString(getMemoryStreamFromResponse(hashResponse).ToArray()); + string hashValue = Regex.Match(loginResponse, hashRegEx).Groups["hash"].Value; + + HttpWebRequest request = getHttpRequest(HttpMethod.POST, loginURL); + request.AllowAutoRedirect = false; + + StringBuilder data = new StringBuilder(); + data.Append("login_email=" + Uri.EscapeDataString(email)); + data.Append("&login_password=" + Uri.EscapeDataString(password.UnWrap())); + data.Append("&hash=" + hashValue); + + byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); + + request.ContentLength = byteData.Length; + + Stream postStream = request.GetRequestStream(); + postStream.Write(byteData, 0, byteData.Length); + + HttpWebResponse response; + response = (HttpWebResponse)request.GetResponse(); + + //If we didn't get a redirect, your gonna have a bad time. + if (response.StatusCode != HttpStatusCode.Found) + throw new LogonFailedException(this.email); + + return true; + } + + private HttpWebRequest getHttpRequest(HttpMethod method, string url) + { + HttpWebRequest request = (HttpWebRequest)RequestThrottle.Instance.Create(url); + + request.CookieContainer = credentialCookies; + request.UserAgent = "User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E; .NET CLR 1.1.4322)"; + request.Method = method.ToString(); + if (useProxy) + request.Proxy = processProxySettings(); + + request.ContentType = "application/x-www-form-urlencoded"; + + return request; + } + + public WebProxy processProxySettings() + { + System.Net.WebProxy proxy = System.Net.WebProxy.GetDefaultProxy(); + System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(proxyUser, proxyPassword, proxyDomain); + proxy.Credentials = credentials; + + return proxy; + } + + public Stream GetStash(int index, string league, bool refresh) + { + HttpWebRequest request = getHttpRequest(HttpMethod.GET, string.Format(stashURL, league, index)); + HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + + return getMemoryStreamFromResponse(response); + } + + public Stream GetStash(int index, string league) + { + return GetStash(index, league, false); + } + + public Stream GetCharacters() + { + HttpWebRequest request = getHttpRequest(HttpMethod.GET, characterURL); + HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + + return getMemoryStreamFromResponse(response); + } + + public Stream GetImage(string url) + { + WebClient client = new WebClient(); + client.Proxy = processProxySettings(); + return new MemoryStream(client.DownloadData(url)); + } + + public Stream GetInventory(string characterName, bool forceRefresh) + { + HttpWebRequest request = getHttpRequest(HttpMethod.GET, string.Format(inventoryURL, characterName)); + HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + + return getMemoryStreamFromResponse(response); + } + + private MemoryStream getMemoryStreamFromResponse(HttpWebResponse response) + { + StreamReader reader = new StreamReader(response.GetResponseStream()); + byte[] buffer = reader.ReadAllBytes(); + RequestThrottle.Instance.Complete(); + + return new MemoryStream(buffer); + } + + public bool UpdateThread(string threadID, string threadTitle, string threadText) + { + try + { + string threadHash = getThreadHash(string.Format(updateShopURL, threadID), updateThreadHashEx); + + StringBuilder data = new StringBuilder(); + data.Append("title=" + Uri.EscapeDataString(threadTitle)); + data.Append("&content=" + Uri.EscapeDataString(threadText)); + data.Append("&forum_thread=" + threadHash); + + postToForum(data.ToString(), string.Format(updateShopURL, threadID)); + + return true; + } + catch (Exception ex) + { + Logger.Log("Error updating shop thread: " + ex.ToString()); + return false; + } + } + + public bool BumpThread(string threadID) + { + try + { + string threadHash = getThreadHash(string.Format(bumpShopURL, threadID), bumpThreadHashEx); + + StringBuilder data = new StringBuilder(); + data.Append("forum_post=" + threadHash); + data.Append("&content=" + Uri.EscapeDataString("[url=https://code.google.com/p/procurement/]Bumped with Procurement![/url]")); + data.Append("&post_submit=" + Uri.EscapeDataString("Submit")); + + var response = postToForum(data.ToString(), string.Format(bumpShopURL, threadID)); + var htmlResponse = Encoding.Default.GetString(getMemoryStreamFromResponse(response).ToArray()); + + return true; + } + catch (Exception ex) + { + Logger.Log("Error bumping shop thread: " + ex.ToString()); + return false; + } + } + + private HttpWebResponse postToForum(string data, string url) + { + HttpWebRequest request = getHttpRequest(HttpMethod.POST, url); + request.AllowAutoRedirect = true; + + byte[] byteData = UTF8Encoding.UTF8.GetBytes(data); + + request.ContentLength = byteData.Length; + + Stream postStream = request.GetRequestStream(); + postStream.Write(byteData, 0, byteData.Length); + + HttpWebResponse response; + response = (HttpWebResponse)request.GetResponse(); + + return response; + } + + private string getThreadHash(string url, string regex) + { + HttpWebRequest getHash = getHttpRequest(HttpMethod.GET, url); + HttpWebResponse hashResponse = (HttpWebResponse)getHash.GetResponse(); + string hashRepsonse = Encoding.Default.GetString(getMemoryStreamFromResponse(hashResponse).ToArray()); + string hashValue = Regex.Match(hashRepsonse, regex).Groups["hash"].Value; + return hashValue; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from System.IO.MemoryStream POEApi.Transport.HttpTransport::getMemoryStreamFromResponse(System.Net.HttpWebResponse) at Line 206) of type System.IO.MemoryStream in method "Boolean HttpTransport.BumpThread(String)". + +### Severity: +ERROR + +### Procedure: +Boolean HttpTransport.BumpThread(String) + +### File: +POEApi.Transport/HttpTransport.cs + +### Key: +HttpTransport.cs|BumpThread|DOTNET_RESOURCE_LEAK + +### Hash: +2fc9d0c9d666ac0c04516d926258c44f + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1561/instruction.md b/inferredbugs-1561/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dbbcfea31ecba58c8201ee95f26457de6c72ae6b --- /dev/null +++ b/inferredbugs-1561/instruction.md @@ -0,0 +1,376 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Procurement +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.Serialization.Json; +using POEApi.Infrastructure; +using POEApi.Model.Events; +using POEApi.Transport; +using System.Security; +using System; +using POEApi.Infrastructure.Events; +using System.Runtime.Serialization; + +namespace POEApi.Model +{ + public class POEModel + { + private ITransport transport; + private CacheService cacheService; + private bool downOnlyMyCharacters; + + + public delegate void AuthenticateEventHandler(POEModel sender, AuthenticateEventArgs e); + public event AuthenticateEventHandler Authenticating; + + public delegate void StashLoadEventHandler(POEModel sender, StashLoadedEventArgs e); + public event StashLoadEventHandler StashLoading; + + public delegate void ImageLoadEventHandler(POEModel sender, ImageLoadedEventArgs e); + public event ImageLoadEventHandler ImageLoading; + + public event ThottledEventHandler Throttled; + + public bool Offline { get; private set; } + + public POEModel() + { + downOnlyMyCharacters = bool.Parse(Settings.UserSettings["DownloadOnlyMyCharacters"]); + } + + public bool Authenticate(string email, SecureString password, bool offline, bool useSessionID) + { + if (transport != null) + transport.Throttled -= new ThottledEventHandler(instance_Throttled); + + transport = getTransport(email); + cacheService = new CacheService(email); + Offline = offline; + + if (offline) + return true; + + transport.Throttled += new ThottledEventHandler(instance_Throttled); + onAuthenticate(POEEventState.BeforeEvent, email); + + transport.Authenticate(email, password, useSessionID); + + onAuthenticate(POEEventState.AfterEvent, email); + + return true; + } + + void instance_Throttled(object sender, ThottledEventArgs e) + { + if (Throttled != null) + Throttled(sender, e); + } + + private ITransport getTransport(string email) + { + if (Settings.ProxySettings["Enabled"] != bool.TrueString) + return new CachedTransport(email, new HttpTransport(email)); + + return new CachedTransport(email, new HttpTransport(email, Settings.ProxySettings["Username"], Settings.ProxySettings["Password"], Settings.ProxySettings["Domain"])); + } + + public void ForceRefresh() + { + cacheService.Clear(); + } + + public Stash GetStash(int index, string league, bool forceRefresh) + { + DataContractJsonSerializer serialiser = new DataContractJsonSerializer(typeof(JSONProxy.Stash)); + JSONProxy.Stash proxy = null; + + onStashLoaded(POEEventState.BeforeEvent, index, -1); + + using (Stream stream = transport.GetStash(index, league, forceRefresh)) + { + try + { + proxy = (JSONProxy.Stash)serialiser.ReadObject(stream); + if (proxy == null) + logNullStash(stream, "Proxy was null"); + } + catch (Exception ex) + { + Logger.Log(ex); + logNullStash(stream, "JSON Serialization Failed"); + } + } + + onStashLoaded(POEEventState.AfterEvent, index, proxy.NumTabs); + + return new Stash(proxy); + } + + private void logNullStash(Stream stream, string errorPrefix) + { + try + { + MemoryStream ms = stream as MemoryStream; + ms.Seek(0, SeekOrigin.Begin); + Logger.Log(errorPrefix + ": base64 bytes:"); + Logger.Log(Convert.ToBase64String(ms.ToArray())); + Logger.Log("END"); + } + catch (Exception ex) + { + Logger.Log(ex); + } + + throw new Exception(@"Downloading stash, details logged to DebugLog.log, please open a ticket at https://code.google.com/p/procurement/issues/list"); + } + + public Stash GetStash(string league) + { + var myTabs = Settings.Lists["MyTabs"]; + bool onlyMyTabs = myTabs.Count != 0; + + Stash stash = GetStash(0, league, false); + + if (stash.Tabs[0].Hidden) + stash.ClearItems(); + + List skippedTabs = new List(); + + if (!onlyMyTabs) + return getAllTabs(league, stash); + + int tabCount = 0; + + for (int i = 1; i < stash.NumberOfTabs; i++) + { + if (myTabs.Contains(stash.Tabs[i].Name)) + { + stash.Add(GetStash(i, league, false)); + ++tabCount; + } + else + skippedTabs.Add(stash.Tabs[i]); + } + + foreach (var tab in skippedTabs) + stash.Tabs.Remove(tab); + + stash.NumberOfTabs = tabCount + 1; + + return stash; + } + + private Stash getAllTabs(string league, Stash stash) + { + List hiddenTabs = new List(); + + for (int i = 1; i < stash.NumberOfTabs; i++) + if (!stash.Tabs[i].Hidden) + stash.Add(GetStash(i, league, false)); + else + hiddenTabs.Add(stash.Tabs[i]); + + if (stash.Tabs[0].Hidden) + { + stash.Tabs.Remove(stash.Tabs[0]); + --stash.NumberOfTabs; + } + + foreach (var tab in hiddenTabs) + { + stash.Tabs.Remove(tab); + --stash.NumberOfTabs; + } + + return stash; + } + + public List GetCharacters() + { + DataContractJsonSerializer serialiser = new DataContractJsonSerializer(typeof(List)); + List characters; + + using (Stream stream = transport.GetCharacters()) + characters = (List)serialiser.ReadObject(stream); + + return characters.Select(c => new Character(c)).ToList(); + } + + public List GetInventory(string characterName, bool forceRefresh) + { + try + { + if (downOnlyMyCharacters && !Settings.Lists["MyCharacters"].Contains(characterName)) + return new List(); + + DataContractJsonSerializer serialiser = new DataContractJsonSerializer(typeof(JSONProxy.Inventory)); + JSONProxy.Inventory item; + + using (Stream stream = transport.GetInventory(characterName, forceRefresh)) + item = (JSONProxy.Inventory)serialiser.ReadObject(stream); + + if (item.Items == null) + return new List(); + + return item.Items.Select(i => ItemFactory.Get(i)).ToList(); + } + catch (SerializationException sex) + { + Logger.Log(sex); + throw new Exception(string.Format("Error reading character data for {0}, if you are in offline mode you will need to login and update. If you received this error while logging in, the authenticated session may have expired or bad data has been returned by GGG or a network issue may have occurred - Please try again.", characterName)); + } + } + + public void GetImages(Stash stash) + { + foreach (var item in stash.Get().Distinct(new ImageComparer())) + getImageWithEvents(item); + + foreach (var item in stash.Tabs) + getImageWithEvents("Tab Icon " + item.i, item.srcC); + } + + public void GetImages(IEnumerable items) + { + foreach (var item in items.Distinct(new ImageComparer())) + getImageWithEvents(item); + } + + private void getImageWithEvents(Item item) + { + getImageWithEvents(GetItemName(item), item.IconURL); + } + + private void getImageWithEvents(string name, string url) + { + onImageLoaded(POEEventState.BeforeEvent, name); + transport.GetImage(url); + onImageLoaded(POEEventState.AfterEvent, name); + } + + public Stream GetImage(string url) + { + return transport.GetImage(url); + } + + public Stream GetImage(Item item) + { + onImageLoaded(POEEventState.BeforeEvent, GetItemName(item)); + Stream ret = transport.GetImage(item.IconURL); + onImageLoaded(POEEventState.AfterEvent, GetItemName(item)); + + return ret; + } + + public IEnumerable GetImage(Tab tab) + { + onImageLoaded(POEEventState.BeforeEvent, tab.Name); + yield return transport.GetImage(tab.srcL); + yield return transport.GetImage(tab.srcC); + yield return transport.GetImage(tab.srcR); + onImageLoaded(POEEventState.AfterEvent, tab.Name); + } + + public bool UpdateThread(string threadID, string threadTitle, string threadText) + { + return transport.UpdateThread(threadID, threadTitle, threadText); + } + + public bool BumpThread(string threadId) + { + return transport.BumpThread(threadId); + } + + private static string GetItemName(Item item) + { + if (item.Name != string.Empty) + return item.Name; + + return item.TypeLine; + } + + public Dictionary CalculateFreeSpace(Stash stash) + { + return stash.CalculateFreeSpace(); + } + + private void onStashLoaded(POEEventState state, int index, int numberOfTabs) + { + if (StashLoading != null) + StashLoading(this, new StashLoadedEventArgs(index, numberOfTabs, state)); + } + + private void onImageLoaded(POEEventState state, string url) + { + if (ImageLoading != null) + ImageLoading(this, new ImageLoadedEventArgs(url, state)); + } + + private void onAuthenticate(POEEventState state, string email) + { + if (Authenticating != null) + Authenticating(this, new AuthenticateEventArgs(email, state)); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `ms` last assigned on line 112 could be null and is dereferenced at line 113, column 17. + +### Severity: +ERROR + +### Procedure: +Void POEModel.logNullStash(Stream,String) + +### File: +POEApi.Model/POEModel.cs + +### Key: +POEModel.cs|logNullStash|NULL_DEREFERENCE + +### Node Key: +2492dd55e18d4854810eec2af8d6b86c + +### Hash: +ae0d37004de706850ec847004c5cbc21 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1566/instruction.md b/inferredbugs-1566/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9756ad3705034fe99a8e024d90cf1fb95e8f6854 --- /dev/null +++ b/inferredbugs-1566/instruction.md @@ -0,0 +1,129 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** MefContrib +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.ComponentModel.Composition.Hosting; +using System.ComponentModel.Composition.Primitives; +using System.Linq; +using System.Text; + +namespace MefContrib.Interception.Generics +{ + public class GenericExportHandler : IExportHandler + { + private ComposablePartCatalog _decoratedCatalog; + private AggregateCatalog _catalog = new AggregateCatalog(); + private IDictionary _genericTypes = new Dictionary(); + private List _manufacturedParts = new List(); + + #region IExportHandler Members + + public void Initialize(ComposablePartCatalog catalog) + { + _decoratedCatalog = catalog; + LoadTypeMappings(_genericTypes); + } + + private void LoadTypeMappings(IDictionary genericTypes) + { + using (var ep = new CatalogExportProvider(_decoratedCatalog)) + { + ep.SourceProvider = ep; + var locators = ep.GetExportedValues(); + foreach (var locator in locators) + genericTypes.Add(locator.GenericContractTypeDefinition, locator.GenericImplementationTypeDefinition); + } + } + + private void CreateGenericPart(Type importDefinitionType) + { + var type = TypeHelper.BuildGenericType(importDefinitionType, _genericTypes); + _manufacturedParts.Add(type); + var typeCatalog = new TypeCatalog(type); + _catalog.Catalogs.Add(typeCatalog); + } + + public IEnumerable> GetExports(ImportDefinition definition, IEnumerable> exports) + { + var contractDef = (ContractBasedImportDefinition)definition; + List> returnedExports = new List>(); + Type importDefinitionType = TypeHelper.GetImportDefinitionType(definition); + + ComposablePartDefinition partDefinition = null; + + if (exports.Any()) + return exports; + + var genericExports = _catalog.GetExports(definition); + returnedExports.Concat(exports); + + if (_manufacturedParts.Contains(importDefinitionType)) + returnedExports.AddRange(_catalog.GetExports(definition)); + else if (TypeHelper.ShouldCreateClosedGenericPart(contractDef, importDefinitionType)) + { + CreateGenericPart(importDefinitionType); + returnedExports.AddRange(_catalog.GetExports(definition)); + } + return returnedExports; + } + + #endregion + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource typeCatalog of type System.ComponentModel.Composition.Hosting.TypeCatalog in method "Void GenericExportHandler.CreateGenericPart(Type)". + +### Severity: +ERROR + +### Procedure: +Void GenericExportHandler.CreateGenericPart(Type) + +### File: +src/MefContrib.Interception/Generics/GenericExportHandler.cs + +### Key: +GenericExportHandler.cs|CreateGenericPart|DOTNET_RESOURCE_LEAK + +### Hash: +81f6fc69ec478e78d7c756e6056badc8 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1568/instruction.md b/inferredbugs-1568/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5ea956073a9aaa5a7f5d6d46d8f105862ed32e3e --- /dev/null +++ b/inferredbugs-1568/instruction.md @@ -0,0 +1,106 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** MefContrib +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace MefContrib.Hosting.Interception.Handlers +{ + using System; + using System.Collections.Generic; + using System.ComponentModel.Composition.Hosting; + using System.ComponentModel.Composition.Primitives; + using System.Linq; + + public class ConcreteTypeExportHandler : IExportHandler + { + private readonly AggregateCatalog catalog; + + public ConcreteTypeExportHandler() + { + this.catalog = new AggregateCatalog(); + } + + public void Initialize(ComposablePartCatalog interceptedCatalog) + { + } + + public IEnumerable> GetExports(ImportDefinition definition, IEnumerable> exports) + { + if (!exports.Any()) + exports = this.catalog.GetExports(definition); + + if (exports.Any()) + return exports; + + var returnedExports = new List>(); + var importDefinitionType = TypeHelper.GetImportDefinitionType(definition); + + if (!importDefinitionType.IsAbstract && !importDefinitionType.IsInterface) + { + var typeCatalog = new TypeCatalog(importDefinitionType); + this.catalog.Catalogs.Add(typeCatalog); + var currentExports = this.catalog.GetExports(definition); + returnedExports.AddRange(currentExports); + } + + return returnedExports; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `importDefinitionType` last assigned on line 31 could be null and is dereferenced at line 33, column 13. + +### Severity: +ERROR + +### Procedure: +IEnumerable`1 ConcreteTypeExportHandler.GetExports(ImportDefinition,IEnumerable`1) + +### File: +src/MefContrib/Hosting/Interception/Handlers/ConcreteTypeExportHandler.cs + +### Key: +ConcreteTypeExportHandler.cs|GetExports|NULL_DEREFERENCE + +### Node Key: +56203f4e21ecf9e860f6a12dc3683775 + +### Hash: +5a2dc5275ec44a24835d86a03c4e8732 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1592/instruction.md b/inferredbugs-1592/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..39b66697a1bbd87ca21b2e7057af70b0ba2f467e --- /dev/null +++ b/inferredbugs-1592/instruction.md @@ -0,0 +1,233 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** AlterNats +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Threading.Tasks.Sources; + +namespace AlterNats.Commands; + +internal sealed class PublishCommand : CommandBase> +{ + NatsKey? subject; + T? value; + INatsSerializer? serializer; + + PublishCommand() + { + } + + // TODO:reply-to + + public static PublishCommand Create(string subject, T? value, INatsSerializer serializer) + { + if (!pool.TryPop(out var result)) + { + result = new PublishCommand(); + } + + result.subject = new NatsKey(subject); // TODO:use specified overload. + result.value = value; + result.serializer = serializer; + + return result; + } + + public static PublishCommand Create(NatsKey subject, T? value, INatsSerializer serializer) + { + if (!pool.TryPop(out var result)) + { + result = new PublishCommand(); + } + + result.subject = subject; + result.value = value; + result.serializer = serializer; + + return result; + } + + public override void Write(ProtocolWriter writer) + { + writer.WritePublish(subject!, null, value, serializer!); + } + + public override void Reset() + { + subject = null; + value = default; + serializer = null; + } +} + +internal sealed class AsyncPublishCommand : AsyncCommandBase> +{ + NatsKey? subject; + T? value; + INatsSerializer? serializer; + + AsyncPublishCommand() + { + } + + // TODO:reply-to + + public static AsyncPublishCommand Create(string subject, T? value, INatsSerializer serializer) + { + if (!pool.TryPop(out var result)) + { + result = new AsyncPublishCommand(); + } + + result.subject = new NatsKey(subject); // TODO:use specified overload. + result.value = value; + result.serializer = serializer; + + return result; + } + + public static AsyncPublishCommand Create(NatsKey subject, T? value, INatsSerializer serializer) + { + if (!pool.TryPop(out var result)) + { + result = new AsyncPublishCommand(); + } + + result.subject = subject; + result.value = value; + result.serializer = serializer; + + return result; + } + + public override void Write(ProtocolWriter writer) + { + writer.WritePublish(subject!, null, value, serializer!); + } + + public override void Reset() + { + subject = null; + value = default; + serializer = null; + } +} + + + +// TODO:Async Impl +internal sealed class PublishBytesCommand : CommandBase +{ + string? stringSubject; + string? stringReplyTo; + NatsKey? encodedSubject; + NatsKey? encodedReplyTo; + ReadOnlyMemory value; + + PublishBytesCommand() + { + } + + public static PublishBytesCommand Create(string subject, string? replyTo, ReadOnlyMemory value) + { + if (!pool.TryPop(out var result)) + { + result = new PublishBytesCommand(); + } + + result.stringSubject = subject; + result.stringReplyTo = replyTo; + result.value = value; + + return result; + } + + public static PublishBytesCommand Create(NatsKey subject, NatsKey? replyTo, byte[] value, INatsSerializer serializer) + { + if (!pool.TryPop(out var result)) + { + result = new PublishBytesCommand(); + } + + result.encodedSubject = subject; + result.encodedReplyTo = replyTo; + result.value = value; + + return result; + } + + public override void Write(ProtocolWriter writer) + { + if (stringSubject != null) + { + writer.WritePublish(stringSubject, stringReplyTo, value.Span); + } + else + { + writer.WritePublish(encodedSubject!, encodedReplyTo, value.Span); + } + } + + public override void Reset() + { + stringSubject = null; + stringReplyTo = null; + encodedSubject = null; + encodedReplyTo = null; + value = default; + } +} + +``` + +### Bug Type: +PULSE_UNINITIALIZED_VALUE + +### Qualifier: +`result` is read without initialization. + +### Severity: +ERROR + +### Procedure: +PublishBatchCommand`1 PublishBatchCommand`1.Create(ObjectPool,IEnumerable`1,INatsSerializer) + +### File: +src/AlterNats/Commands/PublishCommand.cs + +### Key: +PublishCommand.cs|Create|PULSE_UNINITIALIZED_VALUE + +### Hash: +e15053763e1d3ff6460996c188d49ff5 + +### Bug Type Hum: +Uninitialized Value + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1595/instruction.md b/inferredbugs-1595/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..94b22be54256766415c577b1e3a643f5ae6aef0b --- /dev/null +++ b/inferredbugs-1595/instruction.md @@ -0,0 +1,322 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** NRules +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace NRules.Json.Converters +{ + internal class ExpressionConverter : JsonConverter + { + public override bool CanConvert(Type typeToConvert) => + typeof(Expression).IsAssignableFrom(typeToConvert); + + public override Expression Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType != JsonTokenType.StartObject) throw new JsonException(); + + reader.Read(); + if (reader.TokenType != JsonTokenType.PropertyName && + reader.GetString() != nameof(Expression.NodeType)) throw new JsonException(); + reader.Read(); + if (!Enum.TryParse(reader.GetString(), out ExpressionType nodeType)) throw new JsonException(); + + Expression value; + if (nodeType == ExpressionType.Lambda) + value = ReadLambda(ref reader, options); + else if (nodeType == ExpressionType.Parameter) + value = ReadParameter(ref reader, options); + else if (nodeType == ExpressionType.MemberAccess) + value = ReadMember(ref reader, options); + else if (nodeType == ExpressionType.Call) + value = ReadMethodCall(ref reader, options); + else + throw new NotSupportedException($"Unsupported expression type. NodeType={nodeType}"); + + return value; + } + + public override void Write(Utf8JsonWriter writer, Expression value, JsonSerializerOptions options) + { + writer.WriteStartObject(); + writer.WriteString(nameof(value.NodeType), value.NodeType.ToString()); + + if (value is LambdaExpression le) + WriteLambda(writer, options, le); + else if (value is ParameterExpression pe) + WriteParameter(writer, options, pe); + else if (value is MemberExpression me) + WriteMember(writer, options, me); + else if (value is MethodCallExpression mce) + WriteMethodCall(writer, options, mce); + else + throw new NotSupportedException($"Unsupported expression type. NodeType={value.NodeType}"); + + writer.WriteEndObject(); + } + + private Expression ReadLambda(ref Utf8JsonReader reader, JsonSerializerOptions options) + { + Type type = default; + Expression body = default; + var parameters = new List(); + + while (reader.Read() && reader.TokenType != JsonTokenType.EndObject) + { + if (reader.TokenType != JsonTokenType.PropertyName) throw new JsonException(); + var propertyName = reader.GetString(); + reader.Read(); + + if (propertyName == nameof(LambdaExpression.Type)) + { + type = JsonSerializer.Deserialize(ref reader, options); + } + else if (propertyName == nameof(LambdaExpression.Body)) + { + body = JsonSerializer.Deserialize(ref reader, options); + } + else if (propertyName == nameof(LambdaExpression.Parameters)) + { + if (reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + + while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) + { + var parameter = JsonSerializer.Deserialize(ref reader, options); + parameters.Add(parameter); + } + } + } + + var expression = Expression.Lambda(type!, body!, parameters); + + var parameterCompactor = new ExpressionParameterCompactor(); + var result = parameterCompactor.Compact(expression); + + return result; + } + + private void WriteLambda(Utf8JsonWriter writer, JsonSerializerOptions options, LambdaExpression value) + { + writer.WritePropertyName(nameof(value.Type)); + JsonSerializer.Serialize(writer, value.Type, options); + + writer.WritePropertyName(nameof(value.Body)); + JsonSerializer.Serialize(writer, value.Body, options); + + writer.WriteStartArray(nameof(value.Parameters)); + foreach (var parameter in value.Parameters) + { + JsonSerializer.Serialize(writer, parameter, options); + } + writer.WriteEndArray(); + } + + private Expression ReadParameter(ref Utf8JsonReader reader, JsonSerializerOptions options) + { + Type type = default; + string name = default; + + while (reader.Read() && reader.TokenType != JsonTokenType.EndObject) + { + if (reader.TokenType != JsonTokenType.PropertyName) throw new JsonException(); + var propertyName = reader.GetString(); + reader.Read(); + + if (propertyName == nameof(ParameterExpression.Name)) + { + name = reader.GetString(); + } + else if (propertyName == nameof(ParameterExpression.Type)) + { + type = JsonSerializer.Deserialize(ref reader, options); + } + } + + return Expression.Parameter(type!, name); + } + + private void WriteParameter(Utf8JsonWriter writer, JsonSerializerOptions options, ParameterExpression value) + { + writer.WriteString(nameof(value.Name), value.Name); + + writer.WritePropertyName(nameof(value.Type)); + JsonSerializer.Serialize(writer, value.Type, options); + } + + private Expression ReadMember(ref Utf8JsonReader reader, JsonSerializerOptions options) + { + Expression expression = default; + MemberTypes memberType = default; + string name = default; + Type declaringType = default; + + while (reader.Read() && reader.TokenType != JsonTokenType.EndObject) + { + if (reader.TokenType != JsonTokenType.PropertyName) throw new JsonException(); + var propertyName = reader.GetString(); + reader.Read(); + + if (propertyName == nameof(MemberExpression.Expression)) + { + expression = JsonSerializer.Deserialize(ref reader, options); + } + else if (propertyName == nameof(MemberExpression.Member.MemberType)) + { + Enum.TryParse(reader.GetString(), out memberType); + } + else if (propertyName == nameof(MemberExpression.Member.Name)) + { + name = reader.GetString(); + } + else if (propertyName == nameof(MemberExpression.Member.DeclaringType)) + { + declaringType = JsonSerializer.Deserialize(ref reader, options); + } + } + + MemberInfo member; + if (memberType == MemberTypes.Field) + member = declaringType.GetField(name); + else if (memberType == MemberTypes.Property) + member = declaringType.GetProperty(name); + else + throw new NotSupportedException($"MemberType={memberType}"); + + return Expression.MakeMemberAccess(expression, member!); + } + + private void WriteMember(Utf8JsonWriter writer, JsonSerializerOptions options, MemberExpression value) + { + writer.WriteString(nameof(value.Member.MemberType), value.Member.MemberType.ToString()); + writer.WriteString(nameof(value.Member.Name), value.Member.Name); + writer.WritePropertyName(nameof(value.Member.DeclaringType)); + JsonSerializer.Serialize(writer, value.Member.DeclaringType, options); + + writer.WritePropertyName(nameof(value.Expression)); + JsonSerializer.Serialize(writer, value.Expression, options); + } + + private Expression ReadMethodCall(ref Utf8JsonReader reader, JsonSerializerOptions options) + { + Expression @object = default; + string name = default; + Type declaringType = default; + var arguments = new List(); + + while (reader.Read() && reader.TokenType != JsonTokenType.EndObject) + { + if (reader.TokenType != JsonTokenType.PropertyName) throw new JsonException(); + var propertyName = reader.GetString(); + reader.Read(); + + if (propertyName == nameof(MethodCallExpression.Object)) + { + @object = JsonSerializer.Deserialize(ref reader, options); + } + else if (propertyName == nameof(MethodCallExpression.Method.Name)) + { + name = reader.GetString(); + } + else if (propertyName == nameof(MethodCallExpression.Method.DeclaringType)) + { + declaringType = JsonSerializer.Deserialize(ref reader, options); + } + else if (propertyName == nameof(MethodCallExpression.Arguments)) + { + if (reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); + + while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) + { + var argument = JsonSerializer.Deserialize(ref reader, options); + arguments.Add(argument); + } + } + } + + var method = declaringType!.GetMethod(name!, arguments.Select(x => x.Type).ToArray()); + + return Expression.Call(@object, method!, arguments); + } + + private void WriteMethodCall(Utf8JsonWriter writer, JsonSerializerOptions options, MethodCallExpression value) + { + writer.WriteString(nameof(value.Method.Name), value.Method.Name); + writer.WritePropertyName(nameof(value.Method.DeclaringType)); + JsonSerializer.Serialize(writer, value.Method.DeclaringType, options); + + if (value.Object != null) + { + writer.WritePropertyName(nameof(value.Object)); + JsonSerializer.Serialize(writer, value.Object, options); + } + + writer.WriteStartArray(nameof(value.Arguments)); + foreach (var argument in value.Arguments) + { + JsonSerializer.Serialize(writer, argument, options); + } + writer.WriteEndArray(); + } + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`name` could be null (last assigned on line 150) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +Expression ExpressionConverter.ReadMember(Utf8JsonReader&,JsonSerializerOptions) + +### File: +src/NRules/NRules.Json/Converters/ExpressionConverter.cs + +### Key: +ExpressionConverter.cs|ReadMember|NULLPTR_DEREFERENCE + +### Hash: +fba29637012c207e3b9b7fbcd6c54ba5 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1610/instruction.md b/inferredbugs-1610/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b25869a90bb74c905b4d78cbf8ccd4889e93c6cb --- /dev/null +++ b/inferredbugs-1610/instruction.md @@ -0,0 +1,2546 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ipnetwork +**Bug ID:** 18 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Numerics; + +namespace System.Net.TestProject +{ + [TestClass] + public class IPNetworkV6UnitTest { + + #region ParseIP + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE8() { + IPNetwork ipnet = IPNetwork.Parse("xxxx::", "xxxx::"); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE9() { + IPNetwork ipnet = IPNetwork.Parse("::", "xxxx::"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE10() { + IPNetwork ipnet = IPNetwork.Parse("xxxx::", 0); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE11() { + IPNetwork ipnet = IPNetwork.Parse("::", 129); + + } + + [TestMethod] + public void TestParsev6_128() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + //string broadcast = "2001:db8::"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::"; + byte cidr = 128; + BigInteger usable = 1; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_127() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"; + //string broadcast = "2001:db8::1"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::1"; + byte cidr = 127; + BigInteger usable = 2; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_126() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"; + //string broadcast = "2001:db8::3"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::3"; + byte cidr = 126; + BigInteger usable = 4; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_125() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"; + //string broadcast = "2001:db8::7"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::7"; + byte cidr = 125; + BigInteger usable = 8; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_124() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + //string broadcast = "2001:db8::f"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::f"; + byte cidr = 124; + BigInteger usable = 16; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParsev6_123() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:0db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"; + //string broadcast = "2001:db8::1f"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::1f"; + byte cidr = 123; + BigInteger usable = 32; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + + [TestMethod] + public void TestParsev6_112() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"; + + string network = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"; + //string broadcast = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 112; + uint usable = 65536; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_64() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:1234:1234:1234:1234"; + string netmask = "ffff:ffff:ffff:ffff:0000:0000:0000:0000"; + + string network = "ffff:ffff:ffff:ffff::"; + string netmask2 = "ffff:ffff:ffff:ffff::"; + //string broadcast = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 64; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)) ; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_16() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:0000:0000:0000:0000:0000:0000:0000"; + + string network = "ffff::"; + string netmask2 = "ffff::"; + //string broadcast = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 16; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)) ; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + + [TestMethod] + public void TestParsev6_EDGE() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + + string network = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 128; + uint usable = 1; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + #endregion + + #region ParseString + + [TestMethod] + public void TestParseString1() { + + string ipaddress = "2001:0db8:: ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + + string network = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::f"; + byte cidr = 124; + uint usable = 16; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParseString3() { + + string ipaddress = ":: ::"; + + string network = "::"; + string netmask = "::"; + string firstUsable = "::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 0; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)); + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParseString4() { + + string ipaddress = "::/0"; + + string network = "::"; + string netmask = "::"; + string firstUsable = "::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 0; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)); + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString5() { + + string ipaddress = "::/32"; + + string network = "::"; + string netmask = "ffff:ffff::"; + string firstUsable = "::"; + string lastUsable = "::ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 32; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)) ; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString6() + { + + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128"; + + string network = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 128; + uint usable = 1; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString7_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFF:123::/60"; + + string network = "2fff:ffff:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:ffff:123::"; + string lastUsable = "2fff:ffff:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParseString8_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFE:123::/60"; + + string network = "2fff:fffe:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:fffe:123::"; + string lastUsable = "2fff:fffe:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + + } + + [TestMethod] + public void TestParseString9_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFC:123::/60"; + + string network = "2fff:fffc:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:fffc:123::"; + string lastUsable = "2fff:fffc:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString10_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFA:123::/60"; + + string network = "2fff:fffa:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:fffa:123::"; + string lastUsable = "2fff:fffa:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString11_Uppercase_ipv6_must_parse() + { + + string ipaddress = "FFFF:FFF1:123::/60"; + + string network = "ffff:fff1:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "ffff:fff1:123::"; + string lastUsable = "ffff:fff1:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseIPAddressNoNetmask1() { + + string ipaddress = "2001:0db8::"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + + string network = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff::"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::ffff:ffff:ffff:ffff"; + byte cidr = 64; + var usable = BigInteger.Pow(2, 64); + + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + [TestMethod] + public void TestParseIPAddressNoNetmask4() { + + string ipaddress = "::"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + + + string network = "::"; + string netmask = "ffff:ffff:ffff:ffff::"; + string firstUsable = "::"; + string lastUsable = "::ffff:ffff:ffff:ffff"; + byte cidr = 64; + var usable = BigInteger.Pow(2, 64); + + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + [TestMethod] + public void TestParseIPAddressNoNetmask5() { + + string ipaddress = "2001:0db8::1"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + string network = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff::"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::ffff:ffff:ffff:ffff"; + byte cidr = 64; + var usable = BigInteger.Pow(2, 64); + + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE1() { + string ipaddress = "garbage"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE2() { + string ipaddress = "0:0:0:0:0:0:1:0:0 0:1:2:3:4:5:6:7:8"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringANE1() { + string ipaddress = null; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + + #endregion + + #region ParseStringString + + [TestMethod] + public void TestParseStringString1() { + + string ipaddress = "2001:0db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + Assert.AreEqual("2001:db8::/124", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString3() { + + string ipaddress = "2001:0db8::"; + string netmask = null; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString5() { + + string ipaddress = "2001:0db8::"; + string netmask = ""; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + #endregion + + #region ParseIpIp + + [TestMethod] + public void ParseIpIp1() { + + string ipaddress = "2001:0db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = IPAddress.Parse(netmask); + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + Assert.AreEqual("2001:db8::/124", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void ParseIpIp3() { + + string ipaddress = "2001:0db8::"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = null; + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + + } + + #endregion + + #region ToCidr + + [TestMethod] + public void TestToCidrAE() { + byte cidr = IPNetwork.ToCidr(IPAddress.IPv6Any); + Assert.AreEqual(0, cidr, "cidr"); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestToCidrAE2() { + IPNetwork.ToCidr(IPAddress.Parse("2001:db8:3:4:5:6:7:8")); + } + + + [TestMethod] + public void TestToCidr128() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + byte cidr = 128; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr127() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"); + byte cidr = 127; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr126() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"); + byte cidr = 126; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr125() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"); + byte cidr = 125; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr124() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + byte cidr = 124; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr123() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"); + byte cidr = 123; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr122() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffc0"); + byte cidr = 122; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr121() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff80"); + byte cidr = 121; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr120() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00"); + byte cidr = 120; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr119() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fe00"); + byte cidr = 119; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr118() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fc00"); + byte cidr = 118; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr117() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f800"); + byte cidr = 117; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr116() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f000"); + byte cidr = 116; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr115() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:e000"); + byte cidr = 115; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr114() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:c000"); + byte cidr = 114; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr113() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:8000"); + byte cidr = 113; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr112() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + byte cidr = 112; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr111() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffe:0"); + byte cidr = 111; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr110() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffc:0"); + byte cidr = 110; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr109() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff8:0"); + byte cidr = 109; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr108() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff0:0"); + byte cidr = 108; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr001() { + + IPAddress mask = IPAddress.Parse("8000::"); + byte cidr = 1; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr000() { + + IPAddress mask = IPAddress.Parse("::"); + byte cidr = 0; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + #endregion + + #region TryToCidr + + + [TestMethod] + public void TestTryToCidr128() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + byte cidr = 128; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + + [TestMethod] + public void TestTryToCidr127() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"); + byte cidr = 127; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr126() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"); + byte cidr = 126; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr125() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"); + byte cidr = 125; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr124() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + byte cidr = 124; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr123() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"); + byte cidr = 123; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr122() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffc0"); + byte cidr = 122; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr121() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff80"); + byte cidr = 121; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr120() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00"); + byte cidr = 120; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr119() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fe00"); + byte cidr = 119; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr118() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fc00"); + byte cidr = 118; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr117() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f800"); + byte cidr = 117; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr116() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f000"); + byte cidr = 116; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr115() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:e000"); + byte cidr = 115; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr114() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:c000"); + byte cidr = 114; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr113() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:8000"); + byte cidr = 113; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr112() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + byte cidr = 112; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr111() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffe:0"); + byte cidr = 111; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr110() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffc:0"); + byte cidr = 110; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr109() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff8:0"); + byte cidr = 109; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr108() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff0:0"); + byte cidr = 108; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr001() { + + IPAddress mask = IPAddress.Parse("8000::"); + byte cidr = 1; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr000() { + + IPAddress mask = IPAddress.Parse("::"); + byte cidr = 0; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + #endregion + + #region ToBigInteger + + [TestMethod] + public void TestToBigInteger32() { + + IPAddress mask = IPAddress.Parse("::f"); + uint uintMask = 0xf; + BigInteger result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger24() { + + IPAddress mask = IPAddress.Parse("::fff"); + uint uintMask = 0xfff; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger16() { + + IPAddress mask = IPAddress.Parse("::ff"); + uint uintMask = 0xff; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger8() { + + IPAddress mask = IPAddress.Parse("::ff00:0"); + uint uintMask = 0xff000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger0() { + + IPAddress mask = IPAddress.Parse("::"); + uint uintMask = 0x00000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + + #endregion + + #region TryToBigInteger + + [TestMethod] + public void TestTryToBigInteger32() { + + IPAddress mask = IPAddress.Parse("::ffff:ffff"); + uint uintMask = 0xffffffff; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger24() { + + IPAddress mask = IPAddress.Parse("::ffff:ff00"); + uint uintMask = 0xffffff00; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger16() { + + IPAddress mask = IPAddress.Parse("::ffff:0"); + uint uintMask = 0xffff0000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger8() { + + IPAddress mask = IPAddress.Parse("::ff00:0"); + uint uintMask = 0xff000000; + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger0() { + + IPAddress mask = IPAddress.Parse("::"); + uint uintMask = 0x00000000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + + #endregion + + #region TryToNetmask + [TestMethod] + public void TryToNetmask1() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(0, Sockets.AddressFamily.InterNetworkV6, out result); + IPAddress expected = IPAddress.Parse("::"); + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(true, parsed, "parsed"); + + } + + [TestMethod] + public void TryToNetmask2() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(33, Sockets.AddressFamily.InterNetworkV6, out result); + IPAddress expected = IPAddress.Parse("ffff:ffff:8000::"); + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(true, parsed, "parsed"); + + } + + #endregion + + #region ToNetmask + + [TestMethod] + public void ToNetmask128() { + + byte cidr = 128; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask31() { + + byte cidr = 127; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask30() { + + byte cidr = 126; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask1() { + + byte cidr = 1; + string netmask = "8000::"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + + [TestMethod] + public void ToNetmask0() { + + byte cidr = 0; + string netmask = "::"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void ToNetmaskOORE1() { + byte cidr = 129; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + } + + #endregion + + #region ValidNetmask + + [TestMethod] + public void TestValidNetmask0() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask1() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask2() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + public void TestValidNetmaskEAE1() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:0000:ffff"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmaskEAE3() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:0000:0001"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + #endregion + + #region BitsSet + + [TestMethod] + public void TestBitsSet128() { + + IPAddress ip = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + uint bits = 128; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet120() { + + IPAddress ip = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + uint bits = 124; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet16() { + + IPAddress ip = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + uint bits = 112; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet4() { + + IPAddress ip = IPAddress.Parse("f0f0:f0f0:f0f0:f0f0:f0f0:f0f0:f0f0:f0f0"); + uint bits = 64; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + + #endregion + + #region Contains + + [TestMethod] + public void TestContains1() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPAddress ipaddress = IPAddress.Parse("2001:0db8::1"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains2() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPAddress ipaddress = IPAddress.Parse("2001:0db8:0:1::"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains3() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::/64"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains4() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::/65"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains5() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8:1::/65"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + + [TestMethod] + public void TestContains6() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::/63"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains10() + { + + IPNetwork ipnetwork = IPNetwork.Parse("::/0"); + IPAddress ipaddress = null; + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + + } + + [TestMethod] + public void TestContains11_different_adress_family_returns_false() + { + + IPNetwork ipnetwork = IPNetwork.Parse("::1"); // IPv6 + IPAddress ipaddress = IPAddress.Parse("127.0.0.1"); // IPv4 + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + Assert.AreEqual(false, result, "contains"); + + } + + #endregion + + #region Overlap + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestOverlap2() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8::/0"); + IPNetwork network2 = null; + IPNetwork.Overlap(network1, network2); + } + + [TestMethod] + public void TestOverlap3() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8::/64"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap4() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8:0:0:1::/65"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap5() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8:0:1::/68"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8:0:2::/68"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = false; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap6() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8:0:1::/68"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8:0:2::/62"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + #endregion + + #region Examples + + public void Example1() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + public void Example2() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + + IPAddress ipaddress = IPAddress.Parse("2001:0db8::1"); + IPAddress ipaddress2 = IPAddress.Parse("2001:0db9::1"); + + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::1/128"); + IPNetwork ipnetwork3 = IPNetwork.Parse("2001:0db9::1/64"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + bool contains3 = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool contains4 = IPNetwork.Contains(ipnetwork, ipnetwork3); + + bool overlap1 = IPNetwork.Overlap(ipnetwork, ipnetwork2); + bool overlap2 = IPNetwork.Overlap(ipnetwork, ipnetwork3); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork2, contains3); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork3, contains4); + + + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork2, overlap1); + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork3, overlap2); + + + } + + public void Example4() { + IPNetwork wholeInternet = IPNetwork.Parse("::/0"); + byte newCidr = 2; + IPNetworkCollection subneted = IPNetwork.Subnet(wholeInternet, newCidr); + + Console.WriteLine("{0} was subnetted into {1} subnets", wholeInternet, subneted.Count); + Console.WriteLine("First: {0}", subneted[0]); + Console.WriteLine("Last : {0}", subneted[subneted.Count - 1]); + Console.WriteLine("All :"); + + foreach (IPNetwork ipnetwork in subneted) { + Console.WriteLine("{0}", ipnetwork); + } + } + + public void Example5() { + IPNetwork ipnetwork1 = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db9::/64"); + IPNetwork[] ipnetwork3 = IPNetwork.Supernet(new[] { ipnetwork1, ipnetwork2 }); + + Console.WriteLine("{0} + {1} = {2}", ipnetwork1, ipnetwork2, ipnetwork3[0]); + + } + public void Example6() { + + IPNetwork ipnetwork = IPNetwork.Parse("fe80::202:b3ff:fe1e:8329/24"); + + IPAddress ipaddress = IPAddress.Parse("2001:db8::"); + IPAddress ipaddress2 = IPAddress.Parse("fe80::202:b3ff:fe1e:1"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + + } + + + + public void Example8() { + + IPNetwork network = IPNetwork.Parse("::/124"); + IPNetworkCollection ips = IPNetwork.Subnet(network, 128); + + foreach (IPNetwork ip in ips) { + Console.WriteLine("{0}", ip); + } + } + + + #endregion + + #region ToString + + + [TestMethod] + public void TestToString() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:0000:0000:0000:0000:0000:0000/32"); + string expected = "2001:db8::/32"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString1() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:1:2:3:4:5:6/32"); + string expected = "2001:db8::/32"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString2() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:1:2:3:4:5:6/64"); + string expected = "2001:db8:1:2::/64"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString3() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:1:2:3:4:5:6/100"); + string expected = "2001:db8:1:2:3:4::/100"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + #endregion + + + #region Subnet + + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet3() { + + IPNetwork ipnetwork = IPNetwork.Parse("::"); + byte cidr = 129; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSubnet4() { + + IPNetwork ipnetwork = IPNetwork.Parse("::"); + byte cidr = 1; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + public void TestSubnet5() { + + IPNetwork ipnetwork = IPNetwork.Parse("1:1:1:1:1:1:1:1"); + byte cidr = 65; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("1:1:1:1::/65", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("1:1:1:1:8000::/65", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestSubnet6() { + + IPNetwork ipnetwork = IPNetwork.Parse("1:1:1:1:1:1:1:1"); + byte cidr = 68; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("1:1:1:1::/68", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("1:1:1:1:1000::/68", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("1:1:1:1:2000::/68", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("1:1:1:1:3000::/68", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("1:1:1:1:4000::/68", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("1:1:1:1:5000::/68", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("1:1:1:1:6000::/68", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("1:1:1:1:7000::/68", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("1:1:1:1:8000::/68", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("1:1:1:1:9000::/68", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("1:1:1:1:a000::/68", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("1:1:1:1:b000::/68", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("1:1:1:1:c000::/68", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("1:1:1:1:d000::/68", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("1:1:1:1:e000::/68", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("1:1:1:1:f000::/68", subnets[15].ToString(), "subnet16"); + + } + + + [TestMethod] + public void TestSubnet7() { + + IPNetwork ipnetwork = IPNetwork.Parse("1:1:1:1:1:1:1:1"); + byte cidr = 72; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("1:1:1:1::/72", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("1:1:1:1:ff00::/72", subnets[255].ToString(), "subnet256"); + + } + + + [TestMethod] + public void TestSubnet9() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08:1:1:1:1:1:1"); + byte cidr = 128; + var count = BigInteger.Pow(2, ipnetwork.Cidr); + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(count, subnets.Count, "count"); + Assert.AreEqual("2001:db08:1:1::/128", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("2001:db08:1:1::ff/128", subnets[255].ToString(), "subnet256"); + Assert.AreEqual("2001:db08:1:1:ffff:ffff:ffff:ffff/128", subnets[count-1].ToString(), "last"); + + } + + + [TestMethod] + public void TestSubnet10() { + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/0"); + byte cidr = 128; + var count = BigInteger.Pow(2, 128-ipnetwork.Cidr); + + // Here I spawm a OOM dragon ! beware of the beast ! + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(count, subnets.Count, "count"); + Assert.AreEqual("::/128", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128", subnets[count - 1].ToString(), "last"); + + } + + + [TestMethod] + public void TestSubnet12() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 70; + int i = -1; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + foreach (IPNetwork ipn in subnets) { + i++; + Assert.AreEqual(subnets[i], ipn, "subnet"); + } + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet13() + { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 70; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + IPNetwork error = subnets[1000]; + + } + + + + [TestMethod] + public void TestSubnet14() + { + + IPNetwork network = IPNetwork.Parse("15.0.0.0/8"); + var subnets = IPNetwork.Subnet(network, (byte)12); + Assert.AreEqual(subnets[0].ToString(), "15.0.0.0/12", "subnets[0]"); + Assert.AreEqual(subnets[1].ToString(), "15.16.0.0/12", "subnets[1]"); + Assert.AreEqual(subnets[2].ToString(), "15.32.0.0/12", "subnets[2]"); + Assert.AreEqual(subnets[15].ToString(), "15.240.0.0/12", "subnets[15]"); + + foreach (IPNetwork ipn in subnets) + { + Console.WriteLine(ipn); + } + } + + + + #endregion + + #region TrySubnet + + + [TestMethod] + public void TestTrySubnet3() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 255; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + } + + + [TestMethod] + public void TestTrySubnet4() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 63; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + + } + + + [TestMethod] + public void TestTrySubnet5() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db8::/64"); + byte cidr = 65; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("2001:db8::/65", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("2001:db8:0:0:8000::/65", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestTrySubnet6() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db8::/64"); + byte cidr = 68; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("2001:db8::/68", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("2001:db8:0:0:1000::/68", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("2001:db8:0:0:2000::/68", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("2001:db8:0:0:3000::/68", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("2001:db8:0:0:4000::/68", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("2001:db8:0:0:5000::/68", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("2001:db8:0:0:6000::/68", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("2001:db8:0:0:7000::/68", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("2001:db8:0:0:8000::/68", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("2001:db8:0:0:9000::/68", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("2001:db8:0:0:a000::/68", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("2001:db8:0:0:b000::/68", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("2001:db8:0:0:c000::/68", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("2001:db8:0:0:d000::/68", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("2001:db8:0:0:e000::/68", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("2001:db8:0:0:f000::/68", subnets[15].ToString(), "subnet16"); + + } + + + + #endregion + + + + + + + #region TrySupernet + + + [TestMethod] + public void TestTrySupernet1() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/65"); + IPNetwork network2 = IPNetwork.Parse("2001:db8:0:0:8000::/65"); + IPNetwork supernetExpected = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernet; + bool supernetted = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetted, result, "supernetted"); + Assert.AreEqual(supernetExpected, supernet, "supernet"); + + } + + [TestMethod] + public void TestTrySupernet2() { + + IPNetwork network1 = null; + IPNetwork network2 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet3() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = null; + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet4() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:db9::/65"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet5() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:dba::/64"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet6() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:db8::1/65"); + IPNetwork supernetExpected = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet7() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:db8::1/65"); + IPNetwork supernetExpected = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet8() { + + IPNetwork network1 = IPNetwork.Parse("2001:db0::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:dbf::/64"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet9() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork[] network3 = new[] { network1, network2 }; + IPNetwork[] supernetExpected = new[] { network1, network2 }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(supernetExpected[1], supernet[1], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet10() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8:0000::/65"); + IPNetwork network2 = IPNetwork.Parse("2001:db8:0:0:8000::/65"); + IPNetwork[] network3 = new[] { network1, network2 }; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("2001:db8::/64") }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet11() { + + IPNetwork[] network3 = null; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("2001:db8::/64") }; + IPNetwork[] supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(null, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + #endregion + + + + + + + + #region TryGuessCidr + + [TestMethod] + public void TestTryGuessCidrNull() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr(null, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(0, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidr1() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("::", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(64, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidr2() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("2001:0db8::", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(64, cidr, "cidr"); + } + + + #endregion + + + + + #region Count + + [TestMethod] + public void Total32() { + var network = IPNetwork.Parse("::/128"); + var total = 1; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total31() { + var network = IPNetwork.Parse("::/127"); + var total = 2; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total30() { + var network = IPNetwork.Parse("::/126"); + var total = 4; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total24() { + var network = IPNetwork.Parse("::/120"); + var total = 256; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total16() { + var network = IPNetwork.Parse("::/112"); + var total = 65536; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total8() { + var network = IPNetwork.Parse("::/104"); + var total = 16777216; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total0() { + var network = IPNetwork.Parse("::/0"); + var total = BigInteger.Pow(2, 128); + Assert.AreEqual(total, network.Total, "Total"); + } + + #endregion + + #region Usable + + [TestMethod] + public void Usable32() { + var network = IPNetwork.Parse("::/128"); + uint usable = 1; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable31() { + var network = IPNetwork.Parse("::/127"); + uint usable = 2; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable30() { + var network = IPNetwork.Parse("::/126"); + uint usable = 4; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable24() { + var network = IPNetwork.Parse("::/120"); + uint usable = 256; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable16() { + var network = IPNetwork.Parse("::/112"); + uint usable = 65536; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable8() { + var network = IPNetwork.Parse("::/104"); + uint usable = 16777216; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable0() { + var network = IPNetwork.Parse("::/0"); + var usable = BigInteger.Pow(2, 128); + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + #endregion + + #region TryParseCidr + + [TestMethod] + public void TryParseCidr1() { + + string sidr = "0"; + byte? cidr; + byte? result = 0; + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr2() { + + string sidr = "sadsd"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr33() { + + string sidr = "33"; + byte? cidr; + byte result = 33; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr128() { + + string sidr = "128"; + byte? cidr; + byte result = 128; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + [TestMethod] + public void TryParseCidr129() { + + string sidr = "129"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + #endregion + + + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource subnets of type System.Net.IPNetworkCollection in method "Void IPNetworkV6UnitTest.TestSubnet10()". + +### Severity: +ERROR + +### Procedure: +Void IPNetworkV6UnitTest.TestSubnet10() + +### File: +src/System.Net.IPNetwork.TestProject.Source/IPNetworkV6UnitTest.cs + +### Key: +IPNetworkV6UnitTest.cs|TestSubnet10|DOTNET_RESOURCE_LEAK + +### Hash: +13e28c1466138755893be5403a90e386 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1611/instruction.md b/inferredbugs-1611/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3262be7f136e380ff393e0901d4bbc26ba5980be --- /dev/null +++ b/inferredbugs-1611/instruction.md @@ -0,0 +1,3382 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ipnetwork +**Bug ID:** 27 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; + +namespace System.Net.TestProject +{ + /// + /// IPNetworkUnitTest test every single method + /// + [TestClass] + public class IPNetworkUnitTest { + + #region Parse + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE2() { + IPAddress ip = null; + IPNetwork.Parse(ip, ip); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE3() { + IPNetwork.Parse("", 0); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE4() { + IPNetwork.Parse(null, 0); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE5() { + string n = null; + IPNetwork.Parse(n, n); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE8() { + IPNetwork ipnet = IPNetwork.Parse("x.x.x.x", "x.x.x.x"); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE9() { + IPNetwork ipnet = IPNetwork.Parse("0.0.0.0", "x.x.x.x"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE10() { + IPNetwork ipnet = IPNetwork.Parse("x.x.x.x", 0); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE11() { + IPNetwork ipnet = IPNetwork.Parse("0.0.0.0", 33); + + } + + [TestMethod] + public void TestParseIPAddressNetmask() { + + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + + string network = "192.168.168.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString1() { + + string ipaddress = "192.168.168.100 255.255.255.0"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString2() { + + string ipaddress = "192.168.168.100/24"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString3() { + + string ipaddress = "0.0.0.0/0"; + + string network = "0.0.0.0"; + string netmask = "0.0.0.0"; + string broadcast = "255.255.255.255"; + string firstUsable = "0.0.0.1"; + string lastUsable = "255.255.255.254"; + byte cidr = 0; + uint usable = 4294967294; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString4() { + + string ipaddress = "0.0.0.0/32"; + + string network = "0.0.0.0"; + string netmask = "255.255.255.255"; + string broadcast = "0.0.0.0"; + string firstUsable = "0.0.0.0"; + string lastUsable = "0.0.0.0"; + byte cidr = 32; + uint usable = 0; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString5() { + + string ipaddress = "255.255.255.255/32"; + + string network = "255.255.255.255"; + string netmask = "255.255.255.255"; + string broadcast = "255.255.255.255"; + string firstUsable = "255.255.255.255"; + string lastUsable = "255.255.255.255"; + byte cidr = 32; + uint usable = 0; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseIPAddressNoNetmask1() { + + string ipaddress = "10.0.0.0"; + + string network = "10.0.0.0"; + string netmask = "255.0.0.0"; + string broadcast = "10.255.255.255"; + string firstUsable = "10.0.0.1"; + string lastUsable = "10.255.255.254"; + byte cidr = 8; + uint usable = 16777214; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + + + [TestMethod] + public void TestParseIPAddressNoNetmask2() { + + string ipaddress = "172.0.0.0"; + + string network = "172.0.0.0"; + string netmask = "255.255.0.0"; + string broadcast = "172.0.255.255"; + string firstUsable = "172.0.0.1"; + string lastUsable = "172.0.255.254"; + byte cidr = 16; + uint usable = 65534; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + [TestMethod] + public void TestParseIPAddressNoNetmask3() { + + string ipaddress = "192.0.0.0"; + + string network = "192.0.0.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.0.0.255"; + string firstUsable = "192.0.0.1"; + string lastUsable = "192.0.0.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNoNetmask4() { + + string ipaddress = "224.0.0.0"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNoNetmask5() { + + string ipaddress = "240.0.0.0"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + } + + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE1() { + string ipaddress = "garbage"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE2() { + string ipaddress = "0.0.0.0 0.0.1.0"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringANE1() { + string ipaddress = null; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + + + #endregion + + #region TryParse + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE2() { + IPNetwork ipnet = null; + IPAddress ip = null; + bool parsed = IPNetwork.TryParse(ip, ip, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE3() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("", 0, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + [TestMethod] + public void TestTryParseIPAddressNetmaskANE4() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse(null, 0, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + [TestMethod] + public void TestTryParseIPAddressNetmaskANE5() { + string n = null; + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse(n, n, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE6() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse(IPAddress.Parse("10.10.10.10"), null, out ipnet); + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE7() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("0.0.0.0", null, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE8() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("x.x.x.x", "x.x.x.x", out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE9() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("0.0.0.0", "x.x.x.x", out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE10() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("x.x.x.x", 0, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE11() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("0.0.0.0", 33, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + + [TestMethod] + public void TestTryParseIPAddressNetmask() { + + IPNetwork ipnetwork = null; + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + + string network = "192.168.168.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString1() { + + IPNetwork ipnetwork = null; + string ipaddress = "192.168.168.100 255.255.255.0"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString2() { + + IPNetwork ipnetwork = null; + string ipaddress = "192.168.168.100/24"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString3() { + + IPNetwork ipnetwork = null; + string ipaddress = "0.0.0.0/0"; + + string network = "0.0.0.0"; + string netmask = "0.0.0.0"; + string broadcast = "255.255.255.255"; + string firstUsable = "0.0.0.1"; + string lastUsable = "255.255.255.254"; + byte cidr = 0; + uint usable = 4294967294; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString4() { + + IPNetwork ipnetwork = null; + string ipaddress = "0.0.0.0/32"; + + string network = "0.0.0.0"; + string netmask = "255.255.255.255"; + string broadcast = "0.0.0.0"; + string firstUsable = "0.0.0.0"; + string lastUsable = "0.0.0.0"; + byte cidr = 32; + uint usable = 0; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString5() { + + IPNetwork ipnetwork = null; + string ipaddress = "255.255.255.255/32"; + + string network = "255.255.255.255"; + string netmask = "255.255.255.255"; + string broadcast = "255.255.255.255"; + string firstUsable = "255.255.255.255"; + string lastUsable = "255.255.255.255"; + byte cidr = 32; + uint usable = 0; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + + [TestMethod] + public void TestTryParseStringAE1() { + string ipaddress = "garbage"; + IPNetwork ipnetwork = null; + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(false, parsed, "parsed"); + } + + [TestMethod] + public void TestTryParseStringAE2() { + string ipaddress = "0.0.0.0 0.0.1.0"; + IPNetwork ipnetwork = null; + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(false, parsed, "parsed"); + } + + [TestMethod] + public void TestTryParseStringANE1() { + string ipaddress = null; + IPNetwork ipnetwork = null; + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(false, parsed, "parsed"); + } + + + + #endregion + + #region ParseStringString + + [TestMethod] + public void TestParseStringString1() { + + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + Assert.AreEqual("192.168.168.0/24", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString2() { + + string ipaddress = null; + string netmask = null; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString3() { + + string ipaddress = "192.168.168.100"; + string netmask = null; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString4() { + + string ipaddress = ""; + string netmask = ""; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString5() { + + string ipaddress = "192.168.168.100"; + string netmask = ""; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + #endregion + + #region ParseIpIp + + [TestMethod] + public void ParseIpIp1() { + + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = IPAddress.Parse(netmask); + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + Assert.AreEqual("192.168.168.0/24", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void ParseIpIp2() { + + IPAddress ip = null; + IPAddress netm = null; + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void ParseIpIp3() { + + string ipaddress = "192.168.168.100"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = null; + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + + } + + #endregion + + #region ToCidr + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestToCidrANE() { + IPNetwork.ToCidr(null); + } + + [TestMethod] + public void TestToCidrAE() { + byte cidr = IPNetwork.ToCidr(IPAddress.IPv6Any); + Assert.AreEqual(0, cidr, "cidr"); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestToCidrAE2() { + IPNetwork.ToCidr(IPAddress.Parse("6.6.6.6")); + } + + + [TestMethod] + public void TestToCidr32() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + byte cidr = 32; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr24() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + byte cidr = 24; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr16() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + byte cidr = 16; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr8() { + + IPAddress mask = IPAddress.Parse("255.0.0.0"); + byte cidr = 8; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr0() { + + IPAddress mask = IPAddress.Parse("0.0.0.0"); + byte cidr = 0; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + #endregion + + #region TryToCidr + + [TestMethod] + public void TestTryToCidrANE() { + byte? cidr = null; + bool parsed = IPNetwork.TryToCidr(null, out cidr); + Assert.AreEqual(false, parsed, "parsed"); + } + + [TestMethod] + public void TestTryToCidrAE() { + byte? cidr = null; + bool parsed = IPNetwork.TryToCidr(IPAddress.IPv6Any, out cidr); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual((byte)0, cidr, "cidr"); + } + + + [TestMethod] + public void TestTryToCidrAE2() { + byte? cidr = null; + bool parsed = IPNetwork.TryToCidr(IPAddress.Parse("6.6.6.6"), out cidr); + Assert.AreEqual(false, parsed, "parsed"); + } + + + [TestMethod] + public void TestTryToCidr32() { + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.255.255.255"); + byte result = 32; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr24() { + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.255.255.0"); + byte result = 24; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + [TestMethod] + public void TestTryToCidr16() { + + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.255.0.0"); + byte result = 16; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + [TestMethod] + public void TestTryToCidr8() { + + + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.0.0.0"); + byte result = 8; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + [TestMethod] + public void TestTryToCidr0() { + + byte? cidr = null; + IPAddress mask = IPAddress.Parse("0.0.0.0"); + byte result = 0; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + + #endregion + + #region ToBigInteger + + [TestMethod] + public void TestToBigInteger32() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + uint uintMask = 0xffffffff; + BigInteger result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger24() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + uint uintMask = 0xffffff00; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger16() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + uint uintMask = 0xffff0000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger8() { + + IPAddress mask = IPAddress.Parse("255.0.0.0"); + uint uintMask = 0xff000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger0() { + + IPAddress mask = IPAddress.Parse("0.0.0.0"); + uint uintMask = 0x00000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestToBigIntegerANE() { + BigInteger? result = IPNetwork.ToBigInteger(null); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestToBigIntegerANE3() { + IPAddress ip = null; + BigInteger? result = IPNetwork.ToBigInteger(ip); + } + [TestMethod] + public void TestToBigIntegerANE2() { + BigInteger? result = IPNetwork.ToBigInteger(IPAddress.IPv6Any); + uint expected = 0; + Assert.AreEqual(expected, result, "result"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestToBigIntegerByte() { + BigInteger result = IPNetwork.ToUint(33, Sockets.AddressFamily.InterNetwork); + } + + [TestMethod] + public void TestToBigIntegerByte2() { + BigInteger result = IPNetwork.ToUint(32, Sockets.AddressFamily.InterNetwork); + uint expected = 4294967295; + Assert.AreEqual(expected, result, "result"); + + } + + + [TestMethod] + public void TestToBigIntegerByte3() { + BigInteger result = IPNetwork.ToUint(0, Sockets.AddressFamily.InterNetwork); + uint expected = 0; + Assert.AreEqual(expected, result, "result"); + + } + + + + #endregion + + #region TryToBigInteger + + [TestMethod] + public void TestTryToBigInteger32() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + uint uintMask = 0xffffffff; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger24() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + uint uintMask = 0xffffff00; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger16() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + uint uintMask = 0xffff0000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger8() { + + IPAddress mask = IPAddress.Parse("255.0.0.0"); + uint uintMask = 0xff000000; + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger0() { + + IPAddress mask = IPAddress.Parse("0.0.0.0"); + uint uintMask = 0x00000000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigIntegerANE() { + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(null, out result); + + Assert.AreEqual(null, result, "uint"); + Assert.AreEqual(false, parsed, "parsed"); + + } + [TestMethod] + public void TestTryToBigIntegerANE3() { + IPAddress ip = null; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(ip, out result); + + Assert.AreEqual(null, result, "uint"); + Assert.AreEqual(false, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigIntegerANE2() { + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(IPAddress.IPv6Any, out result); + + Assert.AreEqual(0, result, "result"); + Assert.AreEqual(true, parsed, "parsed"); + } + + + + #endregion + + #region TryToNetmask + [TestMethod] + public void TryToNetmask1() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(0, Sockets.AddressFamily.InterNetwork, out result); + IPAddress expected = IPAddress.Parse("0.0.0.0"); + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(true, parsed, "parsed"); + + } + + [TestMethod] + public void TryToNetmask2() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(33, Sockets.AddressFamily.InterNetwork, out result); + IPAddress expected = null; + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(false, parsed, "parsed"); + + } + + #endregion + + #region ToNetmask + + [TestMethod] + public void ToNetmask32() { + + byte cidr = 32; + string netmask = "255.255.255.255"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask31() { + + byte cidr = 31; + string netmask = "255.255.255.254"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask30() { + + byte cidr = 30; + string netmask = "255.255.255.252"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask29() { + + byte cidr = 29; + string netmask = "255.255.255.248"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask1() { + + byte cidr = 1; + string netmask = "128.0.0.0"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + + [TestMethod] + public void ToNetmask0() { + + byte cidr = 0; + string netmask = "0.0.0.0"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void ToNetmaskOORE1() { + byte cidr = 33; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + } + + #endregion + + #region ValidNetmask + + [TestMethod] + public void TestValidNetmask0() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask1() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask2() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + public void TestValidNetmaskEAE1() { + + IPAddress mask = IPAddress.Parse("0.255.0.0"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestValidNetmaskEAE2() { + + IPAddress mask = null; + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + public void TestValidNetmaskEAE3() { + + IPAddress mask = IPAddress.Parse("255.255.0.1"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + #endregion + + #region BitsSet + + [TestMethod] + public void TestBitsSet32() { + + IPAddress ip = IPAddress.Parse("255.255.255.255"); + uint bits = 32; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet24() { + + IPAddress ip = IPAddress.Parse("255.255.255.0"); + uint bits = 24; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet16() { + + IPAddress ip = IPAddress.Parse("255.255.0.0"); + uint bits = 16; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet4() { + + IPAddress ip = IPAddress.Parse("128.128.128.128"); + uint bits = 4; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + + #endregion + + #region Contains + + [TestMethod] + public void TestContains1() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/24"); + IPAddress ipaddress = IPAddress.Parse("192.168.0.100"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains2() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/24"); + IPAddress ipaddress = IPAddress.Parse("10.10.10.10"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains3() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.0.1/24"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains4() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/16"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.1/24"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains5() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/16"); + IPNetwork ipnetwork2 = IPNetwork.Parse("10.10.10.0/24"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + + [TestMethod] + public void TestContains6() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.0.0/16"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains7() + { + + IPNetwork ipnetwork = null; + IPNetwork ipnetwork2 = null; + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains8() + { + + IPNetwork ipnetwork = IPNetwork.Parse("0.0.0.0/0"); + IPNetwork ipnetwork2 = null; + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains9() + { + + IPNetwork ipnetwork = null; + IPAddress ipaddress = null; + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains10() + { + + IPNetwork ipnetwork = IPNetwork.Parse("0.0.0.0/0"); + IPAddress ipaddress = null; + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + + } + + #endregion + + #region Overlap + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestOverlap1() + { + IPNetwork network1 = null; + IPNetwork network2 = null; + IPNetwork.Overlap(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestOverlap2() + { + IPNetwork network1 = IPNetwork.Parse("10.0.0.0/0"); + IPNetwork network2 = null; + IPNetwork.Overlap(network1, network2); + } + + [TestMethod] + public void TestOverlap3() + { + IPNetwork network1 = IPNetwork.Parse("10.0.0.0/0"); + IPNetwork network2 = IPNetwork.Parse("10.0.0.0/0"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap4() + { + IPNetwork network1 = IPNetwork.Parse("10.10.0.0/16"); + IPNetwork network2 = IPNetwork.Parse("10.10.1.0/24"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap5() + { + IPNetwork network1 = IPNetwork.Parse("10.10.0.0/24"); + IPNetwork network2 = IPNetwork.Parse("10.10.1.0/24"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = false; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap6() + { + IPNetwork network1 = IPNetwork.Parse("10.10.1.0/24"); + IPNetwork network2 = IPNetwork.Parse("10.10.0.0/16"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + #endregion + + #region Examples + + public void Example1() + { + IPNetwork ipnetwork = IPNetwork.Parse("192.168.168.100/24"); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + public void Example2() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.0/24"); + IPAddress ipaddress = IPAddress.Parse("192.168.0.100"); + IPAddress ipaddress2 = IPAddress.Parse("192.168.1.100"); + + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.0.128/25"); + IPNetwork ipnetwork3 = IPNetwork.Parse("192.168.1.1/24"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + bool contains3 = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool contains4 = IPNetwork.Contains(ipnetwork, ipnetwork3); + + bool overlap1 = IPNetwork.Overlap(ipnetwork, ipnetwork2); + bool overlap2 = IPNetwork.Overlap(ipnetwork, ipnetwork3); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork2, contains3); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork3, contains4); + + + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork2, overlap1); + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork3, overlap2); + + + } + + public void Example2b() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("10.1.0.0/16"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.0/24"); + + IPAddress ipaddress1 = IPAddress.Parse("192.168.1.1"); + IPAddress ipaddress2 = IPAddress.Parse("192.168.2.100"); + IPAddress ipaddress3 = IPAddress.Parse("10.1.2.3"); + IPAddress ipaddress4 = IPAddress.Parse("10.4.5.6"); + + + bool contains1 = IPNetwork.Contains(ipnetwork2, ipaddress1); + bool contains2 = IPNetwork.Contains(ipnetwork2, ipaddress2); + bool contains3 = IPNetwork.Contains(ipnetwork1, ipaddress3); + bool contains4 = IPNetwork.Contains(ipnetwork1, ipaddress4); + + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork1, ipaddress1, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork1, ipaddress2, contains2); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork2, ipaddress3, contains3); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork2, ipaddress4, contains4); + + + } + + public void Example3() + { + + IPNetwork iana_a_block = IPNetwork.IANA_ABLK_RESERVED1; + IPNetwork iana_b_block = IPNetwork.IANA_BBLK_RESERVED1; + IPNetwork iana_c_block = IPNetwork.IANA_CBLK_RESERVED1; + + Console.WriteLine("IANA_ABLK_RESERVED1 is {0}", iana_a_block); + Console.WriteLine("IANA_BBLK_RESERVED1 is {0}", iana_b_block); + Console.WriteLine("IANA_CBLK_RESERVED1 is {0}", iana_c_block); + + } + + + public void Example4() + { + IPNetwork wholeInternet = IPNetwork.Parse("0.0.0.0/0"); + byte newCidr = 2; + IPNetworkCollection subneted = IPNetwork.Subnet(wholeInternet, newCidr); + + Console.WriteLine("{0} was subnetted into {1} subnets", wholeInternet, subneted.Count); + Console.WriteLine("First: {0}", subneted[0]); + Console.WriteLine("Last : {0}", subneted[subneted.Count - 1]); + Console.WriteLine("All :"); + + foreach (IPNetwork ipnetwork in subneted) + { + Console.WriteLine("{0}", ipnetwork); + } + } + + public void Example5() + { + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.0/24"); + IPNetwork[] ipnetwork3 = IPNetwork.Supernet(new[]{ipnetwork1, ipnetwork2}); + + Console.WriteLine("{0} + {1} = {2}", ipnetwork1, ipnetwork2, ipnetwork3[0]); + + } + + + + public void Example7() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.168.100/24"); + + IPAddress ipaddress = IPAddress.Parse("192.168.168.200"); + IPAddress ipaddress2 = IPAddress.Parse("192.168.0.200"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + + } + public void Example9() { + + IPNetwork network = IPNetwork.Parse("192.168.0.1"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.254"); + + IPNetwork ipnetwork = IPNetwork.Supernet(network, network2); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + + public void Example10() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/25"); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + #endregion + + #region IANA blocks + [TestMethod] + public void TestIANA1() { + + IPAddress ipaddress = IPAddress.Parse("192.168.66.66"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA2() { + + IPAddress ipaddress = IPAddress.Parse("10.0.0.0"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA3() { + + IPAddress ipaddress = IPAddress.Parse("172.17.10.10"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA4() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.66.66/24"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA5() { + + IPNetwork ipnetwork = IPNetwork.Parse("10.10.10/18"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA6() { + + IPNetwork ipnetwork = IPNetwork.Parse("172.31.10.10/24"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestIANA7() { + + IPAddress ipaddress = null; + IPNetwork.IsIANAReserved(ipaddress); + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestIANA8() { + + IPNetwork ipnetwork = null; + IPNetwork.IsIANAReserved(ipnetwork); + + + } + + + [TestMethod] + public void TestIANA9() { + + IPAddress ipaddress = IPAddress.Parse("1.2.3.4"); + bool expected = false; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA10() { + + IPNetwork ipnetwork = IPNetwork.Parse("172.16.0.0/8"); + bool expected = false; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + + [TestMethod] + public void TestIANA11() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/8"); + bool expected = false; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + #endregion + + #region ToString + + + [TestMethod] + public void TestToString() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/8"); + string expected = "192.0.0.0/8"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString1() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/9"); + string expected = "192.128.0.0/9"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString2() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/10"); + string expected = "192.128.0.0/10"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString3() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/11"); + string expected = "192.160.0.0/11"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString4() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/12"); + string expected = "192.160.0.0/12"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString5() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/13"); + string expected = "192.168.0.0/13"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString6() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/14"); + string expected = "192.168.0.0/14"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + [TestMethod] + public void TestToString7() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/15"); + string expected = "192.168.0.0/15"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString8() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/16"); + string expected = "192.168.0.0/16"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + #endregion + + #region Subnet + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestSubnet1() { + + IPNetwork ipnetwork = null; + byte cidr = 9; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet3() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 55; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSubnet4() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 1; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + public void TestSubnet5() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 9; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("10.0.0.0/9", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("10.128.0.0/9", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestSubnet6() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/20", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.16.0/20", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("192.168.32.0/20", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("192.168.48.0/20", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("192.168.64.0/20", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("192.168.80.0/20", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("192.168.96.0/20", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("192.168.112.0/20", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("192.168.128.0/20", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("192.168.144.0/20", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("192.168.160.0/20", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("192.168.176.0/20", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("192.168.192.0/20", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("192.168.208.0/20", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("192.168.224.0/20", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("192.168.240.0/20", subnets[15].ToString(), "subnet16"); + + } + + + [TestMethod] + public void TestSubnet7() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 24; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/24", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.255.0/24", subnets[255].ToString(), "subnet16"); + + } + + + [TestMethod] + public void TestSubnet8() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 24; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/24", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.255.0/24", subnets[255].ToString(), "subnet256"); + + } + + [TestMethod] + public void TestSubnet9() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.0/24"); + byte cidr = 32; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/32", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.0.255/32", subnets[255].ToString(), "subnet256"); + + } + + + [TestMethod] + public void TestSubnet10() + { + IPNetwork ipnetwork = IPNetwork.Parse("0.0.0.0/0"); + byte cidr = 32; + + // Here I spawm a OOM dragon ! beware of the beast ! + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(4294967296, subnets.Count, "count"); + Assert.AreEqual("0.0.0.0/32", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("255.255.255.255/32", subnets[4294967295].ToString(), "subnet256"); + + } + + + [TestMethod] + public void TestSubnet12() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + int i = -1; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + foreach (IPNetwork ipn in subnets) { + i++; + Assert.AreEqual(subnets[i], ipn, "subnet"); + } + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet13() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + IPNetwork error = subnets[1000]; + + } + + #endregion + + #region TrySubnet + + + [TestMethod] + public void TestTrySubnet1() { + + IPNetwork ipnetwork = null; + byte cidr = 9; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + + } + + [TestMethod] + public void TestTrySubnet3() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 55; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + } + + + [TestMethod] + public void TestTrySubnet4() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 1; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + + } + + + [TestMethod] + public void TestTrySubnet5() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 9; + + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("10.0.0.0/9", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("10.128.0.0/9", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestTrySubnet6() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/20", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.16.0/20", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("192.168.32.0/20", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("192.168.48.0/20", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("192.168.64.0/20", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("192.168.80.0/20", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("192.168.96.0/20", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("192.168.112.0/20", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("192.168.128.0/20", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("192.168.144.0/20", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("192.168.160.0/20", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("192.168.176.0/20", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("192.168.192.0/20", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("192.168.208.0/20", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("192.168.224.0/20", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("192.168.240.0/20", subnets[15].ToString(), "subnet16"); + + } + + + + #endregion + + #region Supernet + + [TestMethod] + public void TestSupernet1() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork expected = IPNetwork.Parse("192.168.0.0/23"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + Assert.AreEqual(expected, supernet, "supernet"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestSupernet2() { + + IPNetwork network1 = null; + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestSupernet3() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = null; + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSupernet4() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/25"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSupernet5() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.5.1/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + public void TestSupernet6() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork expected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + Assert.AreEqual(expected, supernet, "supernet"); + + } + + [TestMethod] + public void TestSupernet7() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork expected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + Assert.AreEqual(expected, supernet, "supernet"); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSupernet8() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + + } + + + [TestMethod] + public void TestSupernet9() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("200.16.0.0/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("200.16.1.0/24"); + IPNetwork ipnetwork3 = IPNetwork.Parse("200.16.2.0/24"); + IPNetwork ipnetwork4 = IPNetwork.Parse("200.16.3.0/24"); + + IPNetwork result = IPNetwork.Supernet(new[] { ipnetwork1, ipnetwork2, ipnetwork3, ipnetwork4 })[0]; + IPNetwork expected = IPNetwork.Parse("200.16.0.0/22"); + + Assert.AreEqual(expected, result, "supernet"); + + } + + #endregion + + #region TrySupernet + + + [TestMethod] + public void TestTrySupernet1() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork supernetExpected = IPNetwork.Parse("192.168.0.0/23"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet2() { + + IPNetwork network1 = null; + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet3() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = null; + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet4() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/25"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet5() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.5.1/24"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet6() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork supernetExpected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet7() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork supernetExpected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet8() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet9() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork[] network3 = new [] { network1, network2 }; + IPNetwork[] supernetExpected = new [] { network1, network2 }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(supernetExpected[1], supernet[1], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet10() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork[] network3 = new[] { network1, network2 }; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("192.168.0.0/23") }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet11() { + + IPNetwork[] network3 = null; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("192.168.0.0/23") }; + IPNetwork[] supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(null, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + #endregion + + #region SupernetArray + + [TestMethod] + public void TestTrySupernetArray() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.0/24"); + IPNetwork ipnetwork3 = IPNetwork.Parse("192.168.2.0/24"); + IPNetwork ipnetwork4 = IPNetwork.Parse("192.168.3.0/24"); + + IPNetwork[] ipnetworks = { ipnetwork1, ipnetwork2, ipnetwork3, ipnetwork4 }; + IPNetwork[] expected = { IPNetwork.Parse("192.168.0.0/22") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], expected[0], "suppernet"); + + } + + [TestMethod] + public void TestTrySupernetArray1() + { + + + IPNetwork[] ipnetworks = { }; + IPNetwork[] expected = { }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestTrySupernetArray2() + { + + + IPNetwork[] ipnetworks = null; + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + } + + + [TestMethod] + public void TestTrySupernetArray3() + { + + IPNetwork ipnetwork1 = null; + IPNetwork ipnetwork2 = null; + IPNetwork ipnetwork3 = null; + IPNetwork ipnetwork4 = null; + + IPNetwork[] ipnetworks = { ipnetwork1, ipnetwork2, ipnetwork3, ipnetwork4 }; + IPNetwork[] expected = { }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + + } + + [TestMethod] + public void TestTrySupernetArray4() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/24"); + IPNetworkCollection subnetted = IPNetwork.Subnet(ipnetwork1, 32); + IPNetwork[] ipnetworks = subnetted.ToArray(); + Assert.AreEqual(256, ipnetworks.Length, "subnet"); + + IPNetwork[] expected = { IPNetwork.Parse("192.168.0.0/24") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], ipnetwork1, "suppernet"); + } + + + [TestMethod] + public void TestTrySupernetArray5() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/16"); + IPNetworkCollection subnetted = IPNetwork.Subnet(ipnetwork1, 32); + IPNetwork[] ipnetworks = subnetted.ToArray(); + Assert.AreEqual(65536, ipnetworks.Length, "subnet"); + + IPNetwork[] expected = { IPNetwork.Parse("192.168.0.0/16") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], ipnetwork1, "suppernet"); + } + + public void TestTrySupernetArray6() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/8"); + IPNetworkCollection subnetted = IPNetwork.Subnet(ipnetwork1, 32); + IPNetwork[] ipnetworks = subnetted.ToArray(); + Assert.AreEqual(16777216, ipnetworks.Length, "subnet"); + + IPNetwork[] expected = { IPNetwork.Parse("192.0.0.0/8") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], ipnetwork1, "suppernet"); + } + + [TestMethod] + public void TestTrySupernetArray7() + { + + IPNetwork[] ipnetworks = { + IPNetwork.Parse("10.0.2.2/24"), + IPNetwork.Parse("192.168.0.0/24"), + IPNetwork.Parse("192.168.1.0/24"), + IPNetwork.Parse("192.168.2.0/24"), + IPNetwork.Parse("10.0.1.1/24"), + IPNetwork.Parse("192.168.3.0/24") + }; + + IPNetwork[] expected = { + IPNetwork.Parse("10.0.1.0/24"), + IPNetwork.Parse("10.0.2.0/24"), + IPNetwork.Parse("192.168.0/22") + }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], result[0], "suppernet"); + Assert.AreEqual(expected[1], result[1], "suppernet1"); + Assert.AreEqual(expected[2], result[2], "suppernet2"); + } + + [TestMethod] + public void TestTrySupernetArray8() + { + + IPNetwork[] ipnetworks = { + IPNetwork.Parse("10.0.2.2/24"), + IPNetwork.Parse("192.168.0.0/24"), + IPNetwork.Parse("192.168.1.0/24"), + IPNetwork.Parse("192.168.2.0/24"), + IPNetwork.Parse("10.0.1.1/24"), + IPNetwork.Parse("192.168.3.0/24"), + IPNetwork.Parse("10.6.6.6/8") + + }; + + IPNetwork[] expected = { + IPNetwork.Parse("10.0.0.0/8"), + IPNetwork.Parse("192.168.0/22") + }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], result[0], "suppernet"); + Assert.AreEqual(expected[1], result[1], "suppernet1"); + } + + + [TestMethod] + public void TestTrySupernetArray9() + { + + IPNetwork[] ipnetworks = { + IPNetwork.Parse("10.0.2.2/24"), + IPNetwork.Parse("192.168.0.0/24"), + IPNetwork.Parse("192.168.1.0/24"), + IPNetwork.Parse("192.168.2.0/24"), + IPNetwork.Parse("10.0.1.1/24"), + IPNetwork.Parse("192.168.3.0/24"), + IPNetwork.Parse("10.6.6.6/8"), + IPNetwork.Parse("11.6.6.6/8"), + IPNetwork.Parse("12.6.6.6/8"), + + }; + + IPNetwork[] expected = { + IPNetwork.Parse("10.0.0.0/7"), + IPNetwork.Parse("12.0.0.0/8"), + IPNetwork.Parse("192.168.0/22") + }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], result[0], "suppernet"); + Assert.AreEqual(expected[1], result[1], "suppernet1"); + Assert.AreEqual(expected[2], result[2], "suppernet2"); + } + + + #endregion + + #region Equals + + [TestMethod] + public void TestEquals1() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/24"); + bool result = network1.Equals(network2); + bool expected = true; + + Assert.AreEqual(expected, result, "equals"); + + } + + [TestMethod] + public void TestEquals2() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = null; + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + [TestMethod] + public void TestEquals3() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + object network2 = ""; + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + [TestMethod] + public void TestEquals4() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/25"); + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + + [TestMethod] + public void TestEquals5() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + #endregion + + #region WideSubnet + + [TestMethod] + public void TestWideSubnet1() { + + string start = "192.168.168.0"; + string end = "192.168.168.255"; + IPNetwork expected = IPNetwork.Parse("192.168.168.0/24"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestWideSubnet2() { + + string start = null; + string end = "192.168.168.255"; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestWideSubnet3() { + + string start = "192.168.168.255"; + string end = null; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + + } + + [TestMethod] + public void TestWideSubnet4() { + + string start = "192.168.168.255"; + string end = "192.168.168.0"; + + + IPNetwork expected = IPNetwork.Parse("192.168.168.0/24"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + } + + + [TestMethod] + public void TestWideSubnet7() { + + string start = "0.0.0.0"; + string end = "0.255.255.255"; + + IPNetwork expected = IPNetwork.Parse("0.0.0.0/8"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + } + + + + [TestMethod] + public void TestWideSubnet8() { + + string start = "1.2.3.4"; + string end = "5.6.7.8"; + + IPNetwork expected = IPNetwork.Parse("0.0.0.0/5"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + } + + + [TestMethod] + public void TestWideSubnet9() + { + + string start = "200.16.0.0/24"; + string end = "200.16.3.0/24"; + var firt = IPNetwork.Parse(start).FirstUsable.ToString(); + var last = IPNetwork.Parse(end).LastUsable.ToString(); + + IPNetwork expected = IPNetwork.Parse("200.16.0.0/22"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(firt, last); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + + + + } + + + [TestMethod] + public void TestWideSubnet10() + { + + string start = "200.16.0.0"; + string end = "200.16.3.255"; + + IPNetwork expected = IPNetwork.Parse("200.16.0.0/22"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestWideSubnetInvalid1() { + + string start = "invalid"; + string end = "5.6.7.8"; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestWideSubnetInvalid2() { + + string start = "1.2.3.4"; + string end = "invalid"; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + } + + #endregion + + #region TryGuessCidr + + [TestMethod] + public void TestTryGuessCidrNull() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr(null, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(0, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrA() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("10.0.0.0", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(8, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrB() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("172.0.0.0", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(16, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrC() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("192.0.0.0", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(24, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrD() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("224.0.0.0", out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + } + [TestMethod] + public void TestTryGuessCidrE() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("240.0.0.0", out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + } + + #endregion + + #region GetHashCode + + [TestMethod] + public void TestGetHashCode1() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("0.0.1.1/0"); + IPNetwork ipnetwork2 = IPNetwork.Parse("0.0.1.1/0"); + int hashCode1 = ipnetwork1.GetHashCode(); + int hashCode2 = ipnetwork2.GetHashCode(); + Assert.AreEqual(hashCode1, hashCode2, "hashcode"); + + } + + [TestMethod] + public void TestGetHashCode2() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("0.0.0.0/1"); + IPNetwork ipnetwork2 = IPNetwork.Parse("0.0.0.0/1"); + int hashCode1 = ipnetwork1.GetHashCode(); + int hashCode2 = ipnetwork2.GetHashCode(); + Assert.AreEqual(hashCode1, hashCode2, "hashcode"); + + } + [TestMethod] + public void TestGetHashCode3() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("0.0.0.0/32"); + IPNetwork ipnetwork2 = IPNetwork.Parse("0.0.0.0/32"); + int hashCode1 = ipnetwork1.GetHashCode(); + int hashCode2 = ipnetwork2.GetHashCode(); + Assert.AreEqual(hashCode1, hashCode2, "hashcode"); + + } + + #endregion + + #region Print + + [TestMethod] + public void Print() { + IPNetwork ipn = IPNetwork.Parse("0.0.0.0/0"); + string print = IPNetwork.Print(ipn).Replace("\r", ""); + string expected = @"IPNetwork : 0.0.0.0/0 +Network : 0.0.0.0 +Netmask : 0.0.0.0 +Cidr : 0 +Broadcast : 255.255.255.255 +FirstUsable : 0.0.0.1 +LastUsable : 255.255.255.254 +Usable : 4294967294 +".Replace("\r", ""); + + Assert.AreEqual(expected, print, "Print"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void PrintNull() { + IPNetwork ipn = null; + string print = IPNetwork.Print(ipn); + } + + #endregion + + #region Sort + + [TestMethod] + public void TestSort1() { + string[] ips = new[] { "1.1.1.1", "255.255.255.255", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach(string ip in ips) { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) { + ipns.Add(ipn); + } + } + + ipns.Sort(); + Assert.AreEqual("0.0.0.0/32", ipns[0].ToString(), "0"); + Assert.AreEqual("1.1.1.1/32", ipns[1].ToString(), "1"); + Assert.AreEqual("2.2.2.2/32", ipns[2].ToString(), "2"); + Assert.AreEqual("255.255.255.255/32", ipns[3].ToString(), "3"); + } + + [TestMethod] + public void TestSort2() { + string[] ips = new[] { "0.0.0.100/32", "0.0.0.0/24" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, out ipn)) { + ipns.Add(ipn); + } + } + + ipns.Sort(); + Assert.AreEqual("0.0.0.0/24", ipns[0].ToString(), "0"); + Assert.AreEqual("0.0.0.100/32", ipns[1].ToString(), "1"); + } + + #endregion + + #region TryWideSubnet + + [TestMethod] + public void TryWideSubnet1() { + string[] ips = new[] { "1.1.1.1", "255.255.255.255", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(true, wide, "wide"); + Assert.AreEqual("0.0.0.0/0", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + public void TryWideSubnet2() { + string[] ips = new[] { "1.1.1.1", "10.0.0.0", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(true, wide, "wide"); + Assert.AreEqual("0.0.0.0/4", ipnetwork.ToString(), "ipnetwork"); + + } + + + [TestMethod] + public void TryWideSubnet3() { + string[] ips = new[] { "a", "b", "c", "d" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(false, wide, "wide"); + + } + + [TestMethod] + public void TryWideSubnet4() { + string[] ips = new[] { "a", "b", "1.1.1.1", "d" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(true, wide, "wide"); + Assert.AreEqual("1.1.1.1/32", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + public void TryWideSubnetNull() { + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(null, out ipnetwork); + Assert.AreEqual(false, wide, "wide"); + + } + + #endregion + + #region WideSubnet + + [TestMethod] + public void WideSubnet1() { + string[] ips = new[] { "1.1.1.1", "255.255.255.255", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = IPNetwork.WideSubnet(ipns.ToArray()); + Assert.AreEqual("0.0.0.0/0", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + public void WideSubnet2() { + string[] ips = new[] { "1.1.1.1", "10.0.0.0", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = IPNetwork.WideSubnet(ipns.ToArray()); + Assert.AreEqual("0.0.0.0/4", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void WideSubnetNull() { + + IPNetwork ipnetwork = IPNetwork.WideSubnet(null); + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void WideSubnetNull2() { + + string[] ips = new[] { "a", "b", "e", "d" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = IPNetwork.WideSubnet(ipns.ToArray()); + + + } + + #endregion + + /** + * + #region TrySubstractNetwork + + + [TestMethod] + public void TrySubstractNetwork1() { + string[] ips = new[] { "178.82.0.0/16" }; + string substract = "178.82.131.209/32"; + + List ipns = new List(); + Array.ForEach(ips, new Action( + delegate(string ip) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, out ipn)) { + ipns.Add(ipn); + } + } + )); + + var nsubstract = IPNetwork.Parse(substract); + + IEnumerable result; + bool substracted = IPNetwork.TrySubstractNetwork(ipns.ToArray(), nsubstract, out result); + Assert.AreEqual(true, substracted, "substracted"); + + } + + [TestMethod] + public void TrySubstractNetwork2() { + string[] ips = new[] { "0.0.0.0/0" }; + string substract = "1.1.1.1/32"; + + List ipns = new List(); + Array.ForEach(ips, new Action( + delegate(string ip) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, out ipn)) { + ipns.Add(ipn); + } + } + )); + + var nsubstract = IPNetwork.Parse(substract); + + IEnumerable result; + bool substracted = IPNetwork.TrySubstractNetwork(ipns.ToArray(), nsubstract, out result); + Assert.AreEqual(true, substracted, "substracted"); + + } + + + + #endregion + **/ + + #region Count + + [TestMethod] + public void Total32() { + var network = IPNetwork.Parse("0.0.0.0/32"); + var total = 1; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total31() { + var network = IPNetwork.Parse("0.0.0.0/31"); + var total = 2; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total30() { + var network = IPNetwork.Parse("0.0.0.0/30"); + var total = 4; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total24() { + var network = IPNetwork.Parse("0.0.0.0/24"); + var total = 256; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total16() { + var network = IPNetwork.Parse("0.0.0.0/16"); + var total = 65536; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total8() { + var network = IPNetwork.Parse("0.0.0.0/8"); + var total = 16777216; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total0() { + var network = IPNetwork.Parse("0.0.0.0/0"); + var total = 4294967296; + Assert.AreEqual(total, network.Total, "Total"); + } + + #endregion + + #region Usable + + [TestMethod] + public void Usable32() { + var network = IPNetwork.Parse("0.0.0.0/32"); + uint usable = 0; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable31() { + var network = IPNetwork.Parse("0.0.0.0/31"); + uint usable = 0; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable30() { + var network = IPNetwork.Parse("0.0.0.0/30"); + uint usable = 2; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable24() { + var network = IPNetwork.Parse("0.0.0.0/24"); + uint usable = 254; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable16() { + var network = IPNetwork.Parse("0.0.0.0/16"); + uint usable = 65534; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable8() { + var network = IPNetwork.Parse("0.0.0.0/8"); + uint usable = 16777214; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable0() { + var network = IPNetwork.Parse("0.0.0.0/0"); + uint usable = 4294967294; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + #endregion + + #region TryParseCidr + + [TestMethod] + public void TryParseCidr1() { + + string sidr = "0"; + byte? cidr; + byte? result = 0; + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetwork, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr2() { + + string sidr = "sadsd"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetwork, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr3() { + + string sidr = "33"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetwork, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + #endregion + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource subnets of type System.Net.IPNetworkCollection in method "Void IPNetworkUnitTest.TestSubnet13()". + +### Severity: +ERROR + +### Procedure: +Void IPNetworkUnitTest.TestSubnet13() + +### File: +src/System.Net.IPNetwork.TestProject.Source/IPNetworkUnitTest.cs + +### Key: +IPNetworkUnitTest.cs|TestSubnet13|DOTNET_RESOURCE_LEAK + +### Hash: +36c8925f26fb69072e1944e8acea6934 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1616/instruction.md b/inferredbugs-1616/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7764d1c57dbe8873684c0d25f1c03516e6118648 --- /dev/null +++ b/inferredbugs-1616/instruction.md @@ -0,0 +1,2546 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ipnetwork +**Bug ID:** 16 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Numerics; + +namespace System.Net.TestProject +{ + [TestClass] + public class IPNetworkV6UnitTest { + + #region ParseIP + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE8() { + IPNetwork ipnet = IPNetwork.Parse("xxxx::", "xxxx::"); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE9() { + IPNetwork ipnet = IPNetwork.Parse("::", "xxxx::"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE10() { + IPNetwork ipnet = IPNetwork.Parse("xxxx::", 0); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE11() { + IPNetwork ipnet = IPNetwork.Parse("::", 129); + + } + + [TestMethod] + public void TestParsev6_128() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + //string broadcast = "2001:db8::"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::"; + byte cidr = 128; + BigInteger usable = 1; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_127() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"; + //string broadcast = "2001:db8::1"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::1"; + byte cidr = 127; + BigInteger usable = 2; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_126() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"; + //string broadcast = "2001:db8::3"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::3"; + byte cidr = 126; + BigInteger usable = 4; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_125() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"; + //string broadcast = "2001:db8::7"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::7"; + byte cidr = 125; + BigInteger usable = 8; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_124() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + //string broadcast = "2001:db8::f"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::f"; + byte cidr = 124; + BigInteger usable = 16; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParsev6_123() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:0db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"; + //string broadcast = "2001:db8::1f"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::1f"; + byte cidr = 123; + BigInteger usable = 32; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + + [TestMethod] + public void TestParsev6_112() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"; + + string network = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"; + //string broadcast = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 112; + uint usable = 65536; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_64() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:1234:1234:1234:1234"; + string netmask = "ffff:ffff:ffff:ffff:0000:0000:0000:0000"; + + string network = "ffff:ffff:ffff:ffff::"; + string netmask2 = "ffff:ffff:ffff:ffff::"; + //string broadcast = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 64; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)) ; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_16() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:0000:0000:0000:0000:0000:0000:0000"; + + string network = "ffff::"; + string netmask2 = "ffff::"; + //string broadcast = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 16; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)) ; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + + [TestMethod] + public void TestParsev6_EDGE() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + + string network = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 128; + uint usable = 1; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + #endregion + + #region ParseString + + [TestMethod] + public void TestParseString1() { + + string ipaddress = "2001:0db8:: ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + + string network = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::f"; + byte cidr = 124; + uint usable = 16; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParseString3() { + + string ipaddress = ":: ::"; + + string network = "::"; + string netmask = "::"; + string firstUsable = "::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 0; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)); + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParseString4() { + + string ipaddress = "::/0"; + + string network = "::"; + string netmask = "::"; + string firstUsable = "::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 0; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)); + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString5() { + + string ipaddress = "::/32"; + + string network = "::"; + string netmask = "ffff:ffff::"; + string firstUsable = "::"; + string lastUsable = "::ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 32; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)) ; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString6() + { + + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128"; + + string network = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 128; + uint usable = 1; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString7_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFF:123::/60"; + + string network = "2fff:ffff:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:ffff:123::"; + string lastUsable = "2fff:ffff:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParseString8_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFE:123::/60"; + + string network = "2fff:fffe:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:fffe:123::"; + string lastUsable = "2fff:fffe:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + + } + + [TestMethod] + public void TestParseString9_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFC:123::/60"; + + string network = "2fff:fffc:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:fffc:123::"; + string lastUsable = "2fff:fffc:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString10_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFA:123::/60"; + + string network = "2fff:fffa:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:fffa:123::"; + string lastUsable = "2fff:fffa:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString11_Uppercase_ipv6_must_parse() + { + + string ipaddress = "FFFF:FFF1:123::/60"; + + string network = "ffff:fff1:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "ffff:fff1:123::"; + string lastUsable = "ffff:fff1:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseIPAddressNoNetmask1() { + + string ipaddress = "2001:0db8::"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + + string network = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff::"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::ffff:ffff:ffff:ffff"; + byte cidr = 64; + var usable = BigInteger.Pow(2, 64); + + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + [TestMethod] + public void TestParseIPAddressNoNetmask4() { + + string ipaddress = "::"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + + + string network = "::"; + string netmask = "ffff:ffff:ffff:ffff::"; + string firstUsable = "::"; + string lastUsable = "::ffff:ffff:ffff:ffff"; + byte cidr = 64; + var usable = BigInteger.Pow(2, 64); + + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + [TestMethod] + public void TestParseIPAddressNoNetmask5() { + + string ipaddress = "2001:0db8::1"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + string network = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff::"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::ffff:ffff:ffff:ffff"; + byte cidr = 64; + var usable = BigInteger.Pow(2, 64); + + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE1() { + string ipaddress = "garbage"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE2() { + string ipaddress = "0:0:0:0:0:0:1:0:0 0:1:2:3:4:5:6:7:8"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringANE1() { + string ipaddress = null; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + + #endregion + + #region ParseStringString + + [TestMethod] + public void TestParseStringString1() { + + string ipaddress = "2001:0db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + Assert.AreEqual("2001:db8::/124", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString3() { + + string ipaddress = "2001:0db8::"; + string netmask = null; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString5() { + + string ipaddress = "2001:0db8::"; + string netmask = ""; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + #endregion + + #region ParseIpIp + + [TestMethod] + public void ParseIpIp1() { + + string ipaddress = "2001:0db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = IPAddress.Parse(netmask); + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + Assert.AreEqual("2001:db8::/124", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void ParseIpIp3() { + + string ipaddress = "2001:0db8::"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = null; + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + + } + + #endregion + + #region ToCidr + + [TestMethod] + public void TestToCidrAE() { + byte cidr = IPNetwork.ToCidr(IPAddress.IPv6Any); + Assert.AreEqual(0, cidr, "cidr"); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestToCidrAE2() { + IPNetwork.ToCidr(IPAddress.Parse("2001:db8:3:4:5:6:7:8")); + } + + + [TestMethod] + public void TestToCidr128() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + byte cidr = 128; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr127() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"); + byte cidr = 127; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr126() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"); + byte cidr = 126; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr125() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"); + byte cidr = 125; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr124() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + byte cidr = 124; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr123() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"); + byte cidr = 123; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr122() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffc0"); + byte cidr = 122; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr121() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff80"); + byte cidr = 121; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr120() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00"); + byte cidr = 120; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr119() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fe00"); + byte cidr = 119; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr118() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fc00"); + byte cidr = 118; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr117() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f800"); + byte cidr = 117; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr116() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f000"); + byte cidr = 116; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr115() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:e000"); + byte cidr = 115; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr114() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:c000"); + byte cidr = 114; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr113() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:8000"); + byte cidr = 113; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr112() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + byte cidr = 112; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr111() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffe:0"); + byte cidr = 111; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr110() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffc:0"); + byte cidr = 110; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr109() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff8:0"); + byte cidr = 109; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr108() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff0:0"); + byte cidr = 108; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr001() { + + IPAddress mask = IPAddress.Parse("8000::"); + byte cidr = 1; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr000() { + + IPAddress mask = IPAddress.Parse("::"); + byte cidr = 0; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + #endregion + + #region TryToCidr + + + [TestMethod] + public void TestTryToCidr128() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + byte cidr = 128; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + + [TestMethod] + public void TestTryToCidr127() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"); + byte cidr = 127; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr126() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"); + byte cidr = 126; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr125() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"); + byte cidr = 125; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr124() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + byte cidr = 124; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr123() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"); + byte cidr = 123; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr122() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffc0"); + byte cidr = 122; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr121() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff80"); + byte cidr = 121; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr120() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00"); + byte cidr = 120; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr119() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fe00"); + byte cidr = 119; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr118() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fc00"); + byte cidr = 118; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr117() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f800"); + byte cidr = 117; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr116() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f000"); + byte cidr = 116; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr115() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:e000"); + byte cidr = 115; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr114() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:c000"); + byte cidr = 114; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr113() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:8000"); + byte cidr = 113; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr112() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + byte cidr = 112; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr111() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffe:0"); + byte cidr = 111; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr110() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffc:0"); + byte cidr = 110; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr109() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff8:0"); + byte cidr = 109; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr108() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff0:0"); + byte cidr = 108; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr001() { + + IPAddress mask = IPAddress.Parse("8000::"); + byte cidr = 1; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr000() { + + IPAddress mask = IPAddress.Parse("::"); + byte cidr = 0; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + #endregion + + #region ToBigInteger + + [TestMethod] + public void TestToBigInteger32() { + + IPAddress mask = IPAddress.Parse("::f"); + uint uintMask = 0xf; + BigInteger result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger24() { + + IPAddress mask = IPAddress.Parse("::fff"); + uint uintMask = 0xfff; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger16() { + + IPAddress mask = IPAddress.Parse("::ff"); + uint uintMask = 0xff; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger8() { + + IPAddress mask = IPAddress.Parse("::ff00:0"); + uint uintMask = 0xff000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger0() { + + IPAddress mask = IPAddress.Parse("::"); + uint uintMask = 0x00000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + + #endregion + + #region TryToBigInteger + + [TestMethod] + public void TestTryToBigInteger32() { + + IPAddress mask = IPAddress.Parse("::ffff:ffff"); + uint uintMask = 0xffffffff; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger24() { + + IPAddress mask = IPAddress.Parse("::ffff:ff00"); + uint uintMask = 0xffffff00; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger16() { + + IPAddress mask = IPAddress.Parse("::ffff:0"); + uint uintMask = 0xffff0000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger8() { + + IPAddress mask = IPAddress.Parse("::ff00:0"); + uint uintMask = 0xff000000; + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger0() { + + IPAddress mask = IPAddress.Parse("::"); + uint uintMask = 0x00000000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + + #endregion + + #region TryToNetmask + [TestMethod] + public void TryToNetmask1() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(0, Sockets.AddressFamily.InterNetworkV6, out result); + IPAddress expected = IPAddress.Parse("::"); + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(true, parsed, "parsed"); + + } + + [TestMethod] + public void TryToNetmask2() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(33, Sockets.AddressFamily.InterNetworkV6, out result); + IPAddress expected = IPAddress.Parse("ffff:ffff:8000::"); + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(true, parsed, "parsed"); + + } + + #endregion + + #region ToNetmask + + [TestMethod] + public void ToNetmask128() { + + byte cidr = 128; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask31() { + + byte cidr = 127; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask30() { + + byte cidr = 126; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask1() { + + byte cidr = 1; + string netmask = "8000::"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + + [TestMethod] + public void ToNetmask0() { + + byte cidr = 0; + string netmask = "::"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void ToNetmaskOORE1() { + byte cidr = 129; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + } + + #endregion + + #region ValidNetmask + + [TestMethod] + public void TestValidNetmask0() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask1() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask2() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + public void TestValidNetmaskEAE1() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:0000:ffff"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmaskEAE3() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:0000:0001"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + #endregion + + #region BitsSet + + [TestMethod] + public void TestBitsSet128() { + + IPAddress ip = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + uint bits = 128; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet120() { + + IPAddress ip = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + uint bits = 124; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet16() { + + IPAddress ip = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + uint bits = 112; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet4() { + + IPAddress ip = IPAddress.Parse("f0f0:f0f0:f0f0:f0f0:f0f0:f0f0:f0f0:f0f0"); + uint bits = 64; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + + #endregion + + #region Contains + + [TestMethod] + public void TestContains1() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPAddress ipaddress = IPAddress.Parse("2001:0db8::1"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains2() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPAddress ipaddress = IPAddress.Parse("2001:0db8:0:1::"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains3() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::/64"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains4() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::/65"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains5() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8:1::/65"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + + [TestMethod] + public void TestContains6() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::/63"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains10() + { + + IPNetwork ipnetwork = IPNetwork.Parse("::/0"); + IPAddress ipaddress = null; + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + + } + + [TestMethod] + public void TestContains11_different_adress_family_returns_false() + { + + IPNetwork ipnetwork = IPNetwork.Parse("::1"); // IPv6 + IPAddress ipaddress = IPAddress.Parse("127.0.0.1"); // IPv4 + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + Assert.AreEqual(false, result, "contains"); + + } + + #endregion + + #region Overlap + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestOverlap2() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8::/0"); + IPNetwork network2 = null; + IPNetwork.Overlap(network1, network2); + } + + [TestMethod] + public void TestOverlap3() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8::/64"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap4() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8:0:0:1::/65"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap5() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8:0:1::/68"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8:0:2::/68"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = false; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap6() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8:0:1::/68"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8:0:2::/62"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + #endregion + + #region Examples + + public void Example1() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + public void Example2() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + + IPAddress ipaddress = IPAddress.Parse("2001:0db8::1"); + IPAddress ipaddress2 = IPAddress.Parse("2001:0db9::1"); + + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::1/128"); + IPNetwork ipnetwork3 = IPNetwork.Parse("2001:0db9::1/64"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + bool contains3 = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool contains4 = IPNetwork.Contains(ipnetwork, ipnetwork3); + + bool overlap1 = IPNetwork.Overlap(ipnetwork, ipnetwork2); + bool overlap2 = IPNetwork.Overlap(ipnetwork, ipnetwork3); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork2, contains3); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork3, contains4); + + + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork2, overlap1); + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork3, overlap2); + + + } + + public void Example4() { + IPNetwork wholeInternet = IPNetwork.Parse("::/0"); + byte newCidr = 2; + IPNetworkCollection subneted = IPNetwork.Subnet(wholeInternet, newCidr); + + Console.WriteLine("{0} was subnetted into {1} subnets", wholeInternet, subneted.Count); + Console.WriteLine("First: {0}", subneted[0]); + Console.WriteLine("Last : {0}", subneted[subneted.Count - 1]); + Console.WriteLine("All :"); + + foreach (IPNetwork ipnetwork in subneted) { + Console.WriteLine("{0}", ipnetwork); + } + } + + public void Example5() { + IPNetwork ipnetwork1 = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db9::/64"); + IPNetwork[] ipnetwork3 = IPNetwork.Supernet(new[] { ipnetwork1, ipnetwork2 }); + + Console.WriteLine("{0} + {1} = {2}", ipnetwork1, ipnetwork2, ipnetwork3[0]); + + } + public void Example6() { + + IPNetwork ipnetwork = IPNetwork.Parse("fe80::202:b3ff:fe1e:8329/24"); + + IPAddress ipaddress = IPAddress.Parse("2001:db8::"); + IPAddress ipaddress2 = IPAddress.Parse("fe80::202:b3ff:fe1e:1"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + + } + + + + public void Example8() { + + IPNetwork network = IPNetwork.Parse("::/124"); + IPNetworkCollection ips = IPNetwork.Subnet(network, 128); + + foreach (IPNetwork ip in ips) { + Console.WriteLine("{0}", ip); + } + } + + + #endregion + + #region ToString + + + [TestMethod] + public void TestToString() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:0000:0000:0000:0000:0000:0000/32"); + string expected = "2001:db8::/32"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString1() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:1:2:3:4:5:6/32"); + string expected = "2001:db8::/32"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString2() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:1:2:3:4:5:6/64"); + string expected = "2001:db8:1:2::/64"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString3() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:1:2:3:4:5:6/100"); + string expected = "2001:db8:1:2:3:4::/100"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + #endregion + + + #region Subnet + + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet3() { + + IPNetwork ipnetwork = IPNetwork.Parse("::"); + byte cidr = 129; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSubnet4() { + + IPNetwork ipnetwork = IPNetwork.Parse("::"); + byte cidr = 1; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + public void TestSubnet5() { + + IPNetwork ipnetwork = IPNetwork.Parse("1:1:1:1:1:1:1:1"); + byte cidr = 65; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("1:1:1:1::/65", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("1:1:1:1:8000::/65", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestSubnet6() { + + IPNetwork ipnetwork = IPNetwork.Parse("1:1:1:1:1:1:1:1"); + byte cidr = 68; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("1:1:1:1::/68", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("1:1:1:1:1000::/68", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("1:1:1:1:2000::/68", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("1:1:1:1:3000::/68", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("1:1:1:1:4000::/68", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("1:1:1:1:5000::/68", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("1:1:1:1:6000::/68", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("1:1:1:1:7000::/68", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("1:1:1:1:8000::/68", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("1:1:1:1:9000::/68", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("1:1:1:1:a000::/68", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("1:1:1:1:b000::/68", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("1:1:1:1:c000::/68", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("1:1:1:1:d000::/68", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("1:1:1:1:e000::/68", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("1:1:1:1:f000::/68", subnets[15].ToString(), "subnet16"); + + } + + + [TestMethod] + public void TestSubnet7() { + + IPNetwork ipnetwork = IPNetwork.Parse("1:1:1:1:1:1:1:1"); + byte cidr = 72; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("1:1:1:1::/72", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("1:1:1:1:ff00::/72", subnets[255].ToString(), "subnet256"); + + } + + + [TestMethod] + public void TestSubnet9() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08:1:1:1:1:1:1"); + byte cidr = 128; + var count = BigInteger.Pow(2, ipnetwork.Cidr); + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(count, subnets.Count, "count"); + Assert.AreEqual("2001:db08:1:1::/128", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("2001:db08:1:1::ff/128", subnets[255].ToString(), "subnet256"); + Assert.AreEqual("2001:db08:1:1:ffff:ffff:ffff:ffff/128", subnets[count-1].ToString(), "last"); + + } + + + [TestMethod] + public void TestSubnet10() { + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/0"); + byte cidr = 128; + var count = BigInteger.Pow(2, 128-ipnetwork.Cidr); + + // Here I spawm a OOM dragon ! beware of the beast ! + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(count, subnets.Count, "count"); + Assert.AreEqual("::/128", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128", subnets[count - 1].ToString(), "last"); + + } + + + [TestMethod] + public void TestSubnet12() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 70; + int i = -1; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + foreach (IPNetwork ipn in subnets) { + i++; + Assert.AreEqual(subnets[i], ipn, "subnet"); + } + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet13() + { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 70; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + IPNetwork error = subnets[1000]; + + } + + + + [TestMethod] + public void TestSubnet14() + { + + IPNetwork network = IPNetwork.Parse("15.0.0.0/8"); + var subnets = IPNetwork.Subnet(network, (byte)12); + Assert.AreEqual(subnets[0].ToString(), "15.0.0.0/12", "subnets[0]"); + Assert.AreEqual(subnets[1].ToString(), "15.16.0.0/12", "subnets[1]"); + Assert.AreEqual(subnets[2].ToString(), "15.32.0.0/12", "subnets[2]"); + Assert.AreEqual(subnets[15].ToString(), "15.240.0.0/12", "subnets[15]"); + + foreach (IPNetwork ipn in subnets) + { + Console.WriteLine(ipn); + } + } + + + + #endregion + + #region TrySubnet + + + [TestMethod] + public void TestTrySubnet3() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 255; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + } + + + [TestMethod] + public void TestTrySubnet4() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 63; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + + } + + + [TestMethod] + public void TestTrySubnet5() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db8::/64"); + byte cidr = 65; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("2001:db8::/65", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("2001:db8:0:0:8000::/65", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestTrySubnet6() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db8::/64"); + byte cidr = 68; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("2001:db8::/68", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("2001:db8:0:0:1000::/68", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("2001:db8:0:0:2000::/68", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("2001:db8:0:0:3000::/68", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("2001:db8:0:0:4000::/68", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("2001:db8:0:0:5000::/68", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("2001:db8:0:0:6000::/68", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("2001:db8:0:0:7000::/68", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("2001:db8:0:0:8000::/68", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("2001:db8:0:0:9000::/68", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("2001:db8:0:0:a000::/68", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("2001:db8:0:0:b000::/68", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("2001:db8:0:0:c000::/68", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("2001:db8:0:0:d000::/68", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("2001:db8:0:0:e000::/68", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("2001:db8:0:0:f000::/68", subnets[15].ToString(), "subnet16"); + + } + + + + #endregion + + + + + + + #region TrySupernet + + + [TestMethod] + public void TestTrySupernet1() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/65"); + IPNetwork network2 = IPNetwork.Parse("2001:db8:0:0:8000::/65"); + IPNetwork supernetExpected = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernet; + bool supernetted = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetted, result, "supernetted"); + Assert.AreEqual(supernetExpected, supernet, "supernet"); + + } + + [TestMethod] + public void TestTrySupernet2() { + + IPNetwork network1 = null; + IPNetwork network2 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet3() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = null; + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet4() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:db9::/65"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet5() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:dba::/64"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet6() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:db8::1/65"); + IPNetwork supernetExpected = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet7() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:db8::1/65"); + IPNetwork supernetExpected = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet8() { + + IPNetwork network1 = IPNetwork.Parse("2001:db0::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:dbf::/64"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet9() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork[] network3 = new[] { network1, network2 }; + IPNetwork[] supernetExpected = new[] { network1, network2 }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(supernetExpected[1], supernet[1], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet10() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8:0000::/65"); + IPNetwork network2 = IPNetwork.Parse("2001:db8:0:0:8000::/65"); + IPNetwork[] network3 = new[] { network1, network2 }; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("2001:db8::/64") }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet11() { + + IPNetwork[] network3 = null; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("2001:db8::/64") }; + IPNetwork[] supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(null, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + #endregion + + + + + + + + #region TryGuessCidr + + [TestMethod] + public void TestTryGuessCidrNull() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr(null, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(0, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidr1() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("::", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(64, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidr2() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("2001:0db8::", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(64, cidr, "cidr"); + } + + + #endregion + + + + + #region Count + + [TestMethod] + public void Total32() { + var network = IPNetwork.Parse("::/128"); + var total = 1; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total31() { + var network = IPNetwork.Parse("::/127"); + var total = 2; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total30() { + var network = IPNetwork.Parse("::/126"); + var total = 4; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total24() { + var network = IPNetwork.Parse("::/120"); + var total = 256; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total16() { + var network = IPNetwork.Parse("::/112"); + var total = 65536; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total8() { + var network = IPNetwork.Parse("::/104"); + var total = 16777216; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total0() { + var network = IPNetwork.Parse("::/0"); + var total = BigInteger.Pow(2, 128); + Assert.AreEqual(total, network.Total, "Total"); + } + + #endregion + + #region Usable + + [TestMethod] + public void Usable32() { + var network = IPNetwork.Parse("::/128"); + uint usable = 1; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable31() { + var network = IPNetwork.Parse("::/127"); + uint usable = 2; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable30() { + var network = IPNetwork.Parse("::/126"); + uint usable = 4; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable24() { + var network = IPNetwork.Parse("::/120"); + uint usable = 256; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable16() { + var network = IPNetwork.Parse("::/112"); + uint usable = 65536; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable8() { + var network = IPNetwork.Parse("::/104"); + uint usable = 16777216; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable0() { + var network = IPNetwork.Parse("::/0"); + var usable = BigInteger.Pow(2, 128); + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + #endregion + + #region TryParseCidr + + [TestMethod] + public void TryParseCidr1() { + + string sidr = "0"; + byte? cidr; + byte? result = 0; + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr2() { + + string sidr = "sadsd"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr33() { + + string sidr = "33"; + byte? cidr; + byte result = 33; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr128() { + + string sidr = "128"; + byte? cidr; + byte result = 128; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + [TestMethod] + public void TryParseCidr129() { + + string sidr = "129"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + #endregion + + + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource subnets of type System.Net.IPNetworkCollection in method "Void IPNetworkV6UnitTest.TestSubnet13()". + +### Severity: +ERROR + +### Procedure: +Void IPNetworkV6UnitTest.TestSubnet13() + +### File: +src/System.Net.IPNetwork.TestProject.Source/IPNetworkV6UnitTest.cs + +### Key: +IPNetworkV6UnitTest.cs|TestSubnet13|DOTNET_RESOURCE_LEAK + +### Hash: +e6f376632f87401df0aa4fc8db62bb23 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1617/instruction.md b/inferredbugs-1617/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4d8f2be338800d30bcb71cab5d5196ddfa80ad09 --- /dev/null +++ b/inferredbugs-1617/instruction.md @@ -0,0 +1,2546 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ipnetwork +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Numerics; + +namespace System.Net.TestProject +{ + [TestClass] + public class IPNetworkV6UnitTest { + + #region ParseIP + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE8() { + IPNetwork ipnet = IPNetwork.Parse("xxxx::", "xxxx::"); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE9() { + IPNetwork ipnet = IPNetwork.Parse("::", "xxxx::"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE10() { + IPNetwork ipnet = IPNetwork.Parse("xxxx::", 0); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE11() { + IPNetwork ipnet = IPNetwork.Parse("::", 129); + + } + + [TestMethod] + public void TestParsev6_128() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + //string broadcast = "2001:db8::"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::"; + byte cidr = 128; + BigInteger usable = 1; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_127() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"; + //string broadcast = "2001:db8::1"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::1"; + byte cidr = 127; + BigInteger usable = 2; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_126() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"; + //string broadcast = "2001:db8::3"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::3"; + byte cidr = 126; + BigInteger usable = 4; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_125() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"; + //string broadcast = "2001:db8::7"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::7"; + byte cidr = 125; + BigInteger usable = 8; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_124() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + //string broadcast = "2001:db8::f"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::f"; + byte cidr = 124; + BigInteger usable = 16; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParsev6_123() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:0db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"; + //string broadcast = "2001:db8::1f"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::1f"; + byte cidr = 123; + BigInteger usable = 32; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + + [TestMethod] + public void TestParsev6_112() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"; + + string network = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"; + //string broadcast = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 112; + uint usable = 65536; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_64() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:1234:1234:1234:1234"; + string netmask = "ffff:ffff:ffff:ffff:0000:0000:0000:0000"; + + string network = "ffff:ffff:ffff:ffff::"; + string netmask2 = "ffff:ffff:ffff:ffff::"; + //string broadcast = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 64; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)) ; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_16() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:0000:0000:0000:0000:0000:0000:0000"; + + string network = "ffff::"; + string netmask2 = "ffff::"; + //string broadcast = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 16; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)) ; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + + [TestMethod] + public void TestParsev6_EDGE() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + + string network = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 128; + uint usable = 1; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + #endregion + + #region ParseString + + [TestMethod] + public void TestParseString1() { + + string ipaddress = "2001:0db8:: ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + + string network = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::f"; + byte cidr = 124; + uint usable = 16; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParseString3() { + + string ipaddress = ":: ::"; + + string network = "::"; + string netmask = "::"; + string firstUsable = "::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 0; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)); + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParseString4() { + + string ipaddress = "::/0"; + + string network = "::"; + string netmask = "::"; + string firstUsable = "::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 0; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)); + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString5() { + + string ipaddress = "::/32"; + + string network = "::"; + string netmask = "ffff:ffff::"; + string firstUsable = "::"; + string lastUsable = "::ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 32; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)) ; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString6() + { + + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128"; + + string network = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 128; + uint usable = 1; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString7_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFF:123::/60"; + + string network = "2fff:ffff:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:ffff:123::"; + string lastUsable = "2fff:ffff:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParseString8_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFE:123::/60"; + + string network = "2fff:fffe:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:fffe:123::"; + string lastUsable = "2fff:fffe:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + + } + + [TestMethod] + public void TestParseString9_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFC:123::/60"; + + string network = "2fff:fffc:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:fffc:123::"; + string lastUsable = "2fff:fffc:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString10_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFA:123::/60"; + + string network = "2fff:fffa:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:fffa:123::"; + string lastUsable = "2fff:fffa:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString11_Uppercase_ipv6_must_parse() + { + + string ipaddress = "FFFF:FFF1:123::/60"; + + string network = "ffff:fff1:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "ffff:fff1:123::"; + string lastUsable = "ffff:fff1:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseIPAddressNoNetmask1() { + + string ipaddress = "2001:0db8::"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + + string network = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff::"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::ffff:ffff:ffff:ffff"; + byte cidr = 64; + var usable = BigInteger.Pow(2, 64); + + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + [TestMethod] + public void TestParseIPAddressNoNetmask4() { + + string ipaddress = "::"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + + + string network = "::"; + string netmask = "ffff:ffff:ffff:ffff::"; + string firstUsable = "::"; + string lastUsable = "::ffff:ffff:ffff:ffff"; + byte cidr = 64; + var usable = BigInteger.Pow(2, 64); + + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + [TestMethod] + public void TestParseIPAddressNoNetmask5() { + + string ipaddress = "2001:0db8::1"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + string network = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff::"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::ffff:ffff:ffff:ffff"; + byte cidr = 64; + var usable = BigInteger.Pow(2, 64); + + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE1() { + string ipaddress = "garbage"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE2() { + string ipaddress = "0:0:0:0:0:0:1:0:0 0:1:2:3:4:5:6:7:8"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringANE1() { + string ipaddress = null; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + + #endregion + + #region ParseStringString + + [TestMethod] + public void TestParseStringString1() { + + string ipaddress = "2001:0db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + Assert.AreEqual("2001:db8::/124", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString3() { + + string ipaddress = "2001:0db8::"; + string netmask = null; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString5() { + + string ipaddress = "2001:0db8::"; + string netmask = ""; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + #endregion + + #region ParseIpIp + + [TestMethod] + public void ParseIpIp1() { + + string ipaddress = "2001:0db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = IPAddress.Parse(netmask); + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + Assert.AreEqual("2001:db8::/124", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void ParseIpIp3() { + + string ipaddress = "2001:0db8::"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = null; + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + + } + + #endregion + + #region ToCidr + + [TestMethod] + public void TestToCidrAE() { + byte cidr = IPNetwork.ToCidr(IPAddress.IPv6Any); + Assert.AreEqual(0, cidr, "cidr"); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestToCidrAE2() { + IPNetwork.ToCidr(IPAddress.Parse("2001:db8:3:4:5:6:7:8")); + } + + + [TestMethod] + public void TestToCidr128() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + byte cidr = 128; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr127() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"); + byte cidr = 127; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr126() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"); + byte cidr = 126; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr125() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"); + byte cidr = 125; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr124() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + byte cidr = 124; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr123() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"); + byte cidr = 123; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr122() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffc0"); + byte cidr = 122; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr121() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff80"); + byte cidr = 121; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr120() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00"); + byte cidr = 120; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr119() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fe00"); + byte cidr = 119; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr118() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fc00"); + byte cidr = 118; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr117() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f800"); + byte cidr = 117; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr116() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f000"); + byte cidr = 116; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr115() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:e000"); + byte cidr = 115; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr114() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:c000"); + byte cidr = 114; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr113() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:8000"); + byte cidr = 113; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr112() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + byte cidr = 112; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr111() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffe:0"); + byte cidr = 111; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr110() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffc:0"); + byte cidr = 110; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr109() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff8:0"); + byte cidr = 109; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr108() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff0:0"); + byte cidr = 108; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr001() { + + IPAddress mask = IPAddress.Parse("8000::"); + byte cidr = 1; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr000() { + + IPAddress mask = IPAddress.Parse("::"); + byte cidr = 0; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + #endregion + + #region TryToCidr + + + [TestMethod] + public void TestTryToCidr128() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + byte cidr = 128; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + + [TestMethod] + public void TestTryToCidr127() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"); + byte cidr = 127; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr126() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"); + byte cidr = 126; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr125() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"); + byte cidr = 125; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr124() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + byte cidr = 124; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr123() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"); + byte cidr = 123; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr122() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffc0"); + byte cidr = 122; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr121() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff80"); + byte cidr = 121; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr120() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00"); + byte cidr = 120; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr119() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fe00"); + byte cidr = 119; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr118() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fc00"); + byte cidr = 118; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr117() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f800"); + byte cidr = 117; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr116() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f000"); + byte cidr = 116; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr115() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:e000"); + byte cidr = 115; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr114() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:c000"); + byte cidr = 114; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr113() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:8000"); + byte cidr = 113; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr112() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + byte cidr = 112; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr111() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffe:0"); + byte cidr = 111; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr110() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffc:0"); + byte cidr = 110; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr109() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff8:0"); + byte cidr = 109; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr108() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff0:0"); + byte cidr = 108; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr001() { + + IPAddress mask = IPAddress.Parse("8000::"); + byte cidr = 1; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr000() { + + IPAddress mask = IPAddress.Parse("::"); + byte cidr = 0; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + #endregion + + #region ToBigInteger + + [TestMethod] + public void TestToBigInteger32() { + + IPAddress mask = IPAddress.Parse("::f"); + uint uintMask = 0xf; + BigInteger result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger24() { + + IPAddress mask = IPAddress.Parse("::fff"); + uint uintMask = 0xfff; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger16() { + + IPAddress mask = IPAddress.Parse("::ff"); + uint uintMask = 0xff; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger8() { + + IPAddress mask = IPAddress.Parse("::ff00:0"); + uint uintMask = 0xff000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger0() { + + IPAddress mask = IPAddress.Parse("::"); + uint uintMask = 0x00000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + + #endregion + + #region TryToBigInteger + + [TestMethod] + public void TestTryToBigInteger32() { + + IPAddress mask = IPAddress.Parse("::ffff:ffff"); + uint uintMask = 0xffffffff; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger24() { + + IPAddress mask = IPAddress.Parse("::ffff:ff00"); + uint uintMask = 0xffffff00; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger16() { + + IPAddress mask = IPAddress.Parse("::ffff:0"); + uint uintMask = 0xffff0000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger8() { + + IPAddress mask = IPAddress.Parse("::ff00:0"); + uint uintMask = 0xff000000; + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger0() { + + IPAddress mask = IPAddress.Parse("::"); + uint uintMask = 0x00000000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + + #endregion + + #region TryToNetmask + [TestMethod] + public void TryToNetmask1() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(0, Sockets.AddressFamily.InterNetworkV6, out result); + IPAddress expected = IPAddress.Parse("::"); + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(true, parsed, "parsed"); + + } + + [TestMethod] + public void TryToNetmask2() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(33, Sockets.AddressFamily.InterNetworkV6, out result); + IPAddress expected = IPAddress.Parse("ffff:ffff:8000::"); + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(true, parsed, "parsed"); + + } + + #endregion + + #region ToNetmask + + [TestMethod] + public void ToNetmask128() { + + byte cidr = 128; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask31() { + + byte cidr = 127; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask30() { + + byte cidr = 126; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask1() { + + byte cidr = 1; + string netmask = "8000::"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + + [TestMethod] + public void ToNetmask0() { + + byte cidr = 0; + string netmask = "::"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void ToNetmaskOORE1() { + byte cidr = 129; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + } + + #endregion + + #region ValidNetmask + + [TestMethod] + public void TestValidNetmask0() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask1() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask2() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + public void TestValidNetmaskEAE1() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:0000:ffff"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmaskEAE3() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:0000:0001"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + #endregion + + #region BitsSet + + [TestMethod] + public void TestBitsSet128() { + + IPAddress ip = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + uint bits = 128; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet120() { + + IPAddress ip = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + uint bits = 124; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet16() { + + IPAddress ip = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + uint bits = 112; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet4() { + + IPAddress ip = IPAddress.Parse("f0f0:f0f0:f0f0:f0f0:f0f0:f0f0:f0f0:f0f0"); + uint bits = 64; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + + #endregion + + #region Contains + + [TestMethod] + public void TestContains1() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPAddress ipaddress = IPAddress.Parse("2001:0db8::1"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains2() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPAddress ipaddress = IPAddress.Parse("2001:0db8:0:1::"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains3() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::/64"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains4() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::/65"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains5() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8:1::/65"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + + [TestMethod] + public void TestContains6() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::/63"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains10() + { + + IPNetwork ipnetwork = IPNetwork.Parse("::/0"); + IPAddress ipaddress = null; + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + + } + + [TestMethod] + public void TestContains11_different_adress_family_returns_false() + { + + IPNetwork ipnetwork = IPNetwork.Parse("::1"); // IPv6 + IPAddress ipaddress = IPAddress.Parse("127.0.0.1"); // IPv4 + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + Assert.AreEqual(false, result, "contains"); + + } + + #endregion + + #region Overlap + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestOverlap2() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8::/0"); + IPNetwork network2 = null; + IPNetwork.Overlap(network1, network2); + } + + [TestMethod] + public void TestOverlap3() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8::/64"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap4() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8:0:0:1::/65"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap5() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8:0:1::/68"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8:0:2::/68"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = false; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap6() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8:0:1::/68"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8:0:2::/62"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + #endregion + + #region Examples + + public void Example1() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + public void Example2() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + + IPAddress ipaddress = IPAddress.Parse("2001:0db8::1"); + IPAddress ipaddress2 = IPAddress.Parse("2001:0db9::1"); + + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::1/128"); + IPNetwork ipnetwork3 = IPNetwork.Parse("2001:0db9::1/64"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + bool contains3 = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool contains4 = IPNetwork.Contains(ipnetwork, ipnetwork3); + + bool overlap1 = IPNetwork.Overlap(ipnetwork, ipnetwork2); + bool overlap2 = IPNetwork.Overlap(ipnetwork, ipnetwork3); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork2, contains3); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork3, contains4); + + + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork2, overlap1); + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork3, overlap2); + + + } + + public void Example4() { + IPNetwork wholeInternet = IPNetwork.Parse("::/0"); + byte newCidr = 2; + IPNetworkCollection subneted = IPNetwork.Subnet(wholeInternet, newCidr); + + Console.WriteLine("{0} was subnetted into {1} subnets", wholeInternet, subneted.Count); + Console.WriteLine("First: {0}", subneted[0]); + Console.WriteLine("Last : {0}", subneted[subneted.Count - 1]); + Console.WriteLine("All :"); + + foreach (IPNetwork ipnetwork in subneted) { + Console.WriteLine("{0}", ipnetwork); + } + } + + public void Example5() { + IPNetwork ipnetwork1 = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db9::/64"); + IPNetwork[] ipnetwork3 = IPNetwork.Supernet(new[] { ipnetwork1, ipnetwork2 }); + + Console.WriteLine("{0} + {1} = {2}", ipnetwork1, ipnetwork2, ipnetwork3[0]); + + } + public void Example6() { + + IPNetwork ipnetwork = IPNetwork.Parse("fe80::202:b3ff:fe1e:8329/24"); + + IPAddress ipaddress = IPAddress.Parse("2001:db8::"); + IPAddress ipaddress2 = IPAddress.Parse("fe80::202:b3ff:fe1e:1"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + + } + + + + public void Example8() { + + IPNetwork network = IPNetwork.Parse("::/124"); + IPNetworkCollection ips = IPNetwork.Subnet(network, 128); + + foreach (IPNetwork ip in ips) { + Console.WriteLine("{0}", ip); + } + } + + + #endregion + + #region ToString + + + [TestMethod] + public void TestToString() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:0000:0000:0000:0000:0000:0000/32"); + string expected = "2001:db8::/32"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString1() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:1:2:3:4:5:6/32"); + string expected = "2001:db8::/32"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString2() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:1:2:3:4:5:6/64"); + string expected = "2001:db8:1:2::/64"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString3() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:1:2:3:4:5:6/100"); + string expected = "2001:db8:1:2:3:4::/100"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + #endregion + + + #region Subnet + + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet3() { + + IPNetwork ipnetwork = IPNetwork.Parse("::"); + byte cidr = 129; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSubnet4() { + + IPNetwork ipnetwork = IPNetwork.Parse("::"); + byte cidr = 1; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + public void TestSubnet5() { + + IPNetwork ipnetwork = IPNetwork.Parse("1:1:1:1:1:1:1:1"); + byte cidr = 65; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("1:1:1:1::/65", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("1:1:1:1:8000::/65", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestSubnet6() { + + IPNetwork ipnetwork = IPNetwork.Parse("1:1:1:1:1:1:1:1"); + byte cidr = 68; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("1:1:1:1::/68", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("1:1:1:1:1000::/68", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("1:1:1:1:2000::/68", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("1:1:1:1:3000::/68", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("1:1:1:1:4000::/68", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("1:1:1:1:5000::/68", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("1:1:1:1:6000::/68", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("1:1:1:1:7000::/68", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("1:1:1:1:8000::/68", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("1:1:1:1:9000::/68", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("1:1:1:1:a000::/68", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("1:1:1:1:b000::/68", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("1:1:1:1:c000::/68", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("1:1:1:1:d000::/68", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("1:1:1:1:e000::/68", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("1:1:1:1:f000::/68", subnets[15].ToString(), "subnet16"); + + } + + + [TestMethod] + public void TestSubnet7() { + + IPNetwork ipnetwork = IPNetwork.Parse("1:1:1:1:1:1:1:1"); + byte cidr = 72; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("1:1:1:1::/72", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("1:1:1:1:ff00::/72", subnets[255].ToString(), "subnet256"); + + } + + + [TestMethod] + public void TestSubnet9() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08:1:1:1:1:1:1"); + byte cidr = 128; + var count = BigInteger.Pow(2, ipnetwork.Cidr); + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(count, subnets.Count, "count"); + Assert.AreEqual("2001:db08:1:1::/128", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("2001:db08:1:1::ff/128", subnets[255].ToString(), "subnet256"); + Assert.AreEqual("2001:db08:1:1:ffff:ffff:ffff:ffff/128", subnets[count-1].ToString(), "last"); + + } + + + [TestMethod] + public void TestSubnet10() { + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/0"); + byte cidr = 128; + var count = BigInteger.Pow(2, 128-ipnetwork.Cidr); + + // Here I spawm a OOM dragon ! beware of the beast ! + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(count, subnets.Count, "count"); + Assert.AreEqual("::/128", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128", subnets[count - 1].ToString(), "last"); + + } + + + [TestMethod] + public void TestSubnet12() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 70; + int i = -1; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + foreach (IPNetwork ipn in subnets) { + i++; + Assert.AreEqual(subnets[i], ipn, "subnet"); + } + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet13() + { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 70; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + IPNetwork error = subnets[1000]; + + } + + + + [TestMethod] + public void TestSubnet14() + { + + IPNetwork network = IPNetwork.Parse("15.0.0.0/8"); + var subnets = IPNetwork.Subnet(network, (byte)12); + Assert.AreEqual(subnets[0].ToString(), "15.0.0.0/12", "subnets[0]"); + Assert.AreEqual(subnets[1].ToString(), "15.16.0.0/12", "subnets[1]"); + Assert.AreEqual(subnets[2].ToString(), "15.32.0.0/12", "subnets[2]"); + Assert.AreEqual(subnets[15].ToString(), "15.240.0.0/12", "subnets[15]"); + + foreach (IPNetwork ipn in subnets) + { + Console.WriteLine(ipn); + } + } + + + + #endregion + + #region TrySubnet + + + [TestMethod] + public void TestTrySubnet3() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 255; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + } + + + [TestMethod] + public void TestTrySubnet4() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 63; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + + } + + + [TestMethod] + public void TestTrySubnet5() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db8::/64"); + byte cidr = 65; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("2001:db8::/65", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("2001:db8:0:0:8000::/65", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestTrySubnet6() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db8::/64"); + byte cidr = 68; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("2001:db8::/68", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("2001:db8:0:0:1000::/68", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("2001:db8:0:0:2000::/68", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("2001:db8:0:0:3000::/68", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("2001:db8:0:0:4000::/68", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("2001:db8:0:0:5000::/68", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("2001:db8:0:0:6000::/68", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("2001:db8:0:0:7000::/68", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("2001:db8:0:0:8000::/68", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("2001:db8:0:0:9000::/68", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("2001:db8:0:0:a000::/68", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("2001:db8:0:0:b000::/68", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("2001:db8:0:0:c000::/68", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("2001:db8:0:0:d000::/68", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("2001:db8:0:0:e000::/68", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("2001:db8:0:0:f000::/68", subnets[15].ToString(), "subnet16"); + + } + + + + #endregion + + + + + + + #region TrySupernet + + + [TestMethod] + public void TestTrySupernet1() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/65"); + IPNetwork network2 = IPNetwork.Parse("2001:db8:0:0:8000::/65"); + IPNetwork supernetExpected = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernet; + bool supernetted = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetted, result, "supernetted"); + Assert.AreEqual(supernetExpected, supernet, "supernet"); + + } + + [TestMethod] + public void TestTrySupernet2() { + + IPNetwork network1 = null; + IPNetwork network2 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet3() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = null; + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet4() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:db9::/65"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet5() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:dba::/64"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet6() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:db8::1/65"); + IPNetwork supernetExpected = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet7() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:db8::1/65"); + IPNetwork supernetExpected = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet8() { + + IPNetwork network1 = IPNetwork.Parse("2001:db0::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:dbf::/64"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet9() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork[] network3 = new[] { network1, network2 }; + IPNetwork[] supernetExpected = new[] { network1, network2 }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(supernetExpected[1], supernet[1], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet10() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8:0000::/65"); + IPNetwork network2 = IPNetwork.Parse("2001:db8:0:0:8000::/65"); + IPNetwork[] network3 = new[] { network1, network2 }; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("2001:db8::/64") }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet11() { + + IPNetwork[] network3 = null; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("2001:db8::/64") }; + IPNetwork[] supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(null, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + #endregion + + + + + + + + #region TryGuessCidr + + [TestMethod] + public void TestTryGuessCidrNull() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr(null, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(0, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidr1() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("::", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(64, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidr2() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("2001:0db8::", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(64, cidr, "cidr"); + } + + + #endregion + + + + + #region Count + + [TestMethod] + public void Total32() { + var network = IPNetwork.Parse("::/128"); + var total = 1; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total31() { + var network = IPNetwork.Parse("::/127"); + var total = 2; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total30() { + var network = IPNetwork.Parse("::/126"); + var total = 4; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total24() { + var network = IPNetwork.Parse("::/120"); + var total = 256; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total16() { + var network = IPNetwork.Parse("::/112"); + var total = 65536; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total8() { + var network = IPNetwork.Parse("::/104"); + var total = 16777216; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total0() { + var network = IPNetwork.Parse("::/0"); + var total = BigInteger.Pow(2, 128); + Assert.AreEqual(total, network.Total, "Total"); + } + + #endregion + + #region Usable + + [TestMethod] + public void Usable32() { + var network = IPNetwork.Parse("::/128"); + uint usable = 1; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable31() { + var network = IPNetwork.Parse("::/127"); + uint usable = 2; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable30() { + var network = IPNetwork.Parse("::/126"); + uint usable = 4; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable24() { + var network = IPNetwork.Parse("::/120"); + uint usable = 256; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable16() { + var network = IPNetwork.Parse("::/112"); + uint usable = 65536; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable8() { + var network = IPNetwork.Parse("::/104"); + uint usable = 16777216; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable0() { + var network = IPNetwork.Parse("::/0"); + var usable = BigInteger.Pow(2, 128); + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + #endregion + + #region TryParseCidr + + [TestMethod] + public void TryParseCidr1() { + + string sidr = "0"; + byte? cidr; + byte? result = 0; + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr2() { + + string sidr = "sadsd"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr33() { + + string sidr = "33"; + byte? cidr; + byte result = 33; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr128() { + + string sidr = "128"; + byte? cidr; + byte result = 128; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + [TestMethod] + public void TryParseCidr129() { + + string sidr = "129"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + #endregion + + + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`subnets` could be null (from the call to `IPNetwork.Subnet(...)` on line 1919) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +Void IPNetworkV6UnitTest.TestSubnet7() + +### File: +src/System.Net.IPNetwork.TestProject.Source/IPNetworkV6UnitTest.cs + +### Key: +IPNetworkV6UnitTest.cs|TestSubnet7|NULLPTR_DEREFERENCE + +### Hash: +79954fc8b12460984546445d78d34c2e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1618/instruction.md b/inferredbugs-1618/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aabb3594f00a106b4750392234446aa8d678b334 --- /dev/null +++ b/inferredbugs-1618/instruction.md @@ -0,0 +1,3382 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ipnetwork +**Bug ID:** 28 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; + +namespace System.Net.TestProject +{ + /// + /// IPNetworkUnitTest test every single method + /// + [TestClass] + public class IPNetworkUnitTest { + + #region Parse + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE2() { + IPAddress ip = null; + IPNetwork.Parse(ip, ip); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE3() { + IPNetwork.Parse("", 0); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE4() { + IPNetwork.Parse(null, 0); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE5() { + string n = null; + IPNetwork.Parse(n, n); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE8() { + IPNetwork ipnet = IPNetwork.Parse("x.x.x.x", "x.x.x.x"); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE9() { + IPNetwork ipnet = IPNetwork.Parse("0.0.0.0", "x.x.x.x"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE10() { + IPNetwork ipnet = IPNetwork.Parse("x.x.x.x", 0); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE11() { + IPNetwork ipnet = IPNetwork.Parse("0.0.0.0", 33); + + } + + [TestMethod] + public void TestParseIPAddressNetmask() { + + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + + string network = "192.168.168.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString1() { + + string ipaddress = "192.168.168.100 255.255.255.0"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString2() { + + string ipaddress = "192.168.168.100/24"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString3() { + + string ipaddress = "0.0.0.0/0"; + + string network = "0.0.0.0"; + string netmask = "0.0.0.0"; + string broadcast = "255.255.255.255"; + string firstUsable = "0.0.0.1"; + string lastUsable = "255.255.255.254"; + byte cidr = 0; + uint usable = 4294967294; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString4() { + + string ipaddress = "0.0.0.0/32"; + + string network = "0.0.0.0"; + string netmask = "255.255.255.255"; + string broadcast = "0.0.0.0"; + string firstUsable = "0.0.0.0"; + string lastUsable = "0.0.0.0"; + byte cidr = 32; + uint usable = 0; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString5() { + + string ipaddress = "255.255.255.255/32"; + + string network = "255.255.255.255"; + string netmask = "255.255.255.255"; + string broadcast = "255.255.255.255"; + string firstUsable = "255.255.255.255"; + string lastUsable = "255.255.255.255"; + byte cidr = 32; + uint usable = 0; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseIPAddressNoNetmask1() { + + string ipaddress = "10.0.0.0"; + + string network = "10.0.0.0"; + string netmask = "255.0.0.0"; + string broadcast = "10.255.255.255"; + string firstUsable = "10.0.0.1"; + string lastUsable = "10.255.255.254"; + byte cidr = 8; + uint usable = 16777214; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + + + [TestMethod] + public void TestParseIPAddressNoNetmask2() { + + string ipaddress = "172.0.0.0"; + + string network = "172.0.0.0"; + string netmask = "255.255.0.0"; + string broadcast = "172.0.255.255"; + string firstUsable = "172.0.0.1"; + string lastUsable = "172.0.255.254"; + byte cidr = 16; + uint usable = 65534; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + [TestMethod] + public void TestParseIPAddressNoNetmask3() { + + string ipaddress = "192.0.0.0"; + + string network = "192.0.0.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.0.0.255"; + string firstUsable = "192.0.0.1"; + string lastUsable = "192.0.0.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNoNetmask4() { + + string ipaddress = "224.0.0.0"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNoNetmask5() { + + string ipaddress = "240.0.0.0"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + } + + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE1() { + string ipaddress = "garbage"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE2() { + string ipaddress = "0.0.0.0 0.0.1.0"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringANE1() { + string ipaddress = null; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + + + #endregion + + #region TryParse + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE2() { + IPNetwork ipnet = null; + IPAddress ip = null; + bool parsed = IPNetwork.TryParse(ip, ip, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE3() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("", 0, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + [TestMethod] + public void TestTryParseIPAddressNetmaskANE4() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse(null, 0, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + [TestMethod] + public void TestTryParseIPAddressNetmaskANE5() { + string n = null; + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse(n, n, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE6() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse(IPAddress.Parse("10.10.10.10"), null, out ipnet); + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE7() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("0.0.0.0", null, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE8() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("x.x.x.x", "x.x.x.x", out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE9() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("0.0.0.0", "x.x.x.x", out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE10() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("x.x.x.x", 0, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE11() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("0.0.0.0", 33, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + + [TestMethod] + public void TestTryParseIPAddressNetmask() { + + IPNetwork ipnetwork = null; + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + + string network = "192.168.168.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString1() { + + IPNetwork ipnetwork = null; + string ipaddress = "192.168.168.100 255.255.255.0"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString2() { + + IPNetwork ipnetwork = null; + string ipaddress = "192.168.168.100/24"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString3() { + + IPNetwork ipnetwork = null; + string ipaddress = "0.0.0.0/0"; + + string network = "0.0.0.0"; + string netmask = "0.0.0.0"; + string broadcast = "255.255.255.255"; + string firstUsable = "0.0.0.1"; + string lastUsable = "255.255.255.254"; + byte cidr = 0; + uint usable = 4294967294; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString4() { + + IPNetwork ipnetwork = null; + string ipaddress = "0.0.0.0/32"; + + string network = "0.0.0.0"; + string netmask = "255.255.255.255"; + string broadcast = "0.0.0.0"; + string firstUsable = "0.0.0.0"; + string lastUsable = "0.0.0.0"; + byte cidr = 32; + uint usable = 0; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString5() { + + IPNetwork ipnetwork = null; + string ipaddress = "255.255.255.255/32"; + + string network = "255.255.255.255"; + string netmask = "255.255.255.255"; + string broadcast = "255.255.255.255"; + string firstUsable = "255.255.255.255"; + string lastUsable = "255.255.255.255"; + byte cidr = 32; + uint usable = 0; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + + [TestMethod] + public void TestTryParseStringAE1() { + string ipaddress = "garbage"; + IPNetwork ipnetwork = null; + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(false, parsed, "parsed"); + } + + [TestMethod] + public void TestTryParseStringAE2() { + string ipaddress = "0.0.0.0 0.0.1.0"; + IPNetwork ipnetwork = null; + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(false, parsed, "parsed"); + } + + [TestMethod] + public void TestTryParseStringANE1() { + string ipaddress = null; + IPNetwork ipnetwork = null; + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(false, parsed, "parsed"); + } + + + + #endregion + + #region ParseStringString + + [TestMethod] + public void TestParseStringString1() { + + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + Assert.AreEqual("192.168.168.0/24", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString2() { + + string ipaddress = null; + string netmask = null; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString3() { + + string ipaddress = "192.168.168.100"; + string netmask = null; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString4() { + + string ipaddress = ""; + string netmask = ""; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString5() { + + string ipaddress = "192.168.168.100"; + string netmask = ""; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + #endregion + + #region ParseIpIp + + [TestMethod] + public void ParseIpIp1() { + + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = IPAddress.Parse(netmask); + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + Assert.AreEqual("192.168.168.0/24", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void ParseIpIp2() { + + IPAddress ip = null; + IPAddress netm = null; + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void ParseIpIp3() { + + string ipaddress = "192.168.168.100"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = null; + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + + } + + #endregion + + #region ToCidr + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestToCidrANE() { + IPNetwork.ToCidr(null); + } + + [TestMethod] + public void TestToCidrAE() { + byte cidr = IPNetwork.ToCidr(IPAddress.IPv6Any); + Assert.AreEqual(0, cidr, "cidr"); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestToCidrAE2() { + IPNetwork.ToCidr(IPAddress.Parse("6.6.6.6")); + } + + + [TestMethod] + public void TestToCidr32() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + byte cidr = 32; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr24() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + byte cidr = 24; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr16() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + byte cidr = 16; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr8() { + + IPAddress mask = IPAddress.Parse("255.0.0.0"); + byte cidr = 8; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr0() { + + IPAddress mask = IPAddress.Parse("0.0.0.0"); + byte cidr = 0; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + #endregion + + #region TryToCidr + + [TestMethod] + public void TestTryToCidrANE() { + byte? cidr = null; + bool parsed = IPNetwork.TryToCidr(null, out cidr); + Assert.AreEqual(false, parsed, "parsed"); + } + + [TestMethod] + public void TestTryToCidrAE() { + byte? cidr = null; + bool parsed = IPNetwork.TryToCidr(IPAddress.IPv6Any, out cidr); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual((byte)0, cidr, "cidr"); + } + + + [TestMethod] + public void TestTryToCidrAE2() { + byte? cidr = null; + bool parsed = IPNetwork.TryToCidr(IPAddress.Parse("6.6.6.6"), out cidr); + Assert.AreEqual(false, parsed, "parsed"); + } + + + [TestMethod] + public void TestTryToCidr32() { + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.255.255.255"); + byte result = 32; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr24() { + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.255.255.0"); + byte result = 24; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + [TestMethod] + public void TestTryToCidr16() { + + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.255.0.0"); + byte result = 16; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + [TestMethod] + public void TestTryToCidr8() { + + + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.0.0.0"); + byte result = 8; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + [TestMethod] + public void TestTryToCidr0() { + + byte? cidr = null; + IPAddress mask = IPAddress.Parse("0.0.0.0"); + byte result = 0; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + + #endregion + + #region ToBigInteger + + [TestMethod] + public void TestToBigInteger32() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + uint uintMask = 0xffffffff; + BigInteger result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger24() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + uint uintMask = 0xffffff00; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger16() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + uint uintMask = 0xffff0000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger8() { + + IPAddress mask = IPAddress.Parse("255.0.0.0"); + uint uintMask = 0xff000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger0() { + + IPAddress mask = IPAddress.Parse("0.0.0.0"); + uint uintMask = 0x00000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestToBigIntegerANE() { + BigInteger? result = IPNetwork.ToBigInteger(null); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestToBigIntegerANE3() { + IPAddress ip = null; + BigInteger? result = IPNetwork.ToBigInteger(ip); + } + [TestMethod] + public void TestToBigIntegerANE2() { + BigInteger? result = IPNetwork.ToBigInteger(IPAddress.IPv6Any); + uint expected = 0; + Assert.AreEqual(expected, result, "result"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestToBigIntegerByte() { + BigInteger result = IPNetwork.ToUint(33, Sockets.AddressFamily.InterNetwork); + } + + [TestMethod] + public void TestToBigIntegerByte2() { + BigInteger result = IPNetwork.ToUint(32, Sockets.AddressFamily.InterNetwork); + uint expected = 4294967295; + Assert.AreEqual(expected, result, "result"); + + } + + + [TestMethod] + public void TestToBigIntegerByte3() { + BigInteger result = IPNetwork.ToUint(0, Sockets.AddressFamily.InterNetwork); + uint expected = 0; + Assert.AreEqual(expected, result, "result"); + + } + + + + #endregion + + #region TryToBigInteger + + [TestMethod] + public void TestTryToBigInteger32() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + uint uintMask = 0xffffffff; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger24() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + uint uintMask = 0xffffff00; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger16() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + uint uintMask = 0xffff0000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger8() { + + IPAddress mask = IPAddress.Parse("255.0.0.0"); + uint uintMask = 0xff000000; + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger0() { + + IPAddress mask = IPAddress.Parse("0.0.0.0"); + uint uintMask = 0x00000000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigIntegerANE() { + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(null, out result); + + Assert.AreEqual(null, result, "uint"); + Assert.AreEqual(false, parsed, "parsed"); + + } + [TestMethod] + public void TestTryToBigIntegerANE3() { + IPAddress ip = null; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(ip, out result); + + Assert.AreEqual(null, result, "uint"); + Assert.AreEqual(false, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigIntegerANE2() { + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(IPAddress.IPv6Any, out result); + + Assert.AreEqual(0, result, "result"); + Assert.AreEqual(true, parsed, "parsed"); + } + + + + #endregion + + #region TryToNetmask + [TestMethod] + public void TryToNetmask1() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(0, Sockets.AddressFamily.InterNetwork, out result); + IPAddress expected = IPAddress.Parse("0.0.0.0"); + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(true, parsed, "parsed"); + + } + + [TestMethod] + public void TryToNetmask2() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(33, Sockets.AddressFamily.InterNetwork, out result); + IPAddress expected = null; + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(false, parsed, "parsed"); + + } + + #endregion + + #region ToNetmask + + [TestMethod] + public void ToNetmask32() { + + byte cidr = 32; + string netmask = "255.255.255.255"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask31() { + + byte cidr = 31; + string netmask = "255.255.255.254"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask30() { + + byte cidr = 30; + string netmask = "255.255.255.252"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask29() { + + byte cidr = 29; + string netmask = "255.255.255.248"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask1() { + + byte cidr = 1; + string netmask = "128.0.0.0"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + + [TestMethod] + public void ToNetmask0() { + + byte cidr = 0; + string netmask = "0.0.0.0"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void ToNetmaskOORE1() { + byte cidr = 33; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + } + + #endregion + + #region ValidNetmask + + [TestMethod] + public void TestValidNetmask0() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask1() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask2() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + public void TestValidNetmaskEAE1() { + + IPAddress mask = IPAddress.Parse("0.255.0.0"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestValidNetmaskEAE2() { + + IPAddress mask = null; + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + public void TestValidNetmaskEAE3() { + + IPAddress mask = IPAddress.Parse("255.255.0.1"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + #endregion + + #region BitsSet + + [TestMethod] + public void TestBitsSet32() { + + IPAddress ip = IPAddress.Parse("255.255.255.255"); + uint bits = 32; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet24() { + + IPAddress ip = IPAddress.Parse("255.255.255.0"); + uint bits = 24; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet16() { + + IPAddress ip = IPAddress.Parse("255.255.0.0"); + uint bits = 16; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet4() { + + IPAddress ip = IPAddress.Parse("128.128.128.128"); + uint bits = 4; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + + #endregion + + #region Contains + + [TestMethod] + public void TestContains1() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/24"); + IPAddress ipaddress = IPAddress.Parse("192.168.0.100"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains2() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/24"); + IPAddress ipaddress = IPAddress.Parse("10.10.10.10"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains3() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.0.1/24"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains4() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/16"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.1/24"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains5() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/16"); + IPNetwork ipnetwork2 = IPNetwork.Parse("10.10.10.0/24"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + + [TestMethod] + public void TestContains6() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.0.0/16"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains7() + { + + IPNetwork ipnetwork = null; + IPNetwork ipnetwork2 = null; + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains8() + { + + IPNetwork ipnetwork = IPNetwork.Parse("0.0.0.0/0"); + IPNetwork ipnetwork2 = null; + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains9() + { + + IPNetwork ipnetwork = null; + IPAddress ipaddress = null; + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains10() + { + + IPNetwork ipnetwork = IPNetwork.Parse("0.0.0.0/0"); + IPAddress ipaddress = null; + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + + } + + #endregion + + #region Overlap + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestOverlap1() + { + IPNetwork network1 = null; + IPNetwork network2 = null; + IPNetwork.Overlap(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestOverlap2() + { + IPNetwork network1 = IPNetwork.Parse("10.0.0.0/0"); + IPNetwork network2 = null; + IPNetwork.Overlap(network1, network2); + } + + [TestMethod] + public void TestOverlap3() + { + IPNetwork network1 = IPNetwork.Parse("10.0.0.0/0"); + IPNetwork network2 = IPNetwork.Parse("10.0.0.0/0"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap4() + { + IPNetwork network1 = IPNetwork.Parse("10.10.0.0/16"); + IPNetwork network2 = IPNetwork.Parse("10.10.1.0/24"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap5() + { + IPNetwork network1 = IPNetwork.Parse("10.10.0.0/24"); + IPNetwork network2 = IPNetwork.Parse("10.10.1.0/24"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = false; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap6() + { + IPNetwork network1 = IPNetwork.Parse("10.10.1.0/24"); + IPNetwork network2 = IPNetwork.Parse("10.10.0.0/16"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + #endregion + + #region Examples + + public void Example1() + { + IPNetwork ipnetwork = IPNetwork.Parse("192.168.168.100/24"); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + public void Example2() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.0/24"); + IPAddress ipaddress = IPAddress.Parse("192.168.0.100"); + IPAddress ipaddress2 = IPAddress.Parse("192.168.1.100"); + + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.0.128/25"); + IPNetwork ipnetwork3 = IPNetwork.Parse("192.168.1.1/24"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + bool contains3 = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool contains4 = IPNetwork.Contains(ipnetwork, ipnetwork3); + + bool overlap1 = IPNetwork.Overlap(ipnetwork, ipnetwork2); + bool overlap2 = IPNetwork.Overlap(ipnetwork, ipnetwork3); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork2, contains3); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork3, contains4); + + + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork2, overlap1); + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork3, overlap2); + + + } + + public void Example2b() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("10.1.0.0/16"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.0/24"); + + IPAddress ipaddress1 = IPAddress.Parse("192.168.1.1"); + IPAddress ipaddress2 = IPAddress.Parse("192.168.2.100"); + IPAddress ipaddress3 = IPAddress.Parse("10.1.2.3"); + IPAddress ipaddress4 = IPAddress.Parse("10.4.5.6"); + + + bool contains1 = IPNetwork.Contains(ipnetwork2, ipaddress1); + bool contains2 = IPNetwork.Contains(ipnetwork2, ipaddress2); + bool contains3 = IPNetwork.Contains(ipnetwork1, ipaddress3); + bool contains4 = IPNetwork.Contains(ipnetwork1, ipaddress4); + + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork1, ipaddress1, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork1, ipaddress2, contains2); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork2, ipaddress3, contains3); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork2, ipaddress4, contains4); + + + } + + public void Example3() + { + + IPNetwork iana_a_block = IPNetwork.IANA_ABLK_RESERVED1; + IPNetwork iana_b_block = IPNetwork.IANA_BBLK_RESERVED1; + IPNetwork iana_c_block = IPNetwork.IANA_CBLK_RESERVED1; + + Console.WriteLine("IANA_ABLK_RESERVED1 is {0}", iana_a_block); + Console.WriteLine("IANA_BBLK_RESERVED1 is {0}", iana_b_block); + Console.WriteLine("IANA_CBLK_RESERVED1 is {0}", iana_c_block); + + } + + + public void Example4() + { + IPNetwork wholeInternet = IPNetwork.Parse("0.0.0.0/0"); + byte newCidr = 2; + IPNetworkCollection subneted = IPNetwork.Subnet(wholeInternet, newCidr); + + Console.WriteLine("{0} was subnetted into {1} subnets", wholeInternet, subneted.Count); + Console.WriteLine("First: {0}", subneted[0]); + Console.WriteLine("Last : {0}", subneted[subneted.Count - 1]); + Console.WriteLine("All :"); + + foreach (IPNetwork ipnetwork in subneted) + { + Console.WriteLine("{0}", ipnetwork); + } + } + + public void Example5() + { + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.0/24"); + IPNetwork[] ipnetwork3 = IPNetwork.Supernet(new[]{ipnetwork1, ipnetwork2}); + + Console.WriteLine("{0} + {1} = {2}", ipnetwork1, ipnetwork2, ipnetwork3[0]); + + } + + + + public void Example7() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.168.100/24"); + + IPAddress ipaddress = IPAddress.Parse("192.168.168.200"); + IPAddress ipaddress2 = IPAddress.Parse("192.168.0.200"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + + } + public void Example9() { + + IPNetwork network = IPNetwork.Parse("192.168.0.1"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.254"); + + IPNetwork ipnetwork = IPNetwork.Supernet(network, network2); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + + public void Example10() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/25"); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + #endregion + + #region IANA blocks + [TestMethod] + public void TestIANA1() { + + IPAddress ipaddress = IPAddress.Parse("192.168.66.66"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA2() { + + IPAddress ipaddress = IPAddress.Parse("10.0.0.0"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA3() { + + IPAddress ipaddress = IPAddress.Parse("172.17.10.10"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA4() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.66.66/24"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA5() { + + IPNetwork ipnetwork = IPNetwork.Parse("10.10.10/18"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA6() { + + IPNetwork ipnetwork = IPNetwork.Parse("172.31.10.10/24"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestIANA7() { + + IPAddress ipaddress = null; + IPNetwork.IsIANAReserved(ipaddress); + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestIANA8() { + + IPNetwork ipnetwork = null; + IPNetwork.IsIANAReserved(ipnetwork); + + + } + + + [TestMethod] + public void TestIANA9() { + + IPAddress ipaddress = IPAddress.Parse("1.2.3.4"); + bool expected = false; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA10() { + + IPNetwork ipnetwork = IPNetwork.Parse("172.16.0.0/8"); + bool expected = false; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + + [TestMethod] + public void TestIANA11() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/8"); + bool expected = false; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + #endregion + + #region ToString + + + [TestMethod] + public void TestToString() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/8"); + string expected = "192.0.0.0/8"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString1() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/9"); + string expected = "192.128.0.0/9"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString2() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/10"); + string expected = "192.128.0.0/10"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString3() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/11"); + string expected = "192.160.0.0/11"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString4() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/12"); + string expected = "192.160.0.0/12"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString5() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/13"); + string expected = "192.168.0.0/13"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString6() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/14"); + string expected = "192.168.0.0/14"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + [TestMethod] + public void TestToString7() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/15"); + string expected = "192.168.0.0/15"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString8() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/16"); + string expected = "192.168.0.0/16"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + #endregion + + #region Subnet + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestSubnet1() { + + IPNetwork ipnetwork = null; + byte cidr = 9; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet3() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 55; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSubnet4() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 1; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + public void TestSubnet5() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 9; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("10.0.0.0/9", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("10.128.0.0/9", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestSubnet6() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/20", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.16.0/20", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("192.168.32.0/20", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("192.168.48.0/20", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("192.168.64.0/20", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("192.168.80.0/20", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("192.168.96.0/20", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("192.168.112.0/20", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("192.168.128.0/20", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("192.168.144.0/20", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("192.168.160.0/20", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("192.168.176.0/20", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("192.168.192.0/20", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("192.168.208.0/20", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("192.168.224.0/20", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("192.168.240.0/20", subnets[15].ToString(), "subnet16"); + + } + + + [TestMethod] + public void TestSubnet7() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 24; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/24", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.255.0/24", subnets[255].ToString(), "subnet16"); + + } + + + [TestMethod] + public void TestSubnet8() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 24; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/24", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.255.0/24", subnets[255].ToString(), "subnet256"); + + } + + [TestMethod] + public void TestSubnet9() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.0/24"); + byte cidr = 32; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/32", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.0.255/32", subnets[255].ToString(), "subnet256"); + + } + + + [TestMethod] + public void TestSubnet10() + { + IPNetwork ipnetwork = IPNetwork.Parse("0.0.0.0/0"); + byte cidr = 32; + + // Here I spawm a OOM dragon ! beware of the beast ! + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(4294967296, subnets.Count, "count"); + Assert.AreEqual("0.0.0.0/32", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("255.255.255.255/32", subnets[4294967295].ToString(), "subnet256"); + + } + + + [TestMethod] + public void TestSubnet12() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + int i = -1; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + foreach (IPNetwork ipn in subnets) { + i++; + Assert.AreEqual(subnets[i], ipn, "subnet"); + } + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet13() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + IPNetwork error = subnets[1000]; + + } + + #endregion + + #region TrySubnet + + + [TestMethod] + public void TestTrySubnet1() { + + IPNetwork ipnetwork = null; + byte cidr = 9; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + + } + + [TestMethod] + public void TestTrySubnet3() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 55; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + } + + + [TestMethod] + public void TestTrySubnet4() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 1; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + + } + + + [TestMethod] + public void TestTrySubnet5() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 9; + + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("10.0.0.0/9", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("10.128.0.0/9", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestTrySubnet6() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/20", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.16.0/20", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("192.168.32.0/20", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("192.168.48.0/20", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("192.168.64.0/20", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("192.168.80.0/20", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("192.168.96.0/20", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("192.168.112.0/20", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("192.168.128.0/20", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("192.168.144.0/20", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("192.168.160.0/20", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("192.168.176.0/20", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("192.168.192.0/20", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("192.168.208.0/20", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("192.168.224.0/20", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("192.168.240.0/20", subnets[15].ToString(), "subnet16"); + + } + + + + #endregion + + #region Supernet + + [TestMethod] + public void TestSupernet1() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork expected = IPNetwork.Parse("192.168.0.0/23"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + Assert.AreEqual(expected, supernet, "supernet"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestSupernet2() { + + IPNetwork network1 = null; + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestSupernet3() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = null; + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSupernet4() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/25"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSupernet5() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.5.1/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + public void TestSupernet6() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork expected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + Assert.AreEqual(expected, supernet, "supernet"); + + } + + [TestMethod] + public void TestSupernet7() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork expected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + Assert.AreEqual(expected, supernet, "supernet"); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSupernet8() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + + } + + + [TestMethod] + public void TestSupernet9() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("200.16.0.0/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("200.16.1.0/24"); + IPNetwork ipnetwork3 = IPNetwork.Parse("200.16.2.0/24"); + IPNetwork ipnetwork4 = IPNetwork.Parse("200.16.3.0/24"); + + IPNetwork result = IPNetwork.Supernet(new[] { ipnetwork1, ipnetwork2, ipnetwork3, ipnetwork4 })[0]; + IPNetwork expected = IPNetwork.Parse("200.16.0.0/22"); + + Assert.AreEqual(expected, result, "supernet"); + + } + + #endregion + + #region TrySupernet + + + [TestMethod] + public void TestTrySupernet1() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork supernetExpected = IPNetwork.Parse("192.168.0.0/23"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet2() { + + IPNetwork network1 = null; + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet3() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = null; + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet4() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/25"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet5() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.5.1/24"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet6() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork supernetExpected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet7() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork supernetExpected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet8() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet9() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork[] network3 = new [] { network1, network2 }; + IPNetwork[] supernetExpected = new [] { network1, network2 }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(supernetExpected[1], supernet[1], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet10() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork[] network3 = new[] { network1, network2 }; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("192.168.0.0/23") }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet11() { + + IPNetwork[] network3 = null; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("192.168.0.0/23") }; + IPNetwork[] supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(null, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + #endregion + + #region SupernetArray + + [TestMethod] + public void TestTrySupernetArray() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.0/24"); + IPNetwork ipnetwork3 = IPNetwork.Parse("192.168.2.0/24"); + IPNetwork ipnetwork4 = IPNetwork.Parse("192.168.3.0/24"); + + IPNetwork[] ipnetworks = { ipnetwork1, ipnetwork2, ipnetwork3, ipnetwork4 }; + IPNetwork[] expected = { IPNetwork.Parse("192.168.0.0/22") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], expected[0], "suppernet"); + + } + + [TestMethod] + public void TestTrySupernetArray1() + { + + + IPNetwork[] ipnetworks = { }; + IPNetwork[] expected = { }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestTrySupernetArray2() + { + + + IPNetwork[] ipnetworks = null; + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + } + + + [TestMethod] + public void TestTrySupernetArray3() + { + + IPNetwork ipnetwork1 = null; + IPNetwork ipnetwork2 = null; + IPNetwork ipnetwork3 = null; + IPNetwork ipnetwork4 = null; + + IPNetwork[] ipnetworks = { ipnetwork1, ipnetwork2, ipnetwork3, ipnetwork4 }; + IPNetwork[] expected = { }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + + } + + [TestMethod] + public void TestTrySupernetArray4() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/24"); + IPNetworkCollection subnetted = IPNetwork.Subnet(ipnetwork1, 32); + IPNetwork[] ipnetworks = subnetted.ToArray(); + Assert.AreEqual(256, ipnetworks.Length, "subnet"); + + IPNetwork[] expected = { IPNetwork.Parse("192.168.0.0/24") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], ipnetwork1, "suppernet"); + } + + + [TestMethod] + public void TestTrySupernetArray5() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/16"); + IPNetworkCollection subnetted = IPNetwork.Subnet(ipnetwork1, 32); + IPNetwork[] ipnetworks = subnetted.ToArray(); + Assert.AreEqual(65536, ipnetworks.Length, "subnet"); + + IPNetwork[] expected = { IPNetwork.Parse("192.168.0.0/16") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], ipnetwork1, "suppernet"); + } + + public void TestTrySupernetArray6() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/8"); + IPNetworkCollection subnetted = IPNetwork.Subnet(ipnetwork1, 32); + IPNetwork[] ipnetworks = subnetted.ToArray(); + Assert.AreEqual(16777216, ipnetworks.Length, "subnet"); + + IPNetwork[] expected = { IPNetwork.Parse("192.0.0.0/8") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], ipnetwork1, "suppernet"); + } + + [TestMethod] + public void TestTrySupernetArray7() + { + + IPNetwork[] ipnetworks = { + IPNetwork.Parse("10.0.2.2/24"), + IPNetwork.Parse("192.168.0.0/24"), + IPNetwork.Parse("192.168.1.0/24"), + IPNetwork.Parse("192.168.2.0/24"), + IPNetwork.Parse("10.0.1.1/24"), + IPNetwork.Parse("192.168.3.0/24") + }; + + IPNetwork[] expected = { + IPNetwork.Parse("10.0.1.0/24"), + IPNetwork.Parse("10.0.2.0/24"), + IPNetwork.Parse("192.168.0/22") + }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], result[0], "suppernet"); + Assert.AreEqual(expected[1], result[1], "suppernet1"); + Assert.AreEqual(expected[2], result[2], "suppernet2"); + } + + [TestMethod] + public void TestTrySupernetArray8() + { + + IPNetwork[] ipnetworks = { + IPNetwork.Parse("10.0.2.2/24"), + IPNetwork.Parse("192.168.0.0/24"), + IPNetwork.Parse("192.168.1.0/24"), + IPNetwork.Parse("192.168.2.0/24"), + IPNetwork.Parse("10.0.1.1/24"), + IPNetwork.Parse("192.168.3.0/24"), + IPNetwork.Parse("10.6.6.6/8") + + }; + + IPNetwork[] expected = { + IPNetwork.Parse("10.0.0.0/8"), + IPNetwork.Parse("192.168.0/22") + }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], result[0], "suppernet"); + Assert.AreEqual(expected[1], result[1], "suppernet1"); + } + + + [TestMethod] + public void TestTrySupernetArray9() + { + + IPNetwork[] ipnetworks = { + IPNetwork.Parse("10.0.2.2/24"), + IPNetwork.Parse("192.168.0.0/24"), + IPNetwork.Parse("192.168.1.0/24"), + IPNetwork.Parse("192.168.2.0/24"), + IPNetwork.Parse("10.0.1.1/24"), + IPNetwork.Parse("192.168.3.0/24"), + IPNetwork.Parse("10.6.6.6/8"), + IPNetwork.Parse("11.6.6.6/8"), + IPNetwork.Parse("12.6.6.6/8"), + + }; + + IPNetwork[] expected = { + IPNetwork.Parse("10.0.0.0/7"), + IPNetwork.Parse("12.0.0.0/8"), + IPNetwork.Parse("192.168.0/22") + }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], result[0], "suppernet"); + Assert.AreEqual(expected[1], result[1], "suppernet1"); + Assert.AreEqual(expected[2], result[2], "suppernet2"); + } + + + #endregion + + #region Equals + + [TestMethod] + public void TestEquals1() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/24"); + bool result = network1.Equals(network2); + bool expected = true; + + Assert.AreEqual(expected, result, "equals"); + + } + + [TestMethod] + public void TestEquals2() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = null; + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + [TestMethod] + public void TestEquals3() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + object network2 = ""; + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + [TestMethod] + public void TestEquals4() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/25"); + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + + [TestMethod] + public void TestEquals5() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + #endregion + + #region WideSubnet + + [TestMethod] + public void TestWideSubnet1() { + + string start = "192.168.168.0"; + string end = "192.168.168.255"; + IPNetwork expected = IPNetwork.Parse("192.168.168.0/24"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestWideSubnet2() { + + string start = null; + string end = "192.168.168.255"; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestWideSubnet3() { + + string start = "192.168.168.255"; + string end = null; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + + } + + [TestMethod] + public void TestWideSubnet4() { + + string start = "192.168.168.255"; + string end = "192.168.168.0"; + + + IPNetwork expected = IPNetwork.Parse("192.168.168.0/24"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + } + + + [TestMethod] + public void TestWideSubnet7() { + + string start = "0.0.0.0"; + string end = "0.255.255.255"; + + IPNetwork expected = IPNetwork.Parse("0.0.0.0/8"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + } + + + + [TestMethod] + public void TestWideSubnet8() { + + string start = "1.2.3.4"; + string end = "5.6.7.8"; + + IPNetwork expected = IPNetwork.Parse("0.0.0.0/5"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + } + + + [TestMethod] + public void TestWideSubnet9() + { + + string start = "200.16.0.0/24"; + string end = "200.16.3.0/24"; + var firt = IPNetwork.Parse(start).FirstUsable.ToString(); + var last = IPNetwork.Parse(end).LastUsable.ToString(); + + IPNetwork expected = IPNetwork.Parse("200.16.0.0/22"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(firt, last); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + + + + } + + + [TestMethod] + public void TestWideSubnet10() + { + + string start = "200.16.0.0"; + string end = "200.16.3.255"; + + IPNetwork expected = IPNetwork.Parse("200.16.0.0/22"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestWideSubnetInvalid1() { + + string start = "invalid"; + string end = "5.6.7.8"; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestWideSubnetInvalid2() { + + string start = "1.2.3.4"; + string end = "invalid"; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + } + + #endregion + + #region TryGuessCidr + + [TestMethod] + public void TestTryGuessCidrNull() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr(null, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(0, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrA() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("10.0.0.0", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(8, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrB() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("172.0.0.0", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(16, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrC() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("192.0.0.0", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(24, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrD() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("224.0.0.0", out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + } + [TestMethod] + public void TestTryGuessCidrE() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("240.0.0.0", out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + } + + #endregion + + #region GetHashCode + + [TestMethod] + public void TestGetHashCode1() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("0.0.1.1/0"); + IPNetwork ipnetwork2 = IPNetwork.Parse("0.0.1.1/0"); + int hashCode1 = ipnetwork1.GetHashCode(); + int hashCode2 = ipnetwork2.GetHashCode(); + Assert.AreEqual(hashCode1, hashCode2, "hashcode"); + + } + + [TestMethod] + public void TestGetHashCode2() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("0.0.0.0/1"); + IPNetwork ipnetwork2 = IPNetwork.Parse("0.0.0.0/1"); + int hashCode1 = ipnetwork1.GetHashCode(); + int hashCode2 = ipnetwork2.GetHashCode(); + Assert.AreEqual(hashCode1, hashCode2, "hashcode"); + + } + [TestMethod] + public void TestGetHashCode3() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("0.0.0.0/32"); + IPNetwork ipnetwork2 = IPNetwork.Parse("0.0.0.0/32"); + int hashCode1 = ipnetwork1.GetHashCode(); + int hashCode2 = ipnetwork2.GetHashCode(); + Assert.AreEqual(hashCode1, hashCode2, "hashcode"); + + } + + #endregion + + #region Print + + [TestMethod] + public void Print() { + IPNetwork ipn = IPNetwork.Parse("0.0.0.0/0"); + string print = IPNetwork.Print(ipn).Replace("\r", ""); + string expected = @"IPNetwork : 0.0.0.0/0 +Network : 0.0.0.0 +Netmask : 0.0.0.0 +Cidr : 0 +Broadcast : 255.255.255.255 +FirstUsable : 0.0.0.1 +LastUsable : 255.255.255.254 +Usable : 4294967294 +".Replace("\r", ""); + + Assert.AreEqual(expected, print, "Print"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void PrintNull() { + IPNetwork ipn = null; + string print = IPNetwork.Print(ipn); + } + + #endregion + + #region Sort + + [TestMethod] + public void TestSort1() { + string[] ips = new[] { "1.1.1.1", "255.255.255.255", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach(string ip in ips) { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) { + ipns.Add(ipn); + } + } + + ipns.Sort(); + Assert.AreEqual("0.0.0.0/32", ipns[0].ToString(), "0"); + Assert.AreEqual("1.1.1.1/32", ipns[1].ToString(), "1"); + Assert.AreEqual("2.2.2.2/32", ipns[2].ToString(), "2"); + Assert.AreEqual("255.255.255.255/32", ipns[3].ToString(), "3"); + } + + [TestMethod] + public void TestSort2() { + string[] ips = new[] { "0.0.0.100/32", "0.0.0.0/24" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, out ipn)) { + ipns.Add(ipn); + } + } + + ipns.Sort(); + Assert.AreEqual("0.0.0.0/24", ipns[0].ToString(), "0"); + Assert.AreEqual("0.0.0.100/32", ipns[1].ToString(), "1"); + } + + #endregion + + #region TryWideSubnet + + [TestMethod] + public void TryWideSubnet1() { + string[] ips = new[] { "1.1.1.1", "255.255.255.255", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(true, wide, "wide"); + Assert.AreEqual("0.0.0.0/0", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + public void TryWideSubnet2() { + string[] ips = new[] { "1.1.1.1", "10.0.0.0", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(true, wide, "wide"); + Assert.AreEqual("0.0.0.0/4", ipnetwork.ToString(), "ipnetwork"); + + } + + + [TestMethod] + public void TryWideSubnet3() { + string[] ips = new[] { "a", "b", "c", "d" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(false, wide, "wide"); + + } + + [TestMethod] + public void TryWideSubnet4() { + string[] ips = new[] { "a", "b", "1.1.1.1", "d" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(true, wide, "wide"); + Assert.AreEqual("1.1.1.1/32", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + public void TryWideSubnetNull() { + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(null, out ipnetwork); + Assert.AreEqual(false, wide, "wide"); + + } + + #endregion + + #region WideSubnet + + [TestMethod] + public void WideSubnet1() { + string[] ips = new[] { "1.1.1.1", "255.255.255.255", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = IPNetwork.WideSubnet(ipns.ToArray()); + Assert.AreEqual("0.0.0.0/0", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + public void WideSubnet2() { + string[] ips = new[] { "1.1.1.1", "10.0.0.0", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = IPNetwork.WideSubnet(ipns.ToArray()); + Assert.AreEqual("0.0.0.0/4", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void WideSubnetNull() { + + IPNetwork ipnetwork = IPNetwork.WideSubnet(null); + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void WideSubnetNull2() { + + string[] ips = new[] { "a", "b", "e", "d" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = IPNetwork.WideSubnet(ipns.ToArray()); + + + } + + #endregion + + /** + * + #region TrySubstractNetwork + + + [TestMethod] + public void TrySubstractNetwork1() { + string[] ips = new[] { "178.82.0.0/16" }; + string substract = "178.82.131.209/32"; + + List ipns = new List(); + Array.ForEach(ips, new Action( + delegate(string ip) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, out ipn)) { + ipns.Add(ipn); + } + } + )); + + var nsubstract = IPNetwork.Parse(substract); + + IEnumerable result; + bool substracted = IPNetwork.TrySubstractNetwork(ipns.ToArray(), nsubstract, out result); + Assert.AreEqual(true, substracted, "substracted"); + + } + + [TestMethod] + public void TrySubstractNetwork2() { + string[] ips = new[] { "0.0.0.0/0" }; + string substract = "1.1.1.1/32"; + + List ipns = new List(); + Array.ForEach(ips, new Action( + delegate(string ip) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, out ipn)) { + ipns.Add(ipn); + } + } + )); + + var nsubstract = IPNetwork.Parse(substract); + + IEnumerable result; + bool substracted = IPNetwork.TrySubstractNetwork(ipns.ToArray(), nsubstract, out result); + Assert.AreEqual(true, substracted, "substracted"); + + } + + + + #endregion + **/ + + #region Count + + [TestMethod] + public void Total32() { + var network = IPNetwork.Parse("0.0.0.0/32"); + var total = 1; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total31() { + var network = IPNetwork.Parse("0.0.0.0/31"); + var total = 2; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total30() { + var network = IPNetwork.Parse("0.0.0.0/30"); + var total = 4; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total24() { + var network = IPNetwork.Parse("0.0.0.0/24"); + var total = 256; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total16() { + var network = IPNetwork.Parse("0.0.0.0/16"); + var total = 65536; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total8() { + var network = IPNetwork.Parse("0.0.0.0/8"); + var total = 16777216; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total0() { + var network = IPNetwork.Parse("0.0.0.0/0"); + var total = 4294967296; + Assert.AreEqual(total, network.Total, "Total"); + } + + #endregion + + #region Usable + + [TestMethod] + public void Usable32() { + var network = IPNetwork.Parse("0.0.0.0/32"); + uint usable = 0; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable31() { + var network = IPNetwork.Parse("0.0.0.0/31"); + uint usable = 0; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable30() { + var network = IPNetwork.Parse("0.0.0.0/30"); + uint usable = 2; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable24() { + var network = IPNetwork.Parse("0.0.0.0/24"); + uint usable = 254; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable16() { + var network = IPNetwork.Parse("0.0.0.0/16"); + uint usable = 65534; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable8() { + var network = IPNetwork.Parse("0.0.0.0/8"); + uint usable = 16777214; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable0() { + var network = IPNetwork.Parse("0.0.0.0/0"); + uint usable = 4294967294; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + #endregion + + #region TryParseCidr + + [TestMethod] + public void TryParseCidr1() { + + string sidr = "0"; + byte? cidr; + byte? result = 0; + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetwork, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr2() { + + string sidr = "sadsd"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetwork, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr3() { + + string sidr = "33"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetwork, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + #endregion + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource subnets of type System.Net.IPNetworkCollection in method "Void IPNetworkUnitTest.TestSubnet12()". + +### Severity: +ERROR + +### Procedure: +Void IPNetworkUnitTest.TestSubnet12() + +### File: +src/System.Net.IPNetwork.TestProject.Source/IPNetworkUnitTest.cs + +### Key: +IPNetworkUnitTest.cs|TestSubnet12|DOTNET_RESOURCE_LEAK + +### Hash: +1c4ba4beee9cb1fa2ed7feb64f63e13e + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1621/instruction.md b/inferredbugs-1621/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..458a57d135536c81a39fbaa9e29f827e85336a77 --- /dev/null +++ b/inferredbugs-1621/instruction.md @@ -0,0 +1,2546 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ipnetwork +**Bug ID:** 10 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Numerics; + +namespace System.Net.TestProject +{ + [TestClass] + public class IPNetworkV6UnitTest { + + #region ParseIP + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE8() { + IPNetwork ipnet = IPNetwork.Parse("xxxx::", "xxxx::"); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE9() { + IPNetwork ipnet = IPNetwork.Parse("::", "xxxx::"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE10() { + IPNetwork ipnet = IPNetwork.Parse("xxxx::", 0); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE11() { + IPNetwork ipnet = IPNetwork.Parse("::", 129); + + } + + [TestMethod] + public void TestParsev6_128() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + //string broadcast = "2001:db8::"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::"; + byte cidr = 128; + BigInteger usable = 1; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_127() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"; + //string broadcast = "2001:db8::1"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::1"; + byte cidr = 127; + BigInteger usable = 2; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_126() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"; + //string broadcast = "2001:db8::3"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::3"; + byte cidr = 126; + BigInteger usable = 4; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_125() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"; + //string broadcast = "2001:db8::7"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::7"; + byte cidr = 125; + BigInteger usable = 8; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_124() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + //string broadcast = "2001:db8::f"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::f"; + byte cidr = 124; + BigInteger usable = 16; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParsev6_123() { + + + IPNetwork ipnetwork = null; + string ipaddress = "2001:0db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"; + + string network = "2001:db8::"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"; + //string broadcast = "2001:db8::1f"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::1f"; + byte cidr = 123; + BigInteger usable = 32; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + + [TestMethod] + public void TestParsev6_112() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"; + + string network = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"; + string netmask2 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"; + //string broadcast = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 112; + uint usable = 65536; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_64() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:1234:1234:1234:1234"; + string netmask = "ffff:ffff:ffff:ffff:0000:0000:0000:0000"; + + string network = "ffff:ffff:ffff:ffff::"; + string netmask2 = "ffff:ffff:ffff:ffff::"; + //string broadcast = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 64; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)) ; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParsev6_16() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:0000:0000:0000:0000:0000:0000:0000"; + + string network = "ffff::"; + string netmask2 = "ffff::"; + //string broadcast = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 16; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)) ; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask2, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + + [TestMethod] + public void TestParsev6_EDGE() { + + + IPNetwork ipnetwork = null; + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + + string network = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 128; + uint usable = 1; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + #endregion + + #region ParseString + + [TestMethod] + public void TestParseString1() { + + string ipaddress = "2001:0db8:: ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + + string network = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::f"; + byte cidr = 124; + uint usable = 16; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParseString3() { + + string ipaddress = ":: ::"; + + string network = "::"; + string netmask = "::"; + string firstUsable = "::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 0; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)); + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParseString4() { + + string ipaddress = "::/0"; + + string network = "::"; + string netmask = "::"; + string firstUsable = "::"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 0; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)); + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString5() { + + string ipaddress = "::/32"; + + string network = "::"; + string netmask = "ffff:ffff::"; + string firstUsable = "::"; + string lastUsable = "::ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 32; + BigInteger usable = BigInteger.Pow(2, (128 - cidr)) ; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString6() + { + + string ipaddress = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128"; + + string network = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string firstUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string lastUsable = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + byte cidr = 128; + uint usable = 1; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString7_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFF:123::/60"; + + string network = "2fff:ffff:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:ffff:123::"; + string lastUsable = "2fff:ffff:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + [TestMethod] + public void TestParseString8_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFE:123::/60"; + + string network = "2fff:fffe:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:fffe:123::"; + string lastUsable = "2fff:fffe:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + + } + + [TestMethod] + public void TestParseString9_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFC:123::/60"; + + string network = "2fff:fffc:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:fffc:123::"; + string lastUsable = "2fff:fffc:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString10_Uppercase_ipv6_must_parse() + { + + string ipaddress = "2FFF:FFFA:123::/60"; + + string network = "2fff:fffa:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "2fff:fffa:123::"; + string lastUsable = "2fff:fffa:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString11_Uppercase_ipv6_must_parse() + { + + string ipaddress = "FFFF:FFF1:123::/60"; + + string network = "ffff:fff1:123::"; + string netmask = "ffff:ffff:ffff:fff0::"; + string firstUsable = "ffff:fff1:123::"; + string lastUsable = "ffff:fff1:123:f:ffff:ffff:ffff:ffff"; + byte cidr = 60; + // BigInteger usable = 295147905179352825856; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + //Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseIPAddressNoNetmask1() { + + string ipaddress = "2001:0db8::"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + + string network = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff::"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::ffff:ffff:ffff:ffff"; + byte cidr = 64; + var usable = BigInteger.Pow(2, 64); + + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + [TestMethod] + public void TestParseIPAddressNoNetmask4() { + + string ipaddress = "::"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + + + string network = "::"; + string netmask = "ffff:ffff:ffff:ffff::"; + string firstUsable = "::"; + string lastUsable = "::ffff:ffff:ffff:ffff"; + byte cidr = 64; + var usable = BigInteger.Pow(2, 64); + + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + [TestMethod] + public void TestParseIPAddressNoNetmask5() { + + string ipaddress = "2001:0db8::1"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + string network = "2001:db8::"; + string netmask = "ffff:ffff:ffff:ffff::"; + string firstUsable = "2001:db8::"; + string lastUsable = "2001:db8::ffff:ffff:ffff:ffff"; + byte cidr = 64; + var usable = BigInteger.Pow(2, 64); + + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(null, ipnetwork.Broadcast, "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE1() { + string ipaddress = "garbage"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE2() { + string ipaddress = "0:0:0:0:0:0:1:0:0 0:1:2:3:4:5:6:7:8"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringANE1() { + string ipaddress = null; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + + #endregion + + #region ParseStringString + + [TestMethod] + public void TestParseStringString1() { + + string ipaddress = "2001:0db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + Assert.AreEqual("2001:db8::/124", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString3() { + + string ipaddress = "2001:0db8::"; + string netmask = null; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString5() { + + string ipaddress = "2001:0db8::"; + string netmask = ""; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + #endregion + + #region ParseIpIp + + [TestMethod] + public void ParseIpIp1() { + + string ipaddress = "2001:0db8::"; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = IPAddress.Parse(netmask); + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + Assert.AreEqual("2001:db8::/124", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void ParseIpIp3() { + + string ipaddress = "2001:0db8::"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = null; + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + + } + + #endregion + + #region ToCidr + + [TestMethod] + public void TestToCidrAE() { + byte cidr = IPNetwork.ToCidr(IPAddress.IPv6Any); + Assert.AreEqual(0, cidr, "cidr"); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestToCidrAE2() { + IPNetwork.ToCidr(IPAddress.Parse("2001:db8:3:4:5:6:7:8")); + } + + + [TestMethod] + public void TestToCidr128() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + byte cidr = 128; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr127() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"); + byte cidr = 127; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr126() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"); + byte cidr = 126; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr125() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"); + byte cidr = 125; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr124() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + byte cidr = 124; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr123() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"); + byte cidr = 123; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr122() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffc0"); + byte cidr = 122; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr121() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff80"); + byte cidr = 121; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr120() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00"); + byte cidr = 120; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr119() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fe00"); + byte cidr = 119; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr118() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fc00"); + byte cidr = 118; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr117() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f800"); + byte cidr = 117; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr116() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f000"); + byte cidr = 116; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr115() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:e000"); + byte cidr = 115; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr114() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:c000"); + byte cidr = 114; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr113() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:8000"); + byte cidr = 113; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr112() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + byte cidr = 112; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr111() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffe:0"); + byte cidr = 111; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr110() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffc:0"); + byte cidr = 110; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestToCidr109() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff8:0"); + byte cidr = 109; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr108() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff0:0"); + byte cidr = 108; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr001() { + + IPAddress mask = IPAddress.Parse("8000::"); + byte cidr = 1; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr000() { + + IPAddress mask = IPAddress.Parse("::"); + byte cidr = 0; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + #endregion + + #region TryToCidr + + + [TestMethod] + public void TestTryToCidr128() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + byte cidr = 128; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + + [TestMethod] + public void TestTryToCidr127() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"); + byte cidr = 127; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr126() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"); + byte cidr = 126; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr125() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8"); + byte cidr = 125; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr124() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + byte cidr = 124; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr123() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffe0"); + byte cidr = 123; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr122() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffc0"); + byte cidr = 122; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr121() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff80"); + byte cidr = 121; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr120() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00"); + byte cidr = 120; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr119() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fe00"); + byte cidr = 119; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr118() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fc00"); + byte cidr = 118; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr117() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f800"); + byte cidr = 117; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr116() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:f000"); + byte cidr = 116; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr115() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:e000"); + byte cidr = 115; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr114() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:c000"); + byte cidr = 114; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr113() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:8000"); + byte cidr = 113; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr112() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + byte cidr = 112; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr111() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffe:0"); + byte cidr = 111; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr110() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fffc:0"); + byte cidr = 110; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + [TestMethod] + public void TestTryToCidr109() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff8:0"); + byte cidr = 109; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr108() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:fff0:0"); + byte cidr = 108; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr001() { + + IPAddress mask = IPAddress.Parse("8000::"); + byte cidr = 1; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr000() { + + IPAddress mask = IPAddress.Parse("::"); + byte cidr = 0; + byte? result = 0; + var parsed = IPNetwork.TryToCidr(mask, out result); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + + #endregion + + #region ToBigInteger + + [TestMethod] + public void TestToBigInteger32() { + + IPAddress mask = IPAddress.Parse("::f"); + uint uintMask = 0xf; + BigInteger result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger24() { + + IPAddress mask = IPAddress.Parse("::fff"); + uint uintMask = 0xfff; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger16() { + + IPAddress mask = IPAddress.Parse("::ff"); + uint uintMask = 0xff; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger8() { + + IPAddress mask = IPAddress.Parse("::ff00:0"); + uint uintMask = 0xff000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger0() { + + IPAddress mask = IPAddress.Parse("::"); + uint uintMask = 0x00000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + + #endregion + + #region TryToBigInteger + + [TestMethod] + public void TestTryToBigInteger32() { + + IPAddress mask = IPAddress.Parse("::ffff:ffff"); + uint uintMask = 0xffffffff; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger24() { + + IPAddress mask = IPAddress.Parse("::ffff:ff00"); + uint uintMask = 0xffffff00; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger16() { + + IPAddress mask = IPAddress.Parse("::ffff:0"); + uint uintMask = 0xffff0000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger8() { + + IPAddress mask = IPAddress.Parse("::ff00:0"); + uint uintMask = 0xff000000; + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger0() { + + IPAddress mask = IPAddress.Parse("::"); + uint uintMask = 0x00000000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + + #endregion + + #region TryToNetmask + [TestMethod] + public void TryToNetmask1() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(0, Sockets.AddressFamily.InterNetworkV6, out result); + IPAddress expected = IPAddress.Parse("::"); + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(true, parsed, "parsed"); + + } + + [TestMethod] + public void TryToNetmask2() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(33, Sockets.AddressFamily.InterNetworkV6, out result); + IPAddress expected = IPAddress.Parse("ffff:ffff:8000::"); + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(true, parsed, "parsed"); + + } + + #endregion + + #region ToNetmask + + [TestMethod] + public void ToNetmask128() { + + byte cidr = 128; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask31() { + + byte cidr = 127; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask30() { + + byte cidr = 126; + string netmask = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffc"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask1() { + + byte cidr = 1; + string netmask = "8000::"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + + [TestMethod] + public void ToNetmask0() { + + byte cidr = 0; + string netmask = "::"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void ToNetmaskOORE1() { + byte cidr = 129; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetworkV6).ToString(); + } + + #endregion + + #region ValidNetmask + + [TestMethod] + public void TestValidNetmask0() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask1() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask2() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + public void TestValidNetmaskEAE1() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:0000:ffff"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmaskEAE3() { + + IPAddress mask = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:0000:0001"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + #endregion + + #region BitsSet + + [TestMethod] + public void TestBitsSet128() { + + IPAddress ip = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); + uint bits = 128; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet120() { + + IPAddress ip = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0"); + uint bits = 124; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet16() { + + IPAddress ip = IPAddress.Parse("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0000"); + uint bits = 112; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet4() { + + IPAddress ip = IPAddress.Parse("f0f0:f0f0:f0f0:f0f0:f0f0:f0f0:f0f0:f0f0"); + uint bits = 64; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + + #endregion + + #region Contains + + [TestMethod] + public void TestContains1() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPAddress ipaddress = IPAddress.Parse("2001:0db8::1"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains2() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPAddress ipaddress = IPAddress.Parse("2001:0db8:0:1::"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains3() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::/64"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains4() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::/65"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains5() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8:1::/65"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + + [TestMethod] + public void TestContains6() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::/63"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains10() + { + + IPNetwork ipnetwork = IPNetwork.Parse("::/0"); + IPAddress ipaddress = null; + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + + } + + [TestMethod] + public void TestContains11_different_adress_family_returns_false() + { + + IPNetwork ipnetwork = IPNetwork.Parse("::1"); // IPv6 + IPAddress ipaddress = IPAddress.Parse("127.0.0.1"); // IPv4 + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + Assert.AreEqual(false, result, "contains"); + + } + + #endregion + + #region Overlap + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestOverlap2() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8::/0"); + IPNetwork network2 = null; + IPNetwork.Overlap(network1, network2); + } + + [TestMethod] + public void TestOverlap3() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8::/64"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap4() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8:0:0:1::/65"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap5() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8:0:1::/68"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8:0:2::/68"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = false; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap6() { + IPNetwork network1 = IPNetwork.Parse("2001:0db8:0:1::/68"); + IPNetwork network2 = IPNetwork.Parse("2001:0db8:0:2::/62"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + #endregion + + #region Examples + + public void Example1() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + public void Example2() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64"); + + IPAddress ipaddress = IPAddress.Parse("2001:0db8::1"); + IPAddress ipaddress2 = IPAddress.Parse("2001:0db9::1"); + + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db8::1/128"); + IPNetwork ipnetwork3 = IPNetwork.Parse("2001:0db9::1/64"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + bool contains3 = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool contains4 = IPNetwork.Contains(ipnetwork, ipnetwork3); + + bool overlap1 = IPNetwork.Overlap(ipnetwork, ipnetwork2); + bool overlap2 = IPNetwork.Overlap(ipnetwork, ipnetwork3); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork2, contains3); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork3, contains4); + + + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork2, overlap1); + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork3, overlap2); + + + } + + public void Example4() { + IPNetwork wholeInternet = IPNetwork.Parse("::/0"); + byte newCidr = 2; + IPNetworkCollection subneted = IPNetwork.Subnet(wholeInternet, newCidr); + + Console.WriteLine("{0} was subnetted into {1} subnets", wholeInternet, subneted.Count); + Console.WriteLine("First: {0}", subneted[0]); + Console.WriteLine("Last : {0}", subneted[subneted.Count - 1]); + Console.WriteLine("All :"); + + foreach (IPNetwork ipnetwork in subneted) { + Console.WriteLine("{0}", ipnetwork); + } + } + + public void Example5() { + IPNetwork ipnetwork1 = IPNetwork.Parse("2001:0db8::/64"); + IPNetwork ipnetwork2 = IPNetwork.Parse("2001:0db9::/64"); + IPNetwork[] ipnetwork3 = IPNetwork.Supernet(new[] { ipnetwork1, ipnetwork2 }); + + Console.WriteLine("{0} + {1} = {2}", ipnetwork1, ipnetwork2, ipnetwork3[0]); + + } + public void Example6() { + + IPNetwork ipnetwork = IPNetwork.Parse("fe80::202:b3ff:fe1e:8329/24"); + + IPAddress ipaddress = IPAddress.Parse("2001:db8::"); + IPAddress ipaddress2 = IPAddress.Parse("fe80::202:b3ff:fe1e:1"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + + } + + + + public void Example8() { + + IPNetwork network = IPNetwork.Parse("::/124"); + IPNetworkCollection ips = IPNetwork.Subnet(network, 128); + + foreach (IPNetwork ip in ips) { + Console.WriteLine("{0}", ip); + } + } + + + #endregion + + #region ToString + + + [TestMethod] + public void TestToString() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:0000:0000:0000:0000:0000:0000/32"); + string expected = "2001:db8::/32"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString1() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:1:2:3:4:5:6/32"); + string expected = "2001:db8::/32"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString2() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:1:2:3:4:5:6/64"); + string expected = "2001:db8:1:2::/64"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString3() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8:1:2:3:4:5:6/100"); + string expected = "2001:db8:1:2:3:4::/100"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + #endregion + + + #region Subnet + + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet3() { + + IPNetwork ipnetwork = IPNetwork.Parse("::"); + byte cidr = 129; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSubnet4() { + + IPNetwork ipnetwork = IPNetwork.Parse("::"); + byte cidr = 1; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + public void TestSubnet5() { + + IPNetwork ipnetwork = IPNetwork.Parse("1:1:1:1:1:1:1:1"); + byte cidr = 65; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("1:1:1:1::/65", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("1:1:1:1:8000::/65", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestSubnet6() { + + IPNetwork ipnetwork = IPNetwork.Parse("1:1:1:1:1:1:1:1"); + byte cidr = 68; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("1:1:1:1::/68", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("1:1:1:1:1000::/68", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("1:1:1:1:2000::/68", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("1:1:1:1:3000::/68", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("1:1:1:1:4000::/68", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("1:1:1:1:5000::/68", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("1:1:1:1:6000::/68", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("1:1:1:1:7000::/68", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("1:1:1:1:8000::/68", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("1:1:1:1:9000::/68", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("1:1:1:1:a000::/68", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("1:1:1:1:b000::/68", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("1:1:1:1:c000::/68", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("1:1:1:1:d000::/68", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("1:1:1:1:e000::/68", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("1:1:1:1:f000::/68", subnets[15].ToString(), "subnet16"); + + } + + + [TestMethod] + public void TestSubnet7() { + + IPNetwork ipnetwork = IPNetwork.Parse("1:1:1:1:1:1:1:1"); + byte cidr = 72; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("1:1:1:1::/72", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("1:1:1:1:ff00::/72", subnets[255].ToString(), "subnet256"); + + } + + + [TestMethod] + public void TestSubnet9() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08:1:1:1:1:1:1"); + byte cidr = 128; + var count = BigInteger.Pow(2, ipnetwork.Cidr); + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(count, subnets.Count, "count"); + Assert.AreEqual("2001:db08:1:1::/128", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("2001:db08:1:1::ff/128", subnets[255].ToString(), "subnet256"); + Assert.AreEqual("2001:db08:1:1:ffff:ffff:ffff:ffff/128", subnets[count-1].ToString(), "last"); + + } + + + [TestMethod] + public void TestSubnet10() { + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/0"); + byte cidr = 128; + var count = BigInteger.Pow(2, 128-ipnetwork.Cidr); + + // Here I spawm a OOM dragon ! beware of the beast ! + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(count, subnets.Count, "count"); + Assert.AreEqual("::/128", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128", subnets[count - 1].ToString(), "last"); + + } + + + [TestMethod] + public void TestSubnet12() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 70; + int i = -1; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + foreach (IPNetwork ipn in subnets) { + i++; + Assert.AreEqual(subnets[i], ipn, "subnet"); + } + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet13() + { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 70; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + IPNetwork error = subnets[1000]; + + } + + + + [TestMethod] + public void TestSubnet14() + { + + IPNetwork network = IPNetwork.Parse("15.0.0.0/8"); + var subnets = IPNetwork.Subnet(network, (byte)12); + Assert.AreEqual(subnets[0].ToString(), "15.0.0.0/12", "subnets[0]"); + Assert.AreEqual(subnets[1].ToString(), "15.16.0.0/12", "subnets[1]"); + Assert.AreEqual(subnets[2].ToString(), "15.32.0.0/12", "subnets[2]"); + Assert.AreEqual(subnets[15].ToString(), "15.240.0.0/12", "subnets[15]"); + + foreach (IPNetwork ipn in subnets) + { + Console.WriteLine(ipn); + } + } + + + + #endregion + + #region TrySubnet + + + [TestMethod] + public void TestTrySubnet3() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 255; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + } + + + [TestMethod] + public void TestTrySubnet4() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); + byte cidr = 63; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + + } + + + [TestMethod] + public void TestTrySubnet5() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db8::/64"); + byte cidr = 65; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("2001:db8::/65", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("2001:db8:0:0:8000::/65", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestTrySubnet6() { + + IPNetwork ipnetwork = IPNetwork.Parse("2001:db8::/64"); + byte cidr = 68; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("2001:db8::/68", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("2001:db8:0:0:1000::/68", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("2001:db8:0:0:2000::/68", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("2001:db8:0:0:3000::/68", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("2001:db8:0:0:4000::/68", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("2001:db8:0:0:5000::/68", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("2001:db8:0:0:6000::/68", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("2001:db8:0:0:7000::/68", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("2001:db8:0:0:8000::/68", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("2001:db8:0:0:9000::/68", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("2001:db8:0:0:a000::/68", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("2001:db8:0:0:b000::/68", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("2001:db8:0:0:c000::/68", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("2001:db8:0:0:d000::/68", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("2001:db8:0:0:e000::/68", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("2001:db8:0:0:f000::/68", subnets[15].ToString(), "subnet16"); + + } + + + + #endregion + + + + + + + #region TrySupernet + + + [TestMethod] + public void TestTrySupernet1() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/65"); + IPNetwork network2 = IPNetwork.Parse("2001:db8:0:0:8000::/65"); + IPNetwork supernetExpected = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernet; + bool supernetted = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetted, result, "supernetted"); + Assert.AreEqual(supernetExpected, supernet, "supernet"); + + } + + [TestMethod] + public void TestTrySupernet2() { + + IPNetwork network1 = null; + IPNetwork network2 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet3() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = null; + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet4() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:db9::/65"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet5() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:dba::/64"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet6() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:db8::1/65"); + IPNetwork supernetExpected = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet7() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:db8::1/65"); + IPNetwork supernetExpected = IPNetwork.Parse("2001:db8::/64"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet8() { + + IPNetwork network1 = IPNetwork.Parse("2001:db0::/64"); + IPNetwork network2 = IPNetwork.Parse("2001:dbf::/64"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet9() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork[] network3 = new[] { network1, network2 }; + IPNetwork[] supernetExpected = new[] { network1, network2 }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(supernetExpected[1], supernet[1], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet10() { + + IPNetwork network1 = IPNetwork.Parse("2001:db8:0000::/65"); + IPNetwork network2 = IPNetwork.Parse("2001:db8:0:0:8000::/65"); + IPNetwork[] network3 = new[] { network1, network2 }; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("2001:db8::/64") }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet11() { + + IPNetwork[] network3 = null; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("2001:db8::/64") }; + IPNetwork[] supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(null, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + #endregion + + + + + + + + #region TryGuessCidr + + [TestMethod] + public void TestTryGuessCidrNull() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr(null, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(0, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidr1() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("::", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(64, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidr2() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("2001:0db8::", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(64, cidr, "cidr"); + } + + + #endregion + + + + + #region Count + + [TestMethod] + public void Total32() { + var network = IPNetwork.Parse("::/128"); + var total = 1; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total31() { + var network = IPNetwork.Parse("::/127"); + var total = 2; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total30() { + var network = IPNetwork.Parse("::/126"); + var total = 4; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total24() { + var network = IPNetwork.Parse("::/120"); + var total = 256; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total16() { + var network = IPNetwork.Parse("::/112"); + var total = 65536; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total8() { + var network = IPNetwork.Parse("::/104"); + var total = 16777216; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total0() { + var network = IPNetwork.Parse("::/0"); + var total = BigInteger.Pow(2, 128); + Assert.AreEqual(total, network.Total, "Total"); + } + + #endregion + + #region Usable + + [TestMethod] + public void Usable32() { + var network = IPNetwork.Parse("::/128"); + uint usable = 1; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable31() { + var network = IPNetwork.Parse("::/127"); + uint usable = 2; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable30() { + var network = IPNetwork.Parse("::/126"); + uint usable = 4; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable24() { + var network = IPNetwork.Parse("::/120"); + uint usable = 256; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable16() { + var network = IPNetwork.Parse("::/112"); + uint usable = 65536; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable8() { + var network = IPNetwork.Parse("::/104"); + uint usable = 16777216; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable0() { + var network = IPNetwork.Parse("::/0"); + var usable = BigInteger.Pow(2, 128); + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + #endregion + + #region TryParseCidr + + [TestMethod] + public void TryParseCidr1() { + + string sidr = "0"; + byte? cidr; + byte? result = 0; + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr2() { + + string sidr = "sadsd"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr33() { + + string sidr = "33"; + byte? cidr; + byte result = 33; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr128() { + + string sidr = "128"; + byte? cidr; + byte result = 128; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + [TestMethod] + public void TryParseCidr129() { + + string sidr = "129"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetworkV6, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + #endregion + + + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`subneted` could be null (from the call to `IPNetwork.Subnet(...)` on line 1748) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +Void IPNetworkV6UnitTest.Example4() + +### File: +src/System.Net.IPNetwork.TestProject.Source/IPNetworkV6UnitTest.cs + +### Key: +IPNetworkV6UnitTest.cs|Example4|NULLPTR_DEREFERENCE + +### Hash: +a3802d7902eec327e94bdca3ce0f9d14 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1627/instruction.md b/inferredbugs-1627/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..facfe4dc3a0b2e13084a63b3ffa493d961dfbab5 --- /dev/null +++ b/inferredbugs-1627/instruction.md @@ -0,0 +1,3382 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ipnetwork +**Bug ID:** 36 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; + +namespace System.Net.TestProject +{ + /// + /// IPNetworkUnitTest test every single method + /// + [TestClass] + public class IPNetworkUnitTest { + + #region Parse + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE2() { + IPAddress ip = null; + IPNetwork.Parse(ip, ip); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE3() { + IPNetwork.Parse("", 0); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE4() { + IPNetwork.Parse(null, 0); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE5() { + string n = null; + IPNetwork.Parse(n, n); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE8() { + IPNetwork ipnet = IPNetwork.Parse("x.x.x.x", "x.x.x.x"); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE9() { + IPNetwork ipnet = IPNetwork.Parse("0.0.0.0", "x.x.x.x"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE10() { + IPNetwork ipnet = IPNetwork.Parse("x.x.x.x", 0); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE11() { + IPNetwork ipnet = IPNetwork.Parse("0.0.0.0", 33); + + } + + [TestMethod] + public void TestParseIPAddressNetmask() { + + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + + string network = "192.168.168.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString1() { + + string ipaddress = "192.168.168.100 255.255.255.0"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString2() { + + string ipaddress = "192.168.168.100/24"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString3() { + + string ipaddress = "0.0.0.0/0"; + + string network = "0.0.0.0"; + string netmask = "0.0.0.0"; + string broadcast = "255.255.255.255"; + string firstUsable = "0.0.0.1"; + string lastUsable = "255.255.255.254"; + byte cidr = 0; + uint usable = 4294967294; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString4() { + + string ipaddress = "0.0.0.0/32"; + + string network = "0.0.0.0"; + string netmask = "255.255.255.255"; + string broadcast = "0.0.0.0"; + string firstUsable = "0.0.0.0"; + string lastUsable = "0.0.0.0"; + byte cidr = 32; + uint usable = 0; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString5() { + + string ipaddress = "255.255.255.255/32"; + + string network = "255.255.255.255"; + string netmask = "255.255.255.255"; + string broadcast = "255.255.255.255"; + string firstUsable = "255.255.255.255"; + string lastUsable = "255.255.255.255"; + byte cidr = 32; + uint usable = 0; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseIPAddressNoNetmask1() { + + string ipaddress = "10.0.0.0"; + + string network = "10.0.0.0"; + string netmask = "255.0.0.0"; + string broadcast = "10.255.255.255"; + string firstUsable = "10.0.0.1"; + string lastUsable = "10.255.255.254"; + byte cidr = 8; + uint usable = 16777214; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + + + [TestMethod] + public void TestParseIPAddressNoNetmask2() { + + string ipaddress = "172.0.0.0"; + + string network = "172.0.0.0"; + string netmask = "255.255.0.0"; + string broadcast = "172.0.255.255"; + string firstUsable = "172.0.0.1"; + string lastUsable = "172.0.255.254"; + byte cidr = 16; + uint usable = 65534; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + [TestMethod] + public void TestParseIPAddressNoNetmask3() { + + string ipaddress = "192.0.0.0"; + + string network = "192.0.0.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.0.0.255"; + string firstUsable = "192.0.0.1"; + string lastUsable = "192.0.0.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNoNetmask4() { + + string ipaddress = "224.0.0.0"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNoNetmask5() { + + string ipaddress = "240.0.0.0"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + } + + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE1() { + string ipaddress = "garbage"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE2() { + string ipaddress = "0.0.0.0 0.0.1.0"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringANE1() { + string ipaddress = null; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + + + #endregion + + #region TryParse + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE2() { + IPNetwork ipnet = null; + IPAddress ip = null; + bool parsed = IPNetwork.TryParse(ip, ip, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE3() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("", 0, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + [TestMethod] + public void TestTryParseIPAddressNetmaskANE4() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse(null, 0, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + [TestMethod] + public void TestTryParseIPAddressNetmaskANE5() { + string n = null; + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse(n, n, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE6() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse(IPAddress.Parse("10.10.10.10"), null, out ipnet); + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE7() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("0.0.0.0", null, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE8() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("x.x.x.x", "x.x.x.x", out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE9() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("0.0.0.0", "x.x.x.x", out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE10() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("x.x.x.x", 0, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE11() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("0.0.0.0", 33, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + + [TestMethod] + public void TestTryParseIPAddressNetmask() { + + IPNetwork ipnetwork = null; + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + + string network = "192.168.168.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString1() { + + IPNetwork ipnetwork = null; + string ipaddress = "192.168.168.100 255.255.255.0"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString2() { + + IPNetwork ipnetwork = null; + string ipaddress = "192.168.168.100/24"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString3() { + + IPNetwork ipnetwork = null; + string ipaddress = "0.0.0.0/0"; + + string network = "0.0.0.0"; + string netmask = "0.0.0.0"; + string broadcast = "255.255.255.255"; + string firstUsable = "0.0.0.1"; + string lastUsable = "255.255.255.254"; + byte cidr = 0; + uint usable = 4294967294; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString4() { + + IPNetwork ipnetwork = null; + string ipaddress = "0.0.0.0/32"; + + string network = "0.0.0.0"; + string netmask = "255.255.255.255"; + string broadcast = "0.0.0.0"; + string firstUsable = "0.0.0.0"; + string lastUsable = "0.0.0.0"; + byte cidr = 32; + uint usable = 0; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString5() { + + IPNetwork ipnetwork = null; + string ipaddress = "255.255.255.255/32"; + + string network = "255.255.255.255"; + string netmask = "255.255.255.255"; + string broadcast = "255.255.255.255"; + string firstUsable = "255.255.255.255"; + string lastUsable = "255.255.255.255"; + byte cidr = 32; + uint usable = 0; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + + [TestMethod] + public void TestTryParseStringAE1() { + string ipaddress = "garbage"; + IPNetwork ipnetwork = null; + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(false, parsed, "parsed"); + } + + [TestMethod] + public void TestTryParseStringAE2() { + string ipaddress = "0.0.0.0 0.0.1.0"; + IPNetwork ipnetwork = null; + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(false, parsed, "parsed"); + } + + [TestMethod] + public void TestTryParseStringANE1() { + string ipaddress = null; + IPNetwork ipnetwork = null; + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(false, parsed, "parsed"); + } + + + + #endregion + + #region ParseStringString + + [TestMethod] + public void TestParseStringString1() { + + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + Assert.AreEqual("192.168.168.0/24", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString2() { + + string ipaddress = null; + string netmask = null; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString3() { + + string ipaddress = "192.168.168.100"; + string netmask = null; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString4() { + + string ipaddress = ""; + string netmask = ""; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString5() { + + string ipaddress = "192.168.168.100"; + string netmask = ""; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + #endregion + + #region ParseIpIp + + [TestMethod] + public void ParseIpIp1() { + + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = IPAddress.Parse(netmask); + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + Assert.AreEqual("192.168.168.0/24", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void ParseIpIp2() { + + IPAddress ip = null; + IPAddress netm = null; + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void ParseIpIp3() { + + string ipaddress = "192.168.168.100"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = null; + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + + } + + #endregion + + #region ToCidr + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestToCidrANE() { + IPNetwork.ToCidr(null); + } + + [TestMethod] + public void TestToCidrAE() { + byte cidr = IPNetwork.ToCidr(IPAddress.IPv6Any); + Assert.AreEqual(0, cidr, "cidr"); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestToCidrAE2() { + IPNetwork.ToCidr(IPAddress.Parse("6.6.6.6")); + } + + + [TestMethod] + public void TestToCidr32() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + byte cidr = 32; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr24() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + byte cidr = 24; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr16() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + byte cidr = 16; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr8() { + + IPAddress mask = IPAddress.Parse("255.0.0.0"); + byte cidr = 8; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr0() { + + IPAddress mask = IPAddress.Parse("0.0.0.0"); + byte cidr = 0; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + #endregion + + #region TryToCidr + + [TestMethod] + public void TestTryToCidrANE() { + byte? cidr = null; + bool parsed = IPNetwork.TryToCidr(null, out cidr); + Assert.AreEqual(false, parsed, "parsed"); + } + + [TestMethod] + public void TestTryToCidrAE() { + byte? cidr = null; + bool parsed = IPNetwork.TryToCidr(IPAddress.IPv6Any, out cidr); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual((byte)0, cidr, "cidr"); + } + + + [TestMethod] + public void TestTryToCidrAE2() { + byte? cidr = null; + bool parsed = IPNetwork.TryToCidr(IPAddress.Parse("6.6.6.6"), out cidr); + Assert.AreEqual(false, parsed, "parsed"); + } + + + [TestMethod] + public void TestTryToCidr32() { + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.255.255.255"); + byte result = 32; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr24() { + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.255.255.0"); + byte result = 24; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + [TestMethod] + public void TestTryToCidr16() { + + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.255.0.0"); + byte result = 16; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + [TestMethod] + public void TestTryToCidr8() { + + + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.0.0.0"); + byte result = 8; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + [TestMethod] + public void TestTryToCidr0() { + + byte? cidr = null; + IPAddress mask = IPAddress.Parse("0.0.0.0"); + byte result = 0; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + + #endregion + + #region ToBigInteger + + [TestMethod] + public void TestToBigInteger32() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + uint uintMask = 0xffffffff; + BigInteger result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger24() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + uint uintMask = 0xffffff00; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger16() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + uint uintMask = 0xffff0000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger8() { + + IPAddress mask = IPAddress.Parse("255.0.0.0"); + uint uintMask = 0xff000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger0() { + + IPAddress mask = IPAddress.Parse("0.0.0.0"); + uint uintMask = 0x00000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestToBigIntegerANE() { + BigInteger? result = IPNetwork.ToBigInteger(null); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestToBigIntegerANE3() { + IPAddress ip = null; + BigInteger? result = IPNetwork.ToBigInteger(ip); + } + [TestMethod] + public void TestToBigIntegerANE2() { + BigInteger? result = IPNetwork.ToBigInteger(IPAddress.IPv6Any); + uint expected = 0; + Assert.AreEqual(expected, result, "result"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestToBigIntegerByte() { + BigInteger result = IPNetwork.ToUint(33, Sockets.AddressFamily.InterNetwork); + } + + [TestMethod] + public void TestToBigIntegerByte2() { + BigInteger result = IPNetwork.ToUint(32, Sockets.AddressFamily.InterNetwork); + uint expected = 4294967295; + Assert.AreEqual(expected, result, "result"); + + } + + + [TestMethod] + public void TestToBigIntegerByte3() { + BigInteger result = IPNetwork.ToUint(0, Sockets.AddressFamily.InterNetwork); + uint expected = 0; + Assert.AreEqual(expected, result, "result"); + + } + + + + #endregion + + #region TryToBigInteger + + [TestMethod] + public void TestTryToBigInteger32() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + uint uintMask = 0xffffffff; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger24() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + uint uintMask = 0xffffff00; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger16() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + uint uintMask = 0xffff0000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger8() { + + IPAddress mask = IPAddress.Parse("255.0.0.0"); + uint uintMask = 0xff000000; + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger0() { + + IPAddress mask = IPAddress.Parse("0.0.0.0"); + uint uintMask = 0x00000000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigIntegerANE() { + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(null, out result); + + Assert.AreEqual(null, result, "uint"); + Assert.AreEqual(false, parsed, "parsed"); + + } + [TestMethod] + public void TestTryToBigIntegerANE3() { + IPAddress ip = null; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(ip, out result); + + Assert.AreEqual(null, result, "uint"); + Assert.AreEqual(false, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigIntegerANE2() { + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(IPAddress.IPv6Any, out result); + + Assert.AreEqual(0, result, "result"); + Assert.AreEqual(true, parsed, "parsed"); + } + + + + #endregion + + #region TryToNetmask + [TestMethod] + public void TryToNetmask1() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(0, Sockets.AddressFamily.InterNetwork, out result); + IPAddress expected = IPAddress.Parse("0.0.0.0"); + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(true, parsed, "parsed"); + + } + + [TestMethod] + public void TryToNetmask2() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(33, Sockets.AddressFamily.InterNetwork, out result); + IPAddress expected = null; + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(false, parsed, "parsed"); + + } + + #endregion + + #region ToNetmask + + [TestMethod] + public void ToNetmask32() { + + byte cidr = 32; + string netmask = "255.255.255.255"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask31() { + + byte cidr = 31; + string netmask = "255.255.255.254"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask30() { + + byte cidr = 30; + string netmask = "255.255.255.252"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask29() { + + byte cidr = 29; + string netmask = "255.255.255.248"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask1() { + + byte cidr = 1; + string netmask = "128.0.0.0"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + + [TestMethod] + public void ToNetmask0() { + + byte cidr = 0; + string netmask = "0.0.0.0"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void ToNetmaskOORE1() { + byte cidr = 33; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + } + + #endregion + + #region ValidNetmask + + [TestMethod] + public void TestValidNetmask0() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask1() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask2() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + public void TestValidNetmaskEAE1() { + + IPAddress mask = IPAddress.Parse("0.255.0.0"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestValidNetmaskEAE2() { + + IPAddress mask = null; + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + public void TestValidNetmaskEAE3() { + + IPAddress mask = IPAddress.Parse("255.255.0.1"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + #endregion + + #region BitsSet + + [TestMethod] + public void TestBitsSet32() { + + IPAddress ip = IPAddress.Parse("255.255.255.255"); + uint bits = 32; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet24() { + + IPAddress ip = IPAddress.Parse("255.255.255.0"); + uint bits = 24; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet16() { + + IPAddress ip = IPAddress.Parse("255.255.0.0"); + uint bits = 16; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet4() { + + IPAddress ip = IPAddress.Parse("128.128.128.128"); + uint bits = 4; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + + #endregion + + #region Contains + + [TestMethod] + public void TestContains1() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/24"); + IPAddress ipaddress = IPAddress.Parse("192.168.0.100"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains2() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/24"); + IPAddress ipaddress = IPAddress.Parse("10.10.10.10"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains3() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.0.1/24"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains4() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/16"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.1/24"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains5() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/16"); + IPNetwork ipnetwork2 = IPNetwork.Parse("10.10.10.0/24"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + + [TestMethod] + public void TestContains6() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.0.0/16"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains7() + { + + IPNetwork ipnetwork = null; + IPNetwork ipnetwork2 = null; + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains8() + { + + IPNetwork ipnetwork = IPNetwork.Parse("0.0.0.0/0"); + IPNetwork ipnetwork2 = null; + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains9() + { + + IPNetwork ipnetwork = null; + IPAddress ipaddress = null; + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains10() + { + + IPNetwork ipnetwork = IPNetwork.Parse("0.0.0.0/0"); + IPAddress ipaddress = null; + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + + } + + #endregion + + #region Overlap + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestOverlap1() + { + IPNetwork network1 = null; + IPNetwork network2 = null; + IPNetwork.Overlap(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestOverlap2() + { + IPNetwork network1 = IPNetwork.Parse("10.0.0.0/0"); + IPNetwork network2 = null; + IPNetwork.Overlap(network1, network2); + } + + [TestMethod] + public void TestOverlap3() + { + IPNetwork network1 = IPNetwork.Parse("10.0.0.0/0"); + IPNetwork network2 = IPNetwork.Parse("10.0.0.0/0"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap4() + { + IPNetwork network1 = IPNetwork.Parse("10.10.0.0/16"); + IPNetwork network2 = IPNetwork.Parse("10.10.1.0/24"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap5() + { + IPNetwork network1 = IPNetwork.Parse("10.10.0.0/24"); + IPNetwork network2 = IPNetwork.Parse("10.10.1.0/24"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = false; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap6() + { + IPNetwork network1 = IPNetwork.Parse("10.10.1.0/24"); + IPNetwork network2 = IPNetwork.Parse("10.10.0.0/16"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + #endregion + + #region Examples + + public void Example1() + { + IPNetwork ipnetwork = IPNetwork.Parse("192.168.168.100/24"); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + public void Example2() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.0/24"); + IPAddress ipaddress = IPAddress.Parse("192.168.0.100"); + IPAddress ipaddress2 = IPAddress.Parse("192.168.1.100"); + + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.0.128/25"); + IPNetwork ipnetwork3 = IPNetwork.Parse("192.168.1.1/24"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + bool contains3 = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool contains4 = IPNetwork.Contains(ipnetwork, ipnetwork3); + + bool overlap1 = IPNetwork.Overlap(ipnetwork, ipnetwork2); + bool overlap2 = IPNetwork.Overlap(ipnetwork, ipnetwork3); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork2, contains3); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork3, contains4); + + + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork2, overlap1); + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork3, overlap2); + + + } + + public void Example2b() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("10.1.0.0/16"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.0/24"); + + IPAddress ipaddress1 = IPAddress.Parse("192.168.1.1"); + IPAddress ipaddress2 = IPAddress.Parse("192.168.2.100"); + IPAddress ipaddress3 = IPAddress.Parse("10.1.2.3"); + IPAddress ipaddress4 = IPAddress.Parse("10.4.5.6"); + + + bool contains1 = IPNetwork.Contains(ipnetwork2, ipaddress1); + bool contains2 = IPNetwork.Contains(ipnetwork2, ipaddress2); + bool contains3 = IPNetwork.Contains(ipnetwork1, ipaddress3); + bool contains4 = IPNetwork.Contains(ipnetwork1, ipaddress4); + + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork1, ipaddress1, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork1, ipaddress2, contains2); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork2, ipaddress3, contains3); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork2, ipaddress4, contains4); + + + } + + public void Example3() + { + + IPNetwork iana_a_block = IPNetwork.IANA_ABLK_RESERVED1; + IPNetwork iana_b_block = IPNetwork.IANA_BBLK_RESERVED1; + IPNetwork iana_c_block = IPNetwork.IANA_CBLK_RESERVED1; + + Console.WriteLine("IANA_ABLK_RESERVED1 is {0}", iana_a_block); + Console.WriteLine("IANA_BBLK_RESERVED1 is {0}", iana_b_block); + Console.WriteLine("IANA_CBLK_RESERVED1 is {0}", iana_c_block); + + } + + + public void Example4() + { + IPNetwork wholeInternet = IPNetwork.Parse("0.0.0.0/0"); + byte newCidr = 2; + IPNetworkCollection subneted = IPNetwork.Subnet(wholeInternet, newCidr); + + Console.WriteLine("{0} was subnetted into {1} subnets", wholeInternet, subneted.Count); + Console.WriteLine("First: {0}", subneted[0]); + Console.WriteLine("Last : {0}", subneted[subneted.Count - 1]); + Console.WriteLine("All :"); + + foreach (IPNetwork ipnetwork in subneted) + { + Console.WriteLine("{0}", ipnetwork); + } + } + + public void Example5() + { + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.0/24"); + IPNetwork[] ipnetwork3 = IPNetwork.Supernet(new[]{ipnetwork1, ipnetwork2}); + + Console.WriteLine("{0} + {1} = {2}", ipnetwork1, ipnetwork2, ipnetwork3[0]); + + } + + + + public void Example7() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.168.100/24"); + + IPAddress ipaddress = IPAddress.Parse("192.168.168.200"); + IPAddress ipaddress2 = IPAddress.Parse("192.168.0.200"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + + } + public void Example9() { + + IPNetwork network = IPNetwork.Parse("192.168.0.1"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.254"); + + IPNetwork ipnetwork = IPNetwork.Supernet(network, network2); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + + public void Example10() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/25"); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + #endregion + + #region IANA blocks + [TestMethod] + public void TestIANA1() { + + IPAddress ipaddress = IPAddress.Parse("192.168.66.66"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA2() { + + IPAddress ipaddress = IPAddress.Parse("10.0.0.0"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA3() { + + IPAddress ipaddress = IPAddress.Parse("172.17.10.10"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA4() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.66.66/24"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA5() { + + IPNetwork ipnetwork = IPNetwork.Parse("10.10.10/18"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA6() { + + IPNetwork ipnetwork = IPNetwork.Parse("172.31.10.10/24"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestIANA7() { + + IPAddress ipaddress = null; + IPNetwork.IsIANAReserved(ipaddress); + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestIANA8() { + + IPNetwork ipnetwork = null; + IPNetwork.IsIANAReserved(ipnetwork); + + + } + + + [TestMethod] + public void TestIANA9() { + + IPAddress ipaddress = IPAddress.Parse("1.2.3.4"); + bool expected = false; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA10() { + + IPNetwork ipnetwork = IPNetwork.Parse("172.16.0.0/8"); + bool expected = false; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + + [TestMethod] + public void TestIANA11() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/8"); + bool expected = false; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + #endregion + + #region ToString + + + [TestMethod] + public void TestToString() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/8"); + string expected = "192.0.0.0/8"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString1() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/9"); + string expected = "192.128.0.0/9"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString2() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/10"); + string expected = "192.128.0.0/10"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString3() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/11"); + string expected = "192.160.0.0/11"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString4() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/12"); + string expected = "192.160.0.0/12"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString5() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/13"); + string expected = "192.168.0.0/13"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString6() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/14"); + string expected = "192.168.0.0/14"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + [TestMethod] + public void TestToString7() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/15"); + string expected = "192.168.0.0/15"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString8() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/16"); + string expected = "192.168.0.0/16"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + #endregion + + #region Subnet + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestSubnet1() { + + IPNetwork ipnetwork = null; + byte cidr = 9; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet3() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 55; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSubnet4() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 1; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + public void TestSubnet5() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 9; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("10.0.0.0/9", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("10.128.0.0/9", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestSubnet6() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/20", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.16.0/20", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("192.168.32.0/20", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("192.168.48.0/20", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("192.168.64.0/20", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("192.168.80.0/20", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("192.168.96.0/20", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("192.168.112.0/20", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("192.168.128.0/20", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("192.168.144.0/20", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("192.168.160.0/20", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("192.168.176.0/20", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("192.168.192.0/20", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("192.168.208.0/20", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("192.168.224.0/20", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("192.168.240.0/20", subnets[15].ToString(), "subnet16"); + + } + + + [TestMethod] + public void TestSubnet7() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 24; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/24", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.255.0/24", subnets[255].ToString(), "subnet16"); + + } + + + [TestMethod] + public void TestSubnet8() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 24; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/24", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.255.0/24", subnets[255].ToString(), "subnet256"); + + } + + [TestMethod] + public void TestSubnet9() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.0/24"); + byte cidr = 32; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/32", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.0.255/32", subnets[255].ToString(), "subnet256"); + + } + + + [TestMethod] + public void TestSubnet10() + { + IPNetwork ipnetwork = IPNetwork.Parse("0.0.0.0/0"); + byte cidr = 32; + + // Here I spawm a OOM dragon ! beware of the beast ! + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(4294967296, subnets.Count, "count"); + Assert.AreEqual("0.0.0.0/32", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("255.255.255.255/32", subnets[4294967295].ToString(), "subnet256"); + + } + + + [TestMethod] + public void TestSubnet12() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + int i = -1; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + foreach (IPNetwork ipn in subnets) { + i++; + Assert.AreEqual(subnets[i], ipn, "subnet"); + } + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet13() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + IPNetwork error = subnets[1000]; + + } + + #endregion + + #region TrySubnet + + + [TestMethod] + public void TestTrySubnet1() { + + IPNetwork ipnetwork = null; + byte cidr = 9; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + + } + + [TestMethod] + public void TestTrySubnet3() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 55; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + } + + + [TestMethod] + public void TestTrySubnet4() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 1; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + + } + + + [TestMethod] + public void TestTrySubnet5() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 9; + + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("10.0.0.0/9", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("10.128.0.0/9", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestTrySubnet6() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/20", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.16.0/20", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("192.168.32.0/20", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("192.168.48.0/20", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("192.168.64.0/20", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("192.168.80.0/20", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("192.168.96.0/20", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("192.168.112.0/20", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("192.168.128.0/20", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("192.168.144.0/20", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("192.168.160.0/20", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("192.168.176.0/20", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("192.168.192.0/20", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("192.168.208.0/20", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("192.168.224.0/20", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("192.168.240.0/20", subnets[15].ToString(), "subnet16"); + + } + + + + #endregion + + #region Supernet + + [TestMethod] + public void TestSupernet1() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork expected = IPNetwork.Parse("192.168.0.0/23"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + Assert.AreEqual(expected, supernet, "supernet"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestSupernet2() { + + IPNetwork network1 = null; + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestSupernet3() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = null; + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSupernet4() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/25"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSupernet5() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.5.1/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + public void TestSupernet6() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork expected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + Assert.AreEqual(expected, supernet, "supernet"); + + } + + [TestMethod] + public void TestSupernet7() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork expected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + Assert.AreEqual(expected, supernet, "supernet"); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSupernet8() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + + } + + + [TestMethod] + public void TestSupernet9() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("200.16.0.0/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("200.16.1.0/24"); + IPNetwork ipnetwork3 = IPNetwork.Parse("200.16.2.0/24"); + IPNetwork ipnetwork4 = IPNetwork.Parse("200.16.3.0/24"); + + IPNetwork result = IPNetwork.Supernet(new[] { ipnetwork1, ipnetwork2, ipnetwork3, ipnetwork4 })[0]; + IPNetwork expected = IPNetwork.Parse("200.16.0.0/22"); + + Assert.AreEqual(expected, result, "supernet"); + + } + + #endregion + + #region TrySupernet + + + [TestMethod] + public void TestTrySupernet1() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork supernetExpected = IPNetwork.Parse("192.168.0.0/23"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet2() { + + IPNetwork network1 = null; + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet3() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = null; + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet4() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/25"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet5() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.5.1/24"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet6() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork supernetExpected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet7() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork supernetExpected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet8() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet9() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork[] network3 = new [] { network1, network2 }; + IPNetwork[] supernetExpected = new [] { network1, network2 }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(supernetExpected[1], supernet[1], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet10() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork[] network3 = new[] { network1, network2 }; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("192.168.0.0/23") }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet11() { + + IPNetwork[] network3 = null; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("192.168.0.0/23") }; + IPNetwork[] supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(null, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + #endregion + + #region SupernetArray + + [TestMethod] + public void TestTrySupernetArray() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.0/24"); + IPNetwork ipnetwork3 = IPNetwork.Parse("192.168.2.0/24"); + IPNetwork ipnetwork4 = IPNetwork.Parse("192.168.3.0/24"); + + IPNetwork[] ipnetworks = { ipnetwork1, ipnetwork2, ipnetwork3, ipnetwork4 }; + IPNetwork[] expected = { IPNetwork.Parse("192.168.0.0/22") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], expected[0], "suppernet"); + + } + + [TestMethod] + public void TestTrySupernetArray1() + { + + + IPNetwork[] ipnetworks = { }; + IPNetwork[] expected = { }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestTrySupernetArray2() + { + + + IPNetwork[] ipnetworks = null; + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + } + + + [TestMethod] + public void TestTrySupernetArray3() + { + + IPNetwork ipnetwork1 = null; + IPNetwork ipnetwork2 = null; + IPNetwork ipnetwork3 = null; + IPNetwork ipnetwork4 = null; + + IPNetwork[] ipnetworks = { ipnetwork1, ipnetwork2, ipnetwork3, ipnetwork4 }; + IPNetwork[] expected = { }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + + } + + [TestMethod] + public void TestTrySupernetArray4() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/24"); + IPNetworkCollection subnetted = IPNetwork.Subnet(ipnetwork1, 32); + IPNetwork[] ipnetworks = subnetted.ToArray(); + Assert.AreEqual(256, ipnetworks.Length, "subnet"); + + IPNetwork[] expected = { IPNetwork.Parse("192.168.0.0/24") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], ipnetwork1, "suppernet"); + } + + + [TestMethod] + public void TestTrySupernetArray5() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/16"); + IPNetworkCollection subnetted = IPNetwork.Subnet(ipnetwork1, 32); + IPNetwork[] ipnetworks = subnetted.ToArray(); + Assert.AreEqual(65536, ipnetworks.Length, "subnet"); + + IPNetwork[] expected = { IPNetwork.Parse("192.168.0.0/16") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], ipnetwork1, "suppernet"); + } + + public void TestTrySupernetArray6() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/8"); + IPNetworkCollection subnetted = IPNetwork.Subnet(ipnetwork1, 32); + IPNetwork[] ipnetworks = subnetted.ToArray(); + Assert.AreEqual(16777216, ipnetworks.Length, "subnet"); + + IPNetwork[] expected = { IPNetwork.Parse("192.0.0.0/8") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], ipnetwork1, "suppernet"); + } + + [TestMethod] + public void TestTrySupernetArray7() + { + + IPNetwork[] ipnetworks = { + IPNetwork.Parse("10.0.2.2/24"), + IPNetwork.Parse("192.168.0.0/24"), + IPNetwork.Parse("192.168.1.0/24"), + IPNetwork.Parse("192.168.2.0/24"), + IPNetwork.Parse("10.0.1.1/24"), + IPNetwork.Parse("192.168.3.0/24") + }; + + IPNetwork[] expected = { + IPNetwork.Parse("10.0.1.0/24"), + IPNetwork.Parse("10.0.2.0/24"), + IPNetwork.Parse("192.168.0/22") + }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], result[0], "suppernet"); + Assert.AreEqual(expected[1], result[1], "suppernet1"); + Assert.AreEqual(expected[2], result[2], "suppernet2"); + } + + [TestMethod] + public void TestTrySupernetArray8() + { + + IPNetwork[] ipnetworks = { + IPNetwork.Parse("10.0.2.2/24"), + IPNetwork.Parse("192.168.0.0/24"), + IPNetwork.Parse("192.168.1.0/24"), + IPNetwork.Parse("192.168.2.0/24"), + IPNetwork.Parse("10.0.1.1/24"), + IPNetwork.Parse("192.168.3.0/24"), + IPNetwork.Parse("10.6.6.6/8") + + }; + + IPNetwork[] expected = { + IPNetwork.Parse("10.0.0.0/8"), + IPNetwork.Parse("192.168.0/22") + }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], result[0], "suppernet"); + Assert.AreEqual(expected[1], result[1], "suppernet1"); + } + + + [TestMethod] + public void TestTrySupernetArray9() + { + + IPNetwork[] ipnetworks = { + IPNetwork.Parse("10.0.2.2/24"), + IPNetwork.Parse("192.168.0.0/24"), + IPNetwork.Parse("192.168.1.0/24"), + IPNetwork.Parse("192.168.2.0/24"), + IPNetwork.Parse("10.0.1.1/24"), + IPNetwork.Parse("192.168.3.0/24"), + IPNetwork.Parse("10.6.6.6/8"), + IPNetwork.Parse("11.6.6.6/8"), + IPNetwork.Parse("12.6.6.6/8"), + + }; + + IPNetwork[] expected = { + IPNetwork.Parse("10.0.0.0/7"), + IPNetwork.Parse("12.0.0.0/8"), + IPNetwork.Parse("192.168.0/22") + }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], result[0], "suppernet"); + Assert.AreEqual(expected[1], result[1], "suppernet1"); + Assert.AreEqual(expected[2], result[2], "suppernet2"); + } + + + #endregion + + #region Equals + + [TestMethod] + public void TestEquals1() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/24"); + bool result = network1.Equals(network2); + bool expected = true; + + Assert.AreEqual(expected, result, "equals"); + + } + + [TestMethod] + public void TestEquals2() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = null; + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + [TestMethod] + public void TestEquals3() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + object network2 = ""; + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + [TestMethod] + public void TestEquals4() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/25"); + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + + [TestMethod] + public void TestEquals5() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + #endregion + + #region WideSubnet + + [TestMethod] + public void TestWideSubnet1() { + + string start = "192.168.168.0"; + string end = "192.168.168.255"; + IPNetwork expected = IPNetwork.Parse("192.168.168.0/24"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestWideSubnet2() { + + string start = null; + string end = "192.168.168.255"; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestWideSubnet3() { + + string start = "192.168.168.255"; + string end = null; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + + } + + [TestMethod] + public void TestWideSubnet4() { + + string start = "192.168.168.255"; + string end = "192.168.168.0"; + + + IPNetwork expected = IPNetwork.Parse("192.168.168.0/24"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + } + + + [TestMethod] + public void TestWideSubnet7() { + + string start = "0.0.0.0"; + string end = "0.255.255.255"; + + IPNetwork expected = IPNetwork.Parse("0.0.0.0/8"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + } + + + + [TestMethod] + public void TestWideSubnet8() { + + string start = "1.2.3.4"; + string end = "5.6.7.8"; + + IPNetwork expected = IPNetwork.Parse("0.0.0.0/5"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + } + + + [TestMethod] + public void TestWideSubnet9() + { + + string start = "200.16.0.0/24"; + string end = "200.16.3.0/24"; + var firt = IPNetwork.Parse(start).FirstUsable.ToString(); + var last = IPNetwork.Parse(end).LastUsable.ToString(); + + IPNetwork expected = IPNetwork.Parse("200.16.0.0/22"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(firt, last); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + + + + } + + + [TestMethod] + public void TestWideSubnet10() + { + + string start = "200.16.0.0"; + string end = "200.16.3.255"; + + IPNetwork expected = IPNetwork.Parse("200.16.0.0/22"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestWideSubnetInvalid1() { + + string start = "invalid"; + string end = "5.6.7.8"; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestWideSubnetInvalid2() { + + string start = "1.2.3.4"; + string end = "invalid"; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + } + + #endregion + + #region TryGuessCidr + + [TestMethod] + public void TestTryGuessCidrNull() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr(null, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(0, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrA() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("10.0.0.0", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(8, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrB() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("172.0.0.0", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(16, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrC() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("192.0.0.0", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(24, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrD() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("224.0.0.0", out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + } + [TestMethod] + public void TestTryGuessCidrE() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("240.0.0.0", out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + } + + #endregion + + #region GetHashCode + + [TestMethod] + public void TestGetHashCode1() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("0.0.1.1/0"); + IPNetwork ipnetwork2 = IPNetwork.Parse("0.0.1.1/0"); + int hashCode1 = ipnetwork1.GetHashCode(); + int hashCode2 = ipnetwork2.GetHashCode(); + Assert.AreEqual(hashCode1, hashCode2, "hashcode"); + + } + + [TestMethod] + public void TestGetHashCode2() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("0.0.0.0/1"); + IPNetwork ipnetwork2 = IPNetwork.Parse("0.0.0.0/1"); + int hashCode1 = ipnetwork1.GetHashCode(); + int hashCode2 = ipnetwork2.GetHashCode(); + Assert.AreEqual(hashCode1, hashCode2, "hashcode"); + + } + [TestMethod] + public void TestGetHashCode3() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("0.0.0.0/32"); + IPNetwork ipnetwork2 = IPNetwork.Parse("0.0.0.0/32"); + int hashCode1 = ipnetwork1.GetHashCode(); + int hashCode2 = ipnetwork2.GetHashCode(); + Assert.AreEqual(hashCode1, hashCode2, "hashcode"); + + } + + #endregion + + #region Print + + [TestMethod] + public void Print() { + IPNetwork ipn = IPNetwork.Parse("0.0.0.0/0"); + string print = IPNetwork.Print(ipn).Replace("\r", ""); + string expected = @"IPNetwork : 0.0.0.0/0 +Network : 0.0.0.0 +Netmask : 0.0.0.0 +Cidr : 0 +Broadcast : 255.255.255.255 +FirstUsable : 0.0.0.1 +LastUsable : 255.255.255.254 +Usable : 4294967294 +".Replace("\r", ""); + + Assert.AreEqual(expected, print, "Print"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void PrintNull() { + IPNetwork ipn = null; + string print = IPNetwork.Print(ipn); + } + + #endregion + + #region Sort + + [TestMethod] + public void TestSort1() { + string[] ips = new[] { "1.1.1.1", "255.255.255.255", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach(string ip in ips) { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) { + ipns.Add(ipn); + } + } + + ipns.Sort(); + Assert.AreEqual("0.0.0.0/32", ipns[0].ToString(), "0"); + Assert.AreEqual("1.1.1.1/32", ipns[1].ToString(), "1"); + Assert.AreEqual("2.2.2.2/32", ipns[2].ToString(), "2"); + Assert.AreEqual("255.255.255.255/32", ipns[3].ToString(), "3"); + } + + [TestMethod] + public void TestSort2() { + string[] ips = new[] { "0.0.0.100/32", "0.0.0.0/24" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, out ipn)) { + ipns.Add(ipn); + } + } + + ipns.Sort(); + Assert.AreEqual("0.0.0.0/24", ipns[0].ToString(), "0"); + Assert.AreEqual("0.0.0.100/32", ipns[1].ToString(), "1"); + } + + #endregion + + #region TryWideSubnet + + [TestMethod] + public void TryWideSubnet1() { + string[] ips = new[] { "1.1.1.1", "255.255.255.255", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(true, wide, "wide"); + Assert.AreEqual("0.0.0.0/0", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + public void TryWideSubnet2() { + string[] ips = new[] { "1.1.1.1", "10.0.0.0", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(true, wide, "wide"); + Assert.AreEqual("0.0.0.0/4", ipnetwork.ToString(), "ipnetwork"); + + } + + + [TestMethod] + public void TryWideSubnet3() { + string[] ips = new[] { "a", "b", "c", "d" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(false, wide, "wide"); + + } + + [TestMethod] + public void TryWideSubnet4() { + string[] ips = new[] { "a", "b", "1.1.1.1", "d" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(true, wide, "wide"); + Assert.AreEqual("1.1.1.1/32", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + public void TryWideSubnetNull() { + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(null, out ipnetwork); + Assert.AreEqual(false, wide, "wide"); + + } + + #endregion + + #region WideSubnet + + [TestMethod] + public void WideSubnet1() { + string[] ips = new[] { "1.1.1.1", "255.255.255.255", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = IPNetwork.WideSubnet(ipns.ToArray()); + Assert.AreEqual("0.0.0.0/0", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + public void WideSubnet2() { + string[] ips = new[] { "1.1.1.1", "10.0.0.0", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = IPNetwork.WideSubnet(ipns.ToArray()); + Assert.AreEqual("0.0.0.0/4", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void WideSubnetNull() { + + IPNetwork ipnetwork = IPNetwork.WideSubnet(null); + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void WideSubnetNull2() { + + string[] ips = new[] { "a", "b", "e", "d" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = IPNetwork.WideSubnet(ipns.ToArray()); + + + } + + #endregion + + /** + * + #region TrySubstractNetwork + + + [TestMethod] + public void TrySubstractNetwork1() { + string[] ips = new[] { "178.82.0.0/16" }; + string substract = "178.82.131.209/32"; + + List ipns = new List(); + Array.ForEach(ips, new Action( + delegate(string ip) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, out ipn)) { + ipns.Add(ipn); + } + } + )); + + var nsubstract = IPNetwork.Parse(substract); + + IEnumerable result; + bool substracted = IPNetwork.TrySubstractNetwork(ipns.ToArray(), nsubstract, out result); + Assert.AreEqual(true, substracted, "substracted"); + + } + + [TestMethod] + public void TrySubstractNetwork2() { + string[] ips = new[] { "0.0.0.0/0" }; + string substract = "1.1.1.1/32"; + + List ipns = new List(); + Array.ForEach(ips, new Action( + delegate(string ip) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, out ipn)) { + ipns.Add(ipn); + } + } + )); + + var nsubstract = IPNetwork.Parse(substract); + + IEnumerable result; + bool substracted = IPNetwork.TrySubstractNetwork(ipns.ToArray(), nsubstract, out result); + Assert.AreEqual(true, substracted, "substracted"); + + } + + + + #endregion + **/ + + #region Count + + [TestMethod] + public void Total32() { + var network = IPNetwork.Parse("0.0.0.0/32"); + var total = 1; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total31() { + var network = IPNetwork.Parse("0.0.0.0/31"); + var total = 2; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total30() { + var network = IPNetwork.Parse("0.0.0.0/30"); + var total = 4; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total24() { + var network = IPNetwork.Parse("0.0.0.0/24"); + var total = 256; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total16() { + var network = IPNetwork.Parse("0.0.0.0/16"); + var total = 65536; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total8() { + var network = IPNetwork.Parse("0.0.0.0/8"); + var total = 16777216; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total0() { + var network = IPNetwork.Parse("0.0.0.0/0"); + var total = 4294967296; + Assert.AreEqual(total, network.Total, "Total"); + } + + #endregion + + #region Usable + + [TestMethod] + public void Usable32() { + var network = IPNetwork.Parse("0.0.0.0/32"); + uint usable = 0; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable31() { + var network = IPNetwork.Parse("0.0.0.0/31"); + uint usable = 0; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable30() { + var network = IPNetwork.Parse("0.0.0.0/30"); + uint usable = 2; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable24() { + var network = IPNetwork.Parse("0.0.0.0/24"); + uint usable = 254; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable16() { + var network = IPNetwork.Parse("0.0.0.0/16"); + uint usable = 65534; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable8() { + var network = IPNetwork.Parse("0.0.0.0/8"); + uint usable = 16777214; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable0() { + var network = IPNetwork.Parse("0.0.0.0/0"); + uint usable = 4294967294; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + #endregion + + #region TryParseCidr + + [TestMethod] + public void TryParseCidr1() { + + string sidr = "0"; + byte? cidr; + byte? result = 0; + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetwork, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr2() { + + string sidr = "sadsd"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetwork, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr3() { + + string sidr = "33"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetwork, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + #endregion + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource subnets of type System.Net.IPNetworkCollection in method "Void IPNetworkUnitTest.TestSubnet3()". + +### Severity: +ERROR + +### Procedure: +Void IPNetworkUnitTest.TestSubnet3() + +### File: +src/System.Net.IPNetwork.TestProject.Source/IPNetworkUnitTest.cs + +### Key: +IPNetworkUnitTest.cs|TestSubnet3|DOTNET_RESOURCE_LEAK + +### Hash: +2ff285f97f5469be18600ae0f08ca6a0 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1628/instruction.md b/inferredbugs-1628/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..95914ad9336a2746615d6fb191ed9181012c14ad --- /dev/null +++ b/inferredbugs-1628/instruction.md @@ -0,0 +1,3382 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ipnetwork +**Bug ID:** 31 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; + +namespace System.Net.TestProject +{ + /// + /// IPNetworkUnitTest test every single method + /// + [TestClass] + public class IPNetworkUnitTest { + + #region Parse + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE2() { + IPAddress ip = null; + IPNetwork.Parse(ip, ip); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE3() { + IPNetwork.Parse("", 0); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE4() { + IPNetwork.Parse(null, 0); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseIPAddressNetmaskANE5() { + string n = null; + IPNetwork.Parse(n, n); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE8() { + IPNetwork ipnet = IPNetwork.Parse("x.x.x.x", "x.x.x.x"); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE9() { + IPNetwork ipnet = IPNetwork.Parse("0.0.0.0", "x.x.x.x"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE10() { + IPNetwork ipnet = IPNetwork.Parse("x.x.x.x", 0); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNetmaskANE11() { + IPNetwork ipnet = IPNetwork.Parse("0.0.0.0", 33); + + } + + [TestMethod] + public void TestParseIPAddressNetmask() { + + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + + string network = "192.168.168.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString1() { + + string ipaddress = "192.168.168.100 255.255.255.0"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString2() { + + string ipaddress = "192.168.168.100/24"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString3() { + + string ipaddress = "0.0.0.0/0"; + + string network = "0.0.0.0"; + string netmask = "0.0.0.0"; + string broadcast = "255.255.255.255"; + string firstUsable = "0.0.0.1"; + string lastUsable = "255.255.255.254"; + byte cidr = 0; + uint usable = 4294967294; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString4() { + + string ipaddress = "0.0.0.0/32"; + + string network = "0.0.0.0"; + string netmask = "255.255.255.255"; + string broadcast = "0.0.0.0"; + string firstUsable = "0.0.0.0"; + string lastUsable = "0.0.0.0"; + byte cidr = 32; + uint usable = 0; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseString5() { + + string ipaddress = "255.255.255.255/32"; + + string network = "255.255.255.255"; + string netmask = "255.255.255.255"; + string broadcast = "255.255.255.255"; + string firstUsable = "255.255.255.255"; + string lastUsable = "255.255.255.255"; + byte cidr = 32; + uint usable = 0; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestParseIPAddressNoNetmask1() { + + string ipaddress = "10.0.0.0"; + + string network = "10.0.0.0"; + string netmask = "255.0.0.0"; + string broadcast = "10.255.255.255"; + string firstUsable = "10.0.0.1"; + string lastUsable = "10.255.255.254"; + byte cidr = 8; + uint usable = 16777214; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + + + [TestMethod] + public void TestParseIPAddressNoNetmask2() { + + string ipaddress = "172.0.0.0"; + + string network = "172.0.0.0"; + string netmask = "255.255.0.0"; + string broadcast = "172.0.255.255"; + string firstUsable = "172.0.0.1"; + string lastUsable = "172.0.255.254"; + byte cidr = 16; + uint usable = 65534; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + [TestMethod] + public void TestParseIPAddressNoNetmask3() { + + string ipaddress = "192.0.0.0"; + + string network = "192.0.0.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.0.0.255"; + string firstUsable = "192.0.0.1"; + string lastUsable = "192.0.0.254"; + byte cidr = 24; + uint usable = 254; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNoNetmask4() { + + string ipaddress = "224.0.0.0"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseIPAddressNoNetmask5() { + + string ipaddress = "240.0.0.0"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + + } + + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE1() { + string ipaddress = "garbage"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestParseStringAE2() { + string ipaddress = "0.0.0.0 0.0.1.0"; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringANE1() { + string ipaddress = null; + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress); + } + + + + #endregion + + #region TryParse + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE2() { + IPNetwork ipnet = null; + IPAddress ip = null; + bool parsed = IPNetwork.TryParse(ip, ip, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE3() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("", 0, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + [TestMethod] + public void TestTryParseIPAddressNetmaskANE4() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse(null, 0, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + [TestMethod] + public void TestTryParseIPAddressNetmaskANE5() { + string n = null; + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse(n, n, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE6() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse(IPAddress.Parse("10.10.10.10"), null, out ipnet); + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE7() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("0.0.0.0", null, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE8() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("x.x.x.x", "x.x.x.x", out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE9() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("0.0.0.0", "x.x.x.x", out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE10() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("x.x.x.x", 0, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + [TestMethod] + public void TestTryParseIPAddressNetmaskANE11() { + IPNetwork ipnet = null; + bool parsed = IPNetwork.TryParse("0.0.0.0", 33, out ipnet); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(null, ipnet, "ipnet"); + + } + + + [TestMethod] + public void TestTryParseIPAddressNetmask() { + + IPNetwork ipnetwork = null; + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + + string network = "192.168.168.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + bool parsed = IPNetwork.TryParse(ipaddress, netmask, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString1() { + + IPNetwork ipnetwork = null; + string ipaddress = "192.168.168.100 255.255.255.0"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString2() { + + IPNetwork ipnetwork = null; + string ipaddress = "192.168.168.100/24"; + + string network = "192.168.168.0"; + string netmask = "255.255.255.0"; + string broadcast = "192.168.168.255"; + string firstUsable = "192.168.168.1"; + string lastUsable = "192.168.168.254"; + byte cidr = 24; + uint usable = 254; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString3() { + + IPNetwork ipnetwork = null; + string ipaddress = "0.0.0.0/0"; + + string network = "0.0.0.0"; + string netmask = "0.0.0.0"; + string broadcast = "255.255.255.255"; + string firstUsable = "0.0.0.1"; + string lastUsable = "255.255.255.254"; + byte cidr = 0; + uint usable = 4294967294; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString4() { + + IPNetwork ipnetwork = null; + string ipaddress = "0.0.0.0/32"; + + string network = "0.0.0.0"; + string netmask = "255.255.255.255"; + string broadcast = "0.0.0.0"; + string firstUsable = "0.0.0.0"; + string lastUsable = "0.0.0.0"; + byte cidr = 32; + uint usable = 0; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + [TestMethod] + public void TestTryParseString5() { + + IPNetwork ipnetwork = null; + string ipaddress = "255.255.255.255/32"; + + string network = "255.255.255.255"; + string netmask = "255.255.255.255"; + string broadcast = "255.255.255.255"; + string firstUsable = "255.255.255.255"; + string lastUsable = "255.255.255.255"; + byte cidr = 32; + uint usable = 0; + + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(network, ipnetwork.Network.ToString(), "Network"); + Assert.AreEqual(netmask, ipnetwork.Netmask.ToString(), "Netmask"); + Assert.AreEqual(broadcast, ipnetwork.Broadcast.ToString(), "Broadcast"); + Assert.AreEqual(cidr, ipnetwork.Cidr, "Cidr"); + Assert.AreEqual(usable, ipnetwork.Usable, "Usable"); + Assert.AreEqual(firstUsable, ipnetwork.FirstUsable.ToString(), "FirstUsable"); + Assert.AreEqual(lastUsable, ipnetwork.LastUsable.ToString(), "LastUsable"); + + } + + + + [TestMethod] + public void TestTryParseStringAE1() { + string ipaddress = "garbage"; + IPNetwork ipnetwork = null; + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(false, parsed, "parsed"); + } + + [TestMethod] + public void TestTryParseStringAE2() { + string ipaddress = "0.0.0.0 0.0.1.0"; + IPNetwork ipnetwork = null; + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(false, parsed, "parsed"); + } + + [TestMethod] + public void TestTryParseStringANE1() { + string ipaddress = null; + IPNetwork ipnetwork = null; + bool parsed = IPNetwork.TryParse(ipaddress, out ipnetwork); + Assert.AreEqual(false, parsed, "parsed"); + } + + + + #endregion + + #region ParseStringString + + [TestMethod] + public void TestParseStringString1() { + + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + Assert.AreEqual("192.168.168.0/24", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString2() { + + string ipaddress = null; + string netmask = null; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString3() { + + string ipaddress = "192.168.168.100"; + string netmask = null; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString4() { + + string ipaddress = ""; + string netmask = ""; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestParseStringString5() { + + string ipaddress = "192.168.168.100"; + string netmask = ""; + + IPNetwork ipnetwork = IPNetwork.Parse(ipaddress, netmask); + + } + + #endregion + + #region ParseIpIp + + [TestMethod] + public void ParseIpIp1() { + + string ipaddress = "192.168.168.100"; + string netmask = "255.255.255.0"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = IPAddress.Parse(netmask); + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + Assert.AreEqual("192.168.168.0/24", ipnetwork.ToString(), "network"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void ParseIpIp2() { + + IPAddress ip = null; + IPAddress netm = null; + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void ParseIpIp3() { + + string ipaddress = "192.168.168.100"; + IPAddress ip = IPAddress.Parse(ipaddress); + IPAddress netm = null; + IPNetwork ipnetwork = IPNetwork.Parse(ip, netm); + + } + + #endregion + + #region ToCidr + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestToCidrANE() { + IPNetwork.ToCidr(null); + } + + [TestMethod] + public void TestToCidrAE() { + byte cidr = IPNetwork.ToCidr(IPAddress.IPv6Any); + Assert.AreEqual(0, cidr, "cidr"); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestToCidrAE2() { + IPNetwork.ToCidr(IPAddress.Parse("6.6.6.6")); + } + + + [TestMethod] + public void TestToCidr32() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + byte cidr = 32; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr24() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + byte cidr = 24; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr16() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + byte cidr = 16; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr8() { + + IPAddress mask = IPAddress.Parse("255.0.0.0"); + byte cidr = 8; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestToCidr0() { + + IPAddress mask = IPAddress.Parse("0.0.0.0"); + byte cidr = 0; + int result = IPNetwork.ToCidr(mask); + + Assert.AreEqual(cidr, result, "cidr"); + } + + #endregion + + #region TryToCidr + + [TestMethod] + public void TestTryToCidrANE() { + byte? cidr = null; + bool parsed = IPNetwork.TryToCidr(null, out cidr); + Assert.AreEqual(false, parsed, "parsed"); + } + + [TestMethod] + public void TestTryToCidrAE() { + byte? cidr = null; + bool parsed = IPNetwork.TryToCidr(IPAddress.IPv6Any, out cidr); + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual((byte)0, cidr, "cidr"); + } + + + [TestMethod] + public void TestTryToCidrAE2() { + byte? cidr = null; + bool parsed = IPNetwork.TryToCidr(IPAddress.Parse("6.6.6.6"), out cidr); + Assert.AreEqual(false, parsed, "parsed"); + } + + + [TestMethod] + public void TestTryToCidr32() { + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.255.255.255"); + byte result = 32; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + } + [TestMethod] + public void TestTryToCidr24() { + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.255.255.0"); + byte result = 24; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + [TestMethod] + public void TestTryToCidr16() { + + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.255.0.0"); + byte result = 16; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + [TestMethod] + public void TestTryToCidr8() { + + + byte? cidr = null; + IPAddress mask = IPAddress.Parse("255.0.0.0"); + byte result = 8; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + [TestMethod] + public void TestTryToCidr0() { + + byte? cidr = null; + IPAddress mask = IPAddress.Parse("0.0.0.0"); + byte result = 0; + bool parsed = IPNetwork.TryToCidr(mask, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(cidr, result, "cidr"); + + } + + #endregion + + #region ToBigInteger + + [TestMethod] + public void TestToBigInteger32() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + uint uintMask = 0xffffffff; + BigInteger result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger24() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + uint uintMask = 0xffffff00; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger16() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + uint uintMask = 0xffff0000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger8() { + + IPAddress mask = IPAddress.Parse("255.0.0.0"); + uint uintMask = 0xff000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + public void TestToBigInteger0() { + + IPAddress mask = IPAddress.Parse("0.0.0.0"); + uint uintMask = 0x00000000; + BigInteger? result = IPNetwork.ToBigInteger(mask); + + Assert.AreEqual(uintMask, result, "uint"); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestToBigIntegerANE() { + BigInteger? result = IPNetwork.ToBigInteger(null); + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestToBigIntegerANE3() { + IPAddress ip = null; + BigInteger? result = IPNetwork.ToBigInteger(ip); + } + [TestMethod] + public void TestToBigIntegerANE2() { + BigInteger? result = IPNetwork.ToBigInteger(IPAddress.IPv6Any); + uint expected = 0; + Assert.AreEqual(expected, result, "result"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestToBigIntegerByte() { + BigInteger result = IPNetwork.ToUint(33, Sockets.AddressFamily.InterNetwork); + } + + [TestMethod] + public void TestToBigIntegerByte2() { + BigInteger result = IPNetwork.ToUint(32, Sockets.AddressFamily.InterNetwork); + uint expected = 4294967295; + Assert.AreEqual(expected, result, "result"); + + } + + + [TestMethod] + public void TestToBigIntegerByte3() { + BigInteger result = IPNetwork.ToUint(0, Sockets.AddressFamily.InterNetwork); + uint expected = 0; + Assert.AreEqual(expected, result, "result"); + + } + + + + #endregion + + #region TryToBigInteger + + [TestMethod] + public void TestTryToBigInteger32() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + uint uintMask = 0xffffffff; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger24() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + uint uintMask = 0xffffff00; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger16() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + uint uintMask = 0xffff0000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger8() { + + IPAddress mask = IPAddress.Parse("255.0.0.0"); + uint uintMask = 0xff000000; + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigInteger0() { + + IPAddress mask = IPAddress.Parse("0.0.0.0"); + uint uintMask = 0x00000000; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(mask, out result); + + Assert.AreEqual(uintMask, result, "uint"); + Assert.AreEqual(true, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigIntegerANE() { + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(null, out result); + + Assert.AreEqual(null, result, "uint"); + Assert.AreEqual(false, parsed, "parsed"); + + } + [TestMethod] + public void TestTryToBigIntegerANE3() { + IPAddress ip = null; + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(ip, out result); + + Assert.AreEqual(null, result, "uint"); + Assert.AreEqual(false, parsed, "parsed"); + } + [TestMethod] + public void TestTryToBigIntegerANE2() { + + BigInteger? result = null; + bool parsed = IPNetwork.TryToBigInteger(IPAddress.IPv6Any, out result); + + Assert.AreEqual(0, result, "result"); + Assert.AreEqual(true, parsed, "parsed"); + } + + + + #endregion + + #region TryToNetmask + [TestMethod] + public void TryToNetmask1() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(0, Sockets.AddressFamily.InterNetwork, out result); + IPAddress expected = IPAddress.Parse("0.0.0.0"); + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(true, parsed, "parsed"); + + } + + [TestMethod] + public void TryToNetmask2() { + IPAddress result = null; + bool parsed = IPNetwork.TryToNetmask(33, Sockets.AddressFamily.InterNetwork, out result); + IPAddress expected = null; + + Assert.AreEqual(expected, result, "Netmask"); + Assert.AreEqual(false, parsed, "parsed"); + + } + + #endregion + + #region ToNetmask + + [TestMethod] + public void ToNetmask32() { + + byte cidr = 32; + string netmask = "255.255.255.255"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask31() { + + byte cidr = 31; + string netmask = "255.255.255.254"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask30() { + + byte cidr = 30; + string netmask = "255.255.255.252"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask29() { + + byte cidr = 29; + string netmask = "255.255.255.248"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + public void ToNetmask1() { + + byte cidr = 1; + string netmask = "128.0.0.0"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + + [TestMethod] + public void ToNetmask0() { + + byte cidr = 0; + string netmask = "0.0.0.0"; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + + Assert.AreEqual(netmask, result, "netmask"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void ToNetmaskOORE1() { + byte cidr = 33; + string result = IPNetwork.ToNetmask(cidr, Sockets.AddressFamily.InterNetwork).ToString(); + } + + #endregion + + #region ValidNetmask + + [TestMethod] + public void TestValidNetmask0() { + + IPAddress mask = IPAddress.Parse("255.255.255.255"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask1() { + + IPAddress mask = IPAddress.Parse("255.255.255.0"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + [TestMethod] + public void TestValidNetmask2() { + + IPAddress mask = IPAddress.Parse("255.255.0.0"); + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + public void TestValidNetmaskEAE1() { + + IPAddress mask = IPAddress.Parse("0.255.0.0"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestValidNetmaskEAE2() { + + IPAddress mask = null; + bool expected = true; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + + [TestMethod] + public void TestValidNetmaskEAE3() { + + IPAddress mask = IPAddress.Parse("255.255.0.1"); + bool expected = false; + bool result = IPNetwork.ValidNetmask(mask); + + Assert.AreEqual(expected, result, "ValidNetmask"); + } + + #endregion + + #region BitsSet + + [TestMethod] + public void TestBitsSet32() { + + IPAddress ip = IPAddress.Parse("255.255.255.255"); + uint bits = 32; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet24() { + + IPAddress ip = IPAddress.Parse("255.255.255.0"); + uint bits = 24; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet16() { + + IPAddress ip = IPAddress.Parse("255.255.0.0"); + uint bits = 16; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + [TestMethod] + public void TestBitsSet4() { + + IPAddress ip = IPAddress.Parse("128.128.128.128"); + uint bits = 4; + uint result = IPNetwork.BitsSet(ip); + + Assert.AreEqual(bits, result, "BitsSet"); + + } + + #endregion + + #region Contains + + [TestMethod] + public void TestContains1() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/24"); + IPAddress ipaddress = IPAddress.Parse("192.168.0.100"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains2() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/24"); + IPAddress ipaddress = IPAddress.Parse("10.10.10.10"); + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains3() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.0.1/24"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains4() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/16"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.1/24"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = true; + + Assert.AreEqual(expected, result, "contains"); + + } + + [TestMethod] + public void TestContains5() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/16"); + IPNetwork ipnetwork2 = IPNetwork.Parse("10.10.10.0/24"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + + [TestMethod] + public void TestContains6() + { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.0.0/16"); + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool expected = false; + + Assert.AreEqual(expected, result, "contains"); + + } + + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains7() + { + + IPNetwork ipnetwork = null; + IPNetwork ipnetwork2 = null; + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains8() + { + + IPNetwork ipnetwork = IPNetwork.Parse("0.0.0.0/0"); + IPNetwork ipnetwork2 = null; + + bool result = IPNetwork.Contains(ipnetwork, ipnetwork2); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains9() + { + + IPNetwork ipnetwork = null; + IPAddress ipaddress = null; + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + + } + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestContains10() + { + + IPNetwork ipnetwork = IPNetwork.Parse("0.0.0.0/0"); + IPAddress ipaddress = null; + + bool result = IPNetwork.Contains(ipnetwork, ipaddress); + + } + + #endregion + + #region Overlap + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestOverlap1() + { + IPNetwork network1 = null; + IPNetwork network2 = null; + IPNetwork.Overlap(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestOverlap2() + { + IPNetwork network1 = IPNetwork.Parse("10.0.0.0/0"); + IPNetwork network2 = null; + IPNetwork.Overlap(network1, network2); + } + + [TestMethod] + public void TestOverlap3() + { + IPNetwork network1 = IPNetwork.Parse("10.0.0.0/0"); + IPNetwork network2 = IPNetwork.Parse("10.0.0.0/0"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap4() + { + IPNetwork network1 = IPNetwork.Parse("10.10.0.0/16"); + IPNetwork network2 = IPNetwork.Parse("10.10.1.0/24"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap5() + { + IPNetwork network1 = IPNetwork.Parse("10.10.0.0/24"); + IPNetwork network2 = IPNetwork.Parse("10.10.1.0/24"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = false; + + Assert.AreEqual(expected, result, "overlap"); + } + + [TestMethod] + public void TestOverlap6() + { + IPNetwork network1 = IPNetwork.Parse("10.10.1.0/24"); + IPNetwork network2 = IPNetwork.Parse("10.10.0.0/16"); + bool result = IPNetwork.Overlap(network1, network2); + bool expected = true; + + Assert.AreEqual(expected, result, "overlap"); + } + + #endregion + + #region Examples + + public void Example1() + { + IPNetwork ipnetwork = IPNetwork.Parse("192.168.168.100/24"); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + public void Example2() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.0/24"); + IPAddress ipaddress = IPAddress.Parse("192.168.0.100"); + IPAddress ipaddress2 = IPAddress.Parse("192.168.1.100"); + + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.0.128/25"); + IPNetwork ipnetwork3 = IPNetwork.Parse("192.168.1.1/24"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + bool contains3 = IPNetwork.Contains(ipnetwork, ipnetwork2); + bool contains4 = IPNetwork.Contains(ipnetwork, ipnetwork3); + + bool overlap1 = IPNetwork.Overlap(ipnetwork, ipnetwork2); + bool overlap2 = IPNetwork.Overlap(ipnetwork, ipnetwork3); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork2, contains3); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipnetwork3, contains4); + + + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork2, overlap1); + Console.WriteLine("{0} overlap {1} : {2}", ipnetwork, ipnetwork3, overlap2); + + + } + + public void Example2b() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("10.1.0.0/16"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.0/24"); + + IPAddress ipaddress1 = IPAddress.Parse("192.168.1.1"); + IPAddress ipaddress2 = IPAddress.Parse("192.168.2.100"); + IPAddress ipaddress3 = IPAddress.Parse("10.1.2.3"); + IPAddress ipaddress4 = IPAddress.Parse("10.4.5.6"); + + + bool contains1 = IPNetwork.Contains(ipnetwork2, ipaddress1); + bool contains2 = IPNetwork.Contains(ipnetwork2, ipaddress2); + bool contains3 = IPNetwork.Contains(ipnetwork1, ipaddress3); + bool contains4 = IPNetwork.Contains(ipnetwork1, ipaddress4); + + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork1, ipaddress1, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork1, ipaddress2, contains2); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork2, ipaddress3, contains3); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork2, ipaddress4, contains4); + + + } + + public void Example3() + { + + IPNetwork iana_a_block = IPNetwork.IANA_ABLK_RESERVED1; + IPNetwork iana_b_block = IPNetwork.IANA_BBLK_RESERVED1; + IPNetwork iana_c_block = IPNetwork.IANA_CBLK_RESERVED1; + + Console.WriteLine("IANA_ABLK_RESERVED1 is {0}", iana_a_block); + Console.WriteLine("IANA_BBLK_RESERVED1 is {0}", iana_b_block); + Console.WriteLine("IANA_CBLK_RESERVED1 is {0}", iana_c_block); + + } + + + public void Example4() + { + IPNetwork wholeInternet = IPNetwork.Parse("0.0.0.0/0"); + byte newCidr = 2; + IPNetworkCollection subneted = IPNetwork.Subnet(wholeInternet, newCidr); + + Console.WriteLine("{0} was subnetted into {1} subnets", wholeInternet, subneted.Count); + Console.WriteLine("First: {0}", subneted[0]); + Console.WriteLine("Last : {0}", subneted[subneted.Count - 1]); + Console.WriteLine("All :"); + + foreach (IPNetwork ipnetwork in subneted) + { + Console.WriteLine("{0}", ipnetwork); + } + } + + public void Example5() + { + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.0/24"); + IPNetwork[] ipnetwork3 = IPNetwork.Supernet(new[]{ipnetwork1, ipnetwork2}); + + Console.WriteLine("{0} + {1} = {2}", ipnetwork1, ipnetwork2, ipnetwork3[0]); + + } + + + + public void Example7() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.168.100/24"); + + IPAddress ipaddress = IPAddress.Parse("192.168.168.200"); + IPAddress ipaddress2 = IPAddress.Parse("192.168.0.200"); + + bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress); + bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2); + + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1); + Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2); + + } + public void Example9() { + + IPNetwork network = IPNetwork.Parse("192.168.0.1"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.254"); + + IPNetwork ipnetwork = IPNetwork.Supernet(network, network2); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + + public void Example10() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/25"); + + Console.WriteLine("Network : {0}", ipnetwork.Network); + Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); + Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); + Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); + Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); + Console.WriteLine("Usable : {0}", ipnetwork.Usable); + Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); + + } + + #endregion + + #region IANA blocks + [TestMethod] + public void TestIANA1() { + + IPAddress ipaddress = IPAddress.Parse("192.168.66.66"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA2() { + + IPAddress ipaddress = IPAddress.Parse("10.0.0.0"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA3() { + + IPAddress ipaddress = IPAddress.Parse("172.17.10.10"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA4() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.66.66/24"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA5() { + + IPNetwork ipnetwork = IPNetwork.Parse("10.10.10/18"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA6() { + + IPNetwork ipnetwork = IPNetwork.Parse("172.31.10.10/24"); + bool expected = true; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestIANA7() { + + IPAddress ipaddress = null; + IPNetwork.IsIANAReserved(ipaddress); + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestIANA8() { + + IPNetwork ipnetwork = null; + IPNetwork.IsIANAReserved(ipnetwork); + + + } + + + [TestMethod] + public void TestIANA9() { + + IPAddress ipaddress = IPAddress.Parse("1.2.3.4"); + bool expected = false; + bool result = IPNetwork.IsIANAReserved(ipaddress); + + Assert.AreEqual(expected, result, "IANA"); + + } + + [TestMethod] + public void TestIANA10() { + + IPNetwork ipnetwork = IPNetwork.Parse("172.16.0.0/8"); + bool expected = false; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + + + [TestMethod] + public void TestIANA11() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/8"); + bool expected = false; + bool result = IPNetwork.IsIANAReserved(ipnetwork); + + Assert.AreEqual(expected, result, "IANA"); + + } + #endregion + + #region ToString + + + [TestMethod] + public void TestToString() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/8"); + string expected = "192.0.0.0/8"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString1() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/9"); + string expected = "192.128.0.0/9"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString2() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/10"); + string expected = "192.128.0.0/10"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString3() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/11"); + string expected = "192.160.0.0/11"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString4() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/12"); + string expected = "192.160.0.0/12"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString5() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/13"); + string expected = "192.168.0.0/13"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString6() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/14"); + string expected = "192.168.0.0/14"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + [TestMethod] + public void TestToString7() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/15"); + string expected = "192.168.0.0/15"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + [TestMethod] + public void TestToString8() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.15.1/16"); + string expected = "192.168.0.0/16"; + string result = ipnetwork.ToString(); + + Assert.AreEqual(expected, result, "ToString"); + } + + #endregion + + #region Subnet + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestSubnet1() { + + IPNetwork ipnetwork = null; + byte cidr = 9; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet3() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 55; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSubnet4() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 1; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + + } + + + [TestMethod] + public void TestSubnet5() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 9; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("10.0.0.0/9", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("10.128.0.0/9", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestSubnet6() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/20", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.16.0/20", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("192.168.32.0/20", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("192.168.48.0/20", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("192.168.64.0/20", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("192.168.80.0/20", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("192.168.96.0/20", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("192.168.112.0/20", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("192.168.128.0/20", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("192.168.144.0/20", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("192.168.160.0/20", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("192.168.176.0/20", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("192.168.192.0/20", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("192.168.208.0/20", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("192.168.224.0/20", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("192.168.240.0/20", subnets[15].ToString(), "subnet16"); + + } + + + [TestMethod] + public void TestSubnet7() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 24; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/24", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.255.0/24", subnets[255].ToString(), "subnet16"); + + } + + + [TestMethod] + public void TestSubnet8() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 24; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/24", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.255.0/24", subnets[255].ToString(), "subnet256"); + + } + + [TestMethod] + public void TestSubnet9() { + + IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.0/24"); + byte cidr = 32; + + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(256, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/32", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.0.255/32", subnets[255].ToString(), "subnet256"); + + } + + + [TestMethod] + public void TestSubnet10() + { + IPNetwork ipnetwork = IPNetwork.Parse("0.0.0.0/0"); + byte cidr = 32; + + // Here I spawm a OOM dragon ! beware of the beast ! + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + Assert.AreEqual(4294967296, subnets.Count, "count"); + Assert.AreEqual("0.0.0.0/32", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("255.255.255.255/32", subnets[4294967295].ToString(), "subnet256"); + + } + + + [TestMethod] + public void TestSubnet12() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + int i = -1; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + foreach (IPNetwork ipn in subnets) { + i++; + Assert.AreEqual(subnets[i], ipn, "subnet"); + } + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSubnet13() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); + IPNetwork error = subnets[1000]; + + } + + #endregion + + #region TrySubnet + + + [TestMethod] + public void TestTrySubnet1() { + + IPNetwork ipnetwork = null; + byte cidr = 9; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + + } + + [TestMethod] + public void TestTrySubnet3() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 55; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + } + + + [TestMethod] + public void TestTrySubnet4() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 1; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(false, subnetted, "subnetted"); + + } + + + [TestMethod] + public void TestTrySubnet5() { + + IPNetwork ipnetwork = IPNetwork.IANA_ABLK_RESERVED1; + byte cidr = 9; + + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(2, subnets.Count, "count"); + Assert.AreEqual("10.0.0.0/9", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("10.128.0.0/9", subnets[1].ToString(), "subnet2"); + + } + + + [TestMethod] + public void TestTrySubnet6() { + + IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; + byte cidr = 20; + + IPNetworkCollection subnets = null; + bool subnetted = IPNetwork.TrySubnet(ipnetwork, cidr, out subnets); + + Assert.AreEqual(true, subnetted, "subnetted"); + Assert.AreEqual(16, subnets.Count, "count"); + Assert.AreEqual("192.168.0.0/20", subnets[0].ToString(), "subnet1"); + Assert.AreEqual("192.168.16.0/20", subnets[1].ToString(), "subnet2"); + Assert.AreEqual("192.168.32.0/20", subnets[2].ToString(), "subnet3"); + Assert.AreEqual("192.168.48.0/20", subnets[3].ToString(), "subnet4"); + Assert.AreEqual("192.168.64.0/20", subnets[4].ToString(), "subnet5"); + Assert.AreEqual("192.168.80.0/20", subnets[5].ToString(), "subnet6"); + Assert.AreEqual("192.168.96.0/20", subnets[6].ToString(), "subnet7"); + Assert.AreEqual("192.168.112.0/20", subnets[7].ToString(), "subnet8"); + Assert.AreEqual("192.168.128.0/20", subnets[8].ToString(), "subnet9"); + Assert.AreEqual("192.168.144.0/20", subnets[9].ToString(), "subnet10"); + Assert.AreEqual("192.168.160.0/20", subnets[10].ToString(), "subnet11"); + Assert.AreEqual("192.168.176.0/20", subnets[11].ToString(), "subnet12"); + Assert.AreEqual("192.168.192.0/20", subnets[12].ToString(), "subnet13"); + Assert.AreEqual("192.168.208.0/20", subnets[13].ToString(), "subnet14"); + Assert.AreEqual("192.168.224.0/20", subnets[14].ToString(), "subnet15"); + Assert.AreEqual("192.168.240.0/20", subnets[15].ToString(), "subnet16"); + + } + + + + #endregion + + #region Supernet + + [TestMethod] + public void TestSupernet1() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork expected = IPNetwork.Parse("192.168.0.0/23"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + Assert.AreEqual(expected, supernet, "supernet"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestSupernet2() { + + IPNetwork network1 = null; + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestSupernet3() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = null; + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSupernet4() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/25"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void TestSupernet5() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.5.1/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + } + + [TestMethod] + public void TestSupernet6() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork expected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + Assert.AreEqual(expected, supernet, "supernet"); + + } + + [TestMethod] + public void TestSupernet7() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork expected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + Assert.AreEqual(expected, supernet, "supernet"); + + } + + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestSupernet8() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork supernet = IPNetwork.Supernet(network1, network2); + + + } + + + [TestMethod] + public void TestSupernet9() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("200.16.0.0/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("200.16.1.0/24"); + IPNetwork ipnetwork3 = IPNetwork.Parse("200.16.2.0/24"); + IPNetwork ipnetwork4 = IPNetwork.Parse("200.16.3.0/24"); + + IPNetwork result = IPNetwork.Supernet(new[] { ipnetwork1, ipnetwork2, ipnetwork3, ipnetwork4 })[0]; + IPNetwork expected = IPNetwork.Parse("200.16.0.0/22"); + + Assert.AreEqual(expected, result, "supernet"); + + } + + #endregion + + #region TrySupernet + + + [TestMethod] + public void TestTrySupernet1() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork supernetExpected = IPNetwork.Parse("192.168.0.0/23"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet2() { + + IPNetwork network1 = null; + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet3() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = null; + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet4() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/25"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet5() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.5.1/24"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + } + + [TestMethod] + public void TestTrySupernet6() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork supernetExpected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet7() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/25"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork supernetExpected = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet8() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork supernetExpected = null; + IPNetwork supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network1, network2, out supernet); + + Assert.AreEqual(supernetExpected, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + [TestMethod] + public void TestTrySupernet9() { + + IPNetwork network1 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.2.1/24"); + IPNetwork[] network3 = new [] { network1, network2 }; + IPNetwork[] supernetExpected = new [] { network1, network2 }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(supernetExpected[1], supernet[1], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet10() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + IPNetwork[] network3 = new[] { network1, network2 }; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("192.168.0.0/23") }; + IPNetwork[] supernet; + bool parsed = true; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(supernetExpected[0], supernet[0], "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + [TestMethod] + public void TestTrySupernet11() { + + IPNetwork[] network3 = null; + IPNetwork[] supernetExpected = new[] { IPNetwork.Parse("192.168.0.0/23") }; + IPNetwork[] supernet; + bool parsed = false; + bool result = IPNetwork.TrySupernet(network3, out supernet); + + Assert.AreEqual(null, supernet, "supernet"); + Assert.AreEqual(parsed, result, "parsed"); + + } + + + #endregion + + #region SupernetArray + + [TestMethod] + public void TestTrySupernetArray() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/24"); + IPNetwork ipnetwork2 = IPNetwork.Parse("192.168.1.0/24"); + IPNetwork ipnetwork3 = IPNetwork.Parse("192.168.2.0/24"); + IPNetwork ipnetwork4 = IPNetwork.Parse("192.168.3.0/24"); + + IPNetwork[] ipnetworks = { ipnetwork1, ipnetwork2, ipnetwork3, ipnetwork4 }; + IPNetwork[] expected = { IPNetwork.Parse("192.168.0.0/22") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], expected[0], "suppernet"); + + } + + [TestMethod] + public void TestTrySupernetArray1() + { + + + IPNetwork[] ipnetworks = { }; + IPNetwork[] expected = { }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestTrySupernetArray2() + { + + + IPNetwork[] ipnetworks = null; + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + } + + + [TestMethod] + public void TestTrySupernetArray3() + { + + IPNetwork ipnetwork1 = null; + IPNetwork ipnetwork2 = null; + IPNetwork ipnetwork3 = null; + IPNetwork ipnetwork4 = null; + + IPNetwork[] ipnetworks = { ipnetwork1, ipnetwork2, ipnetwork3, ipnetwork4 }; + IPNetwork[] expected = { }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + + } + + [TestMethod] + public void TestTrySupernetArray4() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/24"); + IPNetworkCollection subnetted = IPNetwork.Subnet(ipnetwork1, 32); + IPNetwork[] ipnetworks = subnetted.ToArray(); + Assert.AreEqual(256, ipnetworks.Length, "subnet"); + + IPNetwork[] expected = { IPNetwork.Parse("192.168.0.0/24") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], ipnetwork1, "suppernet"); + } + + + [TestMethod] + public void TestTrySupernetArray5() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/16"); + IPNetworkCollection subnetted = IPNetwork.Subnet(ipnetwork1, 32); + IPNetwork[] ipnetworks = subnetted.ToArray(); + Assert.AreEqual(65536, ipnetworks.Length, "subnet"); + + IPNetwork[] expected = { IPNetwork.Parse("192.168.0.0/16") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], ipnetwork1, "suppernet"); + } + + public void TestTrySupernetArray6() + { + + IPNetwork ipnetwork1 = IPNetwork.Parse("192.168.0.0/8"); + IPNetworkCollection subnetted = IPNetwork.Subnet(ipnetwork1, 32); + IPNetwork[] ipnetworks = subnetted.ToArray(); + Assert.AreEqual(16777216, ipnetworks.Length, "subnet"); + + IPNetwork[] expected = { IPNetwork.Parse("192.0.0.0/8") }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], ipnetwork1, "suppernet"); + } + + [TestMethod] + public void TestTrySupernetArray7() + { + + IPNetwork[] ipnetworks = { + IPNetwork.Parse("10.0.2.2/24"), + IPNetwork.Parse("192.168.0.0/24"), + IPNetwork.Parse("192.168.1.0/24"), + IPNetwork.Parse("192.168.2.0/24"), + IPNetwork.Parse("10.0.1.1/24"), + IPNetwork.Parse("192.168.3.0/24") + }; + + IPNetwork[] expected = { + IPNetwork.Parse("10.0.1.0/24"), + IPNetwork.Parse("10.0.2.0/24"), + IPNetwork.Parse("192.168.0/22") + }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], result[0], "suppernet"); + Assert.AreEqual(expected[1], result[1], "suppernet1"); + Assert.AreEqual(expected[2], result[2], "suppernet2"); + } + + [TestMethod] + public void TestTrySupernetArray8() + { + + IPNetwork[] ipnetworks = { + IPNetwork.Parse("10.0.2.2/24"), + IPNetwork.Parse("192.168.0.0/24"), + IPNetwork.Parse("192.168.1.0/24"), + IPNetwork.Parse("192.168.2.0/24"), + IPNetwork.Parse("10.0.1.1/24"), + IPNetwork.Parse("192.168.3.0/24"), + IPNetwork.Parse("10.6.6.6/8") + + }; + + IPNetwork[] expected = { + IPNetwork.Parse("10.0.0.0/8"), + IPNetwork.Parse("192.168.0/22") + }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], result[0], "suppernet"); + Assert.AreEqual(expected[1], result[1], "suppernet1"); + } + + + [TestMethod] + public void TestTrySupernetArray9() + { + + IPNetwork[] ipnetworks = { + IPNetwork.Parse("10.0.2.2/24"), + IPNetwork.Parse("192.168.0.0/24"), + IPNetwork.Parse("192.168.1.0/24"), + IPNetwork.Parse("192.168.2.0/24"), + IPNetwork.Parse("10.0.1.1/24"), + IPNetwork.Parse("192.168.3.0/24"), + IPNetwork.Parse("10.6.6.6/8"), + IPNetwork.Parse("11.6.6.6/8"), + IPNetwork.Parse("12.6.6.6/8"), + + }; + + IPNetwork[] expected = { + IPNetwork.Parse("10.0.0.0/7"), + IPNetwork.Parse("12.0.0.0/8"), + IPNetwork.Parse("192.168.0/22") + }; + + IPNetwork[] result = IPNetwork.Supernet(ipnetworks); + + Assert.AreEqual(expected.Length, result.Length, "supernetarray"); + Assert.AreEqual(expected[0], result[0], "suppernet"); + Assert.AreEqual(expected[1], result[1], "suppernet1"); + Assert.AreEqual(expected[2], result[2], "suppernet2"); + } + + + #endregion + + #region Equals + + [TestMethod] + public void TestEquals1() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/24"); + bool result = network1.Equals(network2); + bool expected = true; + + Assert.AreEqual(expected, result, "equals"); + + } + + [TestMethod] + public void TestEquals2() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = null; + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + [TestMethod] + public void TestEquals3() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + object network2 = ""; + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + [TestMethod] + public void TestEquals4() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.0.1/25"); + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + + [TestMethod] + public void TestEquals5() { + + IPNetwork network1 = IPNetwork.Parse("192.168.0.1/24"); + IPNetwork network2 = IPNetwork.Parse("192.168.1.1/24"); + bool result = network1.Equals(network2); + bool expected = false; + + Assert.AreEqual(expected, result, "equals"); + + } + + #endregion + + #region WideSubnet + + [TestMethod] + public void TestWideSubnet1() { + + string start = "192.168.168.0"; + string end = "192.168.168.255"; + IPNetwork expected = IPNetwork.Parse("192.168.168.0/24"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestWideSubnet2() { + + string start = null; + string end = "192.168.168.255"; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void TestWideSubnet3() { + + string start = "192.168.168.255"; + string end = null; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + + } + + [TestMethod] + public void TestWideSubnet4() { + + string start = "192.168.168.255"; + string end = "192.168.168.0"; + + + IPNetwork expected = IPNetwork.Parse("192.168.168.0/24"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + } + + + [TestMethod] + public void TestWideSubnet7() { + + string start = "0.0.0.0"; + string end = "0.255.255.255"; + + IPNetwork expected = IPNetwork.Parse("0.0.0.0/8"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + } + + + + [TestMethod] + public void TestWideSubnet8() { + + string start = "1.2.3.4"; + string end = "5.6.7.8"; + + IPNetwork expected = IPNetwork.Parse("0.0.0.0/5"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + } + + + [TestMethod] + public void TestWideSubnet9() + { + + string start = "200.16.0.0/24"; + string end = "200.16.3.0/24"; + var firt = IPNetwork.Parse(start).FirstUsable.ToString(); + var last = IPNetwork.Parse(end).LastUsable.ToString(); + + IPNetwork expected = IPNetwork.Parse("200.16.0.0/22"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(firt, last); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + + + + } + + + [TestMethod] + public void TestWideSubnet10() + { + + string start = "200.16.0.0"; + string end = "200.16.3.255"; + + IPNetwork expected = IPNetwork.Parse("200.16.0.0/22"); + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + Assert.AreEqual(expected, wideSubnet, "wideSubnet"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestWideSubnetInvalid1() { + + string start = "invalid"; + string end = "5.6.7.8"; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void TestWideSubnetInvalid2() { + + string start = "1.2.3.4"; + string end = "invalid"; + + IPNetwork wideSubnet = IPNetwork.WideSubnet(start, end); + } + + #endregion + + #region TryGuessCidr + + [TestMethod] + public void TestTryGuessCidrNull() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr(null, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(0, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrA() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("10.0.0.0", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(8, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrB() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("172.0.0.0", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(16, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrC() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("192.0.0.0", out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(24, cidr, "cidr"); + } + + [TestMethod] + public void TestTryGuessCidrD() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("224.0.0.0", out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + } + [TestMethod] + public void TestTryGuessCidrE() { + + byte cidr; + bool parsed = IPNetwork.TryGuessCidr("240.0.0.0", out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + } + + #endregion + + #region GetHashCode + + [TestMethod] + public void TestGetHashCode1() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("0.0.1.1/0"); + IPNetwork ipnetwork2 = IPNetwork.Parse("0.0.1.1/0"); + int hashCode1 = ipnetwork1.GetHashCode(); + int hashCode2 = ipnetwork2.GetHashCode(); + Assert.AreEqual(hashCode1, hashCode2, "hashcode"); + + } + + [TestMethod] + public void TestGetHashCode2() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("0.0.0.0/1"); + IPNetwork ipnetwork2 = IPNetwork.Parse("0.0.0.0/1"); + int hashCode1 = ipnetwork1.GetHashCode(); + int hashCode2 = ipnetwork2.GetHashCode(); + Assert.AreEqual(hashCode1, hashCode2, "hashcode"); + + } + [TestMethod] + public void TestGetHashCode3() { + + IPNetwork ipnetwork1 = IPNetwork.Parse("0.0.0.0/32"); + IPNetwork ipnetwork2 = IPNetwork.Parse("0.0.0.0/32"); + int hashCode1 = ipnetwork1.GetHashCode(); + int hashCode2 = ipnetwork2.GetHashCode(); + Assert.AreEqual(hashCode1, hashCode2, "hashcode"); + + } + + #endregion + + #region Print + + [TestMethod] + public void Print() { + IPNetwork ipn = IPNetwork.Parse("0.0.0.0/0"); + string print = IPNetwork.Print(ipn).Replace("\r", ""); + string expected = @"IPNetwork : 0.0.0.0/0 +Network : 0.0.0.0 +Netmask : 0.0.0.0 +Cidr : 0 +Broadcast : 255.255.255.255 +FirstUsable : 0.0.0.1 +LastUsable : 255.255.255.254 +Usable : 4294967294 +".Replace("\r", ""); + + Assert.AreEqual(expected, print, "Print"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void PrintNull() { + IPNetwork ipn = null; + string print = IPNetwork.Print(ipn); + } + + #endregion + + #region Sort + + [TestMethod] + public void TestSort1() { + string[] ips = new[] { "1.1.1.1", "255.255.255.255", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach(string ip in ips) { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) { + ipns.Add(ipn); + } + } + + ipns.Sort(); + Assert.AreEqual("0.0.0.0/32", ipns[0].ToString(), "0"); + Assert.AreEqual("1.1.1.1/32", ipns[1].ToString(), "1"); + Assert.AreEqual("2.2.2.2/32", ipns[2].ToString(), "2"); + Assert.AreEqual("255.255.255.255/32", ipns[3].ToString(), "3"); + } + + [TestMethod] + public void TestSort2() { + string[] ips = new[] { "0.0.0.100/32", "0.0.0.0/24" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, out ipn)) { + ipns.Add(ipn); + } + } + + ipns.Sort(); + Assert.AreEqual("0.0.0.0/24", ipns[0].ToString(), "0"); + Assert.AreEqual("0.0.0.100/32", ipns[1].ToString(), "1"); + } + + #endregion + + #region TryWideSubnet + + [TestMethod] + public void TryWideSubnet1() { + string[] ips = new[] { "1.1.1.1", "255.255.255.255", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(true, wide, "wide"); + Assert.AreEqual("0.0.0.0/0", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + public void TryWideSubnet2() { + string[] ips = new[] { "1.1.1.1", "10.0.0.0", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(true, wide, "wide"); + Assert.AreEqual("0.0.0.0/4", ipnetwork.ToString(), "ipnetwork"); + + } + + + [TestMethod] + public void TryWideSubnet3() { + string[] ips = new[] { "a", "b", "c", "d" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(false, wide, "wide"); + + } + + [TestMethod] + public void TryWideSubnet4() { + string[] ips = new[] { "a", "b", "1.1.1.1", "d" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(ipns.ToArray(), out ipnetwork); + Assert.AreEqual(true, wide, "wide"); + Assert.AreEqual("1.1.1.1/32", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + public void TryWideSubnetNull() { + + IPNetwork ipnetwork = null; + bool wide = IPNetwork.TryWideSubnet(null, out ipnetwork); + Assert.AreEqual(false, wide, "wide"); + + } + + #endregion + + #region WideSubnet + + [TestMethod] + public void WideSubnet1() { + string[] ips = new[] { "1.1.1.1", "255.255.255.255", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = IPNetwork.WideSubnet(ipns.ToArray()); + Assert.AreEqual("0.0.0.0/0", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + public void WideSubnet2() { + string[] ips = new[] { "1.1.1.1", "10.0.0.0", "2.2.2.2", "0.0.0.0" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = IPNetwork.WideSubnet(ipns.ToArray()); + Assert.AreEqual("0.0.0.0/4", ipnetwork.ToString(), "ipnetwork"); + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void WideSubnetNull() { + + IPNetwork ipnetwork = IPNetwork.WideSubnet(null); + + + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void WideSubnetNull2() { + + string[] ips = new[] { "a", "b", "e", "d" }; + List ipns = new List(); + foreach (string ip in ips) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, 32, out ipn)) + { + ipns.Add(ipn); + } + } + + IPNetwork ipnetwork = IPNetwork.WideSubnet(ipns.ToArray()); + + + } + + #endregion + + /** + * + #region TrySubstractNetwork + + + [TestMethod] + public void TrySubstractNetwork1() { + string[] ips = new[] { "178.82.0.0/16" }; + string substract = "178.82.131.209/32"; + + List ipns = new List(); + Array.ForEach(ips, new Action( + delegate(string ip) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, out ipn)) { + ipns.Add(ipn); + } + } + )); + + var nsubstract = IPNetwork.Parse(substract); + + IEnumerable result; + bool substracted = IPNetwork.TrySubstractNetwork(ipns.ToArray(), nsubstract, out result); + Assert.AreEqual(true, substracted, "substracted"); + + } + + [TestMethod] + public void TrySubstractNetwork2() { + string[] ips = new[] { "0.0.0.0/0" }; + string substract = "1.1.1.1/32"; + + List ipns = new List(); + Array.ForEach(ips, new Action( + delegate(string ip) + { + IPNetwork ipn; + if (IPNetwork.TryParse(ip, out ipn)) { + ipns.Add(ipn); + } + } + )); + + var nsubstract = IPNetwork.Parse(substract); + + IEnumerable result; + bool substracted = IPNetwork.TrySubstractNetwork(ipns.ToArray(), nsubstract, out result); + Assert.AreEqual(true, substracted, "substracted"); + + } + + + + #endregion + **/ + + #region Count + + [TestMethod] + public void Total32() { + var network = IPNetwork.Parse("0.0.0.0/32"); + var total = 1; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total31() { + var network = IPNetwork.Parse("0.0.0.0/31"); + var total = 2; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total30() { + var network = IPNetwork.Parse("0.0.0.0/30"); + var total = 4; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total24() { + var network = IPNetwork.Parse("0.0.0.0/24"); + var total = 256; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total16() { + var network = IPNetwork.Parse("0.0.0.0/16"); + var total = 65536; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total8() { + var network = IPNetwork.Parse("0.0.0.0/8"); + var total = 16777216; + Assert.AreEqual(total, network.Total, "Total"); + } + + [TestMethod] + public void Total0() { + var network = IPNetwork.Parse("0.0.0.0/0"); + var total = 4294967296; + Assert.AreEqual(total, network.Total, "Total"); + } + + #endregion + + #region Usable + + [TestMethod] + public void Usable32() { + var network = IPNetwork.Parse("0.0.0.0/32"); + uint usable = 0; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable31() { + var network = IPNetwork.Parse("0.0.0.0/31"); + uint usable = 0; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable30() { + var network = IPNetwork.Parse("0.0.0.0/30"); + uint usable = 2; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable24() { + var network = IPNetwork.Parse("0.0.0.0/24"); + uint usable = 254; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable16() { + var network = IPNetwork.Parse("0.0.0.0/16"); + uint usable = 65534; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable8() { + var network = IPNetwork.Parse("0.0.0.0/8"); + uint usable = 16777214; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + [TestMethod] + public void Usable0() { + var network = IPNetwork.Parse("0.0.0.0/0"); + uint usable = 4294967294; + Assert.AreEqual(usable, network.Usable, "Usable"); + } + + #endregion + + #region TryParseCidr + + [TestMethod] + public void TryParseCidr1() { + + string sidr = "0"; + byte? cidr; + byte? result = 0; + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetwork, out cidr); + + Assert.AreEqual(true, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr2() { + + string sidr = "sadsd"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetwork, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + [TestMethod] + public void TryParseCidr3() { + + string sidr = "33"; + byte? cidr; + byte? result = null; + + bool parsed = IPNetwork.TryParseCidr(sidr, Sockets.AddressFamily.InterNetwork, out cidr); + + Assert.AreEqual(false, parsed, "parsed"); + Assert.AreEqual(result, cidr, "cidr"); + + } + + #endregion + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource subnets of type System.Net.IPNetworkCollection in method "Void IPNetworkUnitTest.TestSubnet8()". + +### Severity: +ERROR + +### Procedure: +Void IPNetworkUnitTest.TestSubnet8() + +### File: +src/System.Net.IPNetwork.TestProject.Source/IPNetworkUnitTest.cs + +### Key: +IPNetworkUnitTest.cs|TestSubnet8|DOTNET_RESOURCE_LEAK + +### Hash: +2315c6d7453660c8f8657dee398d421d + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1643/instruction.md b/inferredbugs-1643/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c0bdf9d0a85997f8fe74ae6ed73974a35ebbec11 --- /dev/null +++ b/inferredbugs-1643/instruction.md @@ -0,0 +1,850 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** sensenet +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using SenseNet.ApplicationModel; +using SenseNet.ContentRepository.Fields; +using SenseNet.ContentRepository.Storage; +using SenseNet.ContentRepository.Storage.Security; +using SenseNet.Diagnostics; +using SenseNet.Configuration; +using SenseNet.ContentRepository.Schema; +using SenseNet.Tools; +using Microsoft.AspNetCore.Http; +using SenseNet.ContentRepository; +using SenseNet.OData.Writers; +using SenseNet.Security; +using Task = System.Threading.Tasks.Task; +// ReSharper disable UnusedMember.Global +// ReSharper disable CommentTypo +// ReSharper disable ArrangeThisQualifier + +namespace SenseNet.OData +{ + /// + /// AN ASP.NET Core middleware to process the OData requests. + /// + public class ODataMiddleware + { + public static readonly string ODataRequestHttpContextKey = "SenseNet.OData.ODataRequest"; + + private static readonly IActionResolver DefaultActionResolver = new DefaultActionResolver(); + internal static IActionResolver ActionResolver => Providers.Instance.GetProvider() ?? DefaultActionResolver; + + internal static readonly string[] HeadFieldNames = new[] { "Id", "Name", "DisplayName", "Icon", "CreationDate", "ModificationDate", "CreatedBy", "ModifiedBy" }; + internal static readonly List DisabledFieldNames = new List(new[] { "TypeIs", "InTree", "InFolder", "NodeType", "Rate"/*, "VersioningMode", "ApprovingMode", "RateAvg", "RateCount"*/ }); + internal static readonly List DeferredFieldNames = new List(new[] { "AllowedChildTypes", "EffectiveAllowedChildTypes" }); + internal static readonly List AllowedMethodNamesWithoutContent = new List(new[] { "PATCH", "PUT", "POST", "DELETE" }); + + internal static List JsonConverters { get; } + internal static List FieldConverters { get; } + + static ODataMiddleware() + { + JsonConverters = new List {new Newtonsoft.Json.Converters.VersionConverter()}; + + FieldConverters = new List(); + var fieldConverterTypes = TypeResolver.GetTypesByBaseType(typeof(FieldConverter)); + foreach (var fieldConverterType in fieldConverterTypes) + { + var fieldConverter = (FieldConverter)Activator.CreateInstance(fieldConverterType); + JsonConverters.Add(fieldConverter); + FieldConverters.Add(fieldConverter); + } + + OperationCenter.Discover(); + Providers.Instance.SetProvider(typeof(IOperationMethodStorage), new OperationMethodStorage()); + } + + internal static readonly DateTime BaseDate = new DateTime(1970, 1, 1); + internal const string ModelRequestKeyName = "models"; + internal const string ActionsPropertyName = "Actions"; + internal const string ChildrenPropertyName = "Children"; + internal const string BinaryPropertyName = "Binary"; + internal const int ExpansionLimit = int.MaxValue - 1; + + private readonly RequestDelegate _next; + // Must have constructor with this signature, otherwise exception at run time + public ODataMiddleware(RequestDelegate next) + { + _next = next; + } + + + public async Task InvokeAsync(HttpContext httpContext) + { + // Create OData-response strategy + var odataRequest = ODataRequest.Parse(httpContext); + + // Write headers and body of the HttpResponse + await ProcessRequestAsync(httpContext, odataRequest).ConfigureAwait(false); + + // Call next in the chain if exists + if (_next != null) + await _next(httpContext).ConfigureAwait(false); + } + + [SuppressMessage("ReSharper", "PossibleNullReferenceException")] + internal async Task ProcessRequestAsync(HttpContext httpContext, ODataRequest odataRequest) + { + httpContext.SetODataRequest(odataRequest); + + var request = httpContext.Request; + var httpMethod = request.Method; + var inputStream = request.Body; + ODataWriter odataWriter = null; + try + { + Content content; + if (odataRequest == null) + { + odataWriter = new ODataJsonWriter(); + throw new ODataException("The Request is not an OData request.", ODataExceptionCode.RequestError); + } + + odataWriter = ODataWriter.Create(httpContext, odataRequest); + if (odataWriter == null) + { + odataWriter = new ODataJsonWriter(); + odataWriter.Initialize(odataRequest); + throw new ODataException(ODataExceptionCode.InvalidFormatParameter); + } + + odataWriter.Initialize(odataRequest); + + var requestError = odataRequest.RequestError; + if (requestError != null) + { + var innerOdataError = requestError as ODataException; + var message = "An error occured during request parsing. " + requestError.Message + + " See inner exception for details."; + var code = innerOdataError?.ODataExceptionCode ?? ODataExceptionCode.RequestError; + throw new ODataException(message, code, requestError); + } + + odataRequest.Format = odataWriter.FormatName; + + var requestedContent = LoadContentByVersionRequest(odataRequest.RepositoryPath, httpContext); + + var exists = requestedContent != null; + if (!exists && !odataRequest.IsServiceDocumentRequest && !odataRequest.IsMetadataRequest && + !AllowedMethodNamesWithoutContent.Contains(httpMethod)) + { + ContentNotFound(httpContext); + return; + } + + JObject model; + switch (httpMethod) + { + case "GET": + if (odataRequest.IsServiceDocumentRequest) + { + await odataWriter.WriteServiceDocumentAsync(httpContext, odataRequest) + .ConfigureAwait(false); + } + else if (odataRequest.IsMetadataRequest) + { + await odataWriter.WriteMetadataAsync(httpContext, odataRequest) + .ConfigureAwait(false); + } + else + { + if (!Node.Exists(odataRequest.RepositoryPath)) + ContentNotFound(httpContext); + else if (odataRequest.IsCollection) + await odataWriter.WriteChildrenCollectionAsync(odataRequest.RepositoryPath, httpContext, + odataRequest) + .ConfigureAwait(false); + else if (odataRequest.IsMemberRequest) + await odataWriter.WriteContentPropertyAsync( + odataRequest.RepositoryPath, odataRequest.PropertyName, + odataRequest.IsRawValueRequest, httpContext, odataRequest) + .ConfigureAwait(false); + else + await odataWriter.WriteSingleContentAsync(requestedContent, httpContext) + .ConfigureAwait(false); + } + + break; + case "PUT": // update + if (odataRequest.IsMemberRequest) + { + throw new ODataException("Cannot access a member with HTTP PUT.", + ODataExceptionCode.IllegalInvoke); + } + else + { + model = await ReadToJsonAsync(inputStream).ConfigureAwait(false); + content = LoadContentOrVirtualChild(odataRequest); + if (content == null) + { + ContentNotFound(httpContext); + return; + } + + ResetContent(content); + UpdateContent(content, model, odataRequest); + await odataWriter.WriteSingleContentAsync(content, httpContext) + .ConfigureAwait(false); + } + + break; + case "MERGE": + case "PATCH": // update + if (odataRequest.IsMemberRequest) + { + throw new ODataException( + String.Concat("Cannot access a member with HTTP ", httpMethod, "."), + ODataExceptionCode.IllegalInvoke); + } + else + { + model = await ReadToJsonAsync(inputStream).ConfigureAwait(false); + content = LoadContentOrVirtualChild(odataRequest); + if (content == null) + { + ContentNotFound(httpContext); + return; + } + + UpdateContent(content, model, odataRequest); + await odataWriter.WriteSingleContentAsync(content, httpContext) + .ConfigureAwait(false); + } + + break; + case "POST": // invoke an action, create content + if (odataRequest.IsMemberRequest) + { + // MEMBER REQUEST + await odataWriter.WriteOperationResultAsync(inputStream, httpContext, odataRequest) + .ConfigureAwait(false); + } + else + { + // CREATION + if (!Node.Exists(odataRequest.RepositoryPath)) + { + // parent does not exist + ContentNotFound(httpContext); + return; + } + + model = await ReadToJsonAsync(inputStream).ConfigureAwait(false); + var newContent = CreateNewContent(model, odataRequest); + await odataWriter.WriteSingleContentAsync(newContent, httpContext) + .ConfigureAwait(false); + } + + break; + case "DELETE": + if (odataRequest.IsMemberRequest) + { + throw new ODataException( + String.Concat("Cannot access a member with HTTP ", httpMethod, "."), + ODataExceptionCode.IllegalInvoke); + } + else + { + content = LoadContentOrVirtualChild(odataRequest); + if (content != null) + { + var x = httpContext.Request.Query["permanent"].ToString(); + if (x.Equals("true", StringComparison.OrdinalIgnoreCase)) + content.DeletePhysical(); + else + content.Delete(); + } + } + + break; + } + } + catch (ContentNotFoundException e) + { + var oe = new ODataException(ODataExceptionCode.ResourceNotFound, e); + await odataWriter.WriteErrorResponseAsync(httpContext, oe) + .ConfigureAwait(false); + } + catch (ODataException e) + { + if (e.HttpStatusCode == 500) + SnLog.WriteException(e); + await odataWriter.WriteErrorResponseAsync(httpContext, e) + .ConfigureAwait(false); + } + catch (AccessDeniedException e) + { + var oe = new ODataException(ODataExceptionCode.Forbidden, e); + await odataWriter.WriteErrorResponseAsync(httpContext, oe) + .ConfigureAwait(false); + } + catch (UnauthorizedAccessException e) + { + var oe = new ODataException(ODataExceptionCode.Unauthorized, e); + await odataWriter.WriteErrorResponseAsync(httpContext, oe) + .ConfigureAwait(false); + } + catch (SenseNetSecurityException e) + { + // In case of a visitor we should not expose the information that this content actually exists. We return + // a simple 404 instead to provide exactly the same response as the regular 404, where the content + // really does not exist. But do this only if the visitor really does not have permission for the + // requested content (because security exception could be thrown by an action or something else too). + if (odataRequest != null && User.Current.Id == Identifiers.VisitorUserId) + { + var head = NodeHead.Get(odataRequest.RepositoryPath); + if (head != null && !SecurityHandler.HasPermission(head, PermissionType.Open)) + { + ContentNotFound(httpContext); + return; + } + } + + var oe = new ODataException(ODataExceptionCode.NotSpecified, e); + + SnLog.WriteException(oe); + + await odataWriter.WriteErrorResponseAsync(httpContext, oe) + .ConfigureAwait(false); + } + catch (InvalidContentActionException ex) + { + var oe = new ODataException(ODataExceptionCode.NotSpecified, ex); + if (ex.Reason != InvalidContentActionReason.NotSpecified) + oe.ErrorCode = Enum.GetName(typeof(InvalidContentActionReason), ex.Reason); + + // it is unnecessary to log this exception as this is not a real error + await odataWriter.WriteErrorResponseAsync(httpContext, oe) + .ConfigureAwait(false); + } + catch (ContentRepository.Storage.Data.NodeAlreadyExistsException nae) + { + var oe = new ODataException(ODataExceptionCode.ContentAlreadyExists, nae); + + await odataWriter.WriteErrorResponseAsync(httpContext, oe) + .ConfigureAwait(false); + } + catch (Exception ex) + { + var oe = new ODataException(ODataExceptionCode.NotSpecified, ex); + + SnLog.WriteException(oe); + + await odataWriter.WriteErrorResponseAsync(httpContext, oe) + .ConfigureAwait(false); + } + } + + /* =================================================================================== */ + + internal static async Task ReadToJsonAsync(Stream inputStream) + { + string models; + if (inputStream == null) + return null; + if (inputStream == Stream.Null) + return null; + using (var reader = new StreamReader(inputStream)) + models = await reader.ReadToEndAsync().ConfigureAwait(false); + + return ReadToJson(models); + } + /// + /// Helper method for deserializing the given string representation. + /// + /// JSON object that will be deserialized. + /// Deserialized JObject instance. + internal static JObject ReadToJson(string models) + { + if (string.IsNullOrEmpty(models)) + return null; + + var firstChar = models.Last() == ']' ? '[' : '{'; + var p = models.IndexOf(firstChar); + if (p > 0) + models = models.Substring(p); + + var settings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat }; + var serializer = JsonSerializer.Create(settings); + var jReader = new JsonTextReader(new StringReader(models)); + var deserialized = serializer.Deserialize(jReader); + + if (deserialized is JObject jObject) + return jObject; + if (deserialized is JArray jArray) + return jArray[0] as JObject; + + throw new SnNotSupportedException(); + } + internal static object Read(Stream inputStream, Type type) + { + string models; + using (var reader = new StreamReader(inputStream)) + models = reader.ReadToEnd(); // HttpUtility.UrlDecode(reader.ReadToEnd()); + + if (string.IsNullOrEmpty(models)) + return null; + + var firstChar = models.Last() == ']' ? '[' : '{'; + var p = models.IndexOf(firstChar); + if (p > 0) + models = models.Substring(p); + + var settings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat }; + var serializer = JsonSerializer.Create(settings); + var jReader = new JsonTextReader(new StringReader(models)); + var deserialized = serializer.Deserialize(jReader, type); + + return deserialized; + } + + internal static string GetEntityUrl(string path) + { + path = path.TrimEnd('/'); + + var p = path.LastIndexOf('/'); + if (p < 0) + return string.Concat("(", path, ")"); + + return string.Concat(path.Substring(0, p), "('", path.Substring(p + 1), "')"); + } + + internal static void ContentNotFound(HttpContext httpContext) + { + httpContext.Response.Clear(); + httpContext.Response.StatusCode = 404; + } + internal static void ContentAlreadyExists(string path) + { + throw new ODataException(SNSR.GetString(SNSR.Exceptions.OData.ContentAlreadyExists_1, path), ODataExceptionCode.ContentAlreadyExists); + } + internal static void ResourceNotFound(Content content, string propertyName) + { + throw new ODataException(SNSR.GetString(SNSR.Exceptions.OData.ResourceNotFound_2, content.Path, propertyName), ODataExceptionCode.ResourceNotFound); + } + internal static void ResourceNotFound() + { + throw new ODataException(SNSR.GetString(SNSR.Exceptions.OData.ResourceNotFound), ODataExceptionCode.ResourceNotFound); + } + + // ============================================================================================================== + + internal static Content LoadContentByVersionRequest(string path, HttpContext httpContext) + { + var versionRequest = httpContext.Request.Query["version"].ToString(); + return !string.IsNullOrEmpty(versionRequest) && VersionNumber.TryParse(versionRequest, out var version) + ? Content.Load(path, version) + : Content.Load(path); + } + + private Content CreateNewContent(JObject model, ODataRequest odataRequest) + { + var contentTypeName = GetPropertyValue("__ContentType", model); + var templateName = GetPropertyValue("__ContentTemplate", model); + + var name = GetPropertyValue("Name", model); + if (string.IsNullOrEmpty(name)) + { + var displayName = GetPropertyValue("DisplayName", model); + name = ContentNamingProvider.GetNameFromDisplayName(displayName); + } + else + { + // do not allow saving a content with unencoded name + name = ContentNamingProvider.GetNameFromDisplayName(name); + } + + var parent = Node.Load(odataRequest.RepositoryPath); + if (string.IsNullOrEmpty(contentTypeName)) + { + var allowedChildTypeNames = parent.GetAllowedChildTypeNames(); + + if (allowedChildTypeNames is AllContentTypeNames) + { + contentTypeName = typeof(ContentRepository.File).Name; + } + else + { + var allowedContentTypeNames = parent.GetAllowedChildTypeNames().ToArray(); + contentTypeName = allowedContentTypeNames.FirstOrDefault(); + if (string.IsNullOrEmpty(contentTypeName)) + contentTypeName = typeof(ContentRepository.File).Name; + } + } + + Content content; + Node template = null; + if (templateName != null) + template = ContentTemplate.GetNamedTemplate(contentTypeName, templateName); + + if (template == null) + { + content = Content.CreateNew(contentTypeName, parent, name); + } + else + { + var node = ContentTemplate.CreateFromTemplate(parent, template, name); + content = Content.Create(node); + } + + + UpdateFields(content, model); + + if (odataRequest.MultistepSave) + content.Save(SavingMode.StartMultistepSave); + else + content.Save(); + + return content; + } + private static readonly List SafeFieldsInReset = new List(new[] { + "Name", + "CreatedBy", "CreatedById", "CreationDate", + "ModifiedBy", "ModifiedById", "ModificationDate" }); + + private static Content LoadContentOrVirtualChild(ODataRequest odataReq) + { + var content = Content.Load(odataReq.RepositoryPath); + + if (content == null) + { + // try to load a virtual content + var parentPath = RepositoryPath.GetParentPath(odataReq.RepositoryPath); + var name = RepositoryPath.GetFileName(odataReq.RepositoryPath); + if (Node.LoadNode(parentPath) is ISupportsVirtualChildren vp) + content = vp.GetChild(name); + } + + return content; + } + + private void ResetContent(Content content) + { + // Create "dummy" content + var newContent = SystemAccount.Execute(() => Content.CreateNew(content.ContentType.Name, content.ContentHandler.Parent, null)); + + Aspect[] aspects = null; + if (content.ContentHandler.HasProperty(GenericContent.ASPECTS)) + { + // Get aspects + aspects = content.ContentHandler.GetReferences(GenericContent.ASPECTS).Cast().ToArray(); + + // Reset aspect fields + if (content.ContentHandler is GenericContent gc) + { + content.RemoveAllAspects(); + gc.AspectData = null; + gc.ClearReference(GenericContent.ASPECTS); + } + } + + // Reset regular fields + foreach (var field in content.Fields.Values) + { + var fieldName = field.Name; + if (newContent.Fields.Any(f => f.Value.Name == fieldName) && !field.ReadOnly && !SafeFieldsInReset.Contains(fieldName)) + content[fieldName] = newContent[fieldName]; + } + + if (content.ContentHandler.HasProperty(GenericContent.ASPECTS)) + { + // Re-add all the aspects + content.AddAspects(aspects); + } + } + private void UpdateContent(Content content, JObject model, ODataRequest odataRequest) + { + UpdateFields(content, model); + + if (odataRequest.MultistepSave) + content.Save(SavingMode.StartMultistepSave); + else + content.Save(); + } + /// + /// Helper method for updating the given with a model represented by JObject. + /// The will not be saved. + /// + /// The that will be modified. Cannot be null. + /// The modifier JObject instance. Cannot be null. + public static void UpdateFields(Content content, JObject model) + { + if (content == null) + throw new ArgumentNullException(nameof(content)); + if (model == null) + throw new ArgumentNullException(nameof(model)); + + var isNew = content.Id == 0; + foreach (var prop in model.Properties()) + { + if (string.IsNullOrEmpty(prop.Name) || prop.Name == "__ContentType" || prop.Name == "__ContentTemplate" || prop.Name == "Type" || prop.Name == "ContentType") + continue; + + var hasField = content.Fields.TryGetValue(prop.Name, out var field); + if (!hasField && content.SupportsAddingFieldsOnTheFly && (prop.Value as JValue)?.Value != null) + { + var value = ((JValue)prop.Value).Value; + var fieldSetting = FieldSetting.InferFieldSettingFromType(value.GetType(), prop.Name); + var meta = new FieldMetadata(true, true, prop.Name, prop.Name, fieldSetting); + hasField = content.AddFieldsOnTheFly(new[] { meta }) && content.Fields.TryGetValue(prop.Name, out field); + } + + if (hasField) + { + if (!field.ReadOnly) + { + if (prop.Value is JValue jValue) + { + if (field is IntegerField) + { + field.SetData(Convert.ToInt32(jValue.Value)); + continue; + } + if (field is DateTimeField && jValue.Value == null) + continue; + if (isNew && field is ReferenceField && jValue.Value == null) + { + if (field.Name == "CreatedBy" || field.Name == "ModifiedBy") + continue; + } + if (field is ReferenceField && jValue.Value != null) + { + var refNode = jValue.Type == JTokenType.Integer + ? Node.LoadNode(Convert.ToInt32(jValue.Value)) + : Node.LoadNode(jValue.Value.ToString()); + + field.SetData(refNode); + continue; + } + if (isNew && field.Name == "Name" && jValue.Value != null) + { + field.SetData(ContentNamingProvider.GetNameFromDisplayName(jValue.Value.ToString())); + continue; + } + + field.SetData(jValue.Value); + continue; + } + + if (prop.Value is JObject) + { + //TODO: ODATA: setting field when posted value is JObject. + // field.SetData(jValue.Value); + continue; + } + + if (prop.Value is JArray aValue) + { + if (field is ReferenceField) + { + var refValues = aValue.Values().ToList(); + if (refValues.Count == 0) + { + field.SetData(null); + continue; + } + + var fieldSetting = field.FieldSetting as ReferenceFieldSetting; + var nodes = refValues.Select(rv => rv.Type == JTokenType.Integer ? Node.LoadNode(Convert.ToInt32(rv.ToString())) : Node.LoadNode(rv.ToString())); + + if (fieldSetting?.AllowMultiple != null && fieldSetting.AllowMultiple.Value) + field.SetData(nodes); + else + field.SetData(nodes.First()); + + } + else if (field is ChoiceField) + { + // ChoiceField expects the value to be of type List + var list = new List(); + foreach (var token in aValue) + { + if (token is JValue value) + list.Add(value.Value.ToString()); + else + throw new Exception( + $"Token type {token.GetType().Name} for field {field.Name} (type {field.GetType().Name}) is not supported."); + } + + field.SetData(list); + } + else if (field is AllowedChildTypesField && + field.Name == "AllowedChildTypes" && + content.ContentHandler is GenericContent gc) + { + var types = aValue.Values().Select(rv => + { + switch (rv.Type) + { + case JTokenType.Integer: + return Node.LoadNode(Convert.ToInt32(rv.ToString())) as ContentType; + default: + var typeId = rv.ToString(); + if (RepositoryPath.IsValidPath(typeId) == RepositoryPath.PathResult.Correct) + return Node.LoadNode(typeId) as ContentType; + return ContentType.GetByName(typeId); + } + }).Where(ct => ct != null).ToArray(); + + gc.SetAllowedChildTypes(types); + } + + continue; + } + + throw new SnNotSupportedException(); + } + } + } + } + + private T GetPropertyValue(string name, JObject model) + { + if (model[name] is JValue jValue) + return (T)jValue.Value; + return default; + } + + /// + /// Returns an OData path that can request the entity identified by the given path. This path is part of the OData entity request. For example + /// "/Root/MyFolder/MyDocument.doc" will be transformed to "/Root/MyFolder('MyDocument.doc')" + /// + /// This path will be transformed. + /// An OData path. + public static string GetODataPath(string path) + { + if (string.Compare(path, Identifiers.RootPath, StringComparison.OrdinalIgnoreCase) == 0) + return string.Empty; + + return GetODataPath(RepositoryPath.GetParentPath(path), RepositoryPath.GetFileName(path)); + } + /// + /// Returns an OData path that can request the entity identified by the given path plus name. This path is part of the OData entity request. For example + /// path = "/Root/MyFolder" and name = "MyDocument.doc" will be transformed to "/Root/MyFolder('MyDocument.doc')". + /// + /// A container path. + /// Content's name in the given container. + /// An OData path. + public static string GetODataPath(string parentPath, string name) + { + return $"{parentPath}('{name}')"; + } + } + + internal interface IActionResolver + { + GenericScenario GetScenario(string name, string parameters, HttpContext httpContext); + IEnumerable GetActions(Content context, string scenario, string backUri, HttpContext httpContext); + ActionBase GetAction(Content context, string scenario, string actionName, string backUri, object parameters, HttpContext httpContext); + } + internal class DefaultActionResolver : IActionResolver + { + public GenericScenario GetScenario(string name, string parameters, HttpContext httpContext) + { + return ScenarioManager.GetScenario(name, httpContext.Request.QueryString.ToString()); + } + public IEnumerable GetActions(Content context, string scenario, string backUri, HttpContext httpContext) + { + return ActionFramework.GetActions(context, scenario, null, backUri, httpContext); + } + public ActionBase GetAction(Content context, string scenario, string actionName, string backUri, object parameters, HttpContext httpContext) + { + return backUri == null + ? ActionFramework.GetAction(actionName, context, parameters, GetMethodBasedAction, httpContext) + : ActionFramework.GetAction(actionName, context, backUri, parameters, GetMethodBasedAction, httpContext); + } + + private ActionBase GetMethodBasedAction(string name, Content content, object state) + { + var httpContext = (HttpContext) state; + //var odataRequest = (ODataRequest) httpContext.Items[ODataMiddleware.ODataRequestHttpContextKey]; + OperationCallingContext method; + try + { + method = OperationCenter.GetMethodByRequest(content, name, + ODataMiddleware.ReadToJsonAsync(httpContext.Request.Body) + .GetAwaiter().GetResult(), + httpContext.Request.Query); + } + catch (OperationNotFoundException e) + { + throw new InvalidContentActionException(e, InvalidContentActionReason.UnknownAction, content.Path, + e.Message, name); + } + catch (AmbiguousMatchException e) + { + throw new InvalidContentActionException(e, InvalidContentActionReason.UnknownAction, content.Path, + e.Message, name); + } + + method.HttpContext = httpContext; + return new ODataOperationMethodExecutor(method); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource jReader of type Newtonsoft.Json.JsonTextReader, Leaked resource (output of System.IO.StringReader::.ctor() at Line 376) of type System.IO.StringReader in method "JObject ODataMiddleware.ReadToJson(String)". + +### Severity: +ERROR + +### Procedure: +JObject ODataMiddleware.ReadToJson(String) + +### File: +src/OData/ODataMiddleware.cs + +### Key: +ODataMiddleware.cs|ReadToJson|DOTNET_RESOURCE_LEAK + +### Hash: +bab19f76a3270adcd89025496bc197c1 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1672/instruction.md b/inferredbugs-1672/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2ff9e8589653cfb3a13f6337f5205a582e60d66a --- /dev/null +++ b/inferredbugs-1672/instruction.md @@ -0,0 +1,325 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** sipsorcery +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +//----------------------------------------------------------------------------- +// Filename: RTPMediaSession.cs +// +// Description: An implementation of IMediaSession based on RTPSession +// +// Author(s): +// Yizchok G. +// +// History: +// 12/23/2019 Yitzchok Created. +// +// License: +// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. +//----------------------------------------------------------------------------- + +using System; +using System.Linq; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using SIPSorcery.Net; +using SIPSorcery.Sys; + +namespace SIPSorcery.SIP.App +{ + /// + /// The SipSorcery concrete implementation of IMediaSession. + /// Relies on RTPSession and RTPChannel for RTP and network functions. + /// + /// This implementation sets up the RTP stream but doesn't process the actual audio or video + /// and will need another component to do the processing of the media and send/receive it to/from the RTP session. + /// + public class RTPMediaSession : IMediaSession + { + private static readonly ILogger logger = Log.Logger; + + public RTPSession Session { get; } + public bool LocalOnHold { get; set; } + public bool RemoteOnHold { get; set; } + + public RTPMediaSession(RTPSession rtpSession) + { + Session = rtpSession; + Session.OnRtpEvent += OnRemoteRtpEvent; + Session.OnReceivedSampleReady += OnReceivedSampleReady; + Session.OnRtpDisconnect += () => OnRtpDisconnected?.Invoke(); + } + + /// + /// This event is invoked when the session media has changed + /// and a new SDP is available. + /// + public event Action SessionMediaChanged; + + /// + /// The remote call party has put us on hold. + /// + public event Action RemotePutOnHold; + + /// + /// The remote call party has taken us off hold. + /// + public event Action RemoteTookOffHold; + + /// + /// Media Session closed. + /// + public event Action Closed; + + /// + /// Gets fired when an RTP DTMF event is completed on the remote call party's RTP stream. + /// + public event Action DtmfCompleted; + + /// + /// Gets fired when an RTP packet is received, has been identified and is ready for processing. + /// + public event Action OnReceivedSampleReady; + + /// + /// Fired when a network error occurs indicating the remote party is no longer accepting + /// RTP packets. + /// + public event Action OnRtpDisconnected; + + public Task SendDtmf(byte key, CancellationToken cancellationToken = default) + { + var dtmfEvent = new RTPEvent(key, false, RTPEvent.DEFAULT_VOLUME, 1200, RTPSession.DTMF_EVENT_PAYLOAD_ID); + return Session.SendDtmfEvent(dtmfEvent, cancellationToken); + } + + /// + /// Send a re-INVITE request to put the remote call party on hold. + /// + public void PutOnHold() + { + LocalOnHold = true; + SessionMediaChanged?.Invoke(CreateOfferInternal()); + } + + /// + /// Send a re-INVITE request to take the remote call party on hold. + /// + public void TakeOffHold() + { + LocalOnHold = false; + SessionMediaChanged?.Invoke(CreateOfferInternal()); + } + + public virtual void Close() + { + Session.OnRtpEvent -= OnRemoteRtpEvent; + Session.OnReceivedSampleReady -= OnReceivedSampleReady; + Session.Close(); + Closed?.Invoke(); + } + + public Task CreateOffer(IPAddress destinationAddress = null) => + Task.FromResult(CreateOfferInternal(destinationAddress)); + + private string CreateOfferInternal(IPAddress destinationAddress = null) + { + var destinationAddressToUse = FindDestinationAddressToUse(destinationAddress); + + IPAddress localIPAddress = NetServices.GetLocalAddressForRemote(destinationAddressToUse); + + var localSDP = Session.GetSDP(localIPAddress); + + AdjustSdpForMediaState(localSDP); + + return localSDP.ToString(); + } + + private IPAddress FindDestinationAddressToUse(IPAddress destinationAddress) + { + IPAddress destinationAddressToUse = destinationAddress; + + if (destinationAddressToUse == null) + { + if (Session.RemoteSDP != null) + { + //Check for endpoint from the SDP + IPEndPoint dstRtpEndPoint = Session.RemoteSDP.GetSDPRTPEndPoint(); + destinationAddressToUse = dstRtpEndPoint.Address; + + bool newEndpoint = Session.DestinationEndPoint != dstRtpEndPoint; + + if (newEndpoint) + { + logger.LogDebug( + $"Remote call party RTP end point changed from {Session.DestinationEndPoint} to {dstRtpEndPoint}."); + } + } + else + { + destinationAddressToUse = IPAddress.Any; + } + } + + return destinationAddressToUse; + } + + private void AdjustSdpForMediaState(SDP localSDP) + { + var mediaAnnouncement = localSDP.Media.FirstOrDefault(x => x.Media == SDPMediaTypesEnum.audio); + + if (mediaAnnouncement == null) + { + return; + } + + if (LocalOnHold && RemoteOnHold) + { + mediaAnnouncement.MediaStreamStatus = MediaStreamStatusEnum.None; + } + else if (!LocalOnHold && !RemoteOnHold) + { + mediaAnnouncement.MediaStreamStatus = MediaStreamStatusEnum.SendRecv; + } + else + { + mediaAnnouncement.MediaStreamStatus = + LocalOnHold + ? MediaStreamStatusEnum.SendOnly + : MediaStreamStatusEnum.RecvOnly; + } + } + + public Task OfferAnswered(string remoteSDP) + { + SetRemoteSDP(remoteSDP); + return Task.FromResult(true); + } + + public Task AnswerOffer(string remoteSDP) + { + SetRemoteSDP(remoteSDP); + return CreateOffer(); + } + + public Task RemoteReInvite(string remoteSDP) + { + SetRemoteSDP(remoteSDP); + return CreateOffer(); + } + + private void SetRemoteSDP(string remoteSDP) + { + var sdp = SDP.ParseSDPDescription(remoteSDP); + Session.SetRemoteSDP(sdp); + Session.DestinationEndPoint = sdp.GetSDPRTPEndPoint(); + + CheckRemotePartyHoldCondition(sdp); + + logger.LogDebug($"Remote RTP socket {Session.DestinationEndPoint}."); + } + + private void CheckRemotePartyHoldCondition(SDP remoteSDP) + { + var mediaStreamStatus = remoteSDP.GetMediaStreamStatus(SDPMediaTypesEnum.audio, 0); + + if (mediaStreamStatus == MediaStreamStatusEnum.SendOnly) + { + if (!RemoteOnHold) + { + RemoteOnHold = true; + RemotePutOnHold?.Invoke(); + } + } + else if (mediaStreamStatus == MediaStreamStatusEnum.SendRecv && RemoteOnHold) + { + if (RemoteOnHold) + { + RemoteOnHold = false; + RemoteTookOffHold?.Invoke(); + } + } + } + + public void SendAudioFrame(uint timestamp, byte[] buffer) => + Session.SendAudioFrame(timestamp, buffer); + + private ushort remoteDtmfDuration; + + /// + /// Event handler for RTP events from the remote call party. + /// + /// The received RTP event. + private void OnRemoteRtpEvent(RTPEvent rtpEvent) + { + if (rtpEvent.EndOfEvent) + { + remoteDtmfDuration = 0; + } + else if (remoteDtmfDuration == 0) + { + remoteDtmfDuration = rtpEvent.Duration; + DtmfCompleted?.Invoke(rtpEvent.EventID); + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `dstRtpEndPoint` last assigned on line 144 could be null and is dereferenced at line 145, column 21. + +### Severity: +ERROR + +### Procedure: +IPAddress RTPMediaSession.FindDestinationAddressToUse(IPAddress) + +### File: +src/app/Media/RTPMediaSession.cs + +### Key: +RTPMediaSession.cs|FindDestinationAddressToUse|NULL_DEREFERENCE + +### Node Key: +90535029835413c6e5d1bdebbf52bdf9 + +### Hash: +c9b2f2f0f764585c70d36baac36ef89f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1675/instruction.md b/inferredbugs-1675/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..67983d6524eb71deab6d7941d3ca2120fc3e5aa0 --- /dev/null +++ b/inferredbugs-1675/instruction.md @@ -0,0 +1,149 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** CSLightStudio +**Bug ID:** 7 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Text; +namespace CSLE +{ + + public class CLS_Expression_LoopDowhile : ICLS_Expression + { + public CLS_Expression_LoopDowhile(int tbegin, int tend, int lbegin, int lend) + { + listParam = new List(); + tokenBegin = tbegin; + tokenEnd = tend; + + lineBegin = lbegin; + lineEnd = lend; + } + public int lineBegin + { + get; + private set; + } + public int lineEnd + { + get; + set; + } + //Block的参数 一个就是一行,顺序执行,没有 + public List listParam + { + get; + private set; + } + public int tokenBegin + { + get; + private set; + } + public int tokenEnd + { + get; + set; + } + public CLS_Content.Value ComputeValue(CLS_Content content) + { + content.InStack(this); + content.DepthAdd(); + ICLS_Expression expr_while = listParam[1] as ICLS_Expression; + ICLS_Expression expr_block = listParam[0] as ICLS_Expression; + + CLS_Content.Value v = null; + do + { + if (expr_block != null) + { + if (expr_block is CLS_Expression_Block) + { + v = expr_block.ComputeValue(content); + if (v != null && v.breakBlock > 1) break; ; + } + else + { + content.DepthAdd(); + v = expr_block.ComputeValue(content); + if (v != null && v.breakBlock > 1) break; ; + content.DepthRemove(); + } + //if (v.breakBlock == 1) continue; + //if (v.breakBlock == 2) break; + //if (v.breakBlock == 10) return v; + } + } while ((bool)expr_while.ComputeValue(content).value); + content.DepthRemove(); + content.OutStack(this); + return v; + //for 逻辑 + //做数学计算 + //从上下文取值 + //_value = null; + } + + + public override string ToString() + { + return "Do{}While|"; + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `expr_while` last assigned on line 48 could be null and is dereferenced at line 72, column 15. + +### Severity: +ERROR + +### Procedure: +CLS_Content$Value CLS_Expression_LoopDowhile.ComputeValue(CLS_Content) + +### File: +CSLightStudio/core/CSLightEvil/C#LE/Expression/Loop/CLS_Expression_LoopDowhile.cs + +### Key: +CLS_Expression_LoopDowhile.cs|ComputeValue|NULL_DEREFERENCE + +### Node Key: +13bfd1f29e10ee7fa9c3e90267e0bca8 + +### Hash: +9e09ca6241cd77105d7605cd9c300fb9 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1681/instruction.md b/inferredbugs-1681/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..596761834e77a575770c2bbd891d530ba56de627 --- /dev/null +++ b/inferredbugs-1681/instruction.md @@ -0,0 +1,153 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** CSLightStudio +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Text; +namespace CSLE +{ + + public class CLS_Expression_LoopFor : ICLS_Expression + { + public CLS_Expression_LoopFor(int tbegin, int tend, int lbegin, int lend) + { + listParam = new List(); + tokenBegin = tbegin; + tokenEnd = tend; + + lineBegin = lbegin; + lineEnd = lend; + } + public int lineBegin + { + get; + private set; + } + public int lineEnd + { + get; + set; + } + //Block的参数 一个就是一行,顺序执行,没有 + public List listParam + { + get; + private set; + } + public int tokenBegin + { + get; + private set; + } + public int tokenEnd + { + get; + set; + } + public CLS_Content.Value ComputeValue(CLS_Content content) + { + content.InStack(this); + content.DepthAdd(); + ICLS_Expression expr_init = listParam[0] as ICLS_Expression; + if (expr_init != null) expr_init.ComputeValue(content); + + ICLS_Expression expr_continue = listParam[1] as ICLS_Expression; + ICLS_Expression expr_step = listParam[2] as ICLS_Expression; + + ICLS_Expression expr_block = listParam[3] as ICLS_Expression; + + for (; (bool)expr_continue.ComputeValue(content).value; expr_step.ComputeValue(content)) + { + if (expr_block != null) + { + if (expr_block is CLS_Expression_Block) + { + var v = expr_block.ComputeValue(content); + if (v != null && v.breakBlock > 1) break; ; + } + else + { + content.DepthAdd(); + var v = expr_block.ComputeValue(content); + if (v != null && v.breakBlock > 1) break; ; + content.DepthRemove(); + } + //if (v.breakBlock == 1) continue; + //if (v.breakBlock == 2) break; + //if (v.breakBlock == 10) return v; + } + } + content.DepthRemove(); + content.OutStack(this); + return null; + //for 逻辑 + //做数学计算 + //从上下文取值 + //_value = null; + } + + + public override string ToString() + { + return "For|"; + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `expr_continue` last assigned on line 51 could be null and is dereferenced at line 56, column 20. + +### Severity: +ERROR + +### Procedure: +CLS_Content$Value CLS_Expression_LoopFor.ComputeValue(CLS_Content) + +### File: +CSLightStudio/core/CSLightEvil/C#LE/Expression/Loop/CLS_Expression_LoopFor.cs + +### Key: +CLS_Expression_LoopFor.cs|ComputeValue|NULL_DEREFERENCE + +### Node Key: +13bfd1f29e10ee7fa9c3e90267e0bca8 + +### Hash: +2b8082ed76f62b2cbacdb930bfc9c743 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1686/instruction.md b/inferredbugs-1686/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6116e20dd9d55dd69d2e9d925c818e4ff6b72024 --- /dev/null +++ b/inferredbugs-1686/instruction.md @@ -0,0 +1,196 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Cirqus +**Bug ID:** 7 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using d60.Cirqus.Aggregates; +using d60.Cirqus.Commands; +using d60.Cirqus.Events; +using d60.Cirqus.Extensions; +using d60.Cirqus.MsSql.Events; +using d60.Cirqus.MsSql.Views; +using d60.Cirqus.Tests.MsSql; +using d60.Cirqus.Views; +using d60.Cirqus.Views.ViewManagers; +using d60.Cirqus.Views.ViewManagers.Locators; +using NUnit.Framework; + +namespace d60.Cirqus.Tests.Examples +{ + [TestFixture] + public class ReadmeSnippet : FixtureBase + { + protected override void DoSetUp() + { + MsSqlTestHelper.EnsureTestDatabaseExists(); + } + + [Test] + public void TheSnippet() + { + MsSqlTestHelper.DropTable("events"); + MsSqlTestHelper.DropTable("counters"); + + var eventStore = new MsSqlEventStore(MsSqlTestHelper.ConnectionString, "events", automaticallyCreateSchema: true); + var aggregateRootRepository = new DefaultAggregateRootRepository(eventStore); + var viewManager = new MsSqlViewManager(MsSqlTestHelper.ConnectionString, "counters", automaticallyCreateSchema: true); + + var eventDispatcher = new ViewManagerEventDispatcher(aggregateRootRepository, eventStore, viewManager); + + var processor = new CommandProcessor(eventStore, aggregateRootRepository, eventDispatcher); + + RegisterForDisposal(processor); + + processor.Initialize(); + + var aggregateRootId = Guid.NewGuid(); + processor.ProcessCommand(new IncrementCounter(aggregateRootId, 1)); + processor.ProcessCommand(new IncrementCounter(aggregateRootId, 2)); + processor.ProcessCommand(new IncrementCounter(aggregateRootId, 3)); + processor.ProcessCommand(new IncrementCounter(aggregateRootId, 5)); + processor.ProcessCommand(new IncrementCounter(aggregateRootId, 8)); + } + + public class IncrementCounter : Command + { + public IncrementCounter(Guid aggregateRootId, int delta) + : base(aggregateRootId) + { + Delta = delta; + } + + public int Delta { get; private set; } + + public override void Execute(Counter aggregateRoot) + { + aggregateRoot.Increment(Delta); + } + } + + public class CounterIncremented : DomainEvent + { + public CounterIncremented(int delta) + { + Delta = delta; + } + + public int Delta { get; private set; } + } + + public class Counter : AggregateRoot, IEmit + { + int _currentValue; + + public void Increment(int delta) + { + Emit(new CounterIncremented(delta)); + } + + public void Apply(CounterIncremented e) + { + _currentValue += e.Delta; + } + + public int CurrentValue + { + get { return _currentValue; } + } + + public double GetSecretBizValue() + { + return CurrentValue%2 == 0 + ? Math.PI + : CurrentValue; + } + } + + public class CounterView : IViewInstance, ISubscribeTo + { + public CounterView() + { + SomeRecentBizValues = new List(); + } + + public string Id { get; set; } + + public long LastGlobalSequenceNumber { get; set; } + + public int CurrentValue { get; set; } + + public double SecretBizValue { get; set; } + + public List SomeRecentBizValues { get; set; } + + public void Handle(IViewContext context, CounterIncremented domainEvent) + { + CurrentValue += domainEvent.Delta; + + var counter = context.Load(domainEvent.GetAggregateRootId(), domainEvent.GetGlobalSequenceNumber()); + + SecretBizValue = counter.GetSecretBizValue(); + + SomeRecentBizValues.Add(SecretBizValue); + + // trim to 10 most recent biz values + while(SomeRecentBizValues.Count > 10) + SomeRecentBizValues.RemoveAt(0); + } + } + } + +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource processor of type d60.Cirqus.CommandProcessor, Leaked resource eventDispatcher of type d60.Cirqus.Views.ViewManagerEventDispatcher in method "Void ReadmeSnippet.TheSnippet()". + +### Severity: +ERROR + +### Procedure: +Void ReadmeSnippet.TheSnippet() + +### File: +d60.Cirqus.Tests/Examples/ReadmeSnippet.cs + +### Key: +ReadmeSnippet.cs|TheSnippet|DOTNET_RESOURCE_LEAK + +### Hash: +3b6e4b145d86abe7073f2e217f4952c2 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1688/instruction.md b/inferredbugs-1688/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b299da9b1a0de9b3bf4138a0c7fe6897b5ca8a91 --- /dev/null +++ b/inferredbugs-1688/instruction.md @@ -0,0 +1,119 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Cirqus +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using d60.Cirqus.Logging; +using d60.Cirqus.Logging.Console; +using d60.Cirqus.Tests.Contracts.Views.Factories; +using d60.Cirqus.Tests.Contracts.Views.Models.ObjectGraph; +using d60.Cirqus.Views.ViewManagers; +using d60.Cirqus.Views.ViewManagers.Locators; +using NUnit.Framework; +using TestContext = d60.Cirqus.Testing.TestContext; + +namespace d60.Cirqus.Tests.Contracts.Views +{ + [TestFixture(typeof(MongoDbViewManagerFactory), Category = TestCategories.MongoDb)] + [TestFixture(typeof(EntityFrameworkViewManagerFactory), Category = TestCategories.MsSql)] + [TestFixture(typeof(InMemoryViewManagerFactory))] + [Description("Some view managers must be able to save and load an entire object graph")] + public class ObjectGraph : FixtureBase where TFactory : AbstractViewManagerFactory, new() + { + TFactory _factory; + TestContext _context; + IViewManager _viewManager; + + protected override void DoSetUp() + { + CirqusLoggerFactory.Current = new ConsoleLoggerFactory(minLevel: Logger.Level.Warn); + + _factory = RegisterForDisposal(new TFactory()); + _context = RegisterForDisposal(new TestContext()); + + _context.AddViewManager(_viewManager = _factory.GetViewManager()); + } + + [Test] + public void WorksWithChildren() + { + var root1 = new Guid("B8FC0210-B7E4-4279-8BC8-53F13A557751"); + + _context.Save(root1, new Event {NumberOfChildren = 3}); + + var view = _factory.Load(InstancePerAggregateRootLocator.GetViewIdFromAggregateRootId(root1)); + Assert.That(view.Children.Count, Is.EqualTo(3)); + } + + [Test] + public void ItWorksWithSeveralViewsAndDeletionOfRemovedChildren() + { + var root1 = new Guid("B8FC0210-B7E4-4279-8BC8-53F13A557751"); + var root2 = new Guid("394C50E4-245A-4C35-829D-B4625EDC59F4"); + _context.Save(root1, new Event { NumberOfChildren = 30 }); + _context.Save(root2, new Event { NumberOfChildren = 20 }); + + _context.Save(root1, new Event {NumberOfChildren = 1}); + _context.Save(root2, new Event {NumberOfChildren = 2}); + + var view1 = _factory.Load(InstancePerAggregateRootLocator.GetViewIdFromAggregateRootId(root1)); + var view2 = _factory.Load(InstancePerAggregateRootLocator.GetViewIdFromAggregateRootId(root2)); + Assert.That(view1.Children.Count, Is.EqualTo(1)); + Assert.That(view2.Children.Count, Is.EqualTo(2)); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of d60.Cirqus.Testing.TestContext::.ctor() at Line 28) of type d60.Cirqus.Testing.TestContext in method "Void ObjectGraph`1.DoSetUp()". + +### Severity: +ERROR + +### Procedure: +Void ObjectGraph`1.DoSetUp() + +### File: +d60.Cirqus.Tests/Contracts/Views/ObjectGraph.cs + +### Key: +ObjectGraph.cs|DoSetUp|DOTNET_RESOURCE_LEAK + +### Hash: +ab904bb952dfad191435446356a9e88d + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1753/instruction.md b/inferredbugs-1753/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a15c22356f13a678ad2abe103222b162e9df5fe7 --- /dev/null +++ b/inferredbugs-1753/instruction.md @@ -0,0 +1,126 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** FastExpressionCompiler +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Linq; +using System.Reflection.Emit; +using ILDebugging.Decoder; +using NUnit.Framework; + +#if LIGHT_EXPRESSION +using static FastExpressionCompiler.LightExpression.Expression; +namespace FastExpressionCompiler.LightExpression.UnitTests +#else +using System.Linq.Expressions; +using static System.Linq.Expressions.Expression; +namespace FastExpressionCompiler.UnitTests +#endif +{ +class Issue91_Issue95_Tests + { + delegate void ActionRef(ref T a1); + + [Test] + public void RefAssign() + { + var objRef = Parameter(typeof(double).MakeByRefType()); + var lambda = Lambda>(Assign(objRef, Add(objRef, Constant((double)3.0))), objRef); + + var compiledB = lambda.CompileFast(true); + var exampleB = 5.0; + compiledB(ref exampleB); + Assert.AreEqual(8.0, exampleB); + } + + [Test] + public void NullComparisonTest() + { + var pParam = Parameter(typeof(string), "p"); + + var condition = Condition(NotEqual(pParam, Constant(null)), + Constant(1), + Constant(0)); + var lambda = Lambda>(condition, pParam); + var convert1 = lambda.CompileFast(true); + Assert.NotNull(convert1); + Assert.AreEqual(1, convert1("aaa")); + + // Check TryEmitInvertedNullComparison is used + var il = ILReaderFactory.Create(convert1.Method).ToList(); + Assert.AreEqual(il[0].OpCode, OpCodes.Ldarg_0); + Assert.AreEqual(il[1].OpCode, OpCodes.Brfalse); + Assert.AreEqual(il[2].OpCode, OpCodes.Ldc_I4_1); + Assert.AreEqual(il[3].OpCode, OpCodes.Br); + Assert.AreEqual(il[4].OpCode, OpCodes.Ldc_I4_0); + Assert.AreEqual(il[5].OpCode, OpCodes.Ret); + } + + [Test] + public void TestAddAssign() + { + var objRef = Parameter(typeof(double).MakeByRefType()); + var lambda = Lambda>(AddAssign(objRef, Constant((double)3.0)), objRef); + + var compiledB = lambda.CompileFast>(true); + var exampleB = 5.0; + compiledB(ref exampleB); + Assert.AreEqual(8.0, exampleB); + } + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`convert1` could be null (from the call to `ExpressionCompiler.CompileFast(...)` on line 41) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +Void Issue91_Issue95_Tests.NullComparisonTest() + +### File: +test/FastExpressionCompiler.IssueTests/Issue91_Issue95_Tests.cs + +### Key: +Issue91_Issue95_Tests.cs|NullComparisonTest|NULLPTR_DEREFERENCE + +### Hash: +1da9e4aae0d6908e6bb20f3661fd83aa + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1754/instruction.md b/inferredbugs-1754/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eef62cb7e8613e248af72489bf42a8d3eb17e7c8 --- /dev/null +++ b/inferredbugs-1754/instruction.md @@ -0,0 +1,558 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** FastExpressionCompiler +**Bug ID:** 5 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq.Expressions; + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#nullable disable + +namespace FastExpressionCompiler.LightExpression +{ + /// The order of the visiting is important + public abstract class ExpressionVisitor + { + public virtual Expression Visit(Expression node) => node?.Accept(this); + + public IReadOnlyList Visit(IReadOnlyList nodes) + { + Expression[] newNodes = null; + var count = nodes.Count; + for (var i = 0; i < count; ++i) + { + var newNode = Visit(nodes[i]); + if (newNodes != null) + newNodes[i] = newNode; + else if (newNode != nodes[i]) + { + newNodes = new Expression[count]; + for (var j = 0; j < i; ++j) + newNodes[j] = nodes[j]; + newNodes[i] = newNode; + } + } + + return newNodes ?? nodes; + } + + public IReadOnlyList VisitAndConvert(IReadOnlyList nodes) where T : Expression + { + T[] newNodes = null; + var count = nodes.Count; + for (var i = 0; i < count; ++i) + { + var newNode = VisitAndConvert(nodes[i]); + if (newNodes != null) + newNodes[i] = newNode; + else if (newNode != nodes[i]) + { + newNodes = new T[count]; + for (var j = 0; j < i; ++j) + newNodes[j] = nodes[j]; + newNodes[i] = newNode; + } + } + return newNodes ?? nodes; + } + + public IReadOnlyList VisitAndConvert(IReadOnlyList nodes, Func visit) + { + T[] newNodes = null; + var count = nodes.Count; + for (var i = 0; i < count; ++i) + { + var newNode = visit(nodes[i]); + if (newNodes != null) + newNodes[i] = newNode; + else if (!Equals(newNode, nodes[i])) + { + newNodes = new T[count]; + for (var j = 0; j < i; ++j) + newNodes[j] = nodes[j]; + newNodes[i] = newNode; + } + } + return newNodes ?? nodes; + } + + public T VisitAndConvert(T node) where T : Expression + { + if (node == null) + return null; + var x = Visit(node); + if (x is T converted) + return converted; + throw new InvalidOperationException($"Converting visited node is not compatible from {x?.GetType()} to {typeof(T)}"); + } + + protected internal virtual Expression VisitBinary(BinaryExpression node) + { + var left = Visit(node.Left); + var conversion = VisitAndConvert(node.Conversion); + var right = Visit(node.Right); + if (node.Left == left && node.Conversion == conversion && node.Right == right) + return node; + return Expression.MakeBinary(node.NodeType, left, right, conversion); + } + + protected internal virtual Expression VisitBlock(BlockExpression node) + { + // the order of the visiting is important + var expressions = Visit(node.Expressions); + var variables = VisitAndConvert(node.Variables); + if (ReferenceEquals(expressions, node.Expressions) && ReferenceEquals(variables, node.Variables)) + return node; + return Expression.MakeBlock(node.Type, variables, expressions); + } + + protected internal virtual Expression VisitConditional(ConditionalExpression node) + { + var test = Visit(node.Test); + var ifTrue = Visit(node.IfTrue); + var ifFalse = Visit(node.IfFalse); + if (test == node.Test && ifTrue == node.IfTrue && ifFalse == node.IfFalse) + return node; + if (ifFalse == Expression.VoidDefault) + return Expression.IfThen(test, ifTrue); + return Expression.Condition(test, ifTrue, ifFalse, node.Type); + } + + protected internal virtual Expression VisitConstant(ConstantExpression node) => node; + + protected internal virtual Expression VisitDefault(DefaultExpression node) => node; + + protected internal virtual LabelTarget VisitLabelTarget(LabelTarget node) => node; + + protected internal virtual Expression VisitGoto(GotoExpression node) + { + var target = VisitLabelTarget(node.Target); + var value = Visit(node.Value); + if (target == node.Target && value == node.Value) + return node; + return Expression.Goto(target, value, node.Type); + } + + protected internal virtual Expression VisitInvocation(InvocationExpression node) + { + var expression = Visit(node.Expression); + if (node is OneArgumentInvocationExpression oneArgExpr) + { + var newArg = Visit(oneArgExpr.Argument); + if (expression == node.Expression && newArg == oneArgExpr.Argument) + return node; + return Expression.Invoke(node.Type, expression, newArg); + } + + var arguments = Visit(node.Arguments); + if (expression == node.Expression && ReferenceEquals(arguments, node.Arguments)) + return node; + return Expression.Invoke(node.Type, expression, arguments); + } + + protected internal virtual Expression VisitLabel(LabelExpression node) + { + var target = VisitLabelTarget(node.Target); + var value = Visit(node.DefaultValue); + if (target == node.Target && value == node.DefaultValue) + return node; + return Expression.Label(target, value); + } + + protected internal virtual Expression VisitLambda(LambdaExpression node) + { + var body = Visit(node.Body); + var parameters = VisitAndConvert(node.Parameters); + if (body == node.Body && ReferenceEquals(parameters, node.Parameters)) + return node; + return parameters.Count == 0 + ? (body.Type == node.ReturnType + ? new LambdaExpression(node.Type, body) + : new TypedReturnLambdaExpression(node.Type, body, node.ReturnType)) + : (body.Type == node.ReturnType + ? new ManyParametersLambdaExpression(node.Type, body, parameters) + : (LambdaExpression)new ManyParametersTypedReturnLambdaExpression(node.Type, body, parameters, node.ReturnType)); + } + + protected internal virtual Expression VisitLambda(Expression node) where T : System.Delegate + { + var body = Visit(node.Body); + var parameters = VisitAndConvert(node.Parameters); + if (body == node.Body && ReferenceEquals(parameters, node.Parameters)) + return node; + return parameters.Count == 0 + ? (body.Type == node.ReturnType + ? new Expression(body) + : new TypedReturnExpression(body, node.ReturnType)) + : (body.Type == node.ReturnType + ? new ManyParametersExpression(body, parameters) + : (Expression)new ManyParametersTypedReturnExpression(body, parameters, node.ReturnType)); + } + + protected internal virtual Expression VisitLoop(LoopExpression node) + { + var breakLabel = VisitLabelTarget(node.BreakLabel); + var continueLabel = VisitLabelTarget(node.ContinueLabel); + var body = Visit(node.Body); + if (breakLabel == node.BreakLabel && continueLabel == node.ContinueLabel && body == node.Body) + return node; + return Expression.Loop(body, breakLabel, continueLabel); + } + + protected internal virtual Expression VisitMember(MemberExpression node) + { + var expression = Visit(node.Expression); + if (expression == node.Expression) + return node; + return Expression.MakeMemberAccess(expression, node.Member); + } + + protected internal virtual Expression VisitIndex(IndexExpression node) + { + var instance = Visit(node.Object); + var arguments = Visit(node.Arguments); + if (instance == node.Object && ReferenceEquals(arguments, node.Arguments)) + return node; + return Expression.MakeIndex(instance, node.Indexer, arguments); + } + + protected internal virtual Expression VisitMethodCall(MethodCallExpression node) + { + var instance = Visit(node.Object); + var instanceUnchanged = instance == node.Object; + var fewArgCount = node.FewArgumentCount; + if (fewArgCount == 0) + return instanceUnchanged ? node : Expression.Call(instance, node.Method); + + if (fewArgCount == 1) + { + var arg = ((OneArgumentMethodCallExpression)node).Argument; + var newArg = Visit(arg); + return instanceUnchanged && newArg == arg ? node : + Expression.Call(instance, node.Method, newArg); + } + + if (fewArgCount == 2) + { + var n = (TwoArgumentsMethodCallExpression)node; + var newArg0 = Visit(n.Argument0); + var newArg1 = Visit(n.Argument1); + return instanceUnchanged && newArg0 == n.Argument0 && newArg1 == n.Argument1 ? node : + Expression.Call(instance, node.Method, newArg0, newArg1); + } + + if (fewArgCount == 3) + { + var n = (ThreeArgumentsMethodCallExpression)node; + var newArg0 = Visit(n.Argument0); + var newArg1 = Visit(n.Argument1); + var newArg2 = Visit(n.Argument2); + return instanceUnchanged && newArg0 == n.Argument0 && newArg1 == n.Argument1 && newArg2 == n.Argument2 ? node : + Expression.Call(instance, node.Method, newArg0, newArg1, newArg2); + } + + if (fewArgCount == 4) + { + var n = (FourArgumentsMethodCallExpression)node; + var newArg0 = Visit(n.Argument0); + var newArg1 = Visit(n.Argument1); + var newArg2 = Visit(n.Argument2); + var newArg3 = Visit(n.Argument3); + return instanceUnchanged && + newArg0 == n.Argument0 && newArg1 == n.Argument1 && newArg2 == n.Argument2 && newArg3 == n.Argument3 ? node : + Expression.Call(instance, node.Method, newArg0, newArg1, newArg2, newArg3); + } + + if (fewArgCount == 5) + { + var n = (FiveArgumentsMethodCallExpression)node; + var newArg0 = Visit(n.Argument0); + var newArg1 = Visit(n.Argument1); + var newArg2 = Visit(n.Argument2); + var newArg3 = Visit(n.Argument3); + var newArg4 = Visit(n.Argument4); + return instanceUnchanged && + newArg0 == n.Argument0 && newArg1 == n.Argument1 && newArg2 == n.Argument2 && newArg3 == n.Argument3 && newArg4 == n.Argument4 ? node : + Expression.Call(instance, node.Method, newArg0, newArg1, newArg2, newArg3, newArg4); + } + + var arguments = Visit(node.Arguments); + return instance == node.Object && ReferenceEquals(arguments, node.Arguments) ? node : + Expression.Call(instance, node.Method, node.Arguments); + } + + protected internal virtual Expression VisitNewArray(NewArrayExpression node) + { + var expressions = Visit(node.Expressions); + if (ReferenceEquals(expressions, node.Expressions)) + return node; + return new NewArrayExpression(node.NodeType, node.Type, expressions); + } + + protected internal virtual Expression VisitNew(NewExpression node) + { + var fewArgCount = node.FewArgumentCount; + if (fewArgCount == 0) + return node; + + if (fewArgCount == 1) + { + var arg = ((OneArgumentNewExpression)node).Argument; + var newArg = Visit(arg); + return newArg == arg ? node : Expression.New(node.Constructor, newArg); + } + + if (fewArgCount == 2) + { + var n = (TwoArgumentsNewExpression)node; + var newArg0 = Visit(n.Argument0); + var newArg1 = Visit(n.Argument1); + return newArg0 == n.Argument0 && newArg1 == n.Argument1 ? node : + Expression.New(node.Constructor, newArg0, newArg1); + } + + if (fewArgCount == 3) + { + var n = (ThreeArgumentsNewExpression)node; + var newArg0 = Visit(n.Argument0); + var newArg1 = Visit(n.Argument1); + var newArg2 = Visit(n.Argument2); + return newArg0 == n.Argument0 && newArg1 == n.Argument1 && newArg2 == n.Argument2 ? node : + Expression.New(node.Constructor, newArg0, newArg1, newArg2); + } + + if (fewArgCount == 4) + { + var n = (FourArgumentsNewExpression)node; + var newArg0 = Visit(n.Argument0); + var newArg1 = Visit(n.Argument1); + var newArg2 = Visit(n.Argument2); + var newArg3 = Visit(n.Argument3); + return newArg0 == n.Argument0 && newArg1 == n.Argument1 && newArg2 == n.Argument2 && newArg3 == n.Argument3 ? node : + Expression.New(node.Constructor, newArg0, newArg1, newArg2, newArg3); + } + + if (fewArgCount == 5) + { + var n = (FiveArgumentsNewExpression)node; + var newArg0 = Visit(n.Argument0); + var newArg1 = Visit(n.Argument1); + var newArg2 = Visit(n.Argument2); + var newArg3 = Visit(n.Argument3); + var newArg4 = Visit(n.Argument4); + return newArg0 == n.Argument0 && newArg1 == n.Argument1 && newArg2 == n.Argument2 && newArg3 == n.Argument3 && newArg4 == n.Argument4 ? node : + Expression.New(node.Constructor, newArg0, newArg1, newArg2, newArg3, newArg4); + } + + var arguments = Visit(node.Arguments); + return ReferenceEquals(arguments, node.Arguments) ? node : + Expression.New(node.Constructor, node.Arguments); + } + + protected internal virtual Expression VisitParameter(ParameterExpression node) => node; + + protected internal virtual SwitchCase VisitSwitchCase(SwitchCase node) + { + var testValues = Visit(node.TestValues); + var body = Visit(node.Body); + if (ReferenceEquals(testValues, node.TestValues) && body == node.Body) + return node; + return new SwitchCase(body, testValues); + } + + protected internal virtual Expression VisitSwitch(SwitchExpression node) + { + var switchValue = Visit(node.SwitchValue); + var cases = VisitAndConvert(node.Cases, VisitSwitchCase); + var defaultBody = Visit(node.DefaultBody); + if (switchValue == node.SwitchValue && ReferenceEquals(cases, node.Cases) && defaultBody == node.DefaultBody) + return node; + return new SwitchExpression(node.Type, switchValue, defaultBody, node.Comparison, cases.AsArray()); + } + + protected internal virtual CatchBlock VisitCatchBlock(CatchBlock node) + { + var variable = VisitAndConvert(node.Variable); + var filter = Visit(node.Filter); + var body = Visit(node.Body); + if (variable == node.Variable && filter == node.Filter && body == node.Body) + return node; + return new CatchBlock(variable, body, filter, node.Test); + } + + protected internal virtual Expression VisitTry(TryExpression node) + { + var body = Visit(node.Body); + + var handlers = node.Handlers?.Count > 0 + ? VisitAndConvert(node.Handlers, VisitCatchBlock) + : node.Handlers; + + var @finally = node.Finally != null + ? Visit(node.Finally) + : node.Finally; + + if (body == node.Body && ReferenceEquals(handlers, node.Handlers) && @finally == node.Finally) + return node; + + return @finally == null + ? new TryExpression(body, handlers.AsArray()) + : new WithFinallyTryExpression(body, handlers.AsArray(), @finally); + } + + protected internal virtual Expression VisitTypeBinary(TypeBinaryExpression node) + { + var expression = Visit(node.Expression); + if (expression == node.Expression) + return node; + return new TypeBinaryExpression(node.NodeType, expression, node.TypeOperand); + } + + protected internal virtual Expression VisitUnary(UnaryExpression node) + { + var operand = Visit(node.Operand); + if (operand == node.Operand) + return node; + return Expression.MakeUnary(node.NodeType, operand, node.Type); + } + + protected internal virtual Expression VisitMemberInit(MemberInitExpression node) + { + var newExpression = VisitAndConvert(node.NewExpression); + var bindings = VisitAndConvert(node.Bindings, VisitMemberBinding); + if (newExpression == node.NewExpression && ReferenceEquals(bindings, node.Bindings)) + return node; + return new MemberInitExpression(newExpression, bindings.AsArray()); + } + + protected internal virtual MemberBinding VisitMemberBinding(MemberBinding node) + { + switch (node.BindingType) + { + case MemberBindingType.Assignment: + return VisitMemberAssignment((MemberAssignment)node); + case MemberBindingType.MemberBinding: + return VisitMemberMemberBinding((MemberMemberBinding)node); + case MemberBindingType.ListBinding: + return VisitMemberListBinding((MemberListBinding)node); + default: + throw new NotSupportedException($"Unhandled Binding Type: {node.BindingType}"); + } + } + + protected internal virtual MemberAssignment VisitMemberAssignment(MemberAssignment node) + { + var expression = Visit(node.Expression); + if (expression == node.Expression) + return node; + return new MemberAssignment(node.Member, expression); + } + + protected internal virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node) + { + var bindings = VisitAndConvert(node.Bindings, b => VisitMemberBinding(b)); + if (ReferenceEquals(bindings, node.Bindings)) + return node; + return new MemberMemberBinding(node.Member, bindings); + } + + protected internal virtual MemberListBinding VisitMemberListBinding(MemberListBinding node) + { + var newItems = VisitAndConvert(node.Initializers, x => VisitElementInit(x)); + if (ReferenceEquals(newItems, node.Initializers)) + return node; + return new MemberListBinding(node.Member, newItems); + } + + protected internal virtual Expression VisitListInit(ListInitExpression node) + { + var newExpression = VisitAndConvert(node.NewExpression); + var initializers = VisitAndConvert(node.Initializers, VisitElementInit); + if (newExpression == node.NewExpression && ReferenceEquals(initializers, node.Initializers)) + return node; + return new ListInitExpression(newExpression, initializers.AsReadOnlyList()); + } + + protected internal virtual ElementInit VisitElementInit(ElementInit node) + { + var arguments = VisitAndConvert(node.Arguments); + if (arguments == node.Arguments) + return node; + return new ElementInit(node.AddMethod, arguments); + } + + protected internal virtual Expression VisitDynamic(DynamicExpression node) => node; + + protected internal virtual Expression VisitExtension(Expression node) => + node.VisitChildren(this); + + protected internal virtual Expression VisitRuntimeVariables(RuntimeVariablesExpression node) + { + var newItems = VisitAndConvert(node.Variables); + if (newItems == node.Variables) + return node; + return new RuntimeVariablesExpression(newItems); + } + + protected internal virtual Expression VisitDebugInfo(DebugInfoExpression node) => node; + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `body` last assigned on line 176 could be null and is dereferenced at line 187, column 9. + +### Severity: +ERROR + +### Procedure: +Expression ExpressionVisitor.VisitLambda(Expression`1) + +### File: +src/FastExpressionCompiler.LightExpression/ExpressionVisitor.cs + +### Key: +ExpressionVisitor.cs|VisitLambda|NULL_DEREFERENCE + +### Node Key: +0a2f2289efc1b4f27401d167fdf3ab36 + +### Hash: +2122d962ad10706045e28079e90ee673 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1816/instruction.md b/inferredbugs-1816/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4667926579c89d776987d855118d374455bf6df0 --- /dev/null +++ b/inferredbugs-1816/instruction.md @@ -0,0 +1,264 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** csly +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using sly.lexer; +using sly.parser.parser; +using sly.parser.syntax.tree; + +namespace sly.parser.generator.visitor +{ + public class EBNFSyntaxTreeVisitor : SyntaxTreeVisitor where IN : struct + { + public EBNFSyntaxTreeVisitor(ParserConfiguration conf, object parserInstance) : base(conf, + parserInstance) + { + } + + + protected override SyntaxVisitorResult Visit(ISyntaxNode n, object context = null) + { + switch (n) + { + case SyntaxLeaf leaf: + return Visit(leaf); + case GroupSyntaxNode node: + return Visit(node, context); + case ManySyntaxNode node: + return Visit(node, context); + case OptionSyntaxNode node: + return Visit(node, context); + case SyntaxNode node: + return Visit(node, context); + default: + return null; + } + } + + private SyntaxVisitorResult Visit(GroupSyntaxNode node, object context = null) + { + var group = new Group(); + var values = new List>(); + foreach (var n in node.Children) + { + var v = Visit(n, context); + + if (v.IsValue) group.Add(n.Name, v.ValueResult); + if (v.IsToken) + if (!v.Discarded) + group.Add(n.Name, v.TokenResult); + } + + + var res = SyntaxVisitorResult.NewGroup(group); + return res; + } + + private SyntaxVisitorResult Visit(OptionSyntaxNode node, object context = null) + { + var child = node.Children != null && node.Children.Any>() ? node.Children[0] : null; + if (child == null || node.IsEmpty) + { + if (node.IsGroupOption) + { + return SyntaxVisitorResult.NewOptionGroupNone(); + } + else + { + return SyntaxVisitorResult.NewOptionNone(); + } + } + + var innerResult = Visit(child, context); + switch (child) + { + case SyntaxLeaf leaf: + return SyntaxVisitorResult.NewToken(leaf.Token); + case GroupSyntaxNode group: + return SyntaxVisitorResult.NewOptionGroupSome(innerResult.GroupResult); + default: + return SyntaxVisitorResult.NewOptionSome(innerResult.ValueResult); + } + } + + + private SyntaxVisitorResult Visit(SyntaxNode node, object context = null) + { + var result = SyntaxVisitorResult.NoneResult(); + if (node.Visitor != null || node.IsByPassNode) + { + + + var args = new List(); + + foreach (var n in node.Children) + { + var v = Visit(n, context); + + if (v.IsToken) + { + if (!n.Discarded) args.Add(v.TokenResult); + } + else if (v.IsValue) + { + args.Add(v.ValueResult); + } + else if (v.IsOption) + { + args.Add(v.OptionResult); + } + else if (v.IsOptionGroup) + { + args.Add(v.OptionGroupResult); + } + else if (v.IsGroup) + { + args.Add(v.GroupResult); + } + else if (v.IsTokenList) + { + args.Add(v.TokenListResult); + } + else if (v.IsValueList) + { + args.Add(v.ValueListResult); + } + else if (v.IsGroupList) + { + args.Add(v.GroupListResult); + } + } + + if (node.IsByPassNode) + { + result = SyntaxVisitorResult.NewValue((OUT)args[0]); + } + else + { + MethodInfo method = null; + try + { + if (!(context is NoContext)) + { + args.Add(context); + } + + if (method == null) method = node.Visitor; + var t = method.Invoke(ParserVsisitorInstance, args.ToArray()); + var res = (OUT) t; + result = SyntaxVisitorResult.NewValue(res); + } + catch (TargetInvocationException tie) + { + if (tie.InnerException != null) + { + throw tie.InnerException; + } + } + } + } + + return result; + } + + private SyntaxVisitorResult Visit(ManySyntaxNode node, object context = null) + { + SyntaxVisitorResult result = null; + + var values = new List>(); + foreach (var n in node.Children) + { + var v = Visit(n, context); + values.Add(v); + } + + if (node.IsManyTokens) + { + var tokens = new List>(); + values.ForEach(v => tokens.Add(v.TokenResult)); + result = SyntaxVisitorResult.NewTokenList(tokens); + } + else if (node.IsManyValues) + { + var vals = new List(); + values.ForEach(v => vals.Add(v.ValueResult)); + result = SyntaxVisitorResult.NewValueList(vals); + } + else if (node.IsManyGroups) + { + var vals = new List>(); + values.ForEach(v => vals.Add(v.GroupResult)); + result = SyntaxVisitorResult.NewGroupList(vals); + } + + + return result; + } + + + private SyntaxVisitorResult Visit(SyntaxLeaf leaf) + { + return SyntaxVisitorResult.NewToken(leaf.Token); + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `innerResult` last assigned on line 69 could be null and is dereferenced at line 74, column 13. + +### Severity: +ERROR + +### Procedure: +SyntaxVisitorResult`2 EBNFSyntaxTreeVisitor`2.Visit(OptionSyntaxNode`1,Object) + +### File: +sly/parser/generator/visitor/EBNFSyntaxTreeVisitor.cs + +### Key: +EBNFSyntaxTreeVisitor.cs|Visit|NULL_DEREFERENCE + +### Node Key: +e0174cb94cf16471080b6c97777c8803 + +### Hash: +fbf793424d41ac35388844fb794bfe01 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1818/instruction.md b/inferredbugs-1818/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5f5e9bd803eb9816cb05ddc00268d29c5d2e73d5 --- /dev/null +++ b/inferredbugs-1818/instruction.md @@ -0,0 +1,321 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** elasticsearch-net +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Net.Sockets; +using System.Net; +using System.Threading; +using System.IO; + +namespace ElasticSearch.Client +{ + internal class Connection : IConnection + { + public static ManualResetEvent allDone = new ManualResetEvent(false); + const int BUFFER_SIZE = 1024; + + private IConnectionSettings _ConnectionSettings { get; set; } + + public Connection(IConnectionSettings settings) + { + this._ConnectionSettings = settings; + } + + public ConnectionStatus GetSync(string path) + { + var connection = this.CreateConnection(path); + connection.Timeout = this._ConnectionSettings.TimeOut; + connection.Method = "GET"; + try + { + var response = connection.GetResponse(); + var result = new StreamReader(response.GetResponseStream()).ReadToEnd(); + return new ConnectionStatus(result); + } + catch (WebException e) + { + if (e.Status == WebExceptionStatus.Timeout) + return new ConnectionStatus(new ConnectionError() { Type = ConnectionErrorType.Server, Message = "Timeout", OriginalException = e }); + + if (e.Status != WebExceptionStatus.Success + && e.Status != WebExceptionStatus.ProtocolError) + return new ConnectionStatus(new ConnectionError() { Type = ConnectionErrorType.Server, Message = e.Message, OriginalException = e }); + + return new ConnectionStatus(new ConnectionError() { HttpStatusCode = ((HttpWebResponse)e.Response).StatusCode, Message = e.Message, OriginalException = e, Type = ConnectionErrorType.Server }); + } + catch (Exception e) { return new ConnectionStatus(new ConnectionError() { Type = ConnectionErrorType.Uncaught }); } + } + public ConnectionStatus PostSync(string path, string data) + { + var connection = this.CreateConnection(path); + connection.Timeout = this._ConnectionSettings.TimeOut; + connection.Method = "POST"; + try + { + byte[] buffer = Encoding.UTF8.GetBytes(data); + connection.ContentLength = buffer.Length; + var postStream = connection.GetRequestStream(); + postStream.Write(buffer, 0, buffer.Length); + postStream.Close(); + var response = connection.GetResponse(); + var result = new StreamReader(response.GetResponseStream()).ReadToEnd(); + return new ConnectionStatus(result); + } + catch (WebException e) + { + ConnectionError error; + if (e.Status == WebExceptionStatus.Timeout) + { + error = new ConnectionError { HttpStatusCode = HttpStatusCode.InternalServerError }; + } + else + { + error = new ConnectionError() { HttpStatusCode = ((HttpWebResponse)e.Response).StatusCode }; + } + error.Type = ConnectionErrorType.Server; + error.OriginalException = e; + error.Message = e.Message; + return new ConnectionStatus(error); + } + catch (Exception e) { return new ConnectionStatus(new ConnectionError() { Type = ConnectionErrorType.Uncaught }); } + } + + public void Get(string path, Action callback) + { + ConnectionState state = new ConnectionState() + { + Callback = callback, + Connection = this.CreateConnection(path) + }; + this.BeginGetResponse(state); + } + public void Post(string path, string data, Action callback) + { + this._PutOrPost("POST", path, data, callback); + } + public void Put(string path, string data, Action callback) + { + this._PutOrPost("PUT", path, data, callback); + } + + private void _PutOrPost(string method, string path,string data, Action callback) + { + ConnectionState state = new ConnectionState() + { + Callback = callback, + Connection = this.CreateConnection(path), + PostData = data + }; + state.Connection.Method = method; + + state.Connection.BeginGetRequestStream(this.PostStreamOpened, state); + } + private void PostStreamOpened(IAsyncResult result) + { + var state = (ConnectionState)result.AsyncState; + + Stream postStream = state.Connection.EndGetRequestStream(result); + + UTF8Encoding encoding = new UTF8Encoding(); + byte[] bytes = encoding.GetBytes(state.PostData); + //state.Connection.ContentLength = bytes.Length; + + postStream.Write(bytes, 0, bytes.Length); + postStream.Close(); + this.BeginGetResponse(state); + + } + + private void BeginGetResponse(ConnectionState state) + { + try + { + IAsyncResult result = (IAsyncResult)state.Connection.BeginGetResponse( + new AsyncCallback(GetResponseHandle), + state + ); + ThreadPool.RegisterWaitForSingleObject( + result.AsyncWaitHandle, + new WaitOrTimerCallback(TimeoutCallback), + state.Connection, + this._ConnectionSettings.TimeOut, + true + ); + + } + catch (WebException e) + { + state.RaiseCallBack(e); + } + catch (Exception e) + { + state.RaiseCallBack(e); + } + } + + + private static void TimeoutCallback(object state, bool timedOut) + { + if (timedOut) + { + HttpWebRequest request = state as HttpWebRequest; + if (request != null) + { + request.Abort(); + allDone.Set(); + + } + } + } + + + private void GetResponseHandle(IAsyncResult result) + { + var state = (ConnectionState)result.AsyncState; + try + { + var conn = state.Connection; + state.Response = (HttpWebResponse)conn.EndGetResponse(result); + + Stream responseStream = state.Response.GetResponseStream(); + + state.StreamResponse = responseStream; + + IAsyncResult readResult = responseStream.BeginRead( + state.BufferRead, + 0, + BUFFER_SIZE, + new AsyncCallback(ReadCallBack), + state + ); + return; + } + catch (Exception e) + { + state.RaiseCallBack(e); + } + } + private static void ReadCallBack(IAsyncResult result) + { + var state = (ConnectionState)result.AsyncState; + try + { + var conn = state.Connection; + + Stream responseStream = state.StreamResponse; + int read = responseStream.EndRead(result); + if (read > 0) + { + state.RequestData.Append(Encoding.ASCII.GetString(state.BufferRead, 0, read)); + IAsyncResult asynchronousResult = responseStream.BeginRead( + state.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), state); + return; + } + else + { + state.Response.Close(); + state.RaiseCallBack(); + } + + } + catch (WebException e) + { + state.RaiseCallBack(e); + } + catch (Exception e) + { + state.RaiseCallBack(e); + } + allDone.Set(); + + } + + + private HttpWebRequest CreateConnection(string path) + { + var url = this._CreateUriString(path); + HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url); + myReq.Accept = "application/json"; + myReq.ContentType = "application/json"; + + if (!string.IsNullOrEmpty(this._ConnectionSettings.ProxyAddress)) + { + var proxy = new WebProxy(); + var uri = new Uri(this._ConnectionSettings.ProxyAddress); + var credentials = new NetworkCredential(this._ConnectionSettings.Username, this._ConnectionSettings.Password); + proxy.Address = uri; + proxy.Credentials = credentials; + myReq.Proxy = proxy; + } + return myReq; + } + + private string _CreateUriString(string path) + { + var s = this._ConnectionSettings; + if (!path.StartsWith("/")) + path = "/" + path; + return string.Format("http://{0}:{1}{2}", s.Host, s.Port, path); + } + + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of System.IO.StreamReader::.ctor() at Line 32) of type System.IO.StreamReader in method "ConnectionStatus Connection.GetSync(String)". + +### Severity: +ERROR + +### Procedure: +ConnectionStatus Connection.GetSync(String) + +### File: +src/ElasticSearch.Client/Connection.cs + +### Key: +Connection.cs|GetSync|DOTNET_RESOURCE_LEAK + +### Hash: +89728bcd9dc1dbde8669af7db19320e9 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1820/instruction.md b/inferredbugs-1820/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ab4728cf2fdee1a412710020d5fd508ec74419e5 --- /dev/null +++ b/inferredbugs-1820/instruction.md @@ -0,0 +1,118 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ultraviolet +**Bug ID:** 9 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using TwistedLogik.Nucleus; + +namespace TwistedLogik.Ultraviolet.UI.Presentation.Styles +{ + /// + /// Represents a trigger which fires when a routed event is raised. + /// + public sealed class EventTrigger : Trigger, IRoutedEventRaisedNotificationSubscriber + { + /// + /// Initializes a new instance of the class. + /// + /// The name of the event that causes this trigger to be applied. + internal EventTrigger(String eventName) + { + Contract.RequireNotEmpty(eventName, "eventName"); + + this.eventName = new UvmlName(eventName); + } + + /// + void IRoutedEventRaisedNotificationSubscriber.ReceiveRoutedEventRaisedNotification(DependencyObject dobj, RoutedEvent evt) + { + Activate(dobj); + } + + /// + /// Gets the name of the event that causes this trigger to be applied. + /// + public UvmlName EventName + { + get { return eventName; } + } + + /// + protected internal override void Attach(DependencyObject dobj) + { + var routedEvent = EventManager.FindByStylingName(Ultraviolet, dobj, eventName.Owner, eventName.Name); + if (routedEvent == null) + throw new InvalidOperationException(PresentationStrings.EventOrPropertyDoesNotExist.Format(eventName, dobj.GetType())); + + RoutedEvent.RegisterRaisedNotification(dobj, routedEvent, this); + } + + /// + protected internal override void Detach(DependencyObject dobj) + { + var routedEvent = EventManager.FindByStylingName(Ultraviolet, dobj, eventName.Owner, eventName.Name); + if (routedEvent == null) + throw new InvalidOperationException(PresentationStrings.EventOrPropertyDoesNotExist.Format(eventName, dobj.GetType())); + + RoutedEvent.UnregisterRaisedNotification(dobj, routedEvent, this); + } + + // Property values. + private readonly UvmlName eventName; + } +} + +``` + +### Bug Type: +PULSE_UNINITIALIZED_VALUE + +### Qualifier: +`this.TwistedLogik.Ultraviolet.UI.Presentation.UvmlName.container` is read without initialization during the call to `UvmlName.get_Owner()`. + +### Severity: +ERROR + +### Procedure: +Void EventTrigger.Detach(DependencyObject) + +### File: +TwistedLogik.Ultraviolet.UI.Presentation/Styles/EventTrigger.cs + +### Key: +EventTrigger.cs|Detach|PULSE_UNINITIALIZED_VALUE + +### Hash: +e408c113c5a52c96d735c0d2a9d7cd11 + +### Bug Type Hum: +Uninitialized Value + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1829/instruction.md b/inferredbugs-1829/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cb9c0efa2d381236810f35532bbc60d7bdec8985 --- /dev/null +++ b/inferredbugs-1829/instruction.md @@ -0,0 +1,140 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ultraviolet +**Bug ID:** 12 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using TwistedLogik.Nucleus; +using TwistedLogik.Nucleus.Data; + +namespace TwistedLogik.Ultraviolet.UI.Presentation.Styles +{ + /// + /// Represents one of the conditions of a property trigger. + /// + public class PropertyTriggerCondition + { + /// + /// Initializes a new instance of the class. + /// + /// A value that specifies the type of comparison performed by this condition. + /// The name of the dependency property to evaluate. + /// The reference value to compare to the value of the dependency property. + internal PropertyTriggerCondition(TriggerComparisonOp op, String dpropName, String refval) + { + this.op = op; + this.dpropName = new UvmlName(dpropName); + this.refval = refval; + } + + /// + /// Evaluates whether the condition is true for the specified object. + /// + /// The object against which to evaluate the trigger condition. + /// true if the condition is true for the specified object; otherwise, false. + internal Boolean Evaluate(UltravioletContext uv, DependencyObject dobj) + { + Contract.Require(uv, "uv"); + Contract.Require(dobj, "dobj"); + + var dprop = DependencyProperty.FindByStylingName(uv, dobj, dpropName.Owner, dpropName.Name); + if (dprop == null) + return false; + + if (refvalCache == null || (refvalCache.GetType() != dprop.PropertyType && Nullable.GetUnderlyingType(dprop.PropertyType) != refvalCache.GetType())) + { + refvalCache = ObjectResolver.FromString(refval, dprop.PropertyType); + } + + var comparison = TriggerComparisonCache.Get(dprop.PropertyType, op); + if (comparison == null) + throw new InvalidOperationException(PresentationStrings.InvalidTriggerComparison.Format(dpropName, op, dprop.PropertyType)); + + return comparison(dobj, dprop, refvalCache); + } + + /// + /// Gets the comparison operation performed by this condition. + /// + public TriggerComparisonOp ComparisonOperation + { + get { return op; } + } + + /// + /// Gets the name of the dependency property which is evaluated by this condition. + /// + public UvmlName DependencyPropertyName + { + get { return dpropName; } + } + + /// + /// Gets a string which represents the reference value for this condition. + /// + public String ReferenceValue + { + get { return refval; } + } + + // State values. + private readonly TriggerComparisonOp op; + private readonly UvmlName dpropName; + private readonly String refval; + private Object refvalCache; + } +} + +``` + +### Bug Type: +PULSE_UNINITIALIZED_VALUE + +### Qualifier: +`this.TwistedLogik.Ultraviolet.UI.Presentation.UvmlName.container` is read without initialization during the call to `UvmlName.get_Owner()`. + +### Severity: +ERROR + +### Procedure: +Boolean PropertyTriggerCondition.Evaluate(UltravioletContext,DependencyObject) + +### File: +TwistedLogik.Ultraviolet.UI.Presentation/Styles/PropertyTriggerCondition.cs + +### Key: +PropertyTriggerCondition.cs|Evaluate|PULSE_UNINITIALIZED_VALUE + +### Hash: +85318a62fe7ca82bf6d08a14f7e58b91 + +### Bug Type Hum: +Uninitialized Value + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1842/instruction.md b/inferredbugs-1842/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d6a59c7978172d914e2c3fe1b45a5f6a986d1504 --- /dev/null +++ b/inferredbugs-1842/instruction.md @@ -0,0 +1,2803 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cscs +**Bug ID:** 95 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Threading.Tasks; + +namespace SplitAndMerge +{ + class BreakStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.BREAK); + } + } + + class ContinueStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.CONTINUE); + } + } + + class ReturnStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = Utils.GetItem(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = await Utils.GetItemAsync(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + } + + class TryBlock : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessTry(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessTryAsync(script); + } + } + + class ExitFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Environment.Exit(0); + return Variable.EmptyInstance; + } + } + + class NullFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Variable.EmptyInstance; + } + } + class InfinityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(double.PositiveInfinity); + } + } + class NegInfinityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(double.NegativeInfinity); + } + } + + class IsNaNFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + Variable arg = args[0]; + return new Variable(arg.Type != Variable.VarType.NUMBER || double.IsNaN(arg.Value)); + } + } + + class TypeOfFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + var args = Utils.GetTokens(script, Constants.TOKEN_SEPARATION); + Utils.CheckArgs(args.Count, 1, m_name); + + var vari = GetVariable(args[0], script); + if (vari == null || vari.GetValue(script).Type == Variable.VarType.UNDEFINED) + { + return Variable.Undefined; + } + + var exists = FunctionExists(args[0]); + if (!exists) + { + return Variable.Undefined; + } + + bool complexVariable = args.Count > 1 && + Utils.CanConvertToDouble(args[1], out double converted) && converted > 0; + Variable element = null; + if (complexVariable) + { + element = Utils.GetVariable(args[0], script, false); + } + if (element == null) + { + element = new Variable(args[0]); + } + + string type = element.GetTypeString(); + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(type); + return newValue; + } + } + + class IsFiniteFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + Variable arg = args[0]; + + double value = arg.Value; + if (arg.Type != Variable.VarType.NUMBER && + !double.TryParse(arg.String, out value)) + { + value = double.PositiveInfinity; + } + + return new Variable(!double.IsInfinity(value)); + } + } + + class IsUndefinedFunction : ParserFunction + { + string m_argument; + string m_action; + + internal IsUndefinedFunction(string arg = "", string action = "") + { + m_argument = arg; + m_action = action; + } + + protected override Variable Evaluate(ParsingScript script) + { + var variable = ParserFunction.GetVariable(m_argument, script); + var varValue = variable == null ? null : variable.GetValue(script); + bool isUndefined = varValue == null || varValue.Type == Variable.VarType.UNDEFINED; + + bool result = m_action == "===" || m_action == "==" ? isUndefined : + !isUndefined; + return new Variable(result); + } + } + + class ObjectPropsFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable obj = Utils.GetItem(script, true); + string propName = Utils.GetItem(script, true).AsString(); + script.MoveForwardIf(','); + + Variable value = Utils.GetProperties(script); + obj.SetProperty(propName, value, script); + + ParserFunction.AddGlobal(obj.ParamName, new GetVarFunction(obj), false); + + return new Variable(obj.ParamName); + } + } + + class ThrowFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = Utils.GetItem(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = await Utils.GetItemAsync(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + } + + class VarFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + var args = Utils.GetTokens(script); + Variable result = Variable.EmptyInstance; + foreach (var arg in args) + { + var ind = arg.IndexOf('='); + if (ind <= 0) + { + if (!FunctionExists(arg)) + { + AddGlobalOrLocalVariable(arg, new GetVarFunction(new Variable(Variable.VarType.NONE)), script); + } + continue; + } + var varName = arg.Substring(0, ind); + ParsingScript tempScript = new ParsingScript(arg.Substring(ind + 1)); + AssignFunction assign = new AssignFunction(); + result = assign.Assign(tempScript, varName, true); + } + return result; + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + //var varName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + //char action = script.CurrentAndForward(); + + var args = Utils.GetTokens(script); + Task result = null; + foreach (var arg in args) + { + var ind = arg.IndexOf('='); + if (ind <= 0) + { + if (!FunctionExists(arg)) + { + AddGlobalOrLocalVariable(arg, new GetVarFunction(new Variable(Variable.VarType.UNDEFINED)), script); + } + continue; + } + var varName = arg.Substring(0, ind); + ParsingScript tempScript = new ParsingScript(arg.Substring(ind + 1)); + AssignFunction assign = new AssignFunction(); + result = assign.AssignAsync(tempScript, varName, true); + } + + return result == null ? Variable.EmptyInstance: await result; + } + } + + class ShowFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + string functionName = args[0].AsString(); + + CustomFunction custFunc = ParserFunction.GetFunction(functionName, script) as CustomFunction; + Utils.CheckNotNull(functionName, custFunc, script); + +#if __ANDROID__ == false && __IOS__ == false + CustomCompiledFunction comp = custFunc as CustomCompiledFunction; + if (comp != null) + { + return new Variable(comp.Precompiler.CSharpCode); + } +#endif + + string body = Utils.BeautifyScript(custFunc.Body, custFunc.Header); + Utils.PrintScript(body, script); + + return new Variable(body); + } + } + + class FunctionCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string funcName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + funcName = Constants.ConvertName(funcName); + + string[] args = Utils.GetFunctionSignature(script); + if (args.Length == 1 && string.IsNullOrWhiteSpace(args[0])) + { + args = new string[0]; + } + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + /*string line = */script.GetOriginalLine(out _); + + int parentOffset = script.Pointer; + + if (script.CurrentClass != null) + { + parentOffset += script.CurrentClass.ParentOffset; + } + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + CustomFunction customFunc = new CustomFunction(funcName, body, args, script); + customFunc.ParentScript = script; + customFunc.ParentOffset = parentOffset; + + if (script.CurrentClass != null) + { + script.CurrentClass.AddMethod(funcName, args, customFunc); + } + else + { + ParserFunction.RegisterFunction(funcName, customFunc, false /* not native */); + } + + return Variable.EmptyInstance; + } + } + + public class CSCSClass : ParserFunction + { + public CSCSClass() {} + + public CSCSClass(string className) + { + Name = className; + RegisterClass(className, this); + } + + public CSCSClass(string className, string[] baseClasses) + { + Name = className; + RegisterClass(className, this); + + foreach (string baseClass in baseClasses) + { + var bc = CSCSClass.GetClass(baseClass); + if (bc == null) + { + throw new ArgumentException("Base Class [" + baseClass + "] not found."); + } + + foreach (var entry in bc.m_classProperties) + { + m_classProperties[entry.Key] = entry.Value; + } + foreach (var entry in bc.m_customFunctions) + { + m_customFunctions[entry.Key] = entry.Value; + } + } + } + + public static void RegisterClass(string className, CSCSClass obj) + { + obj.Namespace = ParserFunction.GetCurrentNamespace; + if (!string.IsNullOrWhiteSpace(obj.Namespace)) + { + className = obj.Namespace + "." + className; + } + + obj.Name = className; + className = Constants.ConvertName(className); + s_allClasses[className] = obj; + } + + protected override Variable Evaluate(ParsingScript script) + { + script.GetFunctionArgs(); + + // TODO: Work in progress, currently not functional + return Variable.EmptyInstance; + } + + public void AddMethod(string name, string[] args, CustomFunction method) + { + if (name == m_name) + { + m_constructors[args.Length] = method; + for (int i = 0; i < method.DefaultArgsCount && i < args.Length; i++) + { + m_constructors[args.Length - i - 1] = method; + } + } + else + { + m_customFunctions[name] = method; + } + } + + public void AddProperty(string name, Variable property) + { + m_classProperties[name] = property; + } + + public static CSCSClass GetClass(string name) + { + string currNamespace = ParserFunction.GetCurrentNamespace; + if (!string.IsNullOrWhiteSpace(currNamespace)) + { + bool namespacePresent = name.Contains("."); + if (!namespacePresent) + { + name = currNamespace + "." + name; + } + } + + CSCSClass theClass = null; + s_allClasses.TryGetValue(name, out theClass); + return theClass; + } + + static Dictionary s_allClasses = + new Dictionary(); + + Dictionary m_constructors = + new Dictionary(); + Dictionary m_customFunctions = + new Dictionary(); + Dictionary m_classProperties = + new Dictionary(); + + public ParsingScript ParentScript = null; + public int ParentOffset = 0; + + public string Namespace { get; private set; } + + public class ClassInstance : ScriptObject + { + public ClassInstance(string instanceName, string className, List args, + ParsingScript script = null) + { + InstanceName = instanceName; + m_cscsClass = CSCSClass.GetClass(className); + if (m_cscsClass == null) + { + throw new ArgumentException("Class [" + className + "] not found."); + } + + // Copy over all the properties defined for this class. + foreach (var entry in m_cscsClass.m_classProperties) + { + SetProperty(entry.Key, entry.Value); + } + + // Run "constructor" if any is defined for this number of args. + CustomFunction constructor = null; + if (m_cscsClass.m_constructors.TryGetValue(args.Count, out constructor)) + { + constructor.Run(args, script, this); + } + } + + public string InstanceName { get; set; } + CSCSClass m_cscsClass; + + Dictionary m_properties = new Dictionary(); + HashSet m_propSet = new HashSet(); + HashSet m_propSetLower = new HashSet(); + + public override string ToString() + { + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(Constants.PROP_TO_STRING.ToLower(), + out customFunction)) + { + return m_cscsClass.Name + "." + InstanceName; + } + + Variable result = customFunction.Run(null, null, this); + return result.ToString(); + } + + public Task SetProperty(string name, Variable value) + { + m_properties[name] = value; + m_propSet.Add(name); + m_propSetLower.Add(name.ToLower()); + return Task.FromResult( Variable.EmptyInstance ); + } + + public async Task GetProperty(string name, List args = null, ParsingScript script = null) + { + if (m_properties.TryGetValue(name, out Variable value)) + { + return value; + } + + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out CustomFunction customFunction)) + { + return null; + } + if (args == null) + { + return Variable.EmptyInstance; + } + + foreach (var entry in m_cscsClass.m_classProperties) + { + args.Add(entry.Value); + } + + Variable result = await customFunction.RunAsync(args, script, this); + return result; + } + + public List> GetPropList() + { + List> props = new List>(); + foreach (var entry in m_properties) + { + props.Add(new KeyValuePair(entry.Key, entry.Value)); + } + return props; + } + + public List GetProperties() + { + List props = new List(m_properties.Keys); + props.AddRange(m_cscsClass.m_customFunctions.Keys); + + return props; + } + public bool PropertyExists(string name) + { + return m_propSetLower.Contains(name.ToLower()); + } + + public bool FunctionExists(string name) + { + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out CustomFunction customFunction)) + { + return false; + } + return true; + } + } + } + + class NameExistsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string varName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + varName = Constants.ConvertName(varName); + + bool result = ParserFunction.GetVariable(varName, script) != null; + return new Variable(result); + } + } + + class EnumFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List properties = Utils.ExtractTokens(script); + + if (properties.Count == 1 && properties[0].Contains(".")) + { + return UseExistingEnum(properties[0]); + } + + Variable enumVar = new Variable(Variable.VarType.ENUM); + for (int i = 0; i < properties.Count; i++) + { + enumVar.SetEnumProperty(properties[i], new Variable(i)); + } + + return enumVar; + } + + public static Variable UseExistingEnum(string enumName) + { + Type enumType = GetEnumType(enumName); + if (enumType == null || !enumType.IsEnum) + { + return Variable.EmptyInstance; + } + + var names = Enum.GetNames(enumType); + + Variable enumVar = new Variable(Variable.VarType.ENUM); + for (int i = 0; i < names.Length; i++) + { + var numValue = Enum.Parse(enumType, names[i], true); + enumVar.SetEnumProperty(names[i], new Variable((int)numValue)); + } + + return enumVar; + } + + public static Type GetEnumType(string enumName) + { + string[] tokens = enumName.Split('.'); + + Type enumType = null; + int index = 0; + string typeName = ""; + while(enumType == null && index < tokens.Length) + { + if (!string.IsNullOrWhiteSpace(typeName)) + { + typeName += "."; + } + typeName += tokens[index]; + enumType = GetType(typeName); + index++; + } + + for (int i = index; i < tokens.Length && enumType != null; i++) + { + enumType = enumType.GetNestedType(tokens[i]); + } + + if (enumType == null || !enumType.IsEnum) + { + return null; + } + + return enumType; + } + + public static Type GetType(string typeName) + { + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); + foreach (var assembly in assemblies) + { + var type = assembly.GetType(typeName, false, true); + if (type != null) + { + return type; + } + } + return null; + } + } + + class NewObjectFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = script.GetFunctionArgs(); + + CompiledClass csClass = CSCSClass.GetClass(className) as CompiledClass; + if (csClass != null) + { + ScriptObject obj = csClass.GetImplementation(args); + return new Variable(obj); + } + CompiledClassAsync csClassAsync = CSCSClass.GetClass(className) as CompiledClassAsync; + if (csClassAsync != null) + { + ScriptObject obj = csClassAsync.GetImplementationAsync(args).Result; + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = await script.GetFunctionArgsAsync(); + + CompiledClassAsync csClassAsync = CSCSClass.GetClass(className) as CompiledClassAsync; + if (csClassAsync != null) + { + ScriptObject obj = await csClassAsync.GetImplementationAsync(args); + return new Variable(obj); + } + CompiledClass csClass = CSCSClass.GetClass(className) as CompiledClass; + if (csClass != null) + { + ScriptObject obj = csClass.GetImplementation(args); + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + } + + public class ClassCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + string[] baseClasses = Utils.GetBaseClasses(script); + CSCSClass newClass = new CSCSClass(className, baseClasses); + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + + newClass.ParentOffset = script.Pointer; + newClass.ParentScript = script; + /*string line = */script.GetOriginalLine(out _); + + string scriptExpr = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + string body = Utils.ConvertToScript(scriptExpr, out _); + + Variable result = null; + ParsingScript tempScript = script.GetTempScript(body); + tempScript.CurrentClass = newClass; + tempScript.DisableBreakpoints = true; + + // Uncomment if want to step into the class creation code when the debugger is attached (unlikely) + /*Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript); + }*/ + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + + return Variable.EmptyInstance; + } + } + + public class NamespaceFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string namespaceName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + //Utils.CheckNotEnd(script, m_name); + Variable result = null; + + ParserFunction.AddNamespace(namespaceName); + try + { + script.MoveForwardIf(Constants.START_GROUP); + string scriptExpr = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + Dictionary char2Line; + string body = Utils.ConvertToScript(scriptExpr, out char2Line); + + ParsingScript tempScript = script.GetTempScript(body); + tempScript.DisableBreakpoints = true; + tempScript.MoveForwardIf(Constants.START_GROUP); + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + } + finally + { + ParserFunction.PopNamespace(); + } + + return result; + } + } + + public class CustomFunction : ParserFunction + { + internal CustomFunction(string funcName, + string body, string[] args, ParsingScript script) + { + Name = funcName; + m_body = body; + m_args = RealArgs = args; + + for (int i = 0; i < args.Length; i++) + { + string arg = args[i]; + int ind = arg.IndexOf('='); + if (ind > 0) + { + RealArgs[i] = arg.Substring(0, ind).Trim(); + m_args[i] = RealArgs[i].ToLower(); + string defValue = ind >= arg.Length - 1 ? "" : arg.Substring(ind + 1).Trim(); + + Variable defVariable = Utils.GetVariableFromString(defValue, script); + defVariable.CurrentAssign = m_args[i]; + defVariable.Index = i; + + m_defArgMap[i] = m_defaultArgs.Count; + m_defaultArgs.Add(defVariable); + } + else + { + m_args[i] = RealArgs[i].ToLower(); + } + + ArgMap[m_args[i]] = i; + } + } + + public void RegisterArguments(List args, + List> args2 = null) + { + if (args == null) + { + args = new List(); + } + int missingArgs = m_args.Length - args.Count; + + bool namedParameters = false; + for (int i = 0; i < args.Count; i++) + { + var arg = args[i]; + int argIndex = -1; + if (ArgMap.TryGetValue(arg.CurrentAssign, out argIndex)) + { + namedParameters = true; + if (i != argIndex) + { + args[i] = argIndex < args.Count ? args[argIndex] : args[i]; + while (argIndex > args.Count - 1) + { + args.Add(Variable.EmptyInstance); + } + args[argIndex] = arg; + } + } + else if (namedParameters) + { + throw new ArgumentException("All arguments in function [" + m_name + + "] must be in arg=value form."); + } + } + + if (missingArgs > 0 && missingArgs <= m_defaultArgs.Count) + { + if (!namedParameters) + { + for (int i = m_defaultArgs.Count - missingArgs; i < m_defaultArgs.Count; i++) + { + args.Add(m_defaultArgs[i]); + } + } + else + { + for (int i = 0; i < args.Count; i++) + { + if (args[i].Type == Variable.VarType.NONE || + (!string.IsNullOrWhiteSpace(args[i].CurrentAssign) && + args[i].CurrentAssign != m_args[i])) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args[i] = m_defaultArgs[defIndex]; + } + } + } + } + for (int i = args.Count; i < m_args.Length; i++) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args.Add(m_defaultArgs[defIndex]); + } + m_stackLevel = new StackLevel(m_name); + + if (args2 != null) + { + foreach (var entry in args2) + { + var arg = new GetVarFunction(entry.Value); + arg.Name = entry.Key; + m_stackLevel.Variables[entry.Key] = arg; + } + } + + int maxSize = Math.Min(args.Count, m_args.Length); + for (int i = 0; i < maxSize; i++) + { + var arg = new GetVarFunction(args[i]); + arg.Name = m_args[i]; + m_stackLevel.Variables[m_args[i]] = arg; + } + + for (int i = m_args.Length; i < args.Count; i++) + { + var arg = new GetVarFunction(args[i]); + m_stackLevel.Variables[args[i].ParamName] = arg; + } + + if (NamespaceData != null) + { + var vars = NamespaceData.Variables; + string prefix = NamespaceData.Name + "."; + foreach (KeyValuePair elem in vars) + { + string key = elem.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ? + elem.Key.Substring(prefix.Length) : elem.Key; + m_stackLevel.Variables[key] = elem.Value; + } + } + + ParserFunction.AddLocalVariables(m_stackLevel); + } + + protected override Variable Evaluate(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + script.GetFunctionArgs(); + + Utils.ExtractParameterNames(args, m_name, script); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = Run(args, script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + await script.GetFunctionArgsAsync(); + + Utils.ExtractParameterNames(args, m_name, script); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = await RunAsync(args, script); + return result; + } + + public Variable Run(List args = null, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = Utils.GetTempScript(m_body, m_stackLevel, m_name, script, + m_parentScript, m_parentOffset, instance); + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (script != null && debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(m_stackLevel.Id); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + public async Task RunAsync(List args = null, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = Utils.GetTempScript(m_body, m_stackLevel, m_name, script, + m_parentScript, m_parentOffset, instance); + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = await debugger.StepInFunctionIfNeeded(tempScript); + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = await tempScript.ExecuteAsync(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(m_stackLevel.Id); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + + public static Task Run(string functionName, + Variable arg1 = null, Variable arg2 = null, Variable arg3 = null, ParsingScript script = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + if (arg3 != null) + { + args.Add(arg3); + } + + Variable result = customFunction.Run(args, script); + return Task.FromResult( result ); + } + + public static async Task RunAsync(string functionName, + Variable arg1 = null, Variable arg2 = null, Variable arg3 = null, ParsingScript script = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + if (arg3 != null) + { + args.Add(arg3); + } + + Variable result = await customFunction.RunAsync(args, script); + return result; + } + + public override ParserFunction NewInstance() + { + var newInstance = (CustomFunction)this.MemberwiseClone(); + newInstance.m_stackLevel = null; + return newInstance; + } + + public ParsingScript ParentScript { set { m_parentScript = value; } } + public int ParentOffset { set { m_parentOffset = value; } } + public string Body { get { return m_body; } } + + public int ArgumentCount { get { return m_args.Length; } } + public string Argument(int nIndex) { return m_args[nIndex]; } + + public StackLevel NamespaceData { get; set; } + + public int DefaultArgsCount + { + get + { + return m_defaultArgs.Count; + } + } + + public string Header + { + get + { + return Constants.FUNCTION + " " + Constants.GetRealName(Name) + " " + + Constants.START_ARG + string.Join(", ", m_args) + + Constants.END_ARG + " " + Constants.START_GROUP; + } + } + + protected string m_body; + protected string[] m_args; + protected ParsingScript m_parentScript = null; + protected int m_parentOffset = 0; + protected StackLevel m_stackLevel; + + List m_defaultArgs = new List(); + Dictionary m_defArgMap = new Dictionary(); + + public Dictionary ArgMap { get; private set; } = new Dictionary(); + public string[] RealArgs { get; private set; } + } + + class StringOrNumberFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // First check if the passed expression is a string between quotes. + if (Item.Length > 1 && + ((Item[0] == Constants.QUOTE && Item[Item.Length - 1] == Constants.QUOTE) || + (Item[0] == Constants.QUOTE1 && Item[Item.Length - 1] == Constants.QUOTE1))) + { + return new Variable(Item.Substring(1, Item.Length - 2)); + } + + // Otherwise this should be a number. + double num = Utils.ConvertToDouble(Item, script); + return new Variable(num); + } + + public string Item { private get; set; } + } + + class AddFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue), script); + } + + return currentValue; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue), script); + } + + return currentValue; + } + } + class RemoveFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + string varName = args[0].AsString(); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func, script); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = args[1]; + + bool removed = currentValue.Tuple.Remove(item); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue), script); + return new Variable(removed); + } + } + class RemoveAtFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func, script); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = Utils.GetItem(script); + Utils.CheckNonNegativeInt(item, script); + + currentValue.Tuple.RemoveAt(item.AsInt()); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue), script); + return Variable.EmptyInstance; + } + } + + class ContainsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + List arrayIndices = Utils.GetArrayIndices(script, varName, (newVarName) => { varName = newVarName; } ); + + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func, script); + Variable currentValue = func.GetValue(script); + + // 2b. Special dealings with arrays: + Variable query = arrayIndices.Count > 0 ? + Utils.ExtractArrayElement(currentValue, arrayIndices, script) : + currentValue; + + // 3. Get the value to be looked for. + Variable searchValue = Utils.GetItem(script); + Utils.CheckNotEnd(script, m_name); + + // 4. Check if the value to search for exists. + bool exists = query.Exists(searchValue, true /* notEmpty */); + + script.MoveBackIf(Constants.START_GROUP); + return new Variable(exists); + } + } + + class FindIndexFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable var = Utils.GetSafeVariable(args, 0); + string val = Utils.GetSafeString(args, 1); + + int index = var.FindIndex(val); + + return new Variable(index); + } + } + + class UndefinedFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.UNDEFINED); + } + } + + class BoolFunction : ParserFunction, INumericFunction + { + bool m_value; + public BoolFunction(bool init) + { + m_value = init; + } + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(m_value); + } + } + class ToDoubleFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToDouble(arg.AsString()); + return new Variable(result); + } + } + class ToIntFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + int result = Utils.ConvertToInt(arg.AsString()); + return new Variable(result); + } + } + class ToBoolFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToBool(arg.AsString()) ? 1 : 0; + return new Variable(result); + } + } + class ToDecimalFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = Decimal.Parse(arg.AsString(), NumberStyles.Any).ToString(); + return new Variable(result); + } + } + class ToStringFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + Variable arg = args[0]; + string format = Utils.GetSafeString(args, 1); + + string result = arg.AsString(format); + return new Variable(result); + } + } + class IdentityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return script.Execute(Constants.END_ARG_ARRAY); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await script.ExecuteAsync(Constants.END_ARG_ARRAY); + } + } + + class ConstantsFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(m_name); + } + } + + class IfStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable result = Interpreter.Instance.ProcessIf(script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + Variable result = await Interpreter.Instance.ProcessIfAsync(script); + return result; + } + } + + class ForStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessFor(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessForAsync(script); + } + } + + class WhileStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessWhile(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessWhileAsync(script); + } + } + + class DoWhileStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessDoWhile(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return Interpreter.Instance.ProcessDoWhile(script); + } + } + + class SwitchStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessSwitch(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return Interpreter.Instance.ProcessSwitch(script); + } + } + + class CaseStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessCase(script, Name); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return Interpreter.Instance.ProcessCase(script, Name); + } + } + + class IncludeFile : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + string filename = args[0].AsString(); + return Execute(filename, script); + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 1, m_name, true); + string filename = args[0].AsString(); + return await ExecuteAsync(filename, script); + } + + public static Variable Execute(string filename, ParsingScript parentScript = null) + { + if (parentScript == null) + { + parentScript = new ParsingScript(""); + } + ParsingScript tempScript = parentScript.GetIncludeFileScript(filename); + + Variable result = null; + if (parentScript.Debugger != null) + { + result = parentScript.Debugger.StepInIncludeIfNeeded(tempScript).Result; + } + + while (tempScript.StillValid()) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + + public static async Task ExecuteAsync(string filename, ParsingScript parentScript = null) + { + if (parentScript == null) + { + parentScript = new ParsingScript(""); + } + ParsingScript tempScript = parentScript.GetIncludeFileScript(filename); + + Variable result = null; + if (parentScript.Debugger != null) + { + result = await parentScript.Debugger.StepInIncludeIfNeeded(tempScript); + } + + while (tempScript.StillValid()) + { + result = await tempScript.ExecuteAsync(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + } + + // Get a value of a variable or of an array element + public class GetVarFunction : ParserFunction + { + public GetVarFunction(Variable value) + { + m_value = value; + } + + protected override Variable Evaluate(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = Utils.GetArrayIndices(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; } ); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices, script); + if (script.Prev == '.') + { + script.Backward(); + } + + if (script.TryCurrent() != '.') + { + return result; + } + script.Forward(); + + m_propName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + Variable propValue = result.GetProperty(m_propName, script); + Utils.CheckNotNull(propValue, m_propName, script); + return propValue; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + string temp = m_propName; + m_propName = null; // Need this to reset for recursive calls + Variable propValue = m_value.Type == Variable.VarType.ENUM ? + m_value.GetEnumProperty(temp, script) : + m_value.GetProperty(temp, script); + Utils.CheckNotNull(propValue, temp, script); + return EvaluateFunction(propValue, script, m_propName); + } + + // Otherwise just return the stored value. + return m_value; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = await Utils.GetArrayIndicesAsync(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; }); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices, script); + if (script.Prev == '.') + { + script.Backward(); + } + if (script.TryCurrent() != '.') + { + return result; + } + + script.Forward(); + m_propName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Variable propValue = await result.GetPropertyAsync(m_propName, script); + Utils.CheckNotNull(propValue, m_propName, script); + return propValue; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + string temp = m_propName; + m_propName = null; // Need this to reset for recursive calls + + Variable propValue = m_value.Type == Variable.VarType.ENUM ? + m_value.GetEnumProperty(temp, script) : + await m_value.GetPropertyAsync(temp, script); + Utils.CheckNotNull(propValue, temp, script); + return await EvaluateFunctionAsync(propValue, script, m_propName); + } + + // Otherwise just return the stored value. + return m_value; + } + + public static Variable EvaluateFunction(Variable var, ParsingScript script, string m_propName) + { + if (var.CustomFunctionGet != null) + { + List args = script.Prev == '(' ? script.GetFunctionArgs() : new List(); + if (var.StackVariables != null) + { + args.AddRange(var.StackVariables); + } + return var.CustomFunctionGet.Run(args, script); + } + if (!string.IsNullOrWhiteSpace(var.CustomGet)) + { + return ParsingScript.RunString(var.CustomGet); + } + return var; + } + + public static async Task EvaluateFunctionAsync(Variable var, ParsingScript script, string m_propName) + { + if (var.CustomFunctionGet != null) + { + List args = script.Prev == '(' ? await script.GetFunctionArgsAsync() : new List(); + if (var.StackVariables != null) + { + args.AddRange(var.StackVariables); + } + return await var.CustomFunctionGet.RunAsync(args, script); + } + if (!string.IsNullOrWhiteSpace(var.CustomGet)) + { + return ParsingScript.RunString(var.CustomGet); + } + return var; + } + + public int Delta + { + set { m_delta = value; } + } + public Variable Value + { + get { return m_value; } + } + public List Indices + { + set { m_arrayIndices = value; } + } + public string PropertyName + { + set { m_propName = value; } + } + + Variable m_value; + int m_delta = 0; + List m_arrayIndices = null; + string m_propName; + } + class IncrementDecrementFunction : ActionFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool prefix = string.IsNullOrWhiteSpace(m_name); + if (prefix) + {// If it is a prefix we do not have the variable name yet. + Name = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + } + + Utils.CheckForValidName(Name, script); + + // Value to be added to the variable: + int valueDelta = m_action == Constants.INCREMENT ? 1 : -1; + int returnDelta = prefix ? valueDelta : 0; + + // Check if the variable to be set has the form of x[a][b], + // meaning that this is an array element. + double newValue = 0; + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetVariable(m_name, script); + Utils.CheckNotNull(m_name, func, script); + + Variable currentValue = func.GetValue(script); + currentValue = currentValue.DeepClone(); + + if (arrayIndices.Count > 0 || script.TryCurrent() == Constants.START_ARRAY) + { + if (prefix) + { + string tmpName = m_name + script.Rest; + int delta = 0; + arrayIndices = Utils.GetArrayIndices(script, tmpName, delta, (string t, int d) => { tmpName = t; delta = d; }); + script.Forward(Math.Max(0, delta - tmpName.Length)); + } + + Variable element = Utils.ExtractArrayElement(currentValue, arrayIndices, script); + script.MoveForwardIf(Constants.END_ARRAY); + + newValue = element.Value + returnDelta; + element.Value += valueDelta; + } + else + { // A normal variable. + newValue = currentValue.Value + returnDelta; + currentValue.Value += valueDelta; + } + + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue), script); + return new Variable(newValue); + } + + override public ParserFunction NewInstance() + { + return new IncrementDecrementFunction(); + } + } + + class OperatorAssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // Value to be added to the variable: + Variable right = Utils.GetItem(script); + + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetVariable(m_name, script); + Utils.CheckNotNull(func, m_name, script); + + Variable currentValue = func.GetValue(script); + currentValue = currentValue.DeepClone(); + Variable left = currentValue; + + if (arrayIndices.Count > 0) + {// array element + left = Utils.ExtractArrayElement(currentValue, arrayIndices, script); + script.MoveForwardIf(Constants.END_ARRAY); + } + + if (left.Type == Variable.VarType.NUMBER) + { + NumberOperator(left, right, m_action); + } + else + { + StringOperator(left, right, m_action); + } + + if (arrayIndices.Count > 0) + {// array element + AssignFunction.ExtendArray(currentValue, arrayIndices, 0, left); + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue), script); + } + else + { + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(left), script); + } + return left; + } + + static void NumberOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + valueA.Value += valueB.Value; + break; + case "-=": + valueA.Value -= valueB.Value; + break; + case "*=": + valueA.Value *= valueB.Value; + break; + case "/=": + valueA.Value /= valueB.Value; + break; + case "%=": + valueA.Value %= valueB.Value; + break; + case "&=": + valueA.Value = (int)valueA.Value & (int)valueB.Value; + break; + case "|=": + valueA.Value = (int)valueA.Value | (int)valueB.Value; + break; + case "^=": + valueA.Value = (int)valueA.Value ^ (int)valueB.Value; + break; + } + } + static void StringOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + if (valueB.Type == Variable.VarType.STRING) + { + valueA.String += valueB.AsString(); + } + else + { + valueA.String += valueB.Value; + } + break; + } + } + + override public ParserFunction NewInstance() + { + return new OperatorAssignFunction(); + } + } + + class AssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Assign(script, m_name); + } + + public Variable Assign(ParsingScript script, string varName, bool localIfPossible = false) + { + m_name = Constants.GetRealName(varName); + script.CurrentAssign = m_name; + Variable varValue = Utils.GetItem(script); + + script.MoveBackIfPrevious(Constants.END_ARG); + varValue.TrySetAsMap(); + + if (script.Current == ' ' || script.Prev == ' ') + { + Utils.ThrowErrorMsg("Can't process expression [" + script.Rest + "].", + script, m_name); + } + + // First try processing as an object (with a dot notation): + Variable result = ProcessObject(script, varValue); + if (result != null) + { + if (script.CurrentClass == null && script.ClassInstance == null) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(result), script, localIfPossible); + } + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue), script, localIfPossible); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + } + + Variable array; + + ParserFunction pf = ParserFunction.GetVariable(m_name, script); + array = pf != null ? (pf.GetValue(script)) : new Variable(); + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array), script, localIfPossible); + return array; + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + return await AssignAsync(script, m_name); + } + + public async Task AssignAsync(ParsingScript script, string varName, bool localIfPossible = false) + { + m_name = Constants.GetRealName(varName); + script.CurrentAssign = m_name; + Variable varValue = await Utils.GetItemAsync(script); + + script.MoveBackIfPrevious(Constants.END_ARG); + varValue.TrySetAsMap(); + + if (script.Current == ' ' || script.Prev == ' ') + { + Utils.ThrowErrorMsg("Can't process expression [" + script.Rest + "].", + script, m_name); + } + + // First try processing as an object (with a dot notation): + Variable result = await ProcessObjectAsync(script, varValue); + if (result != null) + { + if (script.CurrentClass == null) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(result), script, localIfPossible); + } + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = await Utils.GetArrayIndicesAsync(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue), script, localIfPossible); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + } + + Variable array; + + ParserFunction pf = ParserFunction.GetVariable(m_name, script); + array = pf != null ? (await pf.GetValueAsync(script)) : new Variable(); + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array), script, localIfPossible); + return array; + } + + Variable ProcessObject(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + varValue = script.ClassInstance.SetProperty(m_name, varValue).Result; + return varValue.DeepClone(); + } + + int ind = varName.IndexOf('.'); + if (ind <= 0) + { + return null; + } + + Utils.CheckForValidName(varName, script); + + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + if (ParserFunction.TryAddToNamespace(prop, name, varValue)) + { + return varValue.DeepClone(); + } + + ParserFunction existing = ParserFunction.GetVariable(name, script); + Variable baseValue = existing != null ? existing.GetValue(script) : new Variable(Variable.VarType.ARRAY); + baseValue.SetProperty(prop, varValue, script, name); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue), script); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + async Task ProcessObjectAsync(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + await script.ClassInstance.SetProperty(m_name, varValue); + return varValue.DeepClone(); + } + + int ind = varName.IndexOf('.'); + if (ind <= 0) + { + return null; + } + + Utils.CheckForValidName(varName, script); + + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + if (ParserFunction.TryAddToNamespace(prop, name, varValue)) + { + return varValue.DeepClone(); + } + + ParserFunction existing = ParserFunction.GetVariable(name, script); + Variable baseValue = existing != null ? await existing.GetValueAsync(script) : new Variable(Variable.VarType.ARRAY); + await baseValue.SetPropertyAsync(prop, varValue, script, name); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue), script); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + + + override public ParserFunction NewInstance() + { + return new AssignFunction(); + } + + public static void ExtendArray(Variable parent, + List arrayIndices, + int indexPtr, + Variable varValue) + { + if (arrayIndices.Count <= indexPtr) + { + return; + } + + Variable index = arrayIndices[indexPtr]; + int currIndex = ExtendArrayHelper(parent, index); + + if (arrayIndices.Count - 1 == indexPtr) + { + parent.Tuple[currIndex] = varValue; + return; + } + + Variable son = parent.Tuple[currIndex]; + ExtendArray(son, arrayIndices, indexPtr + 1, varValue); + } + + private static int ExtendArrayHelper(Variable parent, Variable indexVar) + { + parent.SetAsArray(); + + int arrayIndex = parent.GetArrayIndex(indexVar); + if (arrayIndex < 0) + { + // This is not a "normal index" but a new string for the dictionary. + string hash = indexVar.AsString(); + arrayIndex = parent.SetHashVariable(hash, Variable.NewEmpty()); + return arrayIndex; + } + + if (parent.Tuple.Count <= arrayIndex) + { + for (int i = parent.Tuple.Count; i <= arrayIndex; i++) + { + parent.Tuple.Add(Variable.NewEmpty()); + } + } + return arrayIndex; + } + } + + class DeepCopyFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varValue = Utils.GetItem(script); + return varValue.DeepClone(); + } + } + + class TokenizeLinesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2, 0); + string sepStr = Utils.GetSafeString(args, 3, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + // var function = ParserFunction.GetVariable(varName, script); + Variable allTokensVar = new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; +#pragma warning disable 219 + // bugbug - the toAdd has side effects + Variable toAdd = new Variable(counter - fromLine); +#pragma warning restore 219 + string line = lineVar.AsString(); + var tokens = line.Split(sep); + Variable tokensVar = new Variable(Variable.VarType.ARRAY); + foreach (string token in tokens) + { + tokensVar.Tuple.Add(new Variable(token)); + } + allTokensVar.Tuple.Add(tokensVar); + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(allTokensVar), script); + + return Variable.EmptyInstance; + } + } + + class AddVariablesToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2); + string hash2 = Utils.GetSafeString(args, 3); + string sepStr = Utils.GetSafeString(args, 4, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + var function = ParserFunction.GetVariable(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; + Variable toAdd = new Variable(counter - fromLine); + string line = lineVar.AsString(); + var tokens = line.Split(sep); + string hash = tokens[0]; + mapVar.AddVariableToHash(hash, toAdd); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar), script); + return Variable.EmptyInstance; + } + } + class AddVariableToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable toAdd = Utils.GetSafeVariable(args, 1); + string hash = Utils.GetSafeString(args, 2); + + var function = ParserFunction.GetVariable(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + mapVar.AddVariableToHash(hash, toAdd); + for (int i = 3; i < args.Count; i++) + { + string hash2 = Utils.GetSafeString(args, 3); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar), script); + + return Variable.EmptyInstance; + } + } + class TokenCounterFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable all = Utils.GetSafeVariable(args, 0); + string varName = Utils.GetSafeString(args, 1); + int index = Utils.GetSafeInt(args, 2); + + // var function = ParserFunction.GetVariable(varName, script); + Variable mapVar = new Variable(Variable.VarType.ARRAY); + + if (all.Tuple == null) + { + return Variable.EmptyInstance; + } + + string currentValue = ""; + int currentCount = 0; + + int globalCount = 0; + + for (int i = 0; i < all.Tuple.Count; i++) + { + Variable current = all.Tuple[i]; + if (current.Tuple == null || current.Tuple.Count < index) + { + break; + } + string newValue = current.Tuple[index].AsString(); + if (currentValue != newValue) + { + currentValue = newValue; + currentCount = 0; + } + mapVar.Tuple.Add(new Variable(currentCount)); + currentCount++; + globalCount++; + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar), script); + // Script - Need to enable the warnings +#pragma warning restore 219 + return mapVar; + } + } + + class TypeFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + bool complexVariable = Utils.GetSafeInt(args, 1, 0) == 1; + Variable element = null; + if (complexVariable) + { + element = Utils.GetVariable(args[0].AsString(), script, false); + } + if (element == null) + { + element = Utils.GetSafeVariable(args, 0); + } + + string type = element.GetTypeString(); + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(type); + return newValue; + } + } + + class SizeFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.END_ARG_ARRAY); + Utils.CheckNotEnd(script, m_name); + + List arrayIndices = Utils.GetArrayIndices(script, varName, (newName) => { varName = newName; } ); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func, script); + Variable currentValue = func.GetValue(script); + Variable element = currentValue; + + // 2b. Special case for an array. + if (arrayIndices.Count > 0) + {// array element + element = Utils.ExtractArrayElement(currentValue, arrayIndices, script); + script.MoveForwardIf(Constants.END_ARRAY); + } + + // 3. Take either the length of the underlying tuple or + // string part if it is defined, + // or the numerical part converted to a string otherwise. + int size = element.GetSize(); + + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(size); + return newValue; + } + } + + class DefineLocalFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable currentValue = Utils.GetSafeVariable(args, 1); + + if (currentValue == null) + { + currentValue = new Variable(""); + } + + if (script.StackLevel != null) + { + ParserFunction.AddLocalVariable(new GetVarFunction(currentValue), varName); + } + else if (script.CurrentClass != null) + { + Utils.ThrowErrorMsg(m_name + " function can't be defined inside of a class.", + script, m_name); + } + else + { + string scopeName = Path.GetFileName(script.Filename); + ParserFunction.AddLocalScopeVariable(varName, scopeName, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + } + + class GetPropertiesFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + Variable baseValue = args[0]; + List props = baseValue.GetProperties(); + return new Variable(props); + } + } + + class GetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = baseValue.GetProperty(propName, script); + Utils.CheckNotNull(propValue, propName, script); + + return new Variable(propValue); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = await baseValue.GetPropertyAsync(propName, script); + Utils.CheckNotNull(propValue, propName, script); + + return new Variable(propValue); + } + public static Variable GetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = baseValue.GetProperty(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName, script); + + return new Variable(propValue); + } + public static async Task GetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = await baseValue.GetPropertyAsync(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName, script); + + return new Variable(propValue); + } + } + + class SetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = baseValue.SetProperty(propName, propValue, script); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue), script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = await baseValue.SetPropertyAsync(propName, propValue, script); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue), script); + return result; + } + + public static Variable SetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = baseValue.SetProperty(sPropertyName, propValue, script); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue), script); + return result; + } + public static async Task SetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = await baseValue.SetPropertyAsync(sPropertyName, propValue, script); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue), script); + return result; + } + } + + class CancelFunction : ParserFunction + { + public static bool Canceled { get; set; } + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 0, m_name, true); + + bool mode = Utils.GetSafeInt(args, 0, 1) == 1; + Canceled = mode; + + return new Variable(Canceled); + } + } + + public class ScheduleRunFunction : ParserFunction + { + static Dictionary m_timers = + new Dictionary(); + + bool m_startTimer; + + public ScheduleRunFunction(bool startTimer) + { + m_startTimer = startTimer; + } + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + + if (!m_startTimer) + { + Utils.CheckArgs(args.Count, 1, m_name); + string cancelTimerId = Utils.GetSafeString(args, 0); + System.Timers.Timer cancelTimer; + if (m_timers.TryGetValue(cancelTimerId, out cancelTimer)) + { + cancelTimer.Stop(); + cancelTimer.Dispose(); + m_timers.Remove(cancelTimerId); + } + return Variable.EmptyInstance; + } + + Utils.CheckArgs(args.Count, 2, m_name); + int timeout = args[0].AsInt(); + string strAction = args[1].AsString(); + string arg = Utils.GetSafeString(args, 2); + string timerId = Utils.GetSafeString(args, 3); + bool autoReset = Utils.GetSafeInt(args, 4, 0) != 0; + + arg = Utils.ProtectQuotes(arg); + timerId = Utils.ProtectQuotes(timerId); + + System.Timers.Timer pauseTimer = new System.Timers.Timer(timeout); + pauseTimer.Elapsed += (sender, e) => + { + if (!autoReset) + { + pauseTimer.Stop(); + pauseTimer.Dispose(); + m_timers.Remove(timerId); + } + string body = string.Format("{0}({1},{2});", strAction, + "\"" + arg + "\"", "\"" + timerId + "\""); + + ParsingScript tempScript = new ParsingScript(body); + tempScript.Execute(); + }; + pauseTimer.AutoReset = autoReset; + m_timers[timerId] = pauseTimer; + + pauseTimer.Start(); + + return Variable.EmptyInstance; + } + } + + public class SingletonFunction : ParserFunction + { + static Dictionary m_singletons = + new Dictionary(); + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string expr = args[0].AsString(); + Dictionary char2Line; + expr = Utils.ConvertToScript(expr, out char2Line); + + Variable result; + if (m_singletons.TryGetValue(expr, out result)) + { + return result; + } + + ParsingScript tempScript = new ParsingScript(expr); + result = tempScript.Execute(); + + m_singletons[expr] = result; + + return result; + } + } + + class GetColumnFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable arrayVar = Utils.GetSafeVariable(args, 0); + int col = Utils.GetSafeInt(args, 1); + int fromCol = Utils.GetSafeInt(args, 2, 0); + + var tuple = arrayVar.Tuple; + + List result = new List(tuple.Count); + for (int i = fromCol; i < tuple.Count; i++) + { + Variable current = tuple[i]; + if (current.Tuple == null || current.Tuple.Count <= col) + { + throw new ArgumentException(m_name + ": Index [" + col + "] doesn't exist in column " + + i + "/" + (tuple.Count - 1)); + } + result.Add(current.Tuple[col]); + } + + return new Variable(result); + } + } + + class GetAllKeysFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varName = Utils.GetItem(script); + Utils.CheckNotNull(varName, m_name, script); + + List results = varName.GetAllKeys(); + + return new Variable(results); + } + } + + class CheckLoaderMainFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool isMain = !string.IsNullOrWhiteSpace(script.MainFilename) && + script.MainFilename == script.Filename; + + return new Variable(isMain); + } + } + + class ResetVariablesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + ParserFunction.CleanUpVariables(); + return Variable.EmptyInstance; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `all` last assigned on line 2619 could be null and is dereferenced at line 2626, column 13. + +### Severity: +ERROR + +### Procedure: +Variable TokenCounterFunction.Evaluate(ParsingScript) + +### File: +cscs/Functions.Flow.cs + +### Key: +Functions.Flow.cs|Evaluate|NULL_DEREFERENCE + +### Node Key: +bef2fe14012af516d6c7bc5d1bd471c5 + +### Hash: +b0f56c2b42f5b0422f61218dea743349 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1843/instruction.md b/inferredbugs-1843/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c8bd554c24b50b161a4fa06ba60b7bcf50d13080 --- /dev/null +++ b/inferredbugs-1843/instruction.md @@ -0,0 +1,2375 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cscs +**Bug ID:** 59 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Threading.Tasks; + +namespace SplitAndMerge +{ + class BreakStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.BREAK); + } + } + class ContinueStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.CONTINUE); + } + } + + class ReturnStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = Utils.GetItem(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = await Utils.GetItemAsync(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + } + + class TryBlock : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessTry(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessTryAsync(script); + } + } + + class ExitFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Environment.Exit(0); + return Variable.EmptyInstance; + } + } + + class ThrowFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = Utils.GetItem(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = await Utils.GetItemAsync(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + } + + class ShowFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + string funcName = args[0].AsString(); + + ParserFunction function = ParserFunction.GetFunction(funcName, script); + CustomFunction custFunc = function as CustomFunction; + Utils.CheckNotNull(funcName, custFunc); + + string body = Utils.BeautifyScript(custFunc.Body, custFunc.Header); + Utils.PrintScript(body, script); + + return new Variable(body); + } + } + + class FunctionCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string funcName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + funcName = Constants.ConvertName(funcName); + + string[] args = Utils.GetFunctionSignature(script); + if (args.Length == 1 && string.IsNullOrWhiteSpace(args[0])) + { + args = new string[0]; + } + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + int lineNumber = 0; + /*string line = */script.GetOriginalLine(out lineNumber); + + int parentOffset = script.Pointer; + + if (script.CurrentClass != null) + { + parentOffset += script.CurrentClass.ParentOffset; + } + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + CustomFunction customFunc = new CustomFunction(funcName, body, args, script); + customFunc.ParentScript = script; + customFunc.ParentOffset = parentOffset; + + if (script.CurrentClass != null) + { + script.CurrentClass.AddMethod(funcName, args, customFunc); + } + else + { + ParserFunction.RegisterFunction(funcName, customFunc, false /* not native */); + } + + return Variable.EmptyInstance; + } + } + + public class CSCSClass : ParserFunction + { + public CSCSClass() {} + + public CSCSClass(string className) + { + Name = className; + RegisterClass(className, this); + } + + public CSCSClass(string className, string[] baseClasses) + { + Name = className; + RegisterClass(className, this); + + foreach (string baseClass in baseClasses) + { + var bc = CSCSClass.GetClass(baseClass); + if (bc == null) + { + throw new ArgumentException("Base Class [" + baseClass + "] not found."); + } + + foreach (var entry in bc.m_classProperties) + { + m_classProperties[entry.Key] = entry.Value; + } + foreach (var entry in bc.m_customFunctions) + { + m_customFunctions[entry.Key] = entry.Value; + } + } + } + + public static void RegisterClass(string className, CSCSClass obj) + { + obj.Name = className; + className = Constants.ConvertName(className); + s_allClasses[className] = obj; + } + + protected override Variable Evaluate(ParsingScript script) + { + script.GetFunctionArgs(); + + // TODO: Work in progress, currently not functional + return Variable.EmptyInstance; + } + + public void AddMethod(string name, string[] args, CustomFunction method) + { + if (name == m_name) + { + m_constructors[args.Length] = method; + for (int i = 0; i < method.DefaultArgsCount && i < args.Length; i++) + { + m_constructors[args.Length - i - 1] = method; + } + } + else + { + m_customFunctions[name] = method; + } + } + + public void AddProperty(string name, Variable property) + { + m_classProperties[name] = property; + } + + public static CSCSClass GetClass(string name) + { + CSCSClass theClass = null; + s_allClasses.TryGetValue(name, out theClass); + return theClass; + } + + static Dictionary s_allClasses = + new Dictionary(); + + Dictionary m_constructors = + new Dictionary(); + Dictionary m_customFunctions = + new Dictionary(); + Dictionary m_classProperties = + new Dictionary(); + + public ParsingScript ParentScript = null; + public int ParentOffset = 0; + + public class ClassInstance : ScriptObject + { + public ClassInstance(string instanceName, string className, List args, + ParsingScript script = null) + { + InstanceName = instanceName; + m_cscsClass = CSCSClass.GetClass(className); + if (m_cscsClass == null) + { + throw new ArgumentException("Class [" + className + "] not found."); + } + + // Copy over all the properties defined for this class. + foreach (var entry in m_cscsClass.m_classProperties) + { + SetProperty(entry.Key, entry.Value); + } + + // Run "constructor" if any is defined for this number of args. + CustomFunction constructor = null; + if (m_cscsClass.m_constructors.TryGetValue(args.Count, out constructor)) + { + constructor.Run(args, script, this); + } + } + + public string InstanceName { get; set; } + CSCSClass m_cscsClass; + + Dictionary m_properties = new Dictionary(); + HashSet m_propSet = new HashSet(); + + public override string ToString() + { + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(Constants.PROP_TO_STRING.ToLower(), + out customFunction)) + { + return m_cscsClass.Name + "." + InstanceName; + } + + Variable result = customFunction.Run(null, null, this); + return result.ToString(); + } + + public Task SetProperty(string name, Variable value) + { + m_properties[name] = value; + m_propSet.Add(name); + return Task.FromResult( Variable.EmptyInstance ); + } + + public async Task GetProperty(string name, List args = null, ParsingScript script = null) + { + Variable value = null; + if (m_properties.TryGetValue(name, out value)) + { + return value; + } + + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out customFunction)) + { + return null; + } + if (args == null) + { + return Variable.EmptyInstance; + } + + foreach (var entry in m_cscsClass.m_classProperties) + { + args.Add(entry.Value); + } + + Variable result = await customFunction.RunAsync(args, script, this); + return result; + } + + public List> GetPropList() + { + List> props = new List>(); + foreach (var entry in m_properties) + { + props.Add(new KeyValuePair(entry.Key, entry.Value)); + } + return props; + } + + public List GetProperties() + { + List props = new List(m_properties.Keys); + props.AddRange(m_cscsClass.m_customFunctions.Keys); + + return props; + } + public bool PropertyExists(string name) + { + return m_propSet.Contains(name); + } + + public bool FunctionExists(string name) + { + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out customFunction)) + { + return false; + } + return true; + } + } + } + + class NameExistsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string funcName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + funcName = Constants.ConvertName(funcName); + + ParserFunction function = ParserFunction.GetFunction(funcName, script); + return new Variable(function != null); + } + } + + class EnumFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List properties = Utils.ExtractTokens(script); + + if (properties.Count == 1 && properties[0].Contains(".")) + { + return UseExistingEnum(properties[0]); + } + + Variable enumVar = new Variable(Variable.VarType.ENUM); + for (int i = 0; i < properties.Count; i++) + { + enumVar.SetEnumProperty(properties[i], new Variable(i)); + } + + return enumVar; + } + + public static Variable UseExistingEnum(string enumName) + { + Type enumType = GetEnumType(enumName); + if (enumType == null || !enumType.IsEnum) + { + return Variable.EmptyInstance; + } + + var names = Enum.GetNames(enumType); + + Variable enumVar = new Variable(Variable.VarType.ENUM); + for (int i = 0; i < names.Length; i++) + { + var numValue = Enum.Parse(enumType, names[i], true); + enumVar.SetEnumProperty(names[i], new Variable((int)numValue)); + } + + return enumVar; + } + + public static Type GetEnumType(string enumName) + { + string[] tokens = enumName.Split('.'); + + Type enumType = null; + int index = 0; + string typeName = ""; + while(enumType == null && index < tokens.Length) + { + if (!string.IsNullOrWhiteSpace(typeName)) + { + typeName += "."; + } + typeName += tokens[index]; + enumType = GetType(typeName); + index++; + } + + for (int i = index; i < tokens.Length && enumType != null; i++) + { + enumType = enumType.GetNestedType(tokens[i]); + } + + if (enumType == null || !enumType.IsEnum) + { + return null; + } + + return enumType; + } + + public static Type GetType(string typeName) + { + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); + foreach (var assembly in assemblies) + { + var type = assembly.GetType(typeName, false, true); + if (type != null) + { + return type; + } + } + return null; + } + } + + class NewObjectFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = script.GetFunctionArgs(); + + CompiledClass csClass = CSCSClass.GetClass(className) as CompiledClass; + if (csClass != null) + { + ScriptObject obj = csClass.GetImplementation(args); + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = await script.GetFunctionArgsAsync(); + + CompiledClassAsync csClass = CSCSClass.GetClass(className) as CompiledClassAsync; + if (csClass != null) + { + ScriptObject obj = await csClass.GetImplementationAsync(args); + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + } + + public class ClassCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + string[] baseClasses = Utils.GetBaseClasses(script); + CSCSClass newClass = new CSCSClass(className, baseClasses); + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + + newClass.ParentOffset = script.Pointer; + newClass.ParentScript = script; + int lineNumber = 0; + /*string line = */script.GetOriginalLine(out lineNumber); + + string scriptExpr = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + Dictionary char2Line; + string body = Utils.ConvertToScript(scriptExpr, out char2Line); + + Variable result = null; + ParsingScript tempScript = new ParsingScript(body); + //tempScript.ScriptOffset = newClass.ParentOffset; + tempScript.Char2Line = script.Char2Line; + tempScript.Filename = script.Filename; + tempScript.OriginalScript = script.OriginalScript; + tempScript.CurrentClass = newClass; + tempScript.ParentScript = script; + tempScript.InTryBlock = script.InTryBlock; + tempScript.DisableBreakpoints = true; + + // Uncomment if want to step into the class creation code when the debugger is attached (unlikely) + /*Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript); + }*/ + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + + return Variable.EmptyInstance; + } + } + + public class CustomFunction : ParserFunction + { + internal CustomFunction(string funcName, + string body, string[] args, ParsingScript script) + { + Name = funcName; + m_body = body; + m_args = args; + + for (int i = 0; i < args.Length; i++) + { + string arg = args[i]; + int ind = arg.IndexOf('='); + if (ind > 0) + { + m_args[i] = arg.Substring(0, ind).Trim().ToLower(); + string defValue = ind >= arg.Length - 1 ? "" : arg.Substring(ind + 1).Trim(); + + Variable defVariable = Utils.GetVariableFromString(defValue, script); + defVariable.CurrentAssign = m_args[i]; + defVariable.Index = i; + + m_defArgMap[i] = m_defaultArgs.Count; + m_defaultArgs.Add(defVariable); + } + else + { + m_args[i] = arg.ToLower(); + } + m_argMap[m_args[i]] = i; + } + } + + public void RegisterArguments(List args, + List> args2 = null) + { + if (args == null) + { + return; + } + + int missingArgs = m_args.Length - args.Count; + + bool namedParameters = false; + for (int i = 0; i < args.Count; i++) + { + var arg = args[i]; + int argIndex = -1; + if (m_argMap.TryGetValue(arg.CurrentAssign, out argIndex)) + { + namedParameters = true; + if (i != argIndex) + { + args[i] = argIndex < args.Count ? args[argIndex] : args[i]; + while (argIndex > args.Count - 1) + { + args.Add(Variable.EmptyInstance); + } + args[argIndex] = arg; + } + } + else if (namedParameters) + { + throw new ArgumentException("All arguments in function [" + m_name + + "] must be arg=value form."); + } + } + + if (missingArgs > 0 && missingArgs <= m_defaultArgs.Count) + { + if (!namedParameters) + { + for (int i = m_defaultArgs.Count - missingArgs; i < m_defaultArgs.Count; i++) + { + args.Add(m_defaultArgs[i]); + } + } + else + { + for (int i = 0; i < args.Count; i++) + { + if (args[i].Type == Variable.VarType.NONE || + (!string.IsNullOrWhiteSpace(args[i].CurrentAssign) && + args[i].CurrentAssign != m_args[i])) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args[i] = m_defaultArgs[defIndex]; + } + } + } + } + for (int i = args.Count; i < m_args.Length; i++) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args.Add(m_defaultArgs[defIndex]); + } + StackLevel stackLevel = new StackLevel(m_name); + + if (args2 != null) + { + foreach (var entry in args2) + { + var arg = new GetVarFunction(entry.Value); + arg.Name = entry.Key; + stackLevel.Variables[entry.Key] = arg; + } + } + + int maxSize = Math.Min(args.Count, m_args.Length); + for (int i = 0; i < maxSize; i++) + { + var arg = new GetVarFunction(args[i]); + arg.Name = m_args[i]; + stackLevel.Variables[m_args[i]] = arg; + } + + ParserFunction.AddLocalVariables(stackLevel); + } + + protected override Variable Evaluate(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + script.GetFunctionArgs(); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = Run(args, script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + await script.GetFunctionArgsAsync(); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = await RunAsync(args, script); + return result; + } + + public Variable Run(List args = null, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = new ParsingScript(m_body); + tempScript.ScriptOffset = m_parentOffset; + if (m_parentScript != null) + { + tempScript.Char2Line = m_parentScript.Char2Line; + tempScript.Filename = m_parentScript.Filename; + tempScript.OriginalScript = m_parentScript.OriginalScript; + } + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.ClassInstance = instance; + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + public async Task RunAsync(List args = null, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = new ParsingScript(m_body); + tempScript.ScriptOffset = m_parentOffset; + if (m_parentScript != null) + { + tempScript.Char2Line = m_parentScript.Char2Line; + tempScript.Filename = m_parentScript.Filename; + tempScript.OriginalScript = m_parentScript.OriginalScript; + } + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.ClassInstance = instance; + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = await debugger.StepInFunctionIfNeeded(tempScript); + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = await tempScript.ExecuteToAsync(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + + public static Task Run(string functionName, + Variable arg1 = null, Variable arg2 = null, Variable arg3 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + if (arg3 != null) + { + args.Add(arg3); + } + + Variable result = customFunction.Run(args); + return Task.FromResult( result ); + } + + public static async Task RunAsync(string functionName, + Variable arg1 = null, Variable arg2 = null, Variable arg3 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + if (arg3 != null) + { + args.Add(arg3); + } + + Variable result = await customFunction.RunAsync(args); + return result; + } + + public ParsingScript ParentScript { set { m_parentScript = value; } } + public int ParentOffset { set { m_parentOffset = value; } } + public string Body { get { return m_body; } } + + public int ArgumentCount { get { return m_args.Length; } } + public string Argument(int nIndex) { return m_args[nIndex]; } + + public int DefaultArgsCount + { + get + { + return m_defaultArgs.Count; + } + } + + public string Header + { + get + { + return Constants.FUNCTION + " " + Constants.GetRealName(Name) + " " + + Constants.START_ARG + string.Join(", ", m_args) + + Constants.END_ARG + " " + Constants.START_GROUP; + } + } + + protected string m_body; + protected string[] m_args; + protected ParsingScript m_parentScript = null; + protected int m_parentOffset = 0; + + List m_defaultArgs = new List(); + Dictionary m_argMap = new Dictionary(); + Dictionary m_defArgMap = new Dictionary(); + } + + class StringOrNumberFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // First check if the passed expression is a string between quotes. + if (Item.Length > 1 && + ((Item[0] == Constants.QUOTE && Item[Item.Length - 1] == Constants.QUOTE) || + (Item[0] == Constants.QUOTE1 && Item[Item.Length - 1] == Constants.QUOTE1))) + { + return new Variable(Item.Substring(1, Item.Length - 2)); + } + + // Otherwise this should be a number. + double num = Utils.ConvertToDouble(Item, script); + return new Variable(num); + } + + public string Item { private get; set; } + } + + class AddFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + } + class RemoveFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + string varName = args[0].AsString(); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = args[1]; + + bool removed = currentValue.Tuple.Remove(item); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return new Variable(removed); + } + } + class RemoveAtFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = Utils.GetItem(script); + Utils.CheckNonNegativeInt(item); + + currentValue.Tuple.RemoveAt(item.AsInt()); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return Variable.EmptyInstance; + } + } + + class ContainsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + List arrayIndices = Utils.GetArrayIndices(script, varName, (newVarName) => { varName = newVarName; } ); + + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + + // 2b. Special dealings with arrays: + Variable query = arrayIndices.Count > 0 ? + Utils.ExtractArrayElement(currentValue, arrayIndices) : + currentValue; + + // 3. Get the value to be looked for. + Variable searchValue = Utils.GetItem(script); + Utils.CheckNotEnd(script, m_name); + + // 4. Check if the value to search for exists. + bool exists = query.Exists(searchValue, true /* notEmpty */); + + script.MoveBackIf(Constants.START_GROUP); + return new Variable(exists); + } + } + + class FindIndexFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable var = Utils.GetSafeVariable(args, 0); + string val = Utils.GetSafeString(args, 1); + + int index = var.FindIndex(val); + + return new Variable(index); + } + } + + class BoolFunction : ParserFunction, INumericFunction + { + bool m_value; + public BoolFunction(bool init) + { + m_value = init; + } + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(m_value); + } + } + class ToDoubleFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToDouble(arg.AsString()); + return new Variable(result); + } + } + class ToIntFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + int result = Utils.ConvertToInt(arg.AsString()); + return new Variable(result); + } + } + class ToBoolFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToBool(arg.AsString()) ? 1 : 0; + return new Variable(result); + } + } + class ToDecimalFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = Decimal.Parse(arg.AsString(), NumberStyles.Any).ToString(); + return new Variable(result); + } + } + class ToStringFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = arg.AsString(); + return new Variable(result); + } + } + class IdentityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return script.ExecuteTo(Constants.END_ARG); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await script.ExecuteToAsync(Constants.END_ARG); + } + } + + class IfStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable result = Interpreter.Instance.ProcessIf(script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + Variable result = await Interpreter.Instance.ProcessIfAsync(script); + return result; + } + } + + class ForStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessFor(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessForAsync(script); + } + } + + class WhileStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessWhile(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessWhileAsync(script); + } + } + + class IncludeFile : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + string includeScript; + ParsingScript tempScript = GetIncludeFileScript(script, args, out includeScript); + + Variable result = null; + if (script.Debugger != null) + { + result = script.Debugger.StepInIncludeIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < includeScript.Length) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + string includeScript; + ParsingScript tempScript = GetIncludeFileScript(script, args, out includeScript); + + Variable result = null; + if (script.Debugger != null) + { + result = await script.Debugger.StepInIncludeIfNeeded(tempScript); + } + + while (tempScript.Pointer < includeScript.Length) + { + result = await tempScript.ExecuteToAsync(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + + ParsingScript GetIncludeFileScript(ParsingScript script, List args, out string includeScript) + { + Utils.CheckArgs(args.Count, 1, m_name, true); + + string filename = args[0].AsString(); + string pathname = script.GetFilePath(filename); + string[] lines = Utils.GetFileLines(pathname); + + string includeFile = string.Join(Environment.NewLine, lines); + Dictionary char2Line; + includeScript = Utils.ConvertToScript(includeFile, out char2Line, pathname); + ParsingScript tempScript = new ParsingScript(includeScript, 0, char2Line); + tempScript.Filename = pathname; + tempScript.OriginalScript = string.Join(Constants.END_LINE.ToString(), lines); + tempScript.ParentScript = script; + tempScript.InTryBlock = script.InTryBlock; + + return tempScript; + } + } + + // Get a value of a variable or of an array element + public class GetVarFunction : ParserFunction + { + public GetVarFunction(Variable value) + { + m_value = value; + } + + protected override Variable Evaluate(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = Utils.GetArrayIndices(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; } ); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices); + if (script.TryCurrent() != '.') + { + return result; + } + + script.Forward(); + m_propName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Variable propValue = result.GetProperty(m_propName, script); + Utils.CheckNotNull(propValue, m_propName); + return propValue; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + string temp = m_propName; + m_propName = null; // Need this to reset for recursive calls + Variable propValue = m_value.Type == Variable.VarType.ENUM ? + m_value.GetEnumProperty(temp, script) : + m_value.GetProperty(temp, script); + Utils.CheckNotNull(propValue, temp); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = await Utils.GetArrayIndicesAsync(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; }); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices); + if (script.TryCurrent() != '.') + { + return result; + } + + script.Forward(); + m_propName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Variable propValue = await result.GetPropertyAsync(m_propName, script); + Utils.CheckNotNull(propValue, m_propName); + return propValue; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + string temp = m_propName; + m_propName = null; // Need this to reset for recursive calls + + Variable propValue = m_value.Type == Variable.VarType.ENUM ? + m_value.GetEnumProperty(temp, script) : + await m_value.GetPropertyAsync(temp, script); + Utils.CheckNotNull(propValue, temp, script); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + + public int Delta + { + set { m_delta = value; } + } + public Variable Value + { + get { return m_value; } + } + public List Indices + { + set { m_arrayIndices = value; } + } + public string PropertyName + { + set { m_propName = value; } + } + + Variable m_value; + int m_delta = 0; + List m_arrayIndices = null; + string m_propName; + } + class IncrementDecrementFunction : ActionFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool prefix = string.IsNullOrWhiteSpace(m_name); + if (prefix) + {// If it is a prefix we do not have the variable name yet. + Name = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + } + + // Value to be added to the variable: + int valueDelta = m_action == Constants.INCREMENT ? 1 : -1; + int returnDelta = prefix ? valueDelta : 0; + + // Check if the variable to be set has the form of x[a][b], + // meaning that this is an array element. + double newValue = 0; + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetFunction(m_name, script); + Utils.CheckNotNull(m_name, func); + + Variable currentValue = func.GetValue(script); + currentValue = currentValue.DeepClone(); + + if (arrayIndices.Count > 0 || script.TryCurrent() == Constants.START_ARRAY) + { + if (prefix) + { + string tmpName = m_name + script.Rest; + int delta = 0; + arrayIndices = Utils.GetArrayIndices(script, tmpName, delta, (string t, int d) => { tmpName = t; delta = d; }); + script.Forward(Math.Max(0, delta - tmpName.Length)); + } + + Variable element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + + newValue = element.Value + returnDelta; + element.Value += valueDelta; + } + else + { // A normal variable. + newValue = currentValue.Value + returnDelta; + currentValue.Value += valueDelta; + } + + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + return new Variable(newValue); + } + + override public ParserFunction NewInstance() + { + return new IncrementDecrementFunction(); + } + } + + class OperatorAssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // Value to be added to the variable: + Variable right = Utils.GetItem(script); + + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetFunction(m_name, script); + Utils.CheckNotNull(func, m_name, script); + + Variable currentValue = func.GetValue(script); + currentValue = currentValue.DeepClone(); + Variable left = currentValue; + + if (arrayIndices.Count > 0) + {// array element + left = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + if (left.Type == Variable.VarType.NUMBER) + { + NumberOperator(left, right, m_action); + } + else + { + StringOperator(left, right, m_action); + } + + if (arrayIndices.Count > 0) + {// array element + AssignFunction.ExtendArray(currentValue, arrayIndices, 0, left); + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + } + else + { + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(left)); + } + return left; + } + + static void NumberOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + valueA.Value += valueB.Value; + break; + case "-=": + valueA.Value -= valueB.Value; + break; + case "*=": + valueA.Value *= valueB.Value; + break; + case "/=": + valueA.Value /= valueB.Value; + break; + case "%=": + valueA.Value %= valueB.Value; + break; + case "&=": + valueA.Value = (int)valueA.Value & (int)valueB.Value; + break; + case "|=": + valueA.Value = (int)valueA.Value | (int)valueB.Value; + break; + case "^=": + valueA.Value = (int)valueA.Value ^ (int)valueB.Value; + break; + } + } + static void StringOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + if (valueB.Type == Variable.VarType.STRING) + { + valueA.String += valueB.AsString(); + } + else + { + valueA.String += valueB.Value; + } + break; + } + } + + override public ParserFunction NewInstance() + { + return new OperatorAssignFunction(); + } + } + + class AssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + m_name = Constants.GetRealName(m_name); + script.CurrentAssign = m_name; + Variable varValue = Utils.GetItem(script); + + // First try processing as an object (with a dot notation): + Variable result = ProcessObject(script, varValue); + if (result != null) + { + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue)); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + //return varValue.DeepClone(); + } + + Variable array; + + ParserFunction pf = ParserFunction.GetFunction(m_name, script); + if (pf != null) + { + array = pf.GetValue(script); + } + else + { + array = new Variable(); + } + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array)); + return array; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + m_name = Constants.GetRealName(m_name); + script.CurrentAssign = m_name; + Variable varValue = await Utils.GetItemAsync(script); + + // First try processing as an object (with a dot notation): + Variable result = await ProcessObjectAsync(script, varValue); + if (result != null) + { + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = await Utils.GetArrayIndicesAsync(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue)); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + //return varValue.DeepClone(); + } + + Variable array; + + ParserFunction pf = ParserFunction.GetFunction(m_name, script); + if (pf != null) + { + array = await pf.GetValueAsync(script); + } + else + { + array = new Variable(); + } + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array)); + return array; + } + + Variable ProcessObject(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + varValue = script.ClassInstance.SetProperty(m_name, varValue).Result; + return varValue.DeepClone(); + } + + int ind = varName.IndexOf('.'); + if (ind <= 0) + { + return null; + } + + Utils.CheckForValidName(varName, script); + + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + ParserFunction existing = ParserFunction.GetFunction(name, script); + Variable baseValue = existing != null ? existing.GetValue(script) : new Variable(Variable.VarType.ARRAY); + baseValue.SetProperty(prop, varValue, name); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue)); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + async Task ProcessObjectAsync(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + await script.ClassInstance.SetProperty(m_name, varValue); + return varValue.DeepClone(); + } + + int ind = varName.IndexOf('.'); + if (ind <= 0) + { + return null; + } + + Utils.CheckForValidName(varName, script); + + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + ParserFunction existing = ParserFunction.GetFunction(name, script); + Variable baseValue = existing != null ? await existing.GetValueAsync(script) : new Variable(Variable.VarType.ARRAY); + await baseValue.SetPropertyAsync(prop, varValue, name); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue)); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + + + override public ParserFunction NewInstance() + { + return new AssignFunction(); + } + + public static void ExtendArray(Variable parent, + List arrayIndices, + int indexPtr, + Variable varValue) + { + if (arrayIndices.Count <= indexPtr) + { + return; + } + + Variable index = arrayIndices[indexPtr]; + int currIndex = ExtendArrayHelper(parent, index); + + if (arrayIndices.Count - 1 == indexPtr) + { + parent.Tuple[currIndex] = varValue; + return; + } + + Variable son = parent.Tuple[currIndex]; + ExtendArray(son, arrayIndices, indexPtr + 1, varValue); + } + + private static int ExtendArrayHelper(Variable parent, Variable indexVar) + { + parent.SetAsArray(); + + int arrayIndex = parent.GetArrayIndex(indexVar); + if (arrayIndex < 0) + { + // This is not a "normal index" but a new string for the dictionary. + string hash = indexVar.AsString(); + arrayIndex = parent.SetHashVariable(hash, Variable.NewEmpty()); + return arrayIndex; + } + + if (parent.Tuple.Count <= arrayIndex) + { + for (int i = parent.Tuple.Count; i <= arrayIndex; i++) + { + parent.Tuple.Add(Variable.NewEmpty()); + } + } + return arrayIndex; + } + } + + class DeepCopyFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varValue = Utils.GetItem(script); + return varValue.DeepClone(); ; + } + } + + class TokenizeLinesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2, 0); + string sepStr = Utils.GetSafeString(args, 3, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + // var function = ParserFunction.GetFunction(varName, script); + Variable allTokensVar = new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; +#pragma warning disable 219 + // bugbug - the toAdd has side effects + Variable toAdd = new Variable(counter - fromLine); +#pragma warning restore 219 + string line = lineVar.AsString(); + var tokens = line.Split(sep); + Variable tokensVar = new Variable(Variable.VarType.ARRAY); + foreach (string token in tokens) + { + tokensVar.Tuple.Add(new Variable(token)); + } + allTokensVar.Tuple.Add(tokensVar); + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(allTokensVar)); + + return Variable.EmptyInstance; + } + } + + class AddVariablesToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2); + string hash2 = Utils.GetSafeString(args, 3); + string sepStr = Utils.GetSafeString(args, 4, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; + Variable toAdd = new Variable(counter - fromLine); + string line = lineVar.AsString(); + var tokens = line.Split(sep); + string hash = tokens[0]; + mapVar.AddVariableToHash(hash, toAdd); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + return Variable.EmptyInstance; + } + } + class AddVariableToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable toAdd = Utils.GetSafeVariable(args, 1); + string hash = Utils.GetSafeString(args, 2); + + var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + mapVar.AddVariableToHash(hash, toAdd); + for (int i = 3; i < args.Count; i++) + { + string hash2 = Utils.GetSafeString(args, 3); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + + return Variable.EmptyInstance; + } + } + class TokenCounterFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable all = Utils.GetSafeVariable(args, 0); + string varName = Utils.GetSafeString(args, 1); + int index = Utils.GetSafeInt(args, 2); + + // var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = new Variable(Variable.VarType.ARRAY); + + if (all.Tuple == null) + { + return Variable.EmptyInstance; + } + + string currentValue = ""; + int currentCount = 0; + + int globalCount = 0; + + for (int i = 0; i < all.Tuple.Count; i++) + { + Variable current = all.Tuple[i]; + if (current.Tuple == null || current.Tuple.Count < index) + { + break; + } + string newValue = current.Tuple[index].AsString(); + if (currentValue != newValue) + { + currentValue = newValue; + currentCount = 0; + } + mapVar.Tuple.Add(new Variable(currentCount)); + currentCount++; + globalCount++; + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + // Script - Need to enable the warnings +#pragma warning restore 219 + return mapVar; + } + } + + class TypeFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + bool complexVariable = Utils.GetSafeInt(args, 1, 0) == 1; + Variable element = null; + if (complexVariable) + { + element = Utils.GetVariable(args[0].AsString(), script, false); + } + if (element == null) + { + element = Utils.GetSafeVariable(args, 0); + } + + string type = element.GetTypeString(); + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(type); + return newValue; + } + } + + class SizeFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.END_ARG_ARRAY); + Utils.CheckNotEnd(script, m_name); + + List arrayIndices = Utils.GetArrayIndices(script, varName, (newName) => { varName = newName; } ); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Variable element = currentValue; + + // 2b. Special case for an array. + if (arrayIndices.Count > 0) + {// array element + element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + // 3. Take either the length of the underlying tuple or + // string part if it is defined, + // or the numerical part converted to a string otherwise. + int size = element.GetSize(); + + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(size); + return newValue; + } + } + + class DefineLocalFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable currentValue = Utils.GetSafeVariable(args, 1); + + if (currentValue == null) + { + currentValue = new Variable(""); + } + + string scopeName = Path.GetFileName(script.Filename); + ParserFunction.AddLocalScopeVariable(varName, scopeName, + new GetVarFunction(currentValue)); + + return currentValue; + } + } + + class GetPropertiesFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + Variable baseValue = args[0]; + List props = baseValue.GetProperties(); + return new Variable(props); + } + } + + class GetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = baseValue.GetProperty(propName, script); + Utils.CheckNotNull(propValue, propName); + + return new Variable(propValue); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = await baseValue.GetPropertyAsync(propName, script); + Utils.CheckNotNull(propValue, propName); + + return new Variable(propValue); + } + public static Variable GetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = baseValue.GetProperty(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName); + + return new Variable(propValue); + } + public static async Task GetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = await baseValue.GetPropertyAsync(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName); + + return new Variable(propValue); + } + } + + class SetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = baseValue.SetProperty(propName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = await baseValue.SetPropertyAsync(propName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + + public static Variable SetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = baseValue.SetProperty(sPropertyName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + public static async Task SetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = await baseValue.SetPropertyAsync(sPropertyName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + } + + class CancelFunction : ParserFunction + { + public static bool Canceled { get; set; } + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 0, m_name, true); + + bool mode = Utils.GetSafeInt(args, 0, 1) == 1; + Canceled = mode; + + return new Variable(Canceled); + } + } + + public class ScheduleRunFunction : ParserFunction + { + static Dictionary m_timers = + new Dictionary(); + + bool m_startTimer; + + public ScheduleRunFunction(bool startTimer) + { + m_startTimer = startTimer; + } + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + + if (!m_startTimer) + { + Utils.CheckArgs(args.Count, 1, m_name); + string cancelTimerId = Utils.GetSafeString(args, 0); + System.Timers.Timer cancelTimer; + if (m_timers.TryGetValue(cancelTimerId, out cancelTimer)) + { + cancelTimer.Stop(); + cancelTimer.Dispose(); + m_timers.Remove(cancelTimerId); + } + return Variable.EmptyInstance; + } + + Utils.CheckArgs(args.Count, 2, m_name); + int timeout = args[0].AsInt(); + string strAction = args[1].AsString(); + string arg = Utils.GetSafeString(args, 2); + string timerId = Utils.GetSafeString(args, 3); + bool autoReset = Utils.GetSafeInt(args, 4, 0) != 0; + + arg = Utils.ProtectQuotes(arg); + timerId = Utils.ProtectQuotes(timerId); + + System.Timers.Timer pauseTimer = new System.Timers.Timer(timeout); + pauseTimer.Elapsed += (sender, e) => + { + if (!autoReset) + { + pauseTimer.Stop(); + pauseTimer.Dispose(); + m_timers.Remove(timerId); + } + string body = string.Format("{0}({1},{2});", strAction, + "\"" + arg + "\"", "\"" + timerId + "\""); + + ParsingScript tempScript = new ParsingScript(body); + tempScript.ExecuteTo(); + }; + pauseTimer.AutoReset = autoReset; + m_timers[timerId] = pauseTimer; + + pauseTimer.Start(); + + return Variable.EmptyInstance; + } + } + + public class SingletonFunction : ParserFunction + { + static Dictionary m_singletons = + new Dictionary(); + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string expr = args[0].AsString(); + Dictionary char2Line; + expr = Utils.ConvertToScript(expr, out char2Line); + + Variable result; + if (m_singletons.TryGetValue(expr, out result)) + { + return result; + } + + ParsingScript tempScript = new ParsingScript(expr); + result = tempScript.ExecuteTo(); + + m_singletons[expr] = result; + + return result; + } + } + + class GetColumnFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable arrayVar = Utils.GetSafeVariable(args, 0); + int col = Utils.GetSafeInt(args, 1); + int fromCol = Utils.GetSafeInt(args, 2, 0); + + var tuple = arrayVar.Tuple; + + List result = new List(tuple.Count); + for (int i = fromCol; i < tuple.Count; i++) + { + Variable current = tuple[i]; + if (current.Tuple == null || current.Tuple.Count <= col) + { + throw new ArgumentException(m_name + ": Index [" + col + "] doesn't exist in column " + + i + "/" + (tuple.Count - 1)); + } + result.Add(current.Tuple[col]); + } + + return new Variable(result); + } + } + + class GetAllKeysFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varName = Utils.GetItem(script); + Utils.CheckNotNull(varName, m_name); + + List results = varName.GetAllKeys(); + + return new Variable(results); + } + } + + class CheckLoaderMainFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool isMain = !string.IsNullOrWhiteSpace(script.MainFilename) && + script.MainFilename == script.Filename; + + return new Variable(isMain); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `all` last assigned on line 2619 could be null and is dereferenced at line 2626, column 13. + +### Severity: +ERROR + +### Procedure: +Variable TokenCounterFunction.Evaluate(ParsingScript) + +### File: +cscs/Functions.Flow.cs + +### Key: +Functions.Flow.cs|Evaluate|NULL_DEREFERENCE + +### Node Key: +bef2fe14012af516d6c7bc5d1bd471c5 + +### Hash: +b0f56c2b42f5b0422f61218dea743349 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1844/instruction.md b/inferredbugs-1844/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..85a7f355f2592733fc3a7168e8d1bdc07ac79b0d --- /dev/null +++ b/inferredbugs-1844/instruction.md @@ -0,0 +1,2552 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cscs +**Bug ID:** 92 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Threading.Tasks; + +namespace SplitAndMerge +{ + class BreakStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.BREAK); + } + } + + class ContinueStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.CONTINUE); + } + } + + class ReturnStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = Utils.GetItem(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = await Utils.GetItemAsync(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + } + + class TryBlock : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessTry(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessTryAsync(script); + } + } + + class ExitFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Environment.Exit(0); + return Variable.EmptyInstance; + } + } + + class ThrowFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = Utils.GetItem(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = await Utils.GetItemAsync(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + } + + class VarFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string varName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + script.MoveForwardIf('='); + AssignFunction assign = new AssignFunction(); + return assign.Assign(script, varName, true); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + string varName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + script.MoveForwardIf('='); + AssignFunction assign = new AssignFunction(); + return await assign.AssignAsync(script, varName, true); + } + } + + class ShowFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + string functionName = args[0].AsString(); + + CustomFunction custFunc = ParserFunction.GetFunction(functionName, script) as CustomFunction; + Utils.CheckNotNull(functionName, custFunc, script); + +#if __ANDROID__ == false && __IOS__ == false + CustomCompiledFunction comp = custFunc as CustomCompiledFunction; + if (comp != null) + { + return new Variable(comp.Precompiler.CSharpCode); + } +#endif + + string body = Utils.BeautifyScript(custFunc.Body, custFunc.Header); + Utils.PrintScript(body, script); + + return new Variable(body); + } + } + + class FunctionCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string funcName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + funcName = Constants.ConvertName(funcName); + + string[] args = Utils.GetFunctionSignature(script); + if (args.Length == 1 && string.IsNullOrWhiteSpace(args[0])) + { + args = new string[0]; + } + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + /*string line = */script.GetOriginalLine(out _); + + int parentOffset = script.Pointer; + + if (script.CurrentClass != null) + { + parentOffset += script.CurrentClass.ParentOffset; + } + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + CustomFunction customFunc = new CustomFunction(funcName, body, args, script); + customFunc.ParentScript = script; + customFunc.ParentOffset = parentOffset; + + if (script.CurrentClass != null) + { + script.CurrentClass.AddMethod(funcName, args, customFunc); + } + else + { + ParserFunction.RegisterFunction(funcName, customFunc, false /* not native */); + } + + return Variable.EmptyInstance; + } + } + + public class CSCSClass : ParserFunction + { + public CSCSClass() {} + + public CSCSClass(string className) + { + Name = className; + RegisterClass(className, this); + } + + public CSCSClass(string className, string[] baseClasses) + { + Name = className; + RegisterClass(className, this); + + foreach (string baseClass in baseClasses) + { + var bc = CSCSClass.GetClass(baseClass); + if (bc == null) + { + throw new ArgumentException("Base Class [" + baseClass + "] not found."); + } + + foreach (var entry in bc.m_classProperties) + { + m_classProperties[entry.Key] = entry.Value; + } + foreach (var entry in bc.m_customFunctions) + { + m_customFunctions[entry.Key] = entry.Value; + } + } + } + + public static void RegisterClass(string className, CSCSClass obj) + { + obj.Namespace = ParserFunction.GetCurrentNamespace; + if (!string.IsNullOrWhiteSpace(obj.Namespace)) + { + className = obj.Namespace + "." + className; + } + + obj.Name = className; + className = Constants.ConvertName(className); + s_allClasses[className] = obj; + } + + protected override Variable Evaluate(ParsingScript script) + { + script.GetFunctionArgs(); + + // TODO: Work in progress, currently not functional + return Variable.EmptyInstance; + } + + public void AddMethod(string name, string[] args, CustomFunction method) + { + if (name == m_name) + { + m_constructors[args.Length] = method; + for (int i = 0; i < method.DefaultArgsCount && i < args.Length; i++) + { + m_constructors[args.Length - i - 1] = method; + } + } + else + { + m_customFunctions[name] = method; + } + } + + public void AddProperty(string name, Variable property) + { + m_classProperties[name] = property; + } + + public static CSCSClass GetClass(string name) + { + string currNamespace = ParserFunction.GetCurrentNamespace; + if (!string.IsNullOrWhiteSpace(currNamespace)) + { + bool namespacePresent = name.Contains("."); + if (!namespacePresent) + { + name = currNamespace + "." + name; + } + } + + CSCSClass theClass = null; + s_allClasses.TryGetValue(name, out theClass); + return theClass; + } + + static Dictionary s_allClasses = + new Dictionary(); + + Dictionary m_constructors = + new Dictionary(); + Dictionary m_customFunctions = + new Dictionary(); + Dictionary m_classProperties = + new Dictionary(); + + public ParsingScript ParentScript = null; + public int ParentOffset = 0; + + public string Namespace { get; private set; } + + public class ClassInstance : ScriptObject + { + public ClassInstance(string instanceName, string className, List args, + ParsingScript script = null) + { + InstanceName = instanceName; + m_cscsClass = CSCSClass.GetClass(className); + if (m_cscsClass == null) + { + throw new ArgumentException("Class [" + className + "] not found."); + } + + // Copy over all the properties defined for this class. + foreach (var entry in m_cscsClass.m_classProperties) + { + SetProperty(entry.Key, entry.Value); + } + + // Run "constructor" if any is defined for this number of args. + CustomFunction constructor = null; + if (m_cscsClass.m_constructors.TryGetValue(args.Count, out constructor)) + { + constructor.Run(args, script, this); + } + } + + public string InstanceName { get; set; } + CSCSClass m_cscsClass; + + Dictionary m_properties = new Dictionary(); + HashSet m_propSet = new HashSet(); + HashSet m_propSetLower = new HashSet(); + + public override string ToString() + { + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(Constants.PROP_TO_STRING.ToLower(), + out customFunction)) + { + return m_cscsClass.Name + "." + InstanceName; + } + + Variable result = customFunction.Run(null, null, this); + return result.ToString(); + } + + public Task SetProperty(string name, Variable value) + { + m_properties[name] = value; + m_propSet.Add(name); + m_propSetLower.Add(name.ToLower()); + return Task.FromResult( Variable.EmptyInstance ); + } + + public async Task GetProperty(string name, List args = null, ParsingScript script = null) + { + if (m_properties.TryGetValue(name, out Variable value)) + { + return value; + } + + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out CustomFunction customFunction)) + { + return null; + } + if (args == null) + { + return Variable.EmptyInstance; + } + + foreach (var entry in m_cscsClass.m_classProperties) + { + args.Add(entry.Value); + } + + Variable result = await customFunction.RunAsync(args, script, this); + return result; + } + + public List> GetPropList() + { + List> props = new List>(); + foreach (var entry in m_properties) + { + props.Add(new KeyValuePair(entry.Key, entry.Value)); + } + return props; + } + + public List GetProperties() + { + List props = new List(m_properties.Keys); + props.AddRange(m_cscsClass.m_customFunctions.Keys); + + return props; + } + public bool PropertyExists(string name) + { + return m_propSetLower.Contains(name.ToLower()); + } + + public bool FunctionExists(string name) + { + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out CustomFunction customFunction)) + { + return false; + } + return true; + } + } + } + + class NameExistsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string varName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + varName = Constants.ConvertName(varName); + + bool result = ParserFunction.GetVariable(varName, script) != null; + return new Variable(result); + } + } + + class EnumFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List properties = Utils.ExtractTokens(script); + + if (properties.Count == 1 && properties[0].Contains(".")) + { + return UseExistingEnum(properties[0]); + } + + Variable enumVar = new Variable(Variable.VarType.ENUM); + for (int i = 0; i < properties.Count; i++) + { + enumVar.SetEnumProperty(properties[i], new Variable(i)); + } + + return enumVar; + } + + public static Variable UseExistingEnum(string enumName) + { + Type enumType = GetEnumType(enumName); + if (enumType == null || !enumType.IsEnum) + { + return Variable.EmptyInstance; + } + + var names = Enum.GetNames(enumType); + + Variable enumVar = new Variable(Variable.VarType.ENUM); + for (int i = 0; i < names.Length; i++) + { + var numValue = Enum.Parse(enumType, names[i], true); + enumVar.SetEnumProperty(names[i], new Variable((int)numValue)); + } + + return enumVar; + } + + public static Type GetEnumType(string enumName) + { + string[] tokens = enumName.Split('.'); + + Type enumType = null; + int index = 0; + string typeName = ""; + while(enumType == null && index < tokens.Length) + { + if (!string.IsNullOrWhiteSpace(typeName)) + { + typeName += "."; + } + typeName += tokens[index]; + enumType = GetType(typeName); + index++; + } + + for (int i = index; i < tokens.Length && enumType != null; i++) + { + enumType = enumType.GetNestedType(tokens[i]); + } + + if (enumType == null || !enumType.IsEnum) + { + return null; + } + + return enumType; + } + + public static Type GetType(string typeName) + { + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); + foreach (var assembly in assemblies) + { + var type = assembly.GetType(typeName, false, true); + if (type != null) + { + return type; + } + } + return null; + } + } + + class NewObjectFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = script.GetFunctionArgs(); + + CompiledClass csClass = CSCSClass.GetClass(className) as CompiledClass; + if (csClass != null) + { + ScriptObject obj = csClass.GetImplementation(args); + return new Variable(obj); + } + CompiledClassAsync csClassAsync = CSCSClass.GetClass(className) as CompiledClassAsync; + if (csClassAsync != null) + { + ScriptObject obj = csClassAsync.GetImplementationAsync(args).Result; + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = await script.GetFunctionArgsAsync(); + + CompiledClassAsync csClassAsync = CSCSClass.GetClass(className) as CompiledClassAsync; + if (csClassAsync != null) + { + ScriptObject obj = await csClassAsync.GetImplementationAsync(args); + return new Variable(obj); + } + CompiledClass csClass = CSCSClass.GetClass(className) as CompiledClass; + if (csClass != null) + { + ScriptObject obj = csClass.GetImplementation(args); + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + } + + public class ClassCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + string[] baseClasses = Utils.GetBaseClasses(script); + CSCSClass newClass = new CSCSClass(className, baseClasses); + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + + newClass.ParentOffset = script.Pointer; + newClass.ParentScript = script; + /*string line = */script.GetOriginalLine(out _); + + string scriptExpr = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + string body = Utils.ConvertToScript(scriptExpr, out _); + + Variable result = null; + ParsingScript tempScript = script.GetTempScript(body); + tempScript.CurrentClass = newClass; + tempScript.DisableBreakpoints = true; + + // Uncomment if want to step into the class creation code when the debugger is attached (unlikely) + /*Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript); + }*/ + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + + return Variable.EmptyInstance; + } + } + + public class NamespaceFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string namespaceName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + //Utils.CheckNotEnd(script, m_name); + Variable result = null; + + ParserFunction.AddNamespace(namespaceName); + try + { + script.MoveForwardIf(Constants.START_GROUP); + string scriptExpr = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + Dictionary char2Line; + string body = Utils.ConvertToScript(scriptExpr, out char2Line); + + ParsingScript tempScript = script.GetTempScript(body); + tempScript.DisableBreakpoints = true; + tempScript.MoveForwardIf(Constants.START_GROUP); + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + } + finally + { + ParserFunction.PopNamespace(); + } + + return result; + } + } + + public class CustomFunction : ParserFunction + { + internal CustomFunction(string funcName, + string body, string[] args, ParsingScript script) + { + Name = funcName; + m_body = body; + m_args = RealArgs = args; + + for (int i = 0; i < args.Length; i++) + { + string arg = args[i]; + int ind = arg.IndexOf('='); + if (ind > 0) + { + RealArgs[i] = arg.Substring(0, ind).Trim(); + m_args[i] = RealArgs[i].ToLower(); + string defValue = ind >= arg.Length - 1 ? "" : arg.Substring(ind + 1).Trim(); + + Variable defVariable = Utils.GetVariableFromString(defValue, script); + defVariable.CurrentAssign = m_args[i]; + defVariable.Index = i; + + m_defArgMap[i] = m_defaultArgs.Count; + m_defaultArgs.Add(defVariable); + } + else + { + m_args[i] = RealArgs[i].ToLower(); + } + + ArgMap[m_args[i]] = i; + } + } + + public void RegisterArguments(List args, + List> args2 = null) + { + if (args == null) + { + args = new List(); + } + + int missingArgs = m_args.Length - args.Count; + + bool namedParameters = false; + for (int i = 0; i < args.Count; i++) + { + var arg = args[i]; + int argIndex = -1; + if (ArgMap.TryGetValue(arg.CurrentAssign, out argIndex)) + { + namedParameters = true; + if (i != argIndex) + { + args[i] = argIndex < args.Count ? args[argIndex] : args[i]; + while (argIndex > args.Count - 1) + { + args.Add(Variable.EmptyInstance); + } + args[argIndex] = arg; + } + } + else if (namedParameters) + { + throw new ArgumentException("All arguments in function [" + m_name + + "] must be in arg=value form."); + } + } + + if (missingArgs > 0 && missingArgs <= m_defaultArgs.Count) + { + if (!namedParameters) + { + for (int i = m_defaultArgs.Count - missingArgs; i < m_defaultArgs.Count; i++) + { + args.Add(m_defaultArgs[i]); + } + } + else + { + for (int i = 0; i < args.Count; i++) + { + if (args[i].Type == Variable.VarType.NONE || + (!string.IsNullOrWhiteSpace(args[i].CurrentAssign) && + args[i].CurrentAssign != m_args[i])) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args[i] = m_defaultArgs[defIndex]; + } + } + } + } + for (int i = args.Count; i < m_args.Length; i++) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args.Add(m_defaultArgs[defIndex]); + } + m_stackLevel = new StackLevel(m_name); + + if (args2 != null) + { + foreach (var entry in args2) + { + var arg = new GetVarFunction(entry.Value); + arg.Name = entry.Key; + m_stackLevel.Variables[entry.Key] = arg; + } + } + + int maxSize = Math.Min(args.Count, m_args.Length); + for (int i = 0; i < maxSize; i++) + { + var arg = new GetVarFunction(args[i]); + arg.Name = m_args[i]; + m_stackLevel.Variables[m_args[i]] = arg; + } + + if (NamespaceData != null) + { + var vars = NamespaceData.Variables; + string prefix = NamespaceData.Name + "."; + foreach (KeyValuePair elem in vars) + { + string key = elem.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ? + elem.Key.Substring(prefix.Length) : elem.Key; + m_stackLevel.Variables[key] = elem.Value; + } + } + + ParserFunction.AddLocalVariables(m_stackLevel); + } + + protected override Variable Evaluate(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + script.GetFunctionArgs(); + + Utils.ExtractParameterNames(args, m_name, script); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = Run(args, script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + await script.GetFunctionArgsAsync(); + + Utils.ExtractParameterNames(args, m_name, script); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = await RunAsync(args, script); + return result; + } + + public Variable Run(List args = null, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = Utils.GetTempScript(m_body, m_stackLevel, m_name, script, + m_parentScript, m_parentOffset, instance); + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (script != null && debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(m_stackLevel.Id); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + public async Task RunAsync(List args = null, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = Utils.GetTempScript(m_body, m_stackLevel, m_name, script, + m_parentScript, m_parentOffset, instance); + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = await debugger.StepInFunctionIfNeeded(tempScript); + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = await tempScript.ExecuteAsync(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(m_stackLevel.Id); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + + public static Task Run(string functionName, + Variable arg1 = null, Variable arg2 = null, Variable arg3 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + if (arg3 != null) + { + args.Add(arg3); + } + + Variable result = customFunction.Run(args); + return Task.FromResult( result ); + } + + public static async Task RunAsync(string functionName, + Variable arg1 = null, Variable arg2 = null, Variable arg3 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + if (arg3 != null) + { + args.Add(arg3); + } + + Variable result = await customFunction.RunAsync(args); + return result; + } + + public override ParserFunction NewInstance() + { + var newInstance = (CustomFunction)this.MemberwiseClone(); + newInstance.m_stackLevel = null; + return newInstance; + } + + public ParsingScript ParentScript { set { m_parentScript = value; } } + public int ParentOffset { set { m_parentOffset = value; } } + public string Body { get { return m_body; } } + + public int ArgumentCount { get { return m_args.Length; } } + public string Argument(int nIndex) { return m_args[nIndex]; } + + public StackLevel NamespaceData { get; set; } + + public int DefaultArgsCount + { + get + { + return m_defaultArgs.Count; + } + } + + public string Header + { + get + { + return Constants.FUNCTION + " " + Constants.GetRealName(Name) + " " + + Constants.START_ARG + string.Join(", ", m_args) + + Constants.END_ARG + " " + Constants.START_GROUP; + } + } + + protected string m_body; + protected string[] m_args; + protected ParsingScript m_parentScript = null; + protected int m_parentOffset = 0; + protected StackLevel m_stackLevel; + + List m_defaultArgs = new List(); + Dictionary m_defArgMap = new Dictionary(); + + public Dictionary ArgMap { get; private set; } = new Dictionary(); + public string[] RealArgs { get; private set; } + } + + class StringOrNumberFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // First check if the passed expression is a string between quotes. + if (Item.Length > 1 && + ((Item[0] == Constants.QUOTE && Item[Item.Length - 1] == Constants.QUOTE) || + (Item[0] == Constants.QUOTE1 && Item[Item.Length - 1] == Constants.QUOTE1))) + { + return new Variable(Item.Substring(1, Item.Length - 2)); + } + + // Otherwise this should be a number. + double num = Utils.ConvertToDouble(Item, script); + return new Variable(num); + } + + public string Item { private get; set; } + } + + class AddFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue), script); + } + + return currentValue; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue), script); + } + + return currentValue; + } + } + class RemoveFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + string varName = args[0].AsString(); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func, script); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = args[1]; + + bool removed = currentValue.Tuple.Remove(item); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue), script); + return new Variable(removed); + } + } + class RemoveAtFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func, script); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = Utils.GetItem(script); + Utils.CheckNonNegativeInt(item, script); + + currentValue.Tuple.RemoveAt(item.AsInt()); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue), script); + return Variable.EmptyInstance; + } + } + + class ContainsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + List arrayIndices = Utils.GetArrayIndices(script, varName, (newVarName) => { varName = newVarName; } ); + + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func, script); + Variable currentValue = func.GetValue(script); + + // 2b. Special dealings with arrays: + Variable query = arrayIndices.Count > 0 ? + Utils.ExtractArrayElement(currentValue, arrayIndices, script) : + currentValue; + + // 3. Get the value to be looked for. + Variable searchValue = Utils.GetItem(script); + Utils.CheckNotEnd(script, m_name); + + // 4. Check if the value to search for exists. + bool exists = query.Exists(searchValue, true /* notEmpty */); + + script.MoveBackIf(Constants.START_GROUP); + return new Variable(exists); + } + } + + class FindIndexFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable var = Utils.GetSafeVariable(args, 0); + string val = Utils.GetSafeString(args, 1); + + int index = var.FindIndex(val); + + return new Variable(index); + } + } + + class BoolFunction : ParserFunction, INumericFunction + { + bool m_value; + public BoolFunction(bool init) + { + m_value = init; + } + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(m_value); + } + } + class ToDoubleFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToDouble(arg.AsString()); + return new Variable(result); + } + } + class ToIntFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + int result = Utils.ConvertToInt(arg.AsString()); + return new Variable(result); + } + } + class ToBoolFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToBool(arg.AsString()) ? 1 : 0; + return new Variable(result); + } + } + class ToDecimalFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = Decimal.Parse(arg.AsString(), NumberStyles.Any).ToString(); + return new Variable(result); + } + } + class ToStringFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + Variable arg = args[0]; + string format = Utils.GetSafeString(args, 1); + + string result = arg.AsString(format); + return new Variable(result); + } + } + class IdentityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return script.Execute(Constants.END_ARG_ARRAY); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await script.ExecuteAsync(Constants.END_ARG_ARRAY); + } + } + + class ConstantsFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(m_name); + } + } + + class IfStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable result = Interpreter.Instance.ProcessIf(script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + Variable result = await Interpreter.Instance.ProcessIfAsync(script); + return result; + } + } + + class ForStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessFor(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessForAsync(script); + } + } + + class WhileStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessWhile(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessWhileAsync(script); + } + } + + class IncludeFile : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + string filename = args[0].AsString(); + return Execute(filename, script); + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 1, m_name, true); + string filename = args[0].AsString(); + return await ExecuteAsync(filename, script); + } + + public static Variable Execute(string filename, ParsingScript parentScript = null) + { + if (parentScript == null) + { + parentScript = new ParsingScript(""); + } + ParsingScript tempScript = parentScript.GetIncludeFileScript(filename); + + Variable result = null; + if (parentScript.Debugger != null) + { + result = parentScript.Debugger.StepInIncludeIfNeeded(tempScript).Result; + } + + while (tempScript.StillValid()) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + + public static async Task ExecuteAsync(string filename, ParsingScript parentScript = null) + { + if (parentScript == null) + { + parentScript = new ParsingScript(""); + } + ParsingScript tempScript = parentScript.GetIncludeFileScript(filename); + + Variable result = null; + if (parentScript.Debugger != null) + { + result = await parentScript.Debugger.StepInIncludeIfNeeded(tempScript); + } + + while (tempScript.StillValid()) + { + result = await tempScript.ExecuteAsync(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + } + + // Get a value of a variable or of an array element + public class GetVarFunction : ParserFunction + { + public GetVarFunction(Variable value) + { + m_value = value; + } + + protected override Variable Evaluate(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = Utils.GetArrayIndices(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; } ); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices, script); + if (script.Prev == '.') + { + script.Backward(); + } + + if (script.TryCurrent() != '.') + { + return result; + } + script.Forward(); + + m_propName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + Variable propValue = result.GetProperty(m_propName, script); + Utils.CheckNotNull(propValue, m_propName, script); + return propValue; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + string temp = m_propName; + m_propName = null; // Need this to reset for recursive calls + Variable propValue = m_value.Type == Variable.VarType.ENUM ? + m_value.GetEnumProperty(temp, script) : + m_value.GetProperty(temp, script); + Utils.CheckNotNull(propValue, temp, script); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = await Utils.GetArrayIndicesAsync(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; }); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices, script); + if (script.Prev == '.') + { + script.Backward(); + } + if (script.TryCurrent() != '.') + { + return result; + } + + script.Forward(); + m_propName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Variable propValue = await result.GetPropertyAsync(m_propName, script); + Utils.CheckNotNull(propValue, m_propName, script); + return propValue; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + string temp = m_propName; + m_propName = null; // Need this to reset for recursive calls + + Variable propValue = m_value.Type == Variable.VarType.ENUM ? + m_value.GetEnumProperty(temp, script) : + await m_value.GetPropertyAsync(temp, script); + Utils.CheckNotNull(propValue, temp, script); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + + public int Delta + { + set { m_delta = value; } + } + public Variable Value + { + get { return m_value; } + } + public List Indices + { + set { m_arrayIndices = value; } + } + public string PropertyName + { + set { m_propName = value; } + } + + Variable m_value; + int m_delta = 0; + List m_arrayIndices = null; + string m_propName; + } + class IncrementDecrementFunction : ActionFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool prefix = string.IsNullOrWhiteSpace(m_name); + if (prefix) + {// If it is a prefix we do not have the variable name yet. + Name = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + } + + Utils.CheckForValidName(Name, script); + + // Value to be added to the variable: + int valueDelta = m_action == Constants.INCREMENT ? 1 : -1; + int returnDelta = prefix ? valueDelta : 0; + + // Check if the variable to be set has the form of x[a][b], + // meaning that this is an array element. + double newValue = 0; + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetVariable(m_name, script); + Utils.CheckNotNull(m_name, func, script); + + Variable currentValue = func.GetValue(script); + currentValue = currentValue.DeepClone(); + + if (arrayIndices.Count > 0 || script.TryCurrent() == Constants.START_ARRAY) + { + if (prefix) + { + string tmpName = m_name + script.Rest; + int delta = 0; + arrayIndices = Utils.GetArrayIndices(script, tmpName, delta, (string t, int d) => { tmpName = t; delta = d; }); + script.Forward(Math.Max(0, delta - tmpName.Length)); + } + + Variable element = Utils.ExtractArrayElement(currentValue, arrayIndices, script); + script.MoveForwardIf(Constants.END_ARRAY); + + newValue = element.Value + returnDelta; + element.Value += valueDelta; + } + else + { // A normal variable. + newValue = currentValue.Value + returnDelta; + currentValue.Value += valueDelta; + } + + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue), script); + return new Variable(newValue); + } + + override public ParserFunction NewInstance() + { + return new IncrementDecrementFunction(); + } + } + + class OperatorAssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // Value to be added to the variable: + Variable right = Utils.GetItem(script); + + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetVariable(m_name, script); + Utils.CheckNotNull(func, m_name, script); + + Variable currentValue = func.GetValue(script); + currentValue = currentValue.DeepClone(); + Variable left = currentValue; + + if (arrayIndices.Count > 0) + {// array element + left = Utils.ExtractArrayElement(currentValue, arrayIndices, script); + script.MoveForwardIf(Constants.END_ARRAY); + } + + if (left.Type == Variable.VarType.NUMBER) + { + NumberOperator(left, right, m_action); + } + else + { + StringOperator(left, right, m_action); + } + + if (arrayIndices.Count > 0) + {// array element + AssignFunction.ExtendArray(currentValue, arrayIndices, 0, left); + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue), script); + } + else + { + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(left), script); + } + return left; + } + + static void NumberOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + valueA.Value += valueB.Value; + break; + case "-=": + valueA.Value -= valueB.Value; + break; + case "*=": + valueA.Value *= valueB.Value; + break; + case "/=": + valueA.Value /= valueB.Value; + break; + case "%=": + valueA.Value %= valueB.Value; + break; + case "&=": + valueA.Value = (int)valueA.Value & (int)valueB.Value; + break; + case "|=": + valueA.Value = (int)valueA.Value | (int)valueB.Value; + break; + case "^=": + valueA.Value = (int)valueA.Value ^ (int)valueB.Value; + break; + } + } + static void StringOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + if (valueB.Type == Variable.VarType.STRING) + { + valueA.String += valueB.AsString(); + } + else + { + valueA.String += valueB.Value; + } + break; + } + } + + override public ParserFunction NewInstance() + { + return new OperatorAssignFunction(); + } + } + + class AssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Assign(script, m_name); + } + + public Variable Assign(ParsingScript script, string varName, bool localIfPossible = false) + { + m_name = Constants.GetRealName(varName); + script.CurrentAssign = m_name; + Variable varValue = Utils.GetItem(script); + + script.MoveBackIfPrevious(Constants.END_ARG); + varValue.TrySetAsMap(); + + if (script.Current == ' ' || script.Prev == ' ') + { + Utils.ThrowErrorMsg("Can't process expression [" + script.Rest + "].", + script, m_name); + } + + // First try processing as an object (with a dot notation): + Variable result = ProcessObject(script, varValue); + if (result != null) + { + if (script.CurrentClass == null && script.ClassInstance == null) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(result), script, localIfPossible); + } + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue), script, localIfPossible); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + } + + Variable array; + + ParserFunction pf = ParserFunction.GetVariable(m_name, script); + array = pf != null ? (pf.GetValue(script)) : new Variable(); + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array), script, localIfPossible); + return array; + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + return await AssignAsync(script, m_name); + } + + public async Task AssignAsync(ParsingScript script, string varName, bool localIfPossible = false) + { + m_name = Constants.GetRealName(varName); + script.CurrentAssign = m_name; + Variable varValue = await Utils.GetItemAsync(script); + + script.MoveBackIfPrevious(Constants.END_ARG); + varValue.TrySetAsMap(); + + if (script.Current == ' ' || script.Prev == ' ') + { + Utils.ThrowErrorMsg("Can't process expression [" + script.Rest + "].", + script, m_name); + } + + // First try processing as an object (with a dot notation): + Variable result = await ProcessObjectAsync(script, varValue); + if (result != null) + { + if (script.CurrentClass == null) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(result), script, localIfPossible); + } + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = await Utils.GetArrayIndicesAsync(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue), script, localIfPossible); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + } + + Variable array; + + ParserFunction pf = ParserFunction.GetVariable(m_name, script); + array = pf != null ? (await pf.GetValueAsync(script)) : new Variable(); + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array), script, localIfPossible); + return array; + } + + Variable ProcessObject(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + varValue = script.ClassInstance.SetProperty(m_name, varValue).Result; + return varValue.DeepClone(); + } + + int ind = varName.IndexOf('.'); + if (ind <= 0) + { + return null; + } + + Utils.CheckForValidName(varName, script); + + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + if (ParserFunction.TryAddToNamespace(prop, name, varValue)) + { + return varValue.DeepClone(); + } + + ParserFunction existing = ParserFunction.GetVariable(name, script); + Variable baseValue = existing != null ? existing.GetValue(script) : new Variable(Variable.VarType.ARRAY); + baseValue.SetProperty(prop, varValue, script, name); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue), script); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + async Task ProcessObjectAsync(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + await script.ClassInstance.SetProperty(m_name, varValue); + return varValue.DeepClone(); + } + + int ind = varName.IndexOf('.'); + if (ind <= 0) + { + return null; + } + + Utils.CheckForValidName(varName, script); + + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + if (ParserFunction.TryAddToNamespace(prop, name, varValue)) + { + return varValue.DeepClone(); + } + + ParserFunction existing = ParserFunction.GetVariable(name, script); + Variable baseValue = existing != null ? await existing.GetValueAsync(script) : new Variable(Variable.VarType.ARRAY); + await baseValue.SetPropertyAsync(prop, varValue, script, name); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue), script); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + + + override public ParserFunction NewInstance() + { + return new AssignFunction(); + } + + public static void ExtendArray(Variable parent, + List arrayIndices, + int indexPtr, + Variable varValue) + { + if (arrayIndices.Count <= indexPtr) + { + return; + } + + Variable index = arrayIndices[indexPtr]; + int currIndex = ExtendArrayHelper(parent, index); + + if (arrayIndices.Count - 1 == indexPtr) + { + parent.Tuple[currIndex] = varValue; + return; + } + + Variable son = parent.Tuple[currIndex]; + ExtendArray(son, arrayIndices, indexPtr + 1, varValue); + } + + private static int ExtendArrayHelper(Variable parent, Variable indexVar) + { + parent.SetAsArray(); + + int arrayIndex = parent.GetArrayIndex(indexVar); + if (arrayIndex < 0) + { + // This is not a "normal index" but a new string for the dictionary. + string hash = indexVar.AsString(); + arrayIndex = parent.SetHashVariable(hash, Variable.NewEmpty()); + return arrayIndex; + } + + if (parent.Tuple.Count <= arrayIndex) + { + for (int i = parent.Tuple.Count; i <= arrayIndex; i++) + { + parent.Tuple.Add(Variable.NewEmpty()); + } + } + return arrayIndex; + } + } + + class DeepCopyFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varValue = Utils.GetItem(script); + return varValue.DeepClone(); + } + } + + class TokenizeLinesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2, 0); + string sepStr = Utils.GetSafeString(args, 3, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + // var function = ParserFunction.GetVariable(varName, script); + Variable allTokensVar = new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; +#pragma warning disable 219 + // bugbug - the toAdd has side effects + Variable toAdd = new Variable(counter - fromLine); +#pragma warning restore 219 + string line = lineVar.AsString(); + var tokens = line.Split(sep); + Variable tokensVar = new Variable(Variable.VarType.ARRAY); + foreach (string token in tokens) + { + tokensVar.Tuple.Add(new Variable(token)); + } + allTokensVar.Tuple.Add(tokensVar); + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(allTokensVar), script); + + return Variable.EmptyInstance; + } + } + + class AddVariablesToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2); + string hash2 = Utils.GetSafeString(args, 3); + string sepStr = Utils.GetSafeString(args, 4, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + var function = ParserFunction.GetVariable(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; + Variable toAdd = new Variable(counter - fromLine); + string line = lineVar.AsString(); + var tokens = line.Split(sep); + string hash = tokens[0]; + mapVar.AddVariableToHash(hash, toAdd); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar), script); + return Variable.EmptyInstance; + } + } + class AddVariableToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable toAdd = Utils.GetSafeVariable(args, 1); + string hash = Utils.GetSafeString(args, 2); + + var function = ParserFunction.GetVariable(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + mapVar.AddVariableToHash(hash, toAdd); + for (int i = 3; i < args.Count; i++) + { + string hash2 = Utils.GetSafeString(args, 3); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar), script); + + return Variable.EmptyInstance; + } + } + class TokenCounterFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable all = Utils.GetSafeVariable(args, 0); + string varName = Utils.GetSafeString(args, 1); + int index = Utils.GetSafeInt(args, 2); + + // var function = ParserFunction.GetVariable(varName, script); + Variable mapVar = new Variable(Variable.VarType.ARRAY); + + if (all.Tuple == null) + { + return Variable.EmptyInstance; + } + + string currentValue = ""; + int currentCount = 0; + + int globalCount = 0; + + for (int i = 0; i < all.Tuple.Count; i++) + { + Variable current = all.Tuple[i]; + if (current.Tuple == null || current.Tuple.Count < index) + { + break; + } + string newValue = current.Tuple[index].AsString(); + if (currentValue != newValue) + { + currentValue = newValue; + currentCount = 0; + } + mapVar.Tuple.Add(new Variable(currentCount)); + currentCount++; + globalCount++; + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar), script); + // Script - Need to enable the warnings +#pragma warning restore 219 + return mapVar; + } + } + + class TypeFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + bool complexVariable = Utils.GetSafeInt(args, 1, 0) == 1; + Variable element = null; + if (complexVariable) + { + element = Utils.GetVariable(args[0].AsString(), script, false); + } + if (element == null) + { + element = Utils.GetSafeVariable(args, 0); + } + + string type = element.GetTypeString(); + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(type); + return newValue; + } + } + + class SizeFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.END_ARG_ARRAY); + Utils.CheckNotEnd(script, m_name); + + List arrayIndices = Utils.GetArrayIndices(script, varName, (newName) => { varName = newName; } ); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func, script); + Variable currentValue = func.GetValue(script); + Variable element = currentValue; + + // 2b. Special case for an array. + if (arrayIndices.Count > 0) + {// array element + element = Utils.ExtractArrayElement(currentValue, arrayIndices, script); + script.MoveForwardIf(Constants.END_ARRAY); + } + + // 3. Take either the length of the underlying tuple or + // string part if it is defined, + // or the numerical part converted to a string otherwise. + int size = element.GetSize(); + + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(size); + return newValue; + } + } + + class DefineLocalFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable currentValue = Utils.GetSafeVariable(args, 1); + + if (currentValue == null) + { + currentValue = new Variable(""); + } + + if (script.StackLevel != null) + { + ParserFunction.AddLocalVariable(new GetVarFunction(currentValue), varName); + } + else if (script.CurrentClass != null) + { + Utils.ThrowErrorMsg(m_name + " function can't be defined inside of a class.", + script, m_name); + } + else + { + string scopeName = Path.GetFileName(script.Filename); + ParserFunction.AddLocalScopeVariable(varName, scopeName, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + } + + class GetPropertiesFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + Variable baseValue = args[0]; + List props = baseValue.GetProperties(); + return new Variable(props); + } + } + + class GetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = baseValue.GetProperty(propName, script); + Utils.CheckNotNull(propValue, propName, script); + + return new Variable(propValue); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = await baseValue.GetPropertyAsync(propName, script); + Utils.CheckNotNull(propValue, propName, script); + + return new Variable(propValue); + } + public static Variable GetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = baseValue.GetProperty(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName, script); + + return new Variable(propValue); + } + public static async Task GetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = await baseValue.GetPropertyAsync(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName, script); + + return new Variable(propValue); + } + } + + class SetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = baseValue.SetProperty(propName, propValue, script); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue), script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = await baseValue.SetPropertyAsync(propName, propValue, script); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue), script); + return result; + } + + public static Variable SetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = baseValue.SetProperty(sPropertyName, propValue, script); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue), script); + return result; + } + public static async Task SetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = await baseValue.SetPropertyAsync(sPropertyName, propValue, script); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue), script); + return result; + } + } + + class CancelFunction : ParserFunction + { + public static bool Canceled { get; set; } + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 0, m_name, true); + + bool mode = Utils.GetSafeInt(args, 0, 1) == 1; + Canceled = mode; + + return new Variable(Canceled); + } + } + + public class ScheduleRunFunction : ParserFunction + { + static Dictionary m_timers = + new Dictionary(); + + bool m_startTimer; + + public ScheduleRunFunction(bool startTimer) + { + m_startTimer = startTimer; + } + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + + if (!m_startTimer) + { + Utils.CheckArgs(args.Count, 1, m_name); + string cancelTimerId = Utils.GetSafeString(args, 0); + System.Timers.Timer cancelTimer; + if (m_timers.TryGetValue(cancelTimerId, out cancelTimer)) + { + cancelTimer.Stop(); + cancelTimer.Dispose(); + m_timers.Remove(cancelTimerId); + } + return Variable.EmptyInstance; + } + + Utils.CheckArgs(args.Count, 2, m_name); + int timeout = args[0].AsInt(); + string strAction = args[1].AsString(); + string arg = Utils.GetSafeString(args, 2); + string timerId = Utils.GetSafeString(args, 3); + bool autoReset = Utils.GetSafeInt(args, 4, 0) != 0; + + arg = Utils.ProtectQuotes(arg); + timerId = Utils.ProtectQuotes(timerId); + + System.Timers.Timer pauseTimer = new System.Timers.Timer(timeout); + pauseTimer.Elapsed += (sender, e) => + { + if (!autoReset) + { + pauseTimer.Stop(); + pauseTimer.Dispose(); + m_timers.Remove(timerId); + } + string body = string.Format("{0}({1},{2});", strAction, + "\"" + arg + "\"", "\"" + timerId + "\""); + + ParsingScript tempScript = new ParsingScript(body); + tempScript.Execute(); + }; + pauseTimer.AutoReset = autoReset; + m_timers[timerId] = pauseTimer; + + pauseTimer.Start(); + + return Variable.EmptyInstance; + } + } + + public class SingletonFunction : ParserFunction + { + static Dictionary m_singletons = + new Dictionary(); + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string expr = args[0].AsString(); + Dictionary char2Line; + expr = Utils.ConvertToScript(expr, out char2Line); + + Variable result; + if (m_singletons.TryGetValue(expr, out result)) + { + return result; + } + + ParsingScript tempScript = new ParsingScript(expr); + result = tempScript.Execute(); + + m_singletons[expr] = result; + + return result; + } + } + + class GetColumnFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable arrayVar = Utils.GetSafeVariable(args, 0); + int col = Utils.GetSafeInt(args, 1); + int fromCol = Utils.GetSafeInt(args, 2, 0); + + var tuple = arrayVar.Tuple; + + List result = new List(tuple.Count); + for (int i = fromCol; i < tuple.Count; i++) + { + Variable current = tuple[i]; + if (current.Tuple == null || current.Tuple.Count <= col) + { + throw new ArgumentException(m_name + ": Index [" + col + "] doesn't exist in column " + + i + "/" + (tuple.Count - 1)); + } + result.Add(current.Tuple[col]); + } + + return new Variable(result); + } + } + + class GetAllKeysFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varName = Utils.GetItem(script); + Utils.CheckNotNull(varName, m_name, script); + + List results = varName.GetAllKeys(); + + return new Variable(results); + } + } + + class CheckLoaderMainFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool isMain = !string.IsNullOrWhiteSpace(script.MainFilename) && + script.MainFilename == script.Filename; + + return new Variable(isMain); + } + } + + class ResetVariablesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + ParserFunction.CleanUpVariables(); + return Variable.EmptyInstance; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `all` last assigned on line 2619 could be null and is dereferenced at line 2626, column 13. + +### Severity: +ERROR + +### Procedure: +Variable TokenCounterFunction.Evaluate(ParsingScript) + +### File: +cscs/Functions.Flow.cs + +### Key: +Functions.Flow.cs|Evaluate|NULL_DEREFERENCE + +### Node Key: +bef2fe14012af516d6c7bc5d1bd471c5 + +### Hash: +b0f56c2b42f5b0422f61218dea743349 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1845/instruction.md b/inferredbugs-1845/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4756f6dd43be5361922739a9be2fd367ff3e0df5 --- /dev/null +++ b/inferredbugs-1845/instruction.md @@ -0,0 +1,807 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cscs +**Bug ID:** 66 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading.Tasks; + +namespace SplitAndMerge +{ + public class ParserFunction + { + public ParserFunction() + { + m_impl = this; + } + + // A "virtual" Constructor + internal ParserFunction(ParsingScript script, string item, char ch, ref string action) + { + if (item.Length == 0 && (ch == Constants.START_ARG || !script.StillValid())) + { + // There is no function, just an expression in parentheses + m_impl = s_idFunction; + return; + } + if (item.Length > 1 && + ((item[0] == Constants.QUOTE && item[item.Length - 1] == Constants.QUOTE) || + (item[0] == Constants.QUOTE1 && item[item.Length - 1] == Constants.QUOTE1))) + { + // We are dealing with a string. + s_strOrNumFunction.Item = item; + m_impl = s_strOrNumFunction; + return; + } + + item = Constants.ConvertName(item); + + m_impl = GetRegisteredAction(item, ref action); + if (m_impl != null) + { + return; + } + + m_impl = GetArrayFunction(item, script, action); + if (m_impl != null) + { + return; + } + + m_impl = GetObjectFunction(item, script); + if (m_impl != null) + { + return; + } + + m_impl = GetFunction(item, script); + if (m_impl != null) + { + return; + } + + if (m_impl == s_strOrNumFunction && string.IsNullOrWhiteSpace(item)) + { + string problem = (!string.IsNullOrWhiteSpace(action) ? action : ch.ToString()); + string restData = ch.ToString() + script.Rest; + throw new ArgumentException("Couldn't parse [" + problem + "] in " + restData + "..."); + } + + // Function not found, will try to parse this as a string in quotes or a number. + s_strOrNumFunction.Item = item; + m_impl = s_strOrNumFunction; + } + + static ParserFunction GetArrayFunction(string name, ParsingScript script, string action) + { + int arrayStart = name.IndexOf(Constants.START_ARRAY); + if (arrayStart < 0) + { + return null; + } + + string arrayName = name; + + int delta = 0; + List arrayIndices = Utils.GetArrayIndices(script, arrayName, delta, (string arr, int del) => { arrayName = arr; delta = del; }); + + if (arrayIndices.Count == 0) + { + return null; + } + + ParserFunction pf = ParserFunction.GetFunction(arrayName, script); + GetVarFunction varFunc = pf as GetVarFunction; + if (varFunc == null) + { + return null; + } + + // we temporarily backtrack for the processing + script.Backward(name.Length - arrayStart - 1); + script.Backward(action != null ? action.Length : 0); + // delta shows us how manxy chars we need to advance forward in GetVarFunction() + delta -= arrayName.Length; + delta += action != null ? action.Length : 0; + + varFunc.Indices = arrayIndices; + varFunc.Delta = delta; + return varFunc; + } + + static ParserFunction GetObjectFunction(string name, ParsingScript script) + { + if (script.CurrentClass != null && script.CurrentClass.Name == name) + { + script.Backward(name.Length + 1); + return new FunctionCreator(); + } + if (script.ClassInstance != null && + (script.ClassInstance.PropertyExists(name) || script.ClassInstance.FunctionExists(name))) + { + name = script.ClassInstance.InstanceName + "." + name; + } + int ind = name.IndexOf("."); + if (ind <= 0) + { + return null; + } + string baseName = name.Substring(0, ind); + string prop = name.Substring(ind + 1); + + ParserFunction pf = ParserFunction.GetFunctionNamespace(prop, baseName, script); + if (pf != null) + { + return pf; + } + + pf = ParserFunction.GetFunction(baseName, script); + GetVarFunction varFunc = pf as GetVarFunction; + if (varFunc == null) + { + return null; + } + + varFunc.PropertyName = prop; + return varFunc; + } + + static ParserFunction GetRegisteredAction(string name, ref string action) + { + ActionFunction actionFunction = GetAction(action); + + // If passed action exists and is registered we are done. + if (actionFunction == null) + { + return null; + } + + ActionFunction theAction = actionFunction.NewInstance() as ActionFunction; + theAction.Name = name; + theAction.Action = action; + + action = null; + return theAction; + } + + public static bool TryAddToNamespace(string name, string nameSpace, Variable varValue) + { + StackLevel level; + if (string.IsNullOrWhiteSpace(nameSpace) || + !s_namespaces.TryGetValue(nameSpace, out level)) + { + return false; + } + + var vars = level.Variables; + vars[name] = new GetVarFunction(varValue); + + return true; + } + + public static ParserFunction GetFunctionNamespace(string name, ParsingScript script) + { + ParserFunction result = GetFunctionNamespace(name, s_namespace, script); + return result; + } + + public static ParserFunction GetFunctionNamespace(string name, string nameSpace, ParsingScript script) + { + if (string.IsNullOrWhiteSpace(nameSpace)) + { + return null; + } + + StackLevel level; + if (!s_namespaces.TryGetValue(nameSpace, out level)) + { + return null; + } + + var vars = level.Variables; + ParserFunction impl; + if (vars.TryGetValue(name, out impl)) + { + return impl; + } + + if (!name.StartsWith(nameSpace, StringComparison.OrdinalIgnoreCase)) + { + name = nameSpace + "." + name; + if (vars.TryGetValue(name, out impl)) + { + return impl; + } + if (s_functions.TryGetValue(name, out impl)) + { + return impl; + } + } + + return null; + } + + public static ParserFunction GetFunction(string name, ParsingScript script) + { + name = Constants.ConvertName(name); + ParserFunction impl; + // First search among local variables. + if (s_locals.Count > StackLevelDelta) + { + Dictionary local = s_locals.Peek().Variables; + if (local.TryGetValue(name, out impl)) + { + // Local function exists (a local variable) + return impl; + } + } + + string scopeName = script == null || script.Filename == null ? "" : script.Filename; + impl = GetLocalScopeVariable(name, scopeName); + if (impl != null) + { + // Local scope variable exists + return impl; + } + + if (s_functions.TryGetValue(name, out impl)) + { + // Global function exists and is registered (e.g. pi, exp, or a variable) + return impl.NewInstance(); + } + + return GetFunctionNamespace(name, script); + } + + public static void UpdateFunction(Variable variable) + { + UpdateFunction(variable.ParsingToken, new GetVarFunction(variable)); + } + public static void UpdateFunction(string name, ParserFunction function) + { + name = Constants.ConvertName(name); + // First search among local variables. + if (s_locals.Count > StackLevelDelta) + { + Dictionary local = s_locals.Peek().Variables; + + if (local.ContainsKey(name)) + { + // Local function exists (a local variable) + local[name] = function; + return; + } + } + // If it's not a local variable, update global. + s_functions[name] = function; + } + public static ActionFunction GetAction(string action) + { + if (string.IsNullOrWhiteSpace(action)) + { + return null; + } + + ActionFunction impl; + if (s_actions.TryGetValue(action, out impl)) + { + // Action exists and is registered (e.g. =, +=, --, etc.) + return impl; + } + + return null; + } + + public static bool FunctionExists(string item) + { + // If it is not defined locally, then check globally: + return LocalNameExists(item) || GlobalNameExists(item); + } + + public static void AddGlobalOrLocalVariable(string name, GetVarFunction function) + { + name = Constants.ConvertName(name); + + Dictionary lastLevel = GetLastLevel(); + if (lastLevel != null && s_locals.Peek().IsNamespace && !string.IsNullOrWhiteSpace(s_namespace)) + { + name = s_namespacePrefix + name; + } + + function.Name = Constants.GetRealName(name); + if (LocalNameExists(name) || !GlobalNameExists(name)) + { + AddLocalVariable(function); + } + else + { + AddGlobal(name, function, false /* not native */); + } + } + + static string CreateVariableEntry(ParserFunction variable, bool isLocal = false) + { + if (!(variable is GetVarFunction) || string.IsNullOrWhiteSpace(variable.Name)) + { + return null; + } + GetVarFunction gvf = variable as GetVarFunction; + return CreateVariableEntry(gvf.Value, variable.Name, isLocal); + } + + static string CreateVariableEntry(Variable var, string name, bool isLocal = false) + { + try + { + string value = var.AsString(true, true, 16); + string localGlobal = isLocal ? "0" : "1"; + string varData = name + ":" + localGlobal + ":" + + Constants.TypeToString(var.Type).ToLower() + ":" + value; + return varData.Trim(); + } + catch(Exception exc) + { + // TODO: Clean up not used objects. + bool removed = isLocal ? PopLocalVariable(name) : RemoveGlobal(name); + Console.WriteLine("Object {0} is probably dead ({1}): {2}. Removing it.", name, removed, exc); + return null; + } + } + + static void GetVariables(Dictionary variablesScope, + StringBuilder sb, bool isLocal = false) + { + var all = variablesScope.Values.ToList(); + for (int i = 0; i < all.Count; i++) + { + var variable = all[i]; + string varData = CreateVariableEntry(variable, isLocal); + if (!string.IsNullOrWhiteSpace(varData)) + { + sb.AppendLine(varData); + GetVarFunction gvf = variable as GetVarFunction; + if (gvf != null && gvf.Value.Type == Variable.VarType.OBJECT) + { + var props = gvf.Value.GetProperties(); + foreach (Variable var in props) + { + var val = gvf.Value.GetProperty(var.AsString()); + varData = CreateVariableEntry(val, variable.Name + "." + var.AsString(), isLocal); + if (!string.IsNullOrWhiteSpace(varData)) + { + sb.AppendLine(varData); + } + } + } + } + } + } + + public static string GetVariables(ParsingScript script) + { + StringBuilder sb = new StringBuilder(); + // Locals, if any: + if (s_locals.Count > 0) + { + Dictionary locals = s_locals.Peek().Variables; + GetVariables(locals, sb, true); + } + + // Variables in the local file scope: + if (script != null && script.Filename != null) + { + Dictionary localScope; + string scopeName = Path.GetFileName(script.Filename); + if (s_localScope.TryGetValue(scopeName, out localScope)) + { + GetVariables(localScope, sb, true); + } + } + + // Globals: + GetVariables(s_functions, sb, false); + + return sb.ToString().Trim(); + } + + static Dictionary GetLastLevel() + { + if (s_locals.Count <= StackLevelDelta) + { + return null; + } + var result = s_locals.Peek().Variables; + return result; + } + + static bool LocalNameExists(string name) + { + Dictionary lastLevel = GetLastLevel(); + if (lastLevel == null) + { + return false; + } + name = Constants.ConvertName(name); + return lastLevel.ContainsKey(name); + } + + static bool GlobalNameExists(string name) + { + name = Constants.ConvertName(name); + return s_functions.ContainsKey(name); + } + + public static Variable RegisterEnum(string varName, string enumName) + { + Variable enumVar = EnumFunction.UseExistingEnum(enumName); + if (enumVar == Variable.EmptyInstance) + { + return enumVar; + } + + AddGlobalOrLocalVariable(varName, new GetVarFunction(enumVar)); + return enumVar; + } + + public static void RegisterFunction(string name, ParserFunction function, + bool isNative = true) + { + if (!string.IsNullOrWhiteSpace(s_namespace)) + { + StackLevel level; + if (s_namespaces.TryGetValue(s_namespace, out level) && + function is CustomFunction) + { + ((CustomFunction)function).NamespaceData = level; + name = s_namespacePrefix + name; + } + } + + AddGlobal(name, function, isNative); + } + + public static bool RemoveGlobal(string name) + { + name = Constants.ConvertName(name); + return s_functions.Remove(name); + } + + static void NormalizeValue(ParserFunction function) + { + GetVarFunction gvf = function as GetVarFunction; + if (gvf != null) + { + gvf.Value.CurrentAssign = ""; + } + } + + public static void AddGlobal(string name, ParserFunction function, + bool isNative = true) + { + name = Constants.ConvertName(name); + NormalizeValue(function); + function.isNative = isNative; + s_functions[name] = function; + + function.Name = Constants.GetRealName(name); +#if UNITY_EDITOR == false && UNITY_STANDALONE == false && __ANDROID__ == false && __IOS__ == false + if (!isNative) + { + Translation.AddTempKeyword(name); + } +#endif + } + + public static void AddLocalScopeVariable(string name, string scopeName, ParserFunction variable) + { + name = Constants.ConvertName(name); + variable.isNative = false; + variable.Name = Constants.GetRealName(name); + + if (scopeName == null) + { + scopeName = ""; + } + + Dictionary localScope; + if (!s_localScope.TryGetValue(scopeName, out localScope)) + { + localScope = new Dictionary(); + } + localScope[name] = variable; + s_localScope[scopeName] = localScope; + } + + static ParserFunction GetLocalScopeVariable(string name, string scopeName) + { + scopeName = Path.GetFileName(scopeName); + Dictionary localScope; + if (!s_localScope.TryGetValue(scopeName, out localScope)) + { + return null; + } + + name = Constants.ConvertName(name); + ParserFunction function = null; + localScope.TryGetValue(name, out function); + return function; + } + + public static void AddAction(string name, ActionFunction action) + { + s_actions[name] = action; + } + + public static void AddLocalVariables(StackLevel locals) + { + s_locals.Push(locals); + } + + public static void AddNamespace(string namespaceName) + { + if (!string.IsNullOrWhiteSpace(s_namespace)) + { + throw new ArgumentException("Already inside of namespace [" + s_namespace + "]."); + } + + StackLevel level; + if (!s_namespaces.TryGetValue(namespaceName, out level)) + { + level = new StackLevel(namespaceName, true); ; + } + + s_locals.Push(level); + s_namespaces[namespaceName] = level; + + s_namespace = namespaceName; + s_namespacePrefix = namespaceName + "."; + } + + public static void PopNamespace() + { + s_namespace = s_namespacePrefix = ""; + while (s_locals.Count > 0) + { + var level = s_locals.Pop(); + if (level.IsNamespace) + { + return; + } + } + } + + public static string AdjustWithNamespace(string name) + { + name = Constants.ConvertName(name); + return s_namespacePrefix + name; + } + + public static void AddStackLevel(string scopeName) + { + s_locals.Push(new StackLevel(scopeName)); + } + + public static void AddLocalVariable(ParserFunction local) + { + NormalizeValue(local); + local.m_isGlobal = false; + StackLevel locals = null; + if (s_locals.Count == 0) + { + locals = new StackLevel(); + s_locals.Push(locals); + } + else + { + locals = s_locals.Peek(); + } + + var name = Constants.ConvertName(local.Name); + local.Name = Constants.GetRealName(name); + locals.Variables[name] = local; +#if UNITY_EDITOR == false && UNITY_STANDALONE == false && __ANDROID__ == false && __IOS__ == false + Translation.AddTempKeyword(name); +#endif + } + + public static void PopLocalVariables() + { + if (s_locals.Count > 0) + { + s_locals.Pop(); + } + } + + public static int GetCurrentStackLevel() + { + return s_locals.Count; + } + + public static void InvalidateStacksAfterLevel(int level) + { + while (level >= 0 && s_locals.Count > level) + { + s_locals.Pop(); + } + } + + public static bool PopLocalVariable(string name) + { + if (s_locals.Count == 0) + { + return false; + } + Dictionary locals = s_locals.Peek().Variables; + name = Constants.ConvertName(name); + return locals.Remove(name); + } + + public Variable GetValue(ParsingScript script) + { + return m_impl.Evaluate(script); + } + + public async Task GetValueAsync(ParsingScript script) + { + return await m_impl.EvaluateAsync(script); + } + + protected virtual Variable Evaluate(ParsingScript script) + { + // The real implementation will be in the derived classes. + return new Variable(); + } + + protected virtual Task EvaluateAsync(ParsingScript script) + { + // If not overriden, the non-sync version will be called. + return Task.FromResult( Evaluate(script) ); + } + + // Derived classes may want to return a new instance in order to + // not to use same object in calculations. + public virtual ParserFunction NewInstance() + { + return this; + } + + public static void CleanUp() + { + s_functions.Clear(); + s_actions.Clear(); + s_locals.Clear(); + s_localScope.Clear(); + } + + protected string m_name; + public string Name + { + get { return m_name; } + set { m_name = value; } + } + + protected bool m_isGlobal = true; + public bool isGlobal { get { return m_isGlobal; } set { m_isGlobal = value; } } + + protected bool m_isNative = true; + public bool isNative { get { return m_isNative; } set { m_isNative = value; } } + + ParserFunction m_impl; + // Global functions and variables: + static Dictionary s_functions = new Dictionary(); + + // Global actions - function: + static Dictionary s_actions = new Dictionary(); + + // Local scope variables- defined only in the current file: + static Dictionary> s_localScope = + new Dictionary>(); + + public static bool IsNumericFunction(string paramName, ParsingScript script = null) + { + ParserFunction function = ParserFunction.GetFunction(paramName, script); + return function is INumericFunction; + } + + public class StackLevel + { + public StackLevel(string name = null, bool isNamespace = false) + { + Name = name; + IsNamespace = isNamespace; + Variables = new Dictionary(); + } + public string Name { get; set; } + public bool IsNamespace { get; set; } + + public Dictionary Variables { get; set; } + } + + // Local variables: + // Stack of the functions being executed: + static Stack s_locals = new Stack(); + public static Stack ExecutionStack { get { return s_locals; } } + + static Dictionary s_namespaces = new Dictionary(); + static string s_namespace; + static string s_namespacePrefix; + + public static string GetCurrentNamespace { get { return s_namespace; } } + + static StringOrNumberFunction s_strOrNumFunction = + new StringOrNumberFunction(); + static IdentityFunction s_idFunction = + new IdentityFunction(); + + public static int StackLevelDelta { get; set; } + } + + public abstract class ActionFunction : ParserFunction + { + protected string m_action; + public string Action { set { m_action = value; } } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `name` last assigned on line 305 could be null and is dereferenced by call to `GetRealName(...)` at line 313, column 13. + +### Severity: +ERROR + +### Procedure: +Void ParserFunction.AddGlobalOrLocalVariable(String,GetVarFunction) + +### File: +cscs/ParserFunction.cs + +### Key: +ParserFunction.cs|AddGlobalOrLocalVariable|NULL_DEREFERENCE + +### Node Key: +840c96a3a061419c9a8b9b3c75aa5d7b + +### Hash: +eb44eb92ddc4fb4a3bd3cf3e55fb489c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1872/instruction.md b/inferredbugs-1872/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cfc51f663ae47807cf15c0e0f9cd35e0d524f239 --- /dev/null +++ b/inferredbugs-1872/instruction.md @@ -0,0 +1,1531 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cscs +**Bug ID:** 16 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; + +namespace SplitAndMerge +{ + class BreakStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.BREAK); + } + } + class ContinueStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.CONTINUE); + } + } + + class ReturnStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = Utils.GetItem(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + } + + class TryBlock : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessTry(script); + } + } + + class ExitFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Environment.Exit(0); + return Variable.EmptyInstance; + } + } + + class ThrowFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = Utils.GetItem(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + } + + class ShowFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + string funcName = args[0].AsString(); + + ParserFunction function = ParserFunction.GetFunction(funcName, script); + CustomFunction custFunc = function as CustomFunction; + Utils.CheckNotNull(funcName, custFunc); + + string body = Utils.BeautifyScript(custFunc.Body, custFunc.Header); + Utils.PrintScript(body, script); + + return new Variable(body); + } + } + + class FunctionCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string funcName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + //Interpreter.Instance.AppendOutput("Registering function [" + funcName + "] ..."); + + string[] args = Utils.GetFunctionSignature(script); + if (args.Length == 1 && string.IsNullOrWhiteSpace(args[0])) + { + args = new string[0]; + } + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + int lineNumber = 0; + string line = script.GetOriginalLine(out lineNumber); + + int parentOffset = script.Pointer; + var parent = script.ParentScript; + + if (script.CurrentClass != null) + { + parentOffset += script.CurrentClass.ParentOffset; + } + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, Constants.END_GROUP); + + CustomFunction customFunc = new CustomFunction(funcName, body, args); + customFunc.ParentScript = script; + customFunc.ParentOffset = parentOffset; + + if (script.CurrentClass != null) + { + script.CurrentClass.AddMethod(funcName, args, customFunc); + } + else + { + ParserFunction.RegisterFunction(funcName, customFunc, false /* not native */); + } + + return Variable.EmptyInstance; + } + } + + public class CSCSClass : ParserFunction + { + public CSCSClass(string className, string[] baseClasses) + { + m_name = className; + s_allClasses[className] = this; + + foreach (string baseClass in baseClasses) + { + var bc = CSCSClass.GetClass(baseClass); + if (bc == null) + { + throw new ArgumentException("Base Class [" + baseClass + "] not found."); + } + + foreach (var entry in bc.m_classProperties) + { + m_classProperties[entry.Key] = entry.Value; + } + foreach (var entry in bc.m_customFunctions) + { + m_customFunctions[entry.Key] = entry.Value; + } + } + } + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + + // TODO: Work in progress, currently not functional + return Variable.EmptyInstance; + } + + public void AddMethod(string name, string[] args, CustomFunction method) + { + if (name == m_name) + { + m_constructors[args.Length] = method; + } + else + { + m_customFunctions[name] = method; + } + } + + public void AddProperty(string name, Variable property) + { + m_classProperties[name] = property; + } + + public static CSCSClass GetClass(string name) + { + CSCSClass theClass = null; + s_allClasses.TryGetValue(name, out theClass); + return theClass; + } + + static Dictionary s_allClasses = + new Dictionary(); + + Dictionary m_constructors = + new Dictionary(); + Dictionary m_customFunctions = + new Dictionary(); + Dictionary m_classProperties = + new Dictionary(); + + public ParsingScript ParentScript = null; + public int ParentOffset = 0; + + public class ClassInstance : ScriptObject + { + public ClassInstance(string instanceName, string className, List args, + ParsingScript script = null) + { + InstanceName = instanceName; + m_cscsClass = CSCSClass.GetClass(className); + if (m_cscsClass == null) + { + throw new ArgumentException("Class [" + className + "] not found."); + } + + // Copy over all the properties defined for this class. + foreach (var entry in m_cscsClass.m_classProperties) + { + SetProperty(entry.Key, entry.Value); + } + + // Run "constructor" if any is defined for this number of args. + CustomFunction constructor = null; + if (m_cscsClass.m_constructors.TryGetValue(args.Count, out constructor)) + { + constructor.Run(args, script, this); + } + } + + public string InstanceName { get; set; } + CSCSClass m_cscsClass; + + Dictionary m_properties = new Dictionary(); + HashSet m_propSet = new HashSet(); + + public Variable SetProperty(string name, Variable value) + { + m_properties[name] = value; + m_propSet.Add(name); + return Variable.EmptyInstance; + } + + public Variable GetProperty(string name, List args = null, ParsingScript script = null) + { + Variable value = null; + if (m_properties.TryGetValue(name, out value)) + { + return value; + } + + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out customFunction)) + { + return null; + } + if (args == null) + { + return Variable.EmptyInstance; + } + + foreach (var entry in m_cscsClass.m_classProperties) + { + args.Add(entry.Value); + } + + Variable result = customFunction.Run(args, script, this); + return result; + } + + public List> GetPropList() + { + List> props = new List>(); + foreach (var entry in m_properties) + { + props.Add(new KeyValuePair(entry.Key, entry.Value)); + } + return props; + } + + public List GetProperties() + { + List props = new List(m_properties.Keys); + props.AddRange(m_cscsClass.m_customFunctions.Keys); + + return props; + } + public bool PropertyExists(string name) + { + return m_propSet.Contains(name); + } + } + } + + class NewObjectFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + script.MoveForwardIf(Constants.START_ARG); + List args = script.GetFunctionArgs(); + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + Variable value = new Variable(instance); + + return value; + } + } + + public class ClassCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + string[] baseClasses = Utils.GetBaseClasses(script); + CSCSClass newClass = new CSCSClass(className, baseClasses); + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + + newClass.ParentOffset = script.Pointer; + newClass.ParentScript = script; + int lineNumber = 0; + string line = script.GetOriginalLine(out lineNumber); + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + + Variable result = null; + ParsingScript tempScript = new ParsingScript(body); + //tempScript.ScriptOffset = newClass.ParentOffset; + tempScript.Char2Line = script.Char2Line; + tempScript.Filename = script.Filename; + tempScript.OriginalScript = script.OriginalScript; + tempScript.CurrentClass = newClass; + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.DisableBreakpoints = true; + + /*Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript); + }*/ + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + + return Variable.EmptyInstance; + } + } + + public class CustomFunction : ParserFunction + { + internal CustomFunction(string funcName, + string body, string[] args) + { + m_name = funcName; + m_body = body; + m_args = args; + } + + public void RegisterArguments(List args, + List> args2 = null) + { + StackLevel stackLevel = new StackLevel(m_name); + + if (args2 != null) + { + foreach (var entry in args2) + { + var arg = new GetVarFunction(entry.Value); + arg.Name = entry.Key; + stackLevel.Variables[entry.Key] = arg; + } + } + + int maxSize = Math.Min(args.Count, m_args.Length); + for (int i = 0; i < maxSize; i++) + { + var arg = new GetVarFunction(args[i]); + arg.Name = m_args[i]; + stackLevel.Variables[m_args[i]] = arg; + } + + ParserFunction.AddLocalVariables(stackLevel); + } + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count != m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = Run(args, script); + return result; + } + + public Variable Run(List args, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = new ParsingScript(m_body); + tempScript.ScriptOffset = m_parentOffset; + if (m_parentScript != null) + { + tempScript.Char2Line = m_parentScript.Char2Line; + tempScript.Filename = m_parentScript.Filename; + tempScript.OriginalScript = m_parentScript.OriginalScript; + } + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false: script.InTryBlock; + tempScript.ClassInstance = instance; + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript); + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + + public static Variable Run(string functionName, Variable arg1 = null, Variable arg2 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + + Variable result = customFunction.Run(args); + return result; + } + + public ParsingScript ParentScript { set { m_parentScript = value; } } + public int ParentOffset { set { m_parentOffset = value; } } + public string Body { get { return m_body; } } + + public int ArgumentCount { get { return m_args.Length; } } + public string Argument(int nIndex) { return m_args[nIndex]; } + + public string Header + { + get + { + return Constants.FUNCTION + " " + Name + " " + + Constants.START_ARG + string.Join(", ", m_args) + + Constants.END_ARG + " " + Constants.START_GROUP; + } + } + + protected string m_body; + protected string[] m_args; + protected ParsingScript m_parentScript = null; + protected int m_parentOffset = 0; + } + + class StringOrNumberFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // First check if the passed expression is a string between quotes. + if (Item.Length > 1 && + Item[0] == Constants.QUOTE && + Item[Item.Length - 1] == Constants.QUOTE) + { + return new Variable(Item.Substring(1, Item.Length - 2)); + } + + // Otherwise this should be a number. + double num = Utils.ConvertToDouble(Item, "StringOrNumber"); + /*if (!Double.TryParse(Item, NumberStyles.Number | + NumberStyles.AllowExponent | + NumberStyles.Float, + CultureInfo.InvariantCulture, out num)) { + Utils.ThrowException(script, "parseToken", Item, "parseTokenExtra"); + }*/ + return new Variable(num); + } + + public string Item { private get; set; } + } + + class AddFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + + currentValue.AddVariable(item); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + } + class RemoveFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + string varName = args[0].AsString(); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = args[1]; + + bool removed = currentValue.Tuple.Remove(item); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return new Variable(removed); + } + } + class RemoveAtFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = Utils.GetItem(script); + Utils.CheckNonNegativeInt(item); + + currentValue.Tuple.RemoveAt(item.AsInt()); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return Variable.EmptyInstance; + } + } + + class ContainsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + List arrayIndices = Utils.GetArrayIndices(script, ref varName); + + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + + // 2b. Special dealings with arrays: + Variable query = arrayIndices.Count > 0 ? + Utils.ExtractArrayElement(currentValue, arrayIndices) : + currentValue; + + // 3. Get the value to be looked for. + Variable searchValue = Utils.GetItem(script); + Utils.CheckNotEnd(script, m_name); + + // 4. Check if the value to search for exists. + bool exists = query.Exists(searchValue, true /* notEmpty */); + + script.MoveBackIf(Constants.START_GROUP); + return new Variable(exists); + } + } + + class BoolFunction : ParserFunction, INumericFunction + { + bool m_value; + public BoolFunction(bool init) + { + m_value = init; + } + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(m_value); + } + } + class ToDoubleFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToDouble(arg.AsString()); + return new Variable(result); + } + } + class ToIntFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + int result = Utils.ConvertToInt(arg.AsString()); + return new Variable(result); + } + } + class ToBoolFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToBool(arg.AsString()) ? 1 : 0; + return new Variable(result); + } + } + class ToDecimalFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = Decimal.Parse(arg.AsString(), NumberStyles.Any).ToString(); + return new Variable(result); + } + } + class ToStringFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = arg.AsString(); + return new Variable(result); + } + } + class IdentityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return script.ExecuteTo(Constants.END_ARG); + } + } + + class IfStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable result = Interpreter.Instance.ProcessIf(script); + return result; + } + } + + class ForStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessFor(script); + } + } + + class WhileStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessWhile(script); + } + } + + class IncludeFile : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + string filename = args[0].AsString(); + string[] lines = Utils.GetFileLines(filename); + + string includeFile = string.Join(Environment.NewLine, lines); + Dictionary char2Line; + string includeScript = Utils.ConvertToScript(includeFile, out char2Line); + ParsingScript tempScript = new ParsingScript(includeScript, 0, char2Line); + tempScript.Filename = filename; + tempScript.OriginalScript = string.Join(Constants.END_LINE.ToString(), lines); + tempScript.ParentScript = script; + tempScript.InTryBlock = script.InTryBlock; + + Variable result = null; + if (script.Debugger != null) + { + result = script.Debugger.StepInIncludeIfNeeded(tempScript); + } + + while (tempScript.Pointer < includeScript.Length) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + } + + // Get a value of a variable or of an array element + public class GetVarFunction : ParserFunction + { + public GetVarFunction(Variable value) + { + m_value = value; + } + + protected override Variable Evaluate(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = Utils.GetArrayIndices(script, ref startName, ref m_delta); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices); + return result; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + Variable propValue = m_value.GetProperty(m_propName, script); + string temp = m_propName; + m_propName = null; // Need this trick in case the below statement throws + Utils.CheckNotNull(propValue, temp); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + + public int Delta + { + set { m_delta = value; } + } + public Variable Value + { + get { return m_value; } + } + public List Indices + { + set { m_arrayIndices = value; } + } + public string PropertyName + { + set { m_propName = value; } + } + + Variable m_value; + int m_delta = 0; + List m_arrayIndices = null; + string m_propName; + } + class IncrementDecrementFunction : ActionFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool prefix = string.IsNullOrWhiteSpace(m_name); + if (prefix) + {// If it is a prefix we do not have the variable name yet. + m_name = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + } + + // Value to be added to the variable: + int valueDelta = m_action == Constants.INCREMENT ? 1 : -1; + int returnDelta = prefix ? valueDelta : 0; + + // Check if the variable to be set has the form of x[a][b], + // meaning that this is an array element. + double newValue = 0; + List arrayIndices = Utils.GetArrayIndices(script, ref m_name); + + ParserFunction func = ParserFunction.GetFunction(m_name, script); + Utils.CheckNotNull(m_name, func); + + Variable currentValue = func.GetValue(script); + + if (arrayIndices.Count > 0 || script.TryCurrent() == Constants.START_ARRAY) + { + if (prefix) + { + string tmpName = m_name + script.Rest; + int delta = 0; + arrayIndices = Utils.GetArrayIndices(script, ref tmpName, ref delta); + script.Forward(Math.Max(0, delta - tmpName.Length)); + } + + Variable element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + + newValue = element.Value + returnDelta; + element.Value += valueDelta; + } + else + { // A normal variable. + newValue = currentValue.Value + returnDelta; + currentValue.Value += valueDelta; + } + + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + return new Variable(newValue); + } + + override public ParserFunction NewInstance() + { + return new IncrementDecrementFunction(); + } + } + + class OperatorAssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // Value to be added to the variable: + Variable right = Utils.GetItem(script); + + List arrayIndices = Utils.GetArrayIndices(script, ref m_name); + + ParserFunction func = ParserFunction.GetFunction(m_name, script); + Utils.CheckNotNull(m_name, func); + + Variable currentValue = func.GetValue(script); + Variable left = currentValue; + + if (arrayIndices.Count > 0) + {// array element + left = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + if (left.Type == Variable.VarType.NUMBER) + { + NumberOperator(left, right, m_action); + } + else + { + StringOperator(left, right, m_action); + } + + if (arrayIndices.Count > 0) + {// array element + AssignFunction.ExtendArray(currentValue, arrayIndices, 0, left); + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + } + else + { + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(left)); + } + return left; + } + + static void NumberOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + valueA.Value += valueB.Value; + break; + case "-=": + valueA.Value -= valueB.Value; + break; + case "*=": + valueA.Value *= valueB.Value; + break; + case "/=": + valueA.Value /= valueB.Value; + break; + case "%=": + valueA.Value %= valueB.Value; + break; + case "&=": + valueA.Value = (int)valueA.Value & (int)valueB.Value; + break; + case "|=": + valueA.Value = (int)valueA.Value | (int)valueB.Value; + break; + case "^=": + valueA.Value = (int)valueA.Value ^ (int)valueB.Value; + break; + } + } + static void StringOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + if (valueB.Type == Variable.VarType.STRING) + { + valueA.String += valueB.AsString(); + } + else + { + valueA.String += valueB.Value; + } + break; + } + } + + override public ParserFunction NewInstance() + { + return new OperatorAssignFunction(); + } + } + + class AssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.CurrentAssign = m_name; + Variable varValue = Utils.GetItem(script); + // First try processing as an object (with a dot notation): + Variable result = ProcessObject(script, varValue); + if (result != null) + { + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = Utils.GetArrayIndices(script, ref m_name); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue)); + return varValue.DeepClone(); + } + + Variable array; + + ParserFunction pf = ParserFunction.GetFunction(m_name, script); + if (pf != null) + { + array = pf.GetValue(script); + } + else + { + array = new Variable(); + } + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array)); + return array; + } + + Variable ProcessObject(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + script.ClassInstance.SetProperty(m_name, varValue); + return varValue.DeepClone(); + } + + int ind = varName.IndexOf("."); + if (ind <= 0) + { + return null; + } + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + ParserFunction existing = ParserFunction.GetFunction(name, script); + Variable baseValue = existing != null ? existing.GetValue(script) : new Variable(Variable.VarType.ARRAY); + baseValue.SetProperty(prop, varValue); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue)); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + + override public ParserFunction NewInstance() + { + return new AssignFunction(); + } + + public static void ExtendArray(Variable parent, + List arrayIndices, + int indexPtr, + Variable varValue) + { + if (arrayIndices.Count <= indexPtr) + { + return; + } + + Variable index = arrayIndices[indexPtr]; + int currIndex = ExtendArrayHelper(parent, index); + + if (arrayIndices.Count - 1 == indexPtr) + { + parent.Tuple[currIndex] = varValue; + return; + } + + Variable son = parent.Tuple[currIndex]; + ExtendArray(son, arrayIndices, indexPtr + 1, varValue); + } + + private static int ExtendArrayHelper(Variable parent, Variable indexVar) + { + parent.SetAsArray(); + + int arrayIndex = parent.GetArrayIndex(indexVar); + if (arrayIndex < 0) + { + // This is not a "normal index" but a new string for the dictionary. + string hash = indexVar.AsString(); + arrayIndex = parent.SetHashVariable(hash, Variable.NewEmpty()); + return arrayIndex; + } + + if (parent.Tuple.Count <= arrayIndex) + { + for (int i = parent.Tuple.Count; i <= arrayIndex; i++) + { + parent.Tuple.Add(Variable.NewEmpty()); + } + } + return arrayIndex; + } + } + + class DeepCopyFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varValue = Utils.GetItem(script); + return varValue.DeepClone(); ; + } + } + + class TokenizeLinesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2); + string sepStr = Utils.GetSafeString(args, 3, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + /* var function = */ ParserFunction.GetFunction(varName, script); + Variable allTokensVar = new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; +#pragma warning disable 219 + // bugbug - the toAdd has side effects + Variable toAdd = new Variable(counter - fromLine); +#pragma warning restore 219 + string line = lineVar.AsString(); + var tokens = line.Split(sep); + Variable tokensVar = new Variable(Variable.VarType.ARRAY); + foreach (string token in tokens) + { + tokensVar.Tuple.Add(new Variable(token)); + } + allTokensVar.Tuple.Add(tokensVar); + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(allTokensVar)); + + return Variable.EmptyInstance; + } + } + + class AddVariablesToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2); + string hash2 = Utils.GetSafeString(args, 3); + string sepStr = Utils.GetSafeString(args, 4, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; + Variable toAdd = new Variable(counter - fromLine); + string line = lineVar.AsString(); + var tokens = line.Split(sep); + string hash = tokens[0]; + mapVar.AddVariableToHash(hash, toAdd); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + return Variable.EmptyInstance; + } + } + class AddVariableToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable toAdd = Utils.GetSafeVariable(args, 1); + string hash = Utils.GetSafeString(args, 2); + + var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + mapVar.AddVariableToHash(hash, toAdd); + for (int i = 3; i < args.Count; i++) + { + string hash2 = Utils.GetSafeString(args, 3); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + + return Variable.EmptyInstance; + } + } + class TokenCounterFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable all = Utils.GetSafeVariable(args, 0); + string varName = Utils.GetSafeString(args, 1); + int index = Utils.GetSafeInt(args, 2); + + /* var function = */ ParserFunction.GetFunction(varName, script); + Variable mapVar = new Variable(Variable.VarType.ARRAY); + + if (all.Tuple == null) + { + return Variable.EmptyInstance; + } + + string currentValue = ""; + int currentCount = 0; + + int globalCount = 0; + + for (int i = 0; i < all.Tuple.Count; i++) + { + Variable current = all.Tuple[i]; + if (current.Tuple == null || current.Tuple.Count < index) + { + break; + } + string newValue = current.Tuple[index].AsString(); + if (currentValue != newValue) + { + currentValue = newValue; + currentCount = 0; + } + mapVar.Tuple.Add(new Variable(currentCount)); + currentCount++; + globalCount++; + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + // Script - Need to enable the warnings +#pragma warning restore 219 + return mapVar; + } + } + + class TypeFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.END_ARG_ARRAY); + Utils.CheckNotEnd(script, m_name); + + List arrayIndices = Utils.GetArrayIndices(script, ref varName); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Variable element = currentValue; + + // 2b. Special case for an array. + if (arrayIndices.Count > 0) + {// array element + element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + // 3. Convert type to string. + string type = element.GetTypeString(); + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(type); + return newValue; + } + } + + class SizeFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.END_ARG_ARRAY); + Utils.CheckNotEnd(script, m_name); + + List arrayIndices = Utils.GetArrayIndices(script, ref varName); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Variable element = currentValue; + + // 2b. Special case for an array. + if (arrayIndices.Count > 0) + {// array element + element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + // 3. Take either the length of the underlying tuple or + // string part if it is defined, + // or the numerical part converted to a string otherwise. + int size = element.Type == Variable.VarType.ARRAY ? + element.Tuple.Count : + element.AsString().Length; + + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(size); + return newValue; + } + } + + class DefineLocalFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable currentValue = Utils.GetSafeVariable(args, 1); + + if (currentValue == null) + { + currentValue = new Variable(""); + } + + string scopeName = Path.GetFileName(script.Filename); + ParserFunction.AddLocalScopeVariable(varName, scopeName, + new GetVarFunction(currentValue)); + + return currentValue; + } + } + + class GetPropertiesFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + Variable baseValue = args[0]; + List props = baseValue.GetProperties(); + return new Variable(props); + } + } + + class GetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = baseValue.GetProperty(propName, script); + Utils.CheckNotNull(propValue, propName); + + return new Variable(propValue); + } + public static Variable GetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = baseValue.GetProperty(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName); + + return new Variable(propValue); + } + } + + class SetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = baseValue.SetProperty(propName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + public static Variable SetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = baseValue.SetProperty(sPropertyName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `currentValue` last assigned on line 1412 could be null and is dereferenced at line 1416, column 13. + +### Severity: +ERROR + +### Procedure: +Variable AddFunction.Evaluate(ParsingScript) + +### File: +cscs/Functions.Flow.cs + +### Key: +Functions.Flow.cs|Evaluate|NULL_DEREFERENCE + +### Node Key: +722f645c76bfb99c288630c5b05ba5dc + +### Hash: +e0a75025508ed3930f8cabca0f7a1d83 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1875/instruction.md b/inferredbugs-1875/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..31746105838553b580e11ebf4ccf461f35f6b341 --- /dev/null +++ b/inferredbugs-1875/instruction.md @@ -0,0 +1,1164 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cscs +**Bug ID:** 45 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SplitAndMerge +{ + public class Variable + { + public enum VarType + { + NONE, NUMBER, STRING, ARRAY, + ARRAY_NUM, ARRAY_STR, MAP_NUM, MAP_STR, + BREAK, CONTINUE, OBJECT, ENUM + }; + + public Variable() + { + Reset(); + } + public Variable(VarType type) + { + Type = type; + if (Type == VarType.ARRAY) + { + SetAsArray(); + } + } + public Variable(double d) + { + Value = d; + } + public Variable(bool d) + { + Value = d ? 1.0 : 0.0; + } + public Variable(string s) + { + String = s; + } + public Variable(List a) + { + this.Tuple = a; + } + public Variable(List a) + { + List tuple = new List(a.Count); + for (int i = 0; i < a.Count; i++) + { + tuple.Add(new Variable(a[i])); + } + this.Tuple = tuple; + } + public Variable(List a) + { + List tuple = new List(a.Count); + for (int i = 0; i < a.Count; i++) + { + tuple.Add(new Variable(a[i])); + } + this.Tuple = tuple; + } + public Variable(Dictionary a) + { + List tuple = new List(a.Count); + foreach (string key in a.Keys) + { + string lower = key.ToLower(); + m_keyMappings[lower] = key; + m_dictionary[lower] = tuple.Count; + tuple.Add(new Variable(a[key])); + } + this.Tuple = tuple; + } + public Variable(Dictionary a) + { + List tuple = new List(a.Count); + foreach (string key in a.Keys) + { + string lower = key.ToLower(); + m_keyMappings[lower] = key; + m_dictionary[lower] = tuple.Count; + tuple.Add(new Variable(a[key])); + } + this.Tuple = tuple; + } + + public Variable(object o) + { + Object = o; + } + + public virtual Variable Clone() + { + Variable newVar = (Variable)this.MemberwiseClone(); + return newVar; + } + + public virtual Variable DeepClone() + { + //Variable newVar = new Variable(); + //newVar.Copy(this); + Variable newVar = (Variable)this.MemberwiseClone(); + + if (m_tuple != null) + { + List newTuple = new List(); + foreach (var item in m_tuple) + { + newTuple.Add(item.DeepClone()); + } + + newVar.Tuple = newTuple; + } + return newVar; + } + + public static Variable NewEmpty() + { + return new Variable(); + } + + public void Reset() + { + m_value = Double.NaN; + m_string = null; + m_object = null; + m_tuple = null; + Action = null; + IsReturn = false; + Type = VarType.NONE; + m_dictionary.Clear(); + m_propertyMap.Clear(); + } + + public bool Equals(Variable other) + { + if (Type != other.Type) + { + return false; + } + if (Double.IsNaN(Value) != Double.IsNaN(other.Value) || + (!Double.IsNaN(Value) && Value != other.Value)) + { + return false; + } + if (!String.Equals(this.String, other.String, StringComparison.Ordinal)) + { + return false; + } + if (!String.Equals(this.Action, other.Action, StringComparison.Ordinal)) + { + return false; + } + if ((this.Tuple == null) != (other.Tuple == null)) + { + return false; + } + if (this.Tuple != null && !this.Tuple.Equals(other.Tuple)) + { + return false; + } + if (!m_propertyMap.Equals(other.m_propertyMap)) + { + return false; + } + return true; + } + + public void AddVariableToHash(string hash, Variable newVar) + { + int retValue = 0; + Variable listVar = null; + string lower = hash.ToLower(); + if (m_dictionary.TryGetValue(lower, out retValue)) + { + // already exists, change the value: + listVar = m_tuple[retValue]; + } + else + { + listVar = new Variable(VarType.ARRAY); + m_tuple.Add(listVar); + + m_keyMappings[lower] = hash; + m_dictionary[lower] = m_tuple.Count - 1; + } + + listVar.AddVariable(newVar); + } + + public List GetAllKeys() + { + List results = new List(); + var keys = m_keyMappings.Values; + foreach (var key in keys) + { + results.Add(new Variable(key)); + } + + if (results.Count == 0 && m_tuple != null) + { + results = m_tuple; + } + + return results; + } + + public List GetKeys() + { + List results = new List(); + var keys = m_keyMappings.Values; + foreach (var key in keys) + { + results.Add(key); + } + return results; + } + + public int SetHashVariable(string hash, Variable var) + { + int retValue = m_tuple.Count; + string lower = hash.ToLower(); + if (m_dictionary.TryGetValue(lower, out retValue)) + { + // already exists, change the value: + m_tuple[retValue] = var; + return retValue; + } + + m_tuple.Add(var); + m_keyMappings[lower] = hash; + m_dictionary[lower] = m_tuple.Count - 1; + + return m_tuple.Count - 1; + } + + public int GetArrayIndex(Variable indexVar) + { + if (this.Type != VarType.ARRAY) + { + return -1; + } + + if (indexVar.Type == VarType.NUMBER) + { + Utils.CheckNonNegativeInt(indexVar); + return (int)indexVar.Value; + } + + string hash = indexVar.AsString(); + string lower = hash.ToLower(); + int ptr = m_tuple.Count; + if (m_dictionary.TryGetValue(lower, out ptr) && + ptr < m_tuple.Count) + { + return ptr; + } + + int result = -1; + if (!String.IsNullOrWhiteSpace(indexVar.String) && + Int32.TryParse(indexVar.String, out result)) + { + return result; + } + + return -1; + } + + public void AddVariable(Variable v, int index = -1) + { + SetAsArray(); + if (index < 0 || m_tuple.Count <= index) + { + m_tuple.Add(v); + } + else + { + m_tuple.Insert(index, v); + } + } + + public Variable GetVariable(int index) + { + if (index < 0 || m_tuple == null || m_tuple.Count <= index) + { + return Variable.EmptyInstance; + } + return m_tuple[index]; + } + + public Variable GetVariable(string hash) + { + int index = 0; + string lower = hash.ToLower(); + if (m_tuple == null || !m_dictionary.TryGetValue(lower, out index) || + m_tuple.Count <= index) + { + return Variable.EmptyInstance; + } + return m_tuple[index]; + } + + public bool Exists(string hash) + { + string lower = hash.ToLower(); + return m_dictionary.ContainsKey(lower); + } + + public int FindIndex(string val) + { + if (this.Type != VarType.ARRAY) + { + return -1; + } + int result = m_tuple.FindIndex(item => item.AsString() == val); + return result; + } + + public bool Exists(Variable indexVar, bool notEmpty = false) + { + if (this.Type != VarType.ARRAY) + { + return false; + } + if (indexVar.Type == VarType.NUMBER) + { + if (indexVar.Value < 0 || + indexVar.Value >= m_tuple.Count || + indexVar.Value - Math.Floor(indexVar.Value) != 0.0) + { + return false; + } + if (notEmpty) + { + return m_tuple[(int)indexVar.Value].Type != VarType.NONE; + } + return true; + } + + string hash = indexVar.AsString(); + return Exists(hash); + } + + public bool AsBool() + { + if (Type == VarType.NUMBER && m_value != 0.0) + { + return true; + } + if (Type == VarType.STRING) + { + if (String.Compare(m_string, "true", true) == 0) + return true; + } + + return false; + } + + public int AsInt() + { + int result = 0; + if (Type == VarType.NUMBER || Value != 0.0) + { + return (int)m_value; + } + if (Type == VarType.STRING) + { + Int32.TryParse(m_string, out result); + } + + return result; + } + public float AsFloat() + { + float result = 0; + if (Type == VarType.NUMBER || Value != 0.0) + { + return (float)m_value; + } + if (Type == VarType.STRING) + { + float.TryParse(m_string, out result); + } + + return result; + } + public long AsLong() + { + long result = 0; + if (Type == VarType.NUMBER || Value != 0.0) + { + return (long)m_value; + } + if (Type == VarType.STRING) + { + long.TryParse(m_string, out result); + } + return result; + } + public double AsDouble() + { + double result = 0.0; + if (Type == VarType.NUMBER) + {// || (Value != 0.0 && Value != Double.NaN)) { + return m_value; + } + if (Type == VarType.STRING) + { + Double.TryParse(m_string, out result); + } + + return result; + } + + public override string ToString() + { + return AsString(); + } + + public virtual string AsString(bool isList = true, + bool sameLine = true, + int maxCount = -1) + { + if (Type == VarType.NUMBER) + { + return Value.ToString(); + } + if (Type == VarType.STRING) + { + return m_string == null ? "" : m_string; + } + if (Type == VarType.OBJECT) + { + return ObjectToString(); + } + + StringBuilder sb = new StringBuilder(); + if (Type == VarType.ENUM) + { + sb.Append(Constants.START_GROUP.ToString() + " "); + foreach (string key in m_propertyMap.Keys) + { + sb.Append(key + " "); + } + sb.Append(Constants.END_GROUP.ToString()); + return sb.ToString(); + } + + if (Type == VarType.NONE || m_tuple == null) + { + return string.Empty; + } + + if (isList) + { + sb.Append(Constants.START_GROUP.ToString() + + (sameLine ? "" : Environment.NewLine)); + } + + int count = maxCount < 0 ? m_tuple.Count : Math.Min(maxCount, m_tuple.Count); + int i = 0; + if (m_dictionary.Count > 0) + { + count = maxCount < 0 ? m_dictionary.Count : Math.Min(maxCount, m_dictionary.Count); + foreach (KeyValuePair entry in m_dictionary) + { + if (entry.Value >= 0 || entry.Value < m_tuple.Count) + { + string value = m_tuple[entry.Value].AsString(isList, sameLine, maxCount); + string realKey = entry.Key; + m_keyMappings.TryGetValue(entry.Key.ToLower(), out realKey); + + sb.Append("\"" + realKey + "\" : " + value); + if (i++ < count - 1) + { + sb.Append(sameLine ? ", " : Environment.NewLine); + } + else + { + break; + } + } + } + } + else + { + for (; i < count; i++) + { + Variable arg = m_tuple[i]; + sb.Append(arg.AsString(isList, sameLine, maxCount)); + if (i != count - 1) + { + sb.Append(sameLine ? ", " : Environment.NewLine); + } + } + } + if (count < m_tuple.Count) + { + sb.Append(" ..."); + } + if (isList) + { + sb.Append(Constants.END_GROUP.ToString() + + (sameLine ? "" : Environment.NewLine)); + } + + return sb.ToString(); + } + + string ObjectToString() + { + StringBuilder sb = new StringBuilder(); + if (m_object != null) + { + sb.Append(m_object.ToString()); + } + else + { + sb.Append((m_object != null ? (m_object.ToString() + " ") : "") + + Constants.START_GROUP.ToString()); + + List allProps = GetAllProperties(); + foreach (string prop in allProps) + { + if (prop.Equals(Constants.OBJECT_PROPERTIES, StringComparison.OrdinalIgnoreCase)) + { + sb.Append(prop); + continue; + } + Variable propValue = GetProperty(prop); + string value = ""; + if (propValue != null && propValue != Variable.EmptyInstance) + { + value = propValue.AsString(); + if (!string.IsNullOrEmpty(value)) + { + if (propValue.Type == VarType.STRING && + !prop.Equals(Constants.OBJECT_TYPE, StringComparison.OrdinalIgnoreCase)) + { + value = "\"" + value + "\""; + } + value = ": " + value; + } + } + sb.Append(prop + value + ", "); + } + + sb.Append(Constants.END_GROUP.ToString()); + } + return sb.ToString(); + } + + public void SetAsArray() + { + Type = VarType.ARRAY; + if (m_tuple == null) + { + m_tuple = new List(); + } + } + + public int Count + { + get { return Type == VarType.ARRAY ? m_tuple.Count : + Type == VarType.NONE ? 0 : 1; } + } + + public int TotalElements() + { + return Count; + } + + public Variable SetProperty(string propName, Variable value, string baseName = "") + { + propName = Constants.ConvertName(propName); + + int ind = propName.IndexOf("."); + if (ind > 0) + { // The case a.b.c = ... is dealt here recursively + string varName = propName.Substring(0, ind); + string actualPropName = propName.Substring(ind + 1); + Variable property = GetProperty(varName); + return property.SetProperty(actualPropName, value, baseName); + } + return FinishSetProperty(propName, value, baseName); + } + + public async Task SetPropertyAsync(string propName, Variable value, string baseName = "") + { + Variable result = Variable.EmptyInstance; + propName = Constants.ConvertName(propName); + + int ind = propName.IndexOf("."); + if (ind > 0) + { // The case a.b.c = ... is dealt here recursively + string varName = propName.Substring(0, ind); + string actualPropName = propName.Substring(ind + 1); + Variable property = await GetPropertyAsync(varName); + result = await property.SetPropertyAsync(actualPropName, value, baseName); + return result; + } + return FinishSetProperty(propName, value, baseName); + } + + public Variable FinishSetProperty(string propName, Variable value, string baseName = "") + { + Variable result = Variable.EmptyInstance; + string match = GetActualPropertyName(propName, GetAllProperties(), baseName, this); + m_propertyMap[match] = value; + Type = VarType.OBJECT; + + if (Object is ScriptObject) + { + ScriptObject obj = Object as ScriptObject; + result = obj.SetProperty(match, value).Result; + } + return result; + } + + public void SetEnumProperty(string propName, Variable value, string baseName = "") + { + propName = Constants.ConvertName(propName); + + string match = GetActualPropertyName(propName, GetAllProperties(), baseName, this); + m_propertyMap[match] = value; + + if (m_enumMap == null) + { + m_enumMap = new Dictionary(); + } + m_enumMap[value.AsInt()] = match; + } + + public Variable GetEnumProperty(string propName, ParsingScript script, string baseName = "") + { + propName = Constants.ConvertName(propName); + if (script.TryPrev() == Constants.START_ARG) + { + Variable value = Utils.GetItem(script); + if (propName == Constants.TO_STRING) + { + return ConvertEnumToString(value); + } + else + { + return new Variable(m_enumMap != null && m_enumMap.ContainsKey(value.AsInt())); + } + + } + + string match = GetActualPropertyName(propName, GetAllProperties(), baseName, this); + + Variable result = GetCoreProperty(match, script); + + return result; + } + + public Variable ConvertEnumToString(Variable value) + { + string result = ""; + if (m_enumMap != null && m_enumMap.TryGetValue(value.AsInt(), out result)) + { + return new Variable(result); + } + return Variable.EmptyInstance; + } + + public Variable GetProperty(string propName, ParsingScript script = null) + { + Variable result = Variable.EmptyInstance; + + int ind = propName.IndexOf("."); + if (ind > 0) + { // The case x = a.b.c ... is dealt here recursively + string varName = propName.Substring(0, ind); + string actualPropName = propName.Substring(ind + 1); + Variable property = GetProperty(varName, script); + result = string.IsNullOrEmpty(actualPropName) ? property : + property.GetProperty(actualPropName, script); + return result; + } + + if (Object is ScriptObject) + { + ScriptObject obj = Object as ScriptObject; + string match = GetActualPropertyName(propName, obj.GetProperties()); + if (!string.IsNullOrWhiteSpace(match)) + { + List args = null; + if (script != null && script.TryPrev() == Constants.START_ARG) + { + args = script.GetFunctionArgs(); + } + else if (script != null) + { + args = new List(); + } + result = obj.GetProperty(match, args, script).Result; + if (result != null) + { + return result; + } + } + } + + return GetCoreProperty(propName, script); + } + + public async Task GetPropertyAsync(string propName, ParsingScript script = null) + { + Variable result = Variable.EmptyInstance; + + int ind = propName.IndexOf("."); + if (ind > 0) + { // The case x = a.b.c ... is dealt here recursively + string varName = propName.Substring(0, ind); + string actualPropName = propName.Substring(ind + 1); + Variable property = await GetPropertyAsync(varName, script); + result = string.IsNullOrEmpty(actualPropName) ? property : + await property.GetPropertyAsync(actualPropName, script); + return result; + } + + if (Object is ScriptObject) + { + ScriptObject obj = Object as ScriptObject; + string match = GetActualPropertyName(propName, obj.GetProperties()); + if (!string.IsNullOrWhiteSpace(match)) + { + List args = null; + if (script != null && script.TryPrev() == Constants.START_ARG) + { + args = await script.GetFunctionArgsAsync(); + } + else if (script != null) + { + args = new List(); + } + result = await obj.GetProperty(match, args, script); + if (result != null) + { + return result; + } + } + } + + return GetCoreProperty(propName, script); + } + + Variable GetCoreProperty(string propName, ParsingScript script = null) + { + Variable result = Variable.EmptyInstance; + + if (m_propertyMap.TryGetValue(propName, out result)) + { + return result; + } + else if (propName.Equals(Constants.OBJECT_PROPERTIES, StringComparison.OrdinalIgnoreCase)) + { + return new Variable(GetProperties()); + } + else if (propName.Equals(Constants.OBJECT_TYPE, StringComparison.OrdinalIgnoreCase)) + { + return new Variable(GetTypeString()); + } + else if (propName.Equals(Constants.SIZE, StringComparison.OrdinalIgnoreCase)) + { + return new Variable(GetSize()); + } + else if (propName.Equals(Constants.UPPER, StringComparison.OrdinalIgnoreCase)) + { + return new Variable(AsString().ToUpper()); + } + else if (propName.Equals(Constants.LOWER, StringComparison.OrdinalIgnoreCase)) + { + return new Variable(AsString().ToLower()); + } + else if (propName.Equals(Constants.STRING, StringComparison.OrdinalIgnoreCase)) + { + return new Variable(AsString()); + } + else if (propName.Equals(Constants.FIRST, StringComparison.OrdinalIgnoreCase)) + { + if (Tuple != null && Tuple.Count > 0) + { + return Tuple[0]; + } + return AsString().Length > 0 ? new Variable("" + AsString()[0]) : Variable.EmptyInstance; + } + else if (propName.Equals(Constants.LAST, StringComparison.OrdinalIgnoreCase)) + { + if (Tuple != null && Tuple.Count > 0) + { + return Tuple.Last(); + } + return AsString().Length > 0 ? new Variable("" + AsString().Last()) : Variable.EmptyInstance; + } + else if (script != null && propName.Equals(Constants.INDEX_OF, StringComparison.OrdinalIgnoreCase)) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, propName); + + string search = Utils.GetSafeString(args, 0); + int startFrom = Utils.GetSafeInt(args, 1, 0); + string param = Utils.GetSafeString(args, 2, "no_case"); + StringComparison comp = param.Equals("case", StringComparison.OrdinalIgnoreCase) ? + StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase; + + return new Variable(AsString().IndexOf(search, startFrom,comp)); + } + else if (script != null && propName.Equals(Constants.SUBSTRING, StringComparison.OrdinalIgnoreCase)) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, propName); + + int startFrom = Utils.GetSafeInt(args, 0, 0); + int length = Utils.GetSafeInt(args, 1, AsString().Length); + length = Math.Min(length, AsString().Length - startFrom); + + return new Variable(AsString().Substring(startFrom, length)); + } + else if (script != null && propName.Equals(Constants.TOKENIZE, StringComparison.OrdinalIgnoreCase)) + { + List args = script.GetFunctionArgs(); + string sep = Utils.GetSafeString(args, 0, " "); + var option = Utils.GetSafeString(args, 1); + + return TokenizeFunction.Tokenize(AsString(), sep, option); + } + else if (script != null && propName.Equals(Constants.JOIN, StringComparison.OrdinalIgnoreCase)) + { + List args = script.GetFunctionArgs(); + string sep = Utils.GetSafeString(args, 0, " "); + if (Tuple == null) + { + return new Variable(AsString()); + } + + var join = string.Join(sep, Tuple); + return new Variable(join); + } + else if (script != null && propName.Equals(Constants.AT, StringComparison.OrdinalIgnoreCase)) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, propName); + int at = Utils.GetSafeInt(args, 0); + + if (Tuple != null && Tuple.Count > 0) + { + return Tuple.Count > at ? Tuple[at] : Variable.EmptyInstance; + } + string str = AsString(); + return str.Length > at ? new Variable("" + str[at]) : Variable.EmptyInstance; + } + else if (script != null && propName.Equals(Constants.REPLACE, StringComparison.OrdinalIgnoreCase)) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, propName); + string oldVal = Utils.GetSafeString(args, 0); + string newVal = Utils.GetSafeString(args, 1); + + return new Variable(AsString().Replace(oldVal, newVal)); + } + else if (script != null && propName.Equals(Constants.CONTAINS, StringComparison.OrdinalIgnoreCase)) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, propName); + string val = Utils.GetSafeString(args, 0); + string param = Utils.GetSafeString(args, 1, "no_case"); + StringComparison comp = param.Equals("case", StringComparison.OrdinalIgnoreCase) ? + StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase; + + int index = AsString().IndexOf(val, comp); + return new Variable(index >= 0); + } + else if (script != null && propName.Equals(Constants.EQUALS, StringComparison.OrdinalIgnoreCase)) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, propName); + string val = Utils.GetSafeString(args, 0); + string param = Utils.GetSafeString(args, 1, "no_case"); + StringComparison comp = param.Equals("case", StringComparison.OrdinalIgnoreCase) ? + StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase; + + return new Variable(AsString().Equals(val, comp)); + } + else if (script != null && propName.Equals(Constants.STARTS_WITH, StringComparison.OrdinalIgnoreCase)) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, propName); + string val = Utils.GetSafeString(args, 0); + string param = Utils.GetSafeString(args, 1, "no_case"); + StringComparison comp = param.Equals("case", StringComparison.OrdinalIgnoreCase) ? + StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase; + + return new Variable(AsString().StartsWith(val, comp)); + } + else if (script != null && propName.Equals(Constants.ENDS_WITH, StringComparison.OrdinalIgnoreCase)) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, propName); + string val = Utils.GetSafeString(args, 0); + string param = Utils.GetSafeString(args, 1, "no_case"); + StringComparison comp = param.Equals("case", StringComparison.OrdinalIgnoreCase) ? + StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase; + + return new Variable(AsString().EndsWith(val, comp)); + } + else if (script != null && propName.Equals(Constants.TRIM, StringComparison.OrdinalIgnoreCase)) + { + script.GetFunctionArgs(); + return new Variable(AsString().Trim()); + } + else if (propName.Equals(Constants.KEYS, StringComparison.OrdinalIgnoreCase)) + { + List results = GetAllKeys(); + return new Variable(results); + } + + return result; + } + + + public List GetProperties() + { + List all = GetAllProperties(); + List allVars = new List(all.Count); + foreach (string key in all) + { + allVars.Add(new Variable(key)); + } + + return allVars; + } + + public List GetAllProperties() + { + HashSet allSet = new HashSet(); + List all = new List(); + + foreach (string key in m_propertyMap.Keys) + { + allSet.Add(key.ToLower()); + all.Add(key); + } + + if (Object is ScriptObject) + { + ScriptObject obj = Object as ScriptObject; + List objProps = obj.GetProperties(); + foreach (string key in objProps) + { + if (allSet.Add(key.ToLower())) + { + all.Add(key); + } + } + } + + all.Sort(); + + if (!allSet.Contains(Constants.OBJECT_PROPERTIES.ToLower())) + { + all.Add(Constants.OBJECT_PROPERTIES); + } + if (!allSet.Contains(Constants.OBJECT_TYPE.ToLower())) + { + all.Add(Constants.OBJECT_TYPE); + } + if (!allSet.Contains(Constants.SIZE.ToLower())) + { + all.Add(Constants.SIZE); + } + if (!allSet.Contains(Constants.STRING.ToLower())) + { + all.Add(Constants.STRING); + } + + return all; + } + + public int GetSize() + { + int size = Type == Variable.VarType.ARRAY ? + Tuple.Count : + AsString().Length; + return size; + } + + public virtual string GetTypeString() + { + if (Type == VarType.OBJECT && Object != null) + { + return Object.GetType().ToString(); + } + return Constants.TypeToString(Type); + } + + public Variable GetValue(int index) + { + if (index >= Count) + { + throw new ArgumentException("There are only [" + Count + + "] but " + index + " requested."); + + } + if (Type == VarType.ARRAY) + { + return m_tuple[index]; + } + return this; + } + + public static string GetActualPropertyName(string propName, List properties, + string baseName = "", Variable root = null) + { + string match = properties.FirstOrDefault(element => element.Equals(propName, + StringComparison.OrdinalIgnoreCase)); + if (string.IsNullOrWhiteSpace(match)) + { + match = ""; + if (root != null) + { + string objName = !string.IsNullOrWhiteSpace(baseName) ? baseName + "." : ""; + if (string.IsNullOrWhiteSpace(objName)) + { + CSCSClass.ClassInstance obj = root.m_object as CSCSClass.ClassInstance; + objName = obj != null ? obj.InstanceName + "." : ""; + } + match = Constants.GetRealName(objName + propName); + match = match.Substring(objName.Length); + } + } + return match; + } + + public double Value + { + get { return m_value; } + set { m_value = value; Type = VarType.NUMBER; } + } + + public string String + { + get { return m_string; } + set { m_string = value; Type = VarType.STRING; } + } + + public object Object + { + get { return m_object; } + set { m_object = value; Type = VarType.OBJECT; } + } + + public List Tuple + { + get { return m_tuple; } + set { m_tuple = value; Type = VarType.ARRAY; } + } + + public string Action { get; set; } + public VarType Type + { + get; + set; + } + public bool IsReturn { get; set; } + public string ParsingToken { get; set; } + public int Index { get; set; } + public string CurrentAssign { get; set; } = ""; + + public static Variable EmptyInstance = new Variable(); + + double m_value; + string m_string; + object m_object; + List m_tuple; + Dictionary m_dictionary = new Dictionary(); + Dictionary m_keyMappings = new Dictionary(); + + Dictionary m_propertyMap = new Dictionary(); + Dictionary m_enumMap; + } + + // A Variable supporting "dot-notation" must have an object implementing this interface. + public interface ScriptObject + { + // SetProperty is triggered by the following scripting call: "a.name = value;" + Task SetProperty(string name, Variable value); + + // GetProperty is triggered by the following scripting call: "x = a.name;" + // If args are null, it is triggered by object.ToString() function" + // If args are not empty, it is triggered by a function call: "y = a.name(arg1, arg2, ...);" + Task GetProperty(string name, List args = null, ParsingScript script = null); + + // Returns all of the properties that this object implements. Only these properties will be processed + // by SetProperty() and GetProperty() methods above. + List GetProperties(); + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `propName` last assigned on line 577 could be null and is dereferenced at line 579, column 13. + +### Severity: +ERROR + +### Procedure: +Variable Variable.SetProperty(String,Variable,String) + +### File: +cscs/Variable.cs + +### Key: +Variable.cs|SetProperty|NULL_DEREFERENCE + +### Node Key: +8f23c407fab7524e0704ad6f3b90d75b + +### Hash: +b3b54157226e4bc8306b2fdc6fe2fd57 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1881/instruction.md b/inferredbugs-1881/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1943d22ee85192e8f5be436ec8eab5ac358a2e47 --- /dev/null +++ b/inferredbugs-1881/instruction.md @@ -0,0 +1,952 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cscs +**Bug ID:** 28 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SplitAndMerge +{ + public class Variable + { + public enum VarType + { + NONE, NUMBER, STRING, ARRAY, + ARRAY_NUM, ARRAY_STR, MAP_NUM, MAP_STR, + BREAK, CONTINUE, OBJECT + }; + + public Variable() + { + Reset(); + } + public Variable(VarType type) + { + Type = type; + if (Type == VarType.ARRAY) + { + SetAsArray(); + } + } + public Variable(double d) + { + Value = d; + } + public Variable(bool d) + { + Value = d ? 1.0 : 0.0; + } + public Variable(string s) + { + String = s; + } + public Variable(List a) + { + this.Tuple = a; + } + public Variable(Variable other) + { + Copy(other); + } + public Variable(List a) + { + List tuple = new List(a.Count); + for (int i = 0; i < a.Count; i++) + { + tuple.Add(new Variable(a[i])); + } + this.Tuple = tuple; + } + public Variable(List a) + { + List tuple = new List(a.Count); + for (int i = 0; i < a.Count; i++) + { + tuple.Add(new Variable(a[i])); + } + this.Tuple = tuple; + } + public Variable(Dictionary a) + { + List tuple = new List(a.Count); + foreach (string key in a.Keys) + { + m_dictionary[key] = tuple.Count; + tuple.Add(new Variable(a[key])); + } + this.Tuple = tuple; + } + public Variable(Dictionary a) + { + List tuple = new List(a.Count); + foreach (string key in a.Keys) + { + m_dictionary[key] = tuple.Count; + tuple.Add(new Variable(a[key])); + } + this.Tuple = tuple; + } + + public Variable(object o) + { + Object = o; + } + + public virtual Variable Clone() + { + Variable newVar = (Variable)this.MemberwiseClone(); + return newVar; + } + + public virtual Variable DeepClone() + { + //Variable newVar = new Variable(); + //newVar.Copy(this); + Variable newVar = (Variable)this.MemberwiseClone(); + + if (m_tuple != null) + { + List newTuple = new List(); + foreach (var item in m_tuple) + { + newTuple.Add(item.DeepClone()); + } + + newVar.Tuple = newTuple; + } + return newVar; + } + public virtual void Copy(Variable other) + { + Reset(); + Action = other.Action; + Type = other.Type; + IsReturn = other.IsReturn; + m_dictionary = other.m_dictionary; + m_propertyMap = other.m_propertyMap; + //bug todo + + switch (other.Type) + { + case VarType.NUMBER: + Value = other.Value; + break; + case VarType.STRING: + String = other.String; + break; + case VarType.ARRAY: + this.Tuple = other.Tuple; + break; + case VarType.OBJECT: + Object = other.Object; + break; + } + } + + public static Variable NewEmpty() + { + return new Variable(); + } + + public void Reset() + { + m_value = Double.NaN; + m_string = null; + m_object = null; + m_tuple = null; + Action = null; + IsReturn = false; + Type = VarType.NONE; + m_dictionary.Clear(); + m_propertyMap.Clear(); + } + + public bool Equals(Variable other) + { + if (Type != other.Type) + { + return false; + } + if (Double.IsNaN(Value) != Double.IsNaN(other.Value) || + (!Double.IsNaN(Value) && Value != other.Value)) + { + return false; + } + if (!String.Equals(this.String, other.String, StringComparison.Ordinal)) + { + return false; + } + if (!String.Equals(this.Action, other.Action, StringComparison.Ordinal)) + { + return false; + } + if ((this.Tuple == null) != (other.Tuple == null)) + { + return false; + } + if (this.Tuple != null && !this.Tuple.Equals(other.Tuple)) + { + return false; + } + if (!m_propertyMap.Equals(other.m_propertyMap)) + { + return false; + } + return true; + } + + public void AddVariableToHash(string hash, Variable newVar) + { + int retValue = 0; + Variable listVar = null; + if (m_dictionary.TryGetValue(hash, out retValue)) + { + // already exists, change the value: + listVar = m_tuple[retValue]; + } + else + { + listVar = new Variable(VarType.ARRAY); + m_tuple.Add(listVar); + m_dictionary[hash] = m_tuple.Count - 1; + } + + listVar.AddVariable(newVar); + } + + public List GetAllKeys() + { + List results = new List(); + var keys = m_dictionary.Keys; + foreach (var key in keys) + { + results.Add(new Variable(key)); + } + + if (results.Count == 0 && m_tuple != null) + { + results = m_tuple; + } + + return results; + } + + public List GetKeys() + { + List results = new List(); + var keys = m_dictionary.Keys; + foreach (var key in keys) + { + results.Add(key); + } + return results; + } + + public int SetHashVariable(string hash, Variable var) + { + int retValue = m_tuple.Count; + if (m_dictionary.TryGetValue(hash, out retValue)) + { + // already exists, change the value: + m_tuple[retValue] = var; + return retValue; + } + + m_tuple.Add(var); + m_dictionary[hash] = m_tuple.Count - 1; + + return m_tuple.Count - 1; + } + + public int GetArrayIndex(Variable indexVar) + { + if (this.Type != VarType.ARRAY) + { + return -1; + } + + if (indexVar.Type == VarType.NUMBER) + { + Utils.CheckNonNegativeInt(indexVar); + return (int)indexVar.Value; + } + + string hash = indexVar.AsString(); + int ptr = m_tuple.Count; + if (m_dictionary.TryGetValue(hash, out ptr) && + ptr < m_tuple.Count) + { + return ptr; + } + + int result = -1; + if (!String.IsNullOrWhiteSpace(indexVar.String) && + Int32.TryParse(indexVar.String, out result)) + { + return result; + } + + return -1; + } + + public void AddVariable(Variable v, int index = -1) + { + SetAsArray(); + if (index < 0 || m_tuple.Count <= index) + { + m_tuple.Add(v); + } + else + { + m_tuple.Insert(index, v); + } + } + + public Variable GetVariable(int index) + { + if (index < 0 || m_tuple == null || m_tuple.Count <= index) + { + return Variable.EmptyInstance; + } + return m_tuple[index]; + } + + public Variable GetVariable(string hash) + { + int index = 0; + if (m_tuple == null || !m_dictionary.TryGetValue(hash, out index) || + m_tuple.Count <= index) + { + return Variable.EmptyInstance; + } + return m_tuple[index]; + } + + public bool Exists(string hash) + { + return m_dictionary.ContainsKey(hash); + } + + public int FindIndex(string val) + { + if (this.Type != VarType.ARRAY) + { + return -1; + } + int result = m_tuple.FindIndex(item => item.AsString() == val); + return result; + } + + public bool Exists(Variable indexVar, bool notEmpty = false) + { + if (this.Type != VarType.ARRAY) + { + return false; + } + if (indexVar.Type == VarType.NUMBER) + { + if (indexVar.Value < 0 || + indexVar.Value >= m_tuple.Count || + indexVar.Value - Math.Floor(indexVar.Value) != 0.0) + { + return false; + } + if (notEmpty) + { + return m_tuple[(int)indexVar.Value].Type != VarType.NONE; + } + return true; + } + + string hash = indexVar.AsString(); + return Exists(hash); + } + + public bool AsBool() + { + if (Type == VarType.NUMBER && m_value != 0.0) + { + return true; + } + if (Type == VarType.STRING) + { + if (String.Compare(m_string, "true", true) == 0) + return true; + } + + return false; + } + + public int AsInt() + { + int result = 0; + if (Type == VarType.NUMBER || Value != 0.0) + { + return (int)m_value; + } + if (Type == VarType.STRING) + { + Int32.TryParse(m_string, out result); + } + + return result; + } + public float AsFloat() + { + float result = 0; + if (Type == VarType.NUMBER || Value != 0.0) + { + return (float)m_value; + } + if (Type == VarType.STRING) + { + float.TryParse(m_string, out result); + } + + return result; + } + public long AsLong() + { + long result = 0; + if (Type == VarType.NUMBER || Value != 0.0) + { + return (long)m_value; + } + if (Type == VarType.STRING) + { + long.TryParse(m_string, out result); + } + return result; + } + public double AsDouble() + { + double result = 0.0; + if (Type == VarType.NUMBER) + {// || (Value != 0.0 && Value != Double.NaN)) { + return m_value; + } + if (Type == VarType.STRING) + { + Double.TryParse(m_string, out result); + } + + return result; + } + + public virtual string AsString(bool isList = true, + bool sameLine = true, + int maxCount = -1) + { + if (Type == VarType.NUMBER) + { + return Value.ToString(); + } + if (Type == VarType.STRING) + { + return m_string == null ? "" : m_string; + } + if (Type == VarType.OBJECT) + { + return ObjectToString(); + } + if (Type == VarType.NONE || m_tuple == null) + { + return string.Empty; + } + + StringBuilder sb = new StringBuilder(); + + if (isList) + { + sb.Append(Constants.START_GROUP.ToString() + + (sameLine ? "" : Environment.NewLine)); + } + + int count = maxCount < 0 ? m_tuple.Count : Math.Min(maxCount, m_tuple.Count); + int i = 0; + if (m_dictionary.Count > 0) + { + count = maxCount < 0 ? m_dictionary.Count : Math.Min(maxCount, m_dictionary.Count); + foreach (KeyValuePair entry in m_dictionary) + { + if (entry.Value >= 0 || entry.Value < m_tuple.Count) + { + string value = m_tuple[entry.Value].AsString(isList, sameLine, maxCount); + sb.Append("\"" + entry.Key + "\" : " + value); + if (i++ < count - 1) + { + sb.Append(sameLine ? ", " : Environment.NewLine); + } + else + { + break; + } + } + } + } + else + { + for (; i < count; i++) + { + Variable arg = m_tuple[i]; + sb.Append(arg.AsString(isList, sameLine, maxCount)); + if (i != count - 1) + { + sb.Append(sameLine ? ", " : Environment.NewLine); + } + } + } + if (count < m_tuple.Count) + { + sb.Append(" ..."); + } + if (isList) + { + sb.Append(Constants.END_GROUP.ToString() + + (sameLine ? "" : Environment.NewLine)); + } + + return sb.ToString(); + } + + string ObjectToString() + { + StringBuilder sb = new StringBuilder(); + if (m_object != null) + { + sb.Append(m_object.ToString()); + } + else + { + sb.Append((m_object != null ? (m_object.ToString() + " ") : "") + Constants.START_GROUP.ToString()); + + List allProps = GetAllProperties(); + foreach (string prop in allProps) + { + if (prop == Constants.OBJECT_PROPERTIES) + { + sb.Append(prop); + continue; + } + Variable propValue = GetProperty(prop); + string value = ""; + if (propValue != null && propValue != Variable.EmptyInstance) + { + value = propValue.AsString(); + if (!string.IsNullOrEmpty(value)) + { + if (propValue.Type == VarType.STRING && prop != Constants.OBJECT_TYPE) + { + value = "\"" + value + "\""; + } + value = ": " + value; + } + } + sb.Append(prop + value + ", "); + } + + sb.Append(Constants.END_GROUP.ToString()); + } + return sb.ToString(); + } + + public void SetAsArray() + { + Type = VarType.ARRAY; + if (m_tuple == null) + { + m_tuple = new List(); + } + } + + public int Count + { + get { return Type == VarType.ARRAY ? m_tuple.Count : + Type == VarType.NONE ? 0 : 1; } + } + + public int TotalElements() + { + return Count; + } + + public Variable SetProperty(string propName, Variable value) + { + Variable result = Variable.EmptyInstance; + propName = Constants.ConvertName(propName); + + int ind = propName.IndexOf("."); + if (ind > 0) + { // The case a.b.c = ... is dealt here recursively + string varName = propName.Substring(0, ind); + string actualPropName = propName.Substring(ind + 1); + Variable property = GetProperty(varName); + result = property.SetProperty(actualPropName, value); + return result; + } + + m_propertyMap[propName] = value; + Type = VarType.OBJECT; + + if (Object is ScriptObject) + { + ScriptObject obj = Object as ScriptObject; + result = obj.SetProperty(propName, value).Result; + } + return result; + } + + public async Task SetPropertyAsync(string propName, Variable value) + { + Variable result = Variable.EmptyInstance; + propName = Constants.ConvertName(propName); + + int ind = propName.IndexOf("."); + if (ind > 0) + { // The case a.b.c = ... is dealt here recursively + string varName = propName.Substring(0, ind); + string actualPropName = propName.Substring(ind + 1); + Variable property = await GetPropertyAsync(varName); + result = await property.SetPropertyAsync(actualPropName, value); + return result; + } + + m_propertyMap[propName] = value; + Type = VarType.OBJECT; + + if (Object is ScriptObject) + { + ScriptObject obj = Object as ScriptObject; + result = await obj.SetProperty(propName, value); + } + return result; + } + + public Variable GetProperty(string propName, ParsingScript script = null) + { + Variable result = Variable.EmptyInstance; + + int ind = propName.IndexOf("."); + if (ind > 0) + { // The case x = a.b.c ... is dealt here recursively + string varName = propName.Substring(0, ind); + string actualPropName = propName.Substring(ind + 1); + Variable property = GetProperty(varName, script); + result = string.IsNullOrEmpty(actualPropName) ? property : + property.GetProperty(actualPropName, script); + return result; + } + + if (Object is ScriptObject) + { + ScriptObject obj = Object as ScriptObject; + string match = GetActualPropertyName(propName, obj.GetProperties()); + if (!string.IsNullOrWhiteSpace(match)) + { + List args = null; + if (script != null && script.TryPrev() == Constants.START_ARG) + { + args = script.GetFunctionArgs(); + } + else if (script != null) + { + args = new List(); + } + result = obj.GetProperty(match, args, script).Result; + if (result != null) + { + return result; + } + } + } + + if (m_propertyMap.TryGetValue(propName, out result)) + { + return result; + } + else if (propName.Equals(Constants.OBJECT_PROPERTIES, StringComparison.OrdinalIgnoreCase)) + { + return new Variable(GetProperties()); + } + else if (propName.Equals(Constants.OBJECT_TYPE, StringComparison.OrdinalIgnoreCase)) + { + return new Variable(GetTypeString()); + } + else if (propName.Equals(Constants.SIZE, StringComparison.OrdinalIgnoreCase)) + { + return new Variable(GetSize()); + } + + return result; + } + public async Task GetPropertyAsync(string propName, ParsingScript script = null) + { + Variable result = Variable.EmptyInstance; + + int ind = propName.IndexOf("."); + if (ind > 0) + { // The case x = a.b.c ... is dealt here recursively + string varName = propName.Substring(0, ind); + string actualPropName = propName.Substring(ind + 1); + Variable property = await GetPropertyAsync(varName, script); + result = string.IsNullOrEmpty(actualPropName) ? property : + await property.GetPropertyAsync(actualPropName, script); + return result; + } + + if (Object is ScriptObject) + { + ScriptObject obj = Object as ScriptObject; + var supported = obj.GetProperties(); + string match = GetActualPropertyName(propName, obj.GetProperties()); + if (!string.IsNullOrWhiteSpace(match)) + { + List args = null; + if (script != null && script.TryPrev() == Constants.START_ARG) + { + args = await script.GetFunctionArgsAsync(); + } + else if (script != null) + { + args = new List(); + } + result = await obj.GetProperty(match, args, script); + if (result != null) + { + return result; + } + } + } + + if (m_propertyMap.TryGetValue(propName, out result)) + { + return result; + } + else if (propName.Equals(Constants.OBJECT_PROPERTIES, StringComparison.OrdinalIgnoreCase)) + { + return new Variable(GetProperties()); + } + else if (propName.Equals(Constants.OBJECT_TYPE, StringComparison.OrdinalIgnoreCase)) + { + return new Variable(GetTypeString()); + } + else if (propName.Equals(Constants.SIZE, StringComparison.OrdinalIgnoreCase)) + { + return new Variable(GetSize()); + } + + return result; + } + + + public List GetProperties() + { + List all = GetAllProperties(); + List allVars = new List(all.Count); + foreach (string key in all) + { + allVars.Add(new Variable(key)); + } + + return allVars; + } + + public List GetAllProperties() + { + HashSet allSet = new HashSet(); + foreach (string key in m_propertyMap.Keys) + { + allSet.Add(key); + } + + if (Object is ScriptObject) + { + ScriptObject obj = Object as ScriptObject; + List objProps = obj.GetProperties(); + foreach (string key in objProps) + { + allSet.Add(key); + } + } + + List all = new List(allSet); + all.Sort(); + + if (!allSet.Contains(Constants.OBJECT_PROPERTIES)) + { + all.Add(Constants.OBJECT_PROPERTIES); + } + if (!allSet.Contains(Constants.OBJECT_TYPE)) + { + all.Insert(0, Constants.OBJECT_TYPE); + } + if (!allSet.Contains(Constants.SIZE)) + { + all.Insert(0, Constants.SIZE); + } + + return all; + } + + public int GetSize() + { + int size = Type == Variable.VarType.ARRAY ? + Tuple.Count : + AsString().Length; + return size; + } + + public virtual string GetTypeString() + { + if (Type == VarType.OBJECT && Object != null) + { + return Object.GetType().ToString(); + } + return Constants.TypeToString(Type); + } + + public Variable GetValue(int index) + { + if (index >= Count) + { + throw new ArgumentException("There are only [" + Count + + "] but " + index + " requested."); + + } + if (Type == VarType.ARRAY) + { + return m_tuple[index]; + } + return this; + } + + public static string GetActualPropertyName(string propName, List properties) + { + string match = properties.FirstOrDefault(element => element.Equals(propName, + StringComparison.OrdinalIgnoreCase)); + if (string.IsNullOrWhiteSpace(match)) + { + match = ""; + } + return match; + } + + public double Value + { + get { return m_value; } + set { m_value = value; Type = VarType.NUMBER; } + } + + public string String + { + get { return m_string; } + set { m_string = value; Type = VarType.STRING; } + } + + public object Object + { + get { return m_object; } + set { m_object = value; Type = VarType.OBJECT; } + } + + public List Tuple + { + get { return m_tuple; } + set { m_tuple = value; Type = VarType.ARRAY; } + } + + public string Action { get; set; } + public VarType Type { get; set; } + public bool IsReturn { get; set; } + public string ParsingToken { get; set; } + public int Index { get; set; } + public string CurrentAssign { get; set; } = ""; + + public static Variable EmptyInstance = new Variable(); + + double m_value; + string m_string; + object m_object; + List m_tuple; + Dictionary m_dictionary = new Dictionary(); + + Dictionary m_propertyMap = new Dictionary(); + } + + // A Variable supporting "dot-notation" must have an object implementing this interface. + public interface ScriptObject + { + // SetProperty is triggered by the following scripting call: "a.name = value;" + Task SetProperty(string name, Variable value); + + // GetProperty is triggered by the following scripting call: "x = a.name;" + // If args are null, it is triggered by object.ToString() function" + // If args are not empty, it is triggered by a function call: "y = a.name(arg1, arg2, ...);" + Task GetProperty(string name, List args = null, ParsingScript script = null); + + // Returns all of the properties that this object implements. Only these properties will be processed + // by SetProperty() and GetProperty() methods above. + List GetProperties(); + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `propName` last assigned on line 575 could be null and is dereferenced at line 577, column 13. + +### Severity: +ERROR + +### Procedure: +Variable Variable.SetProperty(String,Variable) + +### File: +cscs/Variable.cs + +### Key: +Variable.cs|SetProperty|NULL_DEREFERENCE + +### Node Key: +8f23c407fab7524e0704ad6f3b90d75b + +### Hash: +b3b54157226e4bc8306b2fdc6fe2fd57 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1886/instruction.md b/inferredbugs-1886/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..de82bf061dc3ef5432eb39b801af5505fe00bf3a --- /dev/null +++ b/inferredbugs-1886/instruction.md @@ -0,0 +1,2043 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cscs +**Bug ID:** 26 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Threading.Tasks; + +namespace SplitAndMerge +{ + class BreakStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.BREAK); + } + } + class ContinueStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.CONTINUE); + } + } + + class ReturnStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = Utils.GetItem(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = await Utils.GetItemAsync(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + } + + class TryBlock : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessTry(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessTryAsync(script); + } + } + + class ExitFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Environment.Exit(0); + return Variable.EmptyInstance; + } + } + + class ThrowFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = Utils.GetItem(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = await Utils.GetItemAsync(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + } + + class ShowFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + string funcName = args[0].AsString(); + + ParserFunction function = ParserFunction.GetFunction(funcName, script); + CustomFunction custFunc = function as CustomFunction; + Utils.CheckNotNull(funcName, custFunc); + + string body = Utils.BeautifyScript(custFunc.Body, custFunc.Header); + Utils.PrintScript(body, script); + + return new Variable(body); + } + } + + class FunctionCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string funcName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + funcName = Constants.ConvertName(funcName); + + string[] args = Utils.GetFunctionSignature(script); + if (args.Length == 1 && string.IsNullOrWhiteSpace(args[0])) + { + args = new string[0]; + } + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + int lineNumber = 0; + /*string line = */script.GetOriginalLine(out lineNumber); + + int parentOffset = script.Pointer; + + if (script.CurrentClass != null) + { + parentOffset += script.CurrentClass.ParentOffset; + } + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, Constants.END_GROUP); + + CustomFunction customFunc = new CustomFunction(funcName, body, args); + customFunc.ParentScript = script; + customFunc.ParentOffset = parentOffset; + + if (script.CurrentClass != null) + { + script.CurrentClass.AddMethod(funcName, args, customFunc); + } + else + { + ParserFunction.RegisterFunction(funcName, customFunc, false /* not native */); + } + + return Variable.EmptyInstance; + } + } + + public class CSCSClass : ParserFunction + { + public CSCSClass() {} + + public CSCSClass(string className) + { + m_name = className; + RegisterClass(className, this); + } + + public CSCSClass(string className, string[] baseClasses) + { + m_name = className; + RegisterClass(className, this); + + foreach (string baseClass in baseClasses) + { + var bc = CSCSClass.GetClass(baseClass); + if (bc == null) + { + throw new ArgumentException("Base Class [" + baseClass + "] not found."); + } + + foreach (var entry in bc.m_classProperties) + { + m_classProperties[entry.Key] = entry.Value; + } + foreach (var entry in bc.m_customFunctions) + { + m_customFunctions[entry.Key] = entry.Value; + } + } + } + + public static void RegisterClass(string className, CSCSClass obj) + { + className = Constants.ConvertName(className); + s_allClasses[className] = obj; + } + + protected override Variable Evaluate(ParsingScript script) + { + script.GetFunctionArgs(); + + // TODO: Work in progress, currently not functional + return Variable.EmptyInstance; + } + + public void AddMethod(string name, string[] args, CustomFunction method) + { + if (name == m_name) + { + m_constructors[args.Length] = method; + } + else + { + m_customFunctions[name] = method; + } + } + + public void AddProperty(string name, Variable property) + { + m_classProperties[name] = property; + } + + public static CSCSClass GetClass(string name) + { + CSCSClass theClass = null; + s_allClasses.TryGetValue(name, out theClass); + return theClass; + } + + static Dictionary s_allClasses = + new Dictionary(); + + Dictionary m_constructors = + new Dictionary(); + Dictionary m_customFunctions = + new Dictionary(); + Dictionary m_classProperties = + new Dictionary(); + + public ParsingScript ParentScript = null; + public int ParentOffset = 0; + + public class ClassInstance : ScriptObject + { + public ClassInstance(string instanceName, string className, List args, + ParsingScript script = null) + { + InstanceName = instanceName; + m_cscsClass = CSCSClass.GetClass(className); + if (m_cscsClass == null) + { + throw new ArgumentException("Class [" + className + "] not found."); + } + + // Copy over all the properties defined for this class. + foreach (var entry in m_cscsClass.m_classProperties) + { + SetProperty(entry.Key, entry.Value); + } + + // Run "constructor" if any is defined for this number of args. + CustomFunction constructor = null; + if (m_cscsClass.m_constructors.TryGetValue(args.Count, out constructor)) + { + constructor.Run(args, script, this); + } + } + + public string InstanceName { get; set; } + CSCSClass m_cscsClass; + + Dictionary m_properties = new Dictionary(); + HashSet m_propSet = new HashSet(); + + public async Task SetProperty(string name, Variable value) + { + m_properties[name] = value; + m_propSet.Add(name); + return Variable.EmptyInstance; + } + + public async Task GetProperty(string name, List args = null, ParsingScript script = null) + { + Variable value = null; + if (m_properties.TryGetValue(name, out value)) + { + return value; + } + + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out customFunction)) + { + return null; + } + if (args == null) + { + return Variable.EmptyInstance; + } + + foreach (var entry in m_cscsClass.m_classProperties) + { + args.Add(entry.Value); + } + + Variable result = await customFunction.RunAsync(args, script, this); + return result; + } + + public List> GetPropList() + { + List> props = new List>(); + foreach (var entry in m_properties) + { + props.Add(new KeyValuePair(entry.Key, entry.Value)); + } + return props; + } + + public List GetProperties() + { + List props = new List(m_properties.Keys); + props.AddRange(m_cscsClass.m_customFunctions.Keys); + + return props; + } + public bool PropertyExists(string name) + { + return m_propSet.Contains(name); + } + } + } + + class NewObjectFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = script.GetFunctionArgs(); + + CompiledClass csClass = CSCSClass.GetClass(className) as CompiledClass; + if (csClass != null) + { + ScriptObject obj = csClass.GetImplementation(args); + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = await script.GetFunctionArgsAsync(); + + CompiledClassAsync csClass = CSCSClass.GetClass(className) as CompiledClassAsync; + if (csClass != null) + { + ScriptObject obj = await csClass.GetImplementationAsync(args); + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + } + + public class ClassCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + string[] baseClasses = Utils.GetBaseClasses(script); + CSCSClass newClass = new CSCSClass(className, baseClasses); + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + + newClass.ParentOffset = script.Pointer; + newClass.ParentScript = script; + int lineNumber = 0; + /*string line = */script.GetOriginalLine(out lineNumber); + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + + Variable result = null; + ParsingScript tempScript = new ParsingScript(body); + //tempScript.ScriptOffset = newClass.ParentOffset; + tempScript.Char2Line = script.Char2Line; + tempScript.Filename = script.Filename; + tempScript.OriginalScript = script.OriginalScript; + tempScript.CurrentClass = newClass; + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.DisableBreakpoints = true; + + /*Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript); + }*/ + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + + return Variable.EmptyInstance; + } + } + + public class CustomFunction : ParserFunction + { + internal CustomFunction(string funcName, + string body, string[] args) + { + m_name = funcName; + m_body = body; + m_args = args; + + for (int i = 0; i < args.Length; i++) + { + string arg = args[i]; + int ind = arg.IndexOf("="); + if (ind > 0) + { + m_args[i] = arg.Substring(0, ind).Trim(); + string defValue = ind >= arg.Length - 1 ? "" : arg.Substring(ind + 1).Trim(); + if (defValue.StartsWith("\"")) + { + defValue = defValue.Substring(1); + } + if (defValue.EndsWith("\"")) + { + defValue = defValue.Substring(0, defValue.Length - 1); + } + Variable defVariable = new Variable(defValue); + defVariable.CurrentAssign = m_args[i]; + defVariable.Index = i; + m_defArgMap[i] = m_defaultArgs.Count; + m_defaultArgs.Add(defVariable); + } + m_argMap[m_args[i]] = i; + } + } + + public void RegisterArguments(List args, + List> args2 = null) + { + int missingArgs = m_args.Length - args.Count; + + bool namedParameters = false; + for (int i = 0; i < args.Count; i++) + { + var arg = args[i]; + int argIndex = -1; + if (m_argMap.TryGetValue(arg.CurrentAssign, out argIndex)) + { + namedParameters = true; + if (i != argIndex) + { + args[i] = argIndex < args.Count ? args[argIndex] : args[i]; + while (argIndex > args.Count - 1) + { + args.Add(Variable.EmptyInstance); + } + args[argIndex] = arg; + } + } + else if (namedParameters) + { + throw new ArgumentException("All arguments in function [" + m_name + + "] must be arg=value form."); + } + } + + if (missingArgs > 0 && missingArgs <= m_defaultArgs.Count) + { + if (!namedParameters) + { + for (int i = m_defaultArgs.Count - missingArgs; i < m_defaultArgs.Count; i++) + { + args.Add(m_defaultArgs[i]); + } + } + else + { + for (int i = 0; i < args.Count; i++) + { + if (args[i].Type == Variable.VarType.NONE || + (!string.IsNullOrWhiteSpace(args[i].CurrentAssign) && + args[i].CurrentAssign != m_args[i])) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args[i] = m_defaultArgs[defIndex]; + } + } + } + } + for (int i = args.Count; i < m_args.Length; i++) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args.Add(m_defaultArgs[defIndex]); + } + StackLevel stackLevel = new StackLevel(m_name); + + if (args2 != null) + { + foreach (var entry in args2) + { + var arg = new GetVarFunction(entry.Value); + arg.Name = entry.Key; + stackLevel.Variables[entry.Key] = arg; + } + } + + int maxSize = Math.Min(args.Count, m_args.Length); + for (int i = 0; i < maxSize; i++) + { + var arg = new GetVarFunction(args[i]); + arg.Name = m_args[i]; + stackLevel.Variables[m_args[i]] = arg; + } + + ParserFunction.AddLocalVariables(stackLevel); + } + + protected override Variable Evaluate(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + script.GetFunctionArgs(); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = Run(args, script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + await script.GetFunctionArgsAsync(); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = await RunAsync(args, script); + return result; + } + + public Variable Run(List args, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = new ParsingScript(m_body); + tempScript.ScriptOffset = m_parentOffset; + if (m_parentScript != null) + { + tempScript.Char2Line = m_parentScript.Char2Line; + tempScript.Filename = m_parentScript.Filename; + tempScript.OriginalScript = m_parentScript.OriginalScript; + } + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.ClassInstance = instance; + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + public async Task RunAsync(List args, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = new ParsingScript(m_body); + tempScript.ScriptOffset = m_parentOffset; + if (m_parentScript != null) + { + tempScript.Char2Line = m_parentScript.Char2Line; + tempScript.Filename = m_parentScript.Filename; + tempScript.OriginalScript = m_parentScript.OriginalScript; + } + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.ClassInstance = instance; + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = await debugger.StepInFunctionIfNeeded(tempScript); + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = await tempScript.ExecuteToAsync(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + + public static async Task Run(string functionName, Variable arg1 = null, Variable arg2 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + + Variable result = customFunction.Run(args); + return result; + } + public static async Task RunAsync(string functionName, Variable arg1 = null, Variable arg2 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + + Variable result = await customFunction.RunAsync(args); + return result; + } + + public ParsingScript ParentScript { set { m_parentScript = value; } } + public int ParentOffset { set { m_parentOffset = value; } } + public string Body { get { return m_body; } } + + public int ArgumentCount { get { return m_args.Length; } } + public string Argument(int nIndex) { return m_args[nIndex]; } + + public string Header + { + get + { + return Constants.FUNCTION + " " + Name + " " + + Constants.START_ARG + string.Join(", ", m_args) + + Constants.END_ARG + " " + Constants.START_GROUP; + } + } + + protected string m_body; + protected string[] m_args; + protected ParsingScript m_parentScript = null; + protected int m_parentOffset = 0; + + List m_defaultArgs = new List(); + Dictionary m_argMap = new Dictionary(); + Dictionary m_defArgMap = new Dictionary(); + } + + class StringOrNumberFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // First check if the passed expression is a string between quotes. + if (Item.Length > 1 && + Item[0] == Constants.QUOTE && + Item[Item.Length - 1] == Constants.QUOTE) + { + return new Variable(Item.Substring(1, Item.Length - 2)); + } + + // Otherwise this should be a number. + double num = Utils.ConvertToDouble(Item, script.OriginalLine); + return new Variable(num); + } + + public string Item { private get; set; } + } + + class AddFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + } + class RemoveFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + string varName = args[0].AsString(); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = args[1]; + + bool removed = currentValue.Tuple.Remove(item); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return new Variable(removed); + } + } + class RemoveAtFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = Utils.GetItem(script); + Utils.CheckNonNegativeInt(item); + + currentValue.Tuple.RemoveAt(item.AsInt()); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return Variable.EmptyInstance; + } + } + + class ContainsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + List arrayIndices = Utils.GetArrayIndices(script, varName, (newVarName) => { varName = newVarName; } ); + + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + + // 2b. Special dealings with arrays: + Variable query = arrayIndices.Count > 0 ? + Utils.ExtractArrayElement(currentValue, arrayIndices) : + currentValue; + + // 3. Get the value to be looked for. + Variable searchValue = Utils.GetItem(script); + Utils.CheckNotEnd(script, m_name); + + // 4. Check if the value to search for exists. + bool exists = query.Exists(searchValue, true /* notEmpty */); + + script.MoveBackIf(Constants.START_GROUP); + return new Variable(exists); + } + } + + class FindIndexFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable var = Utils.GetSafeVariable(args, 0); + string val = Utils.GetSafeString(args, 1); + + int index = var.FindIndex(val); + + return new Variable(index); + } + } + + class BoolFunction : ParserFunction, INumericFunction + { + bool m_value; + public BoolFunction(bool init) + { + m_value = init; + } + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(m_value); + } + } + class ToDoubleFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToDouble(arg.AsString()); + return new Variable(result); + } + } + class ToIntFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + int result = Utils.ConvertToInt(arg.AsString()); + return new Variable(result); + } + } + class ToBoolFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToBool(arg.AsString()) ? 1 : 0; + return new Variable(result); + } + } + class ToDecimalFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = Decimal.Parse(arg.AsString(), NumberStyles.Any).ToString(); + return new Variable(result); + } + } + class ToStringFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = arg.AsString(); + return new Variable(result); + } + } + class IdentityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return script.ExecuteTo(Constants.END_ARG); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await script.ExecuteToAsync(Constants.END_ARG); + } + } + + class IfStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable result = Interpreter.Instance.ProcessIf(script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + Variable result = await Interpreter.Instance.ProcessIfAsync(script); + return result; + } + } + + class ForStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessFor(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessForAsync(script); + } + } + + class WhileStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessWhile(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessWhileAsync(script); + } + } + + class IncludeFile : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + string includeScript; + ParsingScript tempScript = GetIncludeFileScript(script, args, out includeScript); + + Variable result = null; + if (script.Debugger != null) + { + result = script.Debugger.StepInIncludeIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < includeScript.Length) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + string includeScript; + ParsingScript tempScript = GetIncludeFileScript(script, args, out includeScript); + + Variable result = null; + if (script.Debugger != null) + { + result = await script.Debugger.StepInIncludeIfNeeded(tempScript); + } + + while (tempScript.Pointer < includeScript.Length) + { + result = await tempScript.ExecuteToAsync(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + + ParsingScript GetIncludeFileScript(ParsingScript script, List args, out string includeScript) + { + Utils.CheckArgs(args.Count, 1, m_name, true); + + string filename = args[0].AsString(); + string pathname = script.GetFilePath(filename); + string[] lines = Utils.GetFileLines(pathname); + + string includeFile = string.Join(Environment.NewLine, lines); + Dictionary char2Line; + includeScript = Utils.ConvertToScript(includeFile, out char2Line); + ParsingScript tempScript = new ParsingScript(includeScript, 0, char2Line); + tempScript.Filename = filename; + tempScript.OriginalScript = string.Join(Constants.END_LINE.ToString(), lines); + tempScript.ParentScript = script; + tempScript.InTryBlock = script.InTryBlock; + + return tempScript; + } + } + + // Get a value of a variable or of an array element + public class GetVarFunction : ParserFunction + { + public GetVarFunction(Variable value) + { + m_value = value; + } + + protected override Variable Evaluate(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = Utils.GetArrayIndices(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; } ); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices); + return result; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + Variable propValue = m_value.GetProperty(m_propName, script); + string temp = m_propName; + m_propName = null; // Need this trick in case the below statement throws + Utils.CheckNotNull(propValue, temp); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = await Utils.GetArrayIndicesAsync(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; }); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices); + return result; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + Variable propValue = await m_value.GetPropertyAsync(m_propName, script); + string temp = m_propName; + m_propName = null; // Need this trick in case the below statement throws + Utils.CheckNotNull(propValue, temp); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + + public int Delta + { + set { m_delta = value; } + } + public Variable Value + { + get { return m_value; } + } + public List Indices + { + set { m_arrayIndices = value; } + } + public string PropertyName + { + set { m_propName = value; } + } + + Variable m_value; + int m_delta = 0; + List m_arrayIndices = null; + string m_propName; + } + class IncrementDecrementFunction : ActionFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool prefix = string.IsNullOrWhiteSpace(m_name); + if (prefix) + {// If it is a prefix we do not have the variable name yet. + m_name = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + } + + // Value to be added to the variable: + int valueDelta = m_action == Constants.INCREMENT ? 1 : -1; + int returnDelta = prefix ? valueDelta : 0; + + // Check if the variable to be set has the form of x[a][b], + // meaning that this is an array element. + double newValue = 0; + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetFunction(m_name, script); + Utils.CheckNotNull(m_name, func); + + Variable currentValue = func.GetValue(script); + + if (arrayIndices.Count > 0 || script.TryCurrent() == Constants.START_ARRAY) + { + if (prefix) + { + string tmpName = m_name + script.Rest; + int delta = 0; + arrayIndices = Utils.GetArrayIndices(script, tmpName, delta, (string t, int d) => { tmpName = t; delta = d; }); + script.Forward(Math.Max(0, delta - tmpName.Length)); + } + + Variable element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + + newValue = element.Value + returnDelta; + element.Value += valueDelta; + } + else + { // A normal variable. + newValue = currentValue.Value + returnDelta; + currentValue.Value += valueDelta; + } + + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + return new Variable(newValue); + } + + override public ParserFunction NewInstance() + { + return new IncrementDecrementFunction(); + } + } + + class OperatorAssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // Value to be added to the variable: + Variable right = Utils.GetItem(script); + + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetFunction(m_name, script); + Utils.CheckNotNull(m_name, func); + + Variable currentValue = func.GetValue(script); + Variable left = currentValue; + + if (arrayIndices.Count > 0) + {// array element + left = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + if (left.Type == Variable.VarType.NUMBER) + { + NumberOperator(left, right, m_action); + } + else + { + StringOperator(left, right, m_action); + } + + if (arrayIndices.Count > 0) + {// array element + AssignFunction.ExtendArray(currentValue, arrayIndices, 0, left); + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + } + else + { + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(left)); + } + return left; + } + + static void NumberOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + valueA.Value += valueB.Value; + break; + case "-=": + valueA.Value -= valueB.Value; + break; + case "*=": + valueA.Value *= valueB.Value; + break; + case "/=": + valueA.Value /= valueB.Value; + break; + case "%=": + valueA.Value %= valueB.Value; + break; + case "&=": + valueA.Value = (int)valueA.Value & (int)valueB.Value; + break; + case "|=": + valueA.Value = (int)valueA.Value | (int)valueB.Value; + break; + case "^=": + valueA.Value = (int)valueA.Value ^ (int)valueB.Value; + break; + } + } + static void StringOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + if (valueB.Type == Variable.VarType.STRING) + { + valueA.String += valueB.AsString(); + } + else + { + valueA.String += valueB.Value; + } + break; + } + } + + override public ParserFunction NewInstance() + { + return new OperatorAssignFunction(); + } + } + + class AssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.CurrentAssign = m_name; + Variable varValue = Utils.GetItem(script); + + // First try processing as an object (with a dot notation): + Variable result = ProcessObject(script, varValue); + if (result != null) + { + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue)); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + //return varValue.DeepClone(); + } + + Variable array; + + ParserFunction pf = ParserFunction.GetFunction(m_name, script); + if (pf != null) + { + array = pf.GetValue(script); + } + else + { + array = new Variable(); + } + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array)); + return array; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + script.CurrentAssign = m_name; + Variable varValue = await Utils.GetItemAsync(script); + + // First try processing as an object (with a dot notation): + Variable result = await ProcessObjectAsync(script, varValue); + if (result != null) + { + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = await Utils.GetArrayIndicesAsync(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue)); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + //return varValue.DeepClone(); + } + + Variable array; + + ParserFunction pf = ParserFunction.GetFunction(m_name, script); + if (pf != null) + { + array = await pf.GetValueAsync(script); + } + else + { + array = new Variable(); + } + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array)); + return array; + } + + Variable ProcessObject(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + varValue = script.ClassInstance.SetProperty(m_name, varValue).Result; + return varValue.DeepClone(); + } + + int ind = varName.IndexOf("."); + if (ind <= 0) + { + return null; + } + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + ParserFunction existing = ParserFunction.GetFunction(name, script); + Variable baseValue = existing != null ? existing.GetValue(script) : new Variable(Variable.VarType.ARRAY); + baseValue.SetProperty(prop, varValue); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue)); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + async Task ProcessObjectAsync(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + await script.ClassInstance.SetProperty(m_name, varValue); + return varValue.DeepClone(); + } + + int ind = varName.IndexOf("."); + if (ind <= 0) + { + return null; + } + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + ParserFunction existing = ParserFunction.GetFunction(name, script); + Variable baseValue = existing != null ? await existing.GetValueAsync(script) : new Variable(Variable.VarType.ARRAY); + await baseValue.SetPropertyAsync(prop, varValue); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue)); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + + + override public ParserFunction NewInstance() + { + return new AssignFunction(); + } + + public static void ExtendArray(Variable parent, + List arrayIndices, + int indexPtr, + Variable varValue) + { + if (arrayIndices.Count <= indexPtr) + { + return; + } + + Variable index = arrayIndices[indexPtr]; + int currIndex = ExtendArrayHelper(parent, index); + + if (arrayIndices.Count - 1 == indexPtr) + { + parent.Tuple[currIndex] = varValue; + return; + } + + Variable son = parent.Tuple[currIndex]; + ExtendArray(son, arrayIndices, indexPtr + 1, varValue); + } + + private static int ExtendArrayHelper(Variable parent, Variable indexVar) + { + parent.SetAsArray(); + + int arrayIndex = parent.GetArrayIndex(indexVar); + if (arrayIndex < 0) + { + // This is not a "normal index" but a new string for the dictionary. + string hash = indexVar.AsString(); + arrayIndex = parent.SetHashVariable(hash, Variable.NewEmpty()); + return arrayIndex; + } + + if (parent.Tuple.Count <= arrayIndex) + { + for (int i = parent.Tuple.Count; i <= arrayIndex; i++) + { + parent.Tuple.Add(Variable.NewEmpty()); + } + } + return arrayIndex; + } + } + + class DeepCopyFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varValue = Utils.GetItem(script); + return varValue.DeepClone(); ; + } + } + + class TokenizeLinesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2, 0); + string sepStr = Utils.GetSafeString(args, 3, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + // var function = ParserFunction.GetFunction(varName, script); + Variable allTokensVar = new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; +#pragma warning disable 219 + // bugbug - the toAdd has side effects + Variable toAdd = new Variable(counter - fromLine); +#pragma warning restore 219 + string line = lineVar.AsString(); + var tokens = line.Split(sep); + Variable tokensVar = new Variable(Variable.VarType.ARRAY); + foreach (string token in tokens) + { + tokensVar.Tuple.Add(new Variable(token)); + } + allTokensVar.Tuple.Add(tokensVar); + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(allTokensVar)); + + return Variable.EmptyInstance; + } + } + + class AddVariablesToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2); + string hash2 = Utils.GetSafeString(args, 3); + string sepStr = Utils.GetSafeString(args, 4, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; + Variable toAdd = new Variable(counter - fromLine); + string line = lineVar.AsString(); + var tokens = line.Split(sep); + string hash = tokens[0]; + mapVar.AddVariableToHash(hash, toAdd); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + return Variable.EmptyInstance; + } + } + class AddVariableToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable toAdd = Utils.GetSafeVariable(args, 1); + string hash = Utils.GetSafeString(args, 2); + + var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + mapVar.AddVariableToHash(hash, toAdd); + for (int i = 3; i < args.Count; i++) + { + string hash2 = Utils.GetSafeString(args, 3); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + + return Variable.EmptyInstance; + } + } + class TokenCounterFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable all = Utils.GetSafeVariable(args, 0); + string varName = Utils.GetSafeString(args, 1); + int index = Utils.GetSafeInt(args, 2); + + // var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = new Variable(Variable.VarType.ARRAY); + + if (all.Tuple == null) + { + return Variable.EmptyInstance; + } + + string currentValue = ""; + int currentCount = 0; + + int globalCount = 0; + + for (int i = 0; i < all.Tuple.Count; i++) + { + Variable current = all.Tuple[i]; + if (current.Tuple == null || current.Tuple.Count < index) + { + break; + } + string newValue = current.Tuple[index].AsString(); + if (currentValue != newValue) + { + currentValue = newValue; + currentCount = 0; + } + mapVar.Tuple.Add(new Variable(currentCount)); + currentCount++; + globalCount++; + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + // Script - Need to enable the warnings +#pragma warning restore 219 + return mapVar; + } + } + + class TypeFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + bool complexVariable = Utils.GetSafeInt(args, 1, 0) == 1; + Variable element = null; + if (complexVariable) + { + element = Utils.GetVariable(args[0].AsString(), script, false); + } + if (element == null) + { + element = Utils.GetSafeVariable(args, 0); + } + + string type = element.GetTypeString(); + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(type); + return newValue; + } + } + + class SizeFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.END_ARG_ARRAY); + Utils.CheckNotEnd(script, m_name); + + List arrayIndices = Utils.GetArrayIndices(script, varName, (newName) => { varName = newName; } ); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Variable element = currentValue; + + // 2b. Special case for an array. + if (arrayIndices.Count > 0) + {// array element + element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + // 3. Take either the length of the underlying tuple or + // string part if it is defined, + // or the numerical part converted to a string otherwise. + int size = element.GetSize(); + + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(size); + return newValue; + } + } + + class DefineLocalFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable currentValue = Utils.GetSafeVariable(args, 1); + + if (currentValue == null) + { + currentValue = new Variable(""); + } + + string scopeName = Path.GetFileName(script.Filename); + ParserFunction.AddLocalScopeVariable(varName, scopeName, + new GetVarFunction(currentValue)); + + return currentValue; + } + } + + class GetPropertiesFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + Variable baseValue = args[0]; + List props = baseValue.GetProperties(); + return new Variable(props); + } + } + + class GetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = baseValue.GetProperty(propName, script); + Utils.CheckNotNull(propValue, propName); + + return new Variable(propValue); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = await baseValue.GetPropertyAsync(propName, script); + Utils.CheckNotNull(propValue, propName); + + return new Variable(propValue); + } + public static Variable GetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = baseValue.GetProperty(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName); + + return new Variable(propValue); + } + public static async Task GetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = await baseValue.GetPropertyAsync(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName); + + return new Variable(propValue); + } + } + + class SetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = baseValue.SetProperty(propName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = await baseValue.SetPropertyAsync(propName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + + public static Variable SetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = baseValue.SetProperty(sPropertyName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + public static async Task SetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = await baseValue.SetPropertyAsync(sPropertyName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + } + + class CancelFunction : ParserFunction + { + public static bool Canceled { get; set; } + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 0, m_name, true); + + bool mode = Utils.GetSafeInt(args, 0, 1) == 1; + Canceled = mode; + + return new Variable(Canceled); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `all` last assigned on line 2619 could be null and is dereferenced at line 2626, column 13. + +### Severity: +ERROR + +### Procedure: +Variable TokenCounterFunction.Evaluate(ParsingScript) + +### File: +cscs/Functions.Flow.cs + +### Key: +Functions.Flow.cs|Evaluate|NULL_DEREFERENCE + +### Node Key: +bef2fe14012af516d6c7bc5d1bd471c5 + +### Hash: +b0f56c2b42f5b0422f61218dea743349 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1888/instruction.md b/inferredbugs-1888/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3686db32278a1b14882ac61a49aac868febfd39 --- /dev/null +++ b/inferredbugs-1888/instruction.md @@ -0,0 +1,1598 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cscs +**Bug ID:** 21 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; + +namespace SplitAndMerge +{ + class BreakStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.BREAK); + } + } + class ContinueStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.CONTINUE); + } + } + + class ReturnStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = Utils.GetItem(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + } + + class TryBlock : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessTry(script); + } + } + + class ExitFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Environment.Exit(0); + return Variable.EmptyInstance; + } + } + + class ThrowFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = Utils.GetItem(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + } + + class ShowFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + string funcName = args[0].AsString(); + + ParserFunction function = ParserFunction.GetFunction(funcName, script); + CustomFunction custFunc = function as CustomFunction; + Utils.CheckNotNull(funcName, custFunc); + + string body = Utils.BeautifyScript(custFunc.Body, custFunc.Header); + Utils.PrintScript(body, script); + + return new Variable(body); + } + } + + class FunctionCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string funcName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + //Interpreter.Instance.AppendOutput("Registering function [" + funcName + "] ..."); + + string[] args = Utils.GetFunctionSignature(script); + if (args.Length == 1 && string.IsNullOrWhiteSpace(args[0])) + { + args = new string[0]; + } + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + int lineNumber = 0; + /*string line = */script.GetOriginalLine(out lineNumber); + + int parentOffset = script.Pointer; + + if (script.CurrentClass != null) + { + parentOffset += script.CurrentClass.ParentOffset; + } + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, Constants.END_GROUP); + + CustomFunction customFunc = new CustomFunction(funcName, body, args); + customFunc.ParentScript = script; + customFunc.ParentOffset = parentOffset; + + if (script.CurrentClass != null) + { + script.CurrentClass.AddMethod(funcName, args, customFunc); + } + else + { + ParserFunction.RegisterFunction(funcName, customFunc, false /* not native */); + } + + return Variable.EmptyInstance; + } + } + + public class CSCSClass : ParserFunction + { + public CSCSClass(string className, string[] baseClasses) + { + m_name = className; + s_allClasses[className] = this; + + foreach (string baseClass in baseClasses) + { + var bc = CSCSClass.GetClass(baseClass); + if (bc == null) + { + throw new ArgumentException("Base Class [" + baseClass + "] not found."); + } + + foreach (var entry in bc.m_classProperties) + { + m_classProperties[entry.Key] = entry.Value; + } + foreach (var entry in bc.m_customFunctions) + { + m_customFunctions[entry.Key] = entry.Value; + } + } + } + + protected override Variable Evaluate(ParsingScript script) + { + script.GetFunctionArgs(); + + // TODO: Work in progress, currently not functional + return Variable.EmptyInstance; + } + + public void AddMethod(string name, string[] args, CustomFunction method) + { + if (name == m_name) + { + m_constructors[args.Length] = method; + } + else + { + m_customFunctions[name] = method; + } + } + + public void AddProperty(string name, Variable property) + { + m_classProperties[name] = property; + } + + public static CSCSClass GetClass(string name) + { + CSCSClass theClass = null; + s_allClasses.TryGetValue(name, out theClass); + return theClass; + } + + static Dictionary s_allClasses = + new Dictionary(); + + Dictionary m_constructors = + new Dictionary(); + Dictionary m_customFunctions = + new Dictionary(); + Dictionary m_classProperties = + new Dictionary(); + + public ParsingScript ParentScript = null; + public int ParentOffset = 0; + + public class ClassInstance : ScriptObject + { + public ClassInstance(string instanceName, string className, List args, + ParsingScript script = null) + { + InstanceName = instanceName; + m_cscsClass = CSCSClass.GetClass(className); + if (m_cscsClass == null) + { + throw new ArgumentException("Class [" + className + "] not found."); + } + + // Copy over all the properties defined for this class. + foreach (var entry in m_cscsClass.m_classProperties) + { + SetProperty(entry.Key, entry.Value); + } + + // Run "constructor" if any is defined for this number of args. + CustomFunction constructor = null; + if (m_cscsClass.m_constructors.TryGetValue(args.Count, out constructor)) + { + constructor.Run(args, script, this); + } + } + + public string InstanceName { get; set; } + CSCSClass m_cscsClass; + + Dictionary m_properties = new Dictionary(); + HashSet m_propSet = new HashSet(); + + public Variable SetProperty(string name, Variable value) + { + m_properties[name] = value; + m_propSet.Add(name); + return Variable.EmptyInstance; + } + + public Variable GetProperty(string name, List args = null, ParsingScript script = null) + { + Variable value = null; + if (m_properties.TryGetValue(name, out value)) + { + return value; + } + + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out customFunction)) + { + return null; + } + if (args == null) + { + return Variable.EmptyInstance; + } + + foreach (var entry in m_cscsClass.m_classProperties) + { + args.Add(entry.Value); + } + + Variable result = customFunction.Run(args, script, this); + return result; + } + + public List> GetPropList() + { + List> props = new List>(); + foreach (var entry in m_properties) + { + props.Add(new KeyValuePair(entry.Key, entry.Value)); + } + return props; + } + + public List GetProperties() + { + List props = new List(m_properties.Keys); + props.AddRange(m_cscsClass.m_customFunctions.Keys); + + return props; + } + public bool PropertyExists(string name) + { + return m_propSet.Contains(name); + } + } + } + + class NewObjectFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + script.MoveForwardIf(Constants.START_ARG); + List args = script.GetFunctionArgs(); + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + Variable value = new Variable(instance); + + return value; + } + } + + public class ClassCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + string[] baseClasses = Utils.GetBaseClasses(script); + CSCSClass newClass = new CSCSClass(className, baseClasses); + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + + newClass.ParentOffset = script.Pointer; + newClass.ParentScript = script; + int lineNumber = 0; + /*string line = */script.GetOriginalLine(out lineNumber); + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + + Variable result = null; + ParsingScript tempScript = new ParsingScript(body); + //tempScript.ScriptOffset = newClass.ParentOffset; + tempScript.Char2Line = script.Char2Line; + tempScript.Filename = script.Filename; + tempScript.OriginalScript = script.OriginalScript; + tempScript.CurrentClass = newClass; + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.DisableBreakpoints = true; + + /*Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript); + }*/ + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + + return Variable.EmptyInstance; + } + } + + public class CustomFunction : ParserFunction + { + internal CustomFunction(string funcName, + string body, string[] args) + { + m_name = funcName; + m_body = body; + m_args = args; + + for (int i = 0; i < args.Length; i++) + { + string arg = args[i]; + int ind = arg.IndexOf("="); + if (ind > 0) + { + m_args[i] = arg.Substring(0, ind).Trim(); + string defValue = ind >= arg.Length - 1 ? "" : arg.Substring(ind + 1).Trim(); + if (defValue.StartsWith("\"")) + { + defValue = defValue.Substring(1); + } + if (defValue.EndsWith("\"")) + { + defValue = defValue.Substring(0, defValue.Length - 1); + } + m_defaultArgs.Add(new Variable(defValue)); + } + } + } + + public void RegisterArguments(List args, + List> args2 = null) + { + int missingArgs = m_args.Length - args.Count; + if (missingArgs > 0 && missingArgs <= m_defaultArgs.Count) + { + for (int i = m_defaultArgs.Count - missingArgs; i < m_defaultArgs.Count; i++) + { + args.Add(m_defaultArgs[i]); + } + } + + StackLevel stackLevel = new StackLevel(m_name); + + if (args2 != null) + { + foreach (var entry in args2) + { + var arg = new GetVarFunction(entry.Value); + arg.Name = entry.Key; + stackLevel.Variables[entry.Key] = arg; + } + } + + int maxSize = Math.Min(args.Count, m_args.Length); + for (int i = 0; i < maxSize; i++) + { + var arg = new GetVarFunction(args[i]); + arg.Name = m_args[i]; + stackLevel.Variables[m_args[i]] = arg; + } + + ParserFunction.AddLocalVariables(stackLevel); + } + + protected override Variable Evaluate(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + script.GetFunctionArgs(); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = Run(args, script); + return result; + } + + public Variable Run(List args, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = new ParsingScript(m_body); + tempScript.ScriptOffset = m_parentOffset; + if (m_parentScript != null) + { + tempScript.Char2Line = m_parentScript.Char2Line; + tempScript.Filename = m_parentScript.Filename; + tempScript.OriginalScript = m_parentScript.OriginalScript; + } + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.ClassInstance = instance; + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript); + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + + public static Variable Run(string functionName, Variable arg1 = null, Variable arg2 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + + Variable result = customFunction.Run(args); + return result; + } + + public ParsingScript ParentScript { set { m_parentScript = value; } } + public int ParentOffset { set { m_parentOffset = value; } } + public string Body { get { return m_body; } } + + public int ArgumentCount { get { return m_args.Length; } } + public string Argument(int nIndex) { return m_args[nIndex]; } + + public string Header + { + get + { + return Constants.FUNCTION + " " + Name + " " + + Constants.START_ARG + string.Join(", ", m_args) + + Constants.END_ARG + " " + Constants.START_GROUP; + } + } + + protected string m_body; + protected string[] m_args; + List m_defaultArgs = new List(); + protected ParsingScript m_parentScript = null; + protected int m_parentOffset = 0; + } + + class StringOrNumberFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // First check if the passed expression is a string between quotes. + if (Item.Length > 1 && + Item[0] == Constants.QUOTE && + Item[Item.Length - 1] == Constants.QUOTE) + { + return new Variable(Item.Substring(1, Item.Length - 2)); + } + + // Otherwise this should be a number. + double num = Utils.ConvertToDouble(Item, "StringOrNumber"); + /*if (!Double.TryParse(Item, NumberStyles.Number | + NumberStyles.AllowExponent | + NumberStyles.Float, + CultureInfo.InvariantCulture, out num)) { + Utils.ThrowException(script, "parseToken", Item, "parseTokenExtra"); + }*/ + return new Variable(num); + } + + public string Item { private get; set; } + } + + class AddFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + } + class RemoveFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + string varName = args[0].AsString(); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = args[1]; + + bool removed = currentValue.Tuple.Remove(item); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return new Variable(removed); + } + } + class RemoveAtFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = Utils.GetItem(script); + Utils.CheckNonNegativeInt(item); + + currentValue.Tuple.RemoveAt(item.AsInt()); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return Variable.EmptyInstance; + } + } + + class ContainsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + List arrayIndices = Utils.GetArrayIndices(script, ref varName); + + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + + // 2b. Special dealings with arrays: + Variable query = arrayIndices.Count > 0 ? + Utils.ExtractArrayElement(currentValue, arrayIndices) : + currentValue; + + // 3. Get the value to be looked for. + Variable searchValue = Utils.GetItem(script); + Utils.CheckNotEnd(script, m_name); + + // 4. Check if the value to search for exists. + bool exists = query.Exists(searchValue, true /* notEmpty */); + + script.MoveBackIf(Constants.START_GROUP); + return new Variable(exists); + } + } + + class FindIndexFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable var = Utils.GetSafeVariable(args, 0); + string val = Utils.GetSafeString(args, 1); + + int index = var.FindIndex(val); + + return new Variable(index); + } + } + + class BoolFunction : ParserFunction, INumericFunction + { + bool m_value; + public BoolFunction(bool init) + { + m_value = init; + } + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(m_value); + } + } + class ToDoubleFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToDouble(arg.AsString()); + return new Variable(result); + } + } + class ToIntFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + int result = Utils.ConvertToInt(arg.AsString()); + return new Variable(result); + } + } + class ToBoolFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToBool(arg.AsString()) ? 1 : 0; + return new Variable(result); + } + } + class ToDecimalFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = Decimal.Parse(arg.AsString(), NumberStyles.Any).ToString(); + return new Variable(result); + } + } + class ToStringFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = arg.AsString(); + return new Variable(result); + } + } + class IdentityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return script.ExecuteTo(Constants.END_ARG); + } + } + + class IfStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable result = Interpreter.Instance.ProcessIf(script); + return result; + } + } + + class ForStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessFor(script); + } + } + + class WhileStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessWhile(script); + } + } + + class IncludeFile : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + string filename = args[0].AsString(); + string[] lines = Utils.GetFileLines(filename); + + string includeFile = string.Join(Environment.NewLine, lines); + Dictionary char2Line; + string includeScript = Utils.ConvertToScript(includeFile, out char2Line); + ParsingScript tempScript = new ParsingScript(includeScript, 0, char2Line); + tempScript.Filename = filename; + tempScript.OriginalScript = string.Join(Constants.END_LINE.ToString(), lines); + tempScript.ParentScript = script; + tempScript.InTryBlock = script.InTryBlock; + + Variable result = null; + if (script.Debugger != null) + { + result = script.Debugger.StepInIncludeIfNeeded(tempScript); + } + + while (tempScript.Pointer < includeScript.Length) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + } + + // Get a value of a variable or of an array element + public class GetVarFunction : ParserFunction + { + public GetVarFunction(Variable value) + { + m_value = value; + } + + protected override Variable Evaluate(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = Utils.GetArrayIndices(script, ref startName, ref m_delta); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices); + return result; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + Variable propValue = m_value.GetProperty(m_propName, script); + string temp = m_propName; + m_propName = null; // Need this trick in case the below statement throws + Utils.CheckNotNull(propValue, temp); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + + public int Delta + { + set { m_delta = value; } + } + public Variable Value + { + get { return m_value; } + } + public List Indices + { + set { m_arrayIndices = value; } + } + public string PropertyName + { + set { m_propName = value; } + } + + Variable m_value; + int m_delta = 0; + List m_arrayIndices = null; + string m_propName; + } + class IncrementDecrementFunction : ActionFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool prefix = string.IsNullOrWhiteSpace(m_name); + if (prefix) + {// If it is a prefix we do not have the variable name yet. + m_name = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + } + + // Value to be added to the variable: + int valueDelta = m_action == Constants.INCREMENT ? 1 : -1; + int returnDelta = prefix ? valueDelta : 0; + + // Check if the variable to be set has the form of x[a][b], + // meaning that this is an array element. + double newValue = 0; + List arrayIndices = Utils.GetArrayIndices(script, ref m_name); + + ParserFunction func = ParserFunction.GetFunction(m_name, script); + Utils.CheckNotNull(m_name, func); + + Variable currentValue = func.GetValue(script); + + if (arrayIndices.Count > 0 || script.TryCurrent() == Constants.START_ARRAY) + { + if (prefix) + { + string tmpName = m_name + script.Rest; + int delta = 0; + arrayIndices = Utils.GetArrayIndices(script, ref tmpName, ref delta); + script.Forward(Math.Max(0, delta - tmpName.Length)); + } + + Variable element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + + newValue = element.Value + returnDelta; + element.Value += valueDelta; + } + else + { // A normal variable. + newValue = currentValue.Value + returnDelta; + currentValue.Value += valueDelta; + } + + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + return new Variable(newValue); + } + + override public ParserFunction NewInstance() + { + return new IncrementDecrementFunction(); + } + } + + class OperatorAssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // Value to be added to the variable: + Variable right = Utils.GetItem(script); + + List arrayIndices = Utils.GetArrayIndices(script, ref m_name); + + ParserFunction func = ParserFunction.GetFunction(m_name, script); + Utils.CheckNotNull(m_name, func); + + Variable currentValue = func.GetValue(script); + Variable left = currentValue; + + if (arrayIndices.Count > 0) + {// array element + left = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + if (left.Type == Variable.VarType.NUMBER) + { + NumberOperator(left, right, m_action); + } + else + { + StringOperator(left, right, m_action); + } + + if (arrayIndices.Count > 0) + {// array element + AssignFunction.ExtendArray(currentValue, arrayIndices, 0, left); + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + } + else + { + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(left)); + } + return left; + } + + static void NumberOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + valueA.Value += valueB.Value; + break; + case "-=": + valueA.Value -= valueB.Value; + break; + case "*=": + valueA.Value *= valueB.Value; + break; + case "/=": + valueA.Value /= valueB.Value; + break; + case "%=": + valueA.Value %= valueB.Value; + break; + case "&=": + valueA.Value = (int)valueA.Value & (int)valueB.Value; + break; + case "|=": + valueA.Value = (int)valueA.Value | (int)valueB.Value; + break; + case "^=": + valueA.Value = (int)valueA.Value ^ (int)valueB.Value; + break; + } + } + static void StringOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + if (valueB.Type == Variable.VarType.STRING) + { + valueA.String += valueB.AsString(); + } + else + { + valueA.String += valueB.Value; + } + break; + } + } + + override public ParserFunction NewInstance() + { + return new OperatorAssignFunction(); + } + } + + class AssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.CurrentAssign = m_name; + Variable varValue = Utils.GetItem(script); + // First try processing as an object (with a dot notation): + Variable result = ProcessObject(script, varValue); + if (result != null) + { + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = Utils.GetArrayIndices(script, ref m_name); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue)); + return varValue.DeepClone(); + } + + Variable array; + + ParserFunction pf = ParserFunction.GetFunction(m_name, script); + if (pf != null) + { + array = pf.GetValue(script); + } + else + { + array = new Variable(); + } + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array)); + return array; + } + + Variable ProcessObject(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + script.ClassInstance.SetProperty(m_name, varValue); + return varValue.DeepClone(); + } + + int ind = varName.IndexOf("."); + if (ind <= 0) + { + return null; + } + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + ParserFunction existing = ParserFunction.GetFunction(name, script); + Variable baseValue = existing != null ? existing.GetValue(script) : new Variable(Variable.VarType.ARRAY); + baseValue.SetProperty(prop, varValue); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue)); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + + override public ParserFunction NewInstance() + { + return new AssignFunction(); + } + + public static void ExtendArray(Variable parent, + List arrayIndices, + int indexPtr, + Variable varValue) + { + if (arrayIndices.Count <= indexPtr) + { + return; + } + + Variable index = arrayIndices[indexPtr]; + int currIndex = ExtendArrayHelper(parent, index); + + if (arrayIndices.Count - 1 == indexPtr) + { + parent.Tuple[currIndex] = varValue; + return; + } + + Variable son = parent.Tuple[currIndex]; + ExtendArray(son, arrayIndices, indexPtr + 1, varValue); + } + + private static int ExtendArrayHelper(Variable parent, Variable indexVar) + { + parent.SetAsArray(); + + int arrayIndex = parent.GetArrayIndex(indexVar); + if (arrayIndex < 0) + { + // This is not a "normal index" but a new string for the dictionary. + string hash = indexVar.AsString(); + arrayIndex = parent.SetHashVariable(hash, Variable.NewEmpty()); + return arrayIndex; + } + + if (parent.Tuple.Count <= arrayIndex) + { + for (int i = parent.Tuple.Count; i <= arrayIndex; i++) + { + parent.Tuple.Add(Variable.NewEmpty()); + } + } + return arrayIndex; + } + } + + class DeepCopyFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varValue = Utils.GetItem(script); + return varValue.DeepClone(); ; + } + } + + class TokenizeLinesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2); + string sepStr = Utils.GetSafeString(args, 3, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + // var function = ParserFunction.GetFunction(varName, script); + Variable allTokensVar = new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; +#pragma warning disable 219 + // bugbug - the toAdd has side effects + Variable toAdd = new Variable(counter - fromLine); +#pragma warning restore 219 + string line = lineVar.AsString(); + var tokens = line.Split(sep); + Variable tokensVar = new Variable(Variable.VarType.ARRAY); + foreach (string token in tokens) + { + tokensVar.Tuple.Add(new Variable(token)); + } + allTokensVar.Tuple.Add(tokensVar); + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(allTokensVar)); + + return Variable.EmptyInstance; + } + } + + class AddVariablesToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2); + string hash2 = Utils.GetSafeString(args, 3); + string sepStr = Utils.GetSafeString(args, 4, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; + Variable toAdd = new Variable(counter - fromLine); + string line = lineVar.AsString(); + var tokens = line.Split(sep); + string hash = tokens[0]; + mapVar.AddVariableToHash(hash, toAdd); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + return Variable.EmptyInstance; + } + } + class AddVariableToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable toAdd = Utils.GetSafeVariable(args, 1); + string hash = Utils.GetSafeString(args, 2); + + var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + mapVar.AddVariableToHash(hash, toAdd); + for (int i = 3; i < args.Count; i++) + { + string hash2 = Utils.GetSafeString(args, 3); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + + return Variable.EmptyInstance; + } + } + class TokenCounterFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable all = Utils.GetSafeVariable(args, 0); + string varName = Utils.GetSafeString(args, 1); + int index = Utils.GetSafeInt(args, 2); + + // var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = new Variable(Variable.VarType.ARRAY); + + if (all.Tuple == null) + { + return Variable.EmptyInstance; + } + + string currentValue = ""; + int currentCount = 0; + + int globalCount = 0; + + for (int i = 0; i < all.Tuple.Count; i++) + { + Variable current = all.Tuple[i]; + if (current.Tuple == null || current.Tuple.Count < index) + { + break; + } + string newValue = current.Tuple[index].AsString(); + if (currentValue != newValue) + { + currentValue = newValue; + currentCount = 0; + } + mapVar.Tuple.Add(new Variable(currentCount)); + currentCount++; + globalCount++; + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + // Script - Need to enable the warnings +#pragma warning restore 219 + return mapVar; + } + } + + class TypeFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.END_ARG_ARRAY); + Utils.CheckNotEnd(script, m_name); + + List arrayIndices = Utils.GetArrayIndices(script, ref varName); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Variable element = currentValue; + + // 2b. Special case for an array. + if (arrayIndices.Count > 0) + {// array element + element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + // 3. Convert type to string. + string type = element.GetTypeString(); + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(type); + return newValue; + } + } + + class SizeFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.END_ARG_ARRAY); + Utils.CheckNotEnd(script, m_name); + + List arrayIndices = Utils.GetArrayIndices(script, ref varName); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Variable element = currentValue; + + // 2b. Special case for an array. + if (arrayIndices.Count > 0) + {// array element + element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + // 3. Take either the length of the underlying tuple or + // string part if it is defined, + // or the numerical part converted to a string otherwise. + int size = element.Type == Variable.VarType.ARRAY ? + element.Tuple.Count : + element.AsString().Length; + + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(size); + return newValue; + } + } + + class DefineLocalFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable currentValue = Utils.GetSafeVariable(args, 1); + + if (currentValue == null) + { + currentValue = new Variable(""); + } + + string scopeName = Path.GetFileName(script.Filename); + ParserFunction.AddLocalScopeVariable(varName, scopeName, + new GetVarFunction(currentValue)); + + return currentValue; + } + } + + class GetPropertiesFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + Variable baseValue = args[0]; + List props = baseValue.GetProperties(); + return new Variable(props); + } + } + + class GetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = baseValue.GetProperty(propName, script); + Utils.CheckNotNull(propValue, propName); + + return new Variable(propValue); + } + public static Variable GetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = baseValue.GetProperty(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName); + + return new Variable(propValue); + } + } + + class SetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = baseValue.SetProperty(propName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + public static Variable SetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = baseValue.SetProperty(sPropertyName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + } + + class CancelFunction : ParserFunction + { + public static bool Canceled { get; set; } + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 0, m_name, true); + + bool mode = Utils.GetSafeInt(args, 0, 1) == 1; + Canceled = mode; + + return new Variable(Canceled); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `currentValue` last assigned on line 1412 could be null and is dereferenced at line 1416, column 13. + +### Severity: +ERROR + +### Procedure: +Variable AddFunction.Evaluate(ParsingScript) + +### File: +cscs/Functions.Flow.cs + +### Key: +Functions.Flow.cs|Evaluate|NULL_DEREFERENCE + +### Node Key: +722f645c76bfb99c288630c5b05ba5dc + +### Hash: +e0a75025508ed3930f8cabca0f7a1d83 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1889/instruction.md b/inferredbugs-1889/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dd564106db3b13221715936226e438c38b1709b3 --- /dev/null +++ b/inferredbugs-1889/instruction.md @@ -0,0 +1,2489 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cscs +**Bug ID:** 75 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Threading.Tasks; + +namespace SplitAndMerge +{ + class BreakStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.BREAK); + } + } + class ContinueStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.CONTINUE); + } + } + + class ReturnStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = Utils.GetItem(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = await Utils.GetItemAsync(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + } + + class TryBlock : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessTry(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessTryAsync(script); + } + } + + class ExitFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Environment.Exit(0); + return Variable.EmptyInstance; + } + } + + class ThrowFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = Utils.GetItem(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = await Utils.GetItemAsync(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + } + + class ShowFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + string functionName = args[0].AsString(); + + CustomFunction custFunc = ParserFunction.GetFunction(functionName, script) as CustomFunction; + Utils.CheckNotNull(functionName, custFunc); + + string body = Utils.BeautifyScript(custFunc.Body, custFunc.Header); + Utils.PrintScript(body, script); + + return new Variable(body); + } + } + + class FunctionCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string funcName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + funcName = Constants.ConvertName(funcName); + + string[] args = Utils.GetFunctionSignature(script); + if (args.Length == 1 && string.IsNullOrWhiteSpace(args[0])) + { + args = new string[0]; + } + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + int lineNumber = 0; + /*string line = */script.GetOriginalLine(out lineNumber); + + int parentOffset = script.Pointer; + + if (script.CurrentClass != null) + { + parentOffset += script.CurrentClass.ParentOffset; + } + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + CustomFunction customFunc = new CustomFunction(funcName, body, args, script); + customFunc.ParentScript = script; + customFunc.ParentOffset = parentOffset; + + if (script.CurrentClass != null) + { + script.CurrentClass.AddMethod(funcName, args, customFunc); + } + else + { + ParserFunction.RegisterFunction(funcName, customFunc, false /* not native */); + } + + return Variable.EmptyInstance; + } + } + + public class CSCSClass : ParserFunction + { + public CSCSClass() {} + + public CSCSClass(string className) + { + Name = className; + RegisterClass(className, this); + } + + public CSCSClass(string className, string[] baseClasses) + { + Name = className; + RegisterClass(className, this); + + RegisterClass(obj: this, className : className); + + foreach (string baseClass in baseClasses) + { + var bc = CSCSClass.GetClass(baseClass); + if (bc == null) + { + throw new ArgumentException("Base Class [" + baseClass + "] not found."); + } + + foreach (var entry in bc.m_classProperties) + { + m_classProperties[entry.Key] = entry.Value; + } + foreach (var entry in bc.m_customFunctions) + { + m_customFunctions[entry.Key] = entry.Value; + } + } + } + + public static void RegisterClass(string className, CSCSClass obj) + { + obj.Namespace = ParserFunction.GetCurrentNamespace; + if (!string.IsNullOrWhiteSpace(obj.Namespace)) + { + className = obj.Namespace + "." + className; + } + + obj.Name = className; + className = Constants.ConvertName(className); + s_allClasses[className] = obj; + } + + protected override Variable Evaluate(ParsingScript script) + { + script.GetFunctionArgs(); + + // TODO: Work in progress, currently not functional + return Variable.EmptyInstance; + } + + public void AddMethod(string name, string[] args, CustomFunction method) + { + if (name == m_name) + { + m_constructors[args.Length] = method; + for (int i = 0; i < method.DefaultArgsCount && i < args.Length; i++) + { + m_constructors[args.Length - i - 1] = method; + } + } + else + { + m_customFunctions[name] = method; + } + } + + public void AddProperty(string name, Variable property) + { + m_classProperties[name] = property; + } + + public static CSCSClass GetClass(string name) + { + string currNamespace = ParserFunction.GetCurrentNamespace; + if (!string.IsNullOrWhiteSpace(currNamespace)) + { + bool namespacePresent = name.Contains("."); + if (!namespacePresent) + { + name = currNamespace + "." + name; + } + } + + CSCSClass theClass = null; + s_allClasses.TryGetValue(name, out theClass); + return theClass; + } + + static Dictionary s_allClasses = + new Dictionary(); + + Dictionary m_constructors = + new Dictionary(); + Dictionary m_customFunctions = + new Dictionary(); + Dictionary m_classProperties = + new Dictionary(); + + public ParsingScript ParentScript = null; + public int ParentOffset = 0; + + public string Namespace { get; private set; } + + public class ClassInstance : ScriptObject + { + public ClassInstance(string instanceName, string className, List args, + ParsingScript script = null) + { + InstanceName = instanceName; + m_cscsClass = CSCSClass.GetClass(className); + if (m_cscsClass == null) + { + throw new ArgumentException("Class [" + className + "] not found."); + } + + // Copy over all the properties defined for this class. + foreach (var entry in m_cscsClass.m_classProperties) + { + SetProperty(entry.Key, entry.Value); + } + + // Run "constructor" if any is defined for this number of args. + CustomFunction constructor = null; + if (m_cscsClass.m_constructors.TryGetValue(args.Count, out constructor)) + { + constructor.Run(args, script, this); + } + } + + public string InstanceName { get; set; } + CSCSClass m_cscsClass; + + Dictionary m_properties = new Dictionary(); + HashSet m_propSet = new HashSet(); + + public override string ToString() + { + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(Constants.PROP_TO_STRING.ToLower(), + out customFunction)) + { + return m_cscsClass.Name + "." + InstanceName; + } + + Variable result = customFunction.Run(null, null, this); + return result.ToString(); + } + + public Task SetProperty(string name, Variable value) + { + m_properties[name] = value; + m_propSet.Add(name); + return Task.FromResult( Variable.EmptyInstance ); + } + + public async Task GetProperty(string name, List args = null, ParsingScript script = null) + { + Variable value = null; + if (m_properties.TryGetValue(name, out value)) + { + return value; + } + + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out customFunction)) + { + return null; + } + if (args == null) + { + return Variable.EmptyInstance; + } + + foreach (var entry in m_cscsClass.m_classProperties) + { + args.Add(entry.Value); + } + + Variable result = await customFunction.RunAsync(args, script, this); + return result; + } + + public List> GetPropList() + { + List> props = new List>(); + foreach (var entry in m_properties) + { + props.Add(new KeyValuePair(entry.Key, entry.Value)); + } + return props; + } + + public List GetProperties() + { + List props = new List(m_properties.Keys); + props.AddRange(m_cscsClass.m_customFunctions.Keys); + + return props; + } + public bool PropertyExists(string name) + { + return m_propSet.Contains(name); + } + + public bool FunctionExists(string name) + { + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out customFunction)) + { + return false; + } + return true; + } + } + } + + class NameExistsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string varName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + varName = Constants.ConvertName(varName); + + bool result = ParserFunction.GetVariable(varName, script) != null || + ParserFunction.GetFunction(varName, script) != null; + return new Variable(result); + } + } + + class EnumFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List properties = Utils.ExtractTokens(script); + + if (properties.Count == 1 && properties[0].Contains(".")) + { + return UseExistingEnum(properties[0]); + } + + Variable enumVar = new Variable(Variable.VarType.ENUM); + for (int i = 0; i < properties.Count; i++) + { + enumVar.SetEnumProperty(properties[i], new Variable(i)); + } + + return enumVar; + } + + public static Variable UseExistingEnum(string enumName) + { + Type enumType = GetEnumType(enumName); + if (enumType == null || !enumType.IsEnum) + { + return Variable.EmptyInstance; + } + + var names = Enum.GetNames(enumType); + + Variable enumVar = new Variable(Variable.VarType.ENUM); + for (int i = 0; i < names.Length; i++) + { + var numValue = Enum.Parse(enumType, names[i], true); + enumVar.SetEnumProperty(names[i], new Variable((int)numValue)); + } + + return enumVar; + } + + public static Type GetEnumType(string enumName) + { + string[] tokens = enumName.Split('.'); + + Type enumType = null; + int index = 0; + string typeName = ""; + while(enumType == null && index < tokens.Length) + { + if (!string.IsNullOrWhiteSpace(typeName)) + { + typeName += "."; + } + typeName += tokens[index]; + enumType = GetType(typeName); + index++; + } + + for (int i = index; i < tokens.Length && enumType != null; i++) + { + enumType = enumType.GetNestedType(tokens[i]); + } + + if (enumType == null || !enumType.IsEnum) + { + return null; + } + + return enumType; + } + + public static Type GetType(string typeName) + { + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); + foreach (var assembly in assemblies) + { + var type = assembly.GetType(typeName, false, true); + if (type != null) + { + return type; + } + } + return null; + } + } + + class NewObjectFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = script.GetFunctionArgs(); + + CompiledClass csClass = CSCSClass.GetClass(className) as CompiledClass; + if (csClass != null) + { + ScriptObject obj = csClass.GetImplementation(args); + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = await script.GetFunctionArgsAsync(); + + CompiledClassAsync csClass = CSCSClass.GetClass(className) as CompiledClassAsync; + if (csClass != null) + { + ScriptObject obj = await csClass.GetImplementationAsync(args); + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + } + + public class ClassCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + string[] baseClasses = Utils.GetBaseClasses(script); + CSCSClass newClass = new CSCSClass(className, baseClasses); + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + + newClass.ParentOffset = script.Pointer; + newClass.ParentScript = script; + int lineNumber = 0; + /*string line = */script.GetOriginalLine(out lineNumber); + + string scriptExpr = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + Dictionary char2Line; + string body = Utils.ConvertToScript(scriptExpr, out char2Line); + + Variable result = null; + ParsingScript tempScript = new ParsingScript(body); + //tempScript.ScriptOffset = newClass.ParentOffset; + tempScript.Char2Line = script.Char2Line; + tempScript.Filename = script.Filename; + tempScript.OriginalScript = script.OriginalScript; + tempScript.CurrentClass = newClass; + tempScript.ParentScript = script; + tempScript.InTryBlock = script.InTryBlock; + tempScript.DisableBreakpoints = true; + + // Uncomment if want to step into the class creation code when the debugger is attached (unlikely) + /*Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript); + }*/ + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + + return Variable.EmptyInstance; + } + } + + public class NamespaceFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string namespaceName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + //Utils.CheckNotEnd(script, m_name); + Variable result = null; + + ParserFunction.AddNamespace(namespaceName); + try + { + script.MoveForwardIf(Constants.START_GROUP); + string scriptExpr = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + Dictionary char2Line; + string body = Utils.ConvertToScript(scriptExpr, out char2Line); + + ParsingScript tempScript = new ParsingScript(body); + //tempScript.ScriptOffset = newClass.ParentOffset; + tempScript.Char2Line = script.Char2Line; + tempScript.Filename = script.Filename; + tempScript.OriginalScript = script.OriginalScript; + tempScript.ParentScript = script; + tempScript.InTryBlock = script.InTryBlock; + tempScript.DisableBreakpoints = true; + tempScript.MoveForwardIf(Constants.START_GROUP); + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + } + finally + { + ParserFunction.PopNamespace(); + } + + return result; + } + } + + public class CustomFunction : ParserFunction + { + internal CustomFunction(string funcName, + string body, string[] args, ParsingScript script) + { + Name = funcName; + m_body = body; + m_args = RealArgs = args; + + for (int i = 0; i < args.Length; i++) + { + string arg = args[i]; + int ind = arg.IndexOf('='); + if (ind > 0) + { + RealArgs[i] = arg.Substring(0, ind).Trim(); + m_args[i] = RealArgs[i].ToLower(); + string defValue = ind >= arg.Length - 1 ? "" : arg.Substring(ind + 1).Trim(); + + Variable defVariable = Utils.GetVariableFromString(defValue, script); + defVariable.CurrentAssign = m_args[i]; + defVariable.Index = i; + + m_defArgMap[i] = m_defaultArgs.Count; + m_defaultArgs.Add(defVariable); + } + else + { + m_args[i] = RealArgs[i].ToLower(); + } + + ArgMap[m_args[i]] = i; + } + } + + public void RegisterArguments(List args, + List> args2 = null) + { + if (args == null) + { + args = new List(); + } + + int missingArgs = m_args.Length - args.Count; + + bool namedParameters = false; + for (int i = 0; i < args.Count; i++) + { + var arg = args[i]; + int argIndex = -1; + if (ArgMap.TryGetValue(arg.CurrentAssign, out argIndex)) + { + namedParameters = true; + if (i != argIndex) + { + args[i] = argIndex < args.Count ? args[argIndex] : args[i]; + while (argIndex > args.Count - 1) + { + args.Add(Variable.EmptyInstance); + } + args[argIndex] = arg; + } + } + else if (namedParameters) + { + throw new ArgumentException("All arguments in function [" + m_name + + "] must be in arg=value form."); + } + } + + if (missingArgs > 0 && missingArgs <= m_defaultArgs.Count) + { + if (!namedParameters) + { + for (int i = m_defaultArgs.Count - missingArgs; i < m_defaultArgs.Count; i++) + { + args.Add(m_defaultArgs[i]); + } + } + else + { + for (int i = 0; i < args.Count; i++) + { + if (args[i].Type == Variable.VarType.NONE || + (!string.IsNullOrWhiteSpace(args[i].CurrentAssign) && + args[i].CurrentAssign != m_args[i])) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args[i] = m_defaultArgs[defIndex]; + } + } + } + } + for (int i = args.Count; i < m_args.Length; i++) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args.Add(m_defaultArgs[defIndex]); + } + StackLevel stackLevel = new StackLevel(m_name); + + if (args2 != null) + { + foreach (var entry in args2) + { + var arg = new GetVarFunction(entry.Value); + arg.Name = entry.Key; + stackLevel.Variables[entry.Key] = arg; + } + } + + int maxSize = Math.Min(args.Count, m_args.Length); + for (int i = 0; i < maxSize; i++) + { + var arg = new GetVarFunction(args[i]); + arg.Name = m_args[i]; + stackLevel.Variables[m_args[i]] = arg; + } + + if (NamespaceData != null) + { + var vars = NamespaceData.Variables; + string prefix = NamespaceData.Name + "."; + foreach (KeyValuePair elem in vars) + { + string key = elem.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ? + elem.Key.Substring(prefix.Length) : elem.Key; + stackLevel.Variables[key] = elem.Value; + } + } + + ParserFunction.AddLocalVariables(stackLevel); + } + + protected override Variable Evaluate(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + script.GetFunctionArgs(); + + Utils.ExtractParameterNames(args, m_name, script); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = Run(args, script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + await script.GetFunctionArgsAsync(); + + Utils.ExtractParameterNames(args, m_name, script); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = await RunAsync(args, script); + return result; + } + + public Variable Run(List args = null, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = new ParsingScript(m_body); + tempScript.ScriptOffset = m_parentOffset; + if (m_parentScript != null) + { + tempScript.Char2Line = m_parentScript.Char2Line; + tempScript.Filename = m_parentScript.Filename; + tempScript.OriginalScript = m_parentScript.OriginalScript; + } + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.ClassInstance = instance; + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (script != null && debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + public async Task RunAsync(List args = null, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = new ParsingScript(m_body); + tempScript.ScriptOffset = m_parentOffset; + if (m_parentScript != null) + { + tempScript.Char2Line = m_parentScript.Char2Line; + tempScript.Filename = m_parentScript.Filename; + tempScript.OriginalScript = m_parentScript.OriginalScript; + } + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.ClassInstance = instance; + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = await debugger.StepInFunctionIfNeeded(tempScript); + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = await tempScript.ExecuteAsync(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + + public static Task Run(string functionName, + Variable arg1 = null, Variable arg2 = null, Variable arg3 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + if (arg3 != null) + { + args.Add(arg3); + } + + Variable result = customFunction.Run(args); + return Task.FromResult( result ); + } + + public static async Task RunAsync(string functionName, + Variable arg1 = null, Variable arg2 = null, Variable arg3 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + if (arg3 != null) + { + args.Add(arg3); + } + + Variable result = await customFunction.RunAsync(args); + return result; + } + + public ParsingScript ParentScript { set { m_parentScript = value; } } + public int ParentOffset { set { m_parentOffset = value; } } + public string Body { get { return m_body; } } + + public int ArgumentCount { get { return m_args.Length; } } + public string Argument(int nIndex) { return m_args[nIndex]; } + + public StackLevel NamespaceData { get; set; } + + public int DefaultArgsCount + { + get + { + return m_defaultArgs.Count; + } + } + + public string Header + { + get + { + return Constants.FUNCTION + " " + Constants.GetRealName(Name) + " " + + Constants.START_ARG + string.Join(", ", m_args) + + Constants.END_ARG + " " + Constants.START_GROUP; + } + } + + protected string m_body; + protected string[] m_args; + protected ParsingScript m_parentScript = null; + protected int m_parentOffset = 0; + + List m_defaultArgs = new List(); + Dictionary m_defArgMap = new Dictionary(); + + public Dictionary ArgMap { get; private set; } = new Dictionary(); + public string[] RealArgs { get; private set; } + } + + class StringOrNumberFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // First check if the passed expression is a string between quotes. + if (Item.Length > 1 && + ((Item[0] == Constants.QUOTE && Item[Item.Length - 1] == Constants.QUOTE) || + (Item[0] == Constants.QUOTE1 && Item[Item.Length - 1] == Constants.QUOTE1))) + { + return new Variable(Item.Substring(1, Item.Length - 2)); + } + + // Otherwise this should be a number. + double num = Utils.ConvertToDouble(Item, script); + return new Variable(num); + } + + public string Item { private get; set; } + } + + class AddFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + } + class RemoveFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + string varName = args[0].AsString(); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = args[1]; + + bool removed = currentValue.Tuple.Remove(item); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return new Variable(removed); + } + } + class RemoveAtFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = Utils.GetItem(script); + Utils.CheckNonNegativeInt(item); + + currentValue.Tuple.RemoveAt(item.AsInt()); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return Variable.EmptyInstance; + } + } + + class ContainsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + List arrayIndices = Utils.GetArrayIndices(script, varName, (newVarName) => { varName = newVarName; } ); + + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + + // 2b. Special dealings with arrays: + Variable query = arrayIndices.Count > 0 ? + Utils.ExtractArrayElement(currentValue, arrayIndices) : + currentValue; + + // 3. Get the value to be looked for. + Variable searchValue = Utils.GetItem(script); + Utils.CheckNotEnd(script, m_name); + + // 4. Check if the value to search for exists. + bool exists = query.Exists(searchValue, true /* notEmpty */); + + script.MoveBackIf(Constants.START_GROUP); + return new Variable(exists); + } + } + + class FindIndexFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable var = Utils.GetSafeVariable(args, 0); + string val = Utils.GetSafeString(args, 1); + + int index = var.FindIndex(val); + + return new Variable(index); + } + } + + class BoolFunction : ParserFunction, INumericFunction + { + bool m_value; + public BoolFunction(bool init) + { + m_value = init; + } + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(m_value); + } + } + class ToDoubleFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToDouble(arg.AsString()); + return new Variable(result); + } + } + class ToIntFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + int result = Utils.ConvertToInt(arg.AsString()); + return new Variable(result); + } + } + class ToBoolFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToBool(arg.AsString()) ? 1 : 0; + return new Variable(result); + } + } + class ToDecimalFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = Decimal.Parse(arg.AsString(), NumberStyles.Any).ToString(); + return new Variable(result); + } + } + class ToStringFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = arg.AsString(); + return new Variable(result); + } + } + class IdentityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return script.Execute(Constants.END_ARG_ARRAY); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await script.ExecuteAsync(Constants.END_ARG_ARRAY); + } + } + + class IfStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable result = Interpreter.Instance.ProcessIf(script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + Variable result = await Interpreter.Instance.ProcessIfAsync(script); + return result; + } + } + + class ForStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessFor(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessForAsync(script); + } + } + + class WhileStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessWhile(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessWhileAsync(script); + } + } + + class IncludeFile : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + string includeScript; + ParsingScript tempScript = GetIncludeFileScript(script, args, out includeScript); + + Variable result = null; + if (script.Debugger != null) + { + result = script.Debugger.StepInIncludeIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < includeScript.Length) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + string includeScript; + ParsingScript tempScript = GetIncludeFileScript(script, args, out includeScript); + + Variable result = null; + if (script.Debugger != null) + { + result = await script.Debugger.StepInIncludeIfNeeded(tempScript); + } + + while (tempScript.Pointer < includeScript.Length) + { + result = await tempScript.ExecuteAsync(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + + ParsingScript GetIncludeFileScript(ParsingScript script, List args, out string includeScript) + { + Utils.CheckArgs(args.Count, 1, m_name, true); + + string filename = args[0].AsString(); + string pathname = script.GetFilePath(filename); + string[] lines = Utils.GetFileLines(pathname); + + string includeFile = string.Join(Environment.NewLine, lines); + Dictionary char2Line; + includeScript = Utils.ConvertToScript(includeFile, out char2Line, pathname); + ParsingScript tempScript = new ParsingScript(includeScript, 0, char2Line); + tempScript.Filename = pathname; + tempScript.OriginalScript = string.Join(Constants.END_LINE.ToString(), lines); + tempScript.ParentScript = script; + tempScript.InTryBlock = script.InTryBlock; + + return tempScript; + } + } + + // Get a value of a variable or of an array element + public class GetVarFunction : ParserFunction + { + public GetVarFunction(Variable value) + { + m_value = value; + } + + protected override Variable Evaluate(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = Utils.GetArrayIndices(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; } ); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices); + if (script.TryCurrent() != '.') + { + return result; + } + + script.Forward(); + m_propName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Variable propValue = result.GetProperty(m_propName, script); + Utils.CheckNotNull(propValue, m_propName); + return propValue; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + string temp = m_propName; + m_propName = null; // Need this to reset for recursive calls + Variable propValue = m_value.Type == Variable.VarType.ENUM ? + m_value.GetEnumProperty(temp, script) : + m_value.GetProperty(temp, script); + Utils.CheckNotNull(propValue, temp); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = await Utils.GetArrayIndicesAsync(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; }); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices); + if (script.TryCurrent() != '.') + { + return result; + } + + script.Forward(); + m_propName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Variable propValue = await result.GetPropertyAsync(m_propName, script); + Utils.CheckNotNull(propValue, m_propName); + return propValue; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + string temp = m_propName; + m_propName = null; // Need this to reset for recursive calls + + Variable propValue = m_value.Type == Variable.VarType.ENUM ? + m_value.GetEnumProperty(temp, script) : + await m_value.GetPropertyAsync(temp, script); + Utils.CheckNotNull(propValue, temp, script); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + + public int Delta + { + set { m_delta = value; } + } + public Variable Value + { + get { return m_value; } + } + public List Indices + { + set { m_arrayIndices = value; } + } + public string PropertyName + { + set { m_propName = value; } + } + + Variable m_value; + int m_delta = 0; + List m_arrayIndices = null; + string m_propName; + } + class IncrementDecrementFunction : ActionFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool prefix = string.IsNullOrWhiteSpace(m_name); + if (prefix) + {// If it is a prefix we do not have the variable name yet. + Name = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + } + + // Value to be added to the variable: + int valueDelta = m_action == Constants.INCREMENT ? 1 : -1; + int returnDelta = prefix ? valueDelta : 0; + + // Check if the variable to be set has the form of x[a][b], + // meaning that this is an array element. + double newValue = 0; + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetVariable(m_name, script); + Utils.CheckNotNull(m_name, func); + + Variable currentValue = func.GetValue(script); + currentValue = currentValue.DeepClone(); + + if (arrayIndices.Count > 0 || script.TryCurrent() == Constants.START_ARRAY) + { + if (prefix) + { + string tmpName = m_name + script.Rest; + int delta = 0; + arrayIndices = Utils.GetArrayIndices(script, tmpName, delta, (string t, int d) => { tmpName = t; delta = d; }); + script.Forward(Math.Max(0, delta - tmpName.Length)); + } + + Variable element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + + newValue = element.Value + returnDelta; + element.Value += valueDelta; + } + else + { // A normal variable. + newValue = currentValue.Value + returnDelta; + currentValue.Value += valueDelta; + } + + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + return new Variable(newValue); + } + + override public ParserFunction NewInstance() + { + return new IncrementDecrementFunction(); + } + } + + class OperatorAssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // Value to be added to the variable: + Variable right = Utils.GetItem(script); + + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetVariable(m_name, script); + Utils.CheckNotNull(func, m_name, script); + + Variable currentValue = func.GetValue(script); + currentValue = currentValue.DeepClone(); + Variable left = currentValue; + + if (arrayIndices.Count > 0) + {// array element + left = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + if (left.Type == Variable.VarType.NUMBER) + { + NumberOperator(left, right, m_action); + } + else + { + StringOperator(left, right, m_action); + } + + if (arrayIndices.Count > 0) + {// array element + AssignFunction.ExtendArray(currentValue, arrayIndices, 0, left); + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + } + else + { + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(left)); + } + return left; + } + + static void NumberOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + valueA.Value += valueB.Value; + break; + case "-=": + valueA.Value -= valueB.Value; + break; + case "*=": + valueA.Value *= valueB.Value; + break; + case "/=": + valueA.Value /= valueB.Value; + break; + case "%=": + valueA.Value %= valueB.Value; + break; + case "&=": + valueA.Value = (int)valueA.Value & (int)valueB.Value; + break; + case "|=": + valueA.Value = (int)valueA.Value | (int)valueB.Value; + break; + case "^=": + valueA.Value = (int)valueA.Value ^ (int)valueB.Value; + break; + } + } + static void StringOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + if (valueB.Type == Variable.VarType.STRING) + { + valueA.String += valueB.AsString(); + } + else + { + valueA.String += valueB.Value; + } + break; + } + } + + override public ParserFunction NewInstance() + { + return new OperatorAssignFunction(); + } + } + + class AssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + m_name = Constants.GetRealName(m_name); + script.CurrentAssign = m_name; + Variable varValue = Utils.GetItem(script); + + // First try processing as an object (with a dot notation): + Variable result = ProcessObject(script, varValue); + if (result != null) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(result)); + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue)); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + //return varValue.DeepClone(); + } + + Variable array; + + ParserFunction pf = ParserFunction.GetVariable(m_name, script); + if (pf != null) + { + array = pf.GetValue(script); + } + else + { + array = new Variable(); + } + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array)); + return array; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + m_name = Constants.GetRealName(m_name); + script.CurrentAssign = m_name; + Variable varValue = await Utils.GetItemAsync(script); + + // First try processing as an object (with a dot notation): + Variable result = await ProcessObjectAsync(script, varValue); + if (result != null) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(result)); + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = await Utils.GetArrayIndicesAsync(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue)); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + //return varValue.DeepClone(); + } + + Variable array; + + ParserFunction pf = ParserFunction.GetVariable(m_name, script); + if (pf != null) + { + array = await pf.GetValueAsync(script); + } + else + { + array = new Variable(); + } + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array)); + return array; + } + + Variable ProcessObject(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + varValue = script.ClassInstance.SetProperty(m_name, varValue).Result; + return varValue.DeepClone(); + } + + int ind = varName.IndexOf('.'); + if (ind <= 0) + { + return null; + } + + Utils.CheckForValidName(varName, script); + + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + if (ParserFunction.TryAddToNamespace(prop, name, varValue)) + { + return varValue.DeepClone(); + } + + ParserFunction existing = ParserFunction.GetVariable(name, script); + Variable baseValue = existing != null ? existing.GetValue(script) : new Variable(Variable.VarType.ARRAY); + baseValue.SetProperty(prop, varValue, name); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue)); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + async Task ProcessObjectAsync(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + await script.ClassInstance.SetProperty(m_name, varValue); + return varValue.DeepClone(); + } + + int ind = varName.IndexOf('.'); + if (ind <= 0) + { + return null; + } + + Utils.CheckForValidName(varName, script); + + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + if (ParserFunction.TryAddToNamespace(prop, name, varValue)) + { + return varValue.DeepClone(); + } + + ParserFunction existing = ParserFunction.GetVariable(name, script); + Variable baseValue = existing != null ? await existing.GetValueAsync(script) : new Variable(Variable.VarType.ARRAY); + await baseValue.SetPropertyAsync(prop, varValue, name); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue)); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + + + override public ParserFunction NewInstance() + { + return new AssignFunction(); + } + + public static void ExtendArray(Variable parent, + List arrayIndices, + int indexPtr, + Variable varValue) + { + if (arrayIndices.Count <= indexPtr) + { + return; + } + + Variable index = arrayIndices[indexPtr]; + int currIndex = ExtendArrayHelper(parent, index); + + if (arrayIndices.Count - 1 == indexPtr) + { + parent.Tuple[currIndex] = varValue; + return; + } + + Variable son = parent.Tuple[currIndex]; + ExtendArray(son, arrayIndices, indexPtr + 1, varValue); + } + + private static int ExtendArrayHelper(Variable parent, Variable indexVar) + { + parent.SetAsArray(); + + int arrayIndex = parent.GetArrayIndex(indexVar); + if (arrayIndex < 0) + { + // This is not a "normal index" but a new string for the dictionary. + string hash = indexVar.AsString(); + arrayIndex = parent.SetHashVariable(hash, Variable.NewEmpty()); + return arrayIndex; + } + + if (parent.Tuple.Count <= arrayIndex) + { + for (int i = parent.Tuple.Count; i <= arrayIndex; i++) + { + parent.Tuple.Add(Variable.NewEmpty()); + } + } + return arrayIndex; + } + } + + class DeepCopyFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varValue = Utils.GetItem(script); + return varValue.DeepClone(); ; + } + } + + class TokenizeLinesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2, 0); + string sepStr = Utils.GetSafeString(args, 3, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + // var function = ParserFunction.GetVariable(varName, script); + Variable allTokensVar = new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; +#pragma warning disable 219 + // bugbug - the toAdd has side effects + Variable toAdd = new Variable(counter - fromLine); +#pragma warning restore 219 + string line = lineVar.AsString(); + var tokens = line.Split(sep); + Variable tokensVar = new Variable(Variable.VarType.ARRAY); + foreach (string token in tokens) + { + tokensVar.Tuple.Add(new Variable(token)); + } + allTokensVar.Tuple.Add(tokensVar); + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(allTokensVar)); + + return Variable.EmptyInstance; + } + } + + class AddVariablesToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2); + string hash2 = Utils.GetSafeString(args, 3); + string sepStr = Utils.GetSafeString(args, 4, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + var function = ParserFunction.GetVariable(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; + Variable toAdd = new Variable(counter - fromLine); + string line = lineVar.AsString(); + var tokens = line.Split(sep); + string hash = tokens[0]; + mapVar.AddVariableToHash(hash, toAdd); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + return Variable.EmptyInstance; + } + } + class AddVariableToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable toAdd = Utils.GetSafeVariable(args, 1); + string hash = Utils.GetSafeString(args, 2); + + var function = ParserFunction.GetVariable(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + mapVar.AddVariableToHash(hash, toAdd); + for (int i = 3; i < args.Count; i++) + { + string hash2 = Utils.GetSafeString(args, 3); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + + return Variable.EmptyInstance; + } + } + class TokenCounterFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable all = Utils.GetSafeVariable(args, 0); + string varName = Utils.GetSafeString(args, 1); + int index = Utils.GetSafeInt(args, 2); + + // var function = ParserFunction.GetVariable(varName, script); + Variable mapVar = new Variable(Variable.VarType.ARRAY); + + if (all.Tuple == null) + { + return Variable.EmptyInstance; + } + + string currentValue = ""; + int currentCount = 0; + + int globalCount = 0; + + for (int i = 0; i < all.Tuple.Count; i++) + { + Variable current = all.Tuple[i]; + if (current.Tuple == null || current.Tuple.Count < index) + { + break; + } + string newValue = current.Tuple[index].AsString(); + if (currentValue != newValue) + { + currentValue = newValue; + currentCount = 0; + } + mapVar.Tuple.Add(new Variable(currentCount)); + currentCount++; + globalCount++; + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + // Script - Need to enable the warnings +#pragma warning restore 219 + return mapVar; + } + } + + class TypeFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + bool complexVariable = Utils.GetSafeInt(args, 1, 0) == 1; + Variable element = null; + if (complexVariable) + { + element = Utils.GetVariable(args[0].AsString(), script, false); + } + if (element == null) + { + element = Utils.GetSafeVariable(args, 0); + } + + string type = element.GetTypeString(); + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(type); + return newValue; + } + } + + class SizeFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.END_ARG_ARRAY); + Utils.CheckNotEnd(script, m_name); + + List arrayIndices = Utils.GetArrayIndices(script, varName, (newName) => { varName = newName; } ); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Variable element = currentValue; + + // 2b. Special case for an array. + if (arrayIndices.Count > 0) + {// array element + element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + // 3. Take either the length of the underlying tuple or + // string part if it is defined, + // or the numerical part converted to a string otherwise. + int size = element.GetSize(); + + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(size); + return newValue; + } + } + + class DefineLocalFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable currentValue = Utils.GetSafeVariable(args, 1); + + if (currentValue == null) + { + currentValue = new Variable(""); + } + + string scopeName = Path.GetFileName(script.Filename); + ParserFunction.AddLocalScopeVariable(varName, scopeName, + new GetVarFunction(currentValue)); + + return currentValue; + } + } + + class GetPropertiesFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + Variable baseValue = args[0]; + List props = baseValue.GetProperties(); + return new Variable(props); + } + } + + class GetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = baseValue.GetProperty(propName, script); + Utils.CheckNotNull(propValue, propName); + + return new Variable(propValue); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = await baseValue.GetPropertyAsync(propName, script); + Utils.CheckNotNull(propValue, propName); + + return new Variable(propValue); + } + public static Variable GetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = baseValue.GetProperty(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName); + + return new Variable(propValue); + } + public static async Task GetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = await baseValue.GetPropertyAsync(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName); + + return new Variable(propValue); + } + } + + class SetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = baseValue.SetProperty(propName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = await baseValue.SetPropertyAsync(propName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + + public static Variable SetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = baseValue.SetProperty(sPropertyName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + public static async Task SetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = await baseValue.SetPropertyAsync(sPropertyName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + } + + class CancelFunction : ParserFunction + { + public static bool Canceled { get; set; } + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 0, m_name, true); + + bool mode = Utils.GetSafeInt(args, 0, 1) == 1; + Canceled = mode; + + return new Variable(Canceled); + } + } + + public class ScheduleRunFunction : ParserFunction + { + static Dictionary m_timers = + new Dictionary(); + + bool m_startTimer; + + public ScheduleRunFunction(bool startTimer) + { + m_startTimer = startTimer; + } + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + + if (!m_startTimer) + { + Utils.CheckArgs(args.Count, 1, m_name); + string cancelTimerId = Utils.GetSafeString(args, 0); + System.Timers.Timer cancelTimer; + if (m_timers.TryGetValue(cancelTimerId, out cancelTimer)) + { + cancelTimer.Stop(); + cancelTimer.Dispose(); + m_timers.Remove(cancelTimerId); + } + return Variable.EmptyInstance; + } + + Utils.CheckArgs(args.Count, 2, m_name); + int timeout = args[0].AsInt(); + string strAction = args[1].AsString(); + string arg = Utils.GetSafeString(args, 2); + string timerId = Utils.GetSafeString(args, 3); + bool autoReset = Utils.GetSafeInt(args, 4, 0) != 0; + + arg = Utils.ProtectQuotes(arg); + timerId = Utils.ProtectQuotes(timerId); + + System.Timers.Timer pauseTimer = new System.Timers.Timer(timeout); + pauseTimer.Elapsed += (sender, e) => + { + if (!autoReset) + { + pauseTimer.Stop(); + pauseTimer.Dispose(); + m_timers.Remove(timerId); + } + string body = string.Format("{0}({1},{2});", strAction, + "\"" + arg + "\"", "\"" + timerId + "\""); + + ParsingScript tempScript = new ParsingScript(body); + tempScript.Execute(); + }; + pauseTimer.AutoReset = autoReset; + m_timers[timerId] = pauseTimer; + + pauseTimer.Start(); + + return Variable.EmptyInstance; + } + } + + public class SingletonFunction : ParserFunction + { + static Dictionary m_singletons = + new Dictionary(); + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string expr = args[0].AsString(); + Dictionary char2Line; + expr = Utils.ConvertToScript(expr, out char2Line); + + Variable result; + if (m_singletons.TryGetValue(expr, out result)) + { + return result; + } + + ParsingScript tempScript = new ParsingScript(expr); + result = tempScript.Execute(); + + m_singletons[expr] = result; + + return result; + } + } + + class GetColumnFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable arrayVar = Utils.GetSafeVariable(args, 0); + int col = Utils.GetSafeInt(args, 1); + int fromCol = Utils.GetSafeInt(args, 2, 0); + + var tuple = arrayVar.Tuple; + + List result = new List(tuple.Count); + for (int i = fromCol; i < tuple.Count; i++) + { + Variable current = tuple[i]; + if (current.Tuple == null || current.Tuple.Count <= col) + { + throw new ArgumentException(m_name + ": Index [" + col + "] doesn't exist in column " + + i + "/" + (tuple.Count - 1)); + } + result.Add(current.Tuple[col]); + } + + return new Variable(result); + } + } + + class GetAllKeysFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varName = Utils.GetItem(script); + Utils.CheckNotNull(varName, m_name); + + List results = varName.GetAllKeys(); + + return new Variable(results); + } + } + + class CheckLoaderMainFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool isMain = !string.IsNullOrWhiteSpace(script.MainFilename) && + script.MainFilename == script.Filename; + + return new Variable(isMain); + } + } + + class ResetVariablesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + ParserFunction.CleanUpVariables(); + return Variable.EmptyInstance; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `all` last assigned on line 2619 could be null and is dereferenced at line 2626, column 13. + +### Severity: +ERROR + +### Procedure: +Variable TokenCounterFunction.Evaluate(ParsingScript) + +### File: +cscs/Functions.Flow.cs + +### Key: +Functions.Flow.cs|Evaluate|NULL_DEREFERENCE + +### Node Key: +bef2fe14012af516d6c7bc5d1bd471c5 + +### Hash: +b0f56c2b42f5b0422f61218dea743349 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1901/instruction.md b/inferredbugs-1901/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..745970892f0f83f7a705455a07b489761544dde7 --- /dev/null +++ b/inferredbugs-1901/instruction.md @@ -0,0 +1,2375 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cscs +**Bug ID:** 62 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Threading.Tasks; + +namespace SplitAndMerge +{ + class BreakStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.BREAK); + } + } + class ContinueStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.CONTINUE); + } + } + + class ReturnStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = Utils.GetItem(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = await Utils.GetItemAsync(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + } + + class TryBlock : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessTry(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessTryAsync(script); + } + } + + class ExitFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Environment.Exit(0); + return Variable.EmptyInstance; + } + } + + class ThrowFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = Utils.GetItem(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = await Utils.GetItemAsync(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + } + + class ShowFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + string funcName = args[0].AsString(); + + ParserFunction function = ParserFunction.GetFunction(funcName, script); + CustomFunction custFunc = function as CustomFunction; + Utils.CheckNotNull(funcName, custFunc); + + string body = Utils.BeautifyScript(custFunc.Body, custFunc.Header); + Utils.PrintScript(body, script); + + return new Variable(body); + } + } + + class FunctionCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string funcName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + funcName = Constants.ConvertName(funcName); + + string[] args = Utils.GetFunctionSignature(script); + if (args.Length == 1 && string.IsNullOrWhiteSpace(args[0])) + { + args = new string[0]; + } + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + int lineNumber = 0; + /*string line = */script.GetOriginalLine(out lineNumber); + + int parentOffset = script.Pointer; + + if (script.CurrentClass != null) + { + parentOffset += script.CurrentClass.ParentOffset; + } + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + CustomFunction customFunc = new CustomFunction(funcName, body, args, script); + customFunc.ParentScript = script; + customFunc.ParentOffset = parentOffset; + + if (script.CurrentClass != null) + { + script.CurrentClass.AddMethod(funcName, args, customFunc); + } + else + { + ParserFunction.RegisterFunction(funcName, customFunc, false /* not native */); + } + + return Variable.EmptyInstance; + } + } + + public class CSCSClass : ParserFunction + { + public CSCSClass() {} + + public CSCSClass(string className) + { + Name = className; + RegisterClass(className, this); + } + + public CSCSClass(string className, string[] baseClasses) + { + Name = className; + RegisterClass(className, this); + + foreach (string baseClass in baseClasses) + { + var bc = CSCSClass.GetClass(baseClass); + if (bc == null) + { + throw new ArgumentException("Base Class [" + baseClass + "] not found."); + } + + foreach (var entry in bc.m_classProperties) + { + m_classProperties[entry.Key] = entry.Value; + } + foreach (var entry in bc.m_customFunctions) + { + m_customFunctions[entry.Key] = entry.Value; + } + } + } + + public static void RegisterClass(string className, CSCSClass obj) + { + obj.Name = className; + className = Constants.ConvertName(className); + s_allClasses[className] = obj; + } + + protected override Variable Evaluate(ParsingScript script) + { + script.GetFunctionArgs(); + + // TODO: Work in progress, currently not functional + return Variable.EmptyInstance; + } + + public void AddMethod(string name, string[] args, CustomFunction method) + { + if (name == m_name) + { + m_constructors[args.Length] = method; + for (int i = 0; i < method.DefaultArgsCount && i < args.Length; i++) + { + m_constructors[args.Length - i - 1] = method; + } + } + else + { + m_customFunctions[name] = method; + } + } + + public void AddProperty(string name, Variable property) + { + m_classProperties[name] = property; + } + + public static CSCSClass GetClass(string name) + { + CSCSClass theClass = null; + s_allClasses.TryGetValue(name, out theClass); + return theClass; + } + + static Dictionary s_allClasses = + new Dictionary(); + + Dictionary m_constructors = + new Dictionary(); + Dictionary m_customFunctions = + new Dictionary(); + Dictionary m_classProperties = + new Dictionary(); + + public ParsingScript ParentScript = null; + public int ParentOffset = 0; + + public class ClassInstance : ScriptObject + { + public ClassInstance(string instanceName, string className, List args, + ParsingScript script = null) + { + InstanceName = instanceName; + m_cscsClass = CSCSClass.GetClass(className); + if (m_cscsClass == null) + { + throw new ArgumentException("Class [" + className + "] not found."); + } + + // Copy over all the properties defined for this class. + foreach (var entry in m_cscsClass.m_classProperties) + { + SetProperty(entry.Key, entry.Value); + } + + // Run "constructor" if any is defined for this number of args. + CustomFunction constructor = null; + if (m_cscsClass.m_constructors.TryGetValue(args.Count, out constructor)) + { + constructor.Run(args, script, this); + } + } + + public string InstanceName { get; set; } + CSCSClass m_cscsClass; + + Dictionary m_properties = new Dictionary(); + HashSet m_propSet = new HashSet(); + + public override string ToString() + { + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(Constants.PROP_TO_STRING.ToLower(), + out customFunction)) + { + return m_cscsClass.Name + "." + InstanceName; + } + + Variable result = customFunction.Run(null, null, this); + return result.ToString(); + } + + public Task SetProperty(string name, Variable value) + { + m_properties[name] = value; + m_propSet.Add(name); + return Task.FromResult( Variable.EmptyInstance ); + } + + public async Task GetProperty(string name, List args = null, ParsingScript script = null) + { + Variable value = null; + if (m_properties.TryGetValue(name, out value)) + { + return value; + } + + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out customFunction)) + { + return null; + } + if (args == null) + { + return Variable.EmptyInstance; + } + + foreach (var entry in m_cscsClass.m_classProperties) + { + args.Add(entry.Value); + } + + Variable result = await customFunction.RunAsync(args, script, this); + return result; + } + + public List> GetPropList() + { + List> props = new List>(); + foreach (var entry in m_properties) + { + props.Add(new KeyValuePair(entry.Key, entry.Value)); + } + return props; + } + + public List GetProperties() + { + List props = new List(m_properties.Keys); + props.AddRange(m_cscsClass.m_customFunctions.Keys); + + return props; + } + public bool PropertyExists(string name) + { + return m_propSet.Contains(name); + } + + public bool FunctionExists(string name) + { + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out customFunction)) + { + return false; + } + return true; + } + } + } + + class NameExistsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string funcName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + funcName = Constants.ConvertName(funcName); + + ParserFunction function = ParserFunction.GetFunction(funcName, script); + return new Variable(function != null); + } + } + + class EnumFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List properties = Utils.ExtractTokens(script); + + if (properties.Count == 1 && properties[0].Contains(".")) + { + return UseExistingEnum(properties[0]); + } + + Variable enumVar = new Variable(Variable.VarType.ENUM); + for (int i = 0; i < properties.Count; i++) + { + enumVar.SetEnumProperty(properties[i], new Variable(i)); + } + + return enumVar; + } + + public static Variable UseExistingEnum(string enumName) + { + Type enumType = GetEnumType(enumName); + if (enumType == null || !enumType.IsEnum) + { + return Variable.EmptyInstance; + } + + var names = Enum.GetNames(enumType); + + Variable enumVar = new Variable(Variable.VarType.ENUM); + for (int i = 0; i < names.Length; i++) + { + var numValue = Enum.Parse(enumType, names[i], true); + enumVar.SetEnumProperty(names[i], new Variable((int)numValue)); + } + + return enumVar; + } + + public static Type GetEnumType(string enumName) + { + string[] tokens = enumName.Split('.'); + + Type enumType = null; + int index = 0; + string typeName = ""; + while(enumType == null && index < tokens.Length) + { + if (!string.IsNullOrWhiteSpace(typeName)) + { + typeName += "."; + } + typeName += tokens[index]; + enumType = GetType(typeName); + index++; + } + + for (int i = index; i < tokens.Length && enumType != null; i++) + { + enumType = enumType.GetNestedType(tokens[i]); + } + + if (enumType == null || !enumType.IsEnum) + { + return null; + } + + return enumType; + } + + public static Type GetType(string typeName) + { + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); + foreach (var assembly in assemblies) + { + var type = assembly.GetType(typeName, false, true); + if (type != null) + { + return type; + } + } + return null; + } + } + + class NewObjectFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = script.GetFunctionArgs(); + + CompiledClass csClass = CSCSClass.GetClass(className) as CompiledClass; + if (csClass != null) + { + ScriptObject obj = csClass.GetImplementation(args); + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = await script.GetFunctionArgsAsync(); + + CompiledClassAsync csClass = CSCSClass.GetClass(className) as CompiledClassAsync; + if (csClass != null) + { + ScriptObject obj = await csClass.GetImplementationAsync(args); + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + } + + public class ClassCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + string[] baseClasses = Utils.GetBaseClasses(script); + CSCSClass newClass = new CSCSClass(className, baseClasses); + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + + newClass.ParentOffset = script.Pointer; + newClass.ParentScript = script; + int lineNumber = 0; + /*string line = */script.GetOriginalLine(out lineNumber); + + string scriptExpr = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + Dictionary char2Line; + string body = Utils.ConvertToScript(scriptExpr, out char2Line); + + Variable result = null; + ParsingScript tempScript = new ParsingScript(body); + //tempScript.ScriptOffset = newClass.ParentOffset; + tempScript.Char2Line = script.Char2Line; + tempScript.Filename = script.Filename; + tempScript.OriginalScript = script.OriginalScript; + tempScript.CurrentClass = newClass; + tempScript.ParentScript = script; + tempScript.InTryBlock = script.InTryBlock; + tempScript.DisableBreakpoints = true; + + // Uncomment if want to step into the class creation code when the debugger is attached (unlikely) + /*Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript); + }*/ + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + + return Variable.EmptyInstance; + } + } + + public class CustomFunction : ParserFunction + { + internal CustomFunction(string funcName, + string body, string[] args, ParsingScript script) + { + Name = funcName; + m_body = body; + m_args = args; + + for (int i = 0; i < args.Length; i++) + { + string arg = args[i]; + int ind = arg.IndexOf('='); + if (ind > 0) + { + m_args[i] = arg.Substring(0, ind).Trim().ToLower(); + string defValue = ind >= arg.Length - 1 ? "" : arg.Substring(ind + 1).Trim(); + + Variable defVariable = Utils.GetVariableFromString(defValue, script); + defVariable.CurrentAssign = m_args[i]; + defVariable.Index = i; + + m_defArgMap[i] = m_defaultArgs.Count; + m_defaultArgs.Add(defVariable); + } + else + { + m_args[i] = arg.ToLower(); + } + m_argMap[m_args[i]] = i; + } + } + + public void RegisterArguments(List args, + List> args2 = null) + { + if (args == null) + { + args = new List(); + } + + int missingArgs = m_args.Length - args.Count; + + bool namedParameters = false; + for (int i = 0; i < args.Count; i++) + { + var arg = args[i]; + int argIndex = -1; + if (m_argMap.TryGetValue(arg.CurrentAssign, out argIndex)) + { + namedParameters = true; + if (i != argIndex) + { + args[i] = argIndex < args.Count ? args[argIndex] : args[i]; + while (argIndex > args.Count - 1) + { + args.Add(Variable.EmptyInstance); + } + args[argIndex] = arg; + } + } + else if (namedParameters) + { + throw new ArgumentException("All arguments in function [" + m_name + + "] must be arg=value form."); + } + } + + if (missingArgs > 0 && missingArgs <= m_defaultArgs.Count) + { + if (!namedParameters) + { + for (int i = m_defaultArgs.Count - missingArgs; i < m_defaultArgs.Count; i++) + { + args.Add(m_defaultArgs[i]); + } + } + else + { + for (int i = 0; i < args.Count; i++) + { + if (args[i].Type == Variable.VarType.NONE || + (!string.IsNullOrWhiteSpace(args[i].CurrentAssign) && + args[i].CurrentAssign != m_args[i])) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args[i] = m_defaultArgs[defIndex]; + } + } + } + } + for (int i = args.Count; i < m_args.Length; i++) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args.Add(m_defaultArgs[defIndex]); + } + StackLevel stackLevel = new StackLevel(m_name); + + if (args2 != null) + { + foreach (var entry in args2) + { + var arg = new GetVarFunction(entry.Value); + arg.Name = entry.Key; + stackLevel.Variables[entry.Key] = arg; + } + } + + int maxSize = Math.Min(args.Count, m_args.Length); + for (int i = 0; i < maxSize; i++) + { + var arg = new GetVarFunction(args[i]); + arg.Name = m_args[i]; + stackLevel.Variables[m_args[i]] = arg; + } + + ParserFunction.AddLocalVariables(stackLevel); + } + + protected override Variable Evaluate(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + script.GetFunctionArgs(); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = Run(args, script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + await script.GetFunctionArgsAsync(); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = await RunAsync(args, script); + return result; + } + + public Variable Run(List args = null, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = new ParsingScript(m_body); + tempScript.ScriptOffset = m_parentOffset; + if (m_parentScript != null) + { + tempScript.Char2Line = m_parentScript.Char2Line; + tempScript.Filename = m_parentScript.Filename; + tempScript.OriginalScript = m_parentScript.OriginalScript; + } + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.ClassInstance = instance; + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + public async Task RunAsync(List args = null, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = new ParsingScript(m_body); + tempScript.ScriptOffset = m_parentOffset; + if (m_parentScript != null) + { + tempScript.Char2Line = m_parentScript.Char2Line; + tempScript.Filename = m_parentScript.Filename; + tempScript.OriginalScript = m_parentScript.OriginalScript; + } + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.ClassInstance = instance; + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = await debugger.StepInFunctionIfNeeded(tempScript); + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = await tempScript.ExecuteToAsync(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + + public static Task Run(string functionName, + Variable arg1 = null, Variable arg2 = null, Variable arg3 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + if (arg3 != null) + { + args.Add(arg3); + } + + Variable result = customFunction.Run(args); + return Task.FromResult( result ); + } + + public static async Task RunAsync(string functionName, + Variable arg1 = null, Variable arg2 = null, Variable arg3 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + if (arg3 != null) + { + args.Add(arg3); + } + + Variable result = await customFunction.RunAsync(args); + return result; + } + + public ParsingScript ParentScript { set { m_parentScript = value; } } + public int ParentOffset { set { m_parentOffset = value; } } + public string Body { get { return m_body; } } + + public int ArgumentCount { get { return m_args.Length; } } + public string Argument(int nIndex) { return m_args[nIndex]; } + + public int DefaultArgsCount + { + get + { + return m_defaultArgs.Count; + } + } + + public string Header + { + get + { + return Constants.FUNCTION + " " + Constants.GetRealName(Name) + " " + + Constants.START_ARG + string.Join(", ", m_args) + + Constants.END_ARG + " " + Constants.START_GROUP; + } + } + + protected string m_body; + protected string[] m_args; + protected ParsingScript m_parentScript = null; + protected int m_parentOffset = 0; + + List m_defaultArgs = new List(); + Dictionary m_argMap = new Dictionary(); + Dictionary m_defArgMap = new Dictionary(); + } + + class StringOrNumberFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // First check if the passed expression is a string between quotes. + if (Item.Length > 1 && + ((Item[0] == Constants.QUOTE && Item[Item.Length - 1] == Constants.QUOTE) || + (Item[0] == Constants.QUOTE1 && Item[Item.Length - 1] == Constants.QUOTE1))) + { + return new Variable(Item.Substring(1, Item.Length - 2)); + } + + // Otherwise this should be a number. + double num = Utils.ConvertToDouble(Item, script); + return new Variable(num); + } + + public string Item { private get; set; } + } + + class AddFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + } + class RemoveFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + string varName = args[0].AsString(); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = args[1]; + + bool removed = currentValue.Tuple.Remove(item); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return new Variable(removed); + } + } + class RemoveAtFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = Utils.GetItem(script); + Utils.CheckNonNegativeInt(item); + + currentValue.Tuple.RemoveAt(item.AsInt()); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return Variable.EmptyInstance; + } + } + + class ContainsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + List arrayIndices = Utils.GetArrayIndices(script, varName, (newVarName) => { varName = newVarName; } ); + + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + + // 2b. Special dealings with arrays: + Variable query = arrayIndices.Count > 0 ? + Utils.ExtractArrayElement(currentValue, arrayIndices) : + currentValue; + + // 3. Get the value to be looked for. + Variable searchValue = Utils.GetItem(script); + Utils.CheckNotEnd(script, m_name); + + // 4. Check if the value to search for exists. + bool exists = query.Exists(searchValue, true /* notEmpty */); + + script.MoveBackIf(Constants.START_GROUP); + return new Variable(exists); + } + } + + class FindIndexFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable var = Utils.GetSafeVariable(args, 0); + string val = Utils.GetSafeString(args, 1); + + int index = var.FindIndex(val); + + return new Variable(index); + } + } + + class BoolFunction : ParserFunction, INumericFunction + { + bool m_value; + public BoolFunction(bool init) + { + m_value = init; + } + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(m_value); + } + } + class ToDoubleFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToDouble(arg.AsString()); + return new Variable(result); + } + } + class ToIntFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + int result = Utils.ConvertToInt(arg.AsString()); + return new Variable(result); + } + } + class ToBoolFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToBool(arg.AsString()) ? 1 : 0; + return new Variable(result); + } + } + class ToDecimalFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = Decimal.Parse(arg.AsString(), NumberStyles.Any).ToString(); + return new Variable(result); + } + } + class ToStringFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = arg.AsString(); + return new Variable(result); + } + } + class IdentityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return script.ExecuteTo(Constants.END_ARG); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await script.ExecuteToAsync(Constants.END_ARG); + } + } + + class IfStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable result = Interpreter.Instance.ProcessIf(script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + Variable result = await Interpreter.Instance.ProcessIfAsync(script); + return result; + } + } + + class ForStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessFor(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessForAsync(script); + } + } + + class WhileStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessWhile(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessWhileAsync(script); + } + } + + class IncludeFile : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + string includeScript; + ParsingScript tempScript = GetIncludeFileScript(script, args, out includeScript); + + Variable result = null; + if (script.Debugger != null) + { + result = script.Debugger.StepInIncludeIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < includeScript.Length) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + string includeScript; + ParsingScript tempScript = GetIncludeFileScript(script, args, out includeScript); + + Variable result = null; + if (script.Debugger != null) + { + result = await script.Debugger.StepInIncludeIfNeeded(tempScript); + } + + while (tempScript.Pointer < includeScript.Length) + { + result = await tempScript.ExecuteToAsync(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + + ParsingScript GetIncludeFileScript(ParsingScript script, List args, out string includeScript) + { + Utils.CheckArgs(args.Count, 1, m_name, true); + + string filename = args[0].AsString(); + string pathname = script.GetFilePath(filename); + string[] lines = Utils.GetFileLines(pathname); + + string includeFile = string.Join(Environment.NewLine, lines); + Dictionary char2Line; + includeScript = Utils.ConvertToScript(includeFile, out char2Line, pathname); + ParsingScript tempScript = new ParsingScript(includeScript, 0, char2Line); + tempScript.Filename = pathname; + tempScript.OriginalScript = string.Join(Constants.END_LINE.ToString(), lines); + tempScript.ParentScript = script; + tempScript.InTryBlock = script.InTryBlock; + + return tempScript; + } + } + + // Get a value of a variable or of an array element + public class GetVarFunction : ParserFunction + { + public GetVarFunction(Variable value) + { + m_value = value; + } + + protected override Variable Evaluate(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = Utils.GetArrayIndices(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; } ); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices); + if (script.TryCurrent() != '.') + { + return result; + } + + script.Forward(); + m_propName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Variable propValue = result.GetProperty(m_propName, script); + Utils.CheckNotNull(propValue, m_propName); + return propValue; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + string temp = m_propName; + m_propName = null; // Need this to reset for recursive calls + Variable propValue = m_value.Type == Variable.VarType.ENUM ? + m_value.GetEnumProperty(temp, script) : + m_value.GetProperty(temp, script); + Utils.CheckNotNull(propValue, temp); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = await Utils.GetArrayIndicesAsync(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; }); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices); + if (script.TryCurrent() != '.') + { + return result; + } + + script.Forward(); + m_propName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Variable propValue = await result.GetPropertyAsync(m_propName, script); + Utils.CheckNotNull(propValue, m_propName); + return propValue; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + string temp = m_propName; + m_propName = null; // Need this to reset for recursive calls + + Variable propValue = m_value.Type == Variable.VarType.ENUM ? + m_value.GetEnumProperty(temp, script) : + await m_value.GetPropertyAsync(temp, script); + Utils.CheckNotNull(propValue, temp, script); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + + public int Delta + { + set { m_delta = value; } + } + public Variable Value + { + get { return m_value; } + } + public List Indices + { + set { m_arrayIndices = value; } + } + public string PropertyName + { + set { m_propName = value; } + } + + Variable m_value; + int m_delta = 0; + List m_arrayIndices = null; + string m_propName; + } + class IncrementDecrementFunction : ActionFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool prefix = string.IsNullOrWhiteSpace(m_name); + if (prefix) + {// If it is a prefix we do not have the variable name yet. + Name = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + } + + // Value to be added to the variable: + int valueDelta = m_action == Constants.INCREMENT ? 1 : -1; + int returnDelta = prefix ? valueDelta : 0; + + // Check if the variable to be set has the form of x[a][b], + // meaning that this is an array element. + double newValue = 0; + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetFunction(m_name, script); + Utils.CheckNotNull(m_name, func); + + Variable currentValue = func.GetValue(script); + currentValue = currentValue.DeepClone(); + + if (arrayIndices.Count > 0 || script.TryCurrent() == Constants.START_ARRAY) + { + if (prefix) + { + string tmpName = m_name + script.Rest; + int delta = 0; + arrayIndices = Utils.GetArrayIndices(script, tmpName, delta, (string t, int d) => { tmpName = t; delta = d; }); + script.Forward(Math.Max(0, delta - tmpName.Length)); + } + + Variable element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + + newValue = element.Value + returnDelta; + element.Value += valueDelta; + } + else + { // A normal variable. + newValue = currentValue.Value + returnDelta; + currentValue.Value += valueDelta; + } + + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + return new Variable(newValue); + } + + override public ParserFunction NewInstance() + { + return new IncrementDecrementFunction(); + } + } + + class OperatorAssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // Value to be added to the variable: + Variable right = Utils.GetItem(script); + + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetFunction(m_name, script); + Utils.CheckNotNull(func, m_name, script); + + Variable currentValue = func.GetValue(script); + currentValue = currentValue.DeepClone(); + Variable left = currentValue; + + if (arrayIndices.Count > 0) + {// array element + left = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + if (left.Type == Variable.VarType.NUMBER) + { + NumberOperator(left, right, m_action); + } + else + { + StringOperator(left, right, m_action); + } + + if (arrayIndices.Count > 0) + {// array element + AssignFunction.ExtendArray(currentValue, arrayIndices, 0, left); + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + } + else + { + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(left)); + } + return left; + } + + static void NumberOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + valueA.Value += valueB.Value; + break; + case "-=": + valueA.Value -= valueB.Value; + break; + case "*=": + valueA.Value *= valueB.Value; + break; + case "/=": + valueA.Value /= valueB.Value; + break; + case "%=": + valueA.Value %= valueB.Value; + break; + case "&=": + valueA.Value = (int)valueA.Value & (int)valueB.Value; + break; + case "|=": + valueA.Value = (int)valueA.Value | (int)valueB.Value; + break; + case "^=": + valueA.Value = (int)valueA.Value ^ (int)valueB.Value; + break; + } + } + static void StringOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + if (valueB.Type == Variable.VarType.STRING) + { + valueA.String += valueB.AsString(); + } + else + { + valueA.String += valueB.Value; + } + break; + } + } + + override public ParserFunction NewInstance() + { + return new OperatorAssignFunction(); + } + } + + class AssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + m_name = Constants.GetRealName(m_name); + script.CurrentAssign = m_name; + Variable varValue = Utils.GetItem(script); + + // First try processing as an object (with a dot notation): + Variable result = ProcessObject(script, varValue); + if (result != null) + { + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue)); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + //return varValue.DeepClone(); + } + + Variable array; + + ParserFunction pf = ParserFunction.GetFunction(m_name, script); + if (pf != null) + { + array = pf.GetValue(script); + } + else + { + array = new Variable(); + } + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array)); + return array; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + m_name = Constants.GetRealName(m_name); + script.CurrentAssign = m_name; + Variable varValue = await Utils.GetItemAsync(script); + + // First try processing as an object (with a dot notation): + Variable result = await ProcessObjectAsync(script, varValue); + if (result != null) + { + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = await Utils.GetArrayIndicesAsync(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue)); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + //return varValue.DeepClone(); + } + + Variable array; + + ParserFunction pf = ParserFunction.GetFunction(m_name, script); + if (pf != null) + { + array = await pf.GetValueAsync(script); + } + else + { + array = new Variable(); + } + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array)); + return array; + } + + Variable ProcessObject(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + varValue = script.ClassInstance.SetProperty(m_name, varValue).Result; + return varValue.DeepClone(); + } + + int ind = varName.IndexOf('.'); + if (ind <= 0) + { + return null; + } + + Utils.CheckForValidName(varName, script); + + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + ParserFunction existing = ParserFunction.GetFunction(name, script); + Variable baseValue = existing != null ? existing.GetValue(script) : new Variable(Variable.VarType.ARRAY); + baseValue.SetProperty(prop, varValue, name); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue)); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + async Task ProcessObjectAsync(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + await script.ClassInstance.SetProperty(m_name, varValue); + return varValue.DeepClone(); + } + + int ind = varName.IndexOf('.'); + if (ind <= 0) + { + return null; + } + + Utils.CheckForValidName(varName, script); + + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + ParserFunction existing = ParserFunction.GetFunction(name, script); + Variable baseValue = existing != null ? await existing.GetValueAsync(script) : new Variable(Variable.VarType.ARRAY); + await baseValue.SetPropertyAsync(prop, varValue, name); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue)); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + + + override public ParserFunction NewInstance() + { + return new AssignFunction(); + } + + public static void ExtendArray(Variable parent, + List arrayIndices, + int indexPtr, + Variable varValue) + { + if (arrayIndices.Count <= indexPtr) + { + return; + } + + Variable index = arrayIndices[indexPtr]; + int currIndex = ExtendArrayHelper(parent, index); + + if (arrayIndices.Count - 1 == indexPtr) + { + parent.Tuple[currIndex] = varValue; + return; + } + + Variable son = parent.Tuple[currIndex]; + ExtendArray(son, arrayIndices, indexPtr + 1, varValue); + } + + private static int ExtendArrayHelper(Variable parent, Variable indexVar) + { + parent.SetAsArray(); + + int arrayIndex = parent.GetArrayIndex(indexVar); + if (arrayIndex < 0) + { + // This is not a "normal index" but a new string for the dictionary. + string hash = indexVar.AsString(); + arrayIndex = parent.SetHashVariable(hash, Variable.NewEmpty()); + return arrayIndex; + } + + if (parent.Tuple.Count <= arrayIndex) + { + for (int i = parent.Tuple.Count; i <= arrayIndex; i++) + { + parent.Tuple.Add(Variable.NewEmpty()); + } + } + return arrayIndex; + } + } + + class DeepCopyFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varValue = Utils.GetItem(script); + return varValue.DeepClone(); ; + } + } + + class TokenizeLinesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2, 0); + string sepStr = Utils.GetSafeString(args, 3, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + // var function = ParserFunction.GetFunction(varName, script); + Variable allTokensVar = new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; +#pragma warning disable 219 + // bugbug - the toAdd has side effects + Variable toAdd = new Variable(counter - fromLine); +#pragma warning restore 219 + string line = lineVar.AsString(); + var tokens = line.Split(sep); + Variable tokensVar = new Variable(Variable.VarType.ARRAY); + foreach (string token in tokens) + { + tokensVar.Tuple.Add(new Variable(token)); + } + allTokensVar.Tuple.Add(tokensVar); + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(allTokensVar)); + + return Variable.EmptyInstance; + } + } + + class AddVariablesToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2); + string hash2 = Utils.GetSafeString(args, 3); + string sepStr = Utils.GetSafeString(args, 4, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; + Variable toAdd = new Variable(counter - fromLine); + string line = lineVar.AsString(); + var tokens = line.Split(sep); + string hash = tokens[0]; + mapVar.AddVariableToHash(hash, toAdd); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + return Variable.EmptyInstance; + } + } + class AddVariableToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable toAdd = Utils.GetSafeVariable(args, 1); + string hash = Utils.GetSafeString(args, 2); + + var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + mapVar.AddVariableToHash(hash, toAdd); + for (int i = 3; i < args.Count; i++) + { + string hash2 = Utils.GetSafeString(args, 3); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + + return Variable.EmptyInstance; + } + } + class TokenCounterFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable all = Utils.GetSafeVariable(args, 0); + string varName = Utils.GetSafeString(args, 1); + int index = Utils.GetSafeInt(args, 2); + + // var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = new Variable(Variable.VarType.ARRAY); + + if (all.Tuple == null) + { + return Variable.EmptyInstance; + } + + string currentValue = ""; + int currentCount = 0; + + int globalCount = 0; + + for (int i = 0; i < all.Tuple.Count; i++) + { + Variable current = all.Tuple[i]; + if (current.Tuple == null || current.Tuple.Count < index) + { + break; + } + string newValue = current.Tuple[index].AsString(); + if (currentValue != newValue) + { + currentValue = newValue; + currentCount = 0; + } + mapVar.Tuple.Add(new Variable(currentCount)); + currentCount++; + globalCount++; + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + // Script - Need to enable the warnings +#pragma warning restore 219 + return mapVar; + } + } + + class TypeFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + bool complexVariable = Utils.GetSafeInt(args, 1, 0) == 1; + Variable element = null; + if (complexVariable) + { + element = Utils.GetVariable(args[0].AsString(), script, false); + } + if (element == null) + { + element = Utils.GetSafeVariable(args, 0); + } + + string type = element.GetTypeString(); + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(type); + return newValue; + } + } + + class SizeFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.END_ARG_ARRAY); + Utils.CheckNotEnd(script, m_name); + + List arrayIndices = Utils.GetArrayIndices(script, varName, (newName) => { varName = newName; } ); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Variable element = currentValue; + + // 2b. Special case for an array. + if (arrayIndices.Count > 0) + {// array element + element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + // 3. Take either the length of the underlying tuple or + // string part if it is defined, + // or the numerical part converted to a string otherwise. + int size = element.GetSize(); + + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(size); + return newValue; + } + } + + class DefineLocalFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable currentValue = Utils.GetSafeVariable(args, 1); + + if (currentValue == null) + { + currentValue = new Variable(""); + } + + string scopeName = Path.GetFileName(script.Filename); + ParserFunction.AddLocalScopeVariable(varName, scopeName, + new GetVarFunction(currentValue)); + + return currentValue; + } + } + + class GetPropertiesFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + Variable baseValue = args[0]; + List props = baseValue.GetProperties(); + return new Variable(props); + } + } + + class GetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = baseValue.GetProperty(propName, script); + Utils.CheckNotNull(propValue, propName); + + return new Variable(propValue); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = await baseValue.GetPropertyAsync(propName, script); + Utils.CheckNotNull(propValue, propName); + + return new Variable(propValue); + } + public static Variable GetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = baseValue.GetProperty(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName); + + return new Variable(propValue); + } + public static async Task GetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = await baseValue.GetPropertyAsync(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName); + + return new Variable(propValue); + } + } + + class SetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = baseValue.SetProperty(propName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = await baseValue.SetPropertyAsync(propName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + + public static Variable SetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = baseValue.SetProperty(sPropertyName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + public static async Task SetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = await baseValue.SetPropertyAsync(sPropertyName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + } + + class CancelFunction : ParserFunction + { + public static bool Canceled { get; set; } + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 0, m_name, true); + + bool mode = Utils.GetSafeInt(args, 0, 1) == 1; + Canceled = mode; + + return new Variable(Canceled); + } + } + + public class ScheduleRunFunction : ParserFunction + { + static Dictionary m_timers = + new Dictionary(); + + bool m_startTimer; + + public ScheduleRunFunction(bool startTimer) + { + m_startTimer = startTimer; + } + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + + if (!m_startTimer) + { + Utils.CheckArgs(args.Count, 1, m_name); + string cancelTimerId = Utils.GetSafeString(args, 0); + System.Timers.Timer cancelTimer; + if (m_timers.TryGetValue(cancelTimerId, out cancelTimer)) + { + cancelTimer.Stop(); + cancelTimer.Dispose(); + m_timers.Remove(cancelTimerId); + } + return Variable.EmptyInstance; + } + + Utils.CheckArgs(args.Count, 2, m_name); + int timeout = args[0].AsInt(); + string strAction = args[1].AsString(); + string arg = Utils.GetSafeString(args, 2); + string timerId = Utils.GetSafeString(args, 3); + bool autoReset = Utils.GetSafeInt(args, 4, 0) != 0; + + arg = Utils.ProtectQuotes(arg); + timerId = Utils.ProtectQuotes(timerId); + + System.Timers.Timer pauseTimer = new System.Timers.Timer(timeout); + pauseTimer.Elapsed += (sender, e) => + { + if (!autoReset) + { + pauseTimer.Stop(); + pauseTimer.Dispose(); + m_timers.Remove(timerId); + } + string body = string.Format("{0}({1},{2});", strAction, + "\"" + arg + "\"", "\"" + timerId + "\""); + + ParsingScript tempScript = new ParsingScript(body); + tempScript.ExecuteTo(); + }; + pauseTimer.AutoReset = autoReset; + m_timers[timerId] = pauseTimer; + + pauseTimer.Start(); + + return Variable.EmptyInstance; + } + } + + public class SingletonFunction : ParserFunction + { + static Dictionary m_singletons = + new Dictionary(); + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string expr = args[0].AsString(); + Dictionary char2Line; + expr = Utils.ConvertToScript(expr, out char2Line); + + Variable result; + if (m_singletons.TryGetValue(expr, out result)) + { + return result; + } + + ParsingScript tempScript = new ParsingScript(expr); + result = tempScript.ExecuteTo(); + + m_singletons[expr] = result; + + return result; + } + } + + class GetColumnFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable arrayVar = Utils.GetSafeVariable(args, 0); + int col = Utils.GetSafeInt(args, 1); + int fromCol = Utils.GetSafeInt(args, 2, 0); + + var tuple = arrayVar.Tuple; + + List result = new List(tuple.Count); + for (int i = fromCol; i < tuple.Count; i++) + { + Variable current = tuple[i]; + if (current.Tuple == null || current.Tuple.Count <= col) + { + throw new ArgumentException(m_name + ": Index [" + col + "] doesn't exist in column " + + i + "/" + (tuple.Count - 1)); + } + result.Add(current.Tuple[col]); + } + + return new Variable(result); + } + } + + class GetAllKeysFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varName = Utils.GetItem(script); + Utils.CheckNotNull(varName, m_name); + + List results = varName.GetAllKeys(); + + return new Variable(results); + } + } + + class CheckLoaderMainFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool isMain = !string.IsNullOrWhiteSpace(script.MainFilename) && + script.MainFilename == script.Filename; + + return new Variable(isMain); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `all` last assigned on line 2619 could be null and is dereferenced at line 2626, column 13. + +### Severity: +ERROR + +### Procedure: +Variable TokenCounterFunction.Evaluate(ParsingScript) + +### File: +cscs/Functions.Flow.cs + +### Key: +Functions.Flow.cs|Evaluate|NULL_DEREFERENCE + +### Node Key: +bef2fe14012af516d6c7bc5d1bd471c5 + +### Hash: +b0f56c2b42f5b0422f61218dea743349 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1906/instruction.md b/inferredbugs-1906/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..30bd7062b9e093ed462c010052f5e65ad45e4229 --- /dev/null +++ b/inferredbugs-1906/instruction.md @@ -0,0 +1,2812 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cscs +**Bug ID:** 98 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Threading.Tasks; + +namespace SplitAndMerge +{ + class BreakStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.BREAK); + } + } + + class ContinueStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.CONTINUE); + } + } + + class ReturnStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = Utils.GetItem(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = await Utils.GetItemAsync(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + } + + class TryBlock : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessTry(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessTryAsync(script); + } + } + + class ExitFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Environment.Exit(0); + return Variable.EmptyInstance; + } + } + + class NullFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Variable.EmptyInstance; + } + } + class InfinityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(double.PositiveInfinity); + } + } + class NegInfinityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(double.NegativeInfinity); + } + } + + class IsNaNFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + Variable arg = args[0]; + return new Variable(arg.Type != Variable.VarType.NUMBER || double.IsNaN(arg.Value)); + } + } + + class TypeOfFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + var args = Utils.GetTokens(script, Constants.TOKEN_SEPARATION); + Utils.CheckArgs(args.Count, 1, m_name); + + if (args[0].StartsWith("\"")) + { + return new Variable(Constants.TypeToString(Variable.VarType.STRING).ToLower()); + } + if (Utils.CanConvertToDouble(args[0], out double _)) + { + return new Variable(Constants.TypeToString(Variable.VarType.NUMBER).ToLower()); + } + + var vari = GetVariable(args[0], script); + if (vari == null || vari.GetValue(script).Type == Variable.VarType.UNDEFINED) + { + return Variable.Undefined; + } + + var exists = FunctionExists(args[0]); + if (!exists) + { + return Variable.Undefined; + } + + bool complexVariable = args.Count > 1 && + Utils.CanConvertToDouble(args[1], out double converted) && converted > 0; + Variable element = null; + if (complexVariable) + { + element = Utils.GetVariable(args[0], script, false); + } + if (element == null) + { + element = new Variable(args[0]); + } + + string type = element.GetTypeString(); + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(type.ToLower()); + return newValue; + } + } + + class IsFiniteFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + Variable arg = args[0]; + + double value = arg.Value; + if (arg.Type != Variable.VarType.NUMBER && + !double.TryParse(arg.String, out value)) + { + value = double.PositiveInfinity; + } + + return new Variable(!double.IsInfinity(value)); + } + } + + class IsUndefinedFunction : ParserFunction + { + string m_argument; + string m_action; + + internal IsUndefinedFunction(string arg = "", string action = "") + { + m_argument = arg; + m_action = action; + } + + protected override Variable Evaluate(ParsingScript script) + { + var variable = ParserFunction.GetVariable(m_argument, script); + var varValue = variable == null ? null : variable.GetValue(script); + bool isUndefined = varValue == null || varValue.Type == Variable.VarType.UNDEFINED; + + bool result = m_action == "===" || m_action == "==" ? isUndefined : + !isUndefined; + return new Variable(result); + } + } + + class ObjectPropsFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable obj = Utils.GetItem(script, true); + string propName = Utils.GetItem(script, true).AsString(); + script.MoveForwardIf(','); + + Variable value = Utils.GetProperties(script); + obj.SetProperty(propName, value, script); + + ParserFunction.AddGlobal(obj.ParamName, new GetVarFunction(obj), false); + + return new Variable(obj.ParamName); + } + } + + class ThrowFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = Utils.GetItem(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = await Utils.GetItemAsync(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + } + + class VarFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + var args = Utils.GetTokens(script); + Variable result = Variable.EmptyInstance; + foreach (var arg in args) + { + var ind = arg.IndexOf('='); + if (ind <= 0) + { + if (!FunctionExists(arg)) + { + AddGlobalOrLocalVariable(arg, new GetVarFunction(new Variable(Variable.VarType.NONE)), script); + } + continue; + } + var varName = arg.Substring(0, ind); + ParsingScript tempScript = new ParsingScript(arg.Substring(ind + 1)); + AssignFunction assign = new AssignFunction(); + result = assign.Assign(tempScript, varName, true); + } + return result; + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + //var varName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + //char action = script.CurrentAndForward(); + + var args = Utils.GetTokens(script); + Task result = null; + foreach (var arg in args) + { + var ind = arg.IndexOf('='); + if (ind <= 0) + { + if (!FunctionExists(arg)) + { + AddGlobalOrLocalVariable(arg, new GetVarFunction(new Variable(Variable.VarType.UNDEFINED)), script); + } + continue; + } + var varName = arg.Substring(0, ind); + ParsingScript tempScript = new ParsingScript(arg.Substring(ind + 1)); + AssignFunction assign = new AssignFunction(); + result = assign.AssignAsync(tempScript, varName, true); + } + + return result == null ? Variable.EmptyInstance: await result; + } + } + + class ShowFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + string functionName = args[0].AsString(); + + CustomFunction custFunc = ParserFunction.GetFunction(functionName, script) as CustomFunction; + Utils.CheckNotNull(functionName, custFunc, script); + +#if __ANDROID__ == false && __IOS__ == false + CustomCompiledFunction comp = custFunc as CustomCompiledFunction; + if (comp != null) + { + return new Variable(comp.Precompiler.CSharpCode); + } +#endif + + string body = Utils.BeautifyScript(custFunc.Body, custFunc.Header); + Utils.PrintScript(body, script); + + return new Variable(body); + } + } + + class FunctionCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string funcName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + funcName = Constants.ConvertName(funcName); + + string[] args = Utils.GetFunctionSignature(script); + if (args.Length == 1 && string.IsNullOrWhiteSpace(args[0])) + { + args = new string[0]; + } + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + /*string line = */script.GetOriginalLine(out _); + + int parentOffset = script.Pointer; + + if (script.CurrentClass != null) + { + parentOffset += script.CurrentClass.ParentOffset; + } + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + CustomFunction customFunc = new CustomFunction(funcName, body, args, script); + customFunc.ParentScript = script; + customFunc.ParentOffset = parentOffset; + + if (script.CurrentClass != null) + { + script.CurrentClass.AddMethod(funcName, args, customFunc); + } + else + { + ParserFunction.RegisterFunction(funcName, customFunc, false /* not native */); + } + + return Variable.EmptyInstance; + } + } + + public class CSCSClass : ParserFunction + { + public CSCSClass() {} + + public CSCSClass(string className) + { + Name = className; + RegisterClass(className, this); + } + + public CSCSClass(string className, string[] baseClasses) + { + Name = className; + RegisterClass(className, this); + + foreach (string baseClass in baseClasses) + { + var bc = CSCSClass.GetClass(baseClass); + if (bc == null) + { + throw new ArgumentException("Base Class [" + baseClass + "] not found."); + } + + foreach (var entry in bc.m_classProperties) + { + m_classProperties[entry.Key] = entry.Value; + } + foreach (var entry in bc.m_customFunctions) + { + m_customFunctions[entry.Key] = entry.Value; + } + } + } + + public static void RegisterClass(string className, CSCSClass obj) + { + obj.Namespace = ParserFunction.GetCurrentNamespace; + if (!string.IsNullOrWhiteSpace(obj.Namespace)) + { + className = obj.Namespace + "." + className; + } + + obj.Name = className; + className = Constants.ConvertName(className); + s_allClasses[className] = obj; + } + + protected override Variable Evaluate(ParsingScript script) + { + script.GetFunctionArgs(); + + // TODO: Work in progress, currently not functional + return Variable.EmptyInstance; + } + + public void AddMethod(string name, string[] args, CustomFunction method) + { + if (name == m_name) + { + m_constructors[args.Length] = method; + for (int i = 0; i < method.DefaultArgsCount && i < args.Length; i++) + { + m_constructors[args.Length - i - 1] = method; + } + } + else + { + m_customFunctions[name] = method; + } + } + + public void AddProperty(string name, Variable property) + { + m_classProperties[name] = property; + } + + public static CSCSClass GetClass(string name) + { + string currNamespace = ParserFunction.GetCurrentNamespace; + if (!string.IsNullOrWhiteSpace(currNamespace)) + { + bool namespacePresent = name.Contains("."); + if (!namespacePresent) + { + name = currNamespace + "." + name; + } + } + + CSCSClass theClass = null; + s_allClasses.TryGetValue(name, out theClass); + return theClass; + } + + static Dictionary s_allClasses = + new Dictionary(); + + Dictionary m_constructors = + new Dictionary(); + Dictionary m_customFunctions = + new Dictionary(); + Dictionary m_classProperties = + new Dictionary(); + + public ParsingScript ParentScript = null; + public int ParentOffset = 0; + + public string Namespace { get; private set; } + + public class ClassInstance : ScriptObject + { + public ClassInstance(string instanceName, string className, List args, + ParsingScript script = null) + { + InstanceName = instanceName; + m_cscsClass = CSCSClass.GetClass(className); + if (m_cscsClass == null) + { + throw new ArgumentException("Class [" + className + "] not found."); + } + + // Copy over all the properties defined for this class. + foreach (var entry in m_cscsClass.m_classProperties) + { + SetProperty(entry.Key, entry.Value); + } + + // Run "constructor" if any is defined for this number of args. + CustomFunction constructor = null; + if (m_cscsClass.m_constructors.TryGetValue(args.Count, out constructor)) + { + constructor.Run(args, script, this); + } + } + + public string InstanceName { get; set; } + CSCSClass m_cscsClass; + + Dictionary m_properties = new Dictionary(); + HashSet m_propSet = new HashSet(); + HashSet m_propSetLower = new HashSet(); + + public override string ToString() + { + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(Constants.PROP_TO_STRING.ToLower(), + out customFunction)) + { + return m_cscsClass.Name + "." + InstanceName; + } + + Variable result = customFunction.Run(null, null, this); + return result.ToString(); + } + + public Task SetProperty(string name, Variable value) + { + m_properties[name] = value; + m_propSet.Add(name); + m_propSetLower.Add(name.ToLower()); + return Task.FromResult( Variable.EmptyInstance ); + } + + public async Task GetProperty(string name, List args = null, ParsingScript script = null) + { + if (m_properties.TryGetValue(name, out Variable value)) + { + return value; + } + + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out CustomFunction customFunction)) + { + return null; + } + if (args == null) + { + return Variable.EmptyInstance; + } + + foreach (var entry in m_cscsClass.m_classProperties) + { + args.Add(entry.Value); + } + + Variable result = await customFunction.RunAsync(args, script, this); + return result; + } + + public List> GetPropList() + { + List> props = new List>(); + foreach (var entry in m_properties) + { + props.Add(new KeyValuePair(entry.Key, entry.Value)); + } + return props; + } + + public List GetProperties() + { + List props = new List(m_properties.Keys); + props.AddRange(m_cscsClass.m_customFunctions.Keys); + + return props; + } + public bool PropertyExists(string name) + { + return m_propSetLower.Contains(name.ToLower()); + } + + public bool FunctionExists(string name) + { + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out CustomFunction customFunction)) + { + return false; + } + return true; + } + } + } + + class NameExistsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string varName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + varName = Constants.ConvertName(varName); + + bool result = ParserFunction.GetVariable(varName, script) != null; + return new Variable(result); + } + } + + class EnumFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List properties = Utils.ExtractTokens(script); + + if (properties.Count == 1 && properties[0].Contains(".")) + { + return UseExistingEnum(properties[0]); + } + + Variable enumVar = new Variable(Variable.VarType.ENUM); + for (int i = 0; i < properties.Count; i++) + { + enumVar.SetEnumProperty(properties[i], new Variable(i)); + } + + return enumVar; + } + + public static Variable UseExistingEnum(string enumName) + { + Type enumType = GetEnumType(enumName); + if (enumType == null || !enumType.IsEnum) + { + return Variable.EmptyInstance; + } + + var names = Enum.GetNames(enumType); + + Variable enumVar = new Variable(Variable.VarType.ENUM); + for (int i = 0; i < names.Length; i++) + { + var numValue = Enum.Parse(enumType, names[i], true); + enumVar.SetEnumProperty(names[i], new Variable((int)numValue)); + } + + return enumVar; + } + + public static Type GetEnumType(string enumName) + { + string[] tokens = enumName.Split('.'); + + Type enumType = null; + int index = 0; + string typeName = ""; + while(enumType == null && index < tokens.Length) + { + if (!string.IsNullOrWhiteSpace(typeName)) + { + typeName += "."; + } + typeName += tokens[index]; + enumType = GetType(typeName); + index++; + } + + for (int i = index; i < tokens.Length && enumType != null; i++) + { + enumType = enumType.GetNestedType(tokens[i]); + } + + if (enumType == null || !enumType.IsEnum) + { + return null; + } + + return enumType; + } + + public static Type GetType(string typeName) + { + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); + foreach (var assembly in assemblies) + { + var type = assembly.GetType(typeName, false, true); + if (type != null) + { + return type; + } + } + return null; + } + } + + class NewObjectFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = script.GetFunctionArgs(); + + CompiledClass csClass = CSCSClass.GetClass(className) as CompiledClass; + if (csClass != null) + { + ScriptObject obj = csClass.GetImplementation(args); + return new Variable(obj); + } + CompiledClassAsync csClassAsync = CSCSClass.GetClass(className) as CompiledClassAsync; + if (csClassAsync != null) + { + ScriptObject obj = csClassAsync.GetImplementationAsync(args).Result; + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = await script.GetFunctionArgsAsync(); + + CompiledClassAsync csClassAsync = CSCSClass.GetClass(className) as CompiledClassAsync; + if (csClassAsync != null) + { + ScriptObject obj = await csClassAsync.GetImplementationAsync(args); + return new Variable(obj); + } + CompiledClass csClass = CSCSClass.GetClass(className) as CompiledClass; + if (csClass != null) + { + ScriptObject obj = csClass.GetImplementation(args); + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + } + + public class ClassCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + string[] baseClasses = Utils.GetBaseClasses(script); + CSCSClass newClass = new CSCSClass(className, baseClasses); + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + + newClass.ParentOffset = script.Pointer; + newClass.ParentScript = script; + /*string line = */script.GetOriginalLine(out _); + + string scriptExpr = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + string body = Utils.ConvertToScript(scriptExpr, out _); + + Variable result = null; + ParsingScript tempScript = script.GetTempScript(body); + tempScript.CurrentClass = newClass; + tempScript.DisableBreakpoints = true; + + // Uncomment if want to step into the class creation code when the debugger is attached (unlikely) + /*Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript); + }*/ + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + + return Variable.EmptyInstance; + } + } + + public class NamespaceFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string namespaceName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + //Utils.CheckNotEnd(script, m_name); + Variable result = null; + + ParserFunction.AddNamespace(namespaceName); + try + { + script.MoveForwardIf(Constants.START_GROUP); + string scriptExpr = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + script.MoveForwardIf(Constants.END_GROUP); + + Dictionary char2Line; + string body = Utils.ConvertToScript(scriptExpr, out char2Line); + + ParsingScript tempScript = script.GetTempScript(body); + tempScript.DisableBreakpoints = true; + tempScript.MoveForwardIf(Constants.START_GROUP); + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + } + finally + { + ParserFunction.PopNamespace(); + } + + return result; + } + } + + public class CustomFunction : ParserFunction + { + internal CustomFunction(string funcName, + string body, string[] args, ParsingScript script) + { + Name = funcName; + m_body = body; + m_args = RealArgs = args; + + for (int i = 0; i < args.Length; i++) + { + string arg = args[i]; + int ind = arg.IndexOf('='); + if (ind > 0) + { + RealArgs[i] = arg.Substring(0, ind).Trim(); + m_args[i] = RealArgs[i].ToLower(); + string defValue = ind >= arg.Length - 1 ? "" : arg.Substring(ind + 1).Trim(); + + Variable defVariable = Utils.GetVariableFromString(defValue, script); + defVariable.CurrentAssign = m_args[i]; + defVariable.Index = i; + + m_defArgMap[i] = m_defaultArgs.Count; + m_defaultArgs.Add(defVariable); + } + else + { + m_args[i] = RealArgs[i].ToLower(); + } + + ArgMap[m_args[i]] = i; + } + } + + public void RegisterArguments(List args, + List> args2 = null) + { + if (args == null) + { + args = new List(); + } + int missingArgs = m_args.Length - args.Count; + + bool namedParameters = false; + for (int i = 0; i < args.Count; i++) + { + var arg = args[i]; + int argIndex = -1; + if (ArgMap.TryGetValue(arg.CurrentAssign, out argIndex)) + { + namedParameters = true; + if (i != argIndex) + { + args[i] = argIndex < args.Count ? args[argIndex] : args[i]; + while (argIndex > args.Count - 1) + { + args.Add(Variable.EmptyInstance); + } + args[argIndex] = arg; + } + } + else if (namedParameters) + { + throw new ArgumentException("All arguments in function [" + m_name + + "] must be in arg=value form."); + } + } + + if (missingArgs > 0 && missingArgs <= m_defaultArgs.Count) + { + if (!namedParameters) + { + for (int i = m_defaultArgs.Count - missingArgs; i < m_defaultArgs.Count; i++) + { + args.Add(m_defaultArgs[i]); + } + } + else + { + for (int i = 0; i < args.Count; i++) + { + if (args[i].Type == Variable.VarType.NONE || + (!string.IsNullOrWhiteSpace(args[i].CurrentAssign) && + args[i].CurrentAssign != m_args[i])) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args[i] = m_defaultArgs[defIndex]; + } + } + } + } + for (int i = args.Count; i < m_args.Length; i++) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args.Add(m_defaultArgs[defIndex]); + } + m_stackLevel = new StackLevel(m_name); + + if (args2 != null) + { + foreach (var entry in args2) + { + var arg = new GetVarFunction(entry.Value); + arg.Name = entry.Key; + m_stackLevel.Variables[entry.Key] = arg; + } + } + + int maxSize = Math.Min(args.Count, m_args.Length); + for (int i = 0; i < maxSize; i++) + { + var arg = new GetVarFunction(args[i]); + arg.Name = m_args[i]; + m_stackLevel.Variables[m_args[i]] = arg; + } + + for (int i = m_args.Length; i < args.Count; i++) + { + var arg = new GetVarFunction(args[i]); + m_stackLevel.Variables[args[i].ParamName] = arg; + } + + if (NamespaceData != null) + { + var vars = NamespaceData.Variables; + string prefix = NamespaceData.Name + "."; + foreach (KeyValuePair elem in vars) + { + string key = elem.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ? + elem.Key.Substring(prefix.Length) : elem.Key; + m_stackLevel.Variables[key] = elem.Value; + } + } + + ParserFunction.AddLocalVariables(m_stackLevel); + } + + protected override Variable Evaluate(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + script.GetFunctionArgs(); + + Utils.ExtractParameterNames(args, m_name, script); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = Run(args, script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + await script.GetFunctionArgsAsync(); + + Utils.ExtractParameterNames(args, m_name, script); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = await RunAsync(args, script); + return result; + } + + public Variable Run(List args = null, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = Utils.GetTempScript(m_body, m_stackLevel, m_name, script, + m_parentScript, m_parentOffset, instance); + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (script != null && debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(m_stackLevel.Id); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + public async Task RunAsync(List args = null, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = Utils.GetTempScript(m_body, m_stackLevel, m_name, script, + m_parentScript, m_parentOffset, instance); + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = await debugger.StepInFunctionIfNeeded(tempScript); + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = await tempScript.ExecuteAsync(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(m_stackLevel.Id); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + + public static Task Run(string functionName, + Variable arg1 = null, Variable arg2 = null, Variable arg3 = null, ParsingScript script = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + if (arg3 != null) + { + args.Add(arg3); + } + + Variable result = customFunction.Run(args, script); + return Task.FromResult( result ); + } + + public static async Task RunAsync(string functionName, + Variable arg1 = null, Variable arg2 = null, Variable arg3 = null, ParsingScript script = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + if (arg3 != null) + { + args.Add(arg3); + } + + Variable result = await customFunction.RunAsync(args, script); + return result; + } + + public override ParserFunction NewInstance() + { + var newInstance = (CustomFunction)this.MemberwiseClone(); + newInstance.m_stackLevel = null; + return newInstance; + } + + public ParsingScript ParentScript { set { m_parentScript = value; } } + public int ParentOffset { set { m_parentOffset = value; } } + public string Body { get { return m_body; } } + + public int ArgumentCount { get { return m_args.Length; } } + public string Argument(int nIndex) { return m_args[nIndex]; } + + public StackLevel NamespaceData { get; set; } + + public int DefaultArgsCount + { + get + { + return m_defaultArgs.Count; + } + } + + public string Header + { + get + { + return Constants.FUNCTION + " " + Constants.GetRealName(Name) + " " + + Constants.START_ARG + string.Join(", ", m_args) + + Constants.END_ARG + " " + Constants.START_GROUP; + } + } + + protected string m_body; + protected string[] m_args; + protected ParsingScript m_parentScript = null; + protected int m_parentOffset = 0; + protected StackLevel m_stackLevel; + + List m_defaultArgs = new List(); + Dictionary m_defArgMap = new Dictionary(); + + public Dictionary ArgMap { get; private set; } = new Dictionary(); + public string[] RealArgs { get; private set; } + } + + class StringOrNumberFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // First check if the passed expression is a string between quotes. + if (Item.Length > 1 && + ((Item[0] == Constants.QUOTE && Item[Item.Length - 1] == Constants.QUOTE) || + (Item[0] == Constants.QUOTE1 && Item[Item.Length - 1] == Constants.QUOTE1))) + { + return new Variable(Item.Substring(1, Item.Length - 2)); + } + + // Otherwise this should be a number. + double num = Utils.ConvertToDouble(Item, script); + return new Variable(num); + } + + public string Item { private get; set; } + } + + class AddFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue), script); + } + + return currentValue; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue), script); + } + + return currentValue; + } + } + class RemoveFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + string varName = args[0].AsString(); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func, script); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = args[1]; + + bool removed = currentValue.Tuple.Remove(item); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue), script); + return new Variable(removed); + } + } + class RemoveAtFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func, script); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = Utils.GetItem(script); + Utils.CheckNonNegativeInt(item, script); + + currentValue.Tuple.RemoveAt(item.AsInt()); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue), script); + return Variable.EmptyInstance; + } + } + + class ContainsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + List arrayIndices = Utils.GetArrayIndices(script, varName, (newVarName) => { varName = newVarName; } ); + + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func, script); + Variable currentValue = func.GetValue(script); + + // 2b. Special dealings with arrays: + Variable query = arrayIndices.Count > 0 ? + Utils.ExtractArrayElement(currentValue, arrayIndices, script) : + currentValue; + + // 3. Get the value to be looked for. + Variable searchValue = Utils.GetItem(script); + Utils.CheckNotEnd(script, m_name); + + // 4. Check if the value to search for exists. + bool exists = query.Exists(searchValue, true /* notEmpty */); + + script.MoveBackIf(Constants.START_GROUP); + return new Variable(exists); + } + } + + class FindIndexFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable var = Utils.GetSafeVariable(args, 0); + string val = Utils.GetSafeString(args, 1); + + int index = var.FindIndex(val); + + return new Variable(index); + } + } + + class UndefinedFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.UNDEFINED); + } + } + + class BoolFunction : ParserFunction, INumericFunction + { + bool m_value; + public BoolFunction(bool init) + { + m_value = init; + } + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(m_value); + } + } + class ToDoubleFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToDouble(arg.AsString()); + return new Variable(result); + } + } + class ToIntFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + int result = Utils.ConvertToInt(arg.AsString()); + return new Variable(result); + } + } + class ToBoolFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToBool(arg.AsString()) ? 1 : 0; + return new Variable(result); + } + } + class ToDecimalFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = Decimal.Parse(arg.AsString(), NumberStyles.Any).ToString(); + return new Variable(result); + } + } + class ToStringFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + Variable arg = args[0]; + string format = Utils.GetSafeString(args, 1); + + string result = arg.AsString(format); + return new Variable(result); + } + } + class IdentityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return script.Execute(Constants.END_ARG_ARRAY); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await script.ExecuteAsync(Constants.END_ARG_ARRAY); + } + } + + class ConstantsFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(m_name); + } + } + + class IfStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable result = Interpreter.Instance.ProcessIf(script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + Variable result = await Interpreter.Instance.ProcessIfAsync(script); + return result; + } + } + + class ForStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessFor(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessForAsync(script); + } + } + + class WhileStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessWhile(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessWhileAsync(script); + } + } + + class DoWhileStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessDoWhile(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return Interpreter.Instance.ProcessDoWhile(script); + } + } + + class SwitchStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessSwitch(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return Interpreter.Instance.ProcessSwitch(script); + } + } + + class CaseStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessCase(script, Name); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return Interpreter.Instance.ProcessCase(script, Name); + } + } + + class IncludeFile : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + string filename = args[0].AsString(); + return Execute(filename, script); + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 1, m_name, true); + string filename = args[0].AsString(); + return await ExecuteAsync(filename, script); + } + + public static Variable Execute(string filename, ParsingScript parentScript = null) + { + if (parentScript == null) + { + parentScript = new ParsingScript(""); + } + ParsingScript tempScript = parentScript.GetIncludeFileScript(filename); + + Variable result = null; + if (parentScript.Debugger != null) + { + result = parentScript.Debugger.StepInIncludeIfNeeded(tempScript).Result; + } + + while (tempScript.StillValid()) + { + result = tempScript.Execute(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + + public static async Task ExecuteAsync(string filename, ParsingScript parentScript = null) + { + if (parentScript == null) + { + parentScript = new ParsingScript(""); + } + ParsingScript tempScript = parentScript.GetIncludeFileScript(filename); + + Variable result = null; + if (parentScript.Debugger != null) + { + result = await parentScript.Debugger.StepInIncludeIfNeeded(tempScript); + } + + while (tempScript.StillValid()) + { + result = await tempScript.ExecuteAsync(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + } + + // Get a value of a variable or of an array element + public class GetVarFunction : ParserFunction + { + public GetVarFunction(Variable value) + { + m_value = value; + } + + protected override Variable Evaluate(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = Utils.GetArrayIndices(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; } ); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices, script); + if (script.Prev == '.') + { + script.Backward(); + } + + if (script.TryCurrent() != '.') + { + return result; + } + script.Forward(); + + m_propName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + Variable propValue = result.GetProperty(m_propName, script); + Utils.CheckNotNull(propValue, m_propName, script); + return propValue; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + string temp = m_propName; + m_propName = null; // Need this to reset for recursive calls + Variable propValue = m_value.Type == Variable.VarType.ENUM ? + m_value.GetEnumProperty(temp, script) : + m_value.GetProperty(temp, script); + Utils.CheckNotNull(propValue, temp, script); + return EvaluateFunction(propValue, script, m_propName); + } + + // Otherwise just return the stored value. + return m_value; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = await Utils.GetArrayIndicesAsync(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; }); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices, script); + if (script.Prev == '.') + { + script.Backward(); + } + if (script.TryCurrent() != '.') + { + return result; + } + + script.Forward(); + m_propName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Variable propValue = await result.GetPropertyAsync(m_propName, script); + Utils.CheckNotNull(propValue, m_propName, script); + return propValue; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + string temp = m_propName; + m_propName = null; // Need this to reset for recursive calls + + Variable propValue = m_value.Type == Variable.VarType.ENUM ? + m_value.GetEnumProperty(temp, script) : + await m_value.GetPropertyAsync(temp, script); + Utils.CheckNotNull(propValue, temp, script); + return await EvaluateFunctionAsync(propValue, script, m_propName); + } + + // Otherwise just return the stored value. + return m_value; + } + + public static Variable EvaluateFunction(Variable var, ParsingScript script, string m_propName) + { + if (var.CustomFunctionGet != null) + { + List args = script.Prev == '(' ? script.GetFunctionArgs() : new List(); + if (var.StackVariables != null) + { + args.AddRange(var.StackVariables); + } + return var.CustomFunctionGet.Run(args, script); + } + if (!string.IsNullOrWhiteSpace(var.CustomGet)) + { + return ParsingScript.RunString(var.CustomGet); + } + return var; + } + + public static async Task EvaluateFunctionAsync(Variable var, ParsingScript script, string m_propName) + { + if (var.CustomFunctionGet != null) + { + List args = script.Prev == '(' ? await script.GetFunctionArgsAsync() : new List(); + if (var.StackVariables != null) + { + args.AddRange(var.StackVariables); + } + return await var.CustomFunctionGet.RunAsync(args, script); + } + if (!string.IsNullOrWhiteSpace(var.CustomGet)) + { + return ParsingScript.RunString(var.CustomGet); + } + return var; + } + + public int Delta + { + set { m_delta = value; } + } + public Variable Value + { + get { return m_value; } + } + public List Indices + { + set { m_arrayIndices = value; } + } + public string PropertyName + { + set { m_propName = value; } + } + + Variable m_value; + int m_delta = 0; + List m_arrayIndices = null; + string m_propName; + } + class IncrementDecrementFunction : ActionFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool prefix = string.IsNullOrWhiteSpace(m_name); + if (prefix) + {// If it is a prefix we do not have the variable name yet. + Name = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + } + + Utils.CheckForValidName(Name, script); + + // Value to be added to the variable: + int valueDelta = m_action == Constants.INCREMENT ? 1 : -1; + int returnDelta = prefix ? valueDelta : 0; + + // Check if the variable to be set has the form of x[a][b], + // meaning that this is an array element. + double newValue = 0; + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetVariable(m_name, script); + Utils.CheckNotNull(m_name, func, script); + + Variable currentValue = func.GetValue(script); + currentValue = currentValue.DeepClone(); + + if (arrayIndices.Count > 0 || script.TryCurrent() == Constants.START_ARRAY) + { + if (prefix) + { + string tmpName = m_name + script.Rest; + int delta = 0; + arrayIndices = Utils.GetArrayIndices(script, tmpName, delta, (string t, int d) => { tmpName = t; delta = d; }); + script.Forward(Math.Max(0, delta - tmpName.Length)); + } + + Variable element = Utils.ExtractArrayElement(currentValue, arrayIndices, script); + script.MoveForwardIf(Constants.END_ARRAY); + + newValue = element.Value + returnDelta; + element.Value += valueDelta; + } + else + { // A normal variable. + newValue = currentValue.Value + returnDelta; + currentValue.Value += valueDelta; + } + + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue), script); + return new Variable(newValue); + } + + override public ParserFunction NewInstance() + { + return new IncrementDecrementFunction(); + } + } + + class OperatorAssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // Value to be added to the variable: + Variable right = Utils.GetItem(script); + + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetVariable(m_name, script); + Utils.CheckNotNull(func, m_name, script); + + Variable currentValue = func.GetValue(script); + currentValue = currentValue.DeepClone(); + Variable left = currentValue; + + if (arrayIndices.Count > 0) + {// array element + left = Utils.ExtractArrayElement(currentValue, arrayIndices, script); + script.MoveForwardIf(Constants.END_ARRAY); + } + + if (left.Type == Variable.VarType.NUMBER) + { + NumberOperator(left, right, m_action); + } + else + { + StringOperator(left, right, m_action); + } + + if (arrayIndices.Count > 0) + {// array element + AssignFunction.ExtendArray(currentValue, arrayIndices, 0, left); + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue), script); + } + else + { + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(left), script); + } + return left; + } + + static void NumberOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + valueA.Value += valueB.Value; + break; + case "-=": + valueA.Value -= valueB.Value; + break; + case "*=": + valueA.Value *= valueB.Value; + break; + case "/=": + valueA.Value /= valueB.Value; + break; + case "%=": + valueA.Value %= valueB.Value; + break; + case "&=": + valueA.Value = (int)valueA.Value & (int)valueB.Value; + break; + case "|=": + valueA.Value = (int)valueA.Value | (int)valueB.Value; + break; + case "^=": + valueA.Value = (int)valueA.Value ^ (int)valueB.Value; + break; + } + } + static void StringOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + if (valueB.Type == Variable.VarType.STRING) + { + valueA.String += valueB.AsString(); + } + else + { + valueA.String += valueB.Value; + } + break; + } + } + + override public ParserFunction NewInstance() + { + return new OperatorAssignFunction(); + } + } + + class AssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Assign(script, m_name); + } + + public Variable Assign(ParsingScript script, string varName, bool localIfPossible = false) + { + m_name = Constants.GetRealName(varName); + script.CurrentAssign = m_name; + Variable varValue = Utils.GetItem(script); + + script.MoveBackIfPrevious(Constants.END_ARG); + varValue.TrySetAsMap(); + + if (script.Current == ' ' || script.Prev == ' ') + { + Utils.ThrowErrorMsg("Can't process expression [" + script.Rest + "].", + script, m_name); + } + + // First try processing as an object (with a dot notation): + Variable result = ProcessObject(script, varValue); + if (result != null) + { + if (script.CurrentClass == null && script.ClassInstance == null) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(result), script, localIfPossible); + } + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue), script, localIfPossible); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + } + + Variable array; + + ParserFunction pf = ParserFunction.GetVariable(m_name, script); + array = pf != null ? (pf.GetValue(script)) : new Variable(); + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array), script, localIfPossible); + return array; + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + return await AssignAsync(script, m_name); + } + + public async Task AssignAsync(ParsingScript script, string varName, bool localIfPossible = false) + { + m_name = Constants.GetRealName(varName); + script.CurrentAssign = m_name; + Variable varValue = await Utils.GetItemAsync(script); + + script.MoveBackIfPrevious(Constants.END_ARG); + varValue.TrySetAsMap(); + + if (script.Current == ' ' || script.Prev == ' ') + { + Utils.ThrowErrorMsg("Can't process expression [" + script.Rest + "].", + script, m_name); + } + + // First try processing as an object (with a dot notation): + Variable result = await ProcessObjectAsync(script, varValue); + if (result != null) + { + if (script.CurrentClass == null) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(result), script, localIfPossible); + } + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = await Utils.GetArrayIndicesAsync(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue), script, localIfPossible); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + } + + Variable array; + + ParserFunction pf = ParserFunction.GetVariable(m_name, script); + array = pf != null ? (await pf.GetValueAsync(script)) : new Variable(); + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array), script, localIfPossible); + return array; + } + + Variable ProcessObject(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + varValue = script.ClassInstance.SetProperty(m_name, varValue).Result; + return varValue.DeepClone(); + } + + int ind = varName.IndexOf('.'); + if (ind <= 0) + { + return null; + } + + Utils.CheckForValidName(varName, script); + + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + if (ParserFunction.TryAddToNamespace(prop, name, varValue)) + { + return varValue.DeepClone(); + } + + ParserFunction existing = ParserFunction.GetVariable(name, script); + Variable baseValue = existing != null ? existing.GetValue(script) : new Variable(Variable.VarType.ARRAY); + baseValue.SetProperty(prop, varValue, script, name); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue), script); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + async Task ProcessObjectAsync(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + await script.ClassInstance.SetProperty(m_name, varValue); + return varValue.DeepClone(); + } + + int ind = varName.IndexOf('.'); + if (ind <= 0) + { + return null; + } + + Utils.CheckForValidName(varName, script); + + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + if (ParserFunction.TryAddToNamespace(prop, name, varValue)) + { + return varValue.DeepClone(); + } + + ParserFunction existing = ParserFunction.GetVariable(name, script); + Variable baseValue = existing != null ? await existing.GetValueAsync(script) : new Variable(Variable.VarType.ARRAY); + await baseValue.SetPropertyAsync(prop, varValue, script, name); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue), script); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + + + override public ParserFunction NewInstance() + { + return new AssignFunction(); + } + + public static void ExtendArray(Variable parent, + List arrayIndices, + int indexPtr, + Variable varValue) + { + if (arrayIndices.Count <= indexPtr) + { + return; + } + + Variable index = arrayIndices[indexPtr]; + int currIndex = ExtendArrayHelper(parent, index); + + if (arrayIndices.Count - 1 == indexPtr) + { + parent.Tuple[currIndex] = varValue; + return; + } + + Variable son = parent.Tuple[currIndex]; + ExtendArray(son, arrayIndices, indexPtr + 1, varValue); + } + + private static int ExtendArrayHelper(Variable parent, Variable indexVar) + { + parent.SetAsArray(); + + int arrayIndex = parent.GetArrayIndex(indexVar); + if (arrayIndex < 0) + { + // This is not a "normal index" but a new string for the dictionary. + string hash = indexVar.AsString(); + arrayIndex = parent.SetHashVariable(hash, Variable.NewEmpty()); + return arrayIndex; + } + + if (parent.Tuple.Count <= arrayIndex) + { + for (int i = parent.Tuple.Count; i <= arrayIndex; i++) + { + parent.Tuple.Add(Variable.NewEmpty()); + } + } + return arrayIndex; + } + } + + class DeepCopyFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varValue = Utils.GetItem(script); + return varValue.DeepClone(); + } + } + + class TokenizeLinesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2, 0); + string sepStr = Utils.GetSafeString(args, 3, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + // var function = ParserFunction.GetVariable(varName, script); + Variable allTokensVar = new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; +#pragma warning disable 219 + // bugbug - the toAdd has side effects + Variable toAdd = new Variable(counter - fromLine); +#pragma warning restore 219 + string line = lineVar.AsString(); + var tokens = line.Split(sep); + Variable tokensVar = new Variable(Variable.VarType.ARRAY); + foreach (string token in tokens) + { + tokensVar.Tuple.Add(new Variable(token)); + } + allTokensVar.Tuple.Add(tokensVar); + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(allTokensVar), script); + + return Variable.EmptyInstance; + } + } + + class AddVariablesToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2); + string hash2 = Utils.GetSafeString(args, 3); + string sepStr = Utils.GetSafeString(args, 4, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + var function = ParserFunction.GetVariable(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; + Variable toAdd = new Variable(counter - fromLine); + string line = lineVar.AsString(); + var tokens = line.Split(sep); + string hash = tokens[0]; + mapVar.AddVariableToHash(hash, toAdd); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar), script); + return Variable.EmptyInstance; + } + } + class AddVariableToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable toAdd = Utils.GetSafeVariable(args, 1); + string hash = Utils.GetSafeString(args, 2); + + var function = ParserFunction.GetVariable(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + mapVar.AddVariableToHash(hash, toAdd); + for (int i = 3; i < args.Count; i++) + { + string hash2 = Utils.GetSafeString(args, 3); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar), script); + + return Variable.EmptyInstance; + } + } + class TokenCounterFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable all = Utils.GetSafeVariable(args, 0); + string varName = Utils.GetSafeString(args, 1); + int index = Utils.GetSafeInt(args, 2); + + // var function = ParserFunction.GetVariable(varName, script); + Variable mapVar = new Variable(Variable.VarType.ARRAY); + + if (all.Tuple == null) + { + return Variable.EmptyInstance; + } + + string currentValue = ""; + int currentCount = 0; + + int globalCount = 0; + + for (int i = 0; i < all.Tuple.Count; i++) + { + Variable current = all.Tuple[i]; + if (current.Tuple == null || current.Tuple.Count < index) + { + break; + } + string newValue = current.Tuple[index].AsString(); + if (currentValue != newValue) + { + currentValue = newValue; + currentCount = 0; + } + mapVar.Tuple.Add(new Variable(currentCount)); + currentCount++; + globalCount++; + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar), script); + // Script - Need to enable the warnings +#pragma warning restore 219 + return mapVar; + } + } + + class TypeFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + bool complexVariable = Utils.GetSafeInt(args, 1, 0) == 1; + Variable element = null; + if (complexVariable) + { + element = Utils.GetVariable(args[0].AsString(), script, false); + } + if (element == null) + { + element = Utils.GetSafeVariable(args, 0); + } + + string type = element.GetTypeString(); + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(type); + return newValue; + } + } + + class SizeFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.END_ARG_ARRAY); + Utils.CheckNotEnd(script, m_name); + + List arrayIndices = Utils.GetArrayIndices(script, varName, (newName) => { varName = newName; } ); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetVariable(varName, script); + Utils.CheckNotNull(varName, func, script); + Variable currentValue = func.GetValue(script); + Variable element = currentValue; + + // 2b. Special case for an array. + if (arrayIndices.Count > 0) + {// array element + element = Utils.ExtractArrayElement(currentValue, arrayIndices, script); + script.MoveForwardIf(Constants.END_ARRAY); + } + + // 3. Take either the length of the underlying tuple or + // string part if it is defined, + // or the numerical part converted to a string otherwise. + int size = element.GetSize(); + + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(size); + return newValue; + } + } + + class DefineLocalFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable currentValue = Utils.GetSafeVariable(args, 1); + + if (currentValue == null) + { + currentValue = new Variable(""); + } + + if (script.StackLevel != null) + { + ParserFunction.AddLocalVariable(new GetVarFunction(currentValue), varName); + } + else if (script.CurrentClass != null) + { + Utils.ThrowErrorMsg(m_name + " function can't be defined inside of a class.", + script, m_name); + } + else + { + string scopeName = Path.GetFileName(script.Filename); + ParserFunction.AddLocalScopeVariable(varName, scopeName, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + } + + class GetPropertiesFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + Variable baseValue = args[0]; + List props = baseValue.GetProperties(); + return new Variable(props); + } + } + + class GetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = baseValue.GetProperty(propName, script); + Utils.CheckNotNull(propValue, propName, script); + + return new Variable(propValue); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = await baseValue.GetPropertyAsync(propName, script); + Utils.CheckNotNull(propValue, propName, script); + + return new Variable(propValue); + } + public static Variable GetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = baseValue.GetProperty(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName, script); + + return new Variable(propValue); + } + public static async Task GetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = await baseValue.GetPropertyAsync(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName, script); + + return new Variable(propValue); + } + } + + class SetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = baseValue.SetProperty(propName, propValue, script); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue), script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = await baseValue.SetPropertyAsync(propName, propValue, script); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue), script); + return result; + } + + public static Variable SetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = baseValue.SetProperty(sPropertyName, propValue, script); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue), script); + return result; + } + public static async Task SetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = await baseValue.SetPropertyAsync(sPropertyName, propValue, script); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue), script); + return result; + } + } + + class CancelFunction : ParserFunction + { + public static bool Canceled { get; set; } + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 0, m_name, true); + + bool mode = Utils.GetSafeInt(args, 0, 1) == 1; + Canceled = mode; + + return new Variable(Canceled); + } + } + + public class ScheduleRunFunction : ParserFunction + { + static Dictionary m_timers = + new Dictionary(); + + bool m_startTimer; + + public ScheduleRunFunction(bool startTimer) + { + m_startTimer = startTimer; + } + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + + if (!m_startTimer) + { + Utils.CheckArgs(args.Count, 1, m_name); + string cancelTimerId = Utils.GetSafeString(args, 0); + System.Timers.Timer cancelTimer; + if (m_timers.TryGetValue(cancelTimerId, out cancelTimer)) + { + cancelTimer.Stop(); + cancelTimer.Dispose(); + m_timers.Remove(cancelTimerId); + } + return Variable.EmptyInstance; + } + + Utils.CheckArgs(args.Count, 2, m_name); + int timeout = args[0].AsInt(); + string strAction = args[1].AsString(); + string arg = Utils.GetSafeString(args, 2); + string timerId = Utils.GetSafeString(args, 3); + bool autoReset = Utils.GetSafeInt(args, 4, 0) != 0; + + arg = Utils.ProtectQuotes(arg); + timerId = Utils.ProtectQuotes(timerId); + + System.Timers.Timer pauseTimer = new System.Timers.Timer(timeout); + pauseTimer.Elapsed += (sender, e) => + { + if (!autoReset) + { + pauseTimer.Stop(); + pauseTimer.Dispose(); + m_timers.Remove(timerId); + } + string body = string.Format("{0}({1},{2});", strAction, + "\"" + arg + "\"", "\"" + timerId + "\""); + + ParsingScript tempScript = new ParsingScript(body); + tempScript.Execute(); + }; + pauseTimer.AutoReset = autoReset; + m_timers[timerId] = pauseTimer; + + pauseTimer.Start(); + + return Variable.EmptyInstance; + } + } + + public class SingletonFunction : ParserFunction + { + static Dictionary m_singletons = + new Dictionary(); + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string expr = args[0].AsString(); + Dictionary char2Line; + expr = Utils.ConvertToScript(expr, out char2Line); + + Variable result; + if (m_singletons.TryGetValue(expr, out result)) + { + return result; + } + + ParsingScript tempScript = new ParsingScript(expr); + result = tempScript.Execute(); + + m_singletons[expr] = result; + + return result; + } + } + + class GetColumnFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable arrayVar = Utils.GetSafeVariable(args, 0); + int col = Utils.GetSafeInt(args, 1); + int fromCol = Utils.GetSafeInt(args, 2, 0); + + var tuple = arrayVar.Tuple; + + List result = new List(tuple.Count); + for (int i = fromCol; i < tuple.Count; i++) + { + Variable current = tuple[i]; + if (current.Tuple == null || current.Tuple.Count <= col) + { + throw new ArgumentException(m_name + ": Index [" + col + "] doesn't exist in column " + + i + "/" + (tuple.Count - 1)); + } + result.Add(current.Tuple[col]); + } + + return new Variable(result); + } + } + + class GetAllKeysFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varName = Utils.GetItem(script); + Utils.CheckNotNull(varName, m_name, script); + + List results = varName.GetAllKeys(); + + return new Variable(results); + } + } + + class CheckLoaderMainFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool isMain = !string.IsNullOrWhiteSpace(script.MainFilename) && + script.MainFilename == script.Filename; + + return new Variable(isMain); + } + } + + class ResetVariablesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + ParserFunction.CleanUpVariables(); + return Variable.EmptyInstance; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `currentValue` last assigned on line 1412 could be null and is dereferenced at line 1416, column 13. + +### Severity: +ERROR + +### Procedure: +Variable AddFunction.Evaluate(ParsingScript) + +### File: +cscs/Functions.Flow.cs + +### Key: +Functions.Flow.cs|Evaluate|NULL_DEREFERENCE + +### Node Key: +722f645c76bfb99c288630c5b05ba5dc + +### Hash: +e0a75025508ed3930f8cabca0f7a1d83 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1930/instruction.md b/inferredbugs-1930/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5ee5b047a79235eda389b20b09d8100730beaa5c --- /dev/null +++ b/inferredbugs-1930/instruction.md @@ -0,0 +1,1616 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cscs +**Bug ID:** 23 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; + +namespace SplitAndMerge +{ + class BreakStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.BREAK); + } + } + class ContinueStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.CONTINUE); + } + } + + class ReturnStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = Utils.GetItem(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + } + + class TryBlock : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessTry(script); + } + } + + class ExitFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Environment.Exit(0); + return Variable.EmptyInstance; + } + } + + class ThrowFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = Utils.GetItem(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + } + + class ShowFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + string funcName = args[0].AsString(); + + ParserFunction function = ParserFunction.GetFunction(funcName, script); + CustomFunction custFunc = function as CustomFunction; + Utils.CheckNotNull(funcName, custFunc); + + string body = Utils.BeautifyScript(custFunc.Body, custFunc.Header); + Utils.PrintScript(body, script); + + return new Variable(body); + } + } + + class FunctionCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string funcName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + //Interpreter.Instance.AppendOutput("Registering function [" + funcName + "] ..."); + + string[] args = Utils.GetFunctionSignature(script); + if (args.Length == 1 && string.IsNullOrWhiteSpace(args[0])) + { + args = new string[0]; + } + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + int lineNumber = 0; + /*string line = */script.GetOriginalLine(out lineNumber); + + int parentOffset = script.Pointer; + + if (script.CurrentClass != null) + { + parentOffset += script.CurrentClass.ParentOffset; + } + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, Constants.END_GROUP); + + CustomFunction customFunc = new CustomFunction(funcName, body, args); + customFunc.ParentScript = script; + customFunc.ParentOffset = parentOffset; + + if (script.CurrentClass != null) + { + script.CurrentClass.AddMethod(funcName, args, customFunc); + } + else + { + ParserFunction.RegisterFunction(funcName, customFunc, false /* not native */); + } + + return Variable.EmptyInstance; + } + } + + public class CSCSClass : ParserFunction + { + public CSCSClass() {} + + public CSCSClass(string className) + { + m_name = className; + RegisterClass(className, this); + } + + public CSCSClass(string className, string[] baseClasses) + { + m_name = className; + RegisterClass(className, this); + + foreach (string baseClass in baseClasses) + { + var bc = CSCSClass.GetClass(baseClass); + if (bc == null) + { + throw new ArgumentException("Base Class [" + baseClass + "] not found."); + } + + foreach (var entry in bc.m_classProperties) + { + m_classProperties[entry.Key] = entry.Value; + } + foreach (var entry in bc.m_customFunctions) + { + m_customFunctions[entry.Key] = entry.Value; + } + } + } + + public static void RegisterClass(string className, CSCSClass obj) + { + s_allClasses[className] = obj; + } + + protected override Variable Evaluate(ParsingScript script) + { + script.GetFunctionArgs(); + + // TODO: Work in progress, currently not functional + return Variable.EmptyInstance; + } + + public void AddMethod(string name, string[] args, CustomFunction method) + { + if (name == m_name) + { + m_constructors[args.Length] = method; + } + else + { + m_customFunctions[name] = method; + } + } + + public void AddProperty(string name, Variable property) + { + m_classProperties[name] = property; + } + + public static CSCSClass GetClass(string name) + { + CSCSClass theClass = null; + s_allClasses.TryGetValue(name, out theClass); + return theClass; + } + + static Dictionary s_allClasses = + new Dictionary(); + + Dictionary m_constructors = + new Dictionary(); + Dictionary m_customFunctions = + new Dictionary(); + Dictionary m_classProperties = + new Dictionary(); + + public ParsingScript ParentScript = null; + public int ParentOffset = 0; + + public class ClassInstance : ScriptObject + { + public ClassInstance(string instanceName, string className, List args, + ParsingScript script = null) + { + InstanceName = instanceName; + m_cscsClass = CSCSClass.GetClass(className); + if (m_cscsClass == null) + { + throw new ArgumentException("Class [" + className + "] not found."); + } + + // Copy over all the properties defined for this class. + foreach (var entry in m_cscsClass.m_classProperties) + { + SetProperty(entry.Key, entry.Value); + } + + // Run "constructor" if any is defined for this number of args. + CustomFunction constructor = null; + if (m_cscsClass.m_constructors.TryGetValue(args.Count, out constructor)) + { + constructor.Run(args, script, this); + } + } + + public string InstanceName { get; set; } + CSCSClass m_cscsClass; + + Dictionary m_properties = new Dictionary(); + HashSet m_propSet = new HashSet(); + + public Variable SetProperty(string name, Variable value) + { + m_properties[name] = value; + m_propSet.Add(name); + return Variable.EmptyInstance; + } + + public Variable GetProperty(string name, List args = null, ParsingScript script = null) + { + Variable value = null; + if (m_properties.TryGetValue(name, out value)) + { + return value; + } + + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out customFunction)) + { + return null; + } + if (args == null) + { + return Variable.EmptyInstance; + } + + foreach (var entry in m_cscsClass.m_classProperties) + { + args.Add(entry.Value); + } + + Variable result = customFunction.Run(args, script, this); + return result; + } + + public List> GetPropList() + { + List> props = new List>(); + foreach (var entry in m_properties) + { + props.Add(new KeyValuePair(entry.Key, entry.Value)); + } + return props; + } + + public List GetProperties() + { + List props = new List(m_properties.Keys); + props.AddRange(m_cscsClass.m_customFunctions.Keys); + + return props; + } + public bool PropertyExists(string name) + { + return m_propSet.Contains(name); + } + } + } + + class NewObjectFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + script.MoveForwardIf(Constants.START_ARG); + List args = script.GetFunctionArgs(); + + CompiledClass csClass = CSCSClass.GetClass(className) as CompiledClass; + if (csClass != null) + { + ScriptObject obj = csClass.GetImplementation(args); + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + } + + public class ClassCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + string[] baseClasses = Utils.GetBaseClasses(script); + CSCSClass newClass = new CSCSClass(className, baseClasses); + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + + newClass.ParentOffset = script.Pointer; + newClass.ParentScript = script; + int lineNumber = 0; + /*string line = */script.GetOriginalLine(out lineNumber); + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + + Variable result = null; + ParsingScript tempScript = new ParsingScript(body); + //tempScript.ScriptOffset = newClass.ParentOffset; + tempScript.Char2Line = script.Char2Line; + tempScript.Filename = script.Filename; + tempScript.OriginalScript = script.OriginalScript; + tempScript.CurrentClass = newClass; + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.DisableBreakpoints = true; + + /*Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript); + }*/ + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + + return Variable.EmptyInstance; + } + } + + public class CustomFunction : ParserFunction + { + internal CustomFunction(string funcName, + string body, string[] args) + { + m_name = funcName; + m_body = body; + m_args = args; + + for (int i = 0; i < args.Length; i++) + { + string arg = args[i]; + int ind = arg.IndexOf("="); + if (ind > 0) + { + m_args[i] = arg.Substring(0, ind).Trim(); + string defValue = ind >= arg.Length - 1 ? "" : arg.Substring(ind + 1).Trim(); + if (defValue.StartsWith("\"")) + { + defValue = defValue.Substring(1); + } + if (defValue.EndsWith("\"")) + { + defValue = defValue.Substring(0, defValue.Length - 1); + } + m_defaultArgs.Add(new Variable(defValue)); + } + } + } + + public void RegisterArguments(List args, + List> args2 = null) + { + int missingArgs = m_args.Length - args.Count; + if (missingArgs > 0 && missingArgs <= m_defaultArgs.Count) + { + for (int i = m_defaultArgs.Count - missingArgs; i < m_defaultArgs.Count; i++) + { + args.Add(m_defaultArgs[i]); + } + } + + StackLevel stackLevel = new StackLevel(m_name); + + if (args2 != null) + { + foreach (var entry in args2) + { + var arg = new GetVarFunction(entry.Value); + arg.Name = entry.Key; + stackLevel.Variables[entry.Key] = arg; + } + } + + int maxSize = Math.Min(args.Count, m_args.Length); + for (int i = 0; i < maxSize; i++) + { + var arg = new GetVarFunction(args[i]); + arg.Name = m_args[i]; + stackLevel.Variables[m_args[i]] = arg; + } + + ParserFunction.AddLocalVariables(stackLevel); + } + + protected override Variable Evaluate(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + script.GetFunctionArgs(); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = Run(args, script); + return result; + } + + public Variable Run(List args, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = new ParsingScript(m_body); + tempScript.ScriptOffset = m_parentOffset; + if (m_parentScript != null) + { + tempScript.Char2Line = m_parentScript.Char2Line; + tempScript.Filename = m_parentScript.Filename; + tempScript.OriginalScript = m_parentScript.OriginalScript; + } + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.ClassInstance = instance; + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript); + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + + public static Variable Run(string functionName, Variable arg1 = null, Variable arg2 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + + Variable result = customFunction.Run(args); + return result; + } + + public ParsingScript ParentScript { set { m_parentScript = value; } } + public int ParentOffset { set { m_parentOffset = value; } } + public string Body { get { return m_body; } } + + public int ArgumentCount { get { return m_args.Length; } } + public string Argument(int nIndex) { return m_args[nIndex]; } + + public string Header + { + get + { + return Constants.FUNCTION + " " + Name + " " + + Constants.START_ARG + string.Join(", ", m_args) + + Constants.END_ARG + " " + Constants.START_GROUP; + } + } + + protected string m_body; + protected string[] m_args; + List m_defaultArgs = new List(); + protected ParsingScript m_parentScript = null; + protected int m_parentOffset = 0; + } + + class StringOrNumberFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // First check if the passed expression is a string between quotes. + if (Item.Length > 1 && + Item[0] == Constants.QUOTE && + Item[Item.Length - 1] == Constants.QUOTE) + { + return new Variable(Item.Substring(1, Item.Length - 2)); + } + + // Otherwise this should be a number. + double num = Utils.ConvertToDouble(Item, "StringOrNumber"); + /*if (!Double.TryParse(Item, NumberStyles.Number | + NumberStyles.AllowExponent | + NumberStyles.Float, + CultureInfo.InvariantCulture, out num)) { + Utils.ThrowException(script, "parseToken", Item, "parseTokenExtra"); + }*/ + return new Variable(num); + } + + public string Item { private get; set; } + } + + class AddFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + } + class RemoveFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + string varName = args[0].AsString(); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = args[1]; + + bool removed = currentValue.Tuple.Remove(item); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return new Variable(removed); + } + } + class RemoveAtFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = Utils.GetItem(script); + Utils.CheckNonNegativeInt(item); + + currentValue.Tuple.RemoveAt(item.AsInt()); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return Variable.EmptyInstance; + } + } + + class ContainsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + List arrayIndices = Utils.GetArrayIndices(script, ref varName); + + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + + // 2b. Special dealings with arrays: + Variable query = arrayIndices.Count > 0 ? + Utils.ExtractArrayElement(currentValue, arrayIndices) : + currentValue; + + // 3. Get the value to be looked for. + Variable searchValue = Utils.GetItem(script); + Utils.CheckNotEnd(script, m_name); + + // 4. Check if the value to search for exists. + bool exists = query.Exists(searchValue, true /* notEmpty */); + + script.MoveBackIf(Constants.START_GROUP); + return new Variable(exists); + } + } + + class FindIndexFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable var = Utils.GetSafeVariable(args, 0); + string val = Utils.GetSafeString(args, 1); + + int index = var.FindIndex(val); + + return new Variable(index); + } + } + + class BoolFunction : ParserFunction, INumericFunction + { + bool m_value; + public BoolFunction(bool init) + { + m_value = init; + } + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(m_value); + } + } + class ToDoubleFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToDouble(arg.AsString()); + return new Variable(result); + } + } + class ToIntFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + int result = Utils.ConvertToInt(arg.AsString()); + return new Variable(result); + } + } + class ToBoolFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToBool(arg.AsString()) ? 1 : 0; + return new Variable(result); + } + } + class ToDecimalFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = Decimal.Parse(arg.AsString(), NumberStyles.Any).ToString(); + return new Variable(result); + } + } + class ToStringFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = arg.AsString(); + return new Variable(result); + } + } + class IdentityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return script.ExecuteTo(Constants.END_ARG); + } + } + + class IfStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable result = Interpreter.Instance.ProcessIf(script); + return result; + } + } + + class ForStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessFor(script); + } + } + + class WhileStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessWhile(script); + } + } + + class IncludeFile : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + string filename = args[0].AsString(); + string[] lines = Utils.GetFileLines(filename); + + string includeFile = string.Join(Environment.NewLine, lines); + Dictionary char2Line; + string includeScript = Utils.ConvertToScript(includeFile, out char2Line); + ParsingScript tempScript = new ParsingScript(includeScript, 0, char2Line); + tempScript.Filename = filename; + tempScript.OriginalScript = string.Join(Constants.END_LINE.ToString(), lines); + tempScript.ParentScript = script; + tempScript.InTryBlock = script.InTryBlock; + + Variable result = null; + if (script.Debugger != null) + { + result = script.Debugger.StepInIncludeIfNeeded(tempScript); + } + + while (tempScript.Pointer < includeScript.Length) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + } + + // Get a value of a variable or of an array element + public class GetVarFunction : ParserFunction + { + public GetVarFunction(Variable value) + { + m_value = value; + } + + protected override Variable Evaluate(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = Utils.GetArrayIndices(script, ref startName, ref m_delta); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices); + return result; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + Variable propValue = m_value.GetProperty(m_propName, script); + string temp = m_propName; + m_propName = null; // Need this trick in case the below statement throws + Utils.CheckNotNull(propValue, temp); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + + public int Delta + { + set { m_delta = value; } + } + public Variable Value + { + get { return m_value; } + } + public List Indices + { + set { m_arrayIndices = value; } + } + public string PropertyName + { + set { m_propName = value; } + } + + Variable m_value; + int m_delta = 0; + List m_arrayIndices = null; + string m_propName; + } + class IncrementDecrementFunction : ActionFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool prefix = string.IsNullOrWhiteSpace(m_name); + if (prefix) + {// If it is a prefix we do not have the variable name yet. + m_name = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + } + + // Value to be added to the variable: + int valueDelta = m_action == Constants.INCREMENT ? 1 : -1; + int returnDelta = prefix ? valueDelta : 0; + + // Check if the variable to be set has the form of x[a][b], + // meaning that this is an array element. + double newValue = 0; + List arrayIndices = Utils.GetArrayIndices(script, ref m_name); + + ParserFunction func = ParserFunction.GetFunction(m_name, script); + Utils.CheckNotNull(m_name, func); + + Variable currentValue = func.GetValue(script); + + if (arrayIndices.Count > 0 || script.TryCurrent() == Constants.START_ARRAY) + { + if (prefix) + { + string tmpName = m_name + script.Rest; + int delta = 0; + arrayIndices = Utils.GetArrayIndices(script, ref tmpName, ref delta); + script.Forward(Math.Max(0, delta - tmpName.Length)); + } + + Variable element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + + newValue = element.Value + returnDelta; + element.Value += valueDelta; + } + else + { // A normal variable. + newValue = currentValue.Value + returnDelta; + currentValue.Value += valueDelta; + } + + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + return new Variable(newValue); + } + + override public ParserFunction NewInstance() + { + return new IncrementDecrementFunction(); + } + } + + class OperatorAssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // Value to be added to the variable: + Variable right = Utils.GetItem(script); + + List arrayIndices = Utils.GetArrayIndices(script, ref m_name); + + ParserFunction func = ParserFunction.GetFunction(m_name, script); + Utils.CheckNotNull(m_name, func); + + Variable currentValue = func.GetValue(script); + Variable left = currentValue; + + if (arrayIndices.Count > 0) + {// array element + left = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + if (left.Type == Variable.VarType.NUMBER) + { + NumberOperator(left, right, m_action); + } + else + { + StringOperator(left, right, m_action); + } + + if (arrayIndices.Count > 0) + {// array element + AssignFunction.ExtendArray(currentValue, arrayIndices, 0, left); + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + } + else + { + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(left)); + } + return left; + } + + static void NumberOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + valueA.Value += valueB.Value; + break; + case "-=": + valueA.Value -= valueB.Value; + break; + case "*=": + valueA.Value *= valueB.Value; + break; + case "/=": + valueA.Value /= valueB.Value; + break; + case "%=": + valueA.Value %= valueB.Value; + break; + case "&=": + valueA.Value = (int)valueA.Value & (int)valueB.Value; + break; + case "|=": + valueA.Value = (int)valueA.Value | (int)valueB.Value; + break; + case "^=": + valueA.Value = (int)valueA.Value ^ (int)valueB.Value; + break; + } + } + static void StringOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + if (valueB.Type == Variable.VarType.STRING) + { + valueA.String += valueB.AsString(); + } + else + { + valueA.String += valueB.Value; + } + break; + } + } + + override public ParserFunction NewInstance() + { + return new OperatorAssignFunction(); + } + } + + class AssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.CurrentAssign = m_name; + Variable varValue = Utils.GetItem(script); + // First try processing as an object (with a dot notation): + Variable result = ProcessObject(script, varValue); + if (result != null) + { + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = Utils.GetArrayIndices(script, ref m_name); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue)); + return varValue.DeepClone(); + } + + Variable array; + + ParserFunction pf = ParserFunction.GetFunction(m_name, script); + if (pf != null) + { + array = pf.GetValue(script); + } + else + { + array = new Variable(); + } + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array)); + return array; + } + + Variable ProcessObject(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + script.ClassInstance.SetProperty(m_name, varValue); + return varValue.DeepClone(); + } + + int ind = varName.IndexOf("."); + if (ind <= 0) + { + return null; + } + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + ParserFunction existing = ParserFunction.GetFunction(name, script); + Variable baseValue = existing != null ? existing.GetValue(script) : new Variable(Variable.VarType.ARRAY); + baseValue.SetProperty(prop, varValue); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue)); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + + override public ParserFunction NewInstance() + { + return new AssignFunction(); + } + + public static void ExtendArray(Variable parent, + List arrayIndices, + int indexPtr, + Variable varValue) + { + if (arrayIndices.Count <= indexPtr) + { + return; + } + + Variable index = arrayIndices[indexPtr]; + int currIndex = ExtendArrayHelper(parent, index); + + if (arrayIndices.Count - 1 == indexPtr) + { + parent.Tuple[currIndex] = varValue; + return; + } + + Variable son = parent.Tuple[currIndex]; + ExtendArray(son, arrayIndices, indexPtr + 1, varValue); + } + + private static int ExtendArrayHelper(Variable parent, Variable indexVar) + { + parent.SetAsArray(); + + int arrayIndex = parent.GetArrayIndex(indexVar); + if (arrayIndex < 0) + { + // This is not a "normal index" but a new string for the dictionary. + string hash = indexVar.AsString(); + arrayIndex = parent.SetHashVariable(hash, Variable.NewEmpty()); + return arrayIndex; + } + + if (parent.Tuple.Count <= arrayIndex) + { + for (int i = parent.Tuple.Count; i <= arrayIndex; i++) + { + parent.Tuple.Add(Variable.NewEmpty()); + } + } + return arrayIndex; + } + } + + class DeepCopyFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varValue = Utils.GetItem(script); + return varValue.DeepClone(); ; + } + } + + class TokenizeLinesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2); + string sepStr = Utils.GetSafeString(args, 3, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + // var function = ParserFunction.GetFunction(varName, script); + Variable allTokensVar = new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; +#pragma warning disable 219 + // bugbug - the toAdd has side effects + Variable toAdd = new Variable(counter - fromLine); +#pragma warning restore 219 + string line = lineVar.AsString(); + var tokens = line.Split(sep); + Variable tokensVar = new Variable(Variable.VarType.ARRAY); + foreach (string token in tokens) + { + tokensVar.Tuple.Add(new Variable(token)); + } + allTokensVar.Tuple.Add(tokensVar); + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(allTokensVar)); + + return Variable.EmptyInstance; + } + } + + class AddVariablesToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2); + string hash2 = Utils.GetSafeString(args, 3); + string sepStr = Utils.GetSafeString(args, 4, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; + Variable toAdd = new Variable(counter - fromLine); + string line = lineVar.AsString(); + var tokens = line.Split(sep); + string hash = tokens[0]; + mapVar.AddVariableToHash(hash, toAdd); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + return Variable.EmptyInstance; + } + } + class AddVariableToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable toAdd = Utils.GetSafeVariable(args, 1); + string hash = Utils.GetSafeString(args, 2); + + var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + mapVar.AddVariableToHash(hash, toAdd); + for (int i = 3; i < args.Count; i++) + { + string hash2 = Utils.GetSafeString(args, 3); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + + return Variable.EmptyInstance; + } + } + class TokenCounterFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable all = Utils.GetSafeVariable(args, 0); + string varName = Utils.GetSafeString(args, 1); + int index = Utils.GetSafeInt(args, 2); + + // var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = new Variable(Variable.VarType.ARRAY); + + if (all.Tuple == null) + { + return Variable.EmptyInstance; + } + + string currentValue = ""; + int currentCount = 0; + + int globalCount = 0; + + for (int i = 0; i < all.Tuple.Count; i++) + { + Variable current = all.Tuple[i]; + if (current.Tuple == null || current.Tuple.Count < index) + { + break; + } + string newValue = current.Tuple[index].AsString(); + if (currentValue != newValue) + { + currentValue = newValue; + currentCount = 0; + } + mapVar.Tuple.Add(new Variable(currentCount)); + currentCount++; + globalCount++; + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + // Script - Need to enable the warnings +#pragma warning restore 219 + return mapVar; + } + } + + class TypeFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.END_ARG_ARRAY); + Utils.CheckNotEnd(script, m_name); + + List arrayIndices = Utils.GetArrayIndices(script, ref varName); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Variable element = currentValue; + + // 2b. Special case for an array. + if (arrayIndices.Count > 0) + {// array element + element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + // 3. Convert type to string. + string type = element.GetTypeString(); + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(type); + return newValue; + } + } + + class SizeFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.END_ARG_ARRAY); + Utils.CheckNotEnd(script, m_name); + + List arrayIndices = Utils.GetArrayIndices(script, ref varName); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Variable element = currentValue; + + // 2b. Special case for an array. + if (arrayIndices.Count > 0) + {// array element + element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + // 3. Take either the length of the underlying tuple or + // string part if it is defined, + // or the numerical part converted to a string otherwise. + int size = element.Type == Variable.VarType.ARRAY ? + element.Tuple.Count : + element.AsString().Length; + + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(size); + return newValue; + } + } + + class DefineLocalFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable currentValue = Utils.GetSafeVariable(args, 1); + + if (currentValue == null) + { + currentValue = new Variable(""); + } + + string scopeName = Path.GetFileName(script.Filename); + ParserFunction.AddLocalScopeVariable(varName, scopeName, + new GetVarFunction(currentValue)); + + return currentValue; + } + } + + class GetPropertiesFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + Variable baseValue = args[0]; + List props = baseValue.GetProperties(); + return new Variable(props); + } + } + + class GetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = baseValue.GetProperty(propName, script); + Utils.CheckNotNull(propValue, propName); + + return new Variable(propValue); + } + public static Variable GetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = baseValue.GetProperty(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName); + + return new Variable(propValue); + } + } + + class SetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = baseValue.SetProperty(propName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + public static Variable SetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = baseValue.SetProperty(sPropertyName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + } + + class CancelFunction : ParserFunction + { + public static bool Canceled { get; set; } + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 0, m_name, true); + + bool mode = Utils.GetSafeInt(args, 0, 1) == 1; + Canceled = mode; + + return new Variable(Canceled); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `currentValue` last assigned on line 1412 could be null and is dereferenced at line 1416, column 13. + +### Severity: +ERROR + +### Procedure: +Variable AddFunction.Evaluate(ParsingScript) + +### File: +cscs/Functions.Flow.cs + +### Key: +Functions.Flow.cs|Evaluate|NULL_DEREFERENCE + +### Node Key: +722f645c76bfb99c288630c5b05ba5dc + +### Hash: +e0a75025508ed3930f8cabca0f7a1d83 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-1939/instruction.md b/inferredbugs-1939/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7d79165fb1a42522159400297a72478561409c85 --- /dev/null +++ b/inferredbugs-1939/instruction.md @@ -0,0 +1,2322 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** cscs +**Bug ID:** 49 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Threading.Tasks; + +namespace SplitAndMerge +{ + class BreakStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.BREAK); + } + } + class ContinueStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(Variable.VarType.CONTINUE); + } + } + + class ReturnStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = Utils.GetItem(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + script.MoveForwardIf(Constants.SPACE); + if (!script.FromPrev(Constants.RETURN.Length).Contains(Constants.RETURN)) + { + script.Backward(); + } + Variable result = await Utils.GetItemAsync(script); + + // If we are in Return, we are done: + script.SetDone(); + result.IsReturn = true; + + return result; + } + } + + class TryBlock : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessTry(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessTryAsync(script); + } + } + + class ExitFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Environment.Exit(0); + return Variable.EmptyInstance; + } + } + + class ThrowFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = Utils.GetItem(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // 1. Extract what to throw. + Variable arg = await Utils.GetItemAsync(script); + + // 2. Convert it to a string. + string result = arg.AsString(); + + // 3. Throw it! + throw new ArgumentException(result); + } + } + + class ShowFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + string funcName = args[0].AsString(); + + ParserFunction function = ParserFunction.GetFunction(funcName, script); + CustomFunction custFunc = function as CustomFunction; + Utils.CheckNotNull(funcName, custFunc); + + string body = Utils.BeautifyScript(custFunc.Body, custFunc.Header); + Utils.PrintScript(body, script); + + return new Variable(body); + } + } + + class FunctionCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string funcName = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + funcName = Constants.ConvertName(funcName); + + string[] args = Utils.GetFunctionSignature(script); + if (args.Length == 1 && string.IsNullOrWhiteSpace(args[0])) + { + args = new string[0]; + } + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + int lineNumber = 0; + /*string line = */script.GetOriginalLine(out lineNumber); + + int parentOffset = script.Pointer; + + if (script.CurrentClass != null) + { + parentOffset += script.CurrentClass.ParentOffset; + } + + string body = Utils.GetBodyBetween(script, Constants.START_GROUP, Constants.END_GROUP); + + CustomFunction customFunc = new CustomFunction(funcName, body, args); + customFunc.ParentScript = script; + customFunc.ParentOffset = parentOffset; + + if (script.CurrentClass != null) + { + script.CurrentClass.AddMethod(funcName, args, customFunc); + } + else + { + ParserFunction.RegisterFunction(funcName, customFunc, false /* not native */); + } + + return Variable.EmptyInstance; + } + } + + public class CSCSClass : ParserFunction + { + public CSCSClass() {} + + public CSCSClass(string className) + { + Name = className; + RegisterClass(className, this); + } + + public CSCSClass(string className, string[] baseClasses) + { + Name = className; + RegisterClass(className, this); + + foreach (string baseClass in baseClasses) + { + var bc = CSCSClass.GetClass(baseClass); + if (bc == null) + { + throw new ArgumentException("Base Class [" + baseClass + "] not found."); + } + + foreach (var entry in bc.m_classProperties) + { + m_classProperties[entry.Key] = entry.Value; + } + foreach (var entry in bc.m_customFunctions) + { + m_customFunctions[entry.Key] = entry.Value; + } + } + } + + public static void RegisterClass(string className, CSCSClass obj) + { + obj.Name = className; + className = Constants.ConvertName(className); + s_allClasses[className] = obj; + } + + protected override Variable Evaluate(ParsingScript script) + { + script.GetFunctionArgs(); + + // TODO: Work in progress, currently not functional + return Variable.EmptyInstance; + } + + public void AddMethod(string name, string[] args, CustomFunction method) + { + if (name == m_name) + { + m_constructors[args.Length] = method; + } + else + { + m_customFunctions[name] = method; + } + } + + public void AddProperty(string name, Variable property) + { + m_classProperties[name] = property; + } + + public static CSCSClass GetClass(string name) + { + CSCSClass theClass = null; + s_allClasses.TryGetValue(name, out theClass); + return theClass; + } + + static Dictionary s_allClasses = + new Dictionary(); + + Dictionary m_constructors = + new Dictionary(); + Dictionary m_customFunctions = + new Dictionary(); + Dictionary m_classProperties = + new Dictionary(); + + public ParsingScript ParentScript = null; + public int ParentOffset = 0; + + public class ClassInstance : ScriptObject + { + public ClassInstance(string instanceName, string className, List args, + ParsingScript script = null) + { + InstanceName = instanceName; + m_cscsClass = CSCSClass.GetClass(className); + if (m_cscsClass == null) + { + throw new ArgumentException("Class [" + className + "] not found."); + } + + // Copy over all the properties defined for this class. + foreach (var entry in m_cscsClass.m_classProperties) + { + SetProperty(entry.Key, entry.Value); + } + + // Run "constructor" if any is defined for this number of args. + CustomFunction constructor = null; + if (m_cscsClass.m_constructors.TryGetValue(args.Count, out constructor)) + { + constructor.Run(args, script, this); + } + } + + public string InstanceName { get; set; } + CSCSClass m_cscsClass; + + Dictionary m_properties = new Dictionary(); + HashSet m_propSet = new HashSet(); + + public override string ToString() + { + return m_cscsClass.Name + "." + InstanceName; + } + + public Task SetProperty(string name, Variable value) + { + m_properties[name] = value; + m_propSet.Add(name); + return Task.FromResult( Variable.EmptyInstance ); + } + + public async Task GetProperty(string name, List args = null, ParsingScript script = null) + { + Variable value = null; + if (m_properties.TryGetValue(name, out value)) + { + return value; + } + + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out customFunction)) + { + return null; + } + if (args == null) + { + return Variable.EmptyInstance; + } + + foreach (var entry in m_cscsClass.m_classProperties) + { + args.Add(entry.Value); + } + + Variable result = await customFunction.RunAsync(args, script, this); + return result; + } + + public List> GetPropList() + { + List> props = new List>(); + foreach (var entry in m_properties) + { + props.Add(new KeyValuePair(entry.Key, entry.Value)); + } + return props; + } + + public List GetProperties() + { + List props = new List(m_properties.Keys); + props.AddRange(m_cscsClass.m_customFunctions.Keys); + + return props; + } + public bool PropertyExists(string name) + { + return m_propSet.Contains(name); + } + + public bool FunctionExists(string name) + { + CustomFunction customFunction = null; + if (!m_cscsClass.m_customFunctions.TryGetValue(name, out customFunction)) + { + return false; + } + return true; + } + } + } + + class EnumFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List properties = Utils.ExtractTokens(script); + + if (properties.Count == 1 && properties[0].Contains(".")) + { + return UseExistingEnum(properties[0]); + } + + Variable enumVar = new Variable(Variable.VarType.ENUM); + for (int i = 0; i < properties.Count; i++) + { + enumVar.SetEnumProperty(properties[i], new Variable(i)); + } + + return enumVar; + } + + public static Variable UseExistingEnum(string enumName) + { + Type enumType = GetEnumType(enumName); + if (enumType == null || !enumType.IsEnum) + { + return Variable.EmptyInstance; + } + + var names = Enum.GetNames(enumType); + + Variable enumVar = new Variable(Variable.VarType.ENUM); + for (int i = 0; i < names.Length; i++) + { + var numValue = Enum.Parse(enumType, names[i], true); + enumVar.SetEnumProperty(names[i], new Variable((int)numValue)); + } + + return enumVar; + } + + public static Type GetEnumType(string enumName) + { + string[] tokens = enumName.Split('.'); + + Type enumType = null; + int index = 0; + string typeName = ""; + while(enumType == null && index < tokens.Length) + { + if (!string.IsNullOrWhiteSpace(typeName)) + { + typeName += "."; + } + typeName += tokens[index]; + enumType = GetType(typeName); + index++; + } + + for (int i = index; i < tokens.Length && enumType != null; i++) + { + enumType = enumType.GetNestedType(tokens[i]); + } + + if (enumType == null || !enumType.IsEnum) + { + return null; + } + + return enumType; + } + + public static Type GetType(string typeName) + { + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); + foreach (var assembly in assemblies) + { + var type = assembly.GetType(typeName, false, true); + if (type != null) + { + return type; + } + } + return null; + } + } + + class NewObjectFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = script.GetFunctionArgs(); + + CompiledClass csClass = CSCSClass.GetClass(className) as CompiledClass; + if (csClass != null) + { + ScriptObject obj = csClass.GetImplementation(args); + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + script.MoveForwardIf(Constants.START_ARG); + List args = await script.GetFunctionArgsAsync(); + + CompiledClassAsync csClass = CSCSClass.GetClass(className) as CompiledClassAsync; + if (csClass != null) + { + ScriptObject obj = await csClass.GetImplementationAsync(args); + return new Variable(obj); + } + + CSCSClass.ClassInstance instance = new + CSCSClass.ClassInstance(script.CurrentAssign, className, args, script); + + return new Variable(instance); + } + } + + public class ClassCreator : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + string className = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + className = Constants.ConvertName(className); + string[] baseClasses = Utils.GetBaseClasses(script); + CSCSClass newClass = new CSCSClass(className, baseClasses); + + script.MoveForwardIf(Constants.START_GROUP, Constants.SPACE); + + newClass.ParentOffset = script.Pointer; + newClass.ParentScript = script; + int lineNumber = 0; + /*string line = */script.GetOriginalLine(out lineNumber); + + string scriptExpr = Utils.GetBodyBetween(script, Constants.START_GROUP, + Constants.END_GROUP); + Dictionary char2Line; + string body = Utils.ConvertToScript(scriptExpr, out char2Line); + + Variable result = null; + ParsingScript tempScript = new ParsingScript(body); + //tempScript.ScriptOffset = newClass.ParentOffset; + tempScript.Char2Line = script.Char2Line; + tempScript.Filename = script.Filename; + tempScript.OriginalScript = script.OriginalScript; + tempScript.CurrentClass = newClass; + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.DisableBreakpoints = true; + + // Uncomment if want to step into the class creation code when the debugger is attached (unlikely) + /*Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript); + }*/ + + while (tempScript.Pointer < body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + + return Variable.EmptyInstance; + } + } + + public class CustomFunction : ParserFunction + { + internal CustomFunction(string funcName, + string body, string[] args) + { + Name = funcName; + m_body = body; + m_args = args; + + for (int i = 0; i < args.Length; i++) + { + string arg = args[i]; + int ind = arg.IndexOf("="); + if (ind > 0) + { + m_args[i] = arg.Substring(0, ind).Trim().ToLower(); + string defValue = ind >= arg.Length - 1 ? "" : arg.Substring(ind + 1).Trim(); + if (defValue.StartsWith("\"")) + { + defValue = defValue.Substring(1); + } + if (defValue.EndsWith("\"")) + { + defValue = defValue.Substring(0, defValue.Length - 1); + } + Variable defVariable = new Variable(defValue); + defVariable.CurrentAssign = m_args[i]; + defVariable.Index = i; + m_defArgMap[i] = m_defaultArgs.Count; + m_defaultArgs.Add(defVariable); + } + else + { + m_args[i] = arg.ToLower(); + } + m_argMap[m_args[i]] = i; + } + } + + public void RegisterArguments(List args, + List> args2 = null) + { + int missingArgs = m_args.Length - args.Count; + + bool namedParameters = false; + for (int i = 0; i < args.Count; i++) + { + var arg = args[i]; + int argIndex = -1; + if (m_argMap.TryGetValue(arg.CurrentAssign, out argIndex)) + { + namedParameters = true; + if (i != argIndex) + { + args[i] = argIndex < args.Count ? args[argIndex] : args[i]; + while (argIndex > args.Count - 1) + { + args.Add(Variable.EmptyInstance); + } + args[argIndex] = arg; + } + } + else if (namedParameters) + { + throw new ArgumentException("All arguments in function [" + m_name + + "] must be arg=value form."); + } + } + + if (missingArgs > 0 && missingArgs <= m_defaultArgs.Count) + { + if (!namedParameters) + { + for (int i = m_defaultArgs.Count - missingArgs; i < m_defaultArgs.Count; i++) + { + args.Add(m_defaultArgs[i]); + } + } + else + { + for (int i = 0; i < args.Count; i++) + { + if (args[i].Type == Variable.VarType.NONE || + (!string.IsNullOrWhiteSpace(args[i].CurrentAssign) && + args[i].CurrentAssign != m_args[i])) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args[i] = m_defaultArgs[defIndex]; + } + } + } + } + for (int i = args.Count; i < m_args.Length; i++) + { + int defIndex = -1; + if (!m_defArgMap.TryGetValue(i, out defIndex)) + { + throw new ArgumentException("No argument [" + m_args[i] + + "] given for function [" + m_name + "]."); + } + args.Add(m_defaultArgs[defIndex]); + } + StackLevel stackLevel = new StackLevel(m_name); + + if (args2 != null) + { + foreach (var entry in args2) + { + var arg = new GetVarFunction(entry.Value); + arg.Name = entry.Key; + stackLevel.Variables[entry.Key] = arg; + } + } + + int maxSize = Math.Min(args.Count, m_args.Length); + for (int i = 0; i < maxSize; i++) + { + var arg = new GetVarFunction(args[i]); + arg.Name = m_args[i]; + stackLevel.Variables[m_args[i]] = arg; + } + + ParserFunction.AddLocalVariables(stackLevel); + } + + protected override Variable Evaluate(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + script.GetFunctionArgs(); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = Run(args, script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = Constants.FUNCT_WITH_SPACE.Contains(m_name) ? + // Special case of extracting args. + Utils.GetFunctionArgsAsStrings(script) : + await script.GetFunctionArgsAsync(); + + script.MoveBackIf(Constants.START_GROUP); + + if (args.Count + m_defaultArgs.Count < m_args.Length) + { + throw new ArgumentException("Function [" + m_name + "] arguments mismatch: " + + m_args.Length + " declared, " + args.Count + " supplied"); + } + + Variable result = await RunAsync(args, script); + return result; + } + + public Variable Run(List args, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = new ParsingScript(m_body); + tempScript.ScriptOffset = m_parentOffset; + if (m_parentScript != null) + { + tempScript.Char2Line = m_parentScript.Char2Line; + tempScript.Filename = m_parentScript.Filename; + tempScript.OriginalScript = m_parentScript.OriginalScript; + } + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.ClassInstance = instance; + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = debugger.StepInFunctionIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + public async Task RunAsync(List args, ParsingScript script = null, + CSCSClass.ClassInstance instance = null) + { + List> args2 = instance == null ? null : instance.GetPropList(); + // 1. Add passed arguments as local variables to the Parser. + RegisterArguments(args, args2); + + // 2. Execute the body of the function. + Variable result = null; + ParsingScript tempScript = new ParsingScript(m_body); + tempScript.ScriptOffset = m_parentOffset; + if (m_parentScript != null) + { + tempScript.Char2Line = m_parentScript.Char2Line; + tempScript.Filename = m_parentScript.Filename; + tempScript.OriginalScript = m_parentScript.OriginalScript; + } + tempScript.ParentScript = script; + tempScript.InTryBlock = script == null ? false : script.InTryBlock; + tempScript.ClassInstance = instance; + + Debugger debugger = script != null && script.Debugger != null ? script.Debugger : Debugger.MainInstance; + if (debugger != null) + { + result = await debugger.StepInFunctionIfNeeded(tempScript); + } + + while (tempScript.Pointer < m_body.Length - 1 && + (result == null || !result.IsReturn)) + { + result = await tempScript.ExecuteToAsync(); + tempScript.GoToNextStatement(); + } + + ParserFunction.PopLocalVariables(); + + if (result == null) + { + result = Variable.EmptyInstance; + } + else + { + result.IsReturn = false; + } + + return result; + } + + public static Task Run(string functionName, Variable arg1 = null, Variable arg2 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + + Variable result = customFunction.Run(args); + return Task.FromResult( result ); + } + public static async Task RunAsync(string functionName, Variable arg1 = null, Variable arg2 = null) + { + CustomFunction customFunction = ParserFunction.GetFunction(functionName, null) as CustomFunction; + + if (customFunction == null) + { + return null; + } + + List args = new List(); + if (arg1 != null) + { + args.Add(arg1); + } + if (arg2 != null) + { + args.Add(arg2); + } + + Variable result = await customFunction.RunAsync(args); + return result; + } + + public ParsingScript ParentScript { set { m_parentScript = value; } } + public int ParentOffset { set { m_parentOffset = value; } } + public string Body { get { return m_body; } } + + public int ArgumentCount { get { return m_args.Length; } } + public string Argument(int nIndex) { return m_args[nIndex]; } + + public string Header + { + get + { + return Constants.FUNCTION + " " + Constants.GetRealName(Name) + " " + + Constants.START_ARG + string.Join(", ", m_args) + + Constants.END_ARG + " " + Constants.START_GROUP; + } + } + + protected string m_body; + protected string[] m_args; + protected ParsingScript m_parentScript = null; + protected int m_parentOffset = 0; + + List m_defaultArgs = new List(); + Dictionary m_argMap = new Dictionary(); + Dictionary m_defArgMap = new Dictionary(); + } + + class StringOrNumberFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // First check if the passed expression is a string between quotes. + if (Item.Length > 1 && + ((Item[0] == Constants.QUOTE && Item[Item.Length - 1] == Constants.QUOTE) || + (Item[0] == Constants.QUOTE1 && Item[Item.Length - 1] == Constants.QUOTE1))) + { + return new Variable(Item.Substring(1, Item.Length - 2)); + } + + // Otherwise this should be a number. + double num = Utils.ConvertToDouble(Item, script); + return new Variable(num); + } + + public string Item { private get; set; } + } + + class AddFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable currentValue = Utils.GetSafeVariable(args, 0); + Variable item = Utils.GetSafeVariable(args, 1); + int index = Utils.GetSafeInt(args, 2, -1); + + currentValue.AddVariable(item, index); + if (!currentValue.ParsingToken.Contains(Constants.START_ARRAY.ToString())) + { + ParserFunction.AddGlobalOrLocalVariable(currentValue.ParsingToken, + new GetVarFunction(currentValue)); + } + + return currentValue; + } + } + class RemoveFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + string varName = args[0].AsString(); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = args[1]; + + bool removed = currentValue.Tuple.Remove(item); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return new Variable(removed); + } + } + class RemoveAtFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Utils.CheckArray(currentValue, varName); + + // 3. Get the variable to remove. + Variable item = Utils.GetItem(script); + Utils.CheckNonNegativeInt(item); + + currentValue.Tuple.RemoveAt(item.AsInt()); + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(currentValue)); + return Variable.EmptyInstance; + } + } + + class ContainsFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Utils.CheckNotEnd(script, m_name); + + // 2. Get the current value of the variable. + List arrayIndices = Utils.GetArrayIndices(script, varName, (newVarName) => { varName = newVarName; } ); + + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + + // 2b. Special dealings with arrays: + Variable query = arrayIndices.Count > 0 ? + Utils.ExtractArrayElement(currentValue, arrayIndices) : + currentValue; + + // 3. Get the value to be looked for. + Variable searchValue = Utils.GetItem(script); + Utils.CheckNotEnd(script, m_name); + + // 4. Check if the value to search for exists. + bool exists = query.Exists(searchValue, true /* notEmpty */); + + script.MoveBackIf(Constants.START_GROUP); + return new Variable(exists); + } + } + + class FindIndexFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable var = Utils.GetSafeVariable(args, 0); + string val = Utils.GetSafeString(args, 1); + + int index = var.FindIndex(val); + + return new Variable(index); + } + } + + class BoolFunction : ParserFunction, INumericFunction + { + bool m_value; + public BoolFunction(bool init) + { + m_value = init; + } + protected override Variable Evaluate(ParsingScript script) + { + return new Variable(m_value); + } + } + class ToDoubleFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToDouble(arg.AsString()); + return new Variable(result); + } + } + class ToIntFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + int result = Utils.ConvertToInt(arg.AsString()); + return new Variable(result); + } + } + class ToBoolFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + double result = Utils.ConvertToBool(arg.AsString()) ? 1 : 0; + return new Variable(result); + } + } + class ToDecimalFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = Decimal.Parse(arg.AsString(), NumberStyles.Any).ToString(); + return new Variable(result); + } + } + class ToStringFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + Variable arg = args[0]; + + string result = arg.AsString(); + return new Variable(result); + } + } + class IdentityFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return script.ExecuteTo(Constants.END_ARG); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await script.ExecuteToAsync(Constants.END_ARG); + } + } + + class IfStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable result = Interpreter.Instance.ProcessIf(script); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + Variable result = await Interpreter.Instance.ProcessIfAsync(script); + return result; + } + } + + class ForStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessFor(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessForAsync(script); + } + } + + class WhileStatement : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + return Interpreter.Instance.ProcessWhile(script); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + return await Interpreter.Instance.ProcessWhileAsync(script); + } + } + + class IncludeFile : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + string includeScript; + ParsingScript tempScript = GetIncludeFileScript(script, args, out includeScript); + + Variable result = null; + if (script.Debugger != null) + { + result = script.Debugger.StepInIncludeIfNeeded(tempScript).Result; + } + + while (tempScript.Pointer < includeScript.Length) + { + result = tempScript.ExecuteTo(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + string includeScript; + ParsingScript tempScript = GetIncludeFileScript(script, args, out includeScript); + + Variable result = null; + if (script.Debugger != null) + { + result = await script.Debugger.StepInIncludeIfNeeded(tempScript); + } + + while (tempScript.Pointer < includeScript.Length) + { + result = await tempScript.ExecuteToAsync(); + tempScript.GoToNextStatement(); + } + return result == null ? Variable.EmptyInstance : result; + } + + ParsingScript GetIncludeFileScript(ParsingScript script, List args, out string includeScript) + { + Utils.CheckArgs(args.Count, 1, m_name, true); + + string filename = args[0].AsString(); + string pathname = script.GetFilePath(filename); + string[] lines = Utils.GetFileLines(pathname); + + string includeFile = string.Join(Environment.NewLine, lines); + Dictionary char2Line; + includeScript = Utils.ConvertToScript(includeFile, out char2Line); + ParsingScript tempScript = new ParsingScript(includeScript, 0, char2Line); + tempScript.Filename = pathname; + tempScript.OriginalScript = string.Join(Constants.END_LINE.ToString(), lines); + tempScript.ParentScript = script; + tempScript.InTryBlock = script.InTryBlock; + + return tempScript; + } + } + + // Get a value of a variable or of an array element + public class GetVarFunction : ParserFunction + { + public GetVarFunction(Variable value) + { + m_value = value; + } + + protected override Variable Evaluate(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = Utils.GetArrayIndices(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; } ); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices); + if (script.TryCurrent() != '.') + { + return result; + } + + script.Forward(); + m_propName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Variable propValue = result.GetProperty(m_propName, script); + Utils.CheckNotNull(propValue, m_propName); + return propValue; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + string temp = m_propName; + m_propName = null; // Need this to reset for recursive calls + Variable propValue = m_value.Type == Variable.VarType.ENUM ? + m_value.GetEnumProperty(temp, script) : + m_value.GetProperty(temp, script); + Utils.CheckNotNull(propValue, temp); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + // First check if this element is part of an array: + if (script.TryPrev() == Constants.START_ARRAY) + { + // There is an index given - it must be for an element of the tuple. + if (m_value.Tuple == null || m_value.Tuple.Count == 0) + { + throw new ArgumentException("No tuple exists for the index"); + } + + if (m_arrayIndices == null) + { + string startName = script.Substr(script.Pointer - 1); + m_arrayIndices = await Utils.GetArrayIndicesAsync(script, startName, m_delta, (newStart, newDelta) => { startName = newStart; m_delta = newDelta; }); + } + + script.Forward(m_delta); + while (script.MoveForwardIf(Constants.END_ARRAY)) + { + } + + Variable result = Utils.ExtractArrayElement(m_value, m_arrayIndices); + if (script.TryCurrent() != '.') + { + return result; + } + + script.Forward(); + m_propName = Utils.GetToken(script, Constants.NEXT_OR_END_ARRAY); + Variable propValue = await result.GetPropertyAsync(m_propName, script); + Utils.CheckNotNull(propValue, m_propName); + return propValue; + } + + // Now check that this is an object: + if (!string.IsNullOrWhiteSpace(m_propName)) + { + string temp = m_propName; + m_propName = null; // Need this to reset for recursive calls + + Variable propValue = m_value.Type == Variable.VarType.ENUM ? + m_value.GetEnumProperty(temp, script) : + await m_value.GetPropertyAsync(temp, script); + Utils.CheckNotNull(propValue, temp); + return propValue; + } + + // Otherwise just return the stored value. + return m_value; + } + + public int Delta + { + set { m_delta = value; } + } + public Variable Value + { + get { return m_value; } + } + public List Indices + { + set { m_arrayIndices = value; } + } + public string PropertyName + { + set { m_propName = value; } + } + + Variable m_value; + int m_delta = 0; + List m_arrayIndices = null; + string m_propName; + } + class IncrementDecrementFunction : ActionFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool prefix = string.IsNullOrWhiteSpace(m_name); + if (prefix) + {// If it is a prefix we do not have the variable name yet. + Name = Utils.GetToken(script, Constants.TOKEN_SEPARATION); + } + + // Value to be added to the variable: + int valueDelta = m_action == Constants.INCREMENT ? 1 : -1; + int returnDelta = prefix ? valueDelta : 0; + + // Check if the variable to be set has the form of x[a][b], + // meaning that this is an array element. + double newValue = 0; + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetFunction(m_name, script); + Utils.CheckNotNull(m_name, func); + + Variable currentValue = func.GetValue(script); + currentValue = currentValue.DeepClone(); + + if (arrayIndices.Count > 0 || script.TryCurrent() == Constants.START_ARRAY) + { + if (prefix) + { + string tmpName = m_name + script.Rest; + int delta = 0; + arrayIndices = Utils.GetArrayIndices(script, tmpName, delta, (string t, int d) => { tmpName = t; delta = d; }); + script.Forward(Math.Max(0, delta - tmpName.Length)); + } + + Variable element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + + newValue = element.Value + returnDelta; + element.Value += valueDelta; + } + else + { // A normal variable. + newValue = currentValue.Value + returnDelta; + currentValue.Value += valueDelta; + } + + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + return new Variable(newValue); + } + + override public ParserFunction NewInstance() + { + return new IncrementDecrementFunction(); + } + } + + class OperatorAssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // Value to be added to the variable: + Variable right = Utils.GetItem(script); + + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + ParserFunction func = ParserFunction.GetFunction(m_name, script); + Utils.CheckNotNull(m_name, func); + + Variable currentValue = func.GetValue(script); + currentValue = currentValue.DeepClone(); + Variable left = currentValue; + + if (arrayIndices.Count > 0) + {// array element + left = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + if (left.Type == Variable.VarType.NUMBER) + { + NumberOperator(left, right, m_action); + } + else + { + StringOperator(left, right, m_action); + } + + if (arrayIndices.Count > 0) + {// array element + AssignFunction.ExtendArray(currentValue, arrayIndices, 0, left); + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(currentValue)); + } + else + { + ParserFunction.AddGlobalOrLocalVariable(m_name, + new GetVarFunction(left)); + } + return left; + } + + static void NumberOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + valueA.Value += valueB.Value; + break; + case "-=": + valueA.Value -= valueB.Value; + break; + case "*=": + valueA.Value *= valueB.Value; + break; + case "/=": + valueA.Value /= valueB.Value; + break; + case "%=": + valueA.Value %= valueB.Value; + break; + case "&=": + valueA.Value = (int)valueA.Value & (int)valueB.Value; + break; + case "|=": + valueA.Value = (int)valueA.Value | (int)valueB.Value; + break; + case "^=": + valueA.Value = (int)valueA.Value ^ (int)valueB.Value; + break; + } + } + static void StringOperator(Variable valueA, + Variable valueB, string action) + { + switch (action) + { + case "+=": + if (valueB.Type == Variable.VarType.STRING) + { + valueA.String += valueB.AsString(); + } + else + { + valueA.String += valueB.Value; + } + break; + } + } + + override public ParserFunction NewInstance() + { + return new OperatorAssignFunction(); + } + } + + class AssignFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + script.CurrentAssign = m_name; + Variable varValue = Utils.GetItem(script); + + // First try processing as an object (with a dot notation): + Variable result = ProcessObject(script, varValue); + if (result != null) + { + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = Utils.GetArrayIndices(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue)); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + //return varValue.DeepClone(); + } + + Variable array; + + ParserFunction pf = ParserFunction.GetFunction(m_name, script); + if (pf != null) + { + array = pf.GetValue(script); + } + else + { + array = new Variable(); + } + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array)); + return array; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + script.CurrentAssign = m_name; + Variable varValue = await Utils.GetItemAsync(script); + + // First try processing as an object (with a dot notation): + Variable result = await ProcessObjectAsync(script, varValue); + if (result != null) + { + return result; + } + + // Check if the variable to be set has the form of x[a][b]..., + // meaning that this is an array element. + List arrayIndices = await Utils.GetArrayIndicesAsync(script, m_name, (string name) => { m_name = name; }); + + if (arrayIndices.Count == 0) + { + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(varValue)); + Variable retVar = varValue.DeepClone(); + retVar.CurrentAssign = m_name; + return retVar; + //return varValue.DeepClone(); + } + + Variable array; + + ParserFunction pf = ParserFunction.GetFunction(m_name, script); + if (pf != null) + { + array = await pf.GetValueAsync(script); + } + else + { + array = new Variable(); + } + + ExtendArray(array, arrayIndices, 0, varValue); + + ParserFunction.AddGlobalOrLocalVariable(m_name, new GetVarFunction(array)); + return array; + } + + Variable ProcessObject(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + varValue = script.ClassInstance.SetProperty(m_name, varValue).Result; + return varValue.DeepClone(); + } + + int ind = varName.IndexOf("."); + if (ind <= 0) + { + return null; + } + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + ParserFunction existing = ParserFunction.GetFunction(name, script); + Variable baseValue = existing != null ? existing.GetValue(script) : new Variable(Variable.VarType.ARRAY); + baseValue.SetProperty(prop, varValue, name); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue)); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + async Task ProcessObjectAsync(ParsingScript script, Variable varValue) + { + if (script.CurrentClass != null) + { + script.CurrentClass.AddProperty(m_name, varValue); + return varValue.DeepClone(); + } + string varName = m_name; + if (script.ClassInstance != null) + { + //varName = script.ClassInstance.InstanceName + "." + m_name; + await script.ClassInstance.SetProperty(m_name, varValue); + return varValue.DeepClone(); + } + + int ind = varName.IndexOf("."); + if (ind <= 0) + { + return null; + } + string name = varName.Substring(0, ind); + string prop = varName.Substring(ind + 1); + + ParserFunction existing = ParserFunction.GetFunction(name, script); + Variable baseValue = existing != null ? await existing.GetValueAsync(script) : new Variable(Variable.VarType.ARRAY); + await baseValue.SetPropertyAsync(prop, varValue, name); + + ParserFunction.AddGlobalOrLocalVariable(name, new GetVarFunction(baseValue)); + //ParserFunction.AddGlobal(name, new GetVarFunction(baseValue), false); + + return varValue.DeepClone(); + } + + + override public ParserFunction NewInstance() + { + return new AssignFunction(); + } + + public static void ExtendArray(Variable parent, + List arrayIndices, + int indexPtr, + Variable varValue) + { + if (arrayIndices.Count <= indexPtr) + { + return; + } + + Variable index = arrayIndices[indexPtr]; + int currIndex = ExtendArrayHelper(parent, index); + + if (arrayIndices.Count - 1 == indexPtr) + { + parent.Tuple[currIndex] = varValue; + return; + } + + Variable son = parent.Tuple[currIndex]; + ExtendArray(son, arrayIndices, indexPtr + 1, varValue); + } + + private static int ExtendArrayHelper(Variable parent, Variable indexVar) + { + parent.SetAsArray(); + + int arrayIndex = parent.GetArrayIndex(indexVar); + if (arrayIndex < 0) + { + // This is not a "normal index" but a new string for the dictionary. + string hash = indexVar.AsString(); + arrayIndex = parent.SetHashVariable(hash, Variable.NewEmpty()); + return arrayIndex; + } + + if (parent.Tuple.Count <= arrayIndex) + { + for (int i = parent.Tuple.Count; i <= arrayIndex; i++) + { + parent.Tuple.Add(Variable.NewEmpty()); + } + } + return arrayIndex; + } + } + + class DeepCopyFunction : ActionFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varValue = Utils.GetItem(script); + return varValue.DeepClone(); ; + } + } + + class TokenizeLinesFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2, 0); + string sepStr = Utils.GetSafeString(args, 3, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + // var function = ParserFunction.GetFunction(varName, script); + Variable allTokensVar = new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; +#pragma warning disable 219 + // bugbug - the toAdd has side effects + Variable toAdd = new Variable(counter - fromLine); +#pragma warning restore 219 + string line = lineVar.AsString(); + var tokens = line.Split(sep); + Variable tokensVar = new Variable(Variable.VarType.ARRAY); + foreach (string token in tokens) + { + tokensVar.Tuple.Add(new Variable(token)); + } + allTokensVar.Tuple.Add(tokensVar); + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(allTokensVar)); + + return Variable.EmptyInstance; + } + } + + class AddVariablesToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable lines = Utils.GetSafeVariable(args, 1); + int fromLine = Utils.GetSafeInt(args, 2); + string hash2 = Utils.GetSafeString(args, 3); + string sepStr = Utils.GetSafeString(args, 4, "\t"); + if (sepStr == "\\t") + { + sepStr = "\t"; + } + char[] sep = sepStr.ToCharArray(); + + var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + for (int counter = fromLine; counter < lines.Tuple.Count; counter++) + { + Variable lineVar = lines.Tuple[counter]; + Variable toAdd = new Variable(counter - fromLine); + string line = lineVar.AsString(); + var tokens = line.Split(sep); + string hash = tokens[0]; + mapVar.AddVariableToHash(hash, toAdd); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + return Variable.EmptyInstance; + } + } + class AddVariableToHashFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable toAdd = Utils.GetSafeVariable(args, 1); + string hash = Utils.GetSafeString(args, 2); + + var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = function != null ? function.GetValue(script) : + new Variable(Variable.VarType.ARRAY); + + mapVar.AddVariableToHash(hash, toAdd); + for (int i = 3; i < args.Count; i++) + { + string hash2 = Utils.GetSafeString(args, 3); + if (!string.IsNullOrWhiteSpace(hash2) && + !hash2.Equals(hash, StringComparison.OrdinalIgnoreCase)) + { + mapVar.AddVariableToHash(hash2, toAdd); + } + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + + return Variable.EmptyInstance; + } + } + class TokenCounterFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable all = Utils.GetSafeVariable(args, 0); + string varName = Utils.GetSafeString(args, 1); + int index = Utils.GetSafeInt(args, 2); + + // var function = ParserFunction.GetFunction(varName, script); + Variable mapVar = new Variable(Variable.VarType.ARRAY); + + if (all.Tuple == null) + { + return Variable.EmptyInstance; + } + + string currentValue = ""; + int currentCount = 0; + + int globalCount = 0; + + for (int i = 0; i < all.Tuple.Count; i++) + { + Variable current = all.Tuple[i]; + if (current.Tuple == null || current.Tuple.Count < index) + { + break; + } + string newValue = current.Tuple[index].AsString(); + if (currentValue != newValue) + { + currentValue = newValue; + currentCount = 0; + } + mapVar.Tuple.Add(new Variable(currentCount)); + currentCount++; + globalCount++; + } + + ParserFunction.AddGlobalOrLocalVariable(varName, + new GetVarFunction(mapVar)); + // Script - Need to enable the warnings +#pragma warning restore 219 + return mapVar; + } + } + + class TypeFunction : ParserFunction, IStringFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + bool complexVariable = Utils.GetSafeInt(args, 1, 0) == 1; + Variable element = null; + if (complexVariable) + { + element = Utils.GetVariable(args[0].AsString(), script, false); + } + if (element == null) + { + element = Utils.GetSafeVariable(args, 0); + } + + string type = element.GetTypeString(); + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(type); + return newValue; + } + } + + class SizeFunction : ParserFunction, INumericFunction + { + protected override Variable Evaluate(ParsingScript script) + { + // 1. Get the name of the variable. + string varName = Utils.GetToken(script, Constants.END_ARG_ARRAY); + Utils.CheckNotEnd(script, m_name); + + List arrayIndices = Utils.GetArrayIndices(script, varName, (newName) => { varName = newName; } ); + + // 2. Get the current value of the variable. + ParserFunction func = ParserFunction.GetFunction(varName, script); + Utils.CheckNotNull(varName, func); + Variable currentValue = func.GetValue(script); + Variable element = currentValue; + + // 2b. Special case for an array. + if (arrayIndices.Count > 0) + {// array element + element = Utils.ExtractArrayElement(currentValue, arrayIndices); + script.MoveForwardIf(Constants.END_ARRAY); + } + + // 3. Take either the length of the underlying tuple or + // string part if it is defined, + // or the numerical part converted to a string otherwise. + int size = element.GetSize(); + + script.MoveForwardIf(Constants.END_ARG, Constants.SPACE); + + Variable newValue = new Variable(size); + return newValue; + } + } + + class DefineLocalFunction : ParserFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string varName = Utils.GetSafeString(args, 0); + Variable currentValue = Utils.GetSafeVariable(args, 1); + + if (currentValue == null) + { + currentValue = new Variable(""); + } + + string scopeName = Path.GetFileName(script.Filename); + ParserFunction.AddLocalScopeVariable(varName, scopeName, + new GetVarFunction(currentValue)); + + return currentValue; + } + } + + class GetPropertiesFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name, true); + + Variable baseValue = args[0]; + List props = baseValue.GetProperties(); + return new Variable(props); + } + } + + class GetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = baseValue.GetProperty(propName, script); + Utils.CheckNotNull(propValue, propName); + + return new Variable(propValue); + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + + Variable propValue = await baseValue.GetPropertyAsync(propName, script); + Utils.CheckNotNull(propValue, propName); + + return new Variable(propValue); + } + public static Variable GetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = baseValue.GetProperty(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName); + + return new Variable(propValue); + } + public static async Task GetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 1, "GetProperty", true); + + Variable baseValue = args[0]; + + Variable propValue = await baseValue.GetPropertyAsync(sPropertyName, script); + Utils.CheckNotNull(propValue, sPropertyName); + + return new Variable(propValue); + } + } + + class SetPropertyFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = baseValue.SetProperty(propName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + protected override async Task EvaluateAsync(ParsingScript script) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 3, m_name, true); + + Variable baseValue = args[0]; + string propName = Utils.GetSafeString(args, 1); + Variable propValue = Utils.GetSafeVariable(args, 2); + + Variable result = await baseValue.SetPropertyAsync(propName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + + public static Variable SetProperty(ParsingScript script, string sPropertyName) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = baseValue.SetProperty(sPropertyName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + public static async Task SetPropertyAsync(ParsingScript script, string sPropertyName) + { + List args = await script.GetFunctionArgsAsync(); + Utils.CheckArgs(args.Count, 2, "SetProperty", true); + + Variable baseValue = args[0]; + Variable propValue = Utils.GetSafeVariable(args, 1); + + Variable result = await baseValue.SetPropertyAsync(sPropertyName, propValue); + + ParserFunction.AddGlobalOrLocalVariable(baseValue.ParsingToken, + new GetVarFunction(baseValue)); + return result; + } + } + + class CancelFunction : ParserFunction + { + public static bool Canceled { get; set; } + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 0, m_name, true); + + bool mode = Utils.GetSafeInt(args, 0, 1) == 1; + Canceled = mode; + + return new Variable(Canceled); + } + } + + public class ScheduleRunFunction : ParserFunction + { + static Dictionary m_timers = + new Dictionary(); + + bool m_startTimer; + + public ScheduleRunFunction(bool startTimer) + { + m_startTimer = startTimer; + } + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + + if (!m_startTimer) + { + Utils.CheckArgs(args.Count, 1, m_name); + string cancelTimerId = Utils.GetSafeString(args, 0); + System.Timers.Timer cancelTimer; + if (m_timers.TryGetValue(cancelTimerId, out cancelTimer)) + { + cancelTimer.Stop(); + cancelTimer.Dispose(); + m_timers.Remove(cancelTimerId); + } + return Variable.EmptyInstance; + } + + Utils.CheckArgs(args.Count, 2, m_name); + int timeout = args[0].AsInt(); + string strAction = args[1].AsString(); + string arg = Utils.GetSafeString(args, 2); + string timerId = Utils.GetSafeString(args, 3); + bool autoReset = Utils.GetSafeInt(args, 4, 0) != 0; + + arg = Utils.ProtectQuotes(arg); + timerId = Utils.ProtectQuotes(timerId); + + System.Timers.Timer pauseTimer = new System.Timers.Timer(timeout); + pauseTimer.Elapsed += (sender, e) => + { + if (!autoReset) + { + pauseTimer.Stop(); + pauseTimer.Dispose(); + m_timers.Remove(timerId); + } + string body = string.Format("{0}({1},{2});", strAction, + "\"" + arg + "\"", "\"" + timerId + "\""); + + ParsingScript tempScript = new ParsingScript(body); + tempScript.ExecuteTo(); + }; + pauseTimer.AutoReset = autoReset; + m_timers[timerId] = pauseTimer; + + pauseTimer.Start(); + + return Variable.EmptyInstance; + } + } + + public class SingletonFunction : ParserFunction + { + static Dictionary m_singletons = + new Dictionary(); + + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 1, m_name); + + string expr = args[0].AsString(); + Dictionary char2Line; + expr = Utils.ConvertToScript(expr, out char2Line); + + Variable result; + if (m_singletons.TryGetValue(expr, out result)) + { + return result; + } + + ParsingScript tempScript = new ParsingScript(expr); + result = tempScript.ExecuteTo(); + + m_singletons[expr] = result; + + return result; + } + } + + class GetColumnFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + List args = script.GetFunctionArgs(); + Utils.CheckArgs(args.Count, 2, m_name); + + Variable arrayVar = Utils.GetSafeVariable(args, 0); + int col = Utils.GetSafeInt(args, 1); + int fromCol = Utils.GetSafeInt(args, 2, 0); + + var tuple = arrayVar.Tuple; + + List result = new List(tuple.Count); + for (int i = fromCol; i < tuple.Count; i++) + { + Variable current = tuple[i]; + if (current.Tuple == null || current.Tuple.Count <= col) + { + throw new ArgumentException(m_name + ": Index [" + col + "] doesn't exist in column " + + i + "/" + (tuple.Count - 1)); + } + result.Add(current.Tuple[col]); + } + + return new Variable(result); + } + } + + class GetAllKeysFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + Variable varName = Utils.GetItem(script); + Utils.CheckNotNull(varName, m_name); + + List results = varName.GetAllKeys(); + + return new Variable(results); + } + } + + class CheckLoaderMainFunction : ParserFunction, IArrayFunction + { + protected override Variable Evaluate(ParsingScript script) + { + bool isMain = !string.IsNullOrWhiteSpace(script.MainFilename) && + script.MainFilename == script.Filename; + + return new Variable(isMain); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `currentValue` last assigned on line 1412 could be null and is dereferenced at line 1416, column 13. + +### Severity: +ERROR + +### Procedure: +Variable AddFunction.Evaluate(ParsingScript) + +### File: +cscs/Functions.Flow.cs + +### Key: +Functions.Flow.cs|Evaluate|NULL_DEREFERENCE + +### Node Key: +722f645c76bfb99c288630c5b05ba5dc + +### Hash: +e0a75025508ed3930f8cabca0f7a1d83 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2003/instruction.md b/inferredbugs-2003/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63001f7f6300fa221d0462ab64f9ac5373a2a8ec --- /dev/null +++ b/inferredbugs-2003/instruction.md @@ -0,0 +1,112 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Cosmonaut +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security; +using System.Threading.Tasks; +using Cosmonaut.Extensions; +using Microsoft.Azure.Documents; +using Microsoft.Azure.Documents.Client; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using Xunit; + +namespace Cosmonaut.Tests +{ + public class ServiceCollectionTests + { + [Fact] + public void AddCosmosStoreRegistersStore() + { + // Assign + var serviceCollection = new ServiceCollection(); + var mockDocumentClient = new Mock(); + var mockDatabase = new Mock(); + var mockCollection = new Mock(); + var mockOffer = new Mock(); + mockDatabase.Setup(x => x.Id).Returns("databaseName"); + mockCollection.Setup(x => x.Id).Returns("dummies"); + + mockDocumentClient.Setup(x => x.AuthKey).Returns(new SecureString()); + mockDocumentClient.Setup(x => x.ServiceEndpoint).Returns(new Uri("http://test.com")); + mockDocumentClient.Setup(x => x.ReadDatabaseAsync(It.IsAny(), null)) + .ReturnsAsync(new ResourceResponse(mockDatabase.Object)); + mockDocumentClient.Setup(x => x.ReadDocumentCollectionAsync(It.IsAny(), null)) + .ReturnsAsync(new ResourceResponse(mockCollection.Object)); + mockDocumentClient.Setup(x => x.CreateDatabaseQuery(null)) + .Returns(new EnumerableQuery(new List(){mockDatabase.Object})); + mockDocumentClient.Setup(x => x.CreateDocumentCollectionQuery(It.IsAny(), null)) + .Returns(new EnumerableQuery(new List() {new DocumentCollection(){Id = "dummies" } })); + mockDocumentClient.Setup(x => x.CreateOfferQuery(null)).Returns( + new EnumerableQuery(new List() + { + new OfferV2(mockOffer.Object, 400) + })); + + //Act + serviceCollection.AddCosmosStore(mockDocumentClient.Object, "databaseName"); + var provider = serviceCollection.BuildServiceProvider(); + + //Assert + var cosmosStore = provider.GetService>(); + Assert.NotNull(cosmosStore); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of System.Security.SecureString::.ctor() at Line 29) of type System.Security.SecureString in method "Void ServiceCollectionTests.AddCosmosStoreRegistersStore()". + +### Severity: +ERROR + +### Procedure: +Void ServiceCollectionTests.AddCosmosStoreRegistersStore() + +### File: +Cosmonaut.Tests/ServiceCollectionTests.cs + +### Key: +ServiceCollectionTests.cs|AddCosmosStoreRegistersStore|DOTNET_RESOURCE_LEAK + +### Hash: +86da0d9270fd87c979109fa86f275ea6 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2004/instruction.md b/inferredbugs-2004/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6e74bdd6e7afc0a8ad9ae24f75cb96f91c2cc42b --- /dev/null +++ b/inferredbugs-2004/instruction.md @@ -0,0 +1,128 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Cosmonaut +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Threading.Tasks; +using Microsoft.Azure.Documents; +using Microsoft.Azure.Documents.ChangeFeedProcessor; +using Microsoft.Azure.WebJobs.Host.Bindings; +using Microsoft.Azure.WebJobs.Host.Listeners; +using Microsoft.Azure.WebJobs.Host.Protocols; +using Microsoft.Azure.WebJobs.Host.Triggers; +using Microsoft.Extensions.Logging; + +namespace Cosmonaut.WebJobs.Extensions.Trigger +{ + internal class CosmosStoreTriggerBinding : ITriggerBinding where T : class + { + private readonly ParameterInfo _parameter; + private readonly ILogger _logger; + private readonly IDocumentClient _monitoredDocumentClient; + private readonly IDocumentClient _leaseDocumentClient; + private readonly IReadOnlyDictionary _emptyBindingData = new Dictionary(); + + public CosmosStoreTriggerBinding(ParameterInfo parameter, DocumentCollectionInfo documentCollectionLocation, DocumentCollectionInfo leaseCollectionLocation, IDocumentClient monitoredDocumentClient, IDocumentClient leaseDocumentClient, ChangeFeedProcessorOptions processorOptions, ILogger logger) + { + DocumentCollectionLocation = documentCollectionLocation; + LeaseCollectionLocation = leaseCollectionLocation; + _monitoredDocumentClient = monitoredDocumentClient; + _leaseDocumentClient = leaseDocumentClient; + _parameter = parameter; + ChangeFeedProcessorOptions = processorOptions; + _logger = logger; + } + + public Type TriggerValueType => typeof(IReadOnlyList); + + internal DocumentCollectionInfo DocumentCollectionLocation { get; } + + internal DocumentCollectionInfo LeaseCollectionLocation { get; } + + internal ChangeFeedProcessorOptions ChangeFeedProcessorOptions { get; } + + public IReadOnlyDictionary BindingDataContract { get; } = new Dictionary(); + + public Task BindAsync(object value, ValueBindingContext context) + { + return Task.FromResult(new TriggerData(null, _emptyBindingData)); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] + public Task CreateListenerAsync(ListenerFactoryContext context) + { + if (context == null) + { + throw new ArgumentNullException(nameof(context), "Missing listener context"); + } + + return Task.FromResult(new CosmosStoreTriggerListener(context.Executor, DocumentCollectionLocation, LeaseCollectionLocation, ChangeFeedProcessorOptions, _monitoredDocumentClient, _leaseDocumentClient, _logger)); + } + + public ParameterDescriptor ToParameterDescriptor() + { + return new CosmosStoreTriggerParameterDescriptor + { + Name = _parameter.Name, + Type = CosmosStoreTriggerConstants.TriggerName, + CollectionName = DocumentCollectionLocation.CollectionName + }; + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Cosmonaut.WebJobs.Extensions.Trigger.CosmosStoreTriggerListener`1::.ctor() at Line 57) of type Cosmonaut.WebJobs.Extensions.Trigger.CosmosStoreTriggerListener`1 in method "Task`1 CosmosStoreTriggerBinding`1.CreateListenerAsync(ListenerFactoryContext)". + +### Severity: +ERROR + +### Procedure: +Task`1 CosmosStoreTriggerBinding`1.CreateListenerAsync(ListenerFactoryContext) + +### File: +src/Cosmonaut.WebJobs.Extensions/Trigger/CosmosStoreTriggerBinding.cs + +### Key: +CosmosStoreTriggerBinding.cs|CreateListenerAsync|DOTNET_RESOURCE_LEAK + +### Hash: +c8d84e45b0f559706d6f4620dc72f27a + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2032/instruction.md b/inferredbugs-2032/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f94467fa77ebf24bdaf032cf6b362619e4425e65 --- /dev/null +++ b/inferredbugs-2032/instruction.md @@ -0,0 +1,675 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** FluentFTP +**Bug ID:** 23 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Net.FtpClient; +using System.Threading; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using System.Linq; +using System.Threading.Tasks; +using System.IO.Compression; +using System.Text; + +namespace Tests { + /// + /// Torture test + /// + class Program { + static readonly string m_host = "ftptest"; + static readonly string m_user = "ftptest"; + static readonly string m_pass = "ftptest"; + + static void Main(string[] args) { + FtpTrace.FlushOnWrite = true; + FtpTrace.AddListener(new ConsoleTraceListener()); + + try { + /*foreach (int i in new int[] { + (int)FtpDataConnectionType.EPSV, + (int)FtpDataConnectionType.EPRT, + (int)FtpDataConnectionType.PASV, + (int)FtpDataConnectionType.PORT + }) { + using (FtpClient cl = new FtpClient()) { + cl.Credentials = new NetworkCredential(m_user, m_pass); + cl.Host = m_host; + cl.EncryptionMode = FtpEncryptionMode.None; + cl.ValidateCertificate += new FtpSslValidation(cl_ValidateCertificate); + cl.DataConnectionType = (FtpDataConnectionType)i; + //cl.Encoding = System.Text.Encoding.Default; + cl.Connect(); + Upload(cl); + Download(cl); + Delete(cl); + } + }*/ + + //TestServer(); + + //TestManualEncoding(); + + //TestServer(); + + //TestDisposeWithMultipleThreads(); + + //TestMODCOMP_PWD_Parser(); + //TestDispose(); + //TestHash(); + + //TestNameListing(); + //TestOpenVMSParser(); + // TestIISParser(); + //GetMicrosoftFTPListing(); + //TestReset(); + //TestUTF8(); + + //TestDirectoryWithDots(); + + //TestUnixListParser(); + + // TestFileZillaKick(); + + //TestUnixList(); + //TestNetBSDServer(); + + // TestConnectionFailure(); + + //TestGetObjectInfo(); + } + catch (Exception ex) { + Console.WriteLine(ex.ToString()); + } + + Console.WriteLine("--DONE--"); + Console.ReadKey(); + } + + static void TestGetObjectInfo() { + using (FtpClient cl = new FtpClient()) { + FtpListItem item; + + cl.Host = "ftptest"; + cl.Credentials = new NetworkCredential("ftptest", "ftptest"); + cl.Encoding = Encoding.Default; + + item = cl.GetObjectInfo("/Examples/OpenRead.cs"); + Console.WriteLine(item.ToString()); + } + } + + static void TestManualEncoding() { + using (FtpClient cl = new FtpClient()) { + cl.Host = "ftptest"; + cl.Credentials = new NetworkCredential("ftptest", "ftptest"); + cl.Encoding = Encoding.Default; + + using (Stream s = cl.OpenWrite("test.txt")) { + s.Close(); + } + } + } + + static void TestServer() { + using (FtpClient cl = new FtpClient()) { + cl.Host = "ftptest"; + cl.Credentials = new NetworkCredential("ftptest", "ftptest"); + cl.EncryptionMode = FtpEncryptionMode.Explicit; + cl.ValidateCertificate += (control, e) => { + e.Accept = true; + }; + + foreach (FtpListItem i in cl.GetListing("/")) { + Console.WriteLine(i.FullName); + } + } + } + + static void TestServerDownload(FtpClient client, string path) { + foreach (FtpListItem i in client.GetListing(path)) { + switch (i.Type) { + case FtpFileSystemObjectType.Directory: + TestServerDownload(client, i.FullName); + break; + case FtpFileSystemObjectType.File: + using (Stream s = client.OpenRead(i.FullName)) { + byte[] b = new byte[8192]; + int read = 0; + long total = 0; + + try { + while ((read = s.Read(b, 0, b.Length)) > 0) { + total += read; + + Console.Write("\r{0}/{1} {2:p} ", + total, s.Length, (double)total / (double)s.Length); + } + + Console.Write("\r{0}/{1} {2:p} ", + total, s.Length, (double)total / (double)s.Length); + } + finally { + Console.WriteLine(); + } + } + break; + } + } + } + + static void cl_ValidateCertificate(FtpClient control, FtpSslValidationEventArgs e) { + e.Accept = true; + } + + static void TestDisposeWithMultipleThreads() { + using (FtpClient cl = new FtpClient()) { + cl.Host = "ftp.netbsd.org"; + cl.Credentials = new NetworkCredential("ftp", "ftp"); + + Thread t1 = new Thread(() => { + cl.GetListing(); + }); + + Thread t2 = new Thread(() => { + cl.Dispose(); + }); + + t1.Start(); + Thread.Sleep(500); + t2.Start(); + + t1.Join(); + t2.Join(); + } + } + + static void TestConnectionFailure() { + try { + using (FtpClient cl = new FtpClient()) { + cl.Credentials = new NetworkCredential("ftp", "ftp"); + cl.Host = "somefakehost"; + cl.ConnectTimeout = 5000; + cl.Connect(); + } + } + catch (Exception e) { + Console.WriteLine("Caught connection faillure: {0}", e.Message); + } + } + + static void TestNetBSDServer() { + using (FtpClient client = new FtpClient()) { + client.Credentials = new NetworkCredential("ftp", "ftp"); + client.Host = "ftp.netbsd.org"; + + foreach (FtpListItem item in client.GetListing(null, + FtpListOption.ForceList | FtpListOption.Modify | FtpListOption.DerefLinks)) { + Console.WriteLine(item); + + if (item.Type == FtpFileSystemObjectType.Link && item.LinkObject != null) + Console.WriteLine(item.LinkObject); + } + } + } + + static void TestUnixList() { + using (FtpClient client = new FtpClient()) { + client.Credentials = new NetworkCredential("ftptest", "ftptest"); + client.Host = "ftptest"; + foreach (FtpListItem i in client.GetListing(null, FtpListOption.ForceList | FtpListOption.Recursive)) { + Console.WriteLine(i.FullName); + } + } + } + + static void TestFileZillaKick() { + using (FtpClient cl = new FtpClient()) { + cl.Host = "localhost"; + cl.Credentials = new NetworkCredential("ftptest", "ftptest"); + cl.EnableThreadSafeDataConnections = false; + + if (cl.FileExists("TestFile.txt")) + cl.DeleteFile("TestFile.txt"); + + try { + Stream s = cl.OpenWrite("TestFile.txt"); + for (int i = 0; true; i++) { + s.WriteByte((byte)i); + Thread.Sleep(100); + } + + //s.Close(); + } + catch (FtpCommandException ex) { + Console.WriteLine("Exception caught!"); + Console.WriteLine(ex.ToString()); + } + } + } + + static void TestUnixListParser() { + string[] sample = new string[] { + "drwxr-xr-x 7 user1 user1 512 Sep 27 2011 .", + "drwxr-xr-x 31 user1 user1 1024 Sep 27 2011 ..", + "lrwxrwxrwx 1 user1 user1 9 Sep 27 2011 data.0000 -> data.6460", + "drwxr-xr-x 10 user1 user1 512 Jun 29 2012 data.6460", + "lrwxrwxrwx 1 user1 user1 8 Sep 27 2011 sys.0000 -> sys.6460", + "drwxr-xr-x 133 user1 user1 4096 Jun 25 16:26 sys.6460" + }; + + foreach (string s in sample) { + FtpListItem item = FtpListItem.Parse("/", s, FtpCapability.NONE); + + if (item != null) + Console.WriteLine(item); + } + } + + static void TestDirectoryWithDots() { + using (FtpClient cl = new FtpClient()) { + cl.Credentials = new NetworkCredential("ftptest", "ftptest"); + cl.Host = "localhost"; + cl.Connect(); + // FTP server set to timeout after 5 seconds. + //Thread.Sleep(6000); + + cl.GetListing("Test.Directory", FtpListOption.ForceList); + cl.SetWorkingDirectory("Test.Directory"); + cl.GetListing(null, FtpListOption.ForceList); + } + } + + static void TestDispose() { + using (FtpClient cl = new FtpClient()) { + cl.Credentials = new NetworkCredential("ftptest", "ftptest"); + cl.Host = "localhost"; + cl.Connect(); + // FTP server set to timeout after 5 seconds. + //Thread.Sleep(6000); + + foreach (FtpListItem item in cl.GetListing()) { + + } + } + } + + static void TestHash() { + using (FtpClient cl = new FtpClient()) { + cl.Credentials = new NetworkCredential("ftptest", "ftptest"); + cl.Host = "localhost"; + cl.Connect(); + + Console.WriteLine("Supported HASH algorithms: {0}", cl.HashAlgorithms); + Console.WriteLine("Current HASH algorithm: {0}", cl.GetHashAlgorithm()); + + foreach (FtpHashAlgorithm alg in Enum.GetValues(typeof(FtpHashAlgorithm))) { + if (alg != FtpHashAlgorithm.NONE && cl.HashAlgorithms.HasFlag(alg)) { + FtpHash hash = null; + + cl.SetHashAlgorithm(alg); + hash = cl.GetHash("LICENSE.TXT"); + + if (hash.IsValid) { + Debug.Assert(hash.Verify(@"C:\FTPTEST\LICENSE.TXT"), "The computed hash didn't match or the hash object was invalid!"); + } + } + } + } + } + + static void TestReset() { + using (FtpClient cl = new FtpClient()) { + cl.Credentials = new NetworkCredential("ftptest", "ftptest"); + cl.Host = "localhost"; + cl.Connect(); + + using (Stream istream = cl.OpenRead("LICENSE.TXT", 10)) { + istream.Close(); + } + } + } + + static void GetMicrosoftFTPListing() { + using (FtpClient cl = new FtpClient()) { + cl.Credentials = new NetworkCredential("ftp", "ftp"); + cl.Host = "ftp.microsoft.com"; + cl.Connect(); + + Console.WriteLine(cl.Capabilities); + + foreach (FtpListItem item in cl.GetListing(null, FtpListOption.Modify)) { + Console.WriteLine(item.Modified); + } + } + } + + static void TestIISParser() { + string[] sample = new string[] { + "03-07-13 10:02AM 901 File01.xml", + "03-07-13 10:03AM 921 File02.xml", + "03-07-13 10:04AM 904 File03.xml", + "03-07-13 10:04AM 912 File04.xml", + "03-08-13 11:10AM 912 File05.xml", + "03-15-13 02:38PM 912 File06.xml", + "03-07-13 10:16AM 909 File07.xml", + "03-07-13 10:16AM 899 File08.xml", + "03-08-13 10:22AM 904 File09.xml", + "03-25-13 07:27AM 895 File10.xml", + "03-08-13 10:22AM 6199 File11.txt", + "03-25-13 07:22AM 31444 File12.txt", + "03-25-13 07:24AM 24537 File13.txt" + }; + + foreach (string s in sample) { + FtpListItem item = FtpListItem.Parse("/", s, 0); + + if (item != null) { + Console.WriteLine(item.Modified); + //Console.WriteLine(item); + } + } + } + + static void TestOpenVMSParser() { + string[] sample = new string[] { + "411_4114.TXT;1 11 21-MAR-2012 15:17 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "ACT_CC_NAME_4114.TXT;1 30 21-MAR-2012 15:17 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "ACT_CC_NUM_4114.TXT;1 30 21-MAR-2012 15:17 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "ACT_CELL_NAME_4114.TXT;1 113 21-MAR-2012 15:17 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "ACT_CELL_NUM_4114.TXT;1 113 21-MAR-2012 15:17 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "AGCY_BUDG_4114.TXT;1 63 21-MAR-2012 15:17 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "CELL_SUMM_4114.TXT;1 125 21-MAR-2012 15:17 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "CELL_SUMM_CHART_4114.PDF;2 95 21-MAR-2012 10:58 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "DET_4114.TXT;1 17472 21-MAR-2012 15:17 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "DET_4114_000.TXT;1 777 21-MAR-2012 15:18 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "DET_4114_001.TXT;1 254 21-MAR-2012 15:18 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "DET_4114_003.TXT;1 21 21-MAR-2012 15:18 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "DET_4114_006.TXT;1 22 21-MAR-2012 15:18 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "DET_4114_101.TXT;1 431 21-MAR-2012 15:18 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "DET_4114_121.TXT;1 2459 21-MAR-2012 15:18 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "DET_4114_124.TXT;1 4610 21-MAR-2012 15:18 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "DET_4114_200.TXT;1 936 21-MAR-2012 15:18 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)", + "TEL_4114.TXT;1 1178 21-MAR-2012 15:19 [TBMS,TBMS_BOSS] (RWED,RWED,,RE)" + }; + + foreach (string s in sample) { + FtpListItem item = FtpListItem.Parse("disk$user520:[4114.2012.Jan]", s, 0); + + if (item != null) { + Console.WriteLine(item.Modified); + //Console.WriteLine(item); + } + } + } + + static void TestMODCOMP_PWD_Parser() { + string response = "PWD = ~TNA=AMP,VNA=VOL03,FNA=U-ED-B2-USL"; + Match m; + + if ((m = Regex.Match(response, "PWD = (?.*)")).Success) + Console.WriteLine("PWD: {0}", m.Groups["pwd"].Value); + } + + static void TestNameListing() { + using (FtpClient cl = new FtpClient()) { + cl.Credentials = new NetworkCredential(m_user, m_pass); + cl.Host = "127.0.0.1"; + cl.ValidateCertificate += OnValidateCertificate; + cl.DataConnectionType = FtpDataConnectionType.PASV; + //cl.EncryptionMode = FtpEncryptionMode.Explicit; + //cl.SocketPollInterval = 5000; + cl.Connect(); + + //Console.WriteLine("Sleeping for 10 seconds to force timeout."); + //Thread.Sleep(10000); + + foreach (FtpListItem item in cl.GetListing(null, FtpListOption.SizeModify | FtpListOption.ForceNameList)) { + Console.WriteLine(item.Modified.Kind); + Console.WriteLine(item.Modified); + } + } + } + + static FtpClient Connect() { + List threads = new List(); + FtpClient cl = new FtpClient(); + + cl.ValidateCertificate += OnValidateCertificate; + //cl.EncryptionMode = FtpEncryptionMode.Explicit; + + for (int i = 0; i < 10; i++) { + int count = i; + + Thread t = new Thread(new ThreadStart(delegate() { + cl.Credentials = new NetworkCredential(m_user, m_pass); + cl.Host = m_host; + cl.Connect(); + + for (int j = 0; j < 10; j++) + cl.Execute("NOOP"); + + if (count % 2 == 0) + cl.Disconnect(); + })); + + t.Start(); + threads.Add(t); + } + + while (threads.Count > 0) { + threads[0].Join(); + threads.RemoveAt(0); + } + + return cl; + } + + static void OnValidateCertificate(FtpClient control, FtpSslValidationEventArgs e) { + e.Accept = true; + } + + static void Upload(FtpClient cl) { + string root = @"..\..\.."; + List threads = new List(); + + foreach (string s in Directory.GetFiles(root, "*", SearchOption.AllDirectories)) { + string file = s; + + if (file.Contains(@"\.git")) + continue; + + Thread t = new Thread(new ThreadStart(delegate() { + DoUpload(cl, root, file); + })); + + t.Start(); + threads.Add(t); + } + + while (threads.Count > 0) { + threads[0].Join(); + threads.RemoveAt(0); + } + } + + static void DoUpload(FtpClient cl, string root, string s) { + FtpDataType type = FtpDataType.Binary; + string path = Path.GetDirectoryName(s).Replace(root, ""); + string name = Path.GetFileName(s); + + if (Path.GetExtension(s).ToLower() == ".cs" || Path.GetExtension(s).ToLower() == ".txt") + type = FtpDataType.ASCII; + + if (!cl.DirectoryExists(path)) + cl.CreateDirectory(path, true); + else if (cl.FileExists(string.Format("{0}/{1}", path, name))) + cl.DeleteFile(string.Format("{0}/{1}", path, name)); + + using ( + Stream istream = new FileStream(s, FileMode.Open, FileAccess.Read), + ostream = cl.OpenWrite(s.Replace(root, ""), type)) { + byte[] buf = new byte[8192]; + int read = 0; + + try { + while ((read = istream.Read(buf, 0, buf.Length)) > 0) { + ostream.Write(buf, 0, read); + } + } + finally { + ostream.Close(); + istream.Close(); + } + + if (cl.HashAlgorithms != FtpHashAlgorithm.NONE) { + Debug.Assert(cl.GetHash(s.Replace(root, "")).Verify(s), "The computed hashes don't match!"); + } + } + + /*if (!cl.GetHash(s.Replace(root, "")).Verify(s)) + throw new Exception("Hashes didn't match!");*/ + } + + static void Download(FtpClient cl) { + List threads = new List(); + + Download(threads, cl, "/"); + + while (threads.Count > 0) { + threads[0].Join(); + + lock (threads) { + threads.RemoveAt(0); + } + } + } + + static void Download(List threads, FtpClient cl, string path) { + foreach (FtpListItem item in cl.GetListing(path)) { + if (item.Type == FtpFileSystemObjectType.Directory) + Download(threads, cl, item.FullName); + else if (item.Type == FtpFileSystemObjectType.File) { + string file = item.FullName; + + Thread t = new Thread(new ThreadStart(delegate() { + DoDownload(cl, file); + })); + + t.Start(); + + lock (threads) { + threads.Add(t); + } + } + } + } + + static void DoDownload(FtpClient cl, string file) { + using (Stream s = cl.OpenRead(file)) { + byte[] buf = new byte[8192]; + + try { + while (s.Read(buf, 0, buf.Length) > 0) ; + } + finally { + s.Close(); + } + } + } + + static void Delete(FtpClient cl) { + DeleteDirectory(cl, "/"); + } + + static void DeleteDirectory(FtpClient cl, string path) { + foreach (FtpListItem item in cl.GetListing(path)) { + if (item.Type == FtpFileSystemObjectType.File) { + cl.DeleteFile(item.FullName); + } + else if (item.Type == FtpFileSystemObjectType.Directory) { + DeleteDirectory(cl, item.FullName); + cl.DeleteDirectory(item.FullName); + } + } + } + + static void TestUTF8() { + // the following file name was reported in the discussions as having + // problems: + // https://netftp.codeplex.com/discussions/445090 + string filename = "Verbundmörtel Zubehör + Technische Daten DE.pdf"; + + using (FtpClient cl = new FtpClient()) { + cl.Host = "localhost"; + cl.Credentials = new NetworkCredential("ftptest", "ftptest"); + cl.DataConnectionType = FtpDataConnectionType.PASV; + cl.InternetProtocolVersions = FtpIpVersion.ANY; + + using (Stream ostream = cl.OpenWrite(filename)) { + StreamWriter writer = new StreamWriter(filename); + writer.WriteLine(filename); + writer.Close(); + } + } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of System.Diagnostics.ConsoleTraceListener::.ctor() at Line 25) of type System.Diagnostics.ConsoleTraceListener in method "Void Program.Main(String[])". + +### Severity: +ERROR + +### Procedure: +Void Program.Main(String[]) + +### File: +Tests/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +a39082a026e7b8146e74698bb9056daa + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2050/instruction.md b/inferredbugs-2050/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a455eec31f2372b26f8796506ea7e9a2c7d1b116 --- /dev/null +++ b/inferredbugs-2050/instruction.md @@ -0,0 +1,97 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** webview-cs +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Drawing; +using System.Linq; +using System.Threading; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server.Features; + +namespace Webview.WebHost +{ + public static class WebHostExtensions + { + public static void RunWebview(this IWebHost host, WebviewBuilder builder) + { + CancellationTokenSource cts = new CancellationTokenSource(); + host.StartAsync(cts.Token); + var features = host.ServerFeatures.Get(); + string address = features.Addresses.FirstOrDefault(); + IContent content = Content.FromUri(new Uri(address)); + builder.WithContent(content).Build().Run(); + cts.Cancel(); + } + + public static void RunWebview(this IWebHost host, string Title = "", Size size = default(Size)) + { + RunWebview(host, new WebviewBuilder().WithTitle(Title).WithSize(size)); + } + } + + public static class WebHostBuilderExtensions + { + public static IWebHostBuilder ConfigureForWebview(this IWebHostBuilder builder) + { + return builder.ConfigureLogging((ILoggingBuilder logBuilder) => { logBuilder.ClearProviders(); }) + .UseUrls("http://127.0.0.1:0"); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource cts of type System.Threading.CancellationTokenSource, Leaked resource (returned from Webview.Webview Webview.WebviewBuilder::Build() at Line 20) of type Webview.Webview in method "Void WebHostExtensions.RunWebview(IWebHost,WebviewBuilder)". + +### Severity: +ERROR + +### Procedure: +Void WebHostExtensions.RunWebview(IWebHost,WebviewBuilder) + +### File: +src/Webview.WebHost/WebHostExtensions.cs + +### Key: +WebHostExtensions.cs|RunWebview|DOTNET_RESOURCE_LEAK + +### Hash: +2b498b75771749aef559e0d7012a5d88 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2051/instruction.md b/inferredbugs-2051/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d7e6a7c6f9159d5bf40c878ad1ac83c9078195c1 --- /dev/null +++ b/inferredbugs-2051/instruction.md @@ -0,0 +1,94 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** webview-cs +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Drawing; + +using Webview; + +namespace Eval +{ + class Program + { + + static void Main(string[] args) + { + var html = @"

Eval

"; + var webview = new WebviewBuilder("Eval", Content.FromHtml(html)) + .WithSize(new Size(1024, 768)) + .Debug() + .Build(); + + TimeSpan duration = TimeSpan.FromMilliseconds(1000); + DateTime timeout = DateTime.Now; + + int tick = 0; + while (webview.Loop() == 0) + { + if (DateTime.Now > timeout) + { + timeout = DateTime.Now + duration; + webview.Eval(@"document.getElementById('content').textContent = 'Time:" + DateTime.Now.ToString() + "'"); + } + + webview.Title = $"Eval - tick:{tick++.ToString()}"; + } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource webview of type Webview.Webview in method "Void Program.Main(String[])". + +### Severity: +ERROR + +### Procedure: +Void Program.Main(String[]) + +### File: +examples/Eval/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +8547cddc1ca80fcace8637903e3c3584 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2058/instruction.md b/inferredbugs-2058/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..889463997ca8196129d6cb039633796bcba2ac8c --- /dev/null +++ b/inferredbugs-2058/instruction.md @@ -0,0 +1,951 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** C-Sharp-Algorithms +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections; +using System.Collections.Generic; + +using DataStructures.Common; + +namespace DataStructures.Trees +{ + /// + /// The binary search tree node. + /// + + public class BSTNode : IComparable> where T : IComparable + { + private T _value; + private BSTNode _parent; + private BSTNode _left; + private BSTNode _right; + + public BSTNode() : this(default(T), 0, null, null, null) { } + public BSTNode(T value) : this(value, 0, null, null, null) { } + public BSTNode(T value, int subTreeSize, BSTNode parent, BSTNode left, BSTNode right) + { + Value = value; + Parent = parent; + LeftChild = left; + RightChild = right; + } + + public virtual T Value + { + get { return this._value; } + set { this._value = value; } + } + + public virtual BSTNode Parent + { + get { return this._parent; } + set { this._parent = value; } + } + + public virtual BSTNode LeftChild + { + get { return this._left; } + set { this._left = value; } + } + + public virtual BSTNode RightChild + { + get { return this._right; } + set { this._right = value; } + } + + /// + /// Checks whether this node has any children. + /// + public virtual bool HasChildren + { + get { return (this.ChildrenCount > 0); } + } + + /// + /// Checks whether this node has left child. + /// + public virtual bool HasLeftChild + { + get { return (this.LeftChild != null); } + } + + /// + /// Checks whether this node has right child. + /// + public virtual bool HasRightChild + { + get { return (this.RightChild != null); } + } + + /// + /// Checks whether this node is the left child of it's parent. + /// + public virtual bool IsLeftChild + { + get { return (this.Parent != null && this.Parent.LeftChild == this); } + } + + /// + /// Checks whether this node is the left child of it's parent. + /// + public virtual bool IsRightChild + { + get { return (this.Parent != null && this.Parent.RightChild == this); } + } + + /// + /// Checks whether this node is a leaf node. + /// + public virtual bool IsLeafNode + { + get { return (this.ChildrenCount == 0); } + } + + /// + /// Returns number of direct descendents: 0, 1, 2 (none, left or right, or both). + /// + /// Number (0,1,2) + public virtual int ChildrenCount + { + get + { + int count = 0; + + if (this.HasLeftChild) + count++; + if (this.HasRightChild) + count++; + + return count; + } + } + + /// + /// Compares to. + /// + public virtual int CompareTo(BSTNode other) + { + if (other == null) + return -1; + + return this.Value.CompareTo(other.Value); + } + }//end-of-bstnode + + + /******************************************************************************/ + + + /// + /// Implements a generic Binary Search Tree data structure. + /// + /// Type of elements. + + public class BinarySearchTree : IBinarySearchTree where T : IComparable + { + /// + /// Specifies the mode of travelling through the tree. + /// + public enum TraversalMode + { + InOrder = 0, + PreOrder = 1, + PostOrder = 2 + } + + + /// + /// TREE INSTANCE VARIABLES + /// + /// + protected int _count { get; set; } + private BSTNode _root { get; set; } + + public virtual BSTNode Root + { + get { return this._root; } + set { this._root = value; } + } + + public BinarySearchTree() + { + Root = null; + _count = 0; + } + + + /// + /// Replaces the node's value from it's parent node object with the newValue. + /// Used in the recusive _remove function. + /// + /// BST node. + /// New value. + protected virtual void _replaceNodeInParent(BSTNode node, BSTNode newNode = null) + { + if (node.Parent != null) + { + if (node.IsLeftChild) + node.Parent.LeftChild = newNode; + else + node.Parent.RightChild = newNode; + } + + if (newNode != null) + newNode.Parent = node.Parent; + } + + /// + /// Remove the specified node. + /// + /// Node. + /// >True if removed successfully; false if node wasn't found. + protected virtual bool _remove(BSTNode node) + { + if (node == null) + return false; + + var parent = node.Parent; + + if (node.ChildrenCount == 2) // if both children are present + { + var successor = node.RightChild; + node.Value = successor.Value; + return (true && _remove(successor)); + } + else if (node.HasLeftChild) // if the node has only a LEFT child + { + _replaceNodeInParent(node, node.LeftChild); + _count--; + + } + else if (node.HasRightChild) // if the node has only a RIGHT child + { + _replaceNodeInParent(node, node.RightChild); + _count--; + } + else //this node has no children + { + _replaceNodeInParent(node, null); + _count--; + } + + return true; + } + + /// + /// Inserts a new node to the tree. + /// + /// Current node to insert afters. + /// New node to be inserted. + protected virtual void _insertNode(BSTNode newNode) + { + // Handle empty trees + if (this.Root == null) + { + Root = newNode; + _count++; + return; + } + else + { + if (newNode.Parent == null) + newNode.Parent = this.Root; + + // Go Left + if (newNode.Parent.Value.IsGreaterThan(newNode.Value)) // newNode < parent + { + if (newNode.Parent.HasLeftChild == false) + { + newNode.Parent.LeftChild = newNode; + _count++; + return; + } + else + { + newNode.Parent = newNode.Parent.LeftChild; + _insertNode(newNode); + } + } + // Go Right + else // new node > parent + { + if (newNode.Parent.HasRightChild == false) + { + newNode.Parent.RightChild = newNode; + _count++; + return; + } + else + { + newNode.Parent = newNode.Parent.RightChild; + _insertNode(newNode); + } + } + } + } + + /// + /// Calculates the tree height from a specific node, recursively. + /// Time-complexity: O(n), where n = number of nodes. + /// + /// Node + /// Height of node's longest subtree + protected virtual int _getTreeHeight(BSTNode node) + { + if (node == null || node.IsLeafNode == true) + return 0; + + if (node.ChildrenCount == 2) // it has both a right child and a left child + { + return (1 + Math.Max(_getTreeHeight(node.LeftChild), _getTreeHeight(node.RightChild))); + } + else if (node.HasLeftChild) + { + return (1 + _getTreeHeight(node.LeftChild)); + } + else if (node.HasRightChild) + { + return (1 + _getTreeHeight(node.RightChild)); + } + + // return-functions-fix + return 0; + } + + /// + /// Finds a node inside another node's subtrees, given it's value. + /// + /// Node to start search from. + /// Search value + /// Node if found; otherwise null + protected virtual BSTNode _findNode(BSTNode currentNode, T item) + { + if (currentNode == null) + return currentNode; + + if (item.IsEqualTo(currentNode.Value)) + { + return currentNode; + } + else if (currentNode.HasLeftChild && item.IsLessThan(currentNode.Value)) + { + return _findNode(currentNode.LeftChild, item); + } + else if (currentNode.HasRightChild && item.IsGreaterThan(currentNode.Value)) + { + return _findNode(currentNode.RightChild, item); + } + + // Return-functions-fix + return null; + } + + /// + /// Returns the min-node in a subtree. + /// Used in the recusive _remove function. + /// + /// The minimum-valued tree node. + /// The tree node with subtree(s). + protected virtual BSTNode _findMinNode(BSTNode node) + { + if (node == null) + return node; + + var currentNode = node; + + while (currentNode.HasLeftChild) + currentNode = currentNode.LeftChild; + + return currentNode; + } + + /// + /// Returns the max-node in a subtree. + /// Used in the recusive _remove function. + /// + /// The maximum-valued tree node. + /// The tree node with subtree(s). + protected virtual BSTNode _findMaxNode(BSTNode node) + { + if (node == null) + return node; + + var currentNode = node; + + while (currentNode.HasRightChild) + currentNode = currentNode.RightChild; + + return currentNode; + } + + /// + /// Finds the next smaller node in value compared to the specified node. + /// + protected virtual BSTNode _findNextSmaller(BSTNode node) + { + if (node == null) + return node; + + if (node.HasLeftChild) + return _findMaxNode(node.LeftChild); + + var currentNode = node; + while (currentNode.Parent != null && currentNode.IsLeftChild) + currentNode = currentNode.Parent; + + return currentNode.Parent; + } + + /// + /// Finds the next larger node in value compared to the specified node. + /// + protected virtual BSTNode _findNextLarger(BSTNode node) + { + if (node == null) + return node; + + if (node.HasRightChild) + return _findMinNode(node.RightChild); + + var currentNode = node; + while (currentNode.Parent != null && currentNode.IsRightChild) + currentNode = currentNode.Parent; + + return currentNode.Parent; + } + + /// + /// A recursive private method. Used in the public FindAll(predicate) functions. + /// Implements in-order traversal to find all the matching elements in a subtree. + /// + /// Node to start searching from. + /// + protected virtual void _findAll(BSTNode currentNode, Predicate match, ref List list) + { + if (currentNode == null) + return; + + // call the left child + _findAll(currentNode.LeftChild, match, ref list); + + if (match(currentNode.Value)) // match + { + list.Add(currentNode.Value); + } + + // call the right child + _findAll(currentNode.RightChild, match, ref list); + } + + /// + /// In-order traversal of the subtrees of a node. Returns every node it vists. + /// + /// Node to traverse the tree from. + /// List to add elements to. + protected virtual void _inOrderTraverse(BSTNode currentNode, ref List list) + { + if (currentNode == null) + return; + + // call the left child + _inOrderTraverse(currentNode.LeftChild, ref list); + + // visit node + list.Add(currentNode.Value); + + // call the right child + _inOrderTraverse(currentNode.RightChild, ref list); + } + + + /// + /// Return the number of elements in this tree + /// + /// + public virtual int Count() + { + return _count; + } + + /// + /// Checks if tree is empty. + /// + /// + public virtual bool IsEmpty() + { + return (_count == 0); + } + + /// + /// Returns the height of the tree. + /// Time-complexity: O(n), where n = number of nodes. + /// + /// Hight + public virtual int Height() + { + if (IsEmpty()) + return 0; + + var currentNode = Root; + return _getTreeHeight(currentNode); + } + + /// + /// Inserts an element to the tree + /// + /// Item to insert + public virtual void Insert(T item) + { + var newNode = new BSTNode(item); + + // Insert node recursively starting from the root. + _insertNode(newNode); + } + + /// + /// Deletes an element from the tree + /// + /// item to remove. + public virtual void Remove(T item) + { + if (IsEmpty()) + throw new Exception("Tree is empty."); + + var node = _findNode(Root, item); + bool status = _remove(node); + + // If the element was found, remove it. + if (status == false) + throw new Exception("Item was not found."); + } + + /// + /// Removes the min value from tree. + /// + public virtual void RemoveMin() + { + if (IsEmpty()) + throw new Exception("Tree is empty."); + + var node = _findMinNode(Root); + var parent = node.Parent; + _remove(node); + } + + /// + /// Removes the max value from tree. + /// + public virtual void RemoveMax() + { + if (IsEmpty()) + throw new Exception("Tree is empty."); + + var node = _findMaxNode(Root); + var parent = node.Parent; + _remove(node); + } + + /// + /// Clears all elements from tree. + /// + public virtual void Clear() + { + Root = null; + _count = 0; + } + + /// + /// Finds the minimum in tree + /// + /// Min + public virtual T FindMin() + { + if (IsEmpty()) + throw new Exception("Tree is empty."); + + return _findMinNode(Root).Value; + } + + /// + /// Finds the next smaller element in tree, compared to the specified item. + /// + public virtual T FindNextSmaller(T item) + { + var node = _findNode(Root, item); + var nextSmaller = _findNextSmaller(node); + + if (nextSmaller == null) + throw new Exception("Item was not found."); + + return nextSmaller.Value; + } + + /// + /// Finds the next larger element in tree, compared to the specified item. + /// + public virtual T FindNextLarger(T item) + { + var node = _findNode(Root, item); + var nextLarger = _findNextLarger(node); + + if (nextLarger == null) + throw new Exception("Item was not found."); + + return nextLarger.Value; + } + + /// + /// Finds the maximum in tree + /// + /// Max + public virtual T FindMax() + { + if (IsEmpty()) + throw new Exception("Tree is empty."); + + return _findMaxNode(Root).Value; + } + + /// + /// Find the item in the tree. Throws an exception if not found. + /// + /// Item to find. + /// Item. + public virtual T Find(T item) + { + if (IsEmpty()) + throw new Exception("Tree is empty."); + + var node = _findNode(Root, item); + + if (node != null) + return node.Value; + else + throw new Exception("Item was not found."); + } + + /// + /// Given a predicate function, find all the elements that match it. + /// + /// The search predicate + /// ArrayList of elements. + public virtual List FindAll(Predicate searchPredicate) + { + var list = new List(); + _findAll(Root, searchPredicate, ref list); + + return list; + } + + /// + /// Sort the elements in this tree, using in-order traversal, and returns them. + /// + public virtual List Sort() + { + var list = new List(); + _inOrderTraverse(Root, ref list); + + return list; + } + + /// + /// Returns an array of nodes' values. + /// + /// The array. + public virtual T[] ToArray() + { + // the array version of binary search tree is the sorted arrangement of nodes. + return Sort().ToArray(); + } + + /// + /// Returns a list of the nodes' value. + /// + public virtual List ToList() + { + // the list version of binary search tree is the sorted arrangement of nodes. + return Sort(); + } + + + /*********************************************************************/ + + + /// + /// Returns an enumerator that visits node in the order: parent, left child, right child + /// + public virtual IEnumerator GetPreOrderEnumerator() + { + return new BinarySearchTreePreOrderEnumerator(this); + } + + /// + /// Returns an enumerator that visits node in the order: left child, parent, right child + /// + public virtual IEnumerator GetInOrderEnumerator() + { + return new BinarySearchTreeInOrderEnumerator(this); + } + + /// + /// Returns an enumerator that visits node in the order: left child, right child, parent + /// + public virtual IEnumerator GetPostOrderEnumerator() + { + return new BinarySearchTreePostOrderEnumerator(this); + } + + + /*********************************************************************/ + + + /// + /// Returns an preorder-traversal enumerator for the tree values + /// + internal class BinarySearchTreePreOrderEnumerator : IEnumerator + { + private BSTNode current; + private BinarySearchTree tree; + internal Queue> traverseQueue; + + public BinarySearchTreePreOrderEnumerator(BinarySearchTree tree) + { + this.tree = tree; + + //Build queue + traverseQueue = new Queue>(); + visitNode(this.tree.Root); + } + + private void visitNode(BSTNode node) + { + if (node == null) + return; + else + { + traverseQueue.Enqueue(node); + visitNode(node.LeftChild); + visitNode(node.RightChild); + } + } + + public T Current + { + get { return current.Value; } + } + + object IEnumerator.Current + { + get { return Current; } + } + + public void Dispose() + { + current = null; + tree = null; + } + + public void Reset() + { + current = null; + } + + public bool MoveNext() + { + if (traverseQueue.Count > 0) + current = traverseQueue.Dequeue(); + else + current = null; + + return (current != null); + } + } + + + /// + /// Returns an inorder-traversal enumerator for the tree values + /// + internal class BinarySearchTreeInOrderEnumerator : IEnumerator + { + private BSTNode current; + private BinarySearchTree tree; + internal Queue> traverseQueue; + + public BinarySearchTreeInOrderEnumerator(BinarySearchTree tree) + { + this.tree = tree; + + //Build queue + traverseQueue = new Queue>(); + visitNode(this.tree.Root); + } + + private void visitNode(BSTNode node) + { + if (node == null) + return; + else + { + visitNode(node.LeftChild); + traverseQueue.Enqueue(node); + visitNode(node.RightChild); + } + } + + public T Current + { + get { return current.Value; } + } + + object IEnumerator.Current + { + get { return Current; } + } + + public void Dispose() + { + current = null; + tree = null; + } + + public void Reset() + { + current = null; + } + + public bool MoveNext() + { + if (traverseQueue.Count > 0) + current = traverseQueue.Dequeue(); + else + current = null; + + return (current != null); + } + } + + /// + /// Returns a postorder-traversal enumerator for the tree values + /// + internal class BinarySearchTreePostOrderEnumerator : IEnumerator + { + private BSTNode current; + private BinarySearchTree tree; + internal Queue> traverseQueue; + + public BinarySearchTreePostOrderEnumerator(BinarySearchTree tree) + { + this.tree = tree; + + //Build queue + traverseQueue = new Queue>(); + visitNode(this.tree.Root); + } + + private void visitNode(BSTNode node) + { + if (node == null) + return; + else + { + visitNode(node.LeftChild); + visitNode(node.RightChild); + traverseQueue.Enqueue(node); + } + } + + public T Current + { + get { return current.Value; } + } + + object IEnumerator.Current + { + get { return Current; } + } + + public void Dispose() + { + current = null; + tree = null; + } + + public void Reset() + { + current = null; + } + + public bool MoveNext() + { + if (traverseQueue.Count > 0) + current = traverseQueue.Dequeue(); + else + current = null; + + return (current != null); + } + } + + }//end-of-binary-search-tree + +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `node` last assigned on line 528 could be null and is dereferenced at line 529, column 13. + +### Severity: +ERROR + +### Procedure: +Void BinarySearchTree`1.RemoveMin() + +### File: +DataStructures/Trees/BinarySearchTree.cs + +### Key: +BinarySearchTree.cs|RemoveMin|NULL_DEREFERENCE + +### Node Key: +2ecce4273ada11ad161ca44c6f340c1e + +### Hash: +bb6474f7f78987b8a61266e1960aa761 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2059/instruction.md b/inferredbugs-2059/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..344b387a9b126ecc1706d9b04f54279bae472e92 --- /dev/null +++ b/inferredbugs-2059/instruction.md @@ -0,0 +1,951 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** C-Sharp-Algorithms +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections; +using System.Collections.Generic; + +using DataStructures.Common; + +namespace DataStructures.Trees +{ + /// + /// The binary search tree node. + /// + + public class BSTNode : IComparable> where T : IComparable + { + private T _value; + private BSTNode _parent; + private BSTNode _left; + private BSTNode _right; + + public BSTNode() : this(default(T), 0, null, null, null) { } + public BSTNode(T value) : this(value, 0, null, null, null) { } + public BSTNode(T value, int subTreeSize, BSTNode parent, BSTNode left, BSTNode right) + { + Value = value; + Parent = parent; + LeftChild = left; + RightChild = right; + } + + public virtual T Value + { + get { return this._value; } + set { this._value = value; } + } + + public virtual BSTNode Parent + { + get { return this._parent; } + set { this._parent = value; } + } + + public virtual BSTNode LeftChild + { + get { return this._left; } + set { this._left = value; } + } + + public virtual BSTNode RightChild + { + get { return this._right; } + set { this._right = value; } + } + + /// + /// Checks whether this node has any children. + /// + public virtual bool HasChildren + { + get { return (this.ChildrenCount > 0); } + } + + /// + /// Checks whether this node has left child. + /// + public virtual bool HasLeftChild + { + get { return (this.LeftChild != null); } + } + + /// + /// Checks whether this node has right child. + /// + public virtual bool HasRightChild + { + get { return (this.RightChild != null); } + } + + /// + /// Checks whether this node is the left child of it's parent. + /// + public virtual bool IsLeftChild + { + get { return (this.Parent != null && this.Parent.LeftChild == this); } + } + + /// + /// Checks whether this node is the left child of it's parent. + /// + public virtual bool IsRightChild + { + get { return (this.Parent != null && this.Parent.RightChild == this); } + } + + /// + /// Checks whether this node is a leaf node. + /// + public virtual bool IsLeafNode + { + get { return (this.ChildrenCount == 0); } + } + + /// + /// Returns number of direct descendents: 0, 1, 2 (none, left or right, or both). + /// + /// Number (0,1,2) + public virtual int ChildrenCount + { + get + { + int count = 0; + + if (this.HasLeftChild) + count++; + if (this.HasRightChild) + count++; + + return count; + } + } + + /// + /// Compares to. + /// + public virtual int CompareTo(BSTNode other) + { + if (other == null) + return -1; + + return this.Value.CompareTo(other.Value); + } + }//end-of-bstnode + + + /******************************************************************************/ + + + /// + /// Implements a generic Binary Search Tree data structure. + /// + /// Type of elements. + + public class BinarySearchTree : IBinarySearchTree where T : IComparable + { + /// + /// Specifies the mode of travelling through the tree. + /// + public enum TraversalMode + { + InOrder = 0, + PreOrder = 1, + PostOrder = 2 + } + + + /// + /// TREE INSTANCE VARIABLES + /// + /// + protected int _count { get; set; } + private BSTNode _root { get; set; } + + public virtual BSTNode Root + { + get { return this._root; } + set { this._root = value; } + } + + public BinarySearchTree() + { + Root = null; + _count = 0; + } + + + /// + /// Replaces the node's value from it's parent node object with the newValue. + /// Used in the recusive _remove function. + /// + /// BST node. + /// New value. + protected virtual void _replaceNodeInParent(BSTNode node, BSTNode newNode = null) + { + if (node.Parent != null) + { + if (node.IsLeftChild) + node.Parent.LeftChild = newNode; + else + node.Parent.RightChild = newNode; + } + + if (newNode != null) + newNode.Parent = node.Parent; + } + + /// + /// Remove the specified node. + /// + /// Node. + /// >True if removed successfully; false if node wasn't found. + protected virtual bool _remove(BSTNode node) + { + if (node == null) + return false; + + var parent = node.Parent; + + if (node.ChildrenCount == 2) // if both children are present + { + var successor = node.RightChild; + node.Value = successor.Value; + return (true && _remove(successor)); + } + else if (node.HasLeftChild) // if the node has only a LEFT child + { + _replaceNodeInParent(node, node.LeftChild); + _count--; + + } + else if (node.HasRightChild) // if the node has only a RIGHT child + { + _replaceNodeInParent(node, node.RightChild); + _count--; + } + else //this node has no children + { + _replaceNodeInParent(node, null); + _count--; + } + + return true; + } + + /// + /// Inserts a new node to the tree. + /// + /// Current node to insert afters. + /// New node to be inserted. + protected virtual void _insertNode(BSTNode newNode) + { + // Handle empty trees + if (this.Root == null) + { + Root = newNode; + _count++; + return; + } + else + { + if (newNode.Parent == null) + newNode.Parent = this.Root; + + // Go Left + if (newNode.Parent.Value.IsGreaterThan(newNode.Value)) // newNode < parent + { + if (newNode.Parent.HasLeftChild == false) + { + newNode.Parent.LeftChild = newNode; + _count++; + return; + } + else + { + newNode.Parent = newNode.Parent.LeftChild; + _insertNode(newNode); + } + } + // Go Right + else // new node > parent + { + if (newNode.Parent.HasRightChild == false) + { + newNode.Parent.RightChild = newNode; + _count++; + return; + } + else + { + newNode.Parent = newNode.Parent.RightChild; + _insertNode(newNode); + } + } + } + } + + /// + /// Calculates the tree height from a specific node, recursively. + /// Time-complexity: O(n), where n = number of nodes. + /// + /// Node + /// Height of node's longest subtree + protected virtual int _getTreeHeight(BSTNode node) + { + if (node == null || node.IsLeafNode == true) + return 0; + + if (node.ChildrenCount == 2) // it has both a right child and a left child + { + return (1 + Math.Max(_getTreeHeight(node.LeftChild), _getTreeHeight(node.RightChild))); + } + else if (node.HasLeftChild) + { + return (1 + _getTreeHeight(node.LeftChild)); + } + else if (node.HasRightChild) + { + return (1 + _getTreeHeight(node.RightChild)); + } + + // return-functions-fix + return 0; + } + + /// + /// Finds a node inside another node's subtrees, given it's value. + /// + /// Node to start search from. + /// Search value + /// Node if found; otherwise null + protected virtual BSTNode _findNode(BSTNode currentNode, T item) + { + if (currentNode == null) + return currentNode; + + if (item.IsEqualTo(currentNode.Value)) + { + return currentNode; + } + else if (currentNode.HasLeftChild && item.IsLessThan(currentNode.Value)) + { + return _findNode(currentNode.LeftChild, item); + } + else if (currentNode.HasRightChild && item.IsGreaterThan(currentNode.Value)) + { + return _findNode(currentNode.RightChild, item); + } + + // Return-functions-fix + return null; + } + + /// + /// Returns the min-node in a subtree. + /// Used in the recusive _remove function. + /// + /// The minimum-valued tree node. + /// The tree node with subtree(s). + protected virtual BSTNode _findMinNode(BSTNode node) + { + if (node == null) + return node; + + var currentNode = node; + + while (currentNode.HasLeftChild) + currentNode = currentNode.LeftChild; + + return currentNode; + } + + /// + /// Returns the max-node in a subtree. + /// Used in the recusive _remove function. + /// + /// The maximum-valued tree node. + /// The tree node with subtree(s). + protected virtual BSTNode _findMaxNode(BSTNode node) + { + if (node == null) + return node; + + var currentNode = node; + + while (currentNode.HasRightChild) + currentNode = currentNode.RightChild; + + return currentNode; + } + + /// + /// Finds the next smaller node in value compared to the specified node. + /// + protected virtual BSTNode _findNextSmaller(BSTNode node) + { + if (node == null) + return node; + + if (node.HasLeftChild) + return _findMaxNode(node.LeftChild); + + var currentNode = node; + while (currentNode.Parent != null && currentNode.IsLeftChild) + currentNode = currentNode.Parent; + + return currentNode.Parent; + } + + /// + /// Finds the next larger node in value compared to the specified node. + /// + protected virtual BSTNode _findNextLarger(BSTNode node) + { + if (node == null) + return node; + + if (node.HasRightChild) + return _findMinNode(node.RightChild); + + var currentNode = node; + while (currentNode.Parent != null && currentNode.IsRightChild) + currentNode = currentNode.Parent; + + return currentNode.Parent; + } + + /// + /// A recursive private method. Used in the public FindAll(predicate) functions. + /// Implements in-order traversal to find all the matching elements in a subtree. + /// + /// Node to start searching from. + /// + protected virtual void _findAll(BSTNode currentNode, Predicate match, ref List list) + { + if (currentNode == null) + return; + + // call the left child + _findAll(currentNode.LeftChild, match, ref list); + + if (match(currentNode.Value)) // match + { + list.Add(currentNode.Value); + } + + // call the right child + _findAll(currentNode.RightChild, match, ref list); + } + + /// + /// In-order traversal of the subtrees of a node. Returns every node it vists. + /// + /// Node to traverse the tree from. + /// List to add elements to. + protected virtual void _inOrderTraverse(BSTNode currentNode, ref List list) + { + if (currentNode == null) + return; + + // call the left child + _inOrderTraverse(currentNode.LeftChild, ref list); + + // visit node + list.Add(currentNode.Value); + + // call the right child + _inOrderTraverse(currentNode.RightChild, ref list); + } + + + /// + /// Return the number of elements in this tree + /// + /// + public virtual int Count() + { + return _count; + } + + /// + /// Checks if tree is empty. + /// + /// + public virtual bool IsEmpty() + { + return (_count == 0); + } + + /// + /// Returns the height of the tree. + /// Time-complexity: O(n), where n = number of nodes. + /// + /// Hight + public virtual int Height() + { + if (IsEmpty()) + return 0; + + var currentNode = Root; + return _getTreeHeight(currentNode); + } + + /// + /// Inserts an element to the tree + /// + /// Item to insert + public virtual void Insert(T item) + { + var newNode = new BSTNode(item); + + // Insert node recursively starting from the root. + _insertNode(newNode); + } + + /// + /// Deletes an element from the tree + /// + /// item to remove. + public virtual void Remove(T item) + { + if (IsEmpty()) + throw new Exception("Tree is empty."); + + var node = _findNode(Root, item); + bool status = _remove(node); + + // If the element was found, remove it. + if (status == false) + throw new Exception("Item was not found."); + } + + /// + /// Removes the min value from tree. + /// + public virtual void RemoveMin() + { + if (IsEmpty()) + throw new Exception("Tree is empty."); + + var node = _findMinNode(Root); + var parent = node.Parent; + _remove(node); + } + + /// + /// Removes the max value from tree. + /// + public virtual void RemoveMax() + { + if (IsEmpty()) + throw new Exception("Tree is empty."); + + var node = _findMaxNode(Root); + var parent = node.Parent; + _remove(node); + } + + /// + /// Clears all elements from tree. + /// + public virtual void Clear() + { + Root = null; + _count = 0; + } + + /// + /// Finds the minimum in tree + /// + /// Min + public virtual T FindMin() + { + if (IsEmpty()) + throw new Exception("Tree is empty."); + + return _findMinNode(Root).Value; + } + + /// + /// Finds the next smaller element in tree, compared to the specified item. + /// + public virtual T FindNextSmaller(T item) + { + var node = _findNode(Root, item); + var nextSmaller = _findNextSmaller(node); + + if (nextSmaller == null) + throw new Exception("Item was not found."); + + return nextSmaller.Value; + } + + /// + /// Finds the next larger element in tree, compared to the specified item. + /// + public virtual T FindNextLarger(T item) + { + var node = _findNode(Root, item); + var nextLarger = _findNextLarger(node); + + if (nextLarger == null) + throw new Exception("Item was not found."); + + return nextLarger.Value; + } + + /// + /// Finds the maximum in tree + /// + /// Max + public virtual T FindMax() + { + if (IsEmpty()) + throw new Exception("Tree is empty."); + + return _findMaxNode(Root).Value; + } + + /// + /// Find the item in the tree. Throws an exception if not found. + /// + /// Item to find. + /// Item. + public virtual T Find(T item) + { + if (IsEmpty()) + throw new Exception("Tree is empty."); + + var node = _findNode(Root, item); + + if (node != null) + return node.Value; + else + throw new Exception("Item was not found."); + } + + /// + /// Given a predicate function, find all the elements that match it. + /// + /// The search predicate + /// ArrayList of elements. + public virtual List FindAll(Predicate searchPredicate) + { + var list = new List(); + _findAll(Root, searchPredicate, ref list); + + return list; + } + + /// + /// Sort the elements in this tree, using in-order traversal, and returns them. + /// + public virtual List Sort() + { + var list = new List(); + _inOrderTraverse(Root, ref list); + + return list; + } + + /// + /// Returns an array of nodes' values. + /// + /// The array. + public virtual T[] ToArray() + { + // the array version of binary search tree is the sorted arrangement of nodes. + return Sort().ToArray(); + } + + /// + /// Returns a list of the nodes' value. + /// + public virtual List ToList() + { + // the list version of binary search tree is the sorted arrangement of nodes. + return Sort(); + } + + + /*********************************************************************/ + + + /// + /// Returns an enumerator that visits node in the order: parent, left child, right child + /// + public virtual IEnumerator GetPreOrderEnumerator() + { + return new BinarySearchTreePreOrderEnumerator(this); + } + + /// + /// Returns an enumerator that visits node in the order: left child, parent, right child + /// + public virtual IEnumerator GetInOrderEnumerator() + { + return new BinarySearchTreeInOrderEnumerator(this); + } + + /// + /// Returns an enumerator that visits node in the order: left child, right child, parent + /// + public virtual IEnumerator GetPostOrderEnumerator() + { + return new BinarySearchTreePostOrderEnumerator(this); + } + + + /*********************************************************************/ + + + /// + /// Returns an preorder-traversal enumerator for the tree values + /// + internal class BinarySearchTreePreOrderEnumerator : IEnumerator + { + private BSTNode current; + private BinarySearchTree tree; + internal Queue> traverseQueue; + + public BinarySearchTreePreOrderEnumerator(BinarySearchTree tree) + { + this.tree = tree; + + //Build queue + traverseQueue = new Queue>(); + visitNode(this.tree.Root); + } + + private void visitNode(BSTNode node) + { + if (node == null) + return; + else + { + traverseQueue.Enqueue(node); + visitNode(node.LeftChild); + visitNode(node.RightChild); + } + } + + public T Current + { + get { return current.Value; } + } + + object IEnumerator.Current + { + get { return Current; } + } + + public void Dispose() + { + current = null; + tree = null; + } + + public void Reset() + { + current = null; + } + + public bool MoveNext() + { + if (traverseQueue.Count > 0) + current = traverseQueue.Dequeue(); + else + current = null; + + return (current != null); + } + } + + + /// + /// Returns an inorder-traversal enumerator for the tree values + /// + internal class BinarySearchTreeInOrderEnumerator : IEnumerator + { + private BSTNode current; + private BinarySearchTree tree; + internal Queue> traverseQueue; + + public BinarySearchTreeInOrderEnumerator(BinarySearchTree tree) + { + this.tree = tree; + + //Build queue + traverseQueue = new Queue>(); + visitNode(this.tree.Root); + } + + private void visitNode(BSTNode node) + { + if (node == null) + return; + else + { + visitNode(node.LeftChild); + traverseQueue.Enqueue(node); + visitNode(node.RightChild); + } + } + + public T Current + { + get { return current.Value; } + } + + object IEnumerator.Current + { + get { return Current; } + } + + public void Dispose() + { + current = null; + tree = null; + } + + public void Reset() + { + current = null; + } + + public bool MoveNext() + { + if (traverseQueue.Count > 0) + current = traverseQueue.Dequeue(); + else + current = null; + + return (current != null); + } + } + + /// + /// Returns a postorder-traversal enumerator for the tree values + /// + internal class BinarySearchTreePostOrderEnumerator : IEnumerator + { + private BSTNode current; + private BinarySearchTree tree; + internal Queue> traverseQueue; + + public BinarySearchTreePostOrderEnumerator(BinarySearchTree tree) + { + this.tree = tree; + + //Build queue + traverseQueue = new Queue>(); + visitNode(this.tree.Root); + } + + private void visitNode(BSTNode node) + { + if (node == null) + return; + else + { + visitNode(node.LeftChild); + visitNode(node.RightChild); + traverseQueue.Enqueue(node); + } + } + + public T Current + { + get { return current.Value; } + } + + object IEnumerator.Current + { + get { return Current; } + } + + public void Dispose() + { + current = null; + tree = null; + } + + public void Reset() + { + current = null; + } + + public bool MoveNext() + { + if (traverseQueue.Count > 0) + current = traverseQueue.Dequeue(); + else + current = null; + + return (current != null); + } + } + + }//end-of-binary-search-tree + +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `node` last assigned on line 541 could be null and is dereferenced at line 542, column 13. + +### Severity: +ERROR + +### Procedure: +Void BinarySearchTree`1.RemoveMax() + +### File: +DataStructures/Trees/BinarySearchTree.cs + +### Key: +BinarySearchTree.cs|RemoveMax|NULL_DEREFERENCE + +### Node Key: +2ecce4273ada11ad161ca44c6f340c1e + +### Hash: +e75e246b3542def1cde85db205ed2b2d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2060/instruction.md b/inferredbugs-2060/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cd85a0a39cd02df007f998e90b328e0566970ef9 --- /dev/null +++ b/inferredbugs-2060/instruction.md @@ -0,0 +1,319 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** NuGet.Client +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Xml; +using System.Xml.Linq; + +namespace NuGet.Configuration +{ + /// + /// Concrete implementation of ISettings to support NuGet Settings + /// + public class Settings : ISettings + { + /// + /// Default file name for a settings file is 'NuGet.config' + /// Also, the machine level setting file at '%APPDATA%\NuGet' always uses this name + /// + public const string DefaultSettingsFileName = "NuGet.config"; + private XDocument ConfigXDocument { get; set; } + private string ConfigFileName { get; set; } + + // next config file to read if any + private Settings _next; + + private readonly bool _isMachineWideSettings; + + // The priority of this setting file + private int _priority; + + public Settings(string root /*, ILogger logger */) + : this(root, DefaultSettingsFileName, false) + { + } + + public Settings(string root, string fileName) + : this(root, fileName, false) + { + } + + public Settings(string root, string fileName, bool isMachineWideSettings) + { + if (String.IsNullOrEmpty(root)) + { + throw new ArgumentException("root cannot be null or empty"); + } + + if (String.IsNullOrEmpty(fileName)) + { + throw new ArgumentException(NuGet_Configuration_Resources.Argument_Cannot_Be_Null_Or_Empty, "fileName"); + } + + if(!String.Equals(fileName, Path.GetFileName(fileName), StringComparison.OrdinalIgnoreCase)) + { + throw new ArgumentException(NuGet_Configuration_Resources.Settings_FileName_Cannot_Be_A_Path); + } + + Root = root; + ConfigFileName = fileName; + XDocument config = null; + ExecuteSynchronized(() => config = XmlUtility.GetOrCreateDocument("configuration", ConfigFilePath)); + ConfigXDocument = config; + _isMachineWideSettings = isMachineWideSettings; + } + + /// + /// Folder under which the config file is present + /// + public string Root + { + get; + private set; + } + + /// + /// Full path to the ConfigFile corresponding to this Settings object + /// + public string ConfigFilePath + { + get + { + return Path.GetFullPath(Path.Combine(Root, ConfigFileName)); + } + } + + public string GetValue(string section, string key, bool isPath = false) + { + if (String.IsNullOrEmpty(section)) + { + throw new ArgumentException(NuGet_Configuration_Resources.Argument_Cannot_Be_Null_Or_Empty, "section"); + } + + if (String.IsNullOrEmpty(key)) + { + throw new ArgumentException(NuGet_Configuration_Resources.Argument_Cannot_Be_Null_Or_Empty, "key"); + } + + XElement element = null; + string ret = null; + + var curr = this; + while (curr != null) + { + XElement newElement = curr.GetValueInternal(section, key, element); + if (!object.ReferenceEquals(element, newElement)) + { + element = newElement; + + // we need to evaluate using current Settings in case value needs path transformation + ret = curr.ElementToValue(element, isPath); + } + curr = curr._next; + } + + return ret; + } + + public IList GetSettingValues(string section) + { + throw new NotImplementedException(); + } + + public IList> GetNestedValues(string section, string subSection) + { + throw new NotImplementedException(); + } + + public void SetValue(string section, string key, string value) + { + throw new NotImplementedException(); + } + + public void SetValues(string section, IList> values) + { + throw new NotImplementedException(); + } + + public void SetNestedValues(string section, string subSection, IList> values) + { + throw new NotImplementedException(); + } + + public bool DeleteValue(string section, string key) + { + throw new NotImplementedException(); + } + + public bool DeleteSection(string section) + { + throw new NotImplementedException(); + } + + private XElement GetValueInternal(string section, string key, XElement curr) + { + // Get the section and return curr if it doesn't exist + var sectionElement = GetSection(ConfigXDocument.Root, section); + if (sectionElement == null) + { + return curr; + } + + // Get the add element that matches the key and return curr if it doesn't exist + return FindElementByKey(sectionElement, key, curr); + } + + private static XElement GetSection(XElement parentElement, string section) + { + section = XmlConvert.EncodeLocalName(section); + return parentElement.Element(section); + } + + private static XElement FindElementByKey(XElement sectionElement, string key, XElement curr) + { + XElement result = curr; + foreach (var element in sectionElement.Elements()) + { + string elementName = element.Name.LocalName; + if (elementName.Equals("clear", StringComparison.OrdinalIgnoreCase)) + { + result = null; + } + else if (elementName.Equals("add", StringComparison.OrdinalIgnoreCase) && + XmlUtility.GetOptionalAttributeValue(element, "key").Equals(key, StringComparison.OrdinalIgnoreCase)) + { + result = element; + } + } + return result; + } + + private string ElementToValue(XElement element, bool isPath) + { + if (element == null) + { + return null; + } + + // Return the optional value which if not there will be null; + string value = XmlUtility.GetOptionalAttributeValue(element, "value"); + if (!isPath || String.IsNullOrEmpty(value)) + { + return value; + } + return Path.Combine(Root, ResolvePath(Path.GetDirectoryName(ConfigFilePath), value)); + } + + private static string ResolvePath(string configDirectory, string value) + { + // Three cases for when Path.IsRooted(value) is true: + // 1- C:\folder\file + // 2- \\share\folder\file + // 3- \folder\file + // In the first two cases, we want to honor the fully qualified path + // In the last case, we want to return X:\folder\file with X: drive where config file is located. + // However, Path.Combine(path1, path2) always returns path2 when Path.IsRooted(path2) == true (which is current case) + var root = Path.GetPathRoot(value); + // this corresponds to 3rd case + if (root != null && root.Length == 1 && (root[0] == Path.DirectorySeparatorChar || value[0] == Path.AltDirectorySeparatorChar)) + { + return Path.Combine(Path.GetPathRoot(configDirectory), value.Substring(1)); + } + return Path.Combine(configDirectory, value); + } + + /// + /// Wrap all IO operations on setting files with this function to avoid file-in-use errors + /// + private void ExecuteSynchronized(Action ioOperation) + { + var configFilePath = ConfigFilePath; + + // Global: ensure mutex is honored across TS sessions + using (var mutex = new Mutex(false, "Global\\" + EncryptionUtility.GenerateUniqueToken(configFilePath))) + { + var owner = false; + try + { + // operations on NuGet.config should be very short lived + owner = mutex.WaitOne(TimeSpan.FromMinutes(1)); + // decision here is to proceed even if we were not able to get mutex ownership + // and let the potential IO errors bubble up. Reasoning is that failure to get + // ownership probably means faulty hardware and in this case it's better to report + // back than hang + ioOperation(); + } + finally + { + if (owner) + { + mutex.ReleaseMutex(); + } + } + } + } + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +``String XmlUtility.GetOptionalAttributeValue(XElement,String,String)`` could be null (from the call to `XmlUtility.GetOptionalAttributeValue(...)` on line 186) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +XElement Settings.FindElementByKey(XElement,String,XElement) + +### File: +src/NuGet.Configuration/Settings/Settings.cs + +### Key: +Settings.cs|FindElementByKey|NULLPTR_DEREFERENCE + +### Hash: +349a073fa4d6d83c657b814434508900 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2061/instruction.md b/inferredbugs-2061/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09630a312cc38533651ea932695968457d78ff49 --- /dev/null +++ b/inferredbugs-2061/instruction.md @@ -0,0 +1,163 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** pvc +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PvcCore +{ + public static class PvcUtil + { + public static PvcStream StringToStream(string data, string streamName) + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream); + + writer.Write(data); + writer.Flush(); + + return new PvcStream(stream).As(streamName); + } + + public static string StreamToTempFile(PvcStream stream) + { + // be sure to start from beginning + stream.Position = 0; + + var tmpFileName = Path.GetTempFileName(); + File.WriteAllText(tmpFileName, new StreamReader(stream).ReadToEnd()); + + return tmpFileName; + } + + public static Tuple StreamProcessExecution(string processPath, string workingDirectory, params string[] args) + { + var startInfo = new ProcessStartInfo(processPath, string.Join(" ", args)); + startInfo.UseShellExecute = false; + startInfo.CreateNoWindow = true; + startInfo.ErrorDialog = false; + startInfo.WorkingDirectory = workingDirectory; + startInfo.RedirectStandardError = true; + startInfo.RedirectStandardOutput = true; + + var process = Process.Start(startInfo); + return new Tuple(process.StandardOutput.BaseStream, process.StandardError.BaseStream); + } + + public static string PathRelativeToCurrentDirectory(string absolutePath) + { + string currentDir = Environment.CurrentDirectory; + DirectoryInfo directory = new DirectoryInfo(currentDir); + FileInfo file = new FileInfo(absolutePath); + + string fullDirectory = directory.FullName; + string fullFile = file.FullName; + + if (fullFile.StartsWith(fullDirectory)) + { + // The +1 is to avoid the directory separator + return fullFile.Substring(fullDirectory.Length + 1); + } + + // could not generate a relative path, let the abs path through? + return absolutePath; + } + + public static string FindBinaryInPath(params string[] binaries) + { + var searchBinaries = new List(); + foreach (var binary in binaries) + { + if (File.Exists(binary)) + return Path.GetFullPath(binary); + + if (Path.GetDirectoryName(binary) == string.Empty) + searchBinaries.Add(binary); + } + + var searchDirectories = (Environment.GetEnvironmentVariable("PATH") ?? "").Split(';'); + + // Add chocolatey bin (in case the users PATH is busted) + searchDirectories.Concat(new[] { Path.Combine(Environment.GetEnvironmentVariable("ChocolateyInstall"), "bin") }); + + foreach (string test in searchDirectories) + { + string path = test.Trim(); + + foreach (var searchBinary in searchBinaries) + { + var binary = Environment.ExpandEnvironmentVariables(searchBinary); + var binaryRelPath = Path.Combine(path, binary); + if (!String.IsNullOrEmpty(path) && File.Exists(binaryRelPath)) + return Path.GetFullPath(binaryRelPath); + } + } + + if (binaries.Length == 1) + throw new FileNotFoundException("Unable to find requested binary in PATH: " + binaries[0]); + else + throw new FileNotFoundException("Unable to find any of the requested binaries in PATH: " + string.Join(", ", binaries)); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource writer of type System.IO.StreamWriter, Leaked resource stream of type System.IO.MemoryStream, Leaked resource (output of PvcCore.PvcStream::.ctor() at Line 21) of type PvcCore.PvcStream in method "PvcStream PvcUtil.StringToStream(String,String)". + +### Severity: +ERROR + +### Procedure: +PvcStream PvcUtil.StringToStream(String,String) + +### File: +Pvc.Core/PvcUtil.cs + +### Key: +PvcUtil.cs|StringToStream|DOTNET_RESOURCE_LEAK + +### Hash: +79a61a2f359a0920faa23500f5b7a4a6 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2066/instruction.md b/inferredbugs-2066/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51be42b1bcc7390dde25d61b8a9b2d0ce42f49f4 --- /dev/null +++ b/inferredbugs-2066/instruction.md @@ -0,0 +1,243 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** exceltk +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; + +#if OS_WINDOWS +using Exceltk.Clipborad; +using System.Runtime.InteropServices; +using System.Windows.Forms; +#endif + +using Exceltk.Util; + +namespace Exceltk { + internal class Program { + + #if OS_WINDOWS + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool AllocConsole(); + + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool FreeConsole(); + + [DllImport("kernel32", SetLastError = true)] + static extern bool AttachConsole(int dwProcessId); + #endif + + [STAThread] + private static void Main(string[] args) { + var cmd=new CommandParser(args); + var r = InitConfig(cmd); + if (r) { + Xls2MarkDown(cmd); + } + } + + private static bool InitConfig(CommandParser cmd) { + // default + Config.DecimalPrecision = 0; + if (cmd["t"]!=null){ + if (cmd["t"] == "md"){ + if (cmd["bhead"]!=null) { + Config.BodyHead = true; + } else { + Config.BodyHead = false; + } + + if (cmd["p"]!=null) { + int precision = 0; + var ret = Int32.TryParse(cmd["p"],out precision); + if (ret) { + if (precision > 10) { + Console.WriteLine("presision too larger:" + precision); + return false; + } + if (precision > 0) { + Config.DecimalPrecision = precision; + } + } + + } + } + + if (cmd["t"] == "tex") { + if (cmd["sn"] != null) { + Config.SplitNumber = true; + } else { + Config.SplitNumber = false; + } + + if (cmd["st"] != null) { + Config.SplitTable = true; + int rows = 0; + bool ret = Int32.TryParse(cmd["st"], out rows); + if (ret) { + Config.SplitTableRow = rows; + } else { + Config.SplitTable = false; + } + } else { + Config.SplitTable = false; + } + } + } + return true; + } + + private static void Xls2MarkDown(CommandParser cmd) { + int ret=1; + #if OS_WINDOWS + var allocConsole = false; + #endif + do { + // check target + if (cmd["t"]==null) { + Console.WriteLine("ERROR:target not found"); + break; + } + + // run gui + if (cmd["t"] == "cm") { + #if OS_WINDOWS + Application.Run(new ClipboradMonitor()); + #endif + ret = 0; + break; + } + + // run console + #if OS_WINDOWS + if (!AttachConsole(-1)) { + AllocConsole(); + allocConsole = true; + } + #endif + + // check xls arg + if (cmd["xls"] == null) { + Console.WriteLine("ERROR:xls not found"); + break; + } + + // check xls exist + string xls = cmd["xls"]; + string sheet = cmd["sheet"]; + string root = Directory.GetCurrentDirectory(); + xls = Path.Combine(root, xls); + if (!File.Exists(xls)) { + Console.WriteLine("ERROR:xls file is not exist:{0}", xls); + break; + } + + // check xls path + string dirName = Path.GetDirectoryName(xls); + string fileName = Path.GetFileNameWithoutExtension(xls); + if(dirName==null||fileName==null){ + Console.WriteLine("ERROR: xls path is valid:{0}",xls); + break; + } + + // check md or json target + var target = cmd["t"]; + if(target!="md"&&target!="json"&&target!="tex"){ + Console.WriteLine("ERROR: target not support",target); + break; + } + + // output + var output=Path.Combine(dirName, fileName); + if (sheet!=null) { + var table=xls.ToSimpleTable(sheet, target); + string tableFile=output+table.Name+"."+ target; + File.WriteAllText(tableFile, table.Value); + Console.WriteLine("Output File: {0}", tableFile); + } else { + var tables=xls.ToSimpleTable(target); + foreach (var table in tables) { + string tableFile=output+table.Name+"."+ target; + File.WriteAllText(tableFile, table.Value); + Console.WriteLine("Output File: {0}", tableFile); + } + } + ret=0; + Console.WriteLine("Done!"); + + + } while (false); + + if (ret!=0) { + Console.WriteLine(); + Console.WriteLine("Usecase:"); + Console.WriteLine("1. Convert xls to markdown: Exceltk -t md -xls xlsfile [-sheet sheetname]"); + Console.WriteLine("2. Monitor and convert clipboard to markdown: Exceltk -t cm"); + } + + #if OS_WINDOWS + SendKeys.SendWait("{ENTER}"); + if (allocConsole) { + FreeConsole(); + } + + System.Environment.Exit(0); + #endif + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Exceltk.Clipborad.ClipboradMonitor::.ctor() at Line 102) of type System.Windows.Forms.Form in method "Void Program.Xls2MarkDown(CommandParser)". + +### Severity: +ERROR + +### Procedure: +Void Program.Xls2MarkDown(CommandParser) + +### File: +src/Exceltk/Program.cs + +### Key: +Program.cs|Xls2MarkDown|DOTNET_RESOURCE_LEAK + +### Hash: +516aa706f6a4989520e2a1f44354b052 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2067/instruction.md b/inferredbugs-2067/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..85bcdf7299514dff542574a876f323272ef484a1 --- /dev/null +++ b/inferredbugs-2067/instruction.md @@ -0,0 +1,192 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** exceltk +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; + +#if OS_WINDOWS +using exceltk.Clipborad; +using System.Runtime.InteropServices; +using System.Windows.Forms; +#endif + +namespace ExcelToolKit { + internal class Program { + + #if OS_WINDOWS + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool AllocConsole(); + + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool FreeConsole(); + + [DllImport("kernel32", SetLastError = true)] + static extern bool AttachConsole(int dwProcessId); + #endif + + [STAThread] + private static void Main(string[] args) { + var cmd=new CommandParser(args); + var r = InitConfig(cmd); + if (r) { + Xls2MarkDown(cmd); + } + } + + private static bool InitConfig(CommandParser cmd) { + // default + Config.DecimalPrecision = 0; + if (cmd["t"]!=null){ + if (cmd["t"] == "md"){ + if (cmd["p"]!=null) { + int precision = 0; + Int32.TryParse(cmd["p"],out precision); + if (precision > 10) { + Console.WriteLine("presision too larger:"+precision); + return false; + } + if(precision>0){ + Config.DecimalPrecision=precision; + } + } + } + } + return true; + } + + private static void Xls2MarkDown(CommandParser cmd) { + int ret=1; + #if OS_WINDOWS + var allocConsole = false; + #endif + do { + if (cmd["t"]!=null) { + if (cmd["t"] == "md") { + #if OS_WINDOWS + if (!AttachConsole(-1)) { + AllocConsole(); + allocConsole = true; + } + #endif + + if (cmd["xls"] == null) { + break; + } + + string xls = cmd["xls"]; + string sheet = cmd["sheet"]; + string dirName = Path.GetDirectoryName(xls); + string fileName = Path.GetFileNameWithoutExtension(xls); + if(dirName!=null&&fileName!=null){ + string output=Path.Combine(dirName, fileName); + + if (!File.Exists(xls)) { + Console.WriteLine("xls file is not exist:{0}", xls); + break; + } + + if (sheet!=null) { + MarkDownTable table=xls.ToMd(sheet); + string tableFile=output+table.Name+".md"; + File.WriteAllText(tableFile, table.Value); + Console.WriteLine("Output File: {0}", tableFile); + } else { + IEnumerable tables=xls.ToMd(); + foreach (MarkDownTable table in tables) { + string tableFile=output+table.Name+".md"; + File.WriteAllText(tableFile, table.Value); + Console.WriteLine("Output File: {0}", tableFile); + } + } + ret=0; + Console.WriteLine("Done!"); + }else{ + Console.WriteLine("ERROR: xls path is valid:{0}",xls); + } + + } else if (cmd["t"] == "cm") { + #if OS_WINDOWS + Application.Run(new ClipboradMonitor()); + #endif + ret = 0; + } else { + // Ignore + } + } + + } while (false); + + if (ret!=0) { + Console.WriteLine(); + Console.WriteLine("Usecase:"); + Console.WriteLine("1. Convert xls to markdown: exceltk -t md -xls xlsfile [-sheet sheetname]"); + Console.WriteLine("2. Monitor and convert clipboard to markdown: exceltk -t cm"); + } + + #if OS_WINDOWS + SendKeys.SendWait("{ENTER}"); + if (allocConsole) { + FreeConsole(); + } + + System.Environment.Exit(0); + #endif + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of exceltk.Clipborad.ClipboradMonitor::.ctor() at Line 107) of type System.Windows.Forms.Form in method "Void Program.Xls2MarkDown(CommandParser)". + +### Severity: +ERROR + +### Procedure: +Void Program.Xls2MarkDown(CommandParser) + +### File: +src/Exceltk/Program.cs + +### Key: +Program.cs|Xls2MarkDown|DOTNET_RESOURCE_LEAK + +### Hash: +04604b28e0e6f8dc469dc111f0eac915 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2068/instruction.md b/inferredbugs-2068/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5ed53d4d84908e6a03cfaa93c0784bea171987cf --- /dev/null +++ b/inferredbugs-2068/instruction.md @@ -0,0 +1,559 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** PowerArgs +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; + +namespace PowerArgs +{ + /// + /// An exception that will be thrown if there was an error while tokenizing a string. + /// + public class TokenizerException : Exception + { + /// + /// Creates a new tokenizer exception given a message + /// + /// The exception message + public TokenizerException(string message) : base(message) { } + } + + /// + /// A base token class that represents a substring from a document. The location in the source + /// document is tracked along with the substring so that code that processes the token can indicate + /// where problems are to the user who supplied the document if needed. + /// + public class Token + { + /// + /// Gets the value of the token + /// + public string Value { get; internal set; } + + /// + /// Gets the zero based start index of this token in the document + /// + public int StartIndex { get; private set; } + + /// + /// Gets a string that represents the source file of this document. It does not need to be a file name, but it usually is. + /// + public string SourceFileLocation { get; set; } + + /// + /// Gets the end index of the token in the document + /// + public int EndIndex + { + get + { + return StartIndex + Value.Length; + } + } + + /// + /// Gets the 1 based line number of the token in the document + /// + public int Line { get; private set; } + + /// + /// Gets the 1 based index of the token within it's line + /// + public int Column { get; private set; } + + internal List ExplicitNonDelimiterCharacters { get; private set; } + + /// + /// Gets a string that represents the position of this token in the source document. + /// + public string Position + { + get + { + return string.Format("Line '{0}', column '{1}', source '{2}'", Line, Column, SourceFileLocation); + } + + } + + /// + /// Creates a token given an initial value, a start index, a line number, and a column number + /// + /// The initial value of a token. You can append to the token later + /// the zero based start index of this token in the document + /// the 1 based line number of the token in the document + /// the 1 based index of the token within it's line + public Token(string initialValue, int startIndex, int line, int col) + { + if (startIndex < 0) + { + throw new ArgumentException("token startIndex cannot be 0"); + } + + ExplicitNonDelimiterCharacters = new List(); + Value = initialValue; + StartIndex = startIndex; + Line = line; + Column = col; + } + + internal void SetLastCharacterAsExplicitNonDelimiter() + { + if(this.Value.Length == 0) + { + throw new InvalidOperationException("This token has no value"); + } + ExplicitNonDelimiterCharacters.Add(this.Value.Length - 1); + } + + internal bool EndsWithDelimiter(string delimiter) + { + if(this.Value.EndsWith(delimiter) == false) + { + return false; + } + + var firstTokenValue = this.Value.Substring(0, this.Value.Length - delimiter.Length); + + for(var i = firstTokenValue.Length; i < this.Value.Length; i++) + { + if(ExplicitNonDelimiterCharacters.Contains(i)) + { + return false; // TODO - P0 - no code coverage for this case + } + } + + return true; + } + + /// + /// Gets a string representation of the token, along with position info + /// + /// a string representation of the token, along with position info + public override string ToString() + { + return "---> '" + Value + "'<--- - " + Position; + } + + /// + /// Creates a new instance of the strongly typed token and copies all of the base token's properties to the new value + /// + /// The type of the derived token. + /// The strongly typed token + public T As() where T : Token + { + var ret = (T)Activator.CreateInstance(typeof(T), this.Value, this.StartIndex, this.Line, this.Column); + ret.SourceFileLocation = this.SourceFileLocation; + return ret; + } + } + + /// + /// An enum describing the different ways the tokenizer can handle whitespace + /// + public enum WhitespaceBehavior + { + /// + /// Treats whitespace as a delimiter and includes the whitespace tokens in the output list of tokens + /// + DelimitAndInclude, + /// + /// Treats whitespace as a delimiter, but excludes the whitespace tokens from the output list of tokens + /// + DelimitAndExclude, + /// + /// Includes whitespace in the output and does not treat it as a delimiter + /// + Include, + } + + /// + /// An enum describing the different ways the tokenizer can handle double quotes + /// + public enum DoubleQuoteBehavior + { + /// + /// No special handling. Double quotes will be treated like any normal character. You can include the double quote in the delimiters list. + /// + NoSpecialHandling, + /// + /// Treat values within double quotes as string literals. + /// + IncludeQuotedTokensAsStringLiterals, + } + + /// + /// A general purpose string tokenizer + /// + /// The type of tokens that this tokenizer should output + public class Tokenizer where T : Token + { + /// + /// strings to treat as delimiters. Delimiters with longer lengths will take preference over + /// those with shorter lengths. For example if you add delimiters '{{' and '{' and the document + /// contains '{{Hello' then you'll get 2 tokens, first '{{', then 'hello' + /// + public List Delimiters { get; private set; } + + /// + /// A function that given a plain token can transform it into the strongly typed token + /// + public Func, T> TokenFactory { get; set; } + + /// + /// Gets or sets the option that describes how whitespace should be treated. + /// + public WhitespaceBehavior WhitespaceBehavior { get; set; } + + /// + /// Gets or sets the option that describes how double quotes should be treated. + /// + public DoubleQuoteBehavior DoubleQuoteBehavior { get; set; } + + /// + /// An escape sequence identifier. By default it is '\' + /// + public char? EscapeSequenceIndicator { get; set; } + + /// + /// A string that describes the source location for the given document + /// + public string SourceFileLocation { get; set; } + + private bool insideStringLiteral = false; + + /// + /// Creates a new tokenizer + /// + public Tokenizer() + { + this.Delimiters = new List(); + this.SourceFileLocation = "Not source location specified"; + if (typeof(T) == typeof(Token)) + { + this.TokenFactory = (token, previousTokens) => (T)token; + } + else + { + this.TokenFactory = (token, previousTokens) => token.As(); + } + + this.EscapeSequenceIndicator = '\\'; + } + + /// + /// Tokenizes the given string into a list of tokens + /// + /// The string to tokenize + /// The list of tokens + public List Tokenize(string input) + { + List tokens = new List(); + Token currentToken = null; + + insideStringLiteral = false; + + char currentCharacter; + char? nextCharacter; + int currentIndex = -1; + int currentLine = 1; + int currentColumn = 0; + while (TryReadCharacter(input, ref currentIndex, out currentCharacter)) + { + char peeked; + if(TryPeekCharacter(input, currentIndex, out peeked)) + { + nextCharacter = peeked; + } + else + { + nextCharacter = null; + } + + currentColumn++; + if(currentCharacter == '\n') + { + Tokenize_Whitespace(input, ref currentIndex, ref currentCharacter, ref currentLine, ref currentColumn, ref currentToken, tokens); + currentLine++; + currentColumn = 0; + } + else if (IsEscapeSequence(currentCharacter, nextCharacter)) + { + Tokenize_EscapeCharacter(input, ref currentIndex, ref currentCharacter, ref currentLine, ref currentColumn, ref currentToken, tokens); + } + else if(insideStringLiteral) + { + Tokenize_Plain(input, ref currentIndex, ref currentCharacter, ref currentLine, ref currentColumn, ref currentToken, tokens); + } + else if (Delimiters.Contains("" + currentCharacter)) + { + Tokenize_DelimiterCharacter(input, ref currentIndex, ref currentCharacter, ref currentLine, ref currentColumn, ref currentToken, tokens); + } + else if (char.IsWhiteSpace(currentCharacter)) + { + Tokenize_Whitespace(input, ref currentIndex, ref currentCharacter, ref currentLine, ref currentColumn, ref currentToken, tokens); + } + else + { + Tokenize_Plain(input, ref currentIndex, ref currentCharacter, ref currentLine, ref currentColumn, ref currentToken, tokens); + } + } + + FinalizeTokenIfNotNull(ref currentToken, tokens); + + return tokens; + } + + private bool IsEscapeSequence(char current, char? next) + { + if (EscapeSequenceIndicator.HasValue == false || current != EscapeSequenceIndicator.Value) + { + return false; + } + else if (next.HasValue == false) + { + return false; + } + else if(DoubleQuoteBehavior == PowerArgs.DoubleQuoteBehavior.IncludeQuotedTokensAsStringLiterals && next.Value == '"') + { + return true; + } + else if (Delimiters.Count > 0 && Delimiters.Contains(next.Value + "")) + { + return true; + } + else + { + return false; + } + } + + private void Tokenize_EscapeCharacter(string input, ref int currentIndex, ref char currentCharacter, ref int line, ref int col, ref Token currentToken, List tokens) + { + char nextCharacter; + if (TryReadCharacter(input, ref currentIndex, out nextCharacter) == false) + { + throw new TokenizerException("Expected character after escape indicator at end of string"); + } + else + { + AppendToTokenSafe(ref currentToken, nextCharacter, currentIndex, line, col); + currentToken.SetLastCharacterAsExplicitNonDelimiter(); + } + } + + private static string[] Empty = new string[0]; + private void Tokenize_Plain(string input, ref int currentIndex, ref char currentCharacter, ref int line, ref int col, ref Token currentToken, List tokens) + { + if (currentCharacter == '"' && DoubleQuoteBehavior != PowerArgs.DoubleQuoteBehavior.NoSpecialHandling) + { + if(DoubleQuoteBehavior == PowerArgs.DoubleQuoteBehavior.IncludeQuotedTokensAsStringLiterals) + { + if (insideStringLiteral == false) + { + FinalizeTokenIfNotNull(ref currentToken, tokens); + AppendToTokenSafe(ref currentToken, currentCharacter, currentIndex, line, col); + insideStringLiteral = true; + } + else + { + AppendToTokenSafe(ref currentToken, currentCharacter, currentIndex, line, col); + FinalizeTokenIfNotNull(ref currentToken, tokens); + insideStringLiteral = false; + } + } + else + { + throw new TokenizerException("Unknown double quote option: " + DoubleQuoteBehavior); + } + } + else + { + AppendToTokenSafe(ref currentToken, currentCharacter, currentIndex, line, col); + + if (insideStringLiteral == false) + { + var t = currentToken; + + var delimiterMatch = Delimiters.Count == 0 ? Empty : (from d in Delimiters where t.EndsWithDelimiter(d) select d).OrderByDescending(d => d.Length).ToArray(); + + if (Delimiters.Count == 0 || delimiterMatch.None()) + { + // do nothing + } + else + { + if (Delimiters.Contains(currentToken.Value)) + { + FinalizeTokenIfNotNull(ref currentToken, tokens); + } + else + { + var delimiter = delimiterMatch.First(); + currentToken.Value = currentToken.Value.Substring(0, currentToken.Value.Length - delimiter.Length); + var prevToken = currentToken; + FinalizeTokenIfNotNull(ref currentToken, tokens); + currentToken = CreateTokenForTokenizer(delimiter, prevToken.StartIndex + prevToken.Value.Length, prevToken.Line, prevToken.Column + prevToken.Value.Length); + FinalizeTokenIfNotNull(ref currentToken, tokens); + } + } + } + } + } + + private void Tokenize_DelimiterCharacter(string input, ref int currentIndex, ref char currentCharacter, ref int line, ref int col, ref Token currentToken, List tokens) + { + FinalizeTokenIfNotNull(ref currentToken, tokens); + currentToken = CreateTokenForTokenizer(currentCharacter,currentIndex, line, col); + FinalizeTokenIfNotNull(ref currentToken, tokens); + } + + private void Tokenize_Whitespace(string input, ref int currentIndex, ref char currentCharacter, ref int line, ref int col, ref Token currentToken, List tokens) + { + if (WhitespaceBehavior == WhitespaceBehavior.DelimitAndExclude) + { + FinalizeTokenIfNotNull(ref currentToken, tokens); + } + else if (WhitespaceBehavior == WhitespaceBehavior.DelimitAndInclude) + { + FinalizeTokenIfNotNull(ref currentToken, tokens); + currentToken = CreateTokenForTokenizer(currentCharacter, currentIndex, line, col); + FinalizeTokenIfNotNull(ref currentToken, tokens); + } + else if (WhitespaceBehavior == WhitespaceBehavior.Include) + { + AppendToTokenSafe(ref currentToken, currentCharacter, currentIndex, line, col); + } + else + { + throw new TokenizerException("Unknown whitespace behavior: " + WhitespaceBehavior); + } + } + + private void FinalizeTokenIfNotNull(ref Token currentToken, List tokens) + { + if (currentToken != null) + { + tokens.Add(TokenFactoryImpl(currentToken, tokens)); + } + + currentToken = null; + } + + protected virtual T TokenFactoryImpl(Token current, List tokens) + { + return TokenFactory(current, tokens); + } + + private void AppendToTokenSafe(ref Token currentToken, char toAppend, int startIndex, int line, int col) + { + if (currentToken == null) + { + currentToken = CreateTokenForTokenizer(toAppend, startIndex, line, col); + currentToken.SourceFileLocation = this.SourceFileLocation; + } + else + { + currentToken.Value += toAppend; + } + } + + private static bool TryReadCharacter(string input, ref int index, out char toRead) + { + index++; + if (index >= input.Length) + { + toRead = default(char); + return false; + } + else + { + toRead = input[index]; + return true; + } + } + + private static bool TryPeekCharacter(string input, int index, out char toRead) + { + var peekIndex = index + 1; + if (peekIndex >= input.Length) + { + toRead = default(char); + return false; + } + else + { + toRead = input[peekIndex]; + return true; + } + } + + private Token CreateTokenForTokenizer(string currentCharacter, int currentIndex, int line, int col) + { + var ret = new Token(currentCharacter, currentIndex, line, col); + ret.SourceFileLocation = this.SourceFileLocation; + return ret; + } + + private Token CreateTokenForTokenizer(char currentCharacter,int currentIndex, int line, int col) + { + return CreateTokenForTokenizer(currentCharacter + "", currentIndex, line, col); + } + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +The call to `Void Tokenizer`1.Tokenize_DelimiterCharacter(String,Int32&,Char&,Int32&,Int32&,Token&,List`1)` may trigger the following issue: `currentToken` could be null (from the call to `Tokenizer`1` on line 403) and is dereferenced in call to `Tokenizer`1`. + +### Severity: +ERROR + +### Procedure: +List`1 Tokenizer`1.Tokenize(String) + +### File: +PowerArgs/Templating/Tokenizer.cs + +### Key: +Tokenizer.cs|Tokenize|NULLPTR_DEREFERENCE + +### Hash: +8f37ff86962c1e7fc1fc4db353d700f0 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2069/instruction.md b/inferredbugs-2069/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4d2dc5098ddc936b7320178eec99c986e4b175a0 --- /dev/null +++ b/inferredbugs-2069/instruction.md @@ -0,0 +1,346 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** PowerArgs +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp + +using System; +using System.ComponentModel; +using System.Threading.Tasks; + +namespace PowerArgs.Cli +{ + // todos before fully supporting the .Cli namespace + // + // Command bar + // Notifications + // Pull out view model concepts + // Samples for different data sources (e.g. An azure table, a file system) + // Lots of testing + // Final code review and documentation + + /// + /// A class representing a console application that uses a message pump to synchronize work on a UI thread + /// + public class ConsoleApp : Lifetime + { + [ThreadStatic] + private static ConsoleApp _current; + + /// + /// Gets a reference to the current app running on this thread. This will only be populated by the thread + /// that is running the message pump (i.e. it will never be your main thread). + /// + public static ConsoleApp Current + { + get + { + return _current; + } + } + + /// + /// An event that fires when a control is added to the visual tree + /// + public event Action ControlAdded; + + /// + /// An event that fires when a control is removed from the visual tree + /// + public event Action ControlRemoved; + + /// + /// An event that fired when the application stops, after the message pump is no longer running, and the console + /// has been cleared of the app's visuals + /// + public event Action ApplicationStopped; + + /// + /// Gets the bitmap that will be painted to the console + /// + public ConsoleBitmap Bitmap { get; private set; } + + /// + /// Gets the root panel that contains the controls being used by the app + /// + public ConsolePanel LayoutRoot { get; private set; } + + /// + /// Gets the message pump that is used to synchronize work + /// + public CliMessagePump MessagePump { get; private set; } + + /// + /// Gets the focus manager used to manage input focus + /// + public FocusManager FocusManager { get; private set; } + + public bool AutoFillOnConsoleResize { get; set; } + + /// + /// Gets or sets the theme + /// + public Theme Theme { get; set; } + + /// + /// Gets or set whether or not to give focus to a control when the app starts. The default is true. + /// + public bool SetFocusOnStart { get; set; } + + /// + /// Creates a new console app given a set of boundaries + /// + /// The left position on the target console to bound this app + /// The right position on the target console to bound this app + /// The width of the app + /// The height of the app + public ConsoleApp(int x, int y, int w, int h) + { + SetFocusOnStart = true; + Theme = new Theme(); + Bitmap = new ConsoleBitmap(x, y, w, h); + MessagePump = new CliMessagePump(Bitmap.Console, KeyPressed); + LayoutRoot = new ConsolePanel { Width = w, Height = h }; + FocusManager = new FocusManager(); + LayoutRoot.Application = this; + AutoFillOnConsoleResize = false; + FocusManager.SubscribeForLifetime(nameof(FocusManager.FocusedControl), Paint, LifetimeManager); + LayoutRoot.Controls.BeforeAdded.SubscribeForLifetime((c) => { c.Application = this; c.BeforeAddedToVisualTreeInternal(); }, LifetimeManager); + LayoutRoot.Controls.BeforeRemoved.SubscribeForLifetime((c) => { c.BeforeRemovedFromVisualTreeInternal(); }, LifetimeManager); + LayoutRoot.Controls.Added.SubscribeForLifetime(ControlAddedToVisualTree, LifetimeManager); + LayoutRoot.Controls.Removed.SubscribeForLifetime(ControlRemovedFromVisualTree, LifetimeManager); + MessagePump.WindowResized += HandleDebouncedResize; + } + + /// + /// Creates a full screen console app + /// + public ConsoleApp() : this(0,0,ConsoleProvider.Current.BufferWidth, ConsoleProvider.Current.WindowHeight-1) + { + this.AutoFillOnConsoleResize = true; + } + + /// + /// Starts the app, asynchronously. + /// + /// A task that will complete when the app exits + public Task Start() + { + Task pumpTask = MessagePump.Start(); + var ret = pumpTask.ContinueWith((t) => + { + ExitInternal(); + }); + + if (SetFocusOnStart) + { + MessagePump.QueueAction(() => { FocusManager.TryMoveFocus(); }); + } + + MessagePump.QueueAction(() => + { + if (_current != null) + { + throw new NotSupportedException("An application is already running on this thread."); + } + // ensures that the current app is set on the message pump thread + _current = this; + }); + Paint(); + + return ret; + } + + private void HandleDebouncedResize() + { + if(AutoFillOnConsoleResize) + { + Bitmap.Resize(Bitmap.Console.BufferWidth, Bitmap.Console.WindowHeight - 1); + this.LayoutRoot.Size = new Size(Bitmap.Console.BufferWidth, Bitmap.Console.WindowHeight - 1); + } + + Paint(); + } + + /// + /// Queues up a request to paint the app. The system will dedupe multiple paint requests when there are multiple in the pump's work queue + /// + public void Paint() + { + MessagePump.QueueAction(new PaintMessage(PaintInternal)); + } + + private void ControlAddedToVisualTree(ConsoleControl c) + { + c.Application = this; + + if (c is ConsolePanel) + { + var childPanel = c as ConsolePanel; + childPanel.Controls.SynchronizeForLifetime((cp) => { ControlAddedToVisualTree(cp); }, (cp) => { ControlRemovedFromVisualTree(cp); }, () => { }, c.LifetimeManager); + } + + FocusManager.Add(c); + c.AddedToVisualTreeInternal(); + + if (ControlAdded != null) + { + ControlAdded(c); + } + } + + private void ControlRemovedFromVisualTree(ConsoleControl c) + { + if (ControlRemovedFromVisualTreeRecursive(c)) + { + FocusManager.TryRestoreFocus(); + } + } + + private bool ControlRemovedFromVisualTreeRecursive(ConsoleControl c) + { + bool focusChanged = false; + + if (c is ConsolePanel) + { + foreach (var child in (c as ConsolePanel).Controls) + { + focusChanged = ControlRemovedFromVisualTreeRecursive(child) || focusChanged; + } + } + + if (FocusManager.FocusedControl == c) + { + FocusManager.ClearFocus(); + focusChanged = true; + } + + FocusManager.Remove(c); + + c.RemovedFromVisualTreeInternal(); + c.Application = null; + if (ControlRemoved != null) + { + ControlRemoved(c); + } + c.Dispose(); + return focusChanged; + } + + private void KeyPressed(ConsoleKeyInfo info) + { + if (FocusManager.GlobalKeyHandlers.TryIntercept(info)) + { + // great, it was handled + } + else if (info.Key == ConsoleKey.Tab) + { + FocusManager.TryMoveFocus(info.Modifiers.HasFlag(ConsoleModifiers.Shift) == false); + } + else if (info.Key == ConsoleKey.Escape) + { + MessagePump.Stop(); + return; + } + else if (FocusManager.FocusedControl != null) + { + FocusManager.FocusedControl.HandleKeyInput(info); + } + + Paint(); + } + + private void ExitInternal() + { + using (var snapshot = Bitmap.CreateSnapshot()) + { + Bitmap.CreateWiper().Wipe(); + if (ApplicationStopped != null) + { + ApplicationStopped(); + } + Bitmap.Console.ForegroundColor = ConsoleString.DefaultForegroundColor; + Bitmap.Console.BackgroundColor = ConsoleString.DefaultBackgroundColor; + } + Dispose(); + } + + private void PaintInternal() + { + + Bitmap.Pen = new ConsoleCharacter(' ', null, Theme.BackgroundColor); + Bitmap.FillRect(0, 0, LayoutRoot.Width, LayoutRoot.Height); +#if PROFILING + using (new TimeProfiler("LayoutRoot.Paint")) + { +#endif + LayoutRoot.Paint(Bitmap); +#if PROFILING + } +#endif + +#if PROFILING + using (new TimeProfiler("Bitmap.Paint")) + { +#endif + Bitmap.Paint(); +#if PROFILING + } +#endif + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from PowerArgs.ConsoleWiper PowerArgs.Cli.ConsoleBitmap::CreateWiper() at Line 252) of type PowerArgs.ConsoleWiper in method "Void ConsoleApp.ExitInternal()". + +### Severity: +ERROR + +### Procedure: +Void ConsoleApp.ExitInternal() + +### File: +PowerArgs/CLI/ConsoleApp.cs + +### Key: +ConsoleApp.cs|ExitInternal|DOTNET_RESOURCE_LEAK + +### Hash: +9d75afc4c6668976b78dbdf8ae1a6b48 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2093/instruction.md b/inferredbugs-2093/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8aa5761cf6963df51e7a8284d32b67413f4c10ec --- /dev/null +++ b/inferredbugs-2093/instruction.md @@ -0,0 +1,554 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** RestSharp +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +#region License +// Copyright 2010 John Sheehan +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#endregion + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Xml; +using System.Xml.Linq; +using System.Security.Cryptography.X509Certificates; +using RestSharp.Deserializers; +using RestSharp.Extensions; +using System.Text; +using System.Reflection; + +namespace RestSharp +{ + /// + /// Client to translate RestRequests into Http requests and process response result + /// + public partial class RestClient : IRestClient + { + public IHttpFactory HttpFactory = new SimpleFactory(); + + /// + /// Default constructor that registers default content handlers + /// + public RestClient() + { + ContentHandlers = new Dictionary(); + AcceptTypes = new List(); + DefaultParameters = new List(); + + // register default handlers + AddHandler("application/json", new JsonDeserializer()); + AddHandler("application/xml", new XmlDeserializer()); + AddHandler("text/json", new JsonDeserializer()); + AddHandler("text/x-json", new JsonDeserializer()); + AddHandler("text/javascript", new JsonDeserializer()); + AddHandler("text/xml", new XmlDeserializer()); + AddHandler("*", new XmlDeserializer()); + + // silverlight friendly way to get current version + var assembly = Assembly.GetExecutingAssembly(); + AssemblyName assemblyName = new AssemblyName(assembly.FullName); + var version = assemblyName.Version; + + UserAgent = "RestSharp " + version.ToString(); + FollowRedirects = true; + } + + /// + /// Sets the BaseUrl property for requests made by this client instance + /// + /// + public RestClient(string baseUrl) + : this() + { + BaseUrl = baseUrl; + } + + private IDictionary ContentHandlers { get; set; } + private IList AcceptTypes { get; set; } + + /// + /// Parameters included with every request made with this instance of RestClient + /// If specified in both client and request, the request wins + /// + public IList DefaultParameters { get; private set; } + + /// + /// Add a parameter to use on every request made with this client instance + /// + /// Parameter to add + /// + public void AddDefaultParameter(Parameter p) + { + if (p.Type == ParameterType.RequestBody) + { + throw new NotSupportedException("Cannot set request body from default headers. Use Request.AddBody() instead."); + } + + DefaultParameters.Add(p); + } + + /// + /// Adds a HTTP parameter (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT) + /// Used on every request made by this client instance + /// + /// Name of the parameter + /// Value of the parameter + /// This request + public void AddDefaultParameter(string name, object value) + { + AddDefaultParameter(new Parameter { Name = name, Value = value, Type = ParameterType.GetOrPost }); + } + + /// + /// Adds a parameter to the request. There are four types of parameters: + /// - GetOrPost: Either a QueryString value or encoded form value based on method + /// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection + /// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId} + /// - RequestBody: Used by AddBody() (not recommended to use directly) + /// + /// Name of the parameter + /// Value of the parameter + /// The type of parameter to add + /// This request + public void AddDefaultParameter(string name, object value, ParameterType type) + { + AddDefaultParameter(new Parameter { Name = name, Value = value, Type = type }); + } + + /// + /// Shortcut to AddDefaultParameter(name, value, HttpHeader) overload + /// + /// Name of the header to add + /// Value of the header to add + /// + public void AddDefaultHeader(string name, string value) + { + AddDefaultParameter(name, value, ParameterType.HttpHeader); + } + + /// + /// Shortcut to AddDefaultParameter(name, value, UrlSegment) overload + /// + /// Name of the segment to add + /// Value of the segment to add + /// + public void AddDefaultUrlSegment(string name, string value) + { + AddDefaultParameter(name, value, ParameterType.UrlSegment); + } + + /// + /// Registers a content handler to process response content + /// + /// MIME content type of the response content + /// Deserializer to use to process content + public void AddHandler(string contentType, IDeserializer deserializer) + { + ContentHandlers[contentType] = deserializer; + if (contentType != "*") + { + AcceptTypes.Add(contentType); + } + } + + /// + /// Remove a content handler for the specified MIME content type + /// + /// MIME content type to remove + public void RemoveHandler(string contentType) + { + ContentHandlers.Remove(contentType); + AcceptTypes.Remove(contentType); + } + + /// + /// Remove all content handlers + /// + public void ClearHandlers() + { + ContentHandlers.Clear(); + AcceptTypes.Clear(); + } + + /// + /// Retrieve the handler for the specified MIME content type + /// + /// MIME content type to retrieve + /// IDeserializer instance + IDeserializer GetHandler(string contentType) + { + if (string.IsNullOrEmpty(contentType) && ContentHandlers.ContainsKey("*")) + { + return ContentHandlers["*"]; + } + + var semicolonIndex = contentType.IndexOf(';'); + if (semicolonIndex > -1) contentType = contentType.Substring(0, semicolonIndex); + IDeserializer handler = null; + if (ContentHandlers.ContainsKey(contentType)) + { + handler = ContentHandlers[contentType]; + } + else if (ContentHandlers.ContainsKey("*")) + { + handler = ContentHandlers["*"]; + } + + return handler; + } + + /// + /// Maximum number of redirects to follow if FollowRedirects is true + /// + public int? MaxRedirects { get; set; } + +#if FRAMEWORK + /// + /// X509CertificateCollection to be sent with request + /// + public X509CertificateCollection ClientCertificates { get; set; } +#endif + + /// + /// Default is true. Determine whether or not requests that result in + /// HTTP status codes of 3xx should follow returned redirect + /// + public bool FollowRedirects { get; set; } + + /// + /// UserAgent to use for requests made by this client instance + /// + public string UserAgent { get; set; } + + /// + /// Timeout in milliseconds to use for requests made by this client instance + /// + public int Timeout { get; set; } + + /// + /// Authenticator to use for requests made by this client instance + /// + public IAuthenticator Authenticator { get; set; } + + private string _baseUrl; + /// + /// Combined with Request.Resource to construct URL for request + /// Should include scheme and domain without trailing slash. + /// + /// + /// client.BaseUrl = "http://example.com"; + /// + public string BaseUrl + { + get + { + return _baseUrl; + } + set + { + _baseUrl = value; + if (_baseUrl.EndsWith("/")) + { + _baseUrl = _baseUrl.Substring(0, _baseUrl.Length - 1); + } + } + } + + private void AuthenticateIfNeeded(RestClient client, RestRequest request) + { + if (Authenticator != null) + { + Authenticator.Authenticate(client, request); + } + } + + /// + /// Assembles URL to call based on parameters, method and resource + /// + /// RestRequest to execute + /// Assembled System.Uri + public Uri BuildUri(RestRequest request) + { + var assembled = request.Resource; + var urlParms = request.Parameters.Where(p => p.Type == ParameterType.UrlSegment); + foreach (var p in urlParms) + { + assembled = assembled.Replace("{" + p.Name + "}", p.Value.ToString().UrlEncode()); + } + + if (!string.IsNullOrEmpty(assembled) && assembled.StartsWith("/")) + { + assembled = assembled.Substring(1); + } + + if(!string.IsNullOrEmpty(BaseUrl)) + assembled = string.Format("{0}/{1}", BaseUrl, assembled); + + if (request.Method != Method.POST && request.Method != Method.PUT) + { + // build and attach querystring if this is a get-style request + if (request.Parameters.Any(p => p.Type == ParameterType.GetOrPost)) + { + if (assembled.EndsWith("/")) + { + assembled = assembled.Substring(0, assembled.Length - 1); + } + + var data = EncodeParameters(request); + assembled = string.Format("{0}?{1}", assembled, data); + } + } + + return new Uri(assembled); + } + + private string EncodeParameters(RestRequest request) + { + var querystring = new StringBuilder(); + foreach (var p in request.Parameters.Where(p => p.Type == ParameterType.GetOrPost)) + { + if (querystring.Length > 1) + querystring.Append("&"); + querystring.AppendFormat("{0}={1}", p.Name.UrlEncode(), (p.Value.ToString()).UrlEncode()); + } + + return querystring.ToString(); + } + + private void ConfigureHttp(RestRequest request, IHttp http) + { + // move RestClient.DefaultParameters into Request.Parameters + foreach(var p in DefaultParameters) + { + if(request.Parameters.Any(p2 => p2.Name == p.Name && p2.Type == p.Type)) + { + continue; + } + + request.AddParameter(p); + } + + http.Url = BuildUri(request); + + if(UserAgent.HasValue()) + { + http.UserAgent = UserAgent; + } + + http.Timeout = request.Timeout == 0 ? Timeout : request.Timeout; + +#if !SILVERLIGHT + http.FollowRedirects = FollowRedirects; +#endif +#if FRAMEWORK + if (ClientCertificates != null) + { + http.ClientCertificates = ClientCertificates; + } + + http.MaxRedirects = MaxRedirects; +#endif + + if(request.Credentials != null) + { + http.Credentials = request.Credentials; + } + + var headers = from p in request.Parameters + where p.Type == ParameterType.HttpHeader + select new HttpHeader + { + Name = p.Name, + Value = p.Value.ToString() + }; + + foreach(var header in headers) + { + http.Headers.Add(header); + } + + var cookies = from p in request.Parameters + where p.Type == ParameterType.Cookie + select new HttpCookie + { + Name = p.Name, + Value = p.Value.ToString() + }; + + foreach(var cookie in cookies) + { + http.Cookies.Add(cookie); + } + + var @params = from p in request.Parameters + where p.Type == ParameterType.GetOrPost + && p.Value != null + select new HttpParameter + { + Name = p.Name, + Value = p.Value.ToString() + }; + + foreach(var parameter in @params) + { + http.Parameters.Add(parameter); + } + + foreach(var file in request.Files) + { + http.Files.Add(new HttpFile { Name = file.Name, ContentType = file.ContentType, Writer = file.Writer, FileName = file.FileName, ContentLength = file.ContentLength }); + } + + var body = (from p in request.Parameters + where p.Type == ParameterType.RequestBody + select p).FirstOrDefault(); + + if(body != null) + { + http.RequestBody = body.Value.ToString(); + http.RequestContentType = body.Name; + } + } + + private RestResponse ConvertToRestResponse(HttpResponse httpResponse) + { + var restResponse = new RestResponse(); + restResponse.Content = httpResponse.Content; + restResponse.ContentEncoding = httpResponse.ContentEncoding; + restResponse.ContentLength = httpResponse.ContentLength; + restResponse.ContentType = httpResponse.ContentType; + restResponse.ErrorException = httpResponse.ErrorException; + restResponse.ErrorMessage = httpResponse.ErrorMessage; + restResponse.RawBytes = httpResponse.RawBytes; + restResponse.ResponseStatus = httpResponse.ResponseStatus; + restResponse.ResponseUri = httpResponse.ResponseUri; + restResponse.Server = httpResponse.Server; + restResponse.StatusCode = httpResponse.StatusCode; + restResponse.StatusDescription = httpResponse.StatusDescription; + + foreach (var header in httpResponse.Headers) + { + restResponse.Headers.Add(new Parameter { Name = header.Name, Value = header.Value, Type = ParameterType.HttpHeader }); + } + + foreach (var cookie in httpResponse.Cookies) + { + restResponse.Cookies.Add(new RestResponseCookie { + Comment = cookie.Comment, + CommentUri = cookie.CommentUri, + Discard = cookie.Discard, + Domain = cookie.Domain, + Expired = cookie.Expired, + Expires = cookie.Expires, + HttpOnly = cookie.HttpOnly, + Name = cookie.Name, + Path = cookie.Path, + Port = cookie.Port, + Secure = cookie.Secure, + TimeStamp = cookie.TimeStamp, + Value = cookie.Value, + Version = cookie.Version + }); + } + + return restResponse; + } + + private RestResponse Deserialize(RestRequest request, RestResponse raw) where T : new() + { + request.OnBeforeDeserialization(raw); + + IDeserializer handler = GetHandler(raw.ContentType); + handler.RootElement = request.RootElement; + handler.DateFormat = request.DateFormat; + handler.Namespace = request.XmlNamespace; + + var response = new RestResponse(); + try + { + response = (RestResponse)raw; + response.Data = handler.Deserialize(raw); + } + catch (Exception ex) + { + response.ResponseStatus = ResponseStatus.Error; + response.ErrorMessage = ex.Message; + response.ErrorException = ex; + } + + return response; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `handler` last assigned on line 471 could be null and is dereferenced at line 472, column 4. + +### Severity: +ERROR + +### Procedure: +RestResponse`1 RestClient.Deserialize(RestRequest,RestResponse) + +### File: +RestSharp/RestClient.cs + +### Key: +RestClient.cs|Deserialize|NULL_DEREFERENCE + +### Node Key: +2236178ec05847b99a27c4d3a26e337e + +### Hash: +d8a3d400cddabf0a45f8402573312304 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2095/instruction.md b/inferredbugs-2095/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6b30d6e27c1b50fe9b8b0c91078e3dd43d28c905 --- /dev/null +++ b/inferredbugs-2095/instruction.md @@ -0,0 +1,373 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** RestSharp +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +#region License +// Copyright 2010 John Sheehan +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#endregion + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Xml; +using System.Xml.Linq; +using RestSharp.Deserializers; + +namespace RestSharp +{ + /// + /// Client to translate RestRequests into Http requests and process response result + /// + public partial class RestClient : IRestClient + { + /// + /// Default constructor that registers default content handlers + /// + public RestClient() + { + ContentHandlers = new Dictionary(); + AcceptTypes = new List(); + + // register default handlers + AddHandler("application/json", new JsonDeserializer()); + AddHandler("application/xml", new XmlDeserializer()); + AddHandler("text/json", new JsonDeserializer()); + AddHandler("text/x-json", new JsonDeserializer()); + AddHandler("text/javascript", new JsonDeserializer()); + AddHandler("text/xml", new XmlDeserializer()); + AddHandler("*", new XmlDeserializer()); + + UserAgent = "RestSharp Release 1"; + } + + /// + /// Sets the BaseUrl property for requests made by this client instance + /// + /// + public RestClient(string baseUrl) + : this() + { + BaseUrl = baseUrl; + } + + private IDictionary ContentHandlers { get; set; } + private IList AcceptTypes { get; set; } + + /// + /// Registers a content handler to process response content + /// + /// MIME content type of the response content + /// Deserializer to use to process content + public void AddHandler(string contentType, IDeserializer deserializer) + { + ContentHandlers[contentType] = deserializer; + if (contentType != "*") + { + AcceptTypes.Add(contentType); + } + } + + /// + /// Remove a content handler for the specified MIME content type + /// + /// MIME content type to remove + public void RemoveHandler(string contentType) + { + ContentHandlers.Remove(contentType); + } + + /// + /// Remove all content handlers + /// + public void ClearHandlers() + { + ContentHandlers.Clear(); + AcceptTypes.Clear(); + } + + /// + /// Retrieve the handler for the specified MIME content type + /// + /// MIME content type to retrieve + /// IDeserializer instance + IDeserializer GetHandler(string contentType) + { + var semicolonIndex = contentType.IndexOf(';'); + if (semicolonIndex > -1) contentType = contentType.Substring(0, semicolonIndex); + IDeserializer handler = null; + if (ContentHandlers.ContainsKey(contentType)) + { + handler = ContentHandlers[contentType]; + } + else if (ContentHandlers.ContainsKey("*")) + { + handler = ContentHandlers["*"]; + } + + return handler; + } + + /// + /// UserAgent to use for requests made by this client instance + /// + public string UserAgent { get; set; } + + /// + /// Timeout in milliseconds to use for requests made by this client instance + /// + public int Timeout { get; set; } + + /// + /// Authenticator to use for requests made by this client instance + /// + public IAuthenticator Authenticator { get; set; } + + private string _baseUrl; + /// + /// Combined with Request.Resource to construct URL for request + /// Should include scheme and domain without trailing slash. + /// + /// + /// client.BaseUrl = "http://example.com"; + /// + public string BaseUrl + { + get + { + return _baseUrl; + } + set + { + _baseUrl = value; + if (_baseUrl.EndsWith("/")) + { + _baseUrl = _baseUrl.Substring(0, _baseUrl.Length - 1); + } + } + } + + private void AuthenticateIfNeeded(RestRequest request) + { + if (Authenticator != null) + { + Authenticator.Authenticate(request); + } + } + + /// + /// Assembles URL to call based on parameters, method and resource + /// + /// RestRequest to execute + /// Assembled System.Uri + public Uri BuildUri(RestRequest request) + { + var assembled = request.Resource; + var urlParms = request.Parameters.Where(p => p.Type == ParameterType.UrlSegment); + foreach (var p in urlParms) + { + assembled = assembled.Replace("{" + p.Name + "}", p.Value.ToString()); + } + + if (!string.IsNullOrEmpty(assembled) && assembled.StartsWith("/")) + { + assembled = assembled.Substring(1); + } + + return new Uri(string.Format("{0}/{1}", BaseUrl, assembled)); + } + + private void ConfigureHttp(RestRequest request, IHttp http) + { + http.Url = BuildUri(request); + + if (UserAgent != null) + { + http.UserAgent = UserAgent; + } + + http.Timeout = request.Timeout == 0 ? Timeout : request.Timeout; + + if (request.Credentials != null) + { + http.Credentials = request.Credentials; + } + + var headers = from p in request.Parameters + where p.Type == ParameterType.HttpHeader + select new HttpHeader + { + Name = p.Name, + Value = p.Value.ToString() + }; + + foreach (var header in headers) + { + http.Headers.Add(header); + } + + var cookies = from p in request.Parameters + where p.Type == ParameterType.Cookie + select new HttpCookie + { + Name = p.Name, + Value = p.Value.ToString() + }; + + foreach (var cookie in cookies) + { + http.Cookies.Add(cookie); + } + + var @params = from p in request.Parameters + where p.Type == ParameterType.GetOrPost + && p.Value != null + select new HttpParameter + { + Name = p.Name, + Value = p.Value.ToString() + }; + + foreach (var parameter in @params) + { + http.Parameters.Add(parameter); + } + + foreach (var file in request.Files) + { + http.Files.Add(new HttpFile { ContentType = file.ContentType, Data = file.Data, FileName = file.FileName }); + } + + var body = (from p in request.Parameters + where p.Type == ParameterType.RequestBody + select p).FirstOrDefault(); + + if (body != null) + { + http.RequestBody = body.Value.ToString(); + http.RequestContentType = body.Name; + } + } + + private RestResponse ConvertToRestResponse(HttpResponse httpResponse) + { + var restResponse = new RestResponse(); + restResponse.Content = httpResponse.Content; + restResponse.ContentEncoding = httpResponse.ContentEncoding; + restResponse.ContentLength = httpResponse.ContentLength; + restResponse.ContentType = httpResponse.ContentType; + restResponse.ErrorException = httpResponse.ErrorException; + restResponse.ErrorMessage = httpResponse.ErrorMessage; + restResponse.RawBytes = httpResponse.RawBytes; + restResponse.ResponseStatus = httpResponse.ResponseStatus; + restResponse.ResponseUri = httpResponse.ResponseUri; + restResponse.Server = httpResponse.Server; + restResponse.StatusCode = httpResponse.StatusCode; + restResponse.StatusDescription = httpResponse.StatusDescription; + + foreach (var header in httpResponse.Headers) + { + restResponse.Headers.Add(new Parameter { Name = header.Name, Value = header.Value, Type = ParameterType.HttpHeader }); + } + + foreach (var cookie in httpResponse.Cookies) + { + restResponse.Cookies.Add(new Parameter { Name = cookie.Name, Value = cookie.Value, Type = ParameterType.Cookie }); + } + + return restResponse; + } + + private RestResponse Deserialize(RestRequest request, RestResponse raw) where T : new() + { + IDeserializer handler = GetHandler(raw.ContentType); + handler.RootElement = request.RootElement; + handler.DateFormat = request.DateFormat; + handler.Namespace = request.XmlNamespace; + + var response = new RestResponse(); + try + { + response = (RestResponse)raw; + response.Data = handler.Deserialize(raw); + } + catch (Exception ex) + { + response.ResponseStatus = ResponseStatus.Error; + response.ErrorMessage = ex.Message; + response.ErrorException = ex; + } + + return response; + } + + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`handler` could be null (from the call to `RestClient.GetHandler(...)` on line 292) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +RestResponse`1 RestClient.Deserialize(RestRequest,RestResponse) + +### File: +RestSharp/RestClient.cs + +### Key: +RestClient.cs|Deserialize|NULLPTR_DEREFERENCE + +### Hash: +0d96ca46d75df919bbec6e4dd0f29849 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2207/instruction.md b/inferredbugs-2207/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..406456827bf86ec55d6dabbb2b4dca573fbd2d4e --- /dev/null +++ b/inferredbugs-2207/instruction.md @@ -0,0 +1,249 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** uhttpsharp +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/* + * Copyright (C) 2011 uhttpsharp project - http://github.com/raistlinthewiz/uhttpsharp + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Dynamic; +using System.Globalization; +using System.Net; +using System.Net.Sockets; +using System.Threading.Tasks; +using System.Web.UI; +using uhttpsharp; +using uhttpsharp.Handlers; +using uhttpsharp.Headers; +using uhttpsharp.Listeners; +using uhttpsharp.ModelBinders; +using uhttpsharp.RequestProviders; +using uhttpsharpdemo.Handlers; +using HttpResponse = System.Web.HttpResponse; + +namespace uhttpsharpdemo +{ + internal static class Program + { + private static void Main() + { + log4net.Config.XmlConfigurator.Configure(); + + //var serverCertificate = X509Certificate.CreateFromCertFile(@"TempCert.cer"); + + using (var httpServer = new HttpServer(new HttpRequestProvider())) + { + httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 82))); + //httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 443)), serverCertificate)); + + //httpServer.Use(new SessionHandler(() => DateTime.Now)); + httpServer.Use(new ExceptionHandler()); + httpServer.Use(new ClassRouter(new MySuperHandler())); + httpServer.Use(new TimingHandler()); + + httpServer.Use(new MyHandler()); + httpServer.Use(new HttpRouter().With(string.Empty, new IndexHandler()) + .With("about", new AboutHandler()) + .With("strings", new RestHandler(new StringsRestController(), JsonResponseProvider.Default))); + + httpServer.Use(new FileHandler()); + httpServer.Use(new ErrorHandler()); + httpServer.Use((context, next) => + { + Console.WriteLine("Got Request!"); + return next(); + }); + + httpServer.Start(); + Console.ReadLine(); + } + + } + } + + public class MySuperHandler : IHttpRequestHandler + { + + public MySuperHandler Child + { + get + { + return new MySuperHandler(); + } + } + + public Task Handle(IHttpContext context, Func next) + { + context.Response = uhttpsharp.HttpResponse.CreateWithMessage(HttpResponseCode.Ok, "Hello!", true); + return Task.Factory.GetCompleted(); + } + + + [Indexer] + public Task GetChild(int index) + { + return Task.FromResult(new MySuperHandler()); + } + + } + + class MyModel + { + public int MyProperty + { + get; + set; + } + + public MyModel Model + { + get; + set; + } + } + + internal class MyHandler : IHttpRequestHandler + { + public System.Threading.Tasks.Task Handle(IHttpContext context, Func next) + { + var model = new ModelBinder(new ObjectActivator()).Get(context.Request.QueryString); + + return Task.Factory.GetCompleted(); + } + } + + internal class SessionHandler : IHttpRequestHandler + { + private readonly Func _sessionFactory; + + private static readonly Random RandomGenerator = new Random(); + + private class SessionHolder + { + private readonly TSession _session; + private DateTime _lastAccessTime = DateTime.Now; + + public TSession Session + { + get + { + _lastAccessTime = DateTime.Now; + return _session; + } + } + + public DateTime LastAccessTime + { + get + { + return _lastAccessTime; + } + } + + public SessionHolder(TSession session) + { + _session = session; + } + } + + private readonly ConcurrentDictionary _sessions = new ConcurrentDictionary(); + + public SessionHandler(Func sessionFactory) + { + _sessionFactory = sessionFactory; + } + + public System.Threading.Tasks.Task Handle(IHttpContext context, Func next) + { + + string sessId; + if (!context.Cookies.TryGetByName("SESSID", out sessId)) + { + sessId = RandomGenerator.Next().ToString(CultureInfo.InvariantCulture); + context.Cookies.Upsert("SESSID", sessId); + } + + var session = _sessions.GetOrAdd(sessId, CreateSession); + + context.State.Session = session; + + return next(); + } + private TSession CreateSession(string sessionId) + { + return _sessionFactory(); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from uhttpsharp.HttpResponse uhttpsharp.HttpResponse::CreateWithMessage(uhttpsharp.HttpResponseCode,System.String,System.Boolean,System.String) at Line 91).uhttpsharp.HttpResponse._headerStream of type System.IO.MemoryStream in method "Task MySuperHandler.Handle(IHttpContext,Func`1)". + +### Severity: +ERROR + +### Procedure: +Task MySuperHandler.Handle(IHttpContext,Func`1) + +### File: +uhttpsharp-demo/Program.cs + +### Key: +Program.cs|Handle|DOTNET_RESOURCE_LEAK + +### Hash: +8bd2945ed82fbbb6b2f7237a19d925a2 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2231/instruction.md b/inferredbugs-2231/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..82a82e88928466c99ea6a4990d86c86e9d769c18 --- /dev/null +++ b/inferredbugs-2231/instruction.md @@ -0,0 +1,154 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ILRuntime +**Bug ID:** 5 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using ILRuntime.CLR.TypeSystem; +using ILRuntimeTest.Test; +using ILRuntimeTest.TestFramework; + +namespace ILRuntimeTest.TestBase +{ + public class TestSession + { + ILRuntime.Runtime.Enviorment.AppDomain _app; + private List _testUnitList = new List(); + FileStream fs, fs2; + + public List TestList => _testUnitList; + + static TestSession lastSession; + + public static TestSession LastSession => lastSession; + + public ILRuntime.Runtime.Enviorment.AppDomain Appdomain => _app; + + public void Load(string assemblyPath, bool useRegister) + { + fs = new FileStream(assemblyPath, FileMode.Open, FileAccess.Read); + { + var path = Path.GetDirectoryName(assemblyPath); + var name = Path.GetFileNameWithoutExtension(assemblyPath); + var pdbPath = Path.Combine(path, name) + ".pdb"; + if (!File.Exists(pdbPath)) + { + name = Path.GetFileName(assemblyPath); + pdbPath = Path.Combine(path, name) + ".mdb"; + } + + _app = new ILRuntime.Runtime.Enviorment.AppDomain(useRegister ? ILRuntime.Runtime.ILRuntimeJITFlags.JITImmediately : ILRuntime.Runtime.ILRuntimeJITFlags.None); + _app.DebugService.StartDebugService(56000); + fs2 = new System.IO.FileStream(pdbPath, FileMode.Open); + { + ILRuntime.Mono.Cecil.Cil.ISymbolReaderProvider symbolReaderProvider = null; + if (pdbPath.EndsWith(".pdb")) + { + symbolReaderProvider = new ILRuntime.Mono.Cecil.Pdb.PdbReaderProvider(); + }/* else if (pdbPath.EndsWith (".mdb")) { + symbolReaderProvider = new Mono.Cecil.Mdb.MdbReaderProvider (); + }*/ + + _app.LoadAssembly(fs, fs2, symbolReaderProvider); + } + + ILRuntimeHelper.Init(_app); + ILRuntime.Runtime.Generated.CLRBindings.Initialize(_app); + _app.InitializeBindings(true); + LoadTest(); + } + lastSession = this; + } + + void LoadTest() + { + var types = _app.LoadedTypes.Values.ToList(); + foreach (var type in types) + { + var ilType = type as ILType; + if (ilType == null) + continue; + var methods = ilType.GetMethods(); + foreach (var methodInfo in methods) + { + string fullName = ilType.FullName; + //Console.WriteLine("call the method:{0},return type {1},params count{2}", fullName + "." + methodInfo.Name, methodInfo.ReturnType, methodInfo.GetParameters().Length); + //目前只支持无参数,无返回值测试 + if (methodInfo.ParameterCount == 0 && methodInfo.IsStatic && ((ILRuntime.CLR.Method.ILMethod)methodInfo).Definition.IsPublic) + { + var testUnit = new StaticTestUnit(); + testUnit.Init(_app, fullName, methodInfo.Name); + _testUnitList.Add(testUnit); + } + } + } + } + + public void Dispose() + { + fs?.Close(); + fs2?.Close(); + _app.Dispose(); + _app = null; + _testUnitList.Clear(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource TestBase.TestSession.ILRuntimeTest.TestBase.TestSession.lastSession.ILRuntimeTest.TestBase.TestSession.fs of type System.IO.FileStream, Leaked resource (returned from ILRuntime.Runtime.Debugger.DebugService ILRuntime.Runtime.Enviorment.AppDomain::get_DebugService() at Line 40).ILRuntime.Runtime.Debugger.DebugService.server.ILRuntime.Runtime.Debugger.DebuggerServer.sendStreamForUdp of type System.IO.MemoryStream, Leaked resource (returned from ILRuntime.Runtime.Debugger.DebugService ILRuntime.Runtime.Enviorment.AppDomain::get_DebugService() at Line 40).ILRuntime.Runtime.Debugger.DebugService.server.ILRuntime.Runtime.Debugger.DebuggerServer.sendStream of type System.IO.MemoryStream, Leaked resource (returned from ILRuntime.Runtime.Debugger.DebugService ILRuntime.Runtime.Enviorment.AppDomain::get_DebugService() at Line 40).ILRuntime.Runtime.Debugger.DebugService.server.ILRuntime.Runtime.Debugger.DebuggerServer.bwForUdp of type System.IO.BinaryWriter, Leaked resource (returned from ILRuntime.Runtime.Debugger.DebugService ILRuntime.Runtime.Enviorment.AppDomain::get_DebugService() at Line 40).ILRuntime.Runtime.Debugger.DebugService.server.ILRuntime.Runtime.Debugger.DebuggerServer.bw of type System.IO.BinaryWriter in method "Void TestSession.Load(String,Boolean)". + +### Severity: +ERROR + +### Procedure: +Void TestSession.Load(String,Boolean) + +### File: +ILRuntimeTestBase/TestBase/TestSession.cs + +### Key: +TestSession.cs|Load|DOTNET_RESOURCE_LEAK + +### Hash: +fef0b8857be2542143c91baa0c649604 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2236/instruction.md b/inferredbugs-2236/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1f52a089a1f1261d1591fa75a888ad10c1ed3452 --- /dev/null +++ b/inferredbugs-2236/instruction.md @@ -0,0 +1,163 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** atata +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Text; +using OpenQA.Selenium.Firefox; +using OpenQA.Selenium.Remote; + +namespace Atata +{ + public class ATContext + { + [ThreadStatic] + private static ATContext current; + + public RemoteWebDriver Driver { get; internal set; } + + public ILogManager Log { get; internal set; } + + public string BaseUrl { get; internal set; } + + public UIComponent PageObject { get; internal set; } + + internal List TemporarilyPreservedPageObjectList { get; private set; } + + internal bool IsNavigated { get; set; } + + private DateTime SetUpDateTime { get; set; } + private DateTime CleanExecutionStartDateTime { get; set; } + + public ReadOnlyCollection TemporarilyPreservedPageObjects + { + get { return TemporarilyPreservedPageObjectList.ToReadOnly(); } + } + + public static ATContext Current + { + get { return current; } + private set { current = value; } + } + + public static void SetUp(Func driverFactory = null, ILogManager log = null, string testName = null, string baseUrl = null) + { + if (baseUrl != null && !Uri.IsWellFormedUriString(baseUrl, UriKind.Absolute)) + throw new ArgumentException("Invalid URL format \"{0}\".".FormatWith(baseUrl), "baseUrl"); + + Current = new ATContext + { + TemporarilyPreservedPageObjectList = new List(), + Log = log ?? new LogManager().Use(new DebugLogConsumer()), + BaseUrl = baseUrl, + SetUpDateTime = DateTime.UtcNow + }; + + Current.LogTestStart(testName); + + Current.Log.Start("Init WebDriver"); + Current.Driver = driverFactory != null ? driverFactory() : new FirefoxDriver(); + Current.Log.EndSection(); + + Current.CleanExecutionStartDateTime = DateTime.UtcNow; + } + + private void LogTestStart(string testName) + { + StringBuilder logMessageBuilder = new StringBuilder("Starting test"); + + if (!string.IsNullOrWhiteSpace(testName)) + logMessageBuilder.AppendFormat(": {0}", testName); + + Current.Log.Info(logMessageBuilder.ToString()); + } + + public static void CleanUp() + { + if (Current != null) + { + TimeSpan cleanTestExecutionTime = DateTime.UtcNow - Current.CleanExecutionStartDateTime; + + Current.Log.Start("Clean-up test context"); + + Current.Driver.Quit(); + Current.CleanUpTemporarilyPreservedPageObjectList(); + + if (Current.PageObject != null) + UIComponentResolver.CleanUpPageObject(Current.PageObject); + + Current.Log.EndSection(); + + TimeSpan testExecutionTime = DateTime.UtcNow - Current.SetUpDateTime; + Current.Log.InfoWithExecutionTimeInBrackets("Finished test", testExecutionTime); + Current.Log.InfoWithExecutionTime("Сlean test execution time: ", cleanTestExecutionTime); + + Current.Log = null; + Current = null; + } + } + + internal void CleanUpTemporarilyPreservedPageObjectList() + { + UIComponentResolver.CleanUpPageObjects(TemporarilyPreservedPageObjects); + TemporarilyPreservedPageObjectList.Clear(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of OpenQA.Selenium.Firefox.FirefoxDriver::.ctor() at Line 61) of type OpenQA.Selenium.Firefox.FirefoxDriver in method "Void ATContext.SetUp(Func`1,ILogManager,String,String)". + +### Severity: +ERROR + +### Procedure: +Void ATContext.SetUp(Func`1,ILogManager,String,String) + +### File: +src/Atata/ATContext.cs + +### Key: +ATContext.cs|SetUp|DOTNET_RESOURCE_LEAK + +### Hash: +64fabcd7beee9467ab3b83380ce37b55 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2238/instruction.md b/inferredbugs-2238/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9a46425690bc76bb163152392861f121fa5b7071 --- /dev/null +++ b/inferredbugs-2238/instruction.md @@ -0,0 +1,138 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** atata +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using OpenQA.Selenium.Firefox; +using OpenQA.Selenium.Remote; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Text; + +namespace Atata +{ + public class AtataContext + { + [ThreadStatic] + private static AtataContext current; + + public RemoteWebDriver Driver { get; internal set; } + + public ILogManager Log { get; internal set; } + + public UIComponent PageObject { get; internal set; } + + internal List TemporarilyPreservedPageObjectList { get; private set; } + + public ReadOnlyCollection TemporarilyPreservedPageObjects + { + get { return TemporarilyPreservedPageObjectList.ToReadOnly(); } + } + + public static AtataContext Current + { + get { return current; } + private set { current = value; } + } + + public static void SetUp(Func driverFactory = null, ILogManager log = null, string testName = null) + { + Current = new AtataContext + { + TemporarilyPreservedPageObjectList = new List(), + Log = log ?? new SimpleLogManager() + }; + + Current.LogTestStart(testName); + + Current.Log.StartSection("Init web driver"); + Current.Driver = driverFactory != null ? driverFactory() : new FirefoxDriver(); + Current.Log.EndSection(); + } + + private void LogTestStart(string testName) + { + StringBuilder logMessageBuilder = new StringBuilder("Starting test"); + + if (!string.IsNullOrWhiteSpace(testName)) + logMessageBuilder.AppendFormat(": {0}", testName); + + Current.Log.Info(logMessageBuilder.ToString()); + } + + public static void CleanUp() + { + if (Current != null) + { + Current.Log.Info("Finished test"); + + Current.Log = null; + Current.Driver.Quit(); + Current.CleanUpTemporarilyPreservedPageObjectList(); + UIComponentResolver.CleanUpPageObject(Current.PageObject); + Current = null; + } + } + + internal void CleanUpTemporarilyPreservedPageObjectList() + { + UIComponentResolver.CleanUpPageObjects(TemporarilyPreservedPageObjects); + TemporarilyPreservedPageObjectList.Clear(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of OpenQA.Selenium.Firefox.FirefoxDriver::.ctor() at Line 47) of type OpenQA.Selenium.Firefox.FirefoxDriver in method "Void AtataContext.SetUp(Func`1,ILogManager,String)". + +### Severity: +ERROR + +### Procedure: +Void AtataContext.SetUp(Func`1,ILogManager,String) + +### File: +src/Atata/AtataContext.cs + +### Key: +AtataContext.cs|SetUp|DOTNET_RESOURCE_LEAK + +### Hash: +3ecab92b038de51aa118bff50f1f25e5 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2252/instruction.md b/inferredbugs-2252/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a061c1fd9dbd8c0265f6fb791892161ec92f1fd7 --- /dev/null +++ b/inferredbugs-2252/instruction.md @@ -0,0 +1,301 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** resin +**Bug ID:** 51 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Sir.Documents; +using Sir.VectorSpace; +using System; +using System.Collections.Generic; + +namespace Sir.Search +{ + public class DocumentStreamSession : IDisposable + { + private readonly string _directory; + protected readonly StreamFactory SessionFactory; + private readonly IDictionary _streamReaders; + + public DocumentStreamSession(string directory, StreamFactory sessionFactory) + { + _directory = directory; + SessionFactory = sessionFactory; + _streamReaders = new Dictionary(); + } + + + public int Count(ulong collectionId) + { + return GetOrCreateDocumentReader(collectionId).DocumentCount(); + } + + public IEnumerable ReadDocuments( + ulong collectionId, + HashSet select, + int skip = 0, + int take = 0) + { + var documentReader = GetOrCreateDocumentReader(collectionId); + var docCount = documentReader.DocumentCount(); + + if (take == 0) + take = docCount; + + var took = 0; + long docId = skip; + + while (docId < docCount && took++ < take) + { + yield return ReadDocument((collectionId, docId++), select, documentReader); + } + } + + public IEnumerable ReadDocumentVectors( + ulong collectionId, + HashSet select, + IModel model, + int skip = 0, + int take = 0) + { + var documentReader = GetOrCreateDocumentReader(collectionId); + var docCount = documentReader.DocumentCount(); + + if (take == 0) + take = docCount; + + var took = 0; + long docId = skip; + + while (docId < docCount && took++ < take) + { + var columns = new List(); + + foreach (var node in ReadDocumentVectors((collectionId, docId), select, documentReader, model)) + { + columns.Add(node); + } + + yield return new AnalyzedDocument(columns); + + docId++; + } + } + + public IEnumerable ReadDocumentValues( + ulong collectionId, + string field, + int skip = 0, + int take = 0) + { + var documentReader = GetOrCreateDocumentReader(collectionId); + var docCount = documentReader.DocumentCount(); + + if (take == 0) + take = docCount; + + var took = 0; + long docId = skip; + + while (docId < docCount && took++ < take) + { + var value = ReadDocumentValue((collectionId, docId), field, documentReader); + + if (value != null) + yield return value; + + docId++; + } + } + + public IEnumerable ReadDocuments( + DocumentReader documentReader, + HashSet select, + int skip = 0, + int take = 0) + { + var docCount = documentReader.DocumentCount(); + + if (take == 0) + take = docCount; + + var took = 0; + long docId = skip; + + while (docId <= docCount && took++ < take) + { + yield return ReadDocument((documentReader.CollectionId, docId++), select, documentReader); + } + } + + public T ReadDocumentValue( + (ulong collectionId, long docId) doc, + string field, + DocumentReader streamReader) + { + var docInfo = streamReader.GetDocumentAddress(doc.docId); + var docMap = streamReader.GetDocumentMap(docInfo.offset, docInfo.length); + T value = default(T); + + for (int i = 0; i < docMap.Count; i++) + { + var kvp = docMap[i]; + var kInfo = streamReader.GetAddressOfKey(kvp.keyId); + var key = (string)streamReader.GetKey(kInfo.offset, kInfo.len, kInfo.dataType); + + if (key == field) + { + var vInfo = streamReader.GetAddressOfValue(kvp.valId); + + value = (T)streamReader.GetValue(vInfo.offset, vInfo.len, vInfo.dataType); + + break; + } + } + + return value; + } + + public IEnumerable ReadDocumentVectors( + (ulong collectionId, long docId) doc, + HashSet select, + DocumentReader streamReader, + IModel model) + { + var docInfo = streamReader.GetDocumentAddress(doc.docId); + var docMap = streamReader.GetDocumentMap(docInfo.offset, docInfo.length); + + // for each key, create a tree + for (int i = 0; i < docMap.Count; i++) + { + var kvp = docMap[i]; + var kInfo = streamReader.GetAddressOfKey(kvp.keyId); + var key = (string)streamReader.GetKey(kInfo.offset, kInfo.len, kInfo.dataType); + var tree = new VectorNode(keyId:kvp.keyId); + + if (select.Contains(key)) + { + var vInfo = streamReader.GetAddressOfValue(kvp.valId); + + foreach (var vector in streamReader.GetVectors(vInfo.offset, vInfo.len, vInfo.dataType, value => model.Tokenize(value))) + { + tree.AddIfUnique(new VectorNode(vector, docId:doc.docId, keyId:kvp.keyId), model); + } + + yield return tree; + } + } + } + + public Document ReadDocument( + (ulong collectionId, long docId) docId, + HashSet select, + double? score = null) + { + var streamReader = GetOrCreateDocumentReader(docId.collectionId); + + return ReadDocument(docId, select, streamReader, score); + } + + public Document ReadDocument( + (ulong collectionId, long docId) doc, + HashSet select, + DocumentReader streamReader, + double? score = null) + { + var docInfo = streamReader.GetDocumentAddress(doc.docId); + var docMap = streamReader.GetDocumentMap(docInfo.offset, docInfo.length); + var fields = new List(); + + for (int i = 0; i < docMap.Count; i++) + { + var kvp = docMap[i]; + var kInfo = streamReader.GetAddressOfKey(kvp.keyId); + var key = (string)streamReader.GetKey(kInfo.offset, kInfo.len, kInfo.dataType); + + if (select.Contains(key)) + { + var vInfo = streamReader.GetAddressOfValue(kvp.valId); + var val = streamReader.GetValue(vInfo.offset, vInfo.len, vInfo.dataType); + + fields.Add(new Field(key, val, kvp.keyId)); + } + } + + return new Document(fields, collectionId:doc.collectionId, documentId:doc.docId, score:(score.HasValue ? score.Value : 0)); + } + + private DocumentReader GetOrCreateDocumentReader(ulong collectionId) + { + DocumentReader reader; + + if (!_streamReaders.TryGetValue(collectionId, out reader)) + { + reader = new DocumentReader(_directory, collectionId, SessionFactory); + _streamReaders.Add(collectionId, reader); + } + + return reader; + } + + public virtual void Dispose() + { + foreach (var reader in _streamReaders.Values) + { + reader.Dispose(); + } + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource streamReader of type Sir.Documents.DocumentReader in method "Document DocumentStreamSession.ReadDocument(ValueTuple`2,HashSet`1,Nullable`1)". + +### Severity: +ERROR + +### Procedure: +Document DocumentStreamSession.ReadDocument(ValueTuple`2,HashSet`1,Nullable`1) + +### File: +src/Sir.Search/Session/DocumentStreamSession.cs + +### Key: +DocumentStreamSession.cs|ReadDocument|DOTNET_RESOURCE_LEAK + +### Hash: +9143f58849b982bb0079db77fd58cc93 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2253/instruction.md b/inferredbugs-2253/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f8f3faa7963b0d162363588551bd33e36b0b3dd3 --- /dev/null +++ b/inferredbugs-2253/instruction.md @@ -0,0 +1,84 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** resin +**Bug ID:** 34 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.Extensions.DependencyInjection; + +namespace Sir.Store +{ + /// + /// Initialize app. + /// + public class Start : IPluginStart + { + public void OnApplicationStartup( + IServiceCollection services, ServiceProvider serviceProvider, IConfigurationProvider config) + { + var httpParser = new HttpQueryParser(new QueryParser()); + var httpBowParser = new HttpBowQueryParser(httpParser); + var sessionFactory = new SessionFactory(config); + + services.AddSingleton(typeof(IStringModel), new BocModel()); + services.AddSingleton(typeof(SessionFactory), sessionFactory); + services.AddSingleton(typeof(HttpQueryParser), httpParser); + services.AddSingleton(typeof(HttpBowQueryParser), new HttpBowQueryParser(httpParser)); + services.AddSingleton(typeof(IQueryFormatter), new QueryFormatter()); + services.AddSingleton(typeof(IWriter), new StoreWriter(sessionFactory)); + services.AddSingleton(typeof(IReader), new StoreReader(sessionFactory, httpParser, httpBowParser)); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource sessionFactory of type Sir.Store.SessionFactory, Leaked resource (output of Sir.Store.StoreReader::.ctor() at Line 23) of type Sir.Store.StoreReader, Leaked resource (output of Sir.Store.StoreWriter::.ctor() at Line 22) of type Sir.Store.StoreWriter in method "Void Start.OnApplicationStartup(IServiceCollection,ServiceProvider,IConfigurationProvider)". + +### Severity: +ERROR + +### Procedure: +Void Start.OnApplicationStartup(IServiceCollection,ServiceProvider,IConfigurationProvider) + +### File: +src/Sir.Store/Start.cs + +### Key: +Start.cs|OnApplicationStartup|DOTNET_RESOURCE_LEAK + +### Hash: +d317358450c14d89d6c8c9318ade33a7 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2254/instruction.md b/inferredbugs-2254/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4e3fd329cd37bff222303bd3cde9a595999b5780 --- /dev/null +++ b/inferredbugs-2254/instruction.md @@ -0,0 +1,194 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** resin +**Bug ID:** 33 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Sir.Core; +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +namespace Sir.Store +{ + public class BowIndexSession : CollectionSession, IDisposable, ILogger + { + private readonly IConfigurationProvider _config; + private readonly ReadSession _readSession; + private readonly ITokenizer _tokenizer; + private readonly ProducerConsumerQueue<(long docId, long keyId, SortedList vector)> _indexWriter; + private readonly SortedList _newColumns; + private readonly Stream _documentVectorStream; + private readonly object _writeSync = new object(); + + public BowIndexSession( + string collectionName, + ulong collectionId, + SessionFactory sessionFactory, + IConfigurationProvider config, + ITokenizer tokenizer, + ConcurrentDictionary indexReaders) : base(collectionName, collectionId, sessionFactory) + { + _config = config; + _readSession = new ReadSession(collectionName, collectionId, sessionFactory, config, indexReaders); + _tokenizer = tokenizer; + + _indexWriter = new ProducerConsumerQueue<(long docId, long keyId, SortedList vector)>( + int.Parse(_config.Get("write_thread_count")), WriteToMemIndex); + + _newColumns = new SortedList(); + + var docVecFileName = Path.Combine(SessionFactory.Dir, CollectionId + ".vec1"); + + _documentVectorStream = SessionFactory.CreateAppendStream(docVecFileName); + } + + public void Write(IEnumerable documents, params long[] excludeKeyIds) + { + foreach (var doc in documents) + { + var docId = (long)doc["___docid"]; + + foreach (var key in doc.Keys) + { + var strKey = key.ToString(); + + if (strKey.StartsWith("__")) + { + continue; + } + + var keyId = SessionFactory.GetKeyId(CollectionId, strKey.ToHash()); + + if (excludeKeyIds.Contains(keyId)) + { + continue; + } + + var treeReader = _readSession.CreateIndexReader(keyId); + var docVec = CreateDocumentVector(doc[key].ToString(), treeReader, _tokenizer); + + _indexWriter.Enqueue((docId, keyId, docVec)); + } + } + } + + private void WriteToMemIndex((long docId, long keyId, SortedList vector) item) + { + VectorNode column; + + if (!_newColumns.TryGetValue(item.keyId, out column)) + { + lock (_writeSync) + { + if (!_newColumns.TryGetValue(item.keyId, out column)) + { + column = new VectorNode(); + _newColumns.Add(item.keyId, column); + } + } + } + + column.Add( + new VectorNode(item.vector, item.docId), + CosineSimilarity.Document, + _documentVectorStream); + + this.Log("added doc field {0}.{1} to memory index", item.docId, item.keyId); + } + + private static SortedList CreateDocumentVector( + string value, NodeReader reader, ITokenizer tokenizer) + { + var terms = tokenizer.Tokenize(value); + + return VectorOperations.CreateDocumentVector(terms.Embeddings(), CosineSimilarity.Document, reader, tokenizer); + } + + private void Flush() + { + _indexWriter.Dispose(); + _documentVectorStream.Dispose(); + + var tasks = new List(); + var writers = new List(); + + foreach (var model in _newColumns) + { + var columnWriter = new ColumnSerializer( + CollectionId, model.Key, SessionFactory, new RemotePostingsWriter(_config, CollectionName), "ix1", "ixp1"); + + tasks.Add(columnWriter.SerializeColumnSegment(model.Value)); + + writers.Add(columnWriter); + } + + Task.WaitAll(tasks.ToArray()); + + this.Log("***FLUSHED*** and completed building of model {0}", CollectionId); + } + + public void Dispose() + { + _readSession.Dispose(); + + Flush(); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource columnWriter.Sir.Store.ColumnSerializer._pageIndexWriter of type Sir.Store.PageIndexWriter, Leaked resource columnWriter.Sir.Store.ColumnSerializer._ixStream of type System.IO.FileStream in method "Void BowIndexSession.Flush()". + +### Severity: +ERROR + +### Procedure: +Void BowIndexSession.Flush() + +### File: +src/Sir.Store/Session/BowIndexSession.cs + +### Key: +BowIndexSession.cs|Flush|DOTNET_RESOURCE_LEAK + +### Hash: +0c1c140da8d875c584b918be66c131c0 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2255/instruction.md b/inferredbugs-2255/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..723d971d9717de133fb5b453cb60725fbba1f3fc --- /dev/null +++ b/inferredbugs-2255/instruction.md @@ -0,0 +1,219 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** resin +**Bug ID:** 20 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using log4net; +using Resin.Analysis; +using Resin.IO; +using Resin.IO.Read; +using Resin.Querying; +using Resin.Sys; + +namespace Resin +{ + public class Collector : IDisposable + { + private readonly string _directory; + private static readonly ILog Log = LogManager.GetLogger(typeof(Collector)); + private readonly IxInfo _ix; + private readonly IDictionary> _termCache; + private readonly IScoringScheme _scorer; + + public Collector(string directory, IxInfo ix, IScoringScheme scorer) + { + _directory = directory; + _ix = ix; + _termCache = new Dictionary>(); + _scorer = scorer; + } + + public IEnumerable Collect(QueryContext query) + { + Scan(query); + GetPostings(query); + + return query.Reduce().Select(p=>p.Score).OrderByDescending(s => s.Score); + } + + private void Scan(QueryContext query) + { + if (query == null) throw new ArgumentNullException("query"); + + Parallel.ForEach(new List {query}.Concat(query.Children), DoScan); + } + + private void DoScan(QueryContext query) + { + var time = Time(); + + using (var reader = GetTreeReader(query.Field)) + { + if (query.Fuzzy) + { + query.Terms = reader.Near(query.Value, query.Edits).Select(word => new Term(query.Field, word)); + } + else if (query.Prefix) + { + query.Terms = reader.StartsWith(query.Value).Select(word => new Term(query.Field, word)); + } + else + { + if (reader.HasWord(query.Value)) + { + query.Terms = new List {new Term(query.Field, new Word(query.Value))}; + } + else + { + query.Terms = new List(); + } + } + } + Log.DebugFormat("scanned {0} in {1}", query, time.Elapsed); + } + + private void GetPostings(QueryContext query) + { + if (query == null) throw new ArgumentNullException("query"); + + var time = Time(); + + foreach (var q in new List {query}.Concat(query.Children)) + { + DoGetPostings(q); + } + + Log.DebugFormat("read postings for {0} in {1}", query, time.Elapsed); + } + + private void DoGetPostings(QueryContext query) + { + var result = DoReadPostings(query.Terms) + .Aggregate, IEnumerable>(null, DocumentPosting.JoinOr); + + query.Postings = result ?? Enumerable.Empty(); + } + + private IEnumerable> DoReadPostings(IEnumerable terms) + { + foreach(var term in terms) + { + IList postings; + + if (!_termCache.TryGetValue(term, out postings)) + { + postings = GetPostingsReader(term).Read(term).ToList(); + postings = Score(postings).ToList(); + _termCache.Add(term, postings); + } + + yield return postings; + } + } + + private PostingsReader GetPostingsReader(Term term) + { + var fileId = term.ToPostingsFileId(); + var fileName = Path.Combine(_directory, fileId + ".pos"); + var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan); + var sr = new StreamReader(fs, Encoding.ASCII); + + return new PostingsReader(sr); + } + + private IEnumerable Score(IEnumerable postings) + { + foreach (var posting in postings) + { + var scorer = _scorer.CreateScorer(_ix.DocumentCount.DocCount[posting.Field], posting.Count); + + posting.Score = new DocumentScore(posting.DocumentId, posting.Count); + + scorer.Score(posting.Score); + + yield return posting; + } + } + + private LcrsTreeReader GetTreeReader(string field) + { + var fileName = Path.Combine(_directory, field.ToTrieFileId() + ".tri"); + var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan); + var sr = new StreamReader(fs, Encoding.Unicode); + var reader = new LcrsTreeReader(sr); + + return reader; + } + + private static Stopwatch Time() + { + var timer = new Stopwatch(); + timer.Start(); + return timer; + } + + public void Dispose() + { + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type Resin.IO.Read.LcrsTreeReader, Leaked resource sr of type System.IO.StreamReader, Leaked resource fs of type System.IO.FileStream in method "LcrsTreeReader Collector.GetTreeReader(String)". + +### Severity: +ERROR + +### Procedure: +LcrsTreeReader Collector.GetTreeReader(String) + +### File: +Resin/Collector.cs + +### Key: +Collector.cs|GetTreeReader|DOTNET_RESOURCE_LEAK + +### Hash: +ec39b4d128f4e72bb0a65d5d1a315443 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2262/instruction.md b/inferredbugs-2262/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2043e830eab41a2773c9fbf5972e66cafa6e46f4 --- /dev/null +++ b/inferredbugs-2262/instruction.md @@ -0,0 +1,137 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** resin +**Bug ID:** 16 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using log4net; +using Resin.IO; + +namespace Resin +{ + /// + /// A reader that provides thread-safe access to an index. Not lock-free. + /// + public class Searcher : IDisposable + { + private static readonly ILog Log = LogManager.GetLogger(typeof(Searcher)); + private readonly string _directory; + private readonly QueryParser _parser; + private readonly IScoringScheme _scorer; + private readonly IndexInfo _ix; + private readonly Dictionary _docContainers; + private static readonly object Sync = new object(); + + public Searcher(string directory, QueryParser parser, IScoringScheme scorer) + { + _directory = directory; + _parser = parser; + _scorer = scorer; + _docContainers = new Dictionary(); + + _ix = IndexInfo.Load(Path.Combine(_directory, "0.ix")); + } + + public Result Search(string query, int page = 0, int size = 10000, bool returnTrace = false) + { + var timer = new Stopwatch(); + timer.Start(); + var collector = new Collector(_directory, _ix); + var q = _parser.Parse(query); + if (q == null) + { + return new Result { Docs = Enumerable.Empty>() }; + } + Log.DebugFormat("parsed query {0} in {1}", q, timer.Elapsed); + var scored = collector.Collect(q, page, size, _scorer).ToList(); + var skip = page * size; + var paged = scored.Skip(skip).Take(size).ToDictionary(x => x.DocId, x => x); + var docs = paged.Values.Select(s => GetDoc(s.DocId)); + return new Result { Docs = docs, Total = scored.Count }; + } + + + private IDictionary GetDoc(string docId) + { + var containerId = docId.ToDocContainerId(); + DocumentFile container; + if (!_docContainers.TryGetValue(containerId, out container)) + { + lock (Sync) + { + if (!_docContainers.TryGetValue(containerId, out container)) + { + container = new DocumentFile(_directory, containerId); + _docContainers.Add(containerId, container); + } + } + } + return container.Get(docId).Fields; + } + + public void Dispose() + { + foreach (var dc in _docContainers.Values) + { + dc.Dispose(); + } + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource container of type Resin.IO.DocumentFile in method "IDictionary`2 Searcher.GetDoc(String)". + +### Severity: +ERROR + +### Procedure: +IDictionary`2 Searcher.GetDoc(String) + +### File: +Resin/Searcher.cs + +### Key: +Searcher.cs|GetDoc|DOTNET_RESOURCE_LEAK + +### Hash: +579d081cc6d679045cc31eeba71e0cee + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2263/instruction.md b/inferredbugs-2263/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..49ea3b22c00e43fb05148149a911458fd7ebe26e --- /dev/null +++ b/inferredbugs-2263/instruction.md @@ -0,0 +1,355 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** resin +**Bug ID:** 42 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.IO.MemoryMappedFiles; +using System.Threading; + +namespace Sir.Store +{ + /// + /// Dispatcher of sessions. + /// + public class SessionFactory : IDisposable, ILogger + { + private ConcurrentDictionary> _keys; + private readonly ConcurrentDictionary> _pageInfo; + private readonly Semaphore WriteSync = new Semaphore(1, 2); + private readonly ConcurrentDictionary _documentWriters; + private readonly ConcurrentDictionary _mmfs; + + public string Dir { get; } + public IConfigurationProvider Config { get; } + public IStringModel Model { get; } + + public SessionFactory(IConfigurationProvider config, IStringModel model) + { + var time = Stopwatch.StartNew(); + + Dir = config.Get("data_dir"); + Config = config; + + if (!Directory.Exists(Dir)) + { + Directory.CreateDirectory(Dir); + } + + _keys = LoadKeys(); + _pageInfo = new ConcurrentDictionary>(); + _documentWriters = new ConcurrentDictionary(); + _mmfs = new ConcurrentDictionary(); + Model = model; + + this.Log($"initiated in {time.Elapsed}"); + } + + public MemoryMappedFile OpenMMF(string fileName) + { + var mapName = fileName.Replace(":", "").Replace("\\", "_"); + + try + { + return _mmfs.GetOrAdd(mapName, x => + { + return MemoryMappedFile.CreateFromFile(fileName, FileMode.Open, mapName, 0, MemoryMappedFileAccess.ReadWrite); + }); + } + catch + { + return _mmfs.GetOrAdd(mapName, x => + { + return MemoryMappedFile.OpenExisting(mapName); + }); + } + } + + public long GetDocCount(string collection) + { + var fileName = Path.Combine(Dir, $"{collection.ToHash()}.dix"); + + if (!File.Exists(fileName)) + return 0; + + return new FileInfo(fileName).Length / (sizeof(long) + sizeof(int)); + } + + public void Truncate(ulong collectionId) + { + foreach (var file in Directory.GetFiles(Dir, $"{collectionId}*")) + File.Delete(file); + + _pageInfo.Clear(); + + _keys.Clear(); + + this.Log($"truncated {collectionId}"); + } + + public void TruncateIndex(ulong collectionId) + { + foreach (var file in Directory.GetFiles(Dir, $"{collectionId}*.ix")) + { + File.Delete(file); + } + foreach (var file in Directory.GetFiles(Dir, $"{collectionId}*.ixp")) + { + File.Delete(file); + } + foreach (var file in Directory.GetFiles(Dir, $"{collectionId}*.vec")) + { + File.Delete(file); + } + foreach (var file in Directory.GetFiles(Dir, $"{collectionId}*.pos")) + { + File.Delete(file); + } + + _pageInfo.Clear(); + } + + public void ExecuteWrite(Job job) + { + WriteSync.WaitOne(); + + var timer = Stopwatch.StartNew(); + + using (var writeSession = CreateWriteSession(job.CollectionId, job.Model)) + { + writeSession.Write(job.Documents); + } + + this.Log("executed {0} write+index job in {1}", job.CollectionId, timer.Elapsed); + + WriteSync.Release(); + } + + public void ClearPageInfo() + { + _pageInfo.Clear(); + } + + public IList<(long offset, long length)> GetAllPages(string pageFileName) + { + return _pageInfo.GetOrAdd(pageFileName, key => + { + using (var ixpStream = CreateReadStream(key)) + { + return new PageIndexReader(ixpStream).GetAll(); + } + }); + } + + public void RefreshKeys() + { + _keys = LoadKeys(); + } + + public ConcurrentDictionary> LoadKeys() + { + var timer = Stopwatch.StartNew(); + var allkeys = new ConcurrentDictionary>(); + + foreach (var keyFile in Directory.GetFiles(Dir, "*.kmap")) + { + var collectionId = ulong.Parse(Path.GetFileNameWithoutExtension(keyFile)); + ConcurrentDictionary keys; + + if (!allkeys.TryGetValue(collectionId, out keys)) + { + keys = new ConcurrentDictionary(); + allkeys.GetOrAdd(collectionId, keys); + } + + using (var stream = new FileStream(keyFile, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite)) + { + long i = 0; + var buf = new byte[sizeof(ulong)]; + var read = stream.Read(buf, 0, buf.Length); + + while (read > 0) + { + keys.GetOrAdd(BitConverter.ToUInt64(buf, 0), i++); + + read = stream.Read(buf, 0, buf.Length); + } + } + } + + this.Log("loaded keys into memory in {0}", timer.Elapsed); + + return allkeys; + } + + public void PersistKeyMapping(ulong collectionId, ulong keyHash, long keyId) + { + var fileName = Path.Combine(Dir, string.Format("{0}.kmap", collectionId)); + ConcurrentDictionary keys; + + if (!_keys.TryGetValue(collectionId, out keys)) + { + keys = new ConcurrentDictionary(); + _keys.GetOrAdd(collectionId, keys); + } + + if (!keys.ContainsKey(keyHash)) + { + keys.GetOrAdd(keyHash, keyId); + + using (var stream = CreateAppendStream(fileName)) + { + stream.Write(BitConverter.GetBytes(keyHash), 0, sizeof(ulong)); + } + } + } + + public long GetKeyId(ulong collectionId, ulong keyHash) + { + return _keys[collectionId][keyHash]; + } + + public bool TryGetKeyId(ulong collectionId, ulong keyHash, out long keyId) + { + var keys = _keys.GetOrAdd(collectionId, new ConcurrentDictionary()); + + if (!keys.TryGetValue(keyHash, out keyId)) + { + keyId = -1; + return false; + } + return true; + } + + public DocumentStreamSession CreateDocumentStreamSession(ulong collectionId) + { + return new DocumentStreamSession(collectionId, this, new DocumentStreamReader(collectionId, this)); + } + + public WriteSession CreateWriteSession(ulong collectionId, IStringModel model) + { + var documentWriter = _documentWriters.GetOrAdd(collectionId, new DocumentStreamWriter(collectionId, this)); + + return new WriteSession( + collectionId, this, documentWriter, Config, model, CreateIndexSession(collectionId)); + } + + public TermIndexSession CreateIndexSession(ulong collectionId) + { + return new TermIndexSession(collectionId, this, Model, Config); + } + + public ValidateSession CreateValidateSession(ulong collectionId) + { + return new ValidateSession(collectionId, this, Model, Config); + } + + public ReadSession CreateReadSession(ulong collectionId) + { + return new ReadSession( + collectionId, this, Config, Model, new DocumentStreamReader(collectionId, this)); + } + + public Stream CreateAsyncReadStream(string fileName, int bufferSize = 4096) + { + return File.Exists(fileName) + ? new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize, FileOptions.Asynchronous) + : null; + } + + public Stream CreateReadStream(string fileName, int bufferSize = 4096, FileOptions fileOptions = FileOptions.RandomAccess) + { + return File.Exists(fileName) + ? new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize, fileOptions) + : null; + } + + public Stream CreateAsyncAppendStream(string fileName, int bufferSize = 4096) + { + return new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, bufferSize, FileOptions.Asynchronous); + } + + public Stream CreateAppendStream(string fileName, int bufferSize = 4096) + { + if (!File.Exists(fileName)) + { + using (var fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, bufferSize)) + { + } + } + + return new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, bufferSize); + } + + public bool CollectionExists(ulong collectionId) + { + return File.Exists(Path.Combine(Dir, collectionId + ".val")); + } + + public void Dispose() + { + foreach (var x in _documentWriters.Values) + x.Dispose(); + + foreach (var file in _mmfs.Values) + file.Dispose(); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type Sir.Store.WriteSession, Leaked resource (returned from Sir.Store.TermIndexSession Sir.Store.SessionFactory::CreateIndexSession(System.UInt64) at Line 232) of type Sir.Store.TermIndexSession, Leaked resource (output of Sir.Store.DocumentStreamWriter::.ctor() at Line 230) of type Sir.Store.DocumentStreamWriter in method "WriteSession SessionFactory.CreateWriteSession(UInt64,IStringModel)". + +### Severity: +ERROR + +### Procedure: +WriteSession SessionFactory.CreateWriteSession(UInt64,IStringModel) + +### File: +src/Sir.Store/Session/SessionFactory.cs + +### Key: +SessionFactory.cs|CreateWriteSession|DOTNET_RESOURCE_LEAK + +### Hash: +31dae4d9c330a2fdc556558f7ffa4ce4 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2290/instruction.md b/inferredbugs-2290/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a200d9248e77c85ac298028d4c2ae3cec031498a --- /dev/null +++ b/inferredbugs-2290/instruction.md @@ -0,0 +1,93 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** resin +**Bug ID:** 23 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using DocumentTable; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.IO; + +namespace Tests +{ + [TestClass()] + public class Setup + { + private const string root = @"c:\temp\resin_tests\"; + + protected static string CreateDir() + { + var dir = root + Guid.NewGuid().ToString(); + Directory.CreateDirectory(dir); + return dir; + } + + protected static IReadSession CreateReadSession(string directory, long version) + { + return new ReadSessionFactory(directory).OpenReadSession(version); + } + + [AssemblyInitialize()] + public static void AssemblyInit(TestContext context) + { + if(Directory.Exists(root)) + foreach(var dir in Directory.GetDirectories(root)) + { + Directory.Delete(dir, true); + } + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type DocumentTable.ReadSession, Leaked resource (output of DocumentTable.ReadSessionFactory::.ctor() at Line 22) of type DocumentTable.ReadSessionFactory in method "IReadSession Setup.CreateReadSession(String,Int64)". + +### Severity: +ERROR + +### Procedure: +IReadSession Setup.CreateReadSession(String,Int64) + +### File: +src/Resin.UnitTests/Setup.cs + +### Key: +Setup.cs|CreateReadSession|DOTNET_RESOURCE_LEAK + +### Hash: +b9b7059a3dd89b2310da55fd4873ee83 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2296/instruction.md b/inferredbugs-2296/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b426bec540ccb268478e398074c4c0f3edcd893a --- /dev/null +++ b/inferredbugs-2296/instruction.md @@ -0,0 +1,345 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** resin +**Bug ID:** 40 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Threading; + +namespace Sir.Store +{ + /// + /// Dispatcher of sessions. + /// + public class SessionFactory : IDisposable, ILogger + { + private ConcurrentDictionary> _keys; + private readonly ConcurrentDictionary> _pageInfo; + private readonly Semaphore WriteSync = new Semaphore(1, 2); + private readonly ConcurrentDictionary _documentWriters; + private readonly ConcurrentDictionary> _columnSerializers; + + public string Dir { get; } + public IConfigurationProvider Config { get; } + public IStringModel Model { get; } + + public SessionFactory(IConfigurationProvider config, IStringModel model) + { + Dir = config.Get("data_dir"); + Config = config; + + if (!Directory.Exists(Dir)) + { + Directory.CreateDirectory(Dir); + } + + Model = model; + _keys = LoadKeys(); + _pageInfo = new ConcurrentDictionary>(); + _documentWriters = new ConcurrentDictionary(); + _columnSerializers = new ConcurrentDictionary>(); + + this.Log("initiated"); + } + + public long GetDocCount(string collection) + { + var fileName = Path.Combine(Dir, $"{collection.ToHash()}.dix"); + + if (!File.Exists(fileName)) + return 0; + + return new FileInfo(fileName).Length / (sizeof(long) + sizeof(int)); + } + + public void Truncate(ulong collectionId) + { + foreach (var file in Directory.GetFiles(Dir, $"{collectionId}*")) + { + File.Delete(file); + } + + _pageInfo.Clear(); + + _keys.Clear(); + + this.Log($"truncated {collectionId}"); + } + + public void TruncateIndex(ulong collectionId) + { + foreach (var file in Directory.GetFiles(Dir, $"{collectionId}*.ix")) + { + File.Delete(file); + } + foreach (var file in Directory.GetFiles(Dir, $"{collectionId}*.ixp")) + { + File.Delete(file); + } + foreach (var file in Directory.GetFiles(Dir, $"{collectionId}*.vec")) + { + File.Delete(file); + } + foreach (var file in Directory.GetFiles(Dir, $"{collectionId}*.pos")) + { + File.Delete(file); + } + + _pageInfo.Clear(); + } + + public void ExecuteWrite(Job job) + { + WriteSync.WaitOne(); + + var timer = Stopwatch.StartNew(); + var colId = job.Collection.ToHash(); + + using (var writeSession = CreateWriteSession(job.Collection, colId, job.Model)) + { + writeSession.Write(job.Documents); + } + + this.Log("executed {0} write+index job in {1}", job.Collection, timer.Elapsed); + + WriteSync.Release(); + } + + public void ClearPageInfo() + { + _pageInfo.Clear(); + } + + public IList<(long offset, long length)> ReadPageInfo(string pageFileName) + { + return _pageInfo.GetOrAdd(pageFileName, key => + { + using (var ixpStream = CreateReadStream(key)) + { + return new PageIndexReader(ixpStream).ReadAll(); + } + }); + } + + public void RefreshKeys() + { + _keys = LoadKeys(); + } + + public ConcurrentDictionary> LoadKeys() + { + var timer = new Stopwatch(); + timer.Start(); + + var allkeys = new ConcurrentDictionary>(); + + foreach (var keyFile in Directory.GetFiles(Dir, "*.kmap")) + { + var collectionId = ulong.Parse(Path.GetFileNameWithoutExtension(keyFile)); + ConcurrentDictionary keys; + + if (!allkeys.TryGetValue(collectionId, out keys)) + { + keys = new ConcurrentDictionary(); + allkeys.GetOrAdd(collectionId, keys); + } + + using (var stream = new FileStream(keyFile, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite)) + { + long i = 0; + var buf = new byte[sizeof(ulong)]; + var read = stream.Read(buf, 0, buf.Length); + + while (read > 0) + { + keys.GetOrAdd(BitConverter.ToUInt64(buf, 0), i++); + + read = stream.Read(buf, 0, buf.Length); + } + } + } + + this.Log("loaded keys into memory in {0}", timer.Elapsed); + + return allkeys; + } + + public void PersistKeyMapping(ulong collectionId, ulong keyHash, long keyId) + { + var fileName = Path.Combine(Dir, string.Format("{0}.kmap", collectionId)); + ConcurrentDictionary keys; + + if (!_keys.TryGetValue(collectionId, out keys)) + { + keys = new ConcurrentDictionary(); + _keys.GetOrAdd(collectionId, keys); + } + + if (!keys.ContainsKey(keyHash)) + { + keys.GetOrAdd(keyHash, keyId); + + using (var stream = CreateAppendStream(fileName)) + { + stream.Write(BitConverter.GetBytes(keyHash), 0, sizeof(ulong)); + } + } + } + + public long GetKeyId(ulong collectionId, ulong keyHash) + { + return _keys[collectionId][keyHash]; + } + + public bool TryGetKeyId(ulong collectionId, ulong keyHash, out long keyId) + { + var keys = _keys.GetOrAdd(collectionId, new ConcurrentDictionary()); + + if (!keys.TryGetValue(keyHash, out keyId)) + { + keyId = -1; + return false; + } + return true; + } + + public WarmupSession CreateWarmupSession(string collectionName, ulong collectionId, string baseUrl) + { + return new WarmupSession(collectionName, collectionId, this, Model, Config, baseUrl); + } + + public DocumentStreamSession CreateDocumentStreamSession(string collectionName, ulong collectionId) + { + return new DocumentStreamSession(collectionName, collectionId, this, new DocumentStreamReader(collectionId, this)); + } + + public WriteSession CreateWriteSession(string collectionName, ulong collectionId, IStringModel model) + { + var documentWriter = _documentWriters.GetOrAdd(collectionId, new DocumentStreamWriter(collectionId, this)); + + return new WriteSession( + collectionName, collectionId, this, documentWriter, Config, model); + } + + public TermIndexSession CreateIndexSession(string collectionName, ulong collectionId) + { + return new TermIndexSession(collectionName, collectionId, this, Model, Config); + } + + public ValidateSession CreateValidateSession(string collectionName, ulong collectionId) + { + return new ValidateSession(collectionName, collectionId, this, Model, Config); + } + + public ReadSession CreateReadSession(string collectionName, ulong collectionId) + { + return new ReadSession( + collectionName, collectionId, this, Config, Model, new DocumentStreamReader(collectionId, this)); + } + + public Stream CreateAsyncReadStream(string fileName, int bufferSize = 4096) + { + return File.Exists(fileName) + ? new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize, FileOptions.Asynchronous) + : null; + } + + public Stream CreateReadStream(string fileName, int bufferSize = 4096, FileOptions fileOptions = FileOptions.RandomAccess) + { + return File.Exists(fileName) + ? new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize, fileOptions) + : null; + } + + public Stream CreateAsyncAppendStream(string fileName, int bufferSize = 4096) + { + return new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, bufferSize, FileOptions.Asynchronous); + } + + public Stream CreateAppendStream(string fileName, int bufferSize = 4096) + { + if (!File.Exists(fileName)) + { + using (var fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, bufferSize)) + { + } + } + + return new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, bufferSize); + } + + public bool CollectionExists(ulong collectionId) + { + return File.Exists(Path.Combine(Dir, collectionId + ".val")); + } + + public void Dispose() + { + foreach (var x in _documentWriters.Values) + x.Dispose(); + + foreach(var d in _columnSerializers.Values) + { + foreach (var x in d.Values) + x.Dispose(); + } + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type Sir.Store.WriteSession, Leaked resource (output of Sir.Store.DocumentStreamWriter::.ctor() at Line 217) of type Sir.Store.DocumentStreamWriter in method "WriteSession SessionFactory.CreateWriteSession(String,UInt64,IStringModel)". + +### Severity: +ERROR + +### Procedure: +WriteSession SessionFactory.CreateWriteSession(String,UInt64,IStringModel) + +### File: +src/Sir.Store/Session/SessionFactory.cs + +### Key: +SessionFactory.cs|CreateWriteSession|DOTNET_RESOURCE_LEAK + +### Hash: +ea545c5d3b5b12f5d191c68acfc68b4d + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2297/instruction.md b/inferredbugs-2297/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f9b613e14955208e728fd6dc0f0c368f93aeba43 --- /dev/null +++ b/inferredbugs-2297/instruction.md @@ -0,0 +1,93 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** resin +**Bug ID:** 47 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Sir.Search +{ + /// + /// Initialize app. + /// + public class Start : IPluginStart + { + public void OnApplicationStartup( + IServiceCollection services, ServiceProvider serviceProvider, IConfigurationProvider config) + { + var loggerFactory = serviceProvider.GetService(); + var model = new BocModel(); + var sessionFactory = new SessionFactory( + config, + model, + loggerFactory); + + var httpParser = new HttpQueryParser(new QueryParser(sessionFactory, model)); + + services.AddSingleton(typeof(IStringModel), model); + services.AddSingleton(typeof(ISessionFactory), sessionFactory); + services.AddSingleton(typeof(SessionFactory), sessionFactory); + services.AddSingleton(typeof(HttpQueryParser), httpParser); + services.AddSingleton(typeof(IHttpWriter), new HttpWriter(sessionFactory)); + services.AddSingleton(typeof(IHttpReader), new HttpReader( + sessionFactory, + httpParser, + config, + loggerFactory.CreateLogger())); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource sessionFactory of type Sir.Search.SessionFactory, Leaked resource (output of Sir.Search.HttpReader::.ctor() at Line 28) of type Sir.Search.HttpReader, Leaked resource (output of Sir.Search.HttpWriter::.ctor() at Line 27) of type Sir.Search.HttpWriter in method "Void Start.OnApplicationStartup(IServiceCollection,ServiceProvider,IConfigurationProvider)". + +### Severity: +ERROR + +### Procedure: +Void Start.OnApplicationStartup(IServiceCollection,ServiceProvider,IConfigurationProvider) + +### File: +src/Sir.Search/Start.cs + +### Key: +Start.cs|OnApplicationStartup|DOTNET_RESOURCE_LEAK + +### Hash: +c5f4e6e7007eb4bcdf04edb339f9a468 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2298/instruction.md b/inferredbugs-2298/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..22d331e04cfd6b95b1ccdbc5386346b86fe48142 --- /dev/null +++ b/inferredbugs-2298/instruction.md @@ -0,0 +1,87 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** resin +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.IO; +using System.Linq; +using NUnit.Framework; +using Resin; + +namespace Tests +{ + [TestFixture] + public class FieldReaderTests + { + [Test] + public void Can_read_field_file() + { + const string fileName = "c:\\temp\\resin_tests\\Can_read_field_file\\0.fld"; + if (File.Exists(fileName)) File.Delete(fileName); + using (var fw = new FieldFile(fileName)) + { + fw.Write(0, "hello", 0); + fw.Write(5, "world", 1); + } + var reader = FieldReader.Load(fileName); + var helloPositionsForDocId0 = reader.GetDocPosition("hello")[0]; + var worldPositionsForDocId5 = reader.GetDocPosition("world")[5]; + Assert.AreEqual(0, helloPositionsForDocId0.First()); + Assert.AreEqual(1, worldPositionsForDocId5.First()); + } + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +``IDictionary`2 FieldReader.GetDocPosition(String)`` could be null (from the call to `FieldReader.GetDocPosition(...)` on line 22) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +Void FieldReaderTests.Can_read_field_file() + +### File: +Tests/FieldReaderTests.cs + +### Key: +FieldReaderTests.cs|Can_read_field_file|NULLPTR_DEREFERENCE + +### Hash: +e2a9d4b492c0066c497869c0d005db38 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2310/instruction.md b/inferredbugs-2310/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2524d7433fc3c9d429fec9f766ea0453a6070921 --- /dev/null +++ b/inferredbugs-2310/instruction.md @@ -0,0 +1,1323 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** TorchSharp +**Bug ID:** 11 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Buffers; +using System.Linq; +using System.Numerics.Tensors; +using System.Runtime.CompilerServices; +using TorchSharp; + +namespace Torch.SNT +{ + + /// + /// Wrapper class used to surface a Torch ByteTensor as a System.Numerics DensorTensor of byte + /// + public sealed class ByteTorchTensor : DenseTensor, IDisposable + { + internal sealed class ByteNativeMemory : MemoryManager + { + private readonly ByteTensor.ByteStorage storage; + + public ByteNativeMemory(ByteTensor.ByteStorage storage) + { + this.storage = storage; + + if (storage.Size () < 0) + { + throw new ArgumentOutOfRangeException ("Length cannot be negative."); + } + } + + /// + /// Returns a span wrapping the underlying memory. + /// Remember to Unpin the memory once the span is disposed. + /// + public override Span GetSpan () + { + ulong len = storage.Size (); + + if (len > int.MaxValue) + { + throw new InvalidCastException ("Tensor size not supported."); + } + + unsafe + { + return new Span (storage.Data.ToPointer (), (int)len); + } + } + + /// + /// Returns a handle to the memory that has been pinned and hence its address can be taken. + /// + /// The offset to the element within the memory at which the returned points to. (default = 0) + public override MemoryHandle Pin (int elementIndex = 0) + { + unsafe + { + storage.Retain(); + if ((uint)elementIndex > storage.Size ()) throw new ArgumentOutOfRangeException (nameof (elementIndex), "Index out of array bound."); + void* pointer = Unsafe.Add ((void*)storage.Data, elementIndex); + return new MemoryHandle (pointer, default, this); + } + } + + /// + /// Lets the garbage collector know that the object is free to be moved now. + /// + public override void Unpin () + { + storage.Free (); + } + + protected override void Dispose (bool disposing) + { + if (disposing) + { + storage.Free (); + } + } + } + + private readonly object inner; + + /// + /// Property returning the inner TorchSharp tensor the class is wrapping. + /// + public ByteTensor TorchSharpTensor => inner as ByteTensor; + + public ByteTorchTensor (Memory memory, ReadOnlySpan dimensions, ByteTensor inner) : base (memory, dimensions) + { + this.inner = inner; + } + + /// + /// Utility method to create a TorchTensor. + /// This is currently failing if the input parameter is empty because SNT + /// does not support zero-size tensors. + /// + /// The desired sizes for the dimensions of the tensor. + public static ByteTorchTensor Create (params int[] sizes) + { + var totLength = Utils.GetTotalLength (sizes); + var shape = sizes; + + if (sizes.Length == 0) + { + shape = new int[] { 0 }; + } + + var inner = CreateByteTensor (sizes.Select (x => (long)x).ToArray ()); + var storage = inner.Storage; + storage.Retain (); + var mem = new ByteNativeMemory (storage); + + return new ByteTorchTensor (mem.Memory, shape, inner); + } + + public void Dispose () + { + var typedInner = inner as ByteTensor; + typedInner.Dispose (); + } + + /// + /// Creates a shallow copy of this tensor, with new backing storage. + /// + /// A shallow copy of this tensor. + public override Tensor Clone () + { + var typedInner = inner as ByteTensor; + var innerClone = typedInner.Clone (); + var storage = innerClone.Storage; + storage.Retain (); + var mem = new ByteNativeMemory (storage); + + return new ByteTorchTensor (mem.Memory, Dimensions, innerClone); + } + + /// + /// Creates a new Tensor of a different type with the specified dimensions and the same layout as this tensor with elements initialized to their default value. + /// + /// Type contained in the returned Tensor. + /// An span of integers that represent the size of each dimension of the DenseTensor to create. + /// A new tensor with the same layout as this tensor but different type and dimensions. + public override Tensor CloneEmpty (ReadOnlySpan dimensions) + { + var typedInner = inner as ByteTensor; + + switch (true) + { + case bool _ when typeof (TResult) == typeof (byte): + var innerClone = CreateByteTensor (typedInner.Shape); + innerClone.Fill (default); + var mem = new ByteNativeMemory (innerClone.Storage); + + return new ByteTorchTensor (mem.Memory, Dimensions, innerClone) as Tensor; + default: throw new NotImplementedException ("Only cloning bytes is currently implemented."); + } + } + + /// + /// Reshapes the current tensor to new dimensions, using the same backing storage. + /// + /// An span of integers that represent the size of each dimension of the DenseTensor to create. + /// A new tensor that reinterprets backing Buffer of this tensor with different dimensions. + public override Tensor Reshape (ReadOnlySpan dimensions) + { + if (dimensions.Length == 0) + { + throw new ArgumentException ("Dimensions must contain elements.", nameof (dimensions)); + } + + var newSize = Utils.GetTotalLength (dimensions); + + if (newSize != Length) + { + throw new ArgumentException ($"Cannot reshape array due to mismatch in lengths, currently {Length} would become {newSize}.", nameof(dimensions)); + } + + var typedInner = inner as ByteTensor; + ByteTensor reshapedTensor; + + switch (dimensions.Length) + { + case 1: + reshapedTensor = typedInner.NewWithStorage1d (UIntPtr.Zero, dimensions[0], 1); + break; + case 2: + reshapedTensor = typedInner.NewWithStorage2d (UIntPtr.Zero, dimensions[0], dimensions[1], dimensions[1], 1); + break; + default: throw new ArgumentException ($"Cannot reshape tensor with more than 4 dimensions"); + } + + return new ByteTorchTensor (Buffer, dimensions, reshapedTensor); + } + + /// + /// Creates a 1-4D tensor of the specified size(s). + /// + /// Sizes for the dimensions. + internal static ByteTensor CreateByteTensor (params long[] dims) + { + switch (dims.Length) + { + case 0: + return new ByteTensor (); + case 1: + return new ByteTensor (dims[0]); + case 2: + return new ByteTensor (dims[0], dims[1]); + case 3: + return new ByteTensor (dims[0], dims[1], dims[2]); + case 4: + return new ByteTensor (dims[0], dims[1], dims[2], dims[3]); + default: + throw new ArgumentOutOfRangeException (nameof (dims), "Maximum number of dimensions for tensor creation is 4."); + } + } + } + + /// + /// Wrapper class used to surface a Torch ShortTensor as a System.Numerics DensorTensor of short + /// + public sealed class ShortTorchTensor : DenseTensor, IDisposable + { + internal sealed class ShortNativeMemory : MemoryManager + { + private readonly ShortTensor.ShortStorage storage; + + public ShortNativeMemory(ShortTensor.ShortStorage storage) + { + this.storage = storage; + + if (storage.Size () < 0) + { + throw new ArgumentOutOfRangeException ("Length cannot be negative."); + } + } + + /// + /// Returns a span wrapping the underlying memory. + /// Remember to Unpin the memory once the span is disposed. + /// + public override Span GetSpan () + { + ulong len = storage.Size (); + + if (len > int.MaxValue) + { + throw new InvalidCastException ("Tensor size not supported."); + } + + unsafe + { + return new Span (storage.Data.ToPointer (), (int)len); + } + } + + /// + /// Returns a handle to the memory that has been pinned and hence its address can be taken. + /// + /// The offset to the element within the memory at which the returned points to. (default = 0) + public override MemoryHandle Pin (int elementIndex = 0) + { + unsafe + { + storage.Retain(); + if ((uint)elementIndex > storage.Size ()) throw new ArgumentOutOfRangeException (nameof (elementIndex), "Index out of array bound."); + void* pointer = Unsafe.Add ((void*)storage.Data, elementIndex); + return new MemoryHandle (pointer, default, this); + } + } + + /// + /// Lets the garbage collector know that the object is free to be moved now. + /// + public override void Unpin () + { + storage.Free (); + } + + protected override void Dispose (bool disposing) + { + if (disposing) + { + storage.Free (); + } + } + } + + private readonly object inner; + + /// + /// Property returning the inner TorchSharp tensor the class is wrapping. + /// + public ShortTensor TorchSharpTensor => inner as ShortTensor; + + public ShortTorchTensor (Memory memory, ReadOnlySpan dimensions, ShortTensor inner) : base (memory, dimensions) + { + this.inner = inner; + } + + /// + /// Utility method to create a TorchTensor. + /// This is currently failing if the input parameter is empty because SNT + /// does not support zero-size tensors. + /// + /// The desired sizes for the dimensions of the tensor. + public static ShortTorchTensor Create (params int[] sizes) + { + var totLength = Utils.GetTotalLength (sizes); + var shape = sizes; + + if (sizes.Length == 0) + { + shape = new int[] { 0 }; + } + + var inner = CreateShortTensor (sizes.Select (x => (long)x).ToArray ()); + var storage = inner.Storage; + storage.Retain (); + var mem = new ShortNativeMemory (storage); + + return new ShortTorchTensor (mem.Memory, shape, inner); + } + + public void Dispose () + { + var typedInner = inner as ShortTensor; + typedInner.Dispose (); + } + + /// + /// Creates a shallow copy of this tensor, with new backing storage. + /// + /// A shallow copy of this tensor. + public override Tensor Clone () + { + var typedInner = inner as ShortTensor; + var innerClone = typedInner.Clone (); + var storage = innerClone.Storage; + storage.Retain (); + var mem = new ShortNativeMemory (storage); + + return new ShortTorchTensor (mem.Memory, Dimensions, innerClone); + } + + /// + /// Creates a new Tensor of a different type with the specified dimensions and the same layout as this tensor with elements initialized to their default value. + /// + /// Type contained in the returned Tensor. + /// An span of integers that represent the size of each dimension of the DenseTensor to create. + /// A new tensor with the same layout as this tensor but different type and dimensions. + public override Tensor CloneEmpty (ReadOnlySpan dimensions) + { + var typedInner = inner as ShortTensor; + + switch (true) + { + case bool _ when typeof (TResult) == typeof (short): + var innerClone = CreateShortTensor (typedInner.Shape); + innerClone.Fill (default); + var mem = new ShortNativeMemory (innerClone.Storage); + + return new ShortTorchTensor (mem.Memory, Dimensions, innerClone) as Tensor; + default: throw new NotImplementedException ("Only cloning shorts is currently implemented."); + } + } + + /// + /// Reshapes the current tensor to new dimensions, using the same backing storage. + /// + /// An span of integers that represent the size of each dimension of the DenseTensor to create. + /// A new tensor that reinterprets backing Buffer of this tensor with different dimensions. + public override Tensor Reshape (ReadOnlySpan dimensions) + { + if (dimensions.Length == 0) + { + throw new ArgumentException ("Dimensions must contain elements.", nameof (dimensions)); + } + + var newSize = Utils.GetTotalLength (dimensions); + + if (newSize != Length) + { + throw new ArgumentException ($"Cannot reshape array due to mismatch in lengths, currently {Length} would become {newSize}.", nameof(dimensions)); + } + + var typedInner = inner as ShortTensor; + ShortTensor reshapedTensor; + + switch (dimensions.Length) + { + case 1: + reshapedTensor = typedInner.NewWithStorage1d (UIntPtr.Zero, dimensions[0], 1); + break; + case 2: + reshapedTensor = typedInner.NewWithStorage2d (UIntPtr.Zero, dimensions[0], dimensions[1], dimensions[1], 1); + break; + default: throw new ArgumentException ($"Cannot reshape tensor with more than 4 dimensions"); + } + + return new ShortTorchTensor (Buffer, dimensions, reshapedTensor); + } + + /// + /// Creates a 1-4D tensor of the specified size(s). + /// + /// Sizes for the dimensions. + internal static ShortTensor CreateShortTensor (params long[] dims) + { + switch (dims.Length) + { + case 0: + return new ShortTensor (); + case 1: + return new ShortTensor (dims[0]); + case 2: + return new ShortTensor (dims[0], dims[1]); + case 3: + return new ShortTensor (dims[0], dims[1], dims[2]); + case 4: + return new ShortTensor (dims[0], dims[1], dims[2], dims[3]); + default: + throw new ArgumentOutOfRangeException (nameof (dims), "Maximum number of dimensions for tensor creation is 4."); + } + } + } + + /// + /// Wrapper class used to surface a Torch IntTensor as a System.Numerics DensorTensor of int + /// + public sealed class IntTorchTensor : DenseTensor, IDisposable + { + internal sealed class IntNativeMemory : MemoryManager + { + private readonly IntTensor.IntStorage storage; + + public IntNativeMemory(IntTensor.IntStorage storage) + { + this.storage = storage; + + if (storage.Size () < 0) + { + throw new ArgumentOutOfRangeException ("Length cannot be negative."); + } + } + + /// + /// Returns a span wrapping the underlying memory. + /// Remember to Unpin the memory once the span is disposed. + /// + public override Span GetSpan () + { + ulong len = storage.Size (); + + if (len > int.MaxValue) + { + throw new InvalidCastException ("Tensor size not supported."); + } + + unsafe + { + return new Span (storage.Data.ToPointer (), (int)len); + } + } + + /// + /// Returns a handle to the memory that has been pinned and hence its address can be taken. + /// + /// The offset to the element within the memory at which the returned points to. (default = 0) + public override MemoryHandle Pin (int elementIndex = 0) + { + unsafe + { + storage.Retain(); + if ((uint)elementIndex > storage.Size ()) throw new ArgumentOutOfRangeException (nameof (elementIndex), "Index out of array bound."); + void* pointer = Unsafe.Add ((void*)storage.Data, elementIndex); + return new MemoryHandle (pointer, default, this); + } + } + + /// + /// Lets the garbage collector know that the object is free to be moved now. + /// + public override void Unpin () + { + storage.Free (); + } + + protected override void Dispose (bool disposing) + { + if (disposing) + { + storage.Free (); + } + } + } + + private readonly object inner; + + /// + /// Property returning the inner TorchSharp tensor the class is wrapping. + /// + public IntTensor TorchSharpTensor => inner as IntTensor; + + public IntTorchTensor (Memory memory, ReadOnlySpan dimensions, IntTensor inner) : base (memory, dimensions) + { + this.inner = inner; + } + + /// + /// Utility method to create a TorchTensor. + /// This is currently failing if the input parameter is empty because SNT + /// does not support zero-size tensors. + /// + /// The desired sizes for the dimensions of the tensor. + public static IntTorchTensor Create (params int[] sizes) + { + var totLength = Utils.GetTotalLength (sizes); + var shape = sizes; + + if (sizes.Length == 0) + { + shape = new int[] { 0 }; + } + + var inner = CreateIntTensor (sizes.Select (x => (long)x).ToArray ()); + var storage = inner.Storage; + storage.Retain (); + var mem = new IntNativeMemory (storage); + + return new IntTorchTensor (mem.Memory, shape, inner); + } + + public void Dispose () + { + var typedInner = inner as IntTensor; + typedInner.Dispose (); + } + + /// + /// Creates a shallow copy of this tensor, with new backing storage. + /// + /// A shallow copy of this tensor. + public override Tensor Clone () + { + var typedInner = inner as IntTensor; + var innerClone = typedInner.Clone (); + var storage = innerClone.Storage; + storage.Retain (); + var mem = new IntNativeMemory (storage); + + return new IntTorchTensor (mem.Memory, Dimensions, innerClone); + } + + /// + /// Creates a new Tensor of a different type with the specified dimensions and the same layout as this tensor with elements initialized to their default value. + /// + /// Type contained in the returned Tensor. + /// An span of integers that represent the size of each dimension of the DenseTensor to create. + /// A new tensor with the same layout as this tensor but different type and dimensions. + public override Tensor CloneEmpty (ReadOnlySpan dimensions) + { + var typedInner = inner as IntTensor; + + switch (true) + { + case bool _ when typeof (TResult) == typeof (int): + var innerClone = CreateIntTensor (typedInner.Shape); + innerClone.Fill (default); + var mem = new IntNativeMemory (innerClone.Storage); + + return new IntTorchTensor (mem.Memory, Dimensions, innerClone) as Tensor; + default: throw new NotImplementedException ("Only cloning ints is currently implemented."); + } + } + + /// + /// Reshapes the current tensor to new dimensions, using the same backing storage. + /// + /// An span of integers that represent the size of each dimension of the DenseTensor to create. + /// A new tensor that reinterprets backing Buffer of this tensor with different dimensions. + public override Tensor Reshape (ReadOnlySpan dimensions) + { + if (dimensions.Length == 0) + { + throw new ArgumentException ("Dimensions must contain elements.", nameof (dimensions)); + } + + var newSize = Utils.GetTotalLength (dimensions); + + if (newSize != Length) + { + throw new ArgumentException ($"Cannot reshape array due to mismatch in lengths, currently {Length} would become {newSize}.", nameof(dimensions)); + } + + var typedInner = inner as IntTensor; + IntTensor reshapedTensor; + + switch (dimensions.Length) + { + case 1: + reshapedTensor = typedInner.NewWithStorage1d (UIntPtr.Zero, dimensions[0], 1); + break; + case 2: + reshapedTensor = typedInner.NewWithStorage2d (UIntPtr.Zero, dimensions[0], dimensions[1], dimensions[1], 1); + break; + default: throw new ArgumentException ($"Cannot reshape tensor with more than 4 dimensions"); + } + + return new IntTorchTensor (Buffer, dimensions, reshapedTensor); + } + + /// + /// Creates a 1-4D tensor of the specified size(s). + /// + /// Sizes for the dimensions. + internal static IntTensor CreateIntTensor (params long[] dims) + { + switch (dims.Length) + { + case 0: + return new IntTensor (); + case 1: + return new IntTensor (dims[0]); + case 2: + return new IntTensor (dims[0], dims[1]); + case 3: + return new IntTensor (dims[0], dims[1], dims[2]); + case 4: + return new IntTensor (dims[0], dims[1], dims[2], dims[3]); + default: + throw new ArgumentOutOfRangeException (nameof (dims), "Maximum number of dimensions for tensor creation is 4."); + } + } + } + + /// + /// Wrapper class used to surface a Torch LongTensor as a System.Numerics DensorTensor of long + /// + public sealed class LongTorchTensor : DenseTensor, IDisposable + { + internal sealed class LongNativeMemory : MemoryManager + { + private readonly LongTensor.LongStorage storage; + + public LongNativeMemory(LongTensor.LongStorage storage) + { + this.storage = storage; + + if (storage.Size () < 0) + { + throw new ArgumentOutOfRangeException ("Length cannot be negative."); + } + } + + /// + /// Returns a span wrapping the underlying memory. + /// Remember to Unpin the memory once the span is disposed. + /// + public override Span GetSpan () + { + ulong len = storage.Size (); + + if (len > int.MaxValue) + { + throw new InvalidCastException ("Tensor size not supported."); + } + + unsafe + { + return new Span (storage.Data.ToPointer (), (int)len); + } + } + + /// + /// Returns a handle to the memory that has been pinned and hence its address can be taken. + /// + /// The offset to the element within the memory at which the returned points to. (default = 0) + public override MemoryHandle Pin (int elementIndex = 0) + { + unsafe + { + storage.Retain(); + if ((uint)elementIndex > storage.Size ()) throw new ArgumentOutOfRangeException (nameof (elementIndex), "Index out of array bound."); + void* pointer = Unsafe.Add ((void*)storage.Data, elementIndex); + return new MemoryHandle (pointer, default, this); + } + } + + /// + /// Lets the garbage collector know that the object is free to be moved now. + /// + public override void Unpin () + { + storage.Free (); + } + + protected override void Dispose (bool disposing) + { + if (disposing) + { + storage.Free (); + } + } + } + + private readonly object inner; + + /// + /// Property returning the inner TorchSharp tensor the class is wrapping. + /// + public LongTensor TorchSharpTensor => inner as LongTensor; + + public LongTorchTensor (Memory memory, ReadOnlySpan dimensions, LongTensor inner) : base (memory, dimensions) + { + this.inner = inner; + } + + /// + /// Utility method to create a TorchTensor. + /// This is currently failing if the input parameter is empty because SNT + /// does not support zero-size tensors. + /// + /// The desired sizes for the dimensions of the tensor. + public static LongTorchTensor Create (params int[] sizes) + { + var totLength = Utils.GetTotalLength (sizes); + var shape = sizes; + + if (sizes.Length == 0) + { + shape = new int[] { 0 }; + } + + var inner = CreateLongTensor (sizes.Select (x => (long)x).ToArray ()); + var storage = inner.Storage; + storage.Retain (); + var mem = new LongNativeMemory (storage); + + return new LongTorchTensor (mem.Memory, shape, inner); + } + + public void Dispose () + { + var typedInner = inner as LongTensor; + typedInner.Dispose (); + } + + /// + /// Creates a shallow copy of this tensor, with new backing storage. + /// + /// A shallow copy of this tensor. + public override Tensor Clone () + { + var typedInner = inner as LongTensor; + var innerClone = typedInner.Clone (); + var storage = innerClone.Storage; + storage.Retain (); + var mem = new LongNativeMemory (storage); + + return new LongTorchTensor (mem.Memory, Dimensions, innerClone); + } + + /// + /// Creates a new Tensor of a different type with the specified dimensions and the same layout as this tensor with elements initialized to their default value. + /// + /// Type contained in the returned Tensor. + /// An span of integers that represent the size of each dimension of the DenseTensor to create. + /// A new tensor with the same layout as this tensor but different type and dimensions. + public override Tensor CloneEmpty (ReadOnlySpan dimensions) + { + var typedInner = inner as LongTensor; + + switch (true) + { + case bool _ when typeof (TResult) == typeof (long): + var innerClone = CreateLongTensor (typedInner.Shape); + innerClone.Fill (default); + var mem = new LongNativeMemory (innerClone.Storage); + + return new LongTorchTensor (mem.Memory, Dimensions, innerClone) as Tensor; + default: throw new NotImplementedException ("Only cloning longs is currently implemented."); + } + } + + /// + /// Reshapes the current tensor to new dimensions, using the same backing storage. + /// + /// An span of integers that represent the size of each dimension of the DenseTensor to create. + /// A new tensor that reinterprets backing Buffer of this tensor with different dimensions. + public override Tensor Reshape (ReadOnlySpan dimensions) + { + if (dimensions.Length == 0) + { + throw new ArgumentException ("Dimensions must contain elements.", nameof (dimensions)); + } + + var newSize = Utils.GetTotalLength (dimensions); + + if (newSize != Length) + { + throw new ArgumentException ($"Cannot reshape array due to mismatch in lengths, currently {Length} would become {newSize}.", nameof(dimensions)); + } + + var typedInner = inner as LongTensor; + LongTensor reshapedTensor; + + switch (dimensions.Length) + { + case 1: + reshapedTensor = typedInner.NewWithStorage1d (UIntPtr.Zero, dimensions[0], 1); + break; + case 2: + reshapedTensor = typedInner.NewWithStorage2d (UIntPtr.Zero, dimensions[0], dimensions[1], dimensions[1], 1); + break; + default: throw new ArgumentException ($"Cannot reshape tensor with more than 4 dimensions"); + } + + return new LongTorchTensor (Buffer, dimensions, reshapedTensor); + } + + /// + /// Creates a 1-4D tensor of the specified size(s). + /// + /// Sizes for the dimensions. + internal static LongTensor CreateLongTensor (params long[] dims) + { + switch (dims.Length) + { + case 0: + return new LongTensor (); + case 1: + return new LongTensor (dims[0]); + case 2: + return new LongTensor (dims[0], dims[1]); + case 3: + return new LongTensor (dims[0], dims[1], dims[2]); + case 4: + return new LongTensor (dims[0], dims[1], dims[2], dims[3]); + default: + throw new ArgumentOutOfRangeException (nameof (dims), "Maximum number of dimensions for tensor creation is 4."); + } + } + } + + /// + /// Wrapper class used to surface a Torch DoubleTensor as a System.Numerics DensorTensor of double + /// + public sealed class DoubleTorchTensor : DenseTensor, IDisposable + { + internal sealed class DoubleNativeMemory : MemoryManager + { + private readonly DoubleTensor.DoubleStorage storage; + + public DoubleNativeMemory(DoubleTensor.DoubleStorage storage) + { + this.storage = storage; + + if (storage.Size () < 0) + { + throw new ArgumentOutOfRangeException ("Length cannot be negative."); + } + } + + /// + /// Returns a span wrapping the underlying memory. + /// Remember to Unpin the memory once the span is disposed. + /// + public override Span GetSpan () + { + ulong len = storage.Size (); + + if (len > int.MaxValue) + { + throw new InvalidCastException ("Tensor size not supported."); + } + + unsafe + { + return new Span (storage.Data.ToPointer (), (int)len); + } + } + + /// + /// Returns a handle to the memory that has been pinned and hence its address can be taken. + /// + /// The offset to the element within the memory at which the returned points to. (default = 0) + public override MemoryHandle Pin (int elementIndex = 0) + { + unsafe + { + storage.Retain(); + if ((uint)elementIndex > storage.Size ()) throw new ArgumentOutOfRangeException (nameof (elementIndex), "Index out of array bound."); + void* pointer = Unsafe.Add ((void*)storage.Data, elementIndex); + return new MemoryHandle (pointer, default, this); + } + } + + /// + /// Lets the garbage collector know that the object is free to be moved now. + /// + public override void Unpin () + { + storage.Free (); + } + + protected override void Dispose (bool disposing) + { + if (disposing) + { + storage.Free (); + } + } + } + + private readonly object inner; + + /// + /// Property returning the inner TorchSharp tensor the class is wrapping. + /// + public DoubleTensor TorchSharpTensor => inner as DoubleTensor; + + public DoubleTorchTensor (Memory memory, ReadOnlySpan dimensions, DoubleTensor inner) : base (memory, dimensions) + { + this.inner = inner; + } + + /// + /// Utility method to create a TorchTensor. + /// This is currently failing if the input parameter is empty because SNT + /// does not support zero-size tensors. + /// + /// The desired sizes for the dimensions of the tensor. + public static DoubleTorchTensor Create (params int[] sizes) + { + var totLength = Utils.GetTotalLength (sizes); + var shape = sizes; + + if (sizes.Length == 0) + { + shape = new int[] { 0 }; + } + + var inner = CreateDoubleTensor (sizes.Select (x => (long)x).ToArray ()); + var storage = inner.Storage; + storage.Retain (); + var mem = new DoubleNativeMemory (storage); + + return new DoubleTorchTensor (mem.Memory, shape, inner); + } + + public void Dispose () + { + var typedInner = inner as DoubleTensor; + typedInner.Dispose (); + } + + /// + /// Creates a shallow copy of this tensor, with new backing storage. + /// + /// A shallow copy of this tensor. + public override Tensor Clone () + { + var typedInner = inner as DoubleTensor; + var innerClone = typedInner.Clone (); + var storage = innerClone.Storage; + storage.Retain (); + var mem = new DoubleNativeMemory (storage); + + return new DoubleTorchTensor (mem.Memory, Dimensions, innerClone); + } + + /// + /// Creates a new Tensor of a different type with the specified dimensions and the same layout as this tensor with elements initialized to their default value. + /// + /// Type contained in the returned Tensor. + /// An span of integers that represent the size of each dimension of the DenseTensor to create. + /// A new tensor with the same layout as this tensor but different type and dimensions. + public override Tensor CloneEmpty (ReadOnlySpan dimensions) + { + var typedInner = inner as DoubleTensor; + + switch (true) + { + case bool _ when typeof (TResult) == typeof (double): + var innerClone = CreateDoubleTensor (typedInner.Shape); + innerClone.Fill (default); + var mem = new DoubleNativeMemory (innerClone.Storage); + + return new DoubleTorchTensor (mem.Memory, Dimensions, innerClone) as Tensor; + default: throw new NotImplementedException ("Only cloning doubles is currently implemented."); + } + } + + /// + /// Reshapes the current tensor to new dimensions, using the same backing storage. + /// + /// An span of integers that represent the size of each dimension of the DenseTensor to create. + /// A new tensor that reinterprets backing Buffer of this tensor with different dimensions. + public override Tensor Reshape (ReadOnlySpan dimensions) + { + if (dimensions.Length == 0) + { + throw new ArgumentException ("Dimensions must contain elements.", nameof (dimensions)); + } + + var newSize = Utils.GetTotalLength (dimensions); + + if (newSize != Length) + { + throw new ArgumentException ($"Cannot reshape array due to mismatch in lengths, currently {Length} would become {newSize}.", nameof(dimensions)); + } + + var typedInner = inner as DoubleTensor; + DoubleTensor reshapedTensor; + + switch (dimensions.Length) + { + case 1: + reshapedTensor = typedInner.NewWithStorage1d (UIntPtr.Zero, dimensions[0], 1); + break; + case 2: + reshapedTensor = typedInner.NewWithStorage2d (UIntPtr.Zero, dimensions[0], dimensions[1], dimensions[1], 1); + break; + default: throw new ArgumentException ($"Cannot reshape tensor with more than 4 dimensions"); + } + + return new DoubleTorchTensor (Buffer, dimensions, reshapedTensor); + } + + /// + /// Creates a 1-4D tensor of the specified size(s). + /// + /// Sizes for the dimensions. + internal static DoubleTensor CreateDoubleTensor (params long[] dims) + { + switch (dims.Length) + { + case 0: + return new DoubleTensor (); + case 1: + return new DoubleTensor (dims[0]); + case 2: + return new DoubleTensor (dims[0], dims[1]); + case 3: + return new DoubleTensor (dims[0], dims[1], dims[2]); + case 4: + return new DoubleTensor (dims[0], dims[1], dims[2], dims[3]); + default: + throw new ArgumentOutOfRangeException (nameof (dims), "Maximum number of dimensions for tensor creation is 4."); + } + } + } + + /// + /// Wrapper class used to surface a Torch FloatTensor as a System.Numerics DensorTensor of float + /// + public sealed class FloatTorchTensor : DenseTensor, IDisposable + { + internal sealed class FloatNativeMemory : MemoryManager + { + private readonly FloatTensor.FloatStorage storage; + + public FloatNativeMemory(FloatTensor.FloatStorage storage) + { + this.storage = storage; + + if (storage.Size () < 0) + { + throw new ArgumentOutOfRangeException ("Length cannot be negative."); + } + } + + /// + /// Returns a span wrapping the underlying memory. + /// Remember to Unpin the memory once the span is disposed. + /// + public override Span GetSpan () + { + ulong len = storage.Size (); + + if (len > int.MaxValue) + { + throw new InvalidCastException ("Tensor size not supported."); + } + + unsafe + { + return new Span (storage.Data.ToPointer (), (int)len); + } + } + + /// + /// Returns a handle to the memory that has been pinned and hence its address can be taken. + /// + /// The offset to the element within the memory at which the returned points to. (default = 0) + public override MemoryHandle Pin (int elementIndex = 0) + { + unsafe + { + storage.Retain(); + if ((uint)elementIndex > storage.Size ()) throw new ArgumentOutOfRangeException (nameof (elementIndex), "Index out of array bound."); + void* pointer = Unsafe.Add ((void*)storage.Data, elementIndex); + return new MemoryHandle (pointer, default, this); + } + } + + /// + /// Lets the garbage collector know that the object is free to be moved now. + /// + public override void Unpin () + { + storage.Free (); + } + + protected override void Dispose (bool disposing) + { + if (disposing) + { + storage.Free (); + } + } + } + + private readonly object inner; + + /// + /// Property returning the inner TorchSharp tensor the class is wrapping. + /// + public FloatTensor TorchSharpTensor => inner as FloatTensor; + + public FloatTorchTensor (Memory memory, ReadOnlySpan dimensions, FloatTensor inner) : base (memory, dimensions) + { + this.inner = inner; + } + + /// + /// Utility method to create a TorchTensor. + /// This is currently failing if the input parameter is empty because SNT + /// does not support zero-size tensors. + /// + /// The desired sizes for the dimensions of the tensor. + public static FloatTorchTensor Create (params int[] sizes) + { + var totLength = Utils.GetTotalLength (sizes); + var shape = sizes; + + if (sizes.Length == 0) + { + shape = new int[] { 0 }; + } + + var inner = CreateFloatTensor (sizes.Select (x => (long)x).ToArray ()); + var storage = inner.Storage; + storage.Retain (); + var mem = new FloatNativeMemory (storage); + + return new FloatTorchTensor (mem.Memory, shape, inner); + } + + public void Dispose () + { + var typedInner = inner as FloatTensor; + typedInner.Dispose (); + } + + /// + /// Creates a shallow copy of this tensor, with new backing storage. + /// + /// A shallow copy of this tensor. + public override Tensor Clone () + { + var typedInner = inner as FloatTensor; + var innerClone = typedInner.Clone (); + var storage = innerClone.Storage; + storage.Retain (); + var mem = new FloatNativeMemory (storage); + + return new FloatTorchTensor (mem.Memory, Dimensions, innerClone); + } + + /// + /// Creates a new Tensor of a different type with the specified dimensions and the same layout as this tensor with elements initialized to their default value. + /// + /// Type contained in the returned Tensor. + /// An span of integers that represent the size of each dimension of the DenseTensor to create. + /// A new tensor with the same layout as this tensor but different type and dimensions. + public override Tensor CloneEmpty (ReadOnlySpan dimensions) + { + var typedInner = inner as FloatTensor; + + switch (true) + { + case bool _ when typeof (TResult) == typeof (float): + var innerClone = CreateFloatTensor (typedInner.Shape); + innerClone.Fill (default); + var mem = new FloatNativeMemory (innerClone.Storage); + + return new FloatTorchTensor (mem.Memory, Dimensions, innerClone) as Tensor; + default: throw new NotImplementedException ("Only cloning floats is currently implemented."); + } + } + + /// + /// Reshapes the current tensor to new dimensions, using the same backing storage. + /// + /// An span of integers that represent the size of each dimension of the DenseTensor to create. + /// A new tensor that reinterprets backing Buffer of this tensor with different dimensions. + public override Tensor Reshape (ReadOnlySpan dimensions) + { + if (dimensions.Length == 0) + { + throw new ArgumentException ("Dimensions must contain elements.", nameof (dimensions)); + } + + var newSize = Utils.GetTotalLength (dimensions); + + if (newSize != Length) + { + throw new ArgumentException ($"Cannot reshape array due to mismatch in lengths, currently {Length} would become {newSize}.", nameof(dimensions)); + } + + var typedInner = inner as FloatTensor; + FloatTensor reshapedTensor; + + switch (dimensions.Length) + { + case 1: + reshapedTensor = typedInner.NewWithStorage1d (UIntPtr.Zero, dimensions[0], 1); + break; + case 2: + reshapedTensor = typedInner.NewWithStorage2d (UIntPtr.Zero, dimensions[0], dimensions[1], dimensions[1], 1); + break; + default: throw new ArgumentException ($"Cannot reshape tensor with more than 4 dimensions"); + } + + return new FloatTorchTensor (Buffer, dimensions, reshapedTensor); + } + + /// + /// Creates a 1-4D tensor of the specified size(s). + /// + /// Sizes for the dimensions. + internal static FloatTensor CreateFloatTensor (params long[] dims) + { + switch (dims.Length) + { + case 0: + return new FloatTensor (); + case 1: + return new FloatTensor (dims[0]); + case 2: + return new FloatTensor (dims[0], dims[1]); + case 3: + return new FloatTensor (dims[0], dims[1], dims[2]); + case 4: + return new FloatTensor (dims[0], dims[1], dims[2], dims[3]); + default: + throw new ArgumentOutOfRangeException (nameof (dims), "Maximum number of dimensions for tensor creation is 4."); + } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource mem of type Torch.SNT.LongTorchTensor$LongNativeMemory, Leaked resource (output of Torch.SNT.LongTorchTensor::.ctor() at Line 782) of type Torch.SNT.LongTorchTensor, Leaked resource (returned from TorchSharp.LongTensor$LongStorage TorchSharp.LongTensor::get_Storage() at Line 780) of type TorchSharp.LongTensor$LongStorage in method "Tensor`1 LongTorchTensor.CloneEmpty(ReadOnlySpan`1)". + +### Severity: +ERROR + +### Procedure: +Tensor`1 LongTorchTensor.CloneEmpty(ReadOnlySpan`1) + +### File: +SNT/TypeGenerator.cs + +### Key: +TypeGenerator.cs|CloneEmpty|DOTNET_RESOURCE_LEAK + +### Hash: +6183cc1eaf81c39db949d4a1166e88c6 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2317/instruction.md b/inferredbugs-2317/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fa3a751c41990ba02deb22cdb0dbf5fc10988d96 --- /dev/null +++ b/inferredbugs-2317/instruction.md @@ -0,0 +1,375 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** TorchSharp +**Bug ID:** 19 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TorchSharp.Tensor; + +namespace TorchSharp.Test +{ + [TestClass] + public class TorchSharp + { + [TestMethod] + public void CreateFloatTensorOnes() + { + var ones = FloatTensor.Ones(new long[] { 2, 2 }); + Assert.IsNotNull(ones); + } + + [TestMethod] + public void CreateFloatTensorOnesCheckData() + { + unsafe + { + var ones = FloatTensor.Ones(new long[] { 2, 2 }); + var data = ones.Data; + + for (int i = 0; i < 4; i++) + { + Assert.AreEqual(data[i], 1.0); + } + } + } + + [TestMethod] + public void CreateIntTensorOnesCheckData() + { + unsafe + { + var ones = IntTensor.Ones(new long[] { 2, 2 }); + var data = ones.Data; + + for (int i = 0; i < 4; i++) + { + Assert.AreEqual(data[i], 1); + } + } + } + + [TestMethod] + public void ScoreModel() + { + var ones = FloatTensor.Ones(new long[] { 1, 3, 224, 224 }); + Assert.IsNotNull(ones); + + var module = JIT.Module.Load(@"E:\Source\Repos\libtorch\model.pt"); + Assert.IsNotNull(module); + + var result = module.Forward(ones); + Assert.IsNotNull(result); + } + + [TestMethod] + public void CreateLinear() + { + var lin = NN.Module.Linear(1000, 100); + Assert.IsNotNull(lin); + var modules = lin.GetName(); + } + + [TestMethod] + public void CreateRelu() + { + var rel = NN.Module.Relu(); + Assert.IsNotNull(rel); + var modules = rel.GetName(); + } + + [TestMethod] + public void CreateSequence() + { + var lin1 = NN.Module.Linear(1000, 100); + var lin2 = NN.Module.Linear(100, 10); + var seq = NN.Module.Sequential(lin1, NN.Module.Relu(), lin2); + var modules = seq.GetModules(); + } + + [TestMethod] + public void EvalSequence() + { + var lin1 = NN.Module.Linear(1000, 100); + var lin2 = NN.Module.Linear(100, 10); + var seq = NN.Module.Sequential(lin1, NN.Module.Relu(), lin2); + + var x = FloatTensor.RandomN(new long[] { 64, 1000 }, device: "cpu:0", requiresGrad: true); + var eval = seq.Forward(x); + Assert.IsNotNull(eval); + } + + [TestMethod] + public void EvalLossSequence() + { + var lin1 = NN.Module.Linear(1000, 100); + var lin2 = NN.Module.Linear(100, 10); + var seq = NN.Module.Sequential(lin1, NN.Module.Relu(), lin2); + + var x = FloatTensor.RandomN(new long[] { 64, 1000 }, device: "cpu:0"); + var y = FloatTensor.RandomN(new long[] { 64, 10 }, device: "cpu:0"); + + var eval = seq.Forward(x); + var loss = NN.LossFunction.MSE(eval, y, NN.Reduction.None); + + var result = loss.Item; + Assert.IsNotNull(result); + } + + [TestMethod] + public void TestZeroGrad() + { + var lin1 = NN.Module.Linear(1000, 100); + var lin2 = NN.Module.Linear(100, 10); + var seq = NN.Module.Sequential(lin1, NN.Module.Relu(), lin2); + + seq.ZeroGrad(); + } + + [TestMethod] + public void TestBackward() + { + var lin1 = NN.Module.Linear(1000, 100); + var lin2 = NN.Module.Linear(100, 10); + var seq = NN.Module.Sequential(lin1, NN.Module.Relu(), lin2); + + var x = FloatTensor.RandomN(new long[] { 64, 1000 }, device: "cpu:0"); + var y = FloatTensor.RandomN(new long[] { 64, 10 }, device: "cpu:0"); + + var eval = seq.Forward(x); + var loss = NN.LossFunction.MSE(eval, y, NN.Reduction.None); + + seq.ZeroGrad(); + + loss.Backward(); + } + + [TestMethod] + public void TestGettingParameters() + { + var lin1 = NN.Module.Linear(1000, 100); + var lin2 = NN.Module.Linear(100, 10); + var seq = NN.Module.Sequential(lin1, NN.Module.Relu(), lin2); + + var x = FloatTensor.RandomN(new long[] { 64, 1000 }, device: "cpu:0"); + var y = FloatTensor.RandomN(new long[] { 64, 10 }, device: "cpu:0"); + + var eval = seq.Forward(x); + var loss = NN.LossFunction.MSE(eval, y, NN.Reduction.None); + + seq.ZeroGrad(); + + loss.Backward(); + + foreach (var parm in seq.Parameters()) + { + Assert.IsNotNull(parm); + } + } + + [TestMethod] + public void TestGrad() + { + var lin1 = NN.Module.Linear(1000, 100); + var lin2 = NN.Module.Linear(100, 10); + var seq = NN.Module.Sequential(lin1, NN.Module.Relu(), lin2); + + var x = FloatTensor.RandomN(new long[] { 64, 1000 }, device: "cpu:0"); + var y = FloatTensor.RandomN(new long[] { 64, 10 }, device: "cpu:0"); + + var eval = seq.Forward(x); + var loss = NN.LossFunction.MSE(eval, y, NN.Reduction.None); + + seq.ZeroGrad(); + + loss.Backward(); + + foreach (var parm in seq.Parameters()) + { + var grad = parm.Grad(); + Assert.IsNotNull(grad); + } + } + + [TestMethod] + public void TestSubInPlace() + { + var x = IntTensor.Ones(new long[] { 100, 100 }); + var y = IntTensor.Ones(new long[] { 100, 100 }); + + var z = x.SubInPlace(y); + + var zdata = z.Data; + var xdata = x.Data; + + for (int i = 0; i < 100; i++) + { + for (int j = 0; j < 100; j++) + { + Assert.AreEqual(zdata[i + j], xdata[i + j]); + } + } + } + + [TestMethod] + public void TestMul() + { + var x = FloatTensor.Ones(new long[] { 100, 100 }); + + var y = x.Mul(0.5f); + + var ydata = y.Data; + var xdata = x.Data; + + for (int i = 0; i < 100; i++) + { + for (int j = 0; j < 100; j++) + { + Assert.AreEqual(ydata[i + j], xdata[i + j] * 0.5f); + } + } + } + + /// + /// Fully connected Relu net with one hidden layer trained using gradient descent. + /// Taken from . + /// + [TestMethod] + public void TestTraining() + { + var lin1 = NN.Module.Linear(1000, 100); + var lin2 = NN.Module.Linear(100, 10); + var seq = NN.Module.Sequential(lin1, NN.Module.Relu(), lin2); + + var x = FloatTensor.RandomN(new long[] { 64, 1000 }, device: "cpu:0"); + var y = FloatTensor.RandomN(new long[] { 64, 10 }, device: "cpu:0"); + + float learning_rate = 0.00004f; + float prevLoss = float.MaxValue; + + for (int i = 0; i < 10; i++) + { + var eval = seq.Forward(x); + var loss = NN.LossFunction.MSE(eval, y, NN.Reduction.None); + var lossVal = loss.Item; + + Assert.IsTrue(lossVal < prevLoss); + prevLoss = lossVal; + + seq.ZeroGrad(); + + loss.Backward(); + + // using(var noGrad = NN.NoGrad()) + // The operators Mul and SubInPlace have no_grad=true by default + foreach (var param in seq.Parameters()) + { + var grad = param.Grad(); + var update = grad.Mul(learning_rate); + param.SubInPlace(update); + } + } + } + + [TestMethod] + public void TestAdam() + { + var lin1 = NN.Module.Linear(1000, 100); + var lin2 = NN.Module.Linear(100, 10); + var seq = NN.Module.Sequential(lin1, NN.Module.Relu(), lin2); + + double learning_rate = 0.00001; + + var optimizer = NN.Optimizer.Adam(seq, learning_rate); + + Assert.IsNotNull(optimizer); + } + + /// + /// Fully connected Relu net with one hidden layer trained using Adam optimizer. + /// Taken from . + /// + [TestMethod] + public void TestTrainingAdam() + { + var lin1 = NN.Module.Linear(1000, 100); + var lin2 = NN.Module.Linear(100, 10); + var seq = NN.Module.Sequential(lin1, NN.Module.Relu(), lin2); + + var x = FloatTensor.RandomN(new long[] { 64, 1000 }, device: "cpu:0"); + var y = FloatTensor.RandomN(new long[] { 64, 10 }, device: "cpu:0"); + + double learning_rate = 0.00004f; + float prevLoss = float.MaxValue; + var optimizer = NN.Optimizer.Adam(seq, learning_rate); + + for (int i = 0; i < 10; i++) + { + var eval = seq.Forward(x); + var loss = NN.LossFunction.MSE(eval, y, NN.Reduction.Sum); + var lossVal = loss.Item; + + Assert.IsTrue(lossVal < prevLoss); + prevLoss = lossVal; + + optimizer.ZeroGrad(); + + loss.Backward(); + + optimizer.Step(); + } + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource optimizer.TorchSharp.NN.Optimizer.handle of type TorchSharp.NN.Optimizer$HType, Leaked resource seq of type TorchSharp.NN.Sequential, Leaked resource n$2.[_] of type TorchSharp.NN.Linear in method "Void TorchSharp.TestTrainingAdam()". + +### Severity: +ERROR + +### Procedure: +Void TorchSharp.TestTrainingAdam() + +### File: +Test/TorchSharp.cs + +### Key: +TorchSharp.cs|TestTrainingAdam|DOTNET_RESOURCE_LEAK + +### Hash: +3c99149e1aeae277795dca3500bcff04 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2402/instruction.md b/inferredbugs-2402/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a8b6609e8c1c63b306cc17a7efb70ca6a521a436 --- /dev/null +++ b/inferredbugs-2402/instruction.md @@ -0,0 +1,736 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** i18n +**Bug ID:** 12 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Web; +using System.Web.Caching; +using System.Web.Hosting; +using i18n.Domain.Abstract; +using i18n.Domain.Entities; +using i18n.Helpers; + +namespace i18n.Domain.Concrete +{ + public class POTranslationRepository : ITranslationRepository + { + private i18nSettings _settings; + + public POTranslationRepository(i18nSettings settings) + { + _settings = settings; + } + + #region load and getters + + public Translation GetTranslation(string langtag) + { + return ParseTranslationFile(langtag); + } + + + /// + /// Checks in first hand settings file, if not found there it checks file structure + /// + /// List of available languages + public IEnumerable GetAvailableLanguages() + { + //todo: ideally we want to fill the other data in the Language object so this is usable by project incorporating i18n that they can simply lookup available languages. Maybe we even add a country property so that it's easier for projects to add corresponding flags. + + List languages = _settings.AvailableLanguages.ToList(); + Language lang; + List dirList = new List(); + + + //This means there was no languages from settings + if (languages.Count == 0 + || (languages.Count == 1 && languages[0] == "")) + { + //We instead check for file structure + DirectoryInfo di = new DirectoryInfo(GetAbsoluteLocaleDir()); + + foreach (var dir in di.EnumerateDirectories().Select(x => x.Name)) + { + lang = new Language(); + lang.LanguageShortTag = dir; + dirList.Add(lang); + } + } + else + { + //see if the desired language was one of the returned from settings + foreach (var language in languages) + { + lang = new Language(); + lang.LanguageShortTag = language; + dirList.Add(lang); + } + } + + return dirList; + + } + + /// + /// Checks if the language is set as supported in config file + /// If not it checks if the PO file is available + /// + /// The tag for which you want to check if support exists. For instance "sv-SE" + /// True if language exists, otherwise false + public bool TranslationExists(string langtag) + { + List languages = _settings.AvailableLanguages.ToList(); + + //This means there was no languages from settings + if (languages.Count == 0 + || (languages.Count == 1 && languages[0] == "")) + { + //We instead check if the file exists + return File.Exists(GetPathForLanguage(langtag)); + } + else + { + //see if the desired language was one of the returned from settings + foreach (var language in languages) + { + if (language == langtag) + { + return true; + } + } + } + + //did not exist in settings nor as file, we return false + return false; + } + + public CacheDependency GetCacheDependencyForSingleLanguage(string langtag) + { + var path = GetPathForLanguage(langtag); + if (!File.Exists(path)) { + return null; } + return new CacheDependency(path); + } + + public CacheDependency GetCacheDependencyForAllLanguages() + { + return new FsCacheDependency(GetAbsoluteLocaleDir()); + } + + #endregion + + #region save + + /// + /// Saves a translation into file with standard pattern locale/langtag/message.po + /// Also saves a backup of previous version + /// + /// The translation you wish to save. Must have Language shortag filled out. + public void SaveTranslation(Translation translation) + { + string filePath = GetPathForLanguage(translation.LanguageInformation.LanguageShortTag); + string backupPath = GetPathForLanguage(translation.LanguageInformation.LanguageShortTag) + ".backup"; + + if (File.Exists(filePath)) //we backup one version. more advanced backup solutions could be added here. + { + if (File.Exists(backupPath)) + { + File.Delete(backupPath); + } + System.IO.File.Move(filePath, backupPath); + } + + if (File.Exists(filePath)) //we make sure the old file is removed first + { + File.Delete(filePath); + } + + bool hasReferences = false; + + if (!File.Exists(filePath)) + { + var fileInfo = new FileInfo(filePath); + var dirInfo = new DirectoryInfo(Path.GetDirectoryName(filePath)); + if (!dirInfo.Exists) + { + dirInfo.Create(); + } + fileInfo.Create().Close(); + } + + using (StreamWriter stream = new StreamWriter(filePath)) + { + // Establish ordering of items in PO file. + var orderedItems = translation.Items.Values + .OrderBy(x => x.References == null || x.References.Count() == 0) + // Non-orphan items before orphan items. + .ThenBy(x => x.MsgKey); + // Then order alphanumerically. + // + + //This is required for poedit to read the files correctly if they contains for instance swedish characters + stream.WriteLine("msgid \"\""); + stream.WriteLine("msgstr \"\""); + stream.WriteLine("\"Content-Type: text/plain; charset=utf-8\\n\""); + stream.WriteLine(); + + foreach (var item in orderedItems) + { + hasReferences = false; + + if (item.TranslatorComments != null) + { + foreach (var translatorComment in item.TranslatorComments) + { + stream.WriteLine("# " + translatorComment); + } + } + + if (item.ExtractedComments != null) + { + foreach (var extractedComment in item.ExtractedComments) + { + stream.WriteLine("#. " + extractedComment); + } + } + + if (item.References != null) + { + foreach (var reference in item.References) + { + hasReferences = true; + stream.WriteLine("#: " + reference); + } + } + + if (item.Flags != null) + { + foreach (var flag in item.Flags) + { + stream.WriteLine("#, " + flag); + } + } + + string prefix = hasReferences ? "" : prefix = "#~ "; + + if (_settings.MessageContextEnabledFromComment + && item.ExtractedComments != null + && item.ExtractedComments.Count() != 0) { + WriteString(stream, hasReferences, "msgctxt", item.ExtractedComments.First()); + } + + WriteString(stream, hasReferences, "msgid", item.MsgId); + WriteString(stream, hasReferences, "msgstr", escape(item.Message)); + + stream.WriteLine(""); + } + } + } + + /// + /// Saves a template file which is a all strings (needing translation) used in the entire project. Not language dependent + /// + /// A list of template items to save. The list should be all template items for the entire project. + public void SaveTemplate(IDictionary items) + { + string filePath = GetAbsoluteLocaleDir() + "/messages.pot"; + string backupPath = filePath + ".backup"; + + if (File.Exists(filePath)) //we backup one version. more advanced backup solutions could be added here. + { + if (File.Exists(backupPath)) + { + File.Delete(backupPath); + } + System.IO.File.Move(filePath, backupPath); + } + + if (File.Exists(filePath)) //we make sure the old file is removed first + { + File.Delete(filePath); + } + + if (! File.Exists(filePath)) + { + var fileInfo = new FileInfo(filePath); + var dirInfo = new DirectoryInfo(Path.GetDirectoryName(filePath)); + if (! dirInfo.Exists) + { + dirInfo.Create(); + } + fileInfo.Create().Close(); + } + + using (StreamWriter stream = new StreamWriter(filePath)) + { + // Establish ordering of items in PO file. + var orderedItems = items.Values + .OrderBy(x => x.References == null || x.References.Count() == 0) + // Non-orphan items before orphan items. + .ThenBy(x => x.MsgKey); + // Then order alphanumerically. + // + + //This is required for poedit to read the files correctly if they contains for instance swedish characters + stream.WriteLine("msgid \"\""); + stream.WriteLine("msgstr \"\""); + stream.WriteLine("\"Content-Type: text/plain; charset=utf-8\\n\""); + stream.WriteLine(); + + foreach (var item in orderedItems) + { + if (item.Comments != null) + { + foreach (var comment in item.Comments) + { + stream.WriteLine("#. " + comment); + } + } + + foreach (var reference in item.References) + { + stream.WriteLine("#: " + reference); + } + + stream.WriteLine("msgid \"" + escape(item.MsgId) + "\""); + stream.WriteLine("msgstr \"\""); // enable loading of POT file into editor e.g. PoEdit. + stream.WriteLine(""); + } + } + } + + #endregion + + #region helpers + + /// + /// Gets the locale directory from settings and makes sure it is translated into absolut path + /// + /// the locale directory in absolute path + private string GetAbsoluteLocaleDir() + { + return _settings.LocaleDirectory; + } + + private string GetPathForLanguage(string langtag) + { + return Path.Combine(GetAbsoluteLocaleDir(), langtag, "messages.po"); + } + + /// + /// Parses a PO file into a Language object + /// + /// The language (tag) you wish to load into Translation object + /// A complete translation object with all all translations and language values set. + private Translation ParseTranslationFile(string langtag) + { + //todo: consider that lines we don't understand like headers from poedit and #| should be preserved and outputted again. + + Translation translation = new Translation(); + Language language = new Language(); + language.LanguageShortTag = langtag; + translation.LanguageInformation = language; + var items = new ConcurrentDictionary(); + + string path = GetPathForLanguage(langtag); + + if (File.Exists(path)) { + + using (var fs = File.OpenText(path)) + { + // http://www.gnu.org/s/hello/manual/gettext/PO-Files.html + + string line; + bool itemStarted = false; + while ((line = fs.ReadLine()) != null) + { + List extractedComments = new List(); + List translatorComments = new List(); + List flags = new List(); + List references = new List(); + + //read all comments, flags and other descriptive items for this string + //if we have #~ its a historical/log entry but it is the messageID/message so we skip this do/while + if (line.StartsWith("#") && !line.StartsWith("#~")) + { + do + { + itemStarted = true; + switch (line[1]) + { + case '.': //Extracted comments + extractedComments.Add(line.Substring(2).Trim()); + break; + case ':': //references + references.Add(line.Substring(2).Trim()); + break; + case ',': //flags + flags.Add(line.Substring(2).Trim()); + break; + case '|': //msgid previous-untranslated-string - NOT used by us + break; + default: //translator comments + translatorComments.Add(line.Substring(1).Trim()); + break; + } + + } while ((line = fs.ReadLine()) != null && line.StartsWith("#")); + } + + if (itemStarted || line.StartsWith("#~")) + { + TranslationItem item = ParseBody(fs, line, extractedComments); + + if (item != null) { + // + item.TranslatorComments = translatorComments; + item.ExtractedComments = extractedComments; + item.Flags = flags; + item.References = references; + // + items.AddOrUpdate( + item.MsgKey, + // Add routine. + k => { + return item; + }, + // Update routine. + (k, v) => { + v.References = v.References.Append(item.References); + v.ExtractedComments = v.ExtractedComments.Append(item.References); + v.TranslatorComments = v.TranslatorComments.Append(item.References); + v.Flags = v.Flags.Append(item.References); + return v; + }); + } + } + + itemStarted = false; + } + } + } + translation.Items = items; + return translation; + } + + /// + /// Removes the preceding characters in a file showing that an item is historical/log. That is to say it has been removed from the project. We don't need care about the character as the fact that it lacks references is what tells us it's a log item + /// + /// + /// + private string RemoveCommentIfHistorical(string line) + { + if (string.IsNullOrWhiteSpace(line)) + { + return null; + } + + if (line.StartsWith("#~")) + { + return line.Replace("#~", "").Trim(); + } + + return line; + } + + /// + /// Parses the body of a PO file item. That is to say the message id and the message itself. + /// Reason for why it must be on second line (textreader) is so that you can read until you have read to far without peek previously for meta data. + /// + /// A textreader that must be on the second line of a message body + /// The first line of the message body. + /// Returns a TranslationItem with only key, id and message set + private TranslationItem ParseBody(TextReader fs, string line, List extractedComments) + { + string originalLine = line; + + if (string.IsNullOrEmpty(line)) { + return null; } + + TranslationItem message = new TranslationItem { MsgKey = "" }; + StringBuilder sb = new StringBuilder(); + + string msgctxt = null; + line = RemoveCommentIfHistorical(line); //so that we read in removed historical records too + if (line.StartsWith("msgctxt")) + { + msgctxt = Unquote(line); + line = fs.ReadLine(); + } + + line = RemoveCommentIfHistorical(line); //so that we read in removed historical records too + if (line.StartsWith("msgid")) + { + var msgid = Unquote(line); + sb.Append(msgid); + + while ((line = fs.ReadLine()) != null) + { + line = RemoveCommentIfHistorical(line); + if (String.IsNullOrEmpty(line)) + { + Console.WriteLine("ERROR - line is empty. Original line: " + originalLine); + } + if (!line.StartsWith("msgstr") && (msgid = Unquote(line)) != null) + { + sb.Append(msgid); + } + else + { + break; + } + } + + message.MsgId = Unescape(sb.ToString()); + + // If no msgctxt is set then msgkey is the msgid; otherwise it is msgid+msgctxt. + message.MsgKey = string.IsNullOrEmpty(msgctxt) ? + message.MsgId: + TemplateItem.KeyFromMsgidAndComment(message.MsgId, msgctxt, true); + } + + sb.Clear(); + line = RemoveCommentIfHistorical(line); + if (!string.IsNullOrEmpty(line) && line.StartsWith("msgstr")) + { + var msgstr = Unquote(line); + sb.Append(msgstr); + + while ((line = fs.ReadLine()) != null && (msgstr = Unquote(line)) != null) + { + line = RemoveCommentIfHistorical(line); + sb.Append(msgstr); + } + + message.Message = Unescape(sb.ToString()); + } + return message; + } + + /// + /// Helper for writing either a msgid or msgstr to the po file. + /// + /// + /// + /// "msgid" or "msgstr" + /// + private static void WriteString(StreamWriter stream, bool hasReferences, string type, string value) + { + // Logic for outputting multi-line msgid. + // + // IN : ab + // OUT: msgid "a\n" + // msgid "b" + // + // IN : ab + // OUT: msgid "a\n" + // msgid "b\n" + // + string prefix = hasReferences ? "" : prefix = "#~ "; + value = value ?? ""; + value = value.Replace("\r\n", "\n"); + string[] lines = value.Split('\n'); + if (lines.Length > 1) { + stream.WriteLine(string.Format("{0}{1} \"\"", prefix, type)); + for (int i = 0; i < lines.Length; ++i) { + string m = lines[i]; + bool last = i == lines.Length -1; + if (m.Length != 0) { + stream.WriteLine(string.Format("\"{0}{1}\"", m, last ? "" : "\\n")); + } + } + } + else { + stream.WriteLine(string.Format("{0}{1} \"{2}\"", prefix, type, value)); + } + } + + #region quoting and escaping + + //this method removes anything before the first quote and also removes first and last quote + private string Unquote(string lhs, string quotechar = "\"") + { + int begin = lhs.IndexOf(quotechar); + if (begin == -1) + { + return null; + } + int end = lhs.LastIndexOf(quotechar); + if (end <= begin) + { + return null; + } + return lhs.Substring(begin + 1, end - begin - 1); + } + + private string escape(string s) + { + if (string.IsNullOrWhiteSpace(s)) + { + return null; + } + return s.Replace("\"", "\\\""); + } + + /// + /// Looks up in the subject string standard C escape sequences and converts them + /// to their actual character counterparts. + /// + /// + private string Unescape(string s) + { + Regex regex_unescape = new Regex("\\\\[abfnrtv?\"'\\\\]|\\\\[0-3]?[0-7]{1,2}|\\\\u[0-9a-fA-F]{4}|.", RegexOptions.Singleline); + + StringBuilder sb = new StringBuilder(); + MatchCollection mc = regex_unescape.Matches(s, 0); + + foreach (Match m in mc) + { + if (m.Length == 1) + { + sb.Append(m.Value); + } + else + { + if (m.Value[1] >= '0' && m.Value[1] <= '7') + { + int i = 0; + + for (int j = 1; j < m.Length; j++) + { + i *= 8; + i += m.Value[j] - '0'; + } + + sb.Append((char)i); + } + else if (m.Value[1] == 'u') + { + int i = 0; + + for (int j = 2; j < m.Length; j++) + { + i *= 16; + + if (m.Value[j] >= '0' && m.Value[j] <= '9') + { + i += m.Value[j] - '0'; + } + else if (m.Value[j] >= 'A' && m.Value[j] <= 'F') + { + i += m.Value[j] - 'A' + 10; + } + else if (m.Value[j] >= 'a' && m.Value[j] <= 'a') + { + i += m.Value[j] - 'a' + 10; + } + } + + sb.Append((char)i); + } + else + { + switch (m.Value[1]) + { + case 'a': + sb.Append('\a'); + break; + case 'b': + sb.Append('\b'); + break; + case 'f': + sb.Append('\f'); + break; + case 'n': + sb.Append('\n'); + break; + case 'r': + sb.Append('\r'); + break; + case 't': + sb.Append('\t'); + break; + case 'v': + sb.Append('\v'); + break; + default: + sb.Append(m.Value[1]); + break; + } + } + } + } + + return sb.ToString(); + } + + #endregion + + #endregion + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `line` last assigned on line 457 could be null and is dereferenced at line 458, column 4. + +### Severity: +ERROR + +### Procedure: +TranslationItem POTranslationRepository.ParseBody(TextReader,String,List`1) + +### File: +src/i18n.Domain/Concrete/POTranslationRepository.cs + +### Key: +POTranslationRepository.cs|ParseBody|NULL_DEREFERENCE + +### Node Key: +90535029835413c6e5d1bdebbf52bdf9 + +### Hash: +0a6f568fc8923f33b510e1c243325c94 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2403/instruction.md b/inferredbugs-2403/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7dbe505e4107bcd593c39e0c037d45b0cf6f233f --- /dev/null +++ b/inferredbugs-2403/instruction.md @@ -0,0 +1,588 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** i18n +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using i18n.Domain.Abstract; +using i18n.Domain.Entities; +using i18n.Helpers; + +namespace i18n.Domain.Concrete +{ + public class POTranslationRepository : ITranslationRepository + { + private i18nSettings _settings; + + public POTranslationRepository(i18nSettings settings) + { + _settings = settings; + } + + #region load + +/*MC001 + /// + /// Retrieves a language queryable for use with LINQ. + /// This does not take care of thread safety. + /// + /// The languagetag to get the language for + /// Queryable translate items for use with LINQ + public IQueryable GetLanguageItems(string tag) + { + Translation translation = ParseTranslationFile(tag); + return translation.Items.AsQueryable(); + } +*/ + + public Translation GetLanguage(string tag) + { + return ParseTranslationFile(tag); + } + +/*MC001 + public ConcurrentDictionary GetLanguageDictionary(string tag) + { + ConcurrentDictionary messages = new ConcurrentDictionary(); + + //todo: instead of always calling ParseTranslationFile here we could cache the translation and just read from there. If we want to do that the ITranslationRepository needs to add a ReleaseCache or similar for when the file has been changed. + Translation translation = ParseTranslationFile(tag); + + + // Only if a msgstr (translation) is provided for this entry do we add an entry to the cache. + // This conditions facilitates more useful operation of the IsLanguageValid method, + // which prior to this condition was indicating a language was available when in fact there + // were zero translation in the PO file (it having been autogenerated during gettext merge). + foreach (TranslateItem item in translation.Items) + { + if (!string.IsNullOrWhiteSpace(item.Message)) + { + if (!messages.ContainsKey(item.Id)) + { + messages[item.Id] = item; + } + } + } + + return messages; + } +*/ + + public IEnumerable GetAvailableLanguages() + { + //todo: ideally we want to fill the other data in the Language object so this is usable by project incorporating i18n that they can simply lookup available languages. Maybe we even add a country property so that it's easier for projects to add corresponding flags. + + DirectoryInfo di = new DirectoryInfo(GetAbsoluteLocaleDir()); + List dirList = new List(); + Language language; + + foreach (var dir in di.EnumerateDirectories().Select(x => x.Name)) + { + language = new Language(); + language.LanguageShortTag = dir; + dirList.Add(language); + } + return dirList; + } + + public bool TranslationExists(string tag) + { + return File.Exists(GetPathForLanguage(tag)); + } + + #endregion + + #region save + + public void SaveTranslation(Translation translation) + { + string filePath = GetPathForLanguage(translation.LanguageInformation.LanguageShortTag); + string backupPath = GetPathForLanguage(translation.LanguageInformation.LanguageShortTag) + ".backup"; + + if (File.Exists(filePath)) //we backup one version. more advanced backup solutions could be added here. + { + if (File.Exists(backupPath)) + { + File.Delete(backupPath); + } + System.IO.File.Move(filePath, backupPath); + } + + if (File.Exists(filePath)) //we make sure the old file is removed first + { + File.Delete(filePath); + } + + bool hasReferences = false; + + using (StreamWriter stream = new StreamWriter(filePath)) + { + // Establish ordering of items in PO file. + var orderedItems = translation.Items.Values + .OrderBy(x => x.References == null || x.References.Count() == 0) + // Non-orphan items before orphan items. + .ThenBy(x => x.Id); + // Then order alphanumerically. + // + foreach (var item in orderedItems) + { + hasReferences = false; + + if (item.TranslatorComments != null) + { + foreach (var translatorComment in item.TranslatorComments) + { + stream.WriteLine("# " + translatorComment); + } + } + + if (item.ExtractedComments != null) + { + foreach (var extractedComment in item.ExtractedComments) + { + stream.WriteLine("#. " + extractedComment); + } + } + + if (item.References != null) + { + foreach (var reference in item.References) + { + hasReferences = true; + stream.WriteLine("#: " + reference); + } + } + + if (item.Flags != null) + { + foreach (var flag in item.Flags) + { + stream.WriteLine("#, " + flag); + } + } + + if (hasReferences) + { + stream.WriteLine("msgid \"" + escape(item.Id) + "\""); + stream.WriteLine("msgstr \"" + escape(item.Message) + "\""); + stream.WriteLine(""); + } + else + { + stream.WriteLine("#~ msgid \"" + escape(item.Id) + "\""); + stream.WriteLine("#~ msgstr \"" + escape(item.Message) + "\""); + stream.WriteLine(""); + } + + } + } + } + + public void SaveTemplate(IDictionary items) + { + string filePath = GetAbsoluteLocaleDir() + "/messages.pot"; + string backupPath = filePath + ".backup"; + + if (File.Exists(filePath)) //we backup one version. more advanced backup solutions could be added here. + { + if (File.Exists(backupPath)) + { + File.Delete(backupPath); + } + System.IO.File.Move(filePath, backupPath); + } + + if (File.Exists(filePath)) //we make sure the old file is removed first + { + File.Delete(filePath); + } + + using (StreamWriter stream = new StreamWriter(filePath)) + { + foreach (var item in items.Values) + { + if (item.Comments != null) + { + foreach (var comment in item.Comments) + { + stream.WriteLine("#. " + comment); + } + } + + foreach (var reference in item.References) + { + stream.WriteLine("#: " + reference); + } + + stream.WriteLine("msgid \"" + escape(item.Id) + "\""); + stream.WriteLine(""); + } + } + } + + #endregion + + #region helpers + + private string GetAbsoluteLocaleDir() + { + string localeDir = _settings.LocaleDirectory; + String path; + + if (Path.IsPathRooted(localeDir)) + { + path = localeDir; + } + else + { + path = Path.GetFullPath(localeDir); + } + + return path; + } + + private string GetPathForLanguage(string tag) + { + string path = GetAbsoluteLocaleDir(); + return path + "/" + tag + "/messages.po"; + } + + private Translation ParseTranslationFile(string tag) + { + //todo: consider that lines we don't understand like headers from poedit and #| should be preserved and outputted again. + + Translation translation = new Translation(); + Language language = new Language(); + language.LanguageShortTag = tag; + translation.LanguageInformation = language; + var items = new ConcurrentDictionary(); + + string path = GetPathForLanguage(tag); + + using (var fs = File.OpenText(path)) + { + // http://www.gnu.org/s/hello/manual/gettext/PO-Files.html + + string line; + bool currentlyReadingItem = false; + while ((line = fs.ReadLine()) != null) + { + List extractedComments = new List(); + List translatorComments = new List(); + List flags = new List(); + List references = new List(); + + //read all comments, flags and other descriptive items for this string + //if we have #~ its a historical/log entry but it is the messageID/message so we skip this do/while + if (line.StartsWith("#") && !line.StartsWith("#~")) + { + do + { + currentlyReadingItem = true; + switch (line[1]) + { + case '.': //Extracted comments + extractedComments.Add(line.Substring(2).Trim()); + break; + case ':': //references + references.Add(line.Substring(2).Trim()); + break; + case ',': //flags + flags.Add(line.Substring(2).Trim()); + break; + case '|': //msgid previous-untranslated-string - NOT used by us + break; + default: //translator comments + translatorComments.Add(line.Substring(1).Trim()); + break; + } + + } while ((line = fs.ReadLine()) != null && line.StartsWith("#")); + } + + if (currentlyReadingItem || line.StartsWith("#~")) + { + TranslateItem item = ParseBody(fs, line); + + if (item != null) { + // + item.TranslatorComments = translatorComments; + item.ExtractedComments = extractedComments; + item.Flags = flags; + item.References = references; + // + items.AddOrUpdate( + item.Id, + // Add routine. + k => { + return item; + }, + // Update routine. + (k, v) => { + v.References = v.References.Append(item.References); + v.ExtractedComments = v.ExtractedComments.Append(item.References); + v.TranslatorComments = v.TranslatorComments.Append(item.References); + v.Flags = v.Flags.Append(item.References); + return v; + }); + } + } + + currentlyReadingItem = false; + } + } + translation.Items = items; + return translation; + } + + private string RemoveCommentIfHistorical(string line) + { + if (string.IsNullOrWhiteSpace(line)) + { + return null; + } + + if (line.StartsWith("#~")) + { + return line.Replace("#~", "").Trim(); + } + + return line; + } + + private TranslateItem ParseBody(TextReader fs, string line) + { + if (string.IsNullOrEmpty(line)) { + return null; } + + TranslateItem message = new TranslateItem(); + StringBuilder sb = new StringBuilder(); + + line = RemoveCommentIfHistorical(line); //so that we read in removed historical records too + if (line.StartsWith("msgid")) + { + var msgid = Unquote(line); + sb.Append(msgid); + + while ((line = fs.ReadLine()) != null) + { + line = RemoveCommentIfHistorical(line); + if (!line.StartsWith("msgstr") && (msgid = Unquote(line)) != null) + { + sb.Append(msgid); + } + else + { + break; + } + } + + message.Id = Unescape(sb.ToString()); + } + + sb.Clear(); + line = RemoveCommentIfHistorical(line); + if (!string.IsNullOrEmpty(line) && line.StartsWith("msgstr")) + { + var msgstr = Unquote(line); + sb.Append(msgstr); + + while ((line = fs.ReadLine()) != null && (msgstr = Unquote(line)) != null) + { + line = RemoveCommentIfHistorical(line); + sb.Append(msgstr); + } + + message.Message = Unescape(sb.ToString()); + } + return message; + } + + #region quoting and escaping + + //this method removes anything before the first quote and also removes first and last quote + private string Unquote(string lhs, string quotechar = "\"") + { + int begin = lhs.IndexOf(quotechar); + if (begin == -1) + { + return null; + } + int end = lhs.LastIndexOf(quotechar); + if (end <= begin) + { + return null; + } + return lhs.Substring(begin + 1, end - begin - 1); + } + + private string escape(string s) + { + if (string.IsNullOrWhiteSpace(s)) + { + return null; + } + return s.Replace("\"", "\\\""); + } + + /// + /// Looks up in the subject string standard C escape sequences and converts them + /// to their actual character counterparts. + /// + /// + private string Unescape(string s) + { + Regex regex_unescape = new Regex("\\\\[abfnrtv?\"'\\\\]|\\\\[0-3]?[0-7]{1,2}|\\\\u[0-9a-fA-F]{4}|."); + + StringBuilder sb = new StringBuilder(); + MatchCollection mc = regex_unescape.Matches(s, 0); + + foreach (Match m in mc) + { + if (m.Length == 1) + { + sb.Append(m.Value); + } + else + { + if (m.Value[1] >= '0' && m.Value[1] <= '7') + { + int i = 0; + + for (int j = 1; j < m.Length; j++) + { + i *= 8; + i += m.Value[j] - '0'; + } + + sb.Append((char)i); + } + else if (m.Value[1] == 'u') + { + int i = 0; + + for (int j = 2; j < m.Length; j++) + { + i *= 16; + + if (m.Value[j] >= '0' && m.Value[j] <= '9') + { + i += m.Value[j] - '0'; + } + else if (m.Value[j] >= 'A' && m.Value[j] <= 'F') + { + i += m.Value[j] - 'A' + 10; + } + else if (m.Value[j] >= 'a' && m.Value[j] <= 'a') + { + i += m.Value[j] - 'a' + 10; + } + } + + sb.Append((char)i); + } + else + { + switch (m.Value[1]) + { + case 'a': + sb.Append('\a'); + break; + case 'b': + sb.Append('\b'); + break; + case 'f': + sb.Append('\f'); + break; + case 'n': + sb.Append('\n'); + break; + case 'r': + sb.Append('\r'); + break; + case 't': + sb.Append('\t'); + break; + case 'v': + sb.Append('\v'); + break; + default: + sb.Append(m.Value[1]); + break; + } + } + } + } + + return sb.ToString(); + } + + #endregion + + #endregion + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `line` last assigned on line 371 could be null and is dereferenced at line 372, column 6. + +### Severity: +ERROR + +### Procedure: +TranslateItem POTranslationRepository.ParseBody(TextReader,String) + +### File: +src/i18n.Domain/Concrete/POTranslationRepository.cs + +### Key: +POTranslationRepository.cs|ParseBody|NULL_DEREFERENCE + +### Node Key: +c16cc1d2b5bc88a6c7c2310f1d47f089 + +### Hash: +0a6f568fc8923f33b510e1c243325c94 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2404/instruction.md b/inferredbugs-2404/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5a379e1fd9c29679783d7d6313c6e036b0739f21 --- /dev/null +++ b/inferredbugs-2404/instruction.md @@ -0,0 +1,212 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** i18n +**Bug ID:** 13 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Web; +using i18n.Helpers; + +namespace i18n +{ + /// + /// HTTP module responsible for: + /// 1. Implementing early URL localization + /// 2. Installing our ResponseFilter into the ASP.NET pipeline. + /// + /// + /// LocalizingModule can be installed like this: + /// + /// IIS7+ Integrated mode: + /// + /// <system.webServer> + /// <modules> + /// <add name="i18n.LocalizingModule" type="i18n.LocalizingModule, i18n" /> + /// </modules> + /// </system.webServer> + /// + /// IIS7 Classic mode and IIS6: + /// + /// <system.web> + /// <httpModules> + /// <add name="i18n.LocalizingModule" type="i18n.LocalizingModule, i18n" /> <!-- #37 --> + /// </httpModules> + /// </system.web> + /// + public class LocalizingModule : IHttpModule + { + private IRootServices m_rootServices; + + public LocalizingModule() + : this(LocalizedApplication.Current) + {} + public LocalizingModule( + IRootServices rootServices) + { + m_rootServices = rootServices; + } + + #region [IHttpModule] + + public void Init(HttpApplication application) + { + DebugHelpers.WriteLine("LocalizingModule::Init -- application: {0}", application); + + // Wire up our event handlers into the ASP.NET pipeline. + application.BeginRequest += OnBeginRequest; + application.ReleaseRequestState += OnReleaseRequestState; + application.PostRequestHandlerExecute += OnPostRequestHandlerExecute; + } + public void Dispose() {} + + #endregion + + // Implementation + + // Events handlers + + /// + /// Handler for the BeginRequest ASP.NET request pipeline event, where we inject our + /// Early URL Localization logic. + /// + private void OnBeginRequest(object sender, EventArgs e) + { + HttpContextBase context = HttpContext.Current.GetHttpContextBase(); + DebugHelpers.WriteLine("LocalizingModule::OnBeginRequest -- sender: {0}, e:{1}, ContentType: {2},\n\tUrl: {3}\n\tRawUrl:{4}", sender, e, context.Response.ContentType, context.Request.Url, context.Request.RawUrl); + + // Establish the language for the request. That is, we need to call + // context.SetPrincipalAppLanguageForRequest with a language, got from the URL, + // the i18n.langtag cookie, the Accept-Language header, or failing all that the + // default application language. + // · If early URL localizer configured, allow it to do it. + if (UrlLocalizer.UrlLocalizationScheme != UrlLocalizationScheme.Void + && m_rootServices.EarlyUrlLocalizerForApp != null) { + m_rootServices.EarlyUrlLocalizerForApp.ProcessIncoming(context); } + // · Otherwise skip the URL aspect and detemrine from the other (inferred) attributes. + else { + context.SetPrincipalAppLanguageForRequest(context.GetInferredLanguage()); } + } + + /// + /// Handler for the ReleaseRequestState ASP.NET request pipeline event. + /// This event occurs late on in the pipeline but prior to the response being filtered. + /// We take the opportunity to inject our i8n post-processing of the response. + /// + private void OnReleaseRequestState(object sender, EventArgs e) + { + // + HttpContextBase context = HttpContext.Current.GetHttpContextBase(); + DebugHelpers.WriteLine("LocalizingModule::OnReleaseRequestState -- sender: {0}, e:{1}, ContentType: {2},\n\tUrl: {3}\n\tRawUrl:{4}", sender, e, context.Response.ContentType, context.Request.Url, context.Request.RawUrl); + + // If the content type of the entity is eligible for processing AND the URL is not to be excluded, + // wire up our filter to do the processing. The entity data will be run through the filter a + // bit later on in the pipeline. + if ((LocalizedApplication.Current.ContentTypesToLocalize != null + && LocalizedApplication.Current.ContentTypesToLocalize.Match(context.Response.ContentType).Success) // Include certain content types from being processed + ) + { + if ((LocalizedApplication.Current.UrlsToExcludeFromProcessing != null + && LocalizedApplication.Current.UrlsToExcludeFromProcessing.Match(context.Request.RawUrl).Success) // Exclude certain URLs from being processed + ) + { + DebugHelpers.WriteLine("LocalizingModule::OnReleaseRequestState -- Bypassing filter, URL excluded: ({0}).", context.Request.RawUrl); + } + else if ((context.Response.Headers["Content-Encoding"] != null + || context.Response.Headers["Content-Encoding"] == "gzip") // Exclude responses that have already been compressed earlier in the pipeline + ) + { + DebugHelpers.WriteLine("LocalizingModule::OnReleaseRequestState -- Bypassing filter, response compressed."); + } + else + { + DebugHelpers.WriteLine("LocalizingModule::OnReleaseRequestState -- Installing filter"); + context.Response.Filter = new ResponseFilter( + context, + context.Response.Filter, + UrlLocalizer.UrlLocalizationScheme == UrlLocalizationScheme.Void ? null : m_rootServices.EarlyUrlLocalizerForApp, + m_rootServices.NuggetLocalizerForApp); + } + } + else { + DebugHelpers.WriteLine("LocalizingModule::OnReleaseRequestState -- Bypassing filter, No content-type match: ({0}).", context.Response.ContentType); + } + } + + private void OnPostRequestHandlerExecute(object sender, EventArgs e) + { + //Deal with an issue that causes empty responses to requests for WebResource.axd, set the internal HttpWriter to allow further writes + //this is not known to be necessary for any other cases, hence the hard-coded check for the WebResource.axd URL + var context = HttpContext.Current; + DebugHelpers.WriteLine("LocalizingModule::OnPostRequestHandlerExecute -- sender: {0}, e:{1}, ContentType: {2},\n\tUrl: {3}\n\tRawUrl:{4}", sender, e, context.Response.ContentType, context.Request.Url, context.Request.RawUrl); + + if (context.Request.RawUrl.ToLower().StartsWith("/webresource.axd")) + { + var response = context.Response; + var httpWriterField = typeof(HttpResponse).GetField("_httpWriter", + System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); + var ignoringFurtherWritesField = typeof(HttpWriter).GetField("_ignoringFurtherWrites", + System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); + var httpWriter = httpWriterField.GetValue(response); + ignoringFurtherWritesField.SetValue(httpWriter, false); + } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of i18n.ResponseFilter::.ctor() at Line 132) of type i18n.ResponseFilter, Leaked resource (output of i18n.ResponseFilter::.ctor() at Line 122) of type i18n.ResponseFilter in method "Void LocalizingModule.OnReleaseRequestState(Object,EventArgs)". + +### Severity: +ERROR + +### Procedure: +Void LocalizingModule.OnReleaseRequestState(Object,EventArgs) + +### File: +src/i18n/Pipeline/LocalizingModule.cs + +### Key: +LocalizingModule.cs|OnReleaseRequestState|DOTNET_RESOURCE_LEAK + +### Hash: +7a1df94c81486d7d259775f60402ea59 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2405/instruction.md b/inferredbugs-2405/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9d8c7db1ca097ebc90217ec106b6b0f86f496bd6 --- /dev/null +++ b/inferredbugs-2405/instruction.md @@ -0,0 +1,730 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** i18n +**Bug ID:** 5 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Web; +using System.Web.Caching; +using System.Web.Hosting; +using i18n.Domain.Abstract; +using i18n.Domain.Entities; +using i18n.Helpers; + +namespace i18n.Domain.Concrete +{ + public class POTranslationRepository : ITranslationRepository + { + private i18nSettings _settings; + + public POTranslationRepository(i18nSettings settings) + { + _settings = settings; + } + + #region load and getters + + public Translation GetTranslation(string langtag) + { + return ParseTranslationFile(langtag); + } + + + /// + /// Checks in first hand settings file, if not found there it checks file structure + /// + /// List of available languages + public IEnumerable GetAvailableLanguages() + { + //todo: ideally we want to fill the other data in the Language object so this is usable by project incorporating i18n that they can simply lookup available languages. Maybe we even add a country property so that it's easier for projects to add corresponding flags. + + List languages = _settings.AvailableLanguages.ToList(); + Language lang; + List dirList = new List(); + + + //This means there was no languages from settings + if (languages.Count == 0 + || (languages.Count == 1 && languages[0] == "")) + { + //We instead check for file structure + DirectoryInfo di = new DirectoryInfo(GetAbsoluteLocaleDir()); + + foreach (var dir in di.EnumerateDirectories().Select(x => x.Name)) + { + lang = new Language(); + lang.LanguageShortTag = dir; + dirList.Add(lang); + } + } + else + { + //see if the desired language was one of the returned from settings + foreach (var language in languages) + { + lang = new Language(); + lang.LanguageShortTag = language; + dirList.Add(lang); + } + } + + return dirList; + + } + + /// + /// Checks if the language is set as supported in config file + /// If not it checks if the PO file is available + /// + /// The tag for which you want to check if support exists. For instance "sv-SE" + /// True if language exists, otherwise false + public bool TranslationExists(string langtag) + { + List languages = _settings.AvailableLanguages.ToList(); + + //This means there was no languages from settings + if (languages.Count == 0 + || (languages.Count == 1 && languages[0] == "")) + { + //We instead check if the file exists + return File.Exists(GetPathForLanguage(langtag)); + } + else + { + //see if the desired language was one of the returned from settings + foreach (var language in languages) + { + if (language == langtag) + { + return true; + } + } + } + + //did not exist in settings nor as file, we return false + return false; + } + + public CacheDependency GetCacheDependencyForSingleLanguage(string langtag) + { + var path = GetPathForLanguage(langtag); + if (!File.Exists(path)) { + return null; } + return new CacheDependency(path); + } + + public CacheDependency GetCacheDependencyForAllLanguages() + { + return new FsCacheDependency(GetAbsoluteLocaleDir()); + } + + #endregion + + #region save + + /// + /// Saves a translation into file with standard pattern locale/langtag/message.po + /// Also saves a backup of previous version + /// + /// The translation you wish to save. Must have Language shortag filled out. + public void SaveTranslation(Translation translation) + { + string filePath = GetPathForLanguage(translation.LanguageInformation.LanguageShortTag); + string backupPath = GetPathForLanguage(translation.LanguageInformation.LanguageShortTag) + ".backup"; + + if (File.Exists(filePath)) //we backup one version. more advanced backup solutions could be added here. + { + if (File.Exists(backupPath)) + { + File.Delete(backupPath); + } + System.IO.File.Move(filePath, backupPath); + } + + if (File.Exists(filePath)) //we make sure the old file is removed first + { + File.Delete(filePath); + } + + bool hasReferences = false; + + if (!File.Exists(filePath)) + { + var fileInfo = new FileInfo(filePath); + var dirInfo = new DirectoryInfo(Path.GetDirectoryName(filePath)); + if (!dirInfo.Exists) + { + dirInfo.Create(); + } + fileInfo.Create().Close(); + } + + using (StreamWriter stream = new StreamWriter(filePath)) + { + // Establish ordering of items in PO file. + var orderedItems = translation.Items.Values + .OrderBy(x => x.References == null || x.References.Count() == 0) + // Non-orphan items before orphan items. + .ThenBy(x => x.MsgKey); + // Then order alphanumerically. + // + + //This is required for poedit to read the files correctly if they contains for instance swedish characters + stream.WriteLine("msgid \"\""); + stream.WriteLine("msgstr \"\""); + stream.WriteLine("\"Content-Type: text/plain; charset=utf-8\\n\""); + stream.WriteLine(); + + foreach (var item in orderedItems) + { + hasReferences = false; + + if (item.TranslatorComments != null) + { + foreach (var translatorComment in item.TranslatorComments) + { + stream.WriteLine("# " + translatorComment); + } + } + + if (item.ExtractedComments != null) + { + foreach (var extractedComment in item.ExtractedComments) + { + stream.WriteLine("#. " + extractedComment); + } + } + + if (item.References != null) + { + foreach (var reference in item.References) + { + hasReferences = true; + stream.WriteLine("#: " + reference); + } + } + + if (item.Flags != null) + { + foreach (var flag in item.Flags) + { + stream.WriteLine("#, " + flag); + } + } + + string prefix = hasReferences ? "" : prefix = "#~ "; + + if (_settings.MessageContextEnabledFromComment + && item.ExtractedComments != null + && item.ExtractedComments.Count() != 0) { + WriteString(stream, hasReferences, "msgctxt", item.ExtractedComments.First()); + } + + WriteString(stream, hasReferences, "msgid", item.MsgId); + WriteString(stream, hasReferences, "msgstr", escape(item.Message)); + + stream.WriteLine(""); + } + } + } + + /// + /// Saves a template file which is a all strings (needing translation) used in the entire project. Not language dependent + /// + /// A list of template items to save. The list should be all template items for the entire project. + public void SaveTemplate(IDictionary items) + { + string filePath = GetAbsoluteLocaleDir() + "/messages.pot"; + string backupPath = filePath + ".backup"; + + if (File.Exists(filePath)) //we backup one version. more advanced backup solutions could be added here. + { + if (File.Exists(backupPath)) + { + File.Delete(backupPath); + } + System.IO.File.Move(filePath, backupPath); + } + + if (File.Exists(filePath)) //we make sure the old file is removed first + { + File.Delete(filePath); + } + + if (! File.Exists(filePath)) + { + var fileInfo = new FileInfo(filePath); + var dirInfo = new DirectoryInfo(Path.GetDirectoryName(filePath)); + if (! dirInfo.Exists) + { + dirInfo.Create(); + } + fileInfo.Create().Close(); + } + + using (StreamWriter stream = new StreamWriter(filePath)) + { + // Establish ordering of items in PO file. + var orderedItems = items.Values + .OrderBy(x => x.References == null || x.References.Count() == 0) + // Non-orphan items before orphan items. + .ThenBy(x => x.MsgKey); + // Then order alphanumerically. + // + + //This is required for poedit to read the files correctly if they contains for instance swedish characters + stream.WriteLine("msgid \"\""); + stream.WriteLine("msgstr \"\""); + stream.WriteLine("\"Content-Type: text/plain; charset=utf-8\\n\""); + stream.WriteLine(); + + foreach (var item in orderedItems) + { + if (item.Comments != null) + { + foreach (var comment in item.Comments) + { + stream.WriteLine("#. " + comment); + } + } + + foreach (var reference in item.References) + { + stream.WriteLine("#: " + reference); + } + + stream.WriteLine("msgid \"" + escape(item.MsgId) + "\""); + stream.WriteLine("msgstr \"\""); // enable loading of POT file into editor e.g. PoEdit. + stream.WriteLine(""); + } + } + } + + #endregion + + #region helpers + + /// + /// Gets the locale directory from settings and makes sure it is translated into absolut path + /// + /// the locale directory in absolute path + private string GetAbsoluteLocaleDir() + { + return _settings.LocaleDirectory; + } + + private string GetPathForLanguage(string langtag) + { + return Path.Combine(GetAbsoluteLocaleDir(), langtag, "messages.po"); + } + + /// + /// Parses a PO file into a Language object + /// + /// The language (tag) you wish to load into Translation object + /// A complete translation object with all all translations and language values set. + private Translation ParseTranslationFile(string langtag) + { + //todo: consider that lines we don't understand like headers from poedit and #| should be preserved and outputted again. + + Translation translation = new Translation(); + Language language = new Language(); + language.LanguageShortTag = langtag; + translation.LanguageInformation = language; + var items = new ConcurrentDictionary(); + + string path = GetPathForLanguage(langtag); + + if (File.Exists(path)) { + + using (var fs = File.OpenText(path)) + { + // http://www.gnu.org/s/hello/manual/gettext/PO-Files.html + + string line; + bool itemStarted = false; + while ((line = fs.ReadLine()) != null) + { + List extractedComments = new List(); + List translatorComments = new List(); + List flags = new List(); + List references = new List(); + + //read all comments, flags and other descriptive items for this string + //if we have #~ its a historical/log entry but it is the messageID/message so we skip this do/while + if (line.StartsWith("#") && !line.StartsWith("#~")) + { + do + { + itemStarted = true; + switch (line[1]) + { + case '.': //Extracted comments + extractedComments.Add(line.Substring(2).Trim()); + break; + case ':': //references + references.Add(line.Substring(2).Trim()); + break; + case ',': //flags + flags.Add(line.Substring(2).Trim()); + break; + case '|': //msgid previous-untranslated-string - NOT used by us + break; + default: //translator comments + translatorComments.Add(line.Substring(1).Trim()); + break; + } + + } while ((line = fs.ReadLine()) != null && line.StartsWith("#")); + } + + if (itemStarted || line.StartsWith("#~")) + { + TranslationItem item = ParseBody(fs, line, extractedComments); + + if (item != null) { + // + item.TranslatorComments = translatorComments; + item.ExtractedComments = extractedComments; + item.Flags = flags; + item.References = references; + // + items.AddOrUpdate( + item.MsgKey, + // Add routine. + k => { + return item; + }, + // Update routine. + (k, v) => { + v.References = v.References.Append(item.References); + v.ExtractedComments = v.ExtractedComments.Append(item.References); + v.TranslatorComments = v.TranslatorComments.Append(item.References); + v.Flags = v.Flags.Append(item.References); + return v; + }); + } + } + + itemStarted = false; + } + } + } + translation.Items = items; + return translation; + } + + /// + /// Removes the preceding characters in a file showing that an item is historical/log. That is to say it has been removed from the project. We don't need care about the character as the fact that it lacks references is what tells us it's a log item + /// + /// + /// + private string RemoveCommentIfHistorical(string line) + { + if (string.IsNullOrWhiteSpace(line)) + { + return null; + } + + if (line.StartsWith("#~")) + { + return line.Replace("#~", "").Trim(); + } + + return line; + } + + /// + /// Parses the body of a PO file item. That is to say the message id and the message itself. + /// Reason for why it must be on second line (textreader) is so that you can read until you have read to far without peek previously for meta data. + /// + /// A textreader that must be on the second line of a message body + /// The first line of the message body. + /// Returns a TranslationItem with only key, id and message set + private TranslationItem ParseBody(TextReader fs, string line, List extractedComments) + { + if (string.IsNullOrEmpty(line)) { + return null; } + + TranslationItem message = new TranslationItem { MsgKey = "" }; + StringBuilder sb = new StringBuilder(); + + string msgctxt = null; + line = RemoveCommentIfHistorical(line); //so that we read in removed historical records too + if (line.StartsWith("msgctxt")) + { + msgctxt = Unquote(line); + line = fs.ReadLine(); + } + + line = RemoveCommentIfHistorical(line); //so that we read in removed historical records too + if (line.StartsWith("msgid")) + { + var msgid = Unquote(line); + sb.Append(msgid); + + while ((line = fs.ReadLine()) != null) + { + line = RemoveCommentIfHistorical(line); + if (!line.StartsWith("msgstr") && (msgid = Unquote(line)) != null) + { + sb.Append(msgid); + } + else + { + break; + } + } + + message.MsgId = Unescape(sb.ToString()); + + // If no msgctxt is set then msgkey is the msgid; otherwise it is msgid+msgctxt. + message.MsgKey = string.IsNullOrEmpty(msgctxt) ? + message.MsgId: + TemplateItem.KeyFromMsgidAndComment(message.MsgId, msgctxt, true); + } + + sb.Clear(); + line = RemoveCommentIfHistorical(line); + if (!string.IsNullOrEmpty(line) && line.StartsWith("msgstr")) + { + var msgstr = Unquote(line); + sb.Append(msgstr); + + while ((line = fs.ReadLine()) != null && (msgstr = Unquote(line)) != null) + { + line = RemoveCommentIfHistorical(line); + sb.Append(msgstr); + } + + message.Message = Unescape(sb.ToString()); + } + return message; + } + + /// + /// Helper for writing either a msgid or msgstr to the po file. + /// + /// + /// + /// "msgid" or "msgstr" + /// + private static void WriteString(StreamWriter stream, bool hasReferences, string type, string value) + { + // Logic for outputting multi-line msgid. + // + // IN : ab + // OUT: msgid "a\n" + // msgid "b" + // + // IN : ab + // OUT: msgid "a\n" + // msgid "b\n" + // + string prefix = hasReferences ? "" : prefix = "#~ "; + value = value ?? ""; + value = value.Replace("\r\n", "\n"); + string[] lines = value.Split('\n'); + if (lines.Length > 1) { + stream.WriteLine(string.Format("{0}{1} \"\"", prefix, type)); + for (int i = 0; i < lines.Length; ++i) { + string m = lines[i]; + bool last = i == lines.Length -1; + if (m.Length != 0) { + stream.WriteLine(string.Format("\"{0}{1}\"", m, last ? "" : "\\n")); + } + } + } + else { + stream.WriteLine(string.Format("{0}{1} \"{2}\"", prefix, type, value)); + } + } + + #region quoting and escaping + + //this method removes anything before the first quote and also removes first and last quote + private string Unquote(string lhs, string quotechar = "\"") + { + int begin = lhs.IndexOf(quotechar); + if (begin == -1) + { + return null; + } + int end = lhs.LastIndexOf(quotechar); + if (end <= begin) + { + return null; + } + return lhs.Substring(begin + 1, end - begin - 1); + } + + private string escape(string s) + { + if (string.IsNullOrWhiteSpace(s)) + { + return null; + } + return s.Replace("\"", "\\\""); + } + + /// + /// Looks up in the subject string standard C escape sequences and converts them + /// to their actual character counterparts. + /// + /// + private string Unescape(string s) + { + Regex regex_unescape = new Regex("\\\\[abfnrtv?\"'\\\\]|\\\\[0-3]?[0-7]{1,2}|\\\\u[0-9a-fA-F]{4}|.", RegexOptions.Singleline); + + StringBuilder sb = new StringBuilder(); + MatchCollection mc = regex_unescape.Matches(s, 0); + + foreach (Match m in mc) + { + if (m.Length == 1) + { + sb.Append(m.Value); + } + else + { + if (m.Value[1] >= '0' && m.Value[1] <= '7') + { + int i = 0; + + for (int j = 1; j < m.Length; j++) + { + i *= 8; + i += m.Value[j] - '0'; + } + + sb.Append((char)i); + } + else if (m.Value[1] == 'u') + { + int i = 0; + + for (int j = 2; j < m.Length; j++) + { + i *= 16; + + if (m.Value[j] >= '0' && m.Value[j] <= '9') + { + i += m.Value[j] - '0'; + } + else if (m.Value[j] >= 'A' && m.Value[j] <= 'F') + { + i += m.Value[j] - 'A' + 10; + } + else if (m.Value[j] >= 'a' && m.Value[j] <= 'a') + { + i += m.Value[j] - 'a' + 10; + } + } + + sb.Append((char)i); + } + else + { + switch (m.Value[1]) + { + case 'a': + sb.Append('\a'); + break; + case 'b': + sb.Append('\b'); + break; + case 'f': + sb.Append('\f'); + break; + case 'n': + sb.Append('\n'); + break; + case 'r': + sb.Append('\r'); + break; + case 't': + sb.Append('\t'); + break; + case 'v': + sb.Append('\v'); + break; + default: + sb.Append(m.Value[1]); + break; + } + } + } + } + + return sb.ToString(); + } + + #endregion + + #endregion + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `line` last assigned on line 462 could be null and is dereferenced at line 463, column 4. + +### Severity: +ERROR + +### Procedure: +TranslationItem POTranslationRepository.ParseBody(TextReader,String,List`1) + +### File: +src/i18n.Domain/Concrete/POTranslationRepository.cs + +### Key: +POTranslationRepository.cs|ParseBody|NULL_DEREFERENCE + +### Node Key: +90535029835413c6e5d1bdebbf52bdf9 + +### Hash: +0a6f568fc8923f33b510e1c243325c94 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2434/instruction.md b/inferredbugs-2434/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f3db9f2883133db6316916d8b5a1903e7db49781 --- /dev/null +++ b/inferredbugs-2434/instruction.md @@ -0,0 +1,488 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** dotliquid +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using DotLiquid.FileSystems; +using DotLiquid.Util; +using DotLiquid.NamingConventions; + +namespace DotLiquid +{ + /// + /// Templates are central to liquid. + /// Interpreting templates is a two step process. First you compile the + /// source code you got. During compile time some extensive error checking is performed. + /// your code should expect to get some SyntaxErrors. + /// + /// After you have a compiled template you can then render it. + /// You can use a compiled template over and over again and keep it cached. + /// + /// Example: + /// + /// template = Liquid::Template.parse(source) + /// template.render('user_name' => 'bob') + /// + public class Template + { + /// + /// Naming convention used for template parsing + /// + /// Default is Ruby + public static INamingConvention NamingConvention { get; set; } + + /// + /// Filesystem used for template reading + /// + public static IFileSystem FileSystem { get; set; } + + /// + /// Indicates if the default is thread safe + /// + public static bool DefaultIsThreadSafe { get; set; } + + private static Dictionary> Tags { get; set; } + + /// + /// TimeOut used for all Regex in DotLiquid + /// + public static TimeSpan RegexTimeOut { get; set; } + + private static readonly Dictionary> SafeTypeTransformers; + private static readonly Dictionary> ValueTypeTransformers; + + static Template() + { + RegexTimeOut = TimeSpan.FromSeconds(10); + NamingConvention = new RubyNamingConvention(); + FileSystem = new BlankFileSystem(); + Tags = new Dictionary>(); + SafeTypeTransformers = new Dictionary>(); + ValueTypeTransformers = new Dictionary>(); + } + + /// + /// Register a tag + /// + /// Type of the tag + /// Name of the tag + public static void RegisterTag(string name) + where T : Tag, new() + { + var tagType = typeof(T); + Tags[name] = new Tuple(new ActivatorTagFactory(tagType, name), tagType); + } + + /// + /// Registers a tag factory. + /// + /// The ITagFactory to be registered + public static void RegisterTagFactory(ITagFactory tagFactory) + { + Tags[tagFactory.TagName] = new Tuple(tagFactory, null); + } + + /// + /// Get the tag type from it's name + /// + /// + /// + public static Type GetTagType(string name) + { + Tags.TryGetValue(name, out Tuple result); + return result.Item2; + } + + internal static Tag CreateTag(string name) + { + Tag tagInstance = null; + Tags.TryGetValue(name, out Tuple result); + + if (result != null) + { + tagInstance = result.Item1.Create(); + } + + return tagInstance; + } + + /// + /// Pass a module with filter methods which should be available + /// to all liquid views. Good for registering the standard library + /// + /// + public static void RegisterFilter(Type filter) + { + Strainer.GlobalFilter(filter); + } + + /// + /// Registers a simple type. DotLiquid will wrap the object in a object. + /// + /// The type to register + /// An array of property and method names that are allowed to be called on the object. + public static void RegisterSafeType(Type type, string[] allowedMembers) + { + RegisterSafeType(type, x => new DropProxy(x, allowedMembers)); + } + + /// + /// Registers a simple type. DotLiquid will wrap the object in a object. + /// + /// The type to register + /// An array of property and method names that are allowed to be called on the object. + /// Function that converts the specified type into a Liquid Drop-compatible object (eg, implements ILiquidizable) + public static void RegisterSafeType(Type type, string[] allowedMembers, Func func) + { + RegisterSafeType(type, x => new DropProxy(x, allowedMembers, func)); + } + + /// + /// Registers a simple type using the specified transformer. + /// + /// The type to register + /// Function that converts the specified type into a Liquid Drop-compatible object (eg, implements ILiquidizable) + public static void RegisterSafeType(Type type, Func func) + { + SafeTypeTransformers[type] = func; + } + + /// + /// Registers a simple value type transformer. Used for rendering a variable to the output stream + /// + /// The type to register + /// Function that converts the specified type into a Liquid Drop-compatible object (eg, implements ILiquidizable) + public static void RegisterValueTypeTransformer(Type type, Func func) + { + ValueTypeTransformers[type] = func; + } + + /// + /// Gets the corresponding value type converter + /// + /// + /// + public static Func GetValueTypeTransformer(Type type) + { + // Check for concrete types + if (ValueTypeTransformers.TryGetValue(type, out Func transformer)) + return transformer; + + // Check for interfaces + var interfaces = type.GetTypeInfo().ImplementedInterfaces; + foreach (var interfaceType in interfaces) + { + if (ValueTypeTransformers.TryGetValue(interfaceType, out transformer)) + return transformer; + if (interfaceType.GetTypeInfo().IsGenericType && ValueTypeTransformers.TryGetValue( + interfaceType.GetGenericTypeDefinition(), out transformer)) + return transformer; + } + return null; + } + + /// + /// Gets the corresponding safe type transformer + /// + /// + /// + public static Func GetSafeTypeTransformer(Type type) + { + // Check for concrete types + if (SafeTypeTransformers.TryGetValue(type, out Func transformer)) + return transformer; + + // Check for interfaces + var interfaces = type.GetTypeInfo().ImplementedInterfaces; + foreach (var interfaceType in interfaces) + { + if (SafeTypeTransformers.TryGetValue(interfaceType, out transformer)) + return transformer; + if (interfaceType.GetTypeInfo().IsGenericType && SafeTypeTransformers.TryGetValue( + interfaceType.GetGenericTypeDefinition(), out transformer)) + return transformer; + } + return null; + } + + /// + /// Creates a new Template object from liquid source code + /// + /// + /// + public static Template Parse(string source) + { + Template template = new Template(); + template.ParseInternal(source); + return template; + } + + private Hash _registers, _assigns, _instanceAssigns; + private List _errors; + private bool? _isThreadSafe; + + /// + /// Liquid document + /// + public Document Root { get; set; } + + /// + /// Hash of user-defined, internally-available variables + /// + public Hash Registers + { + get { return (_registers = _registers ?? new Hash()); } + } + + public Hash Assigns + { + get { return (_assigns = _assigns ?? new Hash()); } + } + + public Hash InstanceAssigns + { + get { return (_instanceAssigns = _instanceAssigns ?? new Hash()); } + } + + /// + /// Exceptions that have been raised during template rendering + /// + public List Errors + { + get { return (_errors = _errors ?? new List()); } + } + + /// + /// Indicates if the parsed templates will be thread safe + /// + public bool IsThreadSafe + { + get { return _isThreadSafe ?? DefaultIsThreadSafe; } + } + + /// + /// Creates a new Template from an array of tokens. Use Template.parse instead + /// + internal Template() + { + } + + /// + /// Parse source code. + /// Returns self for easy chaining + /// + /// + /// + internal Template ParseInternal(string source) + { + source = DotLiquid.Tags.Literal.FromShortHand(source); + source = DotLiquid.Tags.Comment.FromShortHand(source); + + Root = new Document(); + Root.Initialize(null, null, Tokenize(source)); + return this; + } + + /// + /// Make this template instance thread safe. + /// After this call, you can't use template owned variables anymore. + /// + /// + public void MakeThreadSafe() + { + _isThreadSafe = true; + } + + /// + /// Renders the template using default parameters and returns a string containing the result. + /// + /// + public string Render(IFormatProvider formatProvider = null) + { + return Render(new RenderParameters(), formatProvider); + } + + /// + /// Renders the template using the specified local variables and returns a string containing the result. + /// + /// + /// + /// + public string Render(Hash localVariables, IFormatProvider formatProvider=null) + { + return Render(new RenderParameters + { + LocalVariables = localVariables + }, formatProvider); + } + + /// + /// Renders the template using the specified parameters and returns a string containing the result. + /// + /// + /// + /// + public string Render(RenderParameters parameters, IFormatProvider formatProvider = null) + { + using (TextWriter writer = formatProvider == null ? new StringWriter() : new StringWriter(formatProvider)) + { + Render(writer, parameters); + return writer.ToString(); + } + } + + /// + /// Renders the template into the specified StreamWriter. + /// + /// + /// + public void Render(TextWriter result, RenderParameters parameters) + { + RenderInternal(result, parameters); + } + + /// + /// Renders the template into the specified Stream. + /// + /// + /// + public void Render(Stream stream, RenderParameters parameters) + { + // Can't dispose this new StreamWriter, because it would close the + // passed-in stream, which isn't up to us. + StreamWriter streamWriter = new StreamWriter(stream); + RenderInternal(streamWriter, parameters); + streamWriter.Flush(); + } + + /// + /// Render takes a hash with local variables. + /// + /// if you use the same filters over and over again consider registering them globally + /// with Template.register_filter + /// + /// Following options can be passed: + /// + /// * filters : array with local filters + /// * registers : hash with register variables. Those can be accessed from + /// filters and tags and might be useful to integrate liquid more with its host application + /// + private void RenderInternal(TextWriter result, RenderParameters parameters) + { + if (Root == null) + return; + + parameters.Evaluate(this, out Context context, out Hash registers, out IEnumerable filters); + + if (!IsThreadSafe) + { + if (registers != null) + Registers.Merge(registers); + + if (filters != null) + context.AddFilters(filters); + } + + try + { + // Render the nodelist. + Root.Render(context, result); + } + finally + { + if (!IsThreadSafe) + _errors = context.Errors; + } + } + + /// + /// Uses the Liquid::TemplateParser regexp to tokenize the passed source + /// + /// + /// + internal static List Tokenize(string source) + { + if (string.IsNullOrEmpty(source)) + return new List(); + + // Trim leading whitespace. + source = Regex.Replace(source, string.Format(@"([ \t]+)?({0}|{1})-", Liquid.VariableStart, Liquid.TagStart), "$2", RegexOptions.None, RegexTimeOut); + + // Trim trailing whitespace. + source = Regex.Replace(source, string.Format(@"-({0}|{1})(\n|\r\n|[ \t]+)?", Liquid.VariableEnd, Liquid.TagEnd), "$1", RegexOptions.None, RegexTimeOut); + + List tokens = Regex.Split(source, Liquid.TemplateParser).ToList(); + + // Trim any whitespace elements from the end of the array. + for (int i = tokens.Count - 1; i > 0; --i) + if (tokens[i] == string.Empty) + tokens.RemoveAt(i); + + // Removes the rogue empty element at the beginning of the array + if (tokens[0] != null && tokens[0] == string.Empty) + tokens.Shift(); + + return tokens; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource streamWriter of type System.IO.StreamWriter in method "Void Template.Render(Stream,RenderParameters)". + +### Severity: +ERROR + +### Procedure: +Void Template.Render(Stream,RenderParameters) + +### File: +src/DotLiquid/Template.cs + +### Key: +Template.cs|Render|DOTNET_RESOURCE_LEAK + +### Hash: +b673a7c69112665a3f7b21f19825c14a + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2435/instruction.md b/inferredbugs-2435/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..28e33d225f2e1979341e7d1accf9087569935951 --- /dev/null +++ b/inferredbugs-2435/instruction.md @@ -0,0 +1,140 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** CleanArchitecture +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using BlazorHero.CleanArchitecture.Application.Extensions; +using BlazorHero.CleanArchitecture.Infrastructure.Extensions; +using BlazorHero.CleanArchitecture.Server.Extensions; +using BlazorHero.CleanArchitecture.Server.Middlewares; +using Hangfire; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.FileProviders; +using System.IO; + +namespace BlazorHero.CleanArchitecture.Server +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + _configuration = configuration; + } + + private readonly IConfiguration _configuration; + + // This method gets called by the runtime. Use this method to add services to the container. + // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 + + public void ConfigureServices(IServiceCollection services) + { + services.AddSignalR(); + services.AddDatabase(_configuration); + services.AddIdentity(); + services.AddJwtAuthentication(services.GetApplicationSettings(_configuration)); + //TODO - add CustomServerLocalStorageService + //services.AddScoped(); + //services.AddScoped(); + services.AddLocalization(options => + { + options.ResourcesPath = "Resources"; + }); + services.AddApplicationLayer(); + services.AddApplicationServices(); + services.AddSharedInfrastructure(_configuration); + services.RegisterSwagger(); + services.AddInfrastructureMappings(); + services.AddHangfire(x => x.UseSqlServerStorage(_configuration.GetConnectionString("DefaultConnection"))); + services.AddHangfireServer(); + services.AddControllers().AddValidators(); + services.AddRazorPages(); + services.AddApiVersioning(config => + { + config.DefaultApiVersion = new ApiVersion(1, 0); + config.AssumeDefaultVersionWhenUnspecified = true; + config.ReportApiVersions = true; + }); + services.AddLazyCache(); + } + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + app.UseExceptionHandling(env); + app.UseHttpsRedirection(); + app.UseHangfireDashboard("/jobs"); + app.UseMiddleware(); + app.UseBlazorFrameworkFiles(); + app.UseStaticFiles(); + app.UseStaticFiles(new StaticFileOptions() + { + FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Files")), + RequestPath = new PathString("/Files") + }); + app.UseRequestLocalizationByCulture(); + app.UseRouting(); + app.UseAuthentication(); + app.UseAuthorization(); + app.UseEndpoints(); + app.ConfigureSwagger(); + app.Initialize(_configuration); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Microsoft.Extensions.FileProviders.PhysicalFileProvider::.ctor() at Line 68) of type Microsoft.Extensions.FileProviders.PhysicalFileProvider in method "Void Startup.Configure(IApplicationBuilder,IWebHostEnvironment)". + +### Severity: +ERROR + +### Procedure: +Void Startup.Configure(IApplicationBuilder,IWebHostEnvironment) + +### File: +BlazorHero.CleanArchitecture/Server/Startup.cs + +### Key: +Startup.cs|Configure|DOTNET_RESOURCE_LEAK + +### Hash: +fc1072ab8d7a22f927118b5157d91cca + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2451/instruction.md b/inferredbugs-2451/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d22b8144cb0483a48b08498d440c7be42d000903 --- /dev/null +++ b/inferredbugs-2451/instruction.md @@ -0,0 +1,141 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** SiaNet +**Bug ID:** 8 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Text; +using SiaNet.Constraints; +using SiaNet.Initializers; +using SiaNet.Layers.Activations; +using SiaNet.Regularizers; +using TensorSharp; +using TensorSharp.Expression; + +namespace SiaNet.Layers +{ + public class Dense : BaseLayer + { + public int Dim { get; set; } + + public BaseLayer Activation { get; set; } + + public bool UseBias { get; set; } + + public BaseInitializer KernalInitializer { get; set; } + + public BaseInitializer BiasInitializer { get; set; } + + public BaseConstraint KernalConstraint { get; set; } + + public BaseConstraint BiasConstraint { get; set; } + + public BaseRegularizer KernalRegularizer { get; set; } + + public BaseRegularizer BiasRegularizer { get; set; } + + public Dense(int dim, ActivationType activation = ActivationType.Linear, + BaseInitializer kernalInitializer = null, BaseRegularizer kernalRegularizer = null, BaseConstraint kernalConstraint = null, + bool useBias = false, BaseInitializer biasInitializer = null, BaseRegularizer biasRegularizer = null, BaseConstraint biasConstraint = null) + : base("dense") + { + Dim = dim; + Activation = ActivationRegistry.Get(activation); + UseBias = useBias; + KernalInitializer = kernalInitializer ?? new GlorotUniform(); + BiasInitializer = biasInitializer ?? new Zeros(); + KernalConstraint = kernalConstraint; + BiasConstraint = biasConstraint; + KernalRegularizer = kernalRegularizer; + BiasRegularizer = biasRegularizer; + } + + public override void Forward(Variable x) + { + Input = x; + Variable weight = BuildVar("w", new long[] { x.Data.Shape[1], Dim }, x.Data.ElementType, KernalInitializer, KernalConstraint, KernalRegularizer); + Variable bias = null; + + if (UseBias) + { + bias = BuildVar("b", new long[] { 1, Dim }, x.Data.ElementType, BiasInitializer, BiasConstraint, BiasRegularizer); + + Output = bias.Data.TVar().Expand(x.Data.Shape[0], Dim) + .Addmm(1, 1, x.Data, weight.Data) + .Evaluate(); + } + else + { + Output = x.Data.TVar().Dot(weight.Data.TVar()).Evaluate(); + } + + Activation.Forward(Output.ToVariable()); + } + + public override void Backward(Tensor outputgrad) + { + Activation.Backward(outputgrad); + + Input.Grad = outputgrad.TVar().Dot(Params["w"].Data.TVar().Transpose()).Evaluate(); + + Params["w"].Grad = outputgrad.TVar().Dot(Params["w"].Data.TVar().Transpose()).Evaluate(); + if(UseBias) + Params["b"].Grad = (Params["b"].Grad + outputgrad.TVar().Sum(0)).Evaluate(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource weight of type SiaNet.Variable, Leaked resource bias of type SiaNet.Variable, Leaked resource (returned from SiaNet.Variable SiaNet.TensorUtil::ToVariable(TensorSharp.Tensor,System.String) at Line 68) of type SiaNet.Variable in method "Void Dense.Forward(Variable)". + +### Severity: +ERROR + +### Procedure: +Void Dense.Forward(Variable) + +### File: +SiaNet/Layers/Core/Dense.cs + +### Key: +Dense.cs|Forward|DOTNET_RESOURCE_LEAK + +### Hash: +1bae32c4bab5fa8a295013e02bc7d3cf + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2456/instruction.md b/inferredbugs-2456/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63674d40ac0fd239b18a04e0338baee7bee2d89f --- /dev/null +++ b/inferredbugs-2456/instruction.md @@ -0,0 +1,128 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** SiaNet +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Text; +using TensorSharp; +using System.Linq; + +namespace SiaNet +{ + public class ImgUtil + { + public static Tensor Im2Col(Tensor x, Tuple kernalSize, uint? padding = null, uint stride = 1) + { + if (padding.HasValue) + { + x = x.Pad(1, padding.Value); + } + + var list = x.NDto2DList(); + var cols = x.Transpose(1, 2, 3, 4, 0).Unfold(3, kernalSize.Item3, stride).Unfold(2, kernalSize.Item2, stride).Unfold(1, kernalSize.Item1, stride); + + return cols; + } + + public static Tensor Im2Col(Tensor x, Tuple kernalSize, uint? padding=null, uint stride = 1) + { + var (n, c, h, w) = x.GetConv2DShape(); + if (padding.HasValue) + { + x = x.Pad(1, padding.Value); + } + + var cols = x.Transpose(0, 1, 2, 3).Unfold(2, kernalSize.Item2, stride).Unfold(3, kernalSize.Item1, stride); + var x_t = x.Transpose(1, 0, 2, 3); + x_t.Narrow(2, 0, 3).Narrow(3, 0, 3).Print(); + + return cols; + } + + public static Tensor Im2Col(Tensor x, uint steps, uint? padding = null, uint stride = 1) + { + + if (padding.HasValue) + { + x = x.Pad(1, padding.Value); + } + + x.Print(); + + var cols = x.Transpose(2,1,0).Unfold(1, 1, stride).Unfold(0, 3, 1); + + return cols; + } + + public static Tensor Col2Im(Tensor cols, long[] x_shape, uint field_height, uint field_width, uint field_depth, uint? padding = null, uint stride = 1) + { + return cols; + } + + public static Tensor Col2Im(Tensor cols, long[] x_shape, uint field_height, uint field_width, uint? padding = null, uint stride = 1) + { + return cols; + } + + public static Tensor Col2Im(Tensor cols, long[] x_shape, uint field_height, uint? padding = null, uint stride = 1) + { + return cols; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type TensorSharp.Tensor, Leaked resource (returned from TensorSharp.Tensor TensorSharp.Tensor::Unfold(System.Int32,System.Int64,System.Int64) at Line 49) of type TensorSharp.Tensor in method "Tensor ImgUtil.Im2Col(Tensor,UInt32,Nullable`1,UInt32)". + +### Severity: +ERROR + +### Procedure: +Tensor ImgUtil.Im2Col(Tensor,UInt32,Nullable`1,UInt32) + +### File: +SiaNet/Utils/ImgUtil.cs + +### Key: +ImgUtil.cs|Im2Col|DOTNET_RESOURCE_LEAK + +### Hash: +389bb24d17105006a454d1606e0d7e77 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2458/instruction.md b/inferredbugs-2458/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0e50d701f11363f01ec34246ed430b12013902f7 --- /dev/null +++ b/inferredbugs-2458/instruction.md @@ -0,0 +1,185 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** SiaNet +**Bug ID:** 5 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using SiaNet.Constraints; +using SiaNet.Initializers; +using SiaNet.Regularizers; +using System; +using System.Collections.Generic; +using System.Text; +using TensorSharp; + +namespace SiaNet.Layers +{ + public class Conv3D : BaseLayer + { + public uint Filters { get; set; } + + public Tuple KernalSize { get; set; } + + public uint Strides { get; set; } + + public PaddingType Padding { get; set; } + + public Tuple DialationRate { get; set; } + + public ActivationType Activation { get; set; } + + public bool UseBias { get; set; } + + public BaseInitializer BiasInitializer { get; set; } + + public BaseInitializer KernalInitializer { get; set; } + + public BaseConstraint KernalConstraint { get; set; } + + public BaseConstraint BiasConstraint { get; set; } + + public BaseRegularizer KernalRegularizer { get; set; } + + public BaseRegularizer BiasRegularizer { get; set; } + + private Tensor xCols; + + public Conv3D(uint filters, Tuple kernalSize, uint strides = 1, PaddingType padding = PaddingType.Same, Tuple dialationRate = null, + ActivationType activation = ActivationType.Linear, BaseInitializer kernalInitializer = null, BaseRegularizer kernalRegularizer = null, + BaseConstraint kernalConstraint = null, bool useBias = true, BaseInitializer biasInitializer = null, BaseRegularizer biasRegularizer = null, BaseConstraint biasConstraint = null) + : base("conv3d") + { + Filters = filters; + KernalSize = kernalSize; + Strides = strides; + Padding = padding; + DialationRate = dialationRate ?? Tuple.Create(1, 1, 1); + Activation = activation; + UseBias = useBias; + KernalInitializer = kernalInitializer ?? new GlorotUniform(); + BiasInitializer = biasInitializer ?? new Zeros(); + KernalConstraint = kernalConstraint; + BiasConstraint = biasConstraint; + KernalRegularizer = kernalRegularizer; + BiasRegularizer = biasRegularizer; + } + + public override void Forward(Variable x) + { + //ToDo: Implement DilationRate + Input = x; + var (n, c, d, h, w) = x.Data.GetConv3DShape(); + + Variable weight = BuildVar("w", new long[] { Filters, c, KernalSize.Item1, KernalSize.Item2, KernalSize.Item2 }, x.Data.ElementType, KernalInitializer, KernalConstraint, KernalRegularizer); + Variable bias = null; + if (UseBias) + { + bias = BuildVar("b", new long[] { Filters, 1 }, x.Data.ElementType, BiasInitializer, BiasConstraint, BiasRegularizer); + } + + uint? pad = null; + if (Padding == PaddingType.Same) + { + pad = 1; + } + else if (Padding == PaddingType.Full) + { + pad = 2; + } + + var d_out = (d - KernalSize.Item1 + 2 * pad) / Strides + 1; + var h_out = (h - KernalSize.Item2 + 2 * pad) / Strides + 1; + var w_out = (w - KernalSize.Item3 + 2 * pad) / Strides + 1; + + xCols = ImgUtil.Im2Col(x.Data, KernalSize, pad, Strides); + var wRows = weight.Data.Reshape(Filters, -1); + + Output = Dot(wRows, xCols); + if (UseBias) + { + Output = Output + bias.Data; + } + + Output = Output.Reshape(Filters, d_out.Value, h_out.Value, w_out.Value, n).Transpose(4, 0, 1, 2, 3); + } + + public override void Backward(Tensor outputgrad) + { + uint? pad = null; + if (Padding == PaddingType.Same) + { + pad = 1; + } + else if (Padding == PaddingType.Full) + { + pad = 2; + } + + var dout_flat = outputgrad.Transpose(4, 0, 1, 2, 3).Reshape(Filters, -1); + var dW = Dot(dout_flat, xCols.Transpose()); + dW = dW.Reshape(Params["w"].Data.Shape); + var db = Sum(outputgrad, 0, 2, 3, 4).Reshape(Filters, -1); + var W_flat = Params["w"].Data.Reshape(Filters, -1); + + var dX_col = Dot(W_flat.Transpose(), dout_flat); + Input.Grad = ImgUtil.Col2Im(dX_col, Input.Data.Shape, KernalSize.Item1, KernalSize.Item2, KernalSize.Item3, pad, Strides); + + Params["w"].Grad = dW; + if (UseBias) + Params["b"].Grad = db; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource this.SiaNet.Layers.Conv3D.xCols of type TensorSharp.Tensor, Leaked resource weight of type SiaNet.Variable, Leaked resource bias of type SiaNet.Variable in method "Void Conv3D.Forward(Variable)". + +### Severity: +ERROR + +### Procedure: +Void Conv3D.Forward(Variable) + +### File: +SiaNet/Layers/Convolution/Conv3D.cs + +### Key: +Conv3D.cs|Forward|DOTNET_RESOURCE_LEAK + +### Hash: +27449cf5359a5e5870db5a4d2fb6c85a + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2460/instruction.md b/inferredbugs-2460/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c4a4185d82516855d58a6a0295481e8d0fb0f0cd --- /dev/null +++ b/inferredbugs-2460/instruction.md @@ -0,0 +1,148 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** graze +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.ComponentModel.Composition; +using System.ComponentModel.Composition.Hosting; +using System.Diagnostics; +using Mono.Options; + +namespace graze +{ + public class Program + { + static void Main(string[] args) + { + try + { + var parameters = GetParameters(args); + var core = new Core(parameters); + + var extrasFolderCatalog = new DirectoryCatalog(parameters.ExtrasFolder); + var currentAssemblyCatalog = new AssemblyCatalog(typeof(Program).Assembly); + var aggregateCatalog = new AggregateCatalog(extrasFolderCatalog, currentAssemblyCatalog); + + var container = new CompositionContainer(aggregateCatalog); + container.ComposeParts(core); + + core.Run(); + + Console.WriteLine("Static site created successfully"); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + + if (Debugger.IsAttached) + { + Console.ReadLine(); + } + + Environment.ExitCode = 1; + } + } + + static Core.Parameters GetParameters(IEnumerable args) + { + string templateRoot = null; + string outputRoot = null; + string templateFile = null; + string outputFile = null; + string extrasRoot = null; + string configurationFile = null; + string templateAssetsFolder = null; + + var shopHelp = false; + var copyAssets = true; + var copyFile = true; + + var options = new OptionSet + { + {"t|template=", "The template's root folder.", v => templateRoot = v}, + {"o|output=", "The output folder where static site is generated.", v => outputRoot = v}, + {"tf|templatefile=", "The template's file name. Default: index.cshtml.", v => templateFile = v}, + {"of|outputfile=", "The output file which is generated.", v => outputFile = v}, + { "h|help", "Show this message and exit", v => shopHelp = true}, + { "s|skip", "Skip directory creation and asset-folder copy", v => copyAssets = false}, + { "sf|skipfile", "Skip output file copy", v => copyFile = false}, + { "e|extras=", "The extras folder", v => extrasRoot = v }, + { "c|configuration=", "Configuration file with path", v => configurationFile = v }, + { "a|assets=", "Template's assets folder", v => templateAssetsFolder = v }, + }; + + options.Parse(args); + + if (shopHelp) + { + options.WriteOptionDescriptions(Console.Out); + if (Debugger.IsAttached) + { + Console.ReadLine(); + } + + Environment.Exit(0); + } + + var result = new Core.Parameters(templateRoot, outputRoot, copyAssets, templateFile, outputFile, copyFile, configurationFile, templateAssetsFolder, null, 4, extrasRoot); + + return result; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource container of type System.ComponentModel.Composition.Hosting.CompositionContainer, Leaked resource aggregateCatalog of type System.ComponentModel.Composition.Hosting.AggregateCatalog, Leaked resource n$17.[_] of type System.ComponentModel.Composition.Hosting.AssemblyCatalog in method "Void Program.Main(String[])". + +### Severity: +ERROR + +### Procedure: +Void Program.Main(String[]) + +### File: +src/graze/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +1b673e62981c0d305bf5dd83f215e51c + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2467/instruction.md b/inferredbugs-2467/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aaa2f31289d23edf965e795d6df348ba95bfe8e3 --- /dev/null +++ b/inferredbugs-2467/instruction.md @@ -0,0 +1,793 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ExcelMapper +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using NPOI.SS.UserModel; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; +using Ganss.Excel.Exceptions; +using System.Runtime.Serialization.Formatters.Binary; +using System.IO; + +namespace Ganss.Excel.Tests +{ + public class Tests + { + [SetUp] + public void Setup() + { + Environment.CurrentDirectory = TestContext.CurrentContext.TestDirectory; + } + + private class Product + { + public string Name { get; set; } + [Column("Number")] + public int NumberInStock { get; set; } + public decimal Price { get; set; } + public string Value { get; set; } + + public override bool Equals(object obj) + { + if (!(obj is Product o)) return false; + return o.Name == Name && o.NumberInStock == NumberInStock && o.Price == Price && o.Value == Value; + } + + public override int GetHashCode() + { + return (Name + NumberInStock + Price + Value).GetHashCode(); + } + } + + private class ProductValue + { + public decimal Value { get; set; } + } + + private class ProductValueString + { + public decimal Value { get; set; } + public string ValueDefaultAsFormula { get; set; } + [FormulaResult] + public string ValueAsString { get; set; } + } + + [Test] + public void FetchTest() + { + var products = new ExcelMapper(@"..\..\..\products.xlsx").Fetch().ToList(); + CollectionAssert.AreEqual(new List + { + new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C2*D2" }, + new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C3*D3" }, + new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C5*D5" }, + }, products); + } + + [Test] + public void FetchWithTypeTest() + { + var products = new ExcelMapper(@"..\..\..\products.xlsx").Fetch(typeof(Product)); + CollectionAssert.AreEqual(new List + { + new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C2*D2" }, + new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C3*D3" }, + new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C5*D5" }, + }, products); + } + + [Test] + public void FetchWithStreamAndIndexTest() + { + var stream = new FileStream(@"..\..\..\products.xlsx", FileMode.Open, FileAccess.Read); + var products = new ExcelMapper().Fetch(stream, 0); + + CollectionAssert.AreEqual(new List + { + new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C2*D2" }, + new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C3*D3" }, + new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C5*D5" }, + }, products); + } + + [Test] + public void FetchWithTypeUsingStreamAndIndexTest() + { + var stream = new FileStream(@"..\..\..\products.xlsx", FileMode.Open, FileAccess.Read); + var products = new ExcelMapper().Fetch(stream, typeof(Product), 0); + + CollectionAssert.AreEqual(new List + { + new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C2*D2" }, + new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C3*D3" }, + new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C5*D5" }, + }, products); + } + + [Test] + public void FetchWithStreamAndSheetNameTest() + { + var stream = new FileStream(@"..\..\..\products.xlsx", FileMode.Open, FileAccess.Read); + var products = new ExcelMapper().Fetch(stream, "Tabelle1"); + + CollectionAssert.AreEqual(new List + { + new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C2*D2" }, + new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C3*D3" }, + new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C5*D5" }, + }, products); + } + + [Test] + public void FetchWithTypeUsingStreamAndSheetNameTest() + { + var stream = new FileStream(@"..\..\..\products.xlsx", FileMode.Open, FileAccess.Read); + var products = new ExcelMapper().Fetch(stream, typeof(Product), "Tabelle1"); + + CollectionAssert.AreEqual(new List + { + new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C2*D2" }, + new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C3*D3" }, + new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C5*D5" }, + }, products); + } + + [Test] + public void FetchWithFileAndSheetNameTest() + { + var products = new ExcelMapper().Fetch(@"..\..\..\products.xlsx", "Tabelle1"); + + CollectionAssert.AreEqual(new List + { + new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C2*D2" }, + new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C3*D3" }, + new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C5*D5" }, + }, products); + } + + [Test] + public void FetchWithFileAndIndexTest() + { + var products = new ExcelMapper().Fetch(@"..\..\..\products.xlsx", 0); + + CollectionAssert.AreEqual(new List + { + new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C2*D2" }, + new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C3*D3" }, + new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C5*D5" }, + }, products); + } + + [Test] + public void FetchWithTypeThrowsExceptionWithPrimitivesTest() + { + var excel = new ExcelMapper(@"..\..\..\products.xlsx"); + Assert.Throws(() => excel.Fetch(typeof(string))); + Assert.Throws(() => excel.Fetch(typeof(object))); + Assert.Throws(() => excel.Fetch(typeof(int))); + Assert.Throws(() => excel.Fetch(typeof(double?))); + } + + [Test] + public void FetchValueTest() + { + var products = new ExcelMapper(@"..\..\..\products.xlsx").Fetch().ToList(); + CollectionAssert.AreEqual(new List { 119.4m, 98.67m, 99m }, products.Select(p => p.Value).ToList()); + } + + [Test] + public void FetchValueWithTypeTest() + { + var products = new ExcelMapper(@"..\..\..\products.xlsx").Fetch(typeof(ProductValue)) + .OfType() + .ToList(); + CollectionAssert.AreEqual(new List { 119.4m, 98.67m, 99m }, products.Select(p => p.Value).ToList()); + } + + private class ProductException : Product + { + public bool Offer { get; set; } + } + + [Test] + public void FetchExcpetionWhenEmptyTest() + { + var ex = Assert.Throws(() => new ExcelMapper(@"..\..\..\productsExceptionEmpty.xlsx").Fetch().ToList()); + Assert.That(ex.Message.Contains("")); + Assert.That(ex.Message.Contains("[L:1]:[C:2]")); + } + + [Test] + public void FetchWithTypeExcpetionWhenEmptyTest() + { + var ex = Assert.Throws(() => new ExcelMapper(@"..\..\..\productsExceptionEmpty.xlsx").Fetch(typeof(ProductException)) + .OfType() + .ToList()); + Assert.That(ex.Message.Contains("")); + Assert.That(ex.Message.Contains("[L:1]:[C:2]")); + } + + [Test] + public void FetchExcpetionWhenFieldTooBigTest() + { + var ex = Assert.Throws(() => new ExcelMapper(@"..\..\..\productsExceptionTooBig.xlsx").Fetch().ToList()); + //2147483649 is Int.MaxValue + 1 + Assert.That(ex.Message.Contains("2147483649")); + Assert.That(ex.Message.Contains("[L:1]:[C:1]")); + } + + [Test] + public void FetchExcpetionWhenFieldInvalidTest() + { + var ex = Assert.Throws(() => new ExcelMapper(@"..\..\..\productsExceptionInvalid.xlsx").Fetch().ToList()); + Assert.That(ex.Message.Contains("FALSEd")); + Assert.That(ex.Message.Contains("[L:1]:[C:3]")); + } + + [Test] + public void FetchExceptionWhenSheetDoesNotExists() + { + var ex = Assert.Throws(() => new ExcelMapper(@"..\..\..\productsExceptionInvalid.xlsx").Fetch("this sheet does not exist").ToList()); + Assert.That(ex.Message.Contains("Sheet not found")); + } + + [Test] + public void FetchWithTypeThrowsExceptionWhenSheetDoesNotExists() + { + var ex = Assert.Throws(() => new ExcelMapper(@"..\..\..\productsExceptionInvalid.xlsx").Fetch(typeof(ProductException), "This is not a exist") + .OfType() + .ToList()); + Assert.That(ex.Message.Contains("Sheet not found")); + } + + private class ProductNoHeader + { + [Column(1)] + public string Name { get; set; } + [Column(3)] + public int NumberInStock { get; set; } + [Column(4)] + public decimal Price { get; set; } + + public override bool Equals(object obj) + { + if (!(obj is ProductNoHeader o)) return false; + return o.Name == Name && o.NumberInStock == NumberInStock && o.Price == Price; + } + + public override int GetHashCode() + { + return (Name + NumberInStock + Price).GetHashCode(); + } + } + + [Test] + public void FetchNoHeaderTest() + { + var products = new ExcelMapper(@"..\..\..\productsnoheader.xlsx") { HeaderRow = false }.Fetch("Products").ToList(); + CollectionAssert.AreEqual(new List + { + new ProductNoHeader { Name = "Nudossi", NumberInStock = 60, Price = 1.99m }, + new ProductNoHeader { Name = "Halloren", NumberInStock = 33, Price = 2.99m }, + new ProductNoHeader { Name = "Filinchen", NumberInStock = 100, Price = 0.99m }, + }, products); + } + + [Test] + public void FetchWithTypeNoHeaderTest() + { + var products = new ExcelMapper(@"..\..\..\productsnoheader.xlsx") { HeaderRow = false }.Fetch(typeof(ProductNoHeader), "Products") + .OfType() + .ToList(); + CollectionAssert.AreEqual(new List + { + new ProductNoHeader { Name = "Nudossi", NumberInStock = 60, Price = 1.99m }, + new ProductNoHeader { Name = "Halloren", NumberInStock = 33, Price = 2.99m }, + new ProductNoHeader { Name = "Filinchen", NumberInStock = 100, Price = 0.99m }, + }, products); + } + + [Test] + public void SaveTest() + { + var products = new List + { + new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C2*D2" }, + new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C3*D3" }, + new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C4*D4" }, + }; + + var file = "productssave.xlsx"; + + new ExcelMapper().Save(file, products, "Products"); + + var productsFetched = new ExcelMapper(file).Fetch().ToList(); + + CollectionAssert.AreEqual(products, productsFetched); + } + + [Test] + public void SaveNoHeaderSaveTest() + { + var products = new List + { + new ProductNoHeader { Name = "Nudossi", NumberInStock = 60, Price = 1.99m }, + new ProductNoHeader { Name = "Halloren", NumberInStock = 33, Price = 2.99m }, + new ProductNoHeader { Name = "Filinchen", NumberInStock = 100, Price = 0.99m }, + }; + + var file = "productsnoheadersave.xlsx"; + + new ExcelMapper() { HeaderRow = false }.Save(file, products, "Products"); + + var productsFetched = new ExcelMapper(file) { HeaderRow = false }.Fetch().ToList(); + + CollectionAssert.AreEqual(products, productsFetched); + } + + [Test] + public void SaveFetchedTest() + { + var excel = new ExcelMapper(@"..\..\..\products.xlsx"); + var products = excel.Fetch().ToList(); + + products[2].Price += 1.0m; + + var file = @"productssavefetched.xlsx"; + + excel.Save(file, products); + + var productsFetched = new ExcelMapper(file).Fetch().ToList(); + + CollectionAssert.AreEqual(products, productsFetched); + } + + private class ProductMapped + { + public string NameX { get; set; } + public int NumberX { get; set; } + public decimal PriceX { get; set; } + + public override bool Equals(object obj) + { + if (!(obj is ProductMapped o)) return false; + return o.NameX == NameX && o.NumberX == NumberX && o.PriceX == PriceX; + } + + public override int GetHashCode() + { + return (NameX + NumberX + PriceX).GetHashCode(); + } + } + + [Test] + public void SaveTrackedObjectsTest() + { + var excel = new ExcelMapper(@"..\..\..\products.xlsx") { TrackObjects = true }; + + excel.AddMapping(typeof(ProductMapped), "Name", "NameX"); + excel.AddMapping("Number", p => p.NumberX); + excel.AddMapping("Price", p => p.PriceX); + + var products = excel.Fetch().ToList(); + + products[1].PriceX += 1.0m; + + var file = @"productssavetracked.xlsx"; + + excel.Save(file); + + var productsFetched = new ExcelMapper(file).Fetch().ToList(); + + CollectionAssert.AreEqual(products, productsFetched); + } + + private class GetterSetterProduct + { + public string Name { get; set; } + public DateTime? OfferEnd { get; set; } + + public override bool Equals(object obj) + { + if (!(obj is GetterSetterProduct o)) return false; + return o.Name == Name && o.OfferEnd == OfferEnd; + } + + public override int GetHashCode() + { + return (Name + OfferEnd).GetHashCode(); + } + } + + [Test] + public void GetterSetterTest() + { + var excel = new ExcelMapper(@"..\..\..\productsconvert.xlsx") { TrackObjects = true }; + + excel.AddMapping("Name", p => p.Name); + excel.AddMapping("OfferEnd", p => p.OfferEnd) + .SetCellUsing((c, o) => + { + if (o == null) c.SetCellValue("NULL"); else c.SetCellValue((DateTime)o); + }) + .SetPropertyUsing(v => + { + if ((v as string) == "NULL") return null; + return Convert.ChangeType(v, typeof(DateTime), CultureInfo.InvariantCulture); + }); + + var products = excel.Fetch().ToList(); + + var file = @"productsconverttracked.xlsx"; + + excel.Save(file); + + var productsFetched = new ExcelMapper(file).Fetch().ToList(); + + CollectionAssert.AreEqual(products, productsFetched); + } + + private class IgnoreProduct + { + public string Name { get; set; } + [Ignore] + public int Number { get; set; } + public decimal Price { get; set; } + public bool Offer { get; set; } + public DateTime OfferEnd { get; set; } + + public override bool Equals(object obj) + { + if (!(obj is IgnoreProduct o)) return false; + return o.Name == Name && o.Number == Number && o.Price == Price && o.Offer == Offer && o.OfferEnd == OfferEnd; + } + + public override int GetHashCode() + { + return (Name + Number + Price + Offer + OfferEnd).GetHashCode(); + } + } + + [Test] + public void IgnoreTest() + { + var excel = new ExcelMapper(@"..\..\..\products.xlsx"); + excel.Ignore(p => p.Price); + var products = excel.Fetch().ToList(); + + var nudossi = products[0]; + Assert.AreEqual("Nudossi", nudossi.Name); + Assert.AreEqual(0, nudossi.Number); + Assert.AreEqual(0m, nudossi.Price); + Assert.IsFalse(nudossi.Offer); + + var halloren = products[1]; + Assert.IsTrue(halloren.Offer); + Assert.AreEqual(new DateTime(2015, 12, 31), halloren.OfferEnd); + + var file = "productsignored.xlsx"; + + new ExcelMapper().Save(file, products, "Products"); + + var productsFetched = new ExcelMapper(file).Fetch().ToList(); + + CollectionAssert.AreEqual(products, productsFetched); + } + + private class NullableProduct + { + public string Name { get; set; } + public int? Number { get; set; } + public decimal? Price { get; set; } + public bool? Offer { get; set; } + public DateTime? OfferEnd { get; set; } + + public override bool Equals(object obj) + { + if (!(obj is NullableProduct o)) return false; + return o.Name == Name && o.Number == Number && o.Price == Price && o.Offer == Offer && o.OfferEnd == OfferEnd; + } + + public override int GetHashCode() + { + return (Name + Number + Price + Offer + OfferEnd).GetHashCode(); + } + } + + [Test] + public void NullableTest() + { + var workbook = WorkbookFactory.Create(@"..\..\..\products.xlsx"); + var excel = new ExcelMapper(workbook); + var products = excel.Fetch().ToList(); + + var nudossi = products[0]; + Assert.AreEqual("Nudossi", nudossi.Name); + Assert.AreEqual(60, nudossi.Number); + Assert.AreEqual(1.99m, nudossi.Price); + Assert.IsFalse(nudossi.Offer.Value); + nudossi.OfferEnd = null; + + var halloren = products[1]; + Assert.IsTrue(halloren.Offer.Value); + Assert.AreEqual(new DateTime(2015, 12, 31), halloren.OfferEnd); + halloren.Number = null; + halloren.Offer = null; + + var file = "productsnullable.xlsx"; + + new ExcelMapper().Save(file, products, "Products"); + + var productsFetched = new ExcelMapper(file).Fetch().ToList(); + + CollectionAssert.AreEqual(products, productsFetched); + } + + private class DataFormatProduct + { + [DataFormat(0xf)] + public DateTime Date { get; set; } + + [DataFormat("0%")] + public decimal Number { get; set; } + } + + [Test] + public void DataFormatTest() + { + var p = new DataFormatProduct { Date = new DateTime(2015, 12, 31), Number = 0.47m }; + var file = "productsdataformat.xlsx"; + new ExcelMapper().Save(file, new[] { p }); + var pfs = new ExcelMapper(file).Fetch().ToList(); + + Assert.AreEqual(1, pfs.Count); + var pf = pfs[0]; + Assert.AreEqual(p.Date, pf.Date); + Assert.AreEqual(p.Number, pf.Number); + } + + private class DataItem + { + [Ignore] + public string Bql { get; set; } + + [Ignore] + public int Id { get; set; } + + [Column(2)] + public string OriginalBql { get; set; } + + [Column(1)] + public string Title { get; set; } + + [Column(3)] + public string TranslatedBql { get; set; } + + public override bool Equals(object obj) + { + if (!(obj is DataItem o)) return false; + return o.Bql == Bql && o.Id == Id && o.OriginalBql == OriginalBql && o.Title == Title && o.TranslatedBql == TranslatedBql; + } + + public override int GetHashCode() + { + return (Bql + Id + OriginalBql + Title + TranslatedBql).GetHashCode(); + } + } + + [Test] + public void ColumnTest() + { + var excel = new ExcelMapper(@"..\..\..\dataitems.xlsx") { HeaderRow = false }; + var items = excel.Fetch().ToList(); + + var trackedFile = "dataitemstracked.xlsx"; + excel.Save(trackedFile, "DataItems"); + var itemsTracked = excel.Fetch(trackedFile, "DataItems").ToList(); + CollectionAssert.AreEqual(items, itemsTracked); + + var saveFile = "dataitemssave.xlsx"; + new ExcelMapper().Save(saveFile, items, "DataItems"); + var itemsSaved = new ExcelMapper().Fetch(saveFile, "DataItems").ToList(); + CollectionAssert.AreEqual(items, itemsSaved); + } + + [Test] + public void ColumnTestUsingFetchWithType() + { + var excel = new ExcelMapper(@"..\..\..\dataitems.xlsx") { HeaderRow = false }; + var items = excel.Fetch(typeof(DataItem)).OfType().ToList(); + + var trackedFile = "dataitemstracked.xlsx"; + excel.Save(trackedFile, "DataItems"); + var itemsTracked = excel.Fetch(trackedFile, typeof(DataItem), "DataItems").OfType().ToList(); + CollectionAssert.AreEqual(items, itemsTracked); + + var saveFile = "dataitemssave.xlsx"; + new ExcelMapper().Save(saveFile, items, "DataItems"); + var itemsSaved = new ExcelMapper().Fetch(saveFile, typeof(DataItem), "DataItems").OfType().ToList(); + CollectionAssert.AreEqual(items, itemsSaved); + } + + [Test] + public void FetchMinMaxTest() + { + var products = new ExcelMapper(@"..\..\..\ProductsMinMaxRow.xlsx") + { + HeaderRowNumber = 2, + MinRowNumber = 6, + MaxRowNumber = 9, + }.Fetch().ToList(); + CollectionAssert.AreEqual(new List + { + new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C7*D7" }, + new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C8*D8" }, + new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C10*D10" }, + }, products); + } + + [Test] + public void SaveMinMaxTest() + { + var products = new List + { + new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m, Value = "C2*D2" }, + new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m, Value = "C3*D3" }, + new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m, Value = "C4*D4" }, + }; + + var file = "productsminmaxsave.xlsx"; + + new ExcelMapper + { + HeaderRowNumber = 1, + MinRowNumber = 3 + }.Save(file, products, "Products"); + + var productsFetched = new ExcelMapper(file) + { + HeaderRowNumber = 1, + MinRowNumber = 3 + }.Fetch().ToList(); + + CollectionAssert.AreEqual(products, productsFetched); + } + + [Test] + public void FormulaResultAttributeTest() + { + var products = new ExcelMapper(@"..\..\..\ProductsAsString.xlsx").Fetch().ToList(); + CollectionAssert.AreEqual(new List { "119.4", "98.67", "99" }, products.Select(p => p.ValueAsString).ToList()); + } + + private class ProductFormulaMapped + { + public decimal Result { get; set; } + public string Formula { get; set; } + public string ResultString { get; set; } + + public override bool Equals(object obj) + { + if (!(obj is ProductFormulaMapped o)) return false; + return o.Result == Result && o.Formula == Formula && o.ResultString == ResultString; + } + + public override int GetHashCode() + { + return (Formula + ResultString + Result).GetHashCode(); + } + } + + [Test] + public void FormulaResultMappedTest() + { + var excel = new ExcelMapper(@"..\..\..\ProductsAsString.xlsx"); + + excel.AddMapping("Value", p => p.Result); + excel.AddMapping("ValueDefaultAsFormula", p => p.Formula); + excel.AddMapping("ValueAsString", p => p.ResultString).AsFormulaResult(); + + var products = excel.Fetch().ToList(); + var expectedProducts = new List + { + new ProductFormulaMapped { Result = 119.4m, Formula = "C2*D2", ResultString = "119.4" }, + new ProductFormulaMapped { Result = 98.67m, Formula = "C3*D3", ResultString = "98.67" }, + new ProductFormulaMapped { Result = 99m, Formula = "C5*D5", ResultString = "99" }, + }; + + Assert.AreEqual(expectedProducts[0], products[0]); + + CollectionAssert.AreEqual(expectedProducts, products); + } + + [Test] + public void TestExcelMapperConvertException() + { + ExcelMapperConvertException ex = + new ExcelMapperConvertException("cellvalue", typeof(string), 12, 34); + + // Sanity check: Make sure custom properties are set before serialization + Assert.AreEqual(12, ex.Line); + Assert.AreEqual(34, ex.Column); + + // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter + var bf = new BinaryFormatter(); + using (var ms = new MemoryStream()) + { + // "Save" object state + bf.Serialize(ms, ex); + + // Re-use the same stream for de-serialization + ms.Seek(0, 0); + + // Replace the original exception with de-serialized one + ex = (ExcelMapperConvertException)bf.Deserialize(ms); + } + + // Make sure custom properties are preserved after serialization + Assert.AreEqual(12, ex.Line); + Assert.AreEqual(34, ex.Column); + + Assert.Throws(() => ex.GetObjectData(null, new System.Runtime.Serialization.StreamingContext())); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource stream of type System.IO.FileStream in method "Void Tests.FetchWithStreamAndSheetNameTest()". + +### Severity: +ERROR + +### Procedure: +Void Tests.FetchWithStreamAndSheetNameTest() + +### File: +ExcelMapper.Tests/Tests.cs + +### Key: +Tests.cs|FetchWithStreamAndSheetNameTest|DOTNET_RESOURCE_LEAK + +### Hash: +56158166580ea46553a34dd8c116b39b + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2469/instruction.md b/inferredbugs-2469/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..68adbb6ffe095902cbbe28eccb160af8f37c0cf7 --- /dev/null +++ b/inferredbugs-2469/instruction.md @@ -0,0 +1,125 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Universalis +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; + +namespace Universalis.GameData +{ + public static class ChineseServers + { + /// + /// Converts the provided data center name into its Hanzi form. If the provided data center name + /// is not a Chinese data center, an will be thrown. + /// + /// The provided data center is not a Chinese data center. + /// The data center name, romanized or already in Hanzi. + /// + public static string DataCenterToHanzi(string dataCenter) + => dataCenter switch + { + "LuXingNiao" => "陆行鸟", + "MoGuLi" => "莫古力", + "MaoXiaoPang" => "猫小胖", + "陆行鸟" => "陆行鸟", + "莫古力" => "莫古力", + "猫小胖" => "猫小胖", + _ => throw new ArgumentException("No mapping for the provided data center was found."), + }; + + internal static IEnumerable DataCenters() + => new[] + { + new DataCenter {Name = "LuXingNiao"}, + new DataCenter {Name = "MoGuLi"}, + new DataCenter {Name = "MaoXiaoPang"}, + new DataCenter {Name = "陆行鸟"}, // LuXingNiao + new DataCenter {Name = "莫古力"}, // MoGuLi + new DataCenter {Name = "猫小胖"}, // MaoXiaoPang + }; + + internal static IEnumerable Worlds() + => new[] + { + new World{Name = "红玉海", Id = 1167}, + new World{Name = "神意之地", Id = 1081}, + new World{Name = "拉诺西亚", Id = 1042}, + new World{Name = "幻影群岛", Id = 1044}, + new World{Name = "萌芽池", Id = 1060}, + new World{Name = "宇宙和音", Id = 1173}, + new World{Name = "沃仙曦染", Id = 1174}, + new World{Name = "晨曦王座", Id = 1175}, + new World{Name = "白银乡", Id = 1172}, + new World{Name = "白金幻象", Id = 1076}, + new World{Name = "神拳痕", Id = 1171}, + new World{Name = "潮风亭", Id = 1170}, + new World{Name = "旅人栈桥", Id = 1113}, + new World{Name = "拂晓之间", Id = 1121}, + new World{Name = "龙巢神殿", Id = 1166}, + new World{Name = "梦羽宝境", Id = 1176}, + new World{Name = "紫水栈桥", Id = 1043}, + new World{Name = "延夏", Id = 1169}, + new World{Name = "静语庄园", Id = 1106}, + new World{Name = "摩杜纳", Id = 1045}, + new World{Name = "海猫茶屋", Id = 1177}, + new World{Name = "柔风海湾", Id = 1178}, + new World{Name = "琥珀原", Id = 1179}, + }; + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +null (last assigned on line 28) is dereferenced. + +### Severity: +ERROR + +### Procedure: +IEnumerable`1 ChineseServers.DataCenters() + +### File: +src/Universalis.GameData/ChineseServers.cs + +### Key: +ChineseServers.cs|DataCenters|NULLPTR_DEREFERENCE + +### Hash: +cc75f7cf186ef69b0048f04e6a5a5a7e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2493/instruction.md b/inferredbugs-2493/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8689cc4d1d79dfb440f8d7afe2ed8c2c0aedccf4 --- /dev/null +++ b/inferredbugs-2493/instruction.md @@ -0,0 +1,120 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** MxNet.Sharp +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using MxNetLib; +using MxNetLib.Metrics; +using MxNetLib.NN; +using MxNetLib.NN.Data; +using MxNetLib.NN.Initializers; +using MxNetLib.NN.Layers; +using MxNetLib.Optimizers; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace ORGate +{ + class Program + { + static void Main(string[] args) + { + MXNet.SetDevice(DeviceType.CPU); + + //Pred data + DataFrame train_x = new DataFrame(2); + DataFrame train_y = new DataFrame(1); + train_x.Load(0, 0, 0, 1, 1, 0, 1, 1); + + train_y.Load(0, 1, 1, 0); + + NDArrayIter train = new NDArrayIter(train_x.ToVariable(), train_y.ToVariable()); + + //Build Model + Module model = new Module(2); + BuildSymbolModel(model); + //BuildNNModel(model); + model.Fit(train, 1000, 2); + + Console.ReadLine(); + } + + private static void BuildSymbolModel(Module model) + { + var x = Symbol.Variable("X"); + var fc1 = sym.Relu(sym.FullyConnected(x, Symbol.Variable("fc1_w"), 64)); + var fc2 = sym.Relu(sym.FullyConnected(fc1, Symbol.Variable("fc2_w"), 32)); + var fc3 = sym.Relu(sym.FullyConnected(fc2, Symbol.Variable("fc3_w"), 1)); + var output = sym.LogisticRegressionOutput(fc3, Symbol.Variable("label")); + + model.SetDefaultInitializer(new RandomUniform(-1, 1)); + model.Compile(output, OptimizerRegistry.Adam(), MetricType.BinaryAccuracy); + } + + private static void BuildNNModel(Module model) + { + model.Add(new Dense(dim: 64, activation: ActivationType.ReLU, kernalInitializer: new RandomUniform(-1, 1))); + model.Add(new Dense(dim: 32, activation: ActivationType.ReLU, kernalInitializer: new GlorotUniform())); + model.Add(new Dense(dim: 1)); + + //Train + model.Compile(OptimizerType.Adam, LossType.SigmoidBinaryCrossEntropy, MetricType.BinaryAccuracy); + } + + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource train of type MxNetLib.NDArrayIter, Leaked resource (returned from MxNetLib.NDArray MxNetLib.NN.Data.DataFrame::ToVariable() at Line 85) of type MxNetLib.NDArray, Leaked resource (returned from MxNetLib.NDArray MxNetLib.NN.Data.DataFrame::ToVariable() at Line 85) of type MxNetLib.NDArray in method "Void Program.Main(String[])". + +### Severity: +ERROR + +### Procedure: +Void Program.Main(String[]) + +### File: +examples/ORGate/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +33d17ffeb3279d533abbc31f48d841ba + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2494/instruction.md b/inferredbugs-2494/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e78ff7ff4201989ece981d2431222b7d7e2030c2 --- /dev/null +++ b/inferredbugs-2494/instruction.md @@ -0,0 +1,148 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** MxNet.Sharp +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using MxNetLib; +using System; +using System.Collections.Generic; +using System.Text; + +namespace MxNetLib +{ + public class NDArrayIter : DataIter + { + private NDArray _data; + private NDArray _label; + + private uint num_data; + + public NDArrayIter(NDArray data, NDArray label) + { + _data = data; + _label = label; + BatchSize = 32; + num_data = data.GetShape()[0]; + cursor = (int)-BatchSize; + } + + public override void BeforeFirst() + { + cursor = (int)-BatchSize; + } + + public override NDArray GetData() + { + uint start = (uint)cursor; + uint end = (uint)cursor + BatchSize; + if(end > num_data) + { + end = num_data; + } + + return _data.Slice(start, end); + } + + public override int[] GetIndex() + { + uint start = (uint)cursor; + uint end = (uint)cursor + BatchSize; + if (end > num_data) + { + end = num_data; + } + + List idx = new List(); + for (int i = (int)start; i < end; i++) + { + idx.Add((int)i); + } + + return idx.ToArray(); + } + + public override NDArray GetLabel() + { + uint start = (uint)cursor; + uint end = (uint)cursor + BatchSize; + if (end >= num_data) + { + end = num_data; + } + + return _label.Slice(start, end).Ravel(); + } + + public override int GetPadNum() + { + return 0; + } + + public override bool Next() + { + cursor += (int)BatchSize; + if(cursor < num_data) + { + return true; + } + else + { + return false; + } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from MxNetLib.NDArray MxNetLib.NDArray::Slice(System.UInt32,System.UInt32) at Line 68) of type MxNetLib.NDArray in method "NDArray NDArrayIter.GetLabel()". + +### Severity: +ERROR + +### Procedure: +NDArray NDArrayIter.GetLabel() + +### File: +src/MxNetLib/IO/NDArrayIter.cs + +### Key: +NDArrayIter.cs|GetLabel|DOTNET_RESOURCE_LEAK + +### Hash: +247c08660a425397f164482a8a136774 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2541/instruction.md b/inferredbugs-2541/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..219f55ea0aee6ee703bae8885a3bdf2ffa363e57 --- /dev/null +++ b/inferredbugs-2541/instruction.md @@ -0,0 +1,409 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** docker-lambda +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using AWSLambda.Internal.Bootstrap.Context; +using AWSLambda.Internal.Bootstrap.Interop.Structures; +using MockLambdaRuntime; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +namespace AWSLambda.Internal.Bootstrap +{ + internal class MockRuntime : ILambdaRuntime + { + private const string STACK_TRACE_INDENT = " "; + + private bool invoked; + + private bool logTail; + + private string logs; + + private Exception invokeError; + + private readonly IntPtr sharedMem = Marshal.AllocHGlobal(SBSharedMem.UnmanagedStructSize); + + private SBSharedMem curSBSharedMem; + + private readonly MockLambdaContext context; + + private static readonly HttpClient client = new HttpClient(); + + public IEnvironment Environment { get; } = new SystemEnvironment(); + + public IXRayProfiler XRayProfiler { get; } = new MockXRayProfiler(); + + public InitData InitData + { + get; + private set; + } + + public MockRuntime(string handler, string body) + { + context = new MockLambdaContext(handler, body); + InitData = new InitData + { + Handler = handler, + InvokeId = context.RequestId, + SuppressUserCodeInit = true, + ErrorCode = null + }; + invoked = false; + client.Timeout = Timeout.InfiniteTimeSpan; + } + + public bool KeepInvokeLoopRunning() + { + return true; + } + + public void Init() + { + var timeout = DateTimeOffset.Now.AddSeconds(1); + while (true) + { + try + { + var result = client.GetAsync("http://127.0.0.1:9001/2018-06-01/ping").Result; + if (result.StatusCode != HttpStatusCode.OK) + { + throw new Exception("Got a bad response from the bootstrap"); + } + break; + } + catch (Exception e) + { + if (DateTimeOffset.Now > timeout) + { + throw e; + } + } + Thread.Sleep(5); + } + } + + unsafe InvokeData ILambdaRuntime.ReceiveInvoke(IDictionary initialEnvironmentVariables, RuntimeReceiveInvokeBuffers buffers) + { + var result = client.GetAsync("http://127.0.0.1:9001/2018-06-01/runtime/invocation/next").Result; + if (result.StatusCode != HttpStatusCode.OK) + { + throw new Exception("Got a bad response from the bootstrap"); + } + + if (invoked) + { + logs = ""; + } + invoked = true; + + var requestId = result.Headers.GetValues("Lambda-Runtime-Aws-Request-Id").First(); + var deadlineMs = result.Headers.GetValues("Lambda-Runtime-Deadline-Ms").First(); + var functionArn = result.Headers.GetValues("Lambda-Runtime-Invoked-Function-Arn").First(); + var xAmznTraceId = result.Headers.GetValues("Lambda-Runtime-Trace-Id").First(); + var clientContext = HeaderHelper.GetFirstOrDefault(result.Headers, "Lambda-Runtime-Client-Context"); + var cognitoIdentity = HeaderHelper.GetFirstOrDefault(result.Headers, "Lambda-Runtime-Cognito-Identity"); + + logTail = HeaderHelper.GetFirstOrDefault(result.Headers, "Docker-Lambda-Log-Type") == "Tail"; + + var body = result.Content.ReadAsStringAsync().Result; + + context.RequestId = requestId; + context.DeadlineMs = long.Parse(deadlineMs); + context.Body = body; + + curSBSharedMem = new SBSharedMem(sharedMem); + return new InvokeData(curSBSharedMem) + { + RequestId = context.RequestId, + AwsCredentials = new AwsCredentials + { + AccessKeyId = EnvHelper.GetOrDefault("AWS_ACCESS_KEY_ID", "SOME_ACCESS_KEY_ID"), + SecretAccessKey = EnvHelper.GetOrDefault("AWS_SECRET_ACCESS_KEY", "SOME_SECRET_ACCESS_KEY"), + SessionToken = System.Environment.GetEnvironmentVariable("AWS_SESSION_TOKEN") + }, + XAmznTraceId = xAmznTraceId, + InputStream = context.InputStream, + OutputStream = new UnmanagedMemoryStream(curSBSharedMem.EventBody, 0, SBSharedMem.SizeOfEventBody, FileAccess.Write), + LambdaContextInternal = new LambdaContextInternal( + context.RemainingTime, + SendCustomerLogMessage, + GetCognitoClientContextInternalLazy(clientContext), + context.RequestId, + new Lazy(context.Arn), + GetCognitoIdentityIdLazy(cognitoIdentity), + GetCognitoIdentityPoolIdLazy(cognitoIdentity), + initialEnvironmentVariables + ) + }; + } + + public unsafe void ReportDone(string invokeId, string errorType, bool waitForExit) + { + if (!invoked && invokeError == null) return; + + var output = Interop.InteropUtils.ReadUTF8String(curSBSharedMem.EventBody, curSBSharedMem.ResponseBodyLen); + + var suffix = errorType == null ? "response" : "error"; + + Task task; + using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"http://127.0.0.1:9001/2018-06-01/runtime/invocation/{context.RequestId}/{suffix}")) + { + if (logTail) + { + requestMessage.Headers.Add("Docker-Lambda-Log-Result", Convert.ToBase64String(LogsTail4k())); + } + requestMessage.Content = new StringContent(output); + task = client.SendAsync(requestMessage); + try + { + task.Wait(); + } + catch (AggregateException ae) + { + if (!context.StayOpen && ae.InnerException is HttpRequestException && ae.InnerException.InnerException != null && + (ae.InnerException.InnerException is SocketException || + // happens on dotnetcore2.0 + ae.InnerException.InnerException.GetType().ToString().Equals("System.Net.Http.CurlException"))) + { + System.Environment.Exit(string.IsNullOrEmpty(errorType) && invokeError == null ? 0 : 1); + } + else + { + throw ae; + } + } + var response = task.Result; + if (response.StatusCode != HttpStatusCode.Accepted) + { + throw new Exception($"Unknown response from invocation: {response.StatusCode}"); + } + } + if (invokeError != null) + { + Console.Error.WriteLine(invokeError); + return; + } + } + + private byte[] LogsTail4k() + { + var logBuf = Encoding.UTF8.GetBytes(logs); + if (logBuf.Length <= 4096) + { + return logBuf; + } + var slicedLogBuf = new byte[4096]; + Array.Copy(logBuf, logBuf.Length - 4096, slicedLogBuf, 0, 4096); + return slicedLogBuf; + } + + public void ReportError(string invokeId, ExceptionResponse exceptionResponse) + { + invokeError = exceptionResponse.OriginalException; + + // XXX: For the future perhaps: + /* + StringBuilder stringBuilder = new StringBuilder(); + if (!string.IsNullOrEmpty(exceptionResponse.StackTrace)) + { + stringBuilder.AppendLine(exceptionResponse.StackTrace); + } + if (exceptionResponse.InnerException != null) + { + AppendStackTraceToStringBuilder(stringBuilder, exceptionResponse.InnerException); + } + */ + } + + /// Try to log everything to stderr except the function result + public void SendCustomerLogMessage(string message) + { + if (context.StayOpen) + { + if (logTail) + { + logs += message + System.Environment.NewLine; + } + Console.WriteLine(message); + } + else + { + Console.Error.WriteLine(message); + } + } + + private static void AppendStackTraceToStringBuilder(StringBuilder builder, ExceptionResponse ex) + { + if (!string.IsNullOrWhiteSpace(ex.StackTrace)) + { + string[] array = (from s in ex.StackTrace.Split(new string[] + { + System.Environment.NewLine + }, StringSplitOptions.None) + select s.Trim() into s + where !string.IsNullOrWhiteSpace(s) + select STACK_TRACE_INDENT + s).ToArray(); + foreach (string value in array) + { + builder.AppendLine(value); + } + } + if (ex.InnerException != null) + { + string errorMessage = ex.InnerException.ErrorMessage; + string errorType = ex.InnerException.ErrorType; + if (errorMessage != null) + { + builder.Append(errorMessage.Trim()); + builder.Append(": "); + } + builder.AppendLine(errorType); + AppendStackTraceToStringBuilder(builder, ex.InnerException); + } + } + + internal static Lazy GetCognitoIdentityIdLazy(string jsonStr) + { + return new Lazy(() => + { + var match = Regex.Match(jsonStr ?? "", "\"identity_id\":\"([^\"]+)\""); + return match.Success ? match.Groups[1].ToString() : string.Empty; + }); + } + + internal static Lazy GetCognitoIdentityPoolIdLazy(string jsonStr) + { + return new Lazy(() => + { + var match = Regex.Match(jsonStr ?? "", "\"identity_pool_id\":\"([^\"]+)\""); + return match.Success ? match.Groups[1].ToString() : string.Empty; + }); + } + + internal static Lazy GetCognitoClientContextInternalLazy(string text) + { + return new Lazy(() => + { + CognitoClientContextInternal result = null; + if (!string.IsNullOrEmpty(text)) + { + try + { + return CognitoClientContextInternal.FromJson(text); + } + catch (Exception innerException) + { + throw LambdaExceptions.ValidationException(innerException, "Unable to parse client context JSON string '{0}'.", text); + } + } + return result; + }); + } + } + + internal class MockXRayProfiler : IXRayProfiler + { + public void ReportUserInitStart() + { + } + + public void ReportUserInitEnd() + { + } + + public void ReportUserInvokeStart() + { + } + + public void ReportUserInvokeEnd() + { + } + + public void ReportError(ExceptionResponse exceptionResponse) + { + } + } + + class HeaderHelper + { + /// Gets the given environment variable with a fallback if it doesn't exist + public static string GetFirstOrDefault(HttpHeaders headers, string name) + { + if (headers.TryGetValues(name, out IEnumerable values)) + { + return values.FirstOrDefault(); + } + return null; + } + } + +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource requestMessage of type System.Net.Http.HttpRequestMessage, Leaked resource (output of System.Net.Http.StringContent::.ctor() at Line 165) of type System.Net.Http.StringContent in method "Void MockRuntime.ReportDone(String,String,Boolean)". + +### Severity: +ERROR + +### Procedure: +Void MockRuntime.ReportDone(String,String,Boolean) + +### File: +dotnetcore2.0/run/MockBootstraps/MockRuntime.cs + +### Key: +MockRuntime.cs|ReportDone|DOTNET_RESOURCE_LEAK + +### Hash: +b26efbdf3055933f86deeb4745f122a7 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2546/instruction.md b/inferredbugs-2546/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..52a4f2bcbbf6c01120ade1d2a29c976471144c4f --- /dev/null +++ b/inferredbugs-2546/instruction.md @@ -0,0 +1,172 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Entitas-CSharp +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using Entitas.CodeGeneration.CodeGenerator; +using Entitas.Utils; +using Fabl.Appenders; +using UnityEditor; +using UnityEngine; + +namespace Entitas.CodeGeneration.Unity.Editor { + + public static class UnityCodeGenerator { + + [MenuItem("Tools/Entitas/Generate #%g", false, 100)] + public static void Generate() { + checkCanGenerate(); + + Debug.Log("Generating..."); + + Preferences.sharedInstance.Refresh(); + var codeGenerator = CodeGeneratorUtil.CodeGeneratorFromPreferences(Preferences.sharedInstance); + + var progressOffset = 0f; + + codeGenerator.OnProgress += (title, info, progress) => { + var cancel = EditorUtility.DisplayCancelableProgressBar(title, info, progressOffset + progress / 2); + if (cancel) { + codeGenerator.Cancel(); + } + }; + + CodeGenFile[] dryFiles = null; + CodeGenFile[] files = null; + + try { + dryFiles = codeGenerator.DryRun(); + progressOffset = 0.5f; + files = codeGenerator.Generate(); + } catch(Exception ex) { + dryFiles = new CodeGenFile[0]; + files = new CodeGenFile[0]; + + EditorUtility.DisplayDialog("Error", ex.Message, "Ok"); + } + + EditorUtility.ClearProgressBar(); + + var totalGeneratedFiles = files.Select(file => file.fileName).Distinct().Count(); + + var sloc = dryFiles + .Select(file => file.fileContent.ToUnixLineEndings()) + .Sum(content => content.Split(new [] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length); + + var loc = files + .Select(file => file.fileContent.ToUnixLineEndings()) + .Sum(content => content.Split(new [] { '\n' }).Length); + + Debug.Log("Generated " + totalGeneratedFiles + " files (" + sloc + " sloc, " + loc + " loc)"); + + AssetDatabase.Refresh(); + } + + static void checkCanGenerate() { + if (EditorApplication.isCompiling) { + throw new Exception("Cannot generate because Unity is still compiling. Please wait..."); + } + + var assembly = typeof(UnityEditor.Editor).Assembly; + + var logEntries = assembly.GetType("UnityEditorInternal.LogEntries") + ?? assembly.GetType("UnityEditor.LogEntries"); + + logEntries.GetMethod("Clear").Invoke(new object(), null); + var canCompile = (int)logEntries.GetMethod("GetCount").Invoke(new object(), null) == 0; + if (!canCompile) { + Debug.Log("There are compile errors! Generated code will be based on last compiled executable."); + } + } + + [MenuItem("Tools/Entitas/Generate with external Code Generator %&g", false, 101)] + public static void GenerateExternal() { + Debug.Log("Connecting..."); + + var client = new TcpClientSocket(); + client.OnConnect += onConnected; + client.OnReceive += onReceive; + client.OnDisconnect += onDisconnect; + client.Connect(IPAddress.Parse("127.0.0.1"), 3333); + + AssetDatabase.Refresh(); + } + + static void onConnected(TcpClientSocket client) { + Debug.Log("Connected."); + Debug.Log("Generating..."); + client.Send(Encoding.UTF8.GetBytes("gen")); + } + + static void onReceive(AbstractTcpSocket socket, Socket client, byte[] bytes) { + Debug.Log("Generated."); + socket.Disconnect(); + } + + static void onDisconnect(AbstractTcpSocket socket) { + Debug.Log("Disconnected"); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `logEntries` last assigned on line 80 could be null and is dereferenced at line 75, column 13. + +### Severity: +ERROR + +### Procedure: +Void UnityCodeGenerator.checkCanGenerate() + +### File: +Addons/Entitas.CodeGeneration.Unity.Editor/Entitas.CodeGeneration.Unity.Editor/Editor/UnityCodeGenerator.cs + +### Key: +UnityCodeGenerator.cs|checkCanGenerate|NULL_DEREFERENCE + +### Node Key: +e0be9bf879e0b443f0f0e322250a767f + +### Hash: +8d2493dd2fa0bf257ba56cdbf49aeba8 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2579/instruction.md b/inferredbugs-2579/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c73bc60b9635ca56657e116364c6d18e5647ddc7 --- /dev/null +++ b/inferredbugs-2579/instruction.md @@ -0,0 +1,171 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** serilog +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// Copyright 2013 Nicholas Blumhardt +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using Serilog.Configuration; +using Serilog.Events; +using Serilog.Formatting.Display; +using Serilog.Sinks.DumpFile; +using Serilog.Sinks.File; +using Serilog.Sinks.RollingFile; +using Serilog.Sinks.SystemConsole; + +namespace Serilog +{ + /// + /// Extends to add Full .NET Framework + /// capabilities. + /// + public static class LoggerConfigurationFullNetFxExtensions + { + const string DefaultOutputTemplate = "{TimeStamp} [{Level}] {Message:l}{NewLine:l}{Exception:l}"; + + /// + /// Writes log events to . + /// + /// Logger sink configuration. + /// The minimum level for + /// events passed through the sink. + /// A message template describing the format used to write to the sink. + /// the default is "{TimeStamp} [{Level}] {Message:l}{NewLine:l}{Exception:l}". + /// Configuration object allowing method chaining. + public static LoggerConfiguration Console( + this LoggerSinkConfiguration sinkConfiguration, + LogEventLevel restrictedToMinimumLevel = LogEventLevel.Minimum, + string outputTemplate = DefaultOutputTemplate) + { + var formatter = new MessageTemplateTextFormatter(outputTemplate); + return sinkConfiguration.Sink(new ConsoleSink(formatter), restrictedToMinimumLevel); + } + + /// + /// Write log events in a simple text dump format to the specified file. + /// + /// Logger sink configuration. + /// Path to the dump file. + /// The minimum level for + /// events passed through the sink. + /// Configuration object allowing method chaining. + public static LoggerConfiguration DumpFile( + this LoggerSinkConfiguration sinkConfiguration, + string path, + LogEventLevel restrictedToMinimumLevel = LogEventLevel.Minimum) + { + return sinkConfiguration.Sink(new DumpFileSink(path), restrictedToMinimumLevel); + } + + /// + /// Write log events to the specified file. + /// + /// Logger sink configuration. + /// Path to the file. + /// The minimum level for + /// events passed through the sink. + /// A message template describing the format used to write to the sink. + /// the default is "{TimeStamp} [{Level}] {Message:l}{NewLine:l}{Exception:l}". + /// Configuration object allowing method chaining. + public static LoggerConfiguration File( + this LoggerSinkConfiguration sinkConfiguration, + string path, + LogEventLevel restrictedToMinimumLevel = LogEventLevel.Minimum, + string outputTemplate = DefaultOutputTemplate) + { + var formatter = new MessageTemplateTextFormatter(outputTemplate); + return sinkConfiguration.Sink(new FileSink(path, formatter), restrictedToMinimumLevel); + } + + /// + /// Write log events to a series of files. Each file will be named according to + /// the date of the first log entry written to it. Only simple date-based rolling is + /// currently supported. + /// + /// Logger sink configuration. + /// .NET format string describing the location of the log files, + /// with {0} in the place of the file date. E.g. "Logs\myapp-{0}.log" will result in log + /// files such as "Logs\myapp-2013-10-20.log", "Logs\myapp-2013-10-21.log" and so on. + /// The minimum level for + /// events passed through the sink. + /// A message template describing the format used to write to the sink. + /// the default is "{TimeStamp} [{Level}] {Message:l}{NewLine:l}{Exception:l}". + /// Configuration object allowing method chaining. + public static LoggerConfiguration RollingFile( + this LoggerSinkConfiguration sinkConfiguration, + string pathFormat, + LogEventLevel restrictedToMinimumLevel = LogEventLevel.Minimum, + string outputTemplate = DefaultOutputTemplate) + { + var formatter = new MessageTemplateTextFormatter(outputTemplate); + return sinkConfiguration.Sink(new RollingFileSink(pathFormat, formatter), restrictedToMinimumLevel); + } + + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Serilog.Sinks.RollingFile.RollingFileSink::.ctor() at Line 108) of type Serilog.Sinks.RollingFile.RollingFileSink in method "LoggerConfiguration LoggerConfigurationFullNetFxExtensions.RollingFile(LoggerSinkConfiguration,String,LogEventLevel,String)". + +### Severity: +ERROR + +### Procedure: +LoggerConfiguration LoggerConfigurationFullNetFxExtensions.RollingFile(LoggerSinkConfiguration,String,LogEventLevel,String) + +### File: +src/Serilog.FullNetFx/LoggerConfigurationFullNetFxExtensions.cs + +### Key: +LoggerConfigurationFullNetFxExtensions.cs|RollingFile|DOTNET_RESOURCE_LEAK + +### Hash: +7b7e9bcda3525504874f6e1ab98fd592 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2606/instruction.md b/inferredbugs-2606/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2efe5f90a5ccba7ca1f609d4150d6da4c4e9b515 --- /dev/null +++ b/inferredbugs-2606/instruction.md @@ -0,0 +1,234 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Hangfire.HttpJob +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Hangfire; +using Hangfire.Console; +using Hangfire.Dashboard.BasicAuthorization; +using Hangfire.HttpJob; +using Hangfire.MySql.Core; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Data; +using Hangfire.Tags; +using Hangfire.Tags.Mysql; +using Microsoft.AspNetCore.Localization; +using Microsoft.Extensions.Hosting; +using Newtonsoft.Json; + +namespace TestHangfire +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + JsonConfig = configuration; + } + + public IConfiguration JsonConfig { get; } + + + public void ConfigureServices(IServiceCollection services) + { + services.AddHangfire(Configuration); //Configuration是下面的方法 + } + + private void Configuration(IGlobalConfiguration globalConfiguration) + { + var mysqlOption = new MySqlStorageOptions + { + TransactionIsolationLevel = IsolationLevel.ReadCommitted, + QueuePollInterval = TimeSpan.FromSeconds(15), + JobExpirationCheckInterval = TimeSpan.FromHours(1), + CountersAggregateInterval = TimeSpan.FromMinutes(5), + PrepareSchemaIfNecessary = true, + DashboardJobListLimit = 50000, + TransactionTimeout = TimeSpan.FromMinutes(1), + TablePrefix = "hangfire" + }; + globalConfiguration.UseStorage( + new MySqlStorage( + JsonConfig.GetSection("HangfireMysqlConnectionString").Get() + , mysqlOption + )) + .UseConsole(new ConsoleOptions() + { + BackgroundColor = "#000079" + }) + .UseHangfireHttpJob(new HangfireHttpJobOptions + { + MailOption = new MailOption + { + Server = JsonConfig.GetSection("HangfireMail:Server").Get(), + Port = JsonConfig.GetSection("HangfireMail:Port").Get(), + UseSsl = JsonConfig.GetSection("HangfireMail:UseSsl").Get(), + User = JsonConfig.GetSection("HangfireMail:User").Get(), + Password = JsonConfig.GetSection("HangfireMail:Password").Get(), + }, + DefaultRecurringQueueName = JsonConfig.GetSection("DefaultRecurringQueueName").Get(), + DefaultBackGroundJobQueueName = "DEFAULT", + DefaultTimeZone = "Asia/Shanghai", + //EnableDingTalk = true, + //CurrentDomain = "http://localhost:5000" + //RecurringJobTimeZone = TimeZoneInfo.Local, + // CheckHttpResponseStatusCode = code => (int)code < 400 //===》(default) + //AddHttpJobFilter = (jobContent) => + //{ + // //添加httpjob的拦截器 如果返回false就代表不添加 返回true则真正的添加 + + // if (jobContent.Url.StartsWith("http://localhost") || + // jobContent.Url.StartsWith("http://127.0.0.1")) + // { + // return true; + // } + + // return false; + //} + }) + .UseTagsWithMysql(sqlOptions: mysqlOption); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory logging) + { + + #region 强制显示中文 + var options = new RequestLocalizationOptions + { + DefaultRequestCulture = new RequestCulture("zh") + }; + + app.UseRequestLocalization(options); + + //强制显示中文 + System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh"); + + #endregion + + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + var queues = JsonConfig.GetSection("HangfireQueues").Get>().ToArray(); + app.UseHangfireServer(new BackgroundJobServerOptions + { + ServerTimeout = TimeSpan.FromMinutes(4), + SchedulePollingInterval = TimeSpan.FromSeconds(15), //秒级任务需要配置短点,一般任务可以配置默认时间,默认15秒 + ShutdownTimeout = TimeSpan.FromMinutes(30), //超时时间 + Queues = queues, //队列 + WorkerCount = Math.Max(Environment.ProcessorCount, 40) //工作线程数,当前允许的最大线程,默认20 + }); + + var hangfireStartUpPath = JsonConfig.GetSection("HangfireStartUpPath").Get(); + if (string.IsNullOrWhiteSpace(hangfireStartUpPath)) hangfireStartUpPath = "/job"; + + var dashbordConfig = new DashboardOptions + { + AppPath = "#", + DisplayStorageConnectionString = false, + IsReadOnlyFunc = Context => false + }; + var dashbordUserName = JsonConfig.GetSection("HangfireUserName").Get(); + var dashbordPwd = JsonConfig.GetSection("HangfirePwd").Get(); + if (!string.IsNullOrEmpty(dashbordPwd) && !string.IsNullOrEmpty(dashbordUserName)) + { + dashbordConfig.Authorization = new[] + { + new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions + { + RequireSsl = false, + SslRedirect = false, + LoginCaseSensitive = true, + Users = new[] + { + new BasicAuthAuthorizationUser + { + Login = dashbordUserName, + PasswordClear = dashbordPwd + } + } + }) + }; + } + app.UseHangfireDashboard(hangfireStartUpPath, dashbordConfig); + + var hangfireReadOnlyPath = JsonConfig.GetSection("HangfireReadOnlyPath").Get(); + if (!string.IsNullOrWhiteSpace(hangfireReadOnlyPath)) + { + //只读面板,只能读取不能操作 + app.UseHangfireDashboard(hangfireReadOnlyPath, new DashboardOptions + { + IgnoreAntiforgeryToken = true, + AppPath = hangfireStartUpPath, //返回时跳转的地址 + DisplayStorageConnectionString = false, //是否显示数据库连接信息 + IsReadOnlyFunc = Context => true + }); + } + + + app.Run(async (context) => { await context.Response.WriteAsync(JsonConvert.SerializeObject(new { Success = false, Info = "ok" })); }); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Hangfire.MySql.Core.MySqlStorage::.ctor() at Line 51) of type Hangfire.MySql.Core.MySqlStorage in method "Void Startup.Configuration(IGlobalConfiguration)". + +### Severity: +ERROR + +### Procedure: +Void Startup.Configuration(IGlobalConfiguration) + +### File: +TestHangfire/Startup.cs + +### Key: +Startup.cs|Configuration|DOTNET_RESOURCE_LEAK + +### Hash: +4a4302563b31d7ab1157358b1d716268 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2607/instruction.md b/inferredbugs-2607/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6dec56bc125389ca0f111f570d383d892e1e5991 --- /dev/null +++ b/inferredbugs-2607/instruction.md @@ -0,0 +1,268 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Hangfire.HttpJob +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Hangfire; +using Hangfire.Console; +using Hangfire.Dashboard.BasicAuthorization; +using Hangfire.HttpJob; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using Hangfire.Heartbeat; +using Hangfire.Heartbeat.Server; +using Hangfire.MySql; +using Hangfire.Tags; +using Hangfire.Tags.MySql; +using Microsoft.AspNetCore.Localization; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; +using Newtonsoft.Json; +using IsolationLevel = System.Transactions.IsolationLevel; + +namespace MysqlHangfire +{ + public static class HangfireCollectionExtensions + { + private const string HangfireSettingsKey = "Hangfire:HangfireSettings"; + private const string HttpJobOptionsKey = "Hangfire:HttpJobOptions"; + private const string HangfireConnectStringKey = "Hangfire:HangfireSettings:ConnectionString"; + private const string HangfireLangKey = "Hangfire:HttpJobOptions:Lang"; + + public static IServiceCollection AddSelfHangfire(this IServiceCollection services, IConfiguration Configuration) + { + var hangfireSettings = Configuration.GetSection(HangfireSettingsKey); + var httpJobOptions = Configuration.GetSection(HttpJobOptionsKey); + + services.Configure(hangfireSettings); + services.Configure(httpJobOptions); + + services.AddHangfire(globalConfiguration => + { + services.ConfigurationHangfire(Configuration, globalConfiguration); + }); + return services; + } + + + public static void ConfigurationHangfire(this IServiceCollection services, IConfiguration Configuration, + IGlobalConfiguration globalConfiguration) + { + var serverProvider = services.BuildServiceProvider(); + var hangfireSettings = serverProvider.GetService>().Value; + var httpJobOptions = serverProvider.GetService>().Value; + + var sqlConnectStr = Configuration.GetSection(HangfireConnectStringKey).Get(); + + var mysqlOption = new MySqlStorageOptions + { + TransactionIsolationLevel = IsolationLevel.ReadCommitted, + QueuePollInterval = TimeSpan.FromSeconds(15), + JobExpirationCheckInterval = TimeSpan.FromHours(1), + CountersAggregateInterval = TimeSpan.FromMinutes(5), + PrepareSchemaIfNecessary = true, + DashboardJobListLimit = 50000, + TransactionTimeout = TimeSpan.FromMinutes(1), + TablesPrefix = hangfireSettings.TablePrefix + }; + + globalConfiguration.UseStorage(new MySqlStorage(sqlConnectStr, mysqlOption)) + .UseConsole(new ConsoleOptions + { + BackgroundColor = "#000079" + }) + .UseHangfireHttpJob(httpJobOptions) + .UseTagsWithMySql(new TagsOptions() + { + TagsListStyle = TagsListStyle.Dropdown + },sqlOptions:mysqlOption) + .UseHeartbeatPage(); + } + + public static IApplicationBuilder ConfigureSelfHangfire(this IApplicationBuilder app, IConfiguration Configuration) + { + var langStr = Configuration.GetSection(HangfireLangKey).Get(); + if (!string.IsNullOrEmpty(langStr)) + { + var options = new RequestLocalizationOptions + { + DefaultRequestCulture = new RequestCulture(langStr) + }; + app.UseRequestLocalization(options); + System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(langStr); + } + + + + var services = app.ApplicationServices; + var hangfireSettings = services.GetService>().Value; + + var queues = hangfireSettings.JobQueues.Select(m => m.ToLower()).Distinct().ToList(); + + var workerCount = Math.Max(Environment.ProcessorCount, hangfireSettings.WorkerCount); //工作线程数,当前允许的最大线程,默认20 + + app.UseHangfireServer(new BackgroundJobServerOptions + { + ServerName = "HangfireServer", + ServerTimeout = TimeSpan.FromMinutes(4), + SchedulePollingInterval = TimeSpan.FromSeconds(15), //秒级任务需要配置短点,一般任务可以配置默认时间,默认15秒 + ShutdownTimeout = TimeSpan.FromMinutes(30), //超时时间 + Queues = queues.ToArray(), //队列 + WorkerCount = workerCount + },additionalProcesses: new[] { new ProcessMonitor() }); + + + var dashbordConfig = new DashboardOptions + { + AppPath = "#", + IgnoreAntiforgeryToken = true, + DisplayStorageConnectionString = hangfireSettings.DisplayStorageConnectionString, + IsReadOnlyFunc = Context => false + }; + + if (hangfireSettings.HttpAuthInfo.IsOpenLogin && hangfireSettings.HttpAuthInfo.Users.Any()) + { + var httpAuthInfo = hangfireSettings.HttpAuthInfo; + var users = hangfireSettings.HttpAuthInfo.Users.Select(m => new BasicAuthAuthorizationUser + { + Login = m.Login, + Password = m.Password, + PasswordClear = m.PasswordClear + }); + + var basicAuthAuthorizationFilterOptions = new BasicAuthAuthorizationFilterOptions + { + RequireSsl = httpAuthInfo.RequireSsl, + SslRedirect = httpAuthInfo.SslRedirect, + LoginCaseSensitive = httpAuthInfo.LoginCaseSensitive, + Users = users + }; + + dashbordConfig.Authorization = new[] + { + new BasicAuthAuthorizationFilter(basicAuthAuthorizationFilterOptions) + }; + + } + + app.UseHangfireDashboard(hangfireSettings.StartUpPath, dashbordConfig); + + if (!string.IsNullOrEmpty(hangfireSettings.ReadOnlyPath)) + //只读面板,只能读取不能操作 + app.UseHangfireDashboard(hangfireSettings.ReadOnlyPath, new DashboardOptions + { + IgnoreAntiforgeryToken = true, + AppPath = hangfireSettings.StartUpPath, //返回时跳转的地址 + DisplayStorageConnectionString = false, //是否显示数据库连接信息 + IsReadOnlyFunc = Context => true + }); + + return app; + } + + } + + public class HangfireSettings + { + public string TablePrefix { get; set; } + public string StartUpPath { get; set; } + public string ReadOnlyPath { get; set; } + public List JobQueues { get; set; } + public HttpAuthInfo HttpAuthInfo { get; set; } = new HttpAuthInfo(); + public int WorkerCount { get; set; } = 40; + public bool DisplayStorageConnectionString { get; set; } = false; + } + + public class HttpAuthInfo + { + /// + /// Redirects all non-SSL requests to SSL URL + /// + public bool SslRedirect { get; set; } = false; + + /// + /// Requires SSL connection to access Hangfire dahsboard. It's strongly recommended to use SSL when you're using basic authentication. + /// + public bool RequireSsl { get; set; } = false; + + /// + /// Whether or not login checking is case sensitive. + /// + public bool LoginCaseSensitive { get; set; } = true; + + public bool IsOpenLogin { get; set; } = true; + + public List Users { get; set; } = new List(); + } + + public class UserInfo + { + public string Login { get; set; } + public string PasswordClear { get; set; } + + public byte[] Password => Encoding.UTF8.GetBytes(PasswordClear); + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Hangfire.MySql.MySqlStorage::.ctor() at Line 74) of type Hangfire.MySql.MySqlStorage in method "Void HangfireCollectionExtensions.ConfigurationHangfire(IServiceCollection,IConfiguration,IGlobalConfiguration)". + +### Severity: +ERROR + +### Procedure: +Void HangfireCollectionExtensions.ConfigurationHangfire(IServiceCollection,IConfiguration,IGlobalConfiguration) + +### File: +Test/TestHangfire/HangfireCollectionExtensions.cs + +### Key: +HangfireCollectionExtensions.cs|ConfigurationHangfire|DOTNET_RESOURCE_LEAK + +### Hash: +f0788add30bc83c8cdf16704318779bf + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2608/instruction.md b/inferredbugs-2608/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b76c851b7e07080725461c471a85c4220cb925f2 --- /dev/null +++ b/inferredbugs-2608/instruction.md @@ -0,0 +1,376 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ArchiSteamFarm +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/* + _ _ _ ____ _ _____ + / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___ + / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \ + / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | | +/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_| + + Copyright 2015-2016 Łukasz "JustArchi" Domeradzki + Contact: JustArchi@JustArchi.net + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +*/ + +using Newtonsoft.Json.Linq; +using System; +using System.IO; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; + +namespace ArchiSteamFarm { + internal static class Program { + internal enum EUserInputType : byte { + Login, + Password, + PhoneNumber, + SMS, + SteamGuard, + SteamParentalPIN, + RevocationCode, + TwoFactorAuthentication, + } + + internal enum EMode : byte { + Normal, // Standard most common usage + Client, // WCF client only + Server // Normal + WCF server + } + + private const string LatestGithubReleaseURL = "https://api.github.com/repos/JustArchi/ArchiSteamFarm/releases/latest"; + internal const string ConfigDirectory = "config"; + internal const string LogFile = "log.txt"; + internal const string GlobalConfigFile = "ASF.json"; + + private static readonly object ConsoleLock = new object(); + private static readonly SemaphoreSlim SteamSemaphore = new SemaphoreSlim(1); + private static readonly ManualResetEvent ShutdownResetEvent = new ManualResetEvent(false); + private static readonly Assembly Assembly = Assembly.GetExecutingAssembly(); + private static readonly string ExecutableFile = Assembly.Location; + private static readonly string ExecutableDirectory = Path.GetDirectoryName(ExecutableFile); + private static readonly WCF WCF = new WCF(); + + internal static readonly string Version = Assembly.GetName().Version.ToString(); + + internal static GlobalConfig GlobalConfig { get; private set; } + internal static bool ConsoleIsBusy { get; private set; } = false; + + private static EMode Mode = EMode.Normal; + + private static async Task CheckForUpdate() { + JObject response = await WebBrowser.UrlGetToJObject(LatestGithubReleaseURL).ConfigureAwait(false); + if (response == null) { + return; + } + + string remoteVersion = response["tag_name"].ToString(); + if (string.IsNullOrEmpty(remoteVersion)) { + return; + } + + string localVersion = Version; + + Logging.LogGenericInfo("Local version: " + localVersion); + Logging.LogGenericInfo("Remote version: " + remoteVersion); + + int comparisonResult = localVersion.CompareTo(remoteVersion); + if (comparisonResult < 0) { + Logging.LogGenericInfo("New version is available!"); + Logging.LogGenericInfo("Consider updating yourself!"); + await Utilities.SleepAsync(5000).ConfigureAwait(false); + } else if (comparisonResult > 0) { + Logging.LogGenericInfo("You're currently using pre-release version!"); + Logging.LogGenericInfo("Be careful!"); + } + } + + internal static void Exit(int exitCode = 0) { + Environment.Exit(exitCode); + } + + internal static void Restart() { + System.Diagnostics.Process.Start(ExecutableFile, string.Join(" ", Environment.GetCommandLineArgs())); + Exit(); + } + + internal static async Task LimitSteamRequestsAsync() { + await SteamSemaphore.WaitAsync().ConfigureAwait(false); + Task.Run(async () => { + await Utilities.SleepAsync(GlobalConfig.RequestLimiterDelay * 1000).ConfigureAwait(false); + SteamSemaphore.Release(); + }).Forget(); + } + + internal static string GetUserInput(string botLogin, EUserInputType userInputType, string extraInformation = null) { + string result; + lock (ConsoleLock) { + ConsoleIsBusy = true; + switch (userInputType) { + case EUserInputType.Login: + Console.Write("<" + botLogin + "> Please enter your login: "); + break; + case EUserInputType.Password: + Console.Write("<" + botLogin + "> Please enter your password: "); + break; + case EUserInputType.PhoneNumber: + Console.Write("<" + botLogin + "> Please enter your full phone number (e.g. +1234567890): "); + break; + case EUserInputType.SMS: + Console.Write("<" + botLogin + "> Please enter SMS code sent on your mobile: "); + break; + case EUserInputType.SteamGuard: + Console.Write("<" + botLogin + "> Please enter the auth code sent to your email: "); + break; + case EUserInputType.SteamParentalPIN: + Console.Write("<" + botLogin + "> Please enter steam parental PIN: "); + break; + case EUserInputType.RevocationCode: + Console.WriteLine("<" + botLogin + "> PLEASE WRITE DOWN YOUR REVOCATION CODE: " + extraInformation); + Console.WriteLine("<" + botLogin + "> THIS IS THE ONLY WAY TO NOT GET LOCKED OUT OF YOUR ACCOUNT!"); + Console.Write("<" + botLogin + "> Hit enter once ready..."); + break; + case EUserInputType.TwoFactorAuthentication: + Console.Write("<" + botLogin + "> Please enter your 2 factor auth code from your authenticator app: "); + break; + } + result = Console.ReadLine(); + Console.Clear(); // For security purposes + ConsoleIsBusy = false; + } + + return result.Trim(); // Get rid of all whitespace characters + } + + internal static void OnBotShutdown() { + foreach (Bot bot in Bot.Bots.Values) { + if (bot.KeepRunning) { + return; + } + } + + if (WCF.IsServerRunning()) { + return; + } + + Logging.LogGenericInfo("No bots are running, exiting"); + ShutdownResetEvent.Set(); + } + + private static void InitServices() { + GlobalConfig = GlobalConfig.Load(); + if (GlobalConfig == null) { + Logging.LogGenericError("Global config could not be loaded, please make sure that ASF.db exists and is valid!"); + Thread.Sleep(5000); + Exit(1); + } + + ArchiWebHandler.Init(); + WebBrowser.Init(); + WCF.Init(); + } + + private static void ParseArgs(string[] args) { + foreach (string arg in args) { + switch (arg) { + case "--client": + Mode = EMode.Client; + Logging.LogToFile = false; + break; + case "--log": + Logging.LogToFile = true; + break; + case "--no-log": + Logging.LogToFile = false; + break; + case "--server": + Mode = EMode.Server; + WCF.StartServer(); + break; + default: + if (arg.StartsWith("--")) { + Logging.LogGenericWarning("Unrecognized parameter: " + arg); + continue; + } + + if (Mode != EMode.Client) { + Logging.LogGenericWarning("Ignoring command because --client wasn't specified: " + arg); + continue; + } + + Logging.LogGenericInfo("Command sent: \"" + arg + "\""); + + // We intentionally execute this async block synchronously + Logging.LogGenericInfo("Response received: \"" + WCF.SendCommand(arg) + "\""); + /* + Task.Run(async () => { + Logging.LogGenericNotice("WCF", "Response received: " + await WCF.SendCommand(arg).ConfigureAwait(false)); + }).Wait(); + */ + break; + } + } + } + + private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args) { + if (sender == null || args == null) { + return; + } + + Logging.LogGenericException((Exception) args.ExceptionObject); + } + + private static void Main(string[] args) { + AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler; + + Logging.LogGenericInfo("Archi's Steam Farm, version " + Version); + Directory.SetCurrentDirectory(ExecutableDirectory); + InitServices(); + + // Allow loading configs from source tree if it's a debug build + if (Debugging.IsDebugBuild) { + + // Common structure is bin/(x64/)Debug/ArchiSteamFarm.exe, so we allow up to 4 directories up + for (var i = 0; i < 4; i++) { + Directory.SetCurrentDirectory(".."); + if (Directory.Exists(ConfigDirectory)) { + break; + } + } + + // If config directory doesn't exist after our adjustment, abort all of that + if (!Directory.Exists(ConfigDirectory)) { + Directory.SetCurrentDirectory(ExecutableDirectory); + } + } + + // Parse args + ParseArgs(args); + + // If we ran ASF as a client, we're done by now + if (Mode == EMode.Client) { + return; + } + + // From now on it's server mode + Logging.Init(); + + if (!Directory.Exists(ConfigDirectory)) { + Logging.LogGenericError("Config directory doesn't exist!"); + Thread.Sleep(5000); + Exit(1); + } + + Task.Run(async () => await CheckForUpdate().ConfigureAwait(false)).Wait(); + + // Before attempting to connect, initialize our list of CMs + Bot.RefreshCMs().Wait(); + + string globalConfigName = GlobalConfigFile.Substring(0, GlobalConfigFile.LastIndexOf('.')); + + foreach (var configFile in Directory.EnumerateFiles(ConfigDirectory, "*.json")) { + string botName = Path.GetFileNameWithoutExtension(configFile); + if (botName.Equals(globalConfigName)) { + continue; + } + + Bot bot = new Bot(botName); + if (!bot.BotConfig.Enabled) { + Logging.LogGenericInfo("Not starting this instance because it's disabled in config file", botName); + } + } + + // CONVERSION START + foreach (var configFile in Directory.EnumerateFiles(ConfigDirectory, "*.xml")) { + string botName = Path.GetFileNameWithoutExtension(configFile); + Logging.LogGenericWarning("Found legacy " + botName + ".xml config file, it will now be converted to new ASF V2.0 format!"); + Bot bot = new Bot(botName); + if (!bot.BotConfig.Enabled) { + Logging.LogGenericInfo("Not starting this instance because it's disabled in config file", botName); + } + } + // CONVERSION END + + // Check if we got any bots running + OnBotShutdown(); + + // Wait for signal to shutdown + ShutdownResetEvent.WaitOne(); + + // We got a signal to shutdown, consider giving user some time to read the message + Thread.Sleep(5000); + + // This is over, cleanup only now + WCF.StopServer(); + } + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`#GB<>$ArchiSteamFarm.Program.ArchiSteamFarm.Program.k__BackingField` could be null (from the call to `GlobalConfig.Load()` on line 171) and is dereferenced in call to `ArchiWebHandler.Init()`. + +### Severity: +ERROR + +### Procedure: +Void Program.InitServices() + +### File: +ArchiSteamFarm/Program.cs + +### Key: +Program.cs|InitServices|NULLPTR_DEREFERENCE + +### Hash: +b80970be1bf4085a97e4ff96ed6ade38 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2609/instruction.md b/inferredbugs-2609/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..df81e74b23de841302500042ef4c19e30f079cb0 --- /dev/null +++ b/inferredbugs-2609/instruction.md @@ -0,0 +1,199 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ArchiSteamFarm +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/* + _ _ _ ____ _ _____ + / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___ + / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \ + / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | | +/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_| + + Copyright 2015-2016 Łukasz "JustArchi" Domeradzki + Contact: JustArchi@JustArchi.net + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +*/ + +using System; +using System.Diagnostics; +using System.IO; +using System.Runtime.CompilerServices; + +namespace ArchiSteamFarm { + internal static class Logging { + private static readonly object FileLock = new object(); + + private static bool LogToFile; + + internal static void Init() { + LogToFile = Program.GlobalConfig.LogToFile; + + if (LogToFile) { + lock (FileLock) { + try { + File.Delete(Program.LogFile); + } catch (Exception e) { + LogToFile = false; + LogGenericException(e); + } + } + } + } + + internal static void LogGenericWTF(string message, string botName = "Main", [CallerMemberName] string previousMethodName = "") { + if (string.IsNullOrEmpty(message)) { + return; + } + + Log("[!!] WTF: " + previousMethodName + "() <" + botName + "> " + message + ", WTF?"); + } + + internal static void LogGenericError(string message, string botName = "Main", [CallerMemberName] string previousMethodName = "") { + if (string.IsNullOrEmpty(message)) { + return; + } + + Log("[!!] ERROR: " + previousMethodName + "() <" + botName + "> " + message); + } + + internal static void LogGenericException(Exception exception, string botName = "Main", [CallerMemberName] string previousMethodName = "") { + if (exception == null) { + return; + } + + Log("[!] EXCEPTION: " + previousMethodName + "() <" + botName + "> " + exception.Message); + Log("[!] StackTrace:" + Environment.NewLine + exception.StackTrace); + + if (exception.InnerException != null) { + LogGenericException(exception.InnerException, botName, previousMethodName); + } + } + + internal static void LogGenericWarning(string message, string botName = "Main", [CallerMemberName] string previousMethodName = "") { + if (string.IsNullOrEmpty(message)) { + return; + } + + Log("[!] WARNING: " + previousMethodName + "() <" + botName + "> " + message); + } + + internal static void LogGenericInfo(string message, string botName = "Main", [CallerMemberName] string previousMethodName = "") { + if (string.IsNullOrEmpty(message)) { + return; + } + + Log("[*] INFO: " + previousMethodName + "() <" + botName + "> " + message); + } + + internal static void LogNullError(string nullObjectName, string botName = "Main", [CallerMemberName] string previousMethodName = "") { + if (string.IsNullOrEmpty(nullObjectName)) { + return; + } + + LogGenericError(nullObjectName + " is null!", botName, previousMethodName); + } + + [Conditional("DEBUG")] + internal static void LogGenericDebug(string message, string botName = "Main", [CallerMemberName] string previousMethodName = "") { + if (string.IsNullOrEmpty(message)) { + return; + } + + Log("[#] DEBUG: " + previousMethodName + "() <" + botName + "> " + message); + } + + private static void Log(string message) { + if (string.IsNullOrEmpty(message)) { + return; + } + + string loggedMessage = DateTime.Now + " " + message + Environment.NewLine; + + // Write on console only when not awaiting response from user + if (!Program.ConsoleIsBusy) { + try { + Console.Write(loggedMessage); + } catch { } + } + + if (LogToFile) { + lock (FileLock) { + try { + File.AppendAllText(Program.LogFile, loggedMessage); + } catch (Exception e) { + LogToFile = false; + LogGenericException(e); + } + } + } + } + } +} + +``` + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `Logging.Init()` reads without synchronization from `ArchiSteamFarm.Logging.ArchiSteamFarm.Logging.LogToFile`. Potentially races with write in method `Logging.Init()`. + Reporting because this access may occur on a background thread. + +### Severity: +WARNING + +### Procedure: +Void Logging.Init() + +### File: +ArchiSteamFarm/Logging.cs + +### Key: +Logging.cs|Init|THREAD_SAFETY_VIOLATION + +### Hash: +a26fbface3e0d9f94d6e0d9d4fd4195c + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2630/instruction.md b/inferredbugs-2630/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bd478a06b8e4793d4885a3533b45866c0d5faefa --- /dev/null +++ b/inferredbugs-2630/instruction.md @@ -0,0 +1,351 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** packetnet +**Bug ID:** 19 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/* +This file is part of PacketDotNet + +PacketDotNet 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. + +PacketDotNet 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 PacketDotNet. If not, see . +*/ +/* + * Copyright 2010 Chris Morgan + */ + +using NUnit.Framework; +using PacketDotNet; +using PacketDotNet.Ieee80211; +using SharpPcap.LibPcap; + +namespace Test.PacketType.Ieee80211 +{ + [TestFixture] + public class PerPacketInformationTest + { + [Test] + public void AddUnknownField() + { + var dev = new CaptureFileReaderDevice("../../CaptureFiles/80211_ppi_multiplefields.pcap"); + dev.Open(); + var rawCapture = dev.GetNextPacket(); + dev.Close(); + + var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as PpiPacket; + + var unknownField = new PpiUnknown(99, new byte[] { 0xAA, 0xBB, 0xCC, 0xDD }); + p.Add(unknownField); + + var recreatedPacket = Packet.ParsePacket(LinkLayers.Ppi, p.Bytes) as PpiPacket; + + Assert.IsTrue(recreatedPacket.Contains(PpiFieldType.PpiCommon)); + Assert.IsTrue(recreatedPacket.Contains(PpiFieldType.PpiMacPhy)); + Assert.IsTrue(recreatedPacket.Contains((PpiFieldType) 99)); + var recreatedUnknownField = recreatedPacket.FindFirstByType((PpiFieldType) 99) as PpiUnknown; + Assert.AreEqual(new byte[] { 0xAA, 0xBB, 0xCC, 0xDD }, recreatedUnknownField.UnknownBytes); + + var macFrame = recreatedPacket.PayloadPacket as MacFrame; + Assert.IsNotNull(macFrame); + Assert.IsTrue(macFrame.FcsValid); + } + + [Test] + public void ConstructPacketWithMultipleAlignedFields() + { + var packet = new PpiPacket(); + packet.Flags |= PpiPacket.HeaderFlags.Alignment32Bit; + + var commonField = new PpiCommon { ChannelFrequency = 2142, AntennaSignalPower = 50, AntennaSignalNoise = 25 }; + packet.Add(commonField); + + Assert.AreEqual(32, packet.Length); + + var processInfoField = new PpiProcessInfo { UserId = 0x1111, UserName = "Hester the tester", GroupId = 0x2222, GroupName = "Test Group" }; + packet.Add(processInfoField); + + Assert.AreEqual(84, packet.Length); + + var aggregationField = new PpiAggregation(0x3333); + packet.Add(aggregationField); + + Assert.AreEqual(92, packet.Length); + + var recreatedPacket = Packet.ParsePacket(LinkLayers.Ppi, packet.Bytes) as PpiPacket; + + var recreatedCommonField = recreatedPacket[0] as PpiCommon; + Assert.IsNotNull(recreatedCommonField); + Assert.AreEqual(2142, recreatedCommonField.ChannelFrequency); + Assert.AreEqual(50, recreatedCommonField.AntennaSignalPower); + Assert.AreEqual(25, recreatedCommonField.AntennaSignalNoise); + + var recreatedProcessField = recreatedPacket[1] as PpiProcessInfo; + Assert.IsNotNull(recreatedProcessField); + Assert.AreEqual(0x1111, recreatedProcessField.UserId); + Assert.AreEqual("Hester the tester", recreatedProcessField.UserName); + Assert.AreEqual(0x2222, recreatedProcessField.GroupId); + Assert.AreEqual("Test Group", recreatedProcessField.GroupName); + + var recreatedAggregationField = recreatedPacket[2] as PpiAggregation; + + Assert.IsNotNull(recreatedAggregationField); + Assert.AreEqual(0x3333, recreatedAggregationField.InterfaceId); + } + + [Test] + public void ConstructPacketWithMultipleFields() + { + var packet = new PpiPacket(); + + var commonField = new PpiCommon { ChannelFrequency = 2142, AntennaSignalPower = 50, AntennaSignalNoise = 25 }; + packet.Add(commonField); + + Assert.AreEqual(32, packet.Length); + + var processInfoField = new PpiProcessInfo { UserId = 0x1111, UserName = "Hester the tester", GroupId = 0x2222, GroupName = "Test Group" }; + packet.Add(processInfoField); + + Assert.AreEqual(82, packet.Length); + + var aggregationField = new PpiAggregation(0x3333); + packet.Add(aggregationField); + + Assert.AreEqual(90, packet.Length); + + var recreatedPacket = Packet.ParsePacket(LinkLayers.Ppi, packet.Bytes) as PpiPacket; + + var recreatedCommonField = recreatedPacket[0] as PpiCommon; + Assert.IsNotNull(recreatedCommonField); + Assert.AreEqual(2142, recreatedCommonField.ChannelFrequency); + Assert.AreEqual(50, recreatedCommonField.AntennaSignalPower); + Assert.AreEqual(25, recreatedCommonField.AntennaSignalNoise); + + var recreatedProcessField = recreatedPacket[1] as PpiProcessInfo; + Assert.IsNotNull(recreatedProcessField); + Assert.AreEqual(0x1111, recreatedProcessField.UserId); + Assert.AreEqual("Hester the tester", recreatedProcessField.UserName); + Assert.AreEqual(0x2222, recreatedProcessField.GroupId); + Assert.AreEqual("Test Group", recreatedProcessField.GroupName); + + var recreatedAggregationField = recreatedPacket[2] as PpiAggregation; + + Assert.IsNotNull(recreatedAggregationField); + Assert.AreEqual(0x3333, recreatedAggregationField.InterfaceId); + } + + [Test] + public void ConstructPacketWithNoFields() + { + var packet = new PpiPacket(); + + var recreatedPacket = Packet.ParsePacket(LinkLayers.Ppi, packet.Bytes) as PpiPacket; + + Assert.AreEqual(0, recreatedPacket.Version); + Assert.IsFalse((recreatedPacket.Flags & PpiPacket.HeaderFlags.Alignment32Bit) == PpiPacket.HeaderFlags.Alignment32Bit); + } + + [Test] + public void ContainsField() + { + var dev = new CaptureFileReaderDevice("../../CaptureFiles/80211_ppi_multiplefields.pcap"); + dev.Open(); + var rawCapture = dev.GetNextPacket(); + dev.Close(); + + var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as PpiPacket; + Assert.IsTrue(p.Contains(PpiFieldType.PpiCommon)); + Assert.IsTrue(p.Contains(PpiFieldType.PpiMacPhy)); + Assert.IsFalse(p.Contains(PpiFieldType.PpiProcessInfo)); + } + + /// + /// Test that parsing an ip packet yields the proper field values + /// + [Test] + public void ReadingPacketsFromFile() + { + var dev = new CaptureFileReaderDevice("../../CaptureFiles/80211_per_packet_information.pcap"); + dev.Open(); + var rawCapture = dev.GetNextPacket(); + dev.Close(); + + var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as PpiPacket; + + Assert.IsNotNull(p); + Assert.AreEqual(0, p.Version); + Assert.AreEqual(32, p.Length); + Assert.AreEqual(1, p.Count); + + var commonField = p.FindFirstByType(PpiFieldType.PpiCommon) as PpiCommon; + + Assert.AreEqual(PpiFieldType.PpiCommon, commonField.FieldType); + Assert.AreEqual(0, commonField.TSFTimer); + Assert.IsTrue((commonField.Flags & PpiCommon.CommonFlags.FcsIncludedInFrame) == PpiCommon.CommonFlags.FcsIncludedInFrame); + Assert.AreEqual(2, commonField.Rate); + Assert.AreEqual(2437, commonField.ChannelFrequency); + Assert.AreEqual(0x00A0, (int) commonField.ChannelFlags); + Assert.AreEqual(0, commonField.FhssHopset); + Assert.AreEqual(0, commonField.FhssPattern); + Assert.AreEqual(-84, commonField.AntennaSignalPower); + Assert.AreEqual(-100, commonField.AntennaSignalNoise); + + var macFrame = p.PayloadPacket as MacFrame; + Assert.AreEqual(FrameControlField.FrameSubTypes.ControlCts, macFrame.FrameControl.SubType); + Assert.IsTrue(macFrame.AppendFcs); + } + + [Test] + public void ReadPacketWithInvalidFcs() + { + var dev = new CaptureFileReaderDevice("../../CaptureFiles/80211_ppi_fcs_present_and_invalid.pcap"); + dev.Open(); + var rawCapture = dev.GetNextPacket(); + dev.Close(); + + var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as PpiPacket; + + //The packet is corrupted in such a way that the type field has been changed + //to a reserved/unused type. Therefore we don't expect there to be a packet + Assert.IsNull(p.PayloadPacket); + Assert.IsNotNull(p.PayloadData); + } + + [Test] + public void ReadPacketWithNoFcs() + { + var dev = new CaptureFileReaderDevice("../../CaptureFiles/80211_ppi_without_fcs.pcap"); + dev.Open(); + var rawCapture = dev.GetNextPacket(); + dev.Close(); + + var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as PpiPacket; + Assert.IsNotNull(p.PayloadPacket); + var macFrame = p.PayloadPacket as MacFrame; + Assert.IsFalse(macFrame.FcsValid); + Assert.IsFalse(macFrame.AppendFcs); + } + + [Test] + public void ReadPacketWithValidFcs() + { + var dev = new CaptureFileReaderDevice("../../CaptureFiles/80211_ppi_fcs_present_and_valid.pcap"); + dev.Open(); + var rawCapture = dev.GetNextPacket(); + dev.Close(); + + var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as PpiPacket; + Assert.IsNotNull(p.PayloadPacket); + var macFrame = p.PayloadPacket as MacFrame; + Assert.IsTrue(macFrame.FcsValid); + Assert.IsTrue(macFrame.AppendFcs); + } + + [Test] + public void RemoveField() + { + var dev = new CaptureFileReaderDevice("../../CaptureFiles/80211_ppi_multiplefields.pcap"); + dev.Open(); + var rawCapture = dev.GetNextPacket(); + dev.Close(); + + var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as PpiPacket; + var expectedLength = p.Length - p[1].Length - PpiHeaderFields.FieldHeaderLength; + p.Remove(p[1]); + + var recreatedPacket = Packet.ParsePacket(LinkLayers.Ppi, p.Bytes) as PpiPacket; + Assert.AreEqual(expectedLength, recreatedPacket.Length); + Assert.IsTrue(recreatedPacket.Contains(PpiFieldType.PpiCommon)); + Assert.IsFalse(recreatedPacket.Contains(PpiFieldType.PpiMacPhy)); + + var macFrame = recreatedPacket.PayloadPacket as MacFrame; + Assert.IsNotNull(macFrame); + Assert.IsTrue(macFrame.FcsValid); + } + + [Test] + public void RemoveFieldByType() + { + var dev = new CaptureFileReaderDevice("../../CaptureFiles/80211_ppi_multiplefields.pcap"); + dev.Open(); + var rawCapture = dev.GetNextPacket(); + dev.Close(); + + var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as PpiPacket; + p.RemoveAll(PpiFieldType.PpiMacPhy); + + var recreatedPacket = Packet.ParsePacket(LinkLayers.Ppi, p.Bytes) as PpiPacket; + + Assert.IsTrue(recreatedPacket.Contains(PpiFieldType.PpiCommon)); + Assert.IsFalse(recreatedPacket.Contains(PpiFieldType.PpiMacPhy)); + + var macFrame = recreatedPacket.PayloadPacket as MacFrame; + Assert.IsNotNull(macFrame); + Assert.IsTrue(macFrame.FcsValid); + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `p` last assigned on line 206 could be null and is dereferenced at line 210, column 13. + +### Severity: +ERROR + +### Procedure: +Void PerPacketInformationTest.ReadPacketWithInvalidFcs() + +### File: +Test/PacketType/Ieee80211/PerPacketInformationTest.cs + +### Key: +PerPacketInformationTest.cs|ReadPacketWithInvalidFcs|NULL_DEREFERENCE + +### Node Key: +a35c6d97ccef7486c04c7fb208054b5b + +### Hash: +5cecee635dc05e0a4cab256a12275fd9 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2636/instruction.md b/inferredbugs-2636/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..025c9a62e34ae209a8973e045af8de37ff3f47e4 --- /dev/null +++ b/inferredbugs-2636/instruction.md @@ -0,0 +1,158 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** packetnet +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/* +This file is part of PacketDotNet + +PacketDotNet 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. + +PacketDotNet 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 PacketDotNet. If not, see . +*/ +/* + * Copyright 2010 Chris Morgan + */ + +using System; +using NUnit.Framework; +using SharpPcap.LibPcap; +using PacketDotNet; +using PacketDotNet.Ieee80211; + +namespace Test.PacketType +{ + namespace Ieee80211 + { + [TestFixture] + public class PerPacketInformationTest + { + /// + /// Test that parsing an ip packet yields the proper field values + /// + [Test] + public void ReadingPacketsFromFile () + { + var dev = new CaptureFileReaderDevice ("../../CaptureFiles/80211_per_packet_information.pcap"); + dev.Open (); + var rawCapture = dev.GetNextPacket (); + dev.Close (); + + PpiPacket p = Packet.ParsePacket (rawCapture.LinkLayerType, rawCapture.Data) as PpiPacket; + + Assert.IsNotNull (p); + Assert.AreEqual (0, p.Version); + Assert.AreEqual (32, p.Length); + Assert.AreEqual (1, p.PpiFields.Count); + + PpiCommon commonField = p.PpiFields [0] as PpiCommon; + + Assert.AreEqual (PpiFieldType.PpiCommon, commonField.FieldType); + Assert.AreEqual (0, commonField.TSFTimer); + Assert.IsTrue ((commonField.Flags & PpiCommon.CommonFlags.FcsIncludedInFrame) == PpiCommon.CommonFlags.FcsIncludedInFrame); + Assert.AreEqual (2, commonField.Rate); + Assert.AreEqual (2437, commonField.ChannelFrequency); + Assert.AreEqual (0x00A0, commonField.ChannelFlags); + Assert.AreEqual (0, commonField.FhssHopset); + Assert.AreEqual (0, commonField.FhssPattern); + Assert.AreEqual (-84, commonField.AntennaSignalPower); + Assert.AreEqual (-100, commonField.AntennaSignalNoise); + + MacFrame macFrame = p.PayloadPacket as MacFrame; + Assert.AreEqual(FrameControlField.FrameSubTypes.ControlCTS, macFrame.FrameControl.SubType); + } + + [Test] + public void ReadPacketWithInvalidFcs () + { + var dev = new CaptureFileReaderDevice ("../../CaptureFiles/80211_ppi_fcs_present_and_invalid.pcap"); + dev.Open (); + var rawCapture = dev.GetNextPacket (); + dev.Close (); + + PpiPacket p = Packet.ParsePacket (rawCapture.LinkLayerType, rawCapture.Data) as PpiPacket; + Assert.IsNull (p.PayloadPacket); + Assert.IsNotNull (p.PayloadData); + } + + [Test] + public void ReadPacketWithValidFcs () + { + var dev = new CaptureFileReaderDevice ("../../CaptureFiles/80211_ppi_fcs_present_and_valid.pcap"); + dev.Open (); + var rawCapture = dev.GetNextPacket (); + dev.Close (); + + PpiPacket p = Packet.ParsePacket (rawCapture.LinkLayerType, rawCapture.Data) as PpiPacket; + Assert.IsNotNull (p.PayloadPacket); + Assert.IsNull (p.PayloadData); + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `macFrame` last assigned on line 243 could be null and is dereferenced at line 244, column 13. + +### Severity: +ERROR + +### Procedure: +Void PerPacketInformationTest.ReadPacketWithValidFcs() + +### File: +Test/PacketType/Ieee80211/PerPacketInformationTest.cs + +### Key: +PerPacketInformationTest.cs|ReadPacketWithValidFcs|NULL_DEREFERENCE + +### Node Key: +a35c6d97ccef7486c04c7fb208054b5b + +### Hash: +497a935c6930025d31b45c8682fc223c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2637/instruction.md b/inferredbugs-2637/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e8285c70b1910df3545f1651e8ce75824eec93d --- /dev/null +++ b/inferredbugs-2637/instruction.md @@ -0,0 +1,303 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** packetnet +**Bug ID:** 12 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/* +This file is part of PacketDotNet + +PacketDotNet 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. + +PacketDotNet 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 PacketDotNet. If not, see . +*/ +/* + * Copyright 2010 Chris Morgan + */ + +using System.IO; +using NUnit.Framework; +using PacketDotNet; +using PacketDotNet.Ieee80211; +using PacketDotNet.Utils.Converters; +using SharpPcap.LibPcap; + +namespace Test.PacketType.Ieee80211 +{ + [TestFixture] + public class RadioPacketTest + { + [Test] + public void ConstructFrameWithSinglePresenceField() + { + var p = new RadioPacket(); + + var expectedLength = 8; + Assert.AreEqual(expectedLength, p.Length); + + var flagsField = new FlagsRadioTapField(); + flagsField.Flags |= RadioTapFlags.FcsIncludedInFrame; + flagsField.Flags |= RadioTapFlags.WepEncrypted; + p.Add(flagsField); + + expectedLength += flagsField.Length; + Assert.AreEqual(expectedLength, p.Length); + + //We will add the noise field before the signal field. This is not the order required + //for radiotap and so will test that the fields are correctly reordered when written + var dbAntennaNoiseField = new DbAntennaNoiseRadioTapField { AntennaNoisedB = 33 }; + p.Add(dbAntennaNoiseField); + + expectedLength += dbAntennaNoiseField.Length; + Assert.AreEqual(expectedLength, p.Length); + + var dbAntennaSignalField = new DbAntennaSignalRadioTapField { SignalStrengthdB = 44 }; + p.Add(dbAntennaSignalField); + + expectedLength += dbAntennaSignalField.Length; + Assert.AreEqual(expectedLength, p.Length); + + //we will just put a single byte of data because we dont want it to be parsed into + //an 802.11 frame in this test + p.PayloadData = new byte[] { 0xFF }; + + var frameBytes = p.Bytes; + + var recreatedFrame = Packet.ParsePacket(LinkLayers.Ieee80211Radio, frameBytes) as RadioPacket; + + Assert.IsNotNull(p[RadioTapType.Flags]); + Assert.IsNotNull(p[RadioTapType.DbAntennaSignal]); + Assert.IsNotNull(p[RadioTapType.DbAntennaNoise]); + Assert.AreEqual(new byte[] { 0xFF }, recreatedFrame.PayloadData); + } + + /// + /// Test that parsing an ip packet yields the proper field values + /// + [Test] + public void ReadingPacketsFromFile() + { + var dev = new CaptureFileReaderDevice("../../CaptureFiles/80211_plus_radiotap_header.pcap"); + dev.Open(); + var rawCapture = dev.GetNextPacket(); + dev.Close(); + + var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as RadioPacket; + Assert.IsNotNull(p); + Assert.IsNotNull(p[RadioTapType.Flags]); + Assert.IsNotNull(p[RadioTapType.Rate]); + Assert.IsNotNull(p[RadioTapType.Channel]); + Assert.IsNotNull(p[RadioTapType.DbmAntennaSignal]); + Assert.IsNotNull(p[RadioTapType.DbmAntennaNoise]); + Assert.IsNotNull(p[RadioTapType.LockQuality]); + Assert.IsNotNull(p[RadioTapType.Antenna]); + Assert.IsNotNull(p[RadioTapType.DbAntennaSignal]); + var macFrame = p.PayloadPacket as MacFrame; + Assert.IsNotNull(macFrame); + Assert.IsTrue(macFrame.AppendFcs); + } + + [Test] + public void ReadPacketWithNoFcs() + { + var dev = new CaptureFileReaderDevice("../../CaptureFiles/80211_radio_without_fcs.pcap"); + dev.Open(); + var rawCapture = dev.GetNextPacket(); + dev.Close(); + + var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as RadioPacket; + Assert.IsNotNull(p.PayloadPacket); + + var tsftField = p[RadioTapType.Tsft] as TsftRadioTapField; + Assert.IsNotNull(tsftField); + Assert.AreEqual(38724775, tsftField.TimestampUsec); + + var flagsField = p[RadioTapType.Flags] as FlagsRadioTapField; + Assert.IsNotNull(flagsField); + Assert.AreEqual(0, (int) flagsField.Flags); + + var rateField = p[RadioTapType.Rate] as RateRadioTapField; + Assert.IsNotNull(rateField); + Assert.AreEqual(1, rateField.RateMbps); + + var channelField = p[RadioTapType.Channel] as ChannelRadioTapField; + Assert.IsNotNull(channelField); + Assert.AreEqual(2462, channelField.FrequencyMHz); + Assert.AreEqual(11, channelField.Channel); + Assert.AreEqual(RadioTapChannelFlags.Channel2Ghz | RadioTapChannelFlags.Cck, channelField.Flags); + + var dbmSignalField = p[RadioTapType.DbmAntennaSignal] as DbmAntennaSignalRadioTapField; + Assert.IsNotNull(dbmSignalField); + Assert.AreEqual(-61, dbmSignalField.AntennaSignalDbm); + + var dbmNoiseField = p[RadioTapType.DbmAntennaNoise] as DbmAntennaNoiseRadioTapField; + Assert.IsNotNull(dbmNoiseField); + Assert.AreEqual(-84, dbmNoiseField.AntennaNoisedBm); + + var antennaField = p[RadioTapType.Antenna] as AntennaRadioTapField; + Assert.IsNotNull(antennaField); + Assert.AreEqual(0, antennaField.Antenna); + + var dbSignalField = p[RadioTapType.DbAntennaSignal] as DbAntennaSignalRadioTapField; + Assert.IsNotNull(dbSignalField); + Assert.AreEqual(23, dbSignalField.SignalStrengthdB); + + var macFrame = p.PayloadPacket as MacFrame; + Assert.IsFalse(macFrame.AppendFcs); + Assert.IsFalse(macFrame.FcsValid); + } + + [Test] + public void RemoveRadioTapField() + { + var dev = new CaptureFileReaderDevice("../../CaptureFiles/80211_plus_radiotap_header.pcap"); + dev.Open(); + var rawCapture = dev.GetNextPacket(); + dev.Close(); + + var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as RadioPacket; + Assert.IsNotNull(p); + Assert.IsNotNull(p[RadioTapType.Flags]); + Assert.IsNotNull(p[RadioTapType.Rate]); + Assert.IsNotNull(p[RadioTapType.Channel]); + Assert.IsNotNull(p[RadioTapType.DbmAntennaSignal]); + Assert.IsNotNull(p[RadioTapType.DbmAntennaNoise]); + Assert.IsNotNull(p[RadioTapType.LockQuality]); + Assert.IsNotNull(p[RadioTapType.Antenna]); + Assert.IsNotNull(p[RadioTapType.DbAntennaSignal]); + var macFrame = p.PayloadPacket as MacFrame; + Assert.IsNotNull(macFrame); + Assert.IsTrue(macFrame.AppendFcs); + Assert.IsTrue(macFrame.FcsValid); + + //Now remove a couple of radio tap fields and check that it is still valid + p.Remove(RadioTapType.Rate); + p.Remove(RadioTapType.Antenna); + + var recreatedFrame = Packet.ParsePacket(rawCapture.LinkLayerType, p.Bytes) as RadioPacket; + Assert.IsNotNull(recreatedFrame); + Assert.IsNotNull(recreatedFrame[RadioTapType.Flags]); + Assert.IsNull(recreatedFrame[RadioTapType.Rate]); + Assert.IsNotNull(recreatedFrame[RadioTapType.Channel]); + Assert.IsNotNull(recreatedFrame[RadioTapType.DbmAntennaSignal]); + Assert.IsNotNull(recreatedFrame[RadioTapType.DbmAntennaNoise]); + Assert.IsNotNull(recreatedFrame[RadioTapType.LockQuality]); + Assert.IsNull(recreatedFrame[RadioTapType.Antenna]); + Assert.IsNotNull(recreatedFrame[RadioTapType.DbAntennaSignal]); + var recreatedMacFrame = p.PayloadPacket as MacFrame; + Assert.IsNotNull(recreatedMacFrame); + Assert.IsTrue(recreatedMacFrame.AppendFcs); + Assert.IsTrue(recreatedMacFrame.FcsValid); + } + + [Test] + public void TestContainsField() + { + var dev = new CaptureFileReaderDevice("../../CaptureFiles/80211_plus_radiotap_header.pcap"); + dev.Open(); + var rawCapture = dev.GetNextPacket(); + dev.Close(); + + var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as RadioPacket; + Assert.IsNotNull(p); + Assert.IsTrue(p.Contains(RadioTapType.Flags)); + Assert.IsFalse(p.Contains(RadioTapType.Fhss)); + } + + [Test] + public void UnhandledRadioTapField() + { + var ms = new MemoryStream(); + var bs = new BinaryWriter(ms); + bs.Write((byte) 0x0); //version + bs.Write((byte) 0x0); //pad + bs.Write((ushort) 0x0010); //length + bs.Write(0x80000002); //present 1 (wth flags field) + bs.Write((uint) 0x00010000); //present 2 (with unhandled field) + bs.Write((ushort) 0x0010); //Flags field (FCS included flag set) + bs.Write((ushort) 0x1234); //a made up field that we want to keep even though we dont know what it is + + var dev = new CaptureFileReaderDevice("../../CaptureFiles/80211_plus_radiotap_header.pcap"); + dev.Open(); + var rawCapture = dev.GetNextPacket(); + dev.Close(); + + var anotherRadioPacket = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as RadioPacket; + bs.Write(anotherRadioPacket.PayloadPacket.Bytes); + + var radioTap = ms.ToArray(); + + var p = Packet.ParsePacket(LinkLayers.Ieee80211Radio, radioTap) as RadioPacket; + Assert.AreEqual(16, p.Length); + p.Add(new TsftRadioTapField(0x123456789)); + var finalFrame = Packet.ParsePacket(LinkLayers.Ieee80211Radio, p.Bytes) as RadioPacket; + + Assert.AreEqual(24, finalFrame.Length); + Assert.AreEqual(0x1234, EndianBitConverter.Little.ToUInt16(finalFrame.Bytes, finalFrame.Length - 2)); + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `p` last assigned on line 156 could be null and is dereferenced at line 158, column 13. + +### Severity: +ERROR + +### Procedure: +Void RadioPacketTest.RemoveRadioTapField() + +### File: +Test/PacketType/Ieee80211/RadioPacketTest.cs + +### Key: +RadioPacketTest.cs|RemoveRadioTapField|NULL_DEREFERENCE + +### Node Key: +a35c6d97ccef7486c04c7fb208054b5b + +### Hash: +218471b31d5c381338417ba26ce1e964 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2638/instruction.md b/inferredbugs-2638/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..506bfb7e005711c848667f9bfc03827216692477 --- /dev/null +++ b/inferredbugs-2638/instruction.md @@ -0,0 +1,177 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** packetnet +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/* +This file is part of PacketDotNet + +PacketDotNet 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. + +PacketDotNet 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 PacketDotNet. If not, see . +*/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NUnit.Framework; +using SharpPcap.LibPcap; +using PacketDotNet; +using PacketDotNet.Utils; +using PacketDotNet.Ieee80211; +using System.Net.NetworkInformation; + +namespace Test.PacketType +{ + namespace Ieee80211 + { + [TestFixture] + public class NullDataFrameTest + { + /// + /// Test that parsing a null data frame yields the proper field values + /// + [Test] + public void Test_Constructor () + { + var dev = new CaptureFileReaderDevice ("../../CaptureFiles/80211_null_data_frame.pcap"); + dev.Open (); + var rawCapture = dev.GetNextPacket (); + dev.Close (); + + Packet p = Packet.ParsePacket (rawCapture.LinkLayerType, rawCapture.Data); + NullDataFrame frame = (NullDataFrame)p.PayloadPacket; + + Assert.AreEqual (0, frame.FrameControl.ProtocolVersion); + Assert.AreEqual (FrameControlField.FrameTypes.DataNullFunctionNoData, frame.FrameControl.Type); + Assert.IsTrue (frame.FrameControl.ToDS); + Assert.IsFalse (frame.FrameControl.FromDS); + Assert.IsFalse (frame.FrameControl.MoreFragments); + Assert.IsFalse (frame.FrameControl.Retry); + Assert.IsFalse (frame.FrameControl.PowerManagement); + Assert.IsFalse (frame.FrameControl.MoreData); + Assert.IsFalse (frame.FrameControl.Wep); + Assert.IsFalse (frame.FrameControl.Order); + Assert.AreEqual (314, frame.Duration.Field); //this need expanding on in the future + Assert.AreEqual ("001B2F02DC6C", frame.DestinationAddress.ToString ().ToUpper ()); + Assert.AreEqual ("2477030C721C", frame.SourceAddress.ToString ().ToUpper ()); + Assert.AreEqual ("001B2F02DC6C", frame.BssId.ToString ().ToUpper ()); + Assert.AreEqual (0, frame.SequenceControl.FragmentNumber); + Assert.AreEqual (1245, frame.SequenceControl.SequenceNumber); + + Assert.AreEqual (0x8DAD458C, frame.FrameCheckSequence); + Assert.AreEqual (24, frame.FrameSize); + } + + [Test] + public void Test_Constructor_ConstructWithValues () + { + NullDataFrame frame = new NullDataFrame (); + + frame.FrameControl.ToDS = false; + frame.FrameControl.FromDS = true; + frame.FrameControl.MoreFragments = true; + + frame.SequenceControl.SequenceNumber = 0x89; + frame.SequenceControl.FragmentNumber = 0x1; + + frame.Duration.Field = 0x1234; + + frame.DestinationAddress = PhysicalAddress.Parse ("111111111111"); + frame.SourceAddress = PhysicalAddress.Parse ("222222222222"); + frame.BssId = PhysicalAddress.Parse ("333333333333"); + + frame.PayloadData = new byte[]{0x01, 0x02, 0x03, 0x04, 0x05}; + frame.FrameCheckSequence = 0x01020304; + + //serialize the frame into a byte buffer + var bytes = frame.Bytes; + var bas = new ByteArraySegment (bytes); + + //create a new frame that should be identical to the original + NullDataFrame recreatedFrame = MacFrame.ParsePacketWithFcs (bas) as NullDataFrame; + + Assert.AreEqual (FrameControlField.FrameTypes.DataNullFunctionNoData, recreatedFrame.FrameControl.Type); + Assert.IsFalse (recreatedFrame.FrameControl.ToDS); + Assert.IsTrue (recreatedFrame.FrameControl.FromDS); + Assert.IsTrue (recreatedFrame.FrameControl.MoreFragments); + + Assert.AreEqual (0x89, recreatedFrame.SequenceControl.SequenceNumber); + Assert.AreEqual (0x1, recreatedFrame.SequenceControl.FragmentNumber); + + Assert.AreEqual ("111111111111", recreatedFrame.DestinationAddress.ToString ().ToUpper ()); + Assert.AreEqual ("222222222222", recreatedFrame.SourceAddress.ToString ().ToUpper ()); + Assert.AreEqual ("333333333333", recreatedFrame.BssId.ToString ().ToUpper ()); + + Assert.AreEqual (0x01020304, recreatedFrame.FrameCheckSequence); + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `recreatedFrame` last assigned on line 85 could be null and is dereferenced at line 87, column 13. + +### Severity: +ERROR + +### Procedure: +Void NullDataFrameTest.Test_Constructor_ConstructWithValues() + +### File: +Test/PacketType/Ieee80211/NullDataFrameTest.cs + +### Key: +NullDataFrameTest.cs|Test_Constructor_ConstructWithValues|NULL_DEREFERENCE + +### Node Key: +77ad2f96ec34c3b456f6b0b046726793 + +### Hash: +dd0ed6e953483cec3c43947b480ea426 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2652/instruction.md b/inferredbugs-2652/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7cb9af3bcd5bfdac648854c0843879df57012197 --- /dev/null +++ b/inferredbugs-2652/instruction.md @@ -0,0 +1,192 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Kuriimu2 +**Bug ID:** 7 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Eto.Forms; +using Eto.Drawing; +using Kuriimu2.EtoForms.Controls; + +namespace Kuriimu2.EtoForms.Forms +{ + public partial class MainForm : Form + { + #region Commands + + private Command openFileCommand; + private Command openFileWithCommand; + private Command saveAllFileCommand; + + private Command openTextSequenceSearcherCommand; + private Command openBatchExtractorCommand; + private Command openBatchInjectorCommand; + + private Command openHashcommand; + + private Command openEncryptionCommand; + private Command openDecryptionCommand; + + private Command openDecompressionCommand; + private Command openCompressionCommand; + + private Command openRawImageViewerCommand; + + private Command openImageTranscoderCommand; + + private Command openAboutCommand; + + #endregion + + #region Controls + + private TabControl tabControl; + private ProgressBarEx _progressBarEx; + private Label statusMessage; + + #endregion + + void InitializeComponent() + { + #region Commands + + openFileCommand = new Command { MenuText = "Open", Shortcut=OpenHotKey }; + openFileWithCommand = new Command { MenuText = "Open with Plugin", Shortcut=OpenWithHotKey }; + saveAllFileCommand = new Command { MenuText = "Save All", Shortcut = SaveAllHotKey, Image= MenuSaveResource }; + + openTextSequenceSearcherCommand = new Command { MenuText = "Text Sequence Searcher" }; + openBatchExtractorCommand = new Command { MenuText = "Batch Extractor" }; + openBatchInjectorCommand = new Command { MenuText = "Batch Injector" }; + + openHashcommand = new Command { MenuText = "Hashes" }; + + openEncryptionCommand = new Command { MenuText = "Encrypt" }; + openDecryptionCommand = new Command { MenuText = "Decrypt" }; + + openDecompressionCommand = new Command { MenuText = "Decompress" }; + openCompressionCommand = new Command { MenuText = "Compress" }; + + openRawImageViewerCommand = new Command { MenuText = "Raw Image Viewer" }; + + openImageTranscoderCommand = new Command { MenuText = "Image Trascoder" }; + + openAboutCommand = new Command { MenuText = "About..." }; + + #endregion + + Title = "Kuriimu2"; + ClientSize = new Size(1116, 643); + Padding = new Padding(3); + Icon = Icon.FromResource("Kuriimu2.EtoForms.Images.kuriimu2winforms.ico"); + + #region Menu + + Menu = new MenuBar + { + Items = + { + new ButtonMenuItem { Text = "File", Items = { openFileCommand, openFileWithCommand, new SeparatorMenuItem(), saveAllFileCommand } }, + new ButtonMenuItem { Text = "Tools", Items = { openBatchExtractorCommand, openBatchInjectorCommand, openTextSequenceSearcherCommand } }, + new ButtonMenuItem(openHashcommand), + new ButtonMenuItem { Text = "Ciphers", Items = { openEncryptionCommand, openDecryptionCommand } }, + new ButtonMenuItem { Text = "Compressions", Items = { openDecompressionCommand, openCompressionCommand } }, + new ButtonMenuItem(openRawImageViewerCommand), + //new ButtonMenuItem(openImageTranscoderCommand) + }, + AboutItem = openAboutCommand + }; + + #endregion + + #region Content + + tabControl = new TabControl(); + _progressBarEx = new ProgressBarEx(); + statusMessage = new Label(); + + var progressLayout = new TableLayout + { + Spacing = new Size(3, 3), + + Rows = + { + new TableRow + { + Cells = + { + new TableCell(_progressBarEx) { ScaleWidth = true }, + new TableCell(statusMessage) { ScaleWidth = true }, + } + } + } + }; + + Content = new TableLayout + { + AllowDrop = true, + Spacing = new Size(3, 3), + + Rows = + { + new TableRow(tabControl) { ScaleHeight = true }, + progressLayout + } + }; + + #endregion + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource this.Kuriimu2.EtoForms.Forms.MainForm.tabControl of type Eto.Forms.TabControl, Leaked resource this.Kuriimu2.EtoForms.Forms.MainForm.statusMessage of type Eto.Forms.Label, Leaked resource this.Kuriimu2.EtoForms.Forms.MainForm._progressBarEx of type Eto.Forms.Drawable, Leaked resource progressLayout of type Eto.Forms.TableLayout, Leaked resource %1 of type Eto.Forms.TableLayout, Leaked resource (output of Eto.Forms.ButtonMenuItem::.ctor() at Line 78) of type Eto.Forms.ButtonMenuItem, Leaked resource (output of Eto.Forms.ButtonMenuItem::.ctor() at Line 78) of type Eto.Forms.ButtonMenuItem, Leaked resource (output of Eto.Forms.ButtonMenuItem::.ctor() at Line 78) of type Eto.Forms.ButtonMenuItem, Leaked resource (output of Eto.Forms.ButtonMenuItem::.ctor() at Line 78) of type Eto.Forms.ButtonMenuItem, Leaked resource (output of Eto.Forms.ButtonMenuItem::.ctor() at Line 78) of type Eto.Forms.ButtonMenuItem, Leaked resource (output of Eto.Forms.SeparatorMenuItem::.ctor() at Line 78) of type Eto.Forms.SeparatorMenuItem, Leaked resource (output of Eto.Forms.ButtonMenuItem::.ctor() at Line 78) of type Eto.Forms.ButtonMenuItem, Leaked resource (output of Eto.Forms.MenuBar::.ctor() at Line 78) of type Eto.Forms.MenuBar in method "Void MainForm.InitializeComponent()". + +### Severity: +ERROR + +### Procedure: +Void MainForm.InitializeComponent() + +### File: +src/Kuriimu2.EtoForms/Kuriimu2.EtoForms/Forms/MainForm.eto.cs + +### Key: +MainForm.eto.cs|InitializeComponent|DOTNET_RESOURCE_LEAK + +### Hash: +9078ce524162000bbb44bccc8d1f8a6d + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2663/instruction.md b/inferredbugs-2663/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3921c8c620493f5bdc85050095d50524eaf3cfd3 --- /dev/null +++ b/inferredbugs-2663/instruction.md @@ -0,0 +1,130 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Kuriimu2 +**Bug ID:** 8 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Eto.Drawing; +using Eto.Forms; +using Kontract.Interfaces.Plugins.Identifier; + +namespace Kuriimu2.EtoForms.Forms.Dialogs +{ + partial class ChoosePluginDialog : Dialog + { + private StackLayout pluginListPanel; + private Button okButton; + private Button cancelButton; + + #region Commands + + private Command okButtonCommand; + private Command cancelButtonCommand; + + #endregion + + private void InitializeComponent() + { + #region Commands + + okButtonCommand = new Command(); + cancelButtonCommand = new Command(); + + #endregion + + Title = "Choose plugin"; + Size = new Size(450, 700); + Padding = new Padding(3); + + #region Content + + pluginListPanel = new StackLayout + { + HorizontalContentAlignment = HorizontalAlignment.Stretch, + VerticalContentAlignment = VerticalAlignment.Stretch + }; + cancelButton = new Button { Text = "Cancel", Command = cancelButtonCommand }; + okButton = new Button { Text = "Ok", Command = okButtonCommand }; + + Content = new TableLayout + { + Rows = + { + new TableRow { ScaleHeight = true, Cells = { new Scrollable { Content = pluginListPanel } } }, + new TableLayout + { + Padding=new Padding(0, 3), + Spacing = new Size(3, 3), + Rows = + { + new TableRow + { + Cells = + { + new TableCell { ScaleWidth = true }, + cancelButton, + okButton + } + } + } + } + } + }; + + #endregion + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource this.Kuriimu2.EtoForms.Forms.Dialogs.ChoosePluginDialog.pluginListPanel of type Eto.Forms.StackLayout, Leaked resource this.Kuriimu2.EtoForms.Forms.Dialogs.ChoosePluginDialog.okButton of type Eto.Forms.Button, Leaked resource this.Kuriimu2.EtoForms.Forms.Dialogs.ChoosePluginDialog.cancelButton of type Eto.Forms.Button, Leaked resource (output of Eto.Forms.TableLayout::.ctor() at Line 43) of type Eto.Forms.TableLayout, Leaked resource (output of Eto.Forms.Scrollable::.ctor() at Line 43) of type Eto.Forms.Scrollable, Leaked resource (output of Eto.Forms.TableLayout::.ctor() at Line 43) of type Eto.Forms.TableLayout in method "Void ChoosePluginDialog.InitializeComponent()". + +### Severity: +ERROR + +### Procedure: +Void ChoosePluginDialog.InitializeComponent() + +### File: +src/Kuriimu2.EtoForms/Kuriimu2.EtoForms/Forms/Dialogs/ChoosePluginDialog.eto.cs + +### Key: +ChoosePluginDialog.eto.cs|InitializeComponent|DOTNET_RESOURCE_LEAK + +### Hash: +a681da611e185a2a0d14d1e1739c1aa3 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2664/instruction.md b/inferredbugs-2664/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a2d068f708d1fe0469617bf722628c4d1f2a59ab --- /dev/null +++ b/inferredbugs-2664/instruction.md @@ -0,0 +1,364 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Kuriimu2 +**Bug ID:** 21 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Collections.ObjectModel; +using Eto.Drawing; +using Eto.Forms; +using Kuriimu2.EtoForms.Controls; +using Kuriimu2.EtoForms.Forms.Models; +using Kuriimu2.EtoForms.Support; + +namespace Kuriimu2.EtoForms.Forms.Formats +{ + partial class ArchiveForm : Panel + { + private TextBox searchTextBox; + private Button searchClearButton; + + private Button cancelButton; + + private TreeGridView folderView; + private TreeGridItemCollection folders; + + private GridView fileView; + private ObservableCollection files; + + private ButtonToolStripItem saveButton; + private ButtonToolStripItem saveAsButton; + + private ButtonToolStripItem extractButton; + private ButtonToolStripItem replaceButton; + private ButtonToolStripItem renameButton; + private ButtonToolStripItem deleteButton; + + private ButtonMenuItem openWithMenuItem; + + #region Commands + + private Command searchClearCommand; + + private Command cancelCommand; + + private Command openCommand; + private Command openWithCommand; + + private Command saveCommand; + private Command saveAsCommand; + + private Command extractDirectoryCommand; + private Command replaceDirectoryCommand; + private Command renameDirectoryCommand; + private Command deleteDirectoryCommand; + private Command addDirectoryCommand; + + private Command extractFileCommand; + private Command replaceFileCommand; + private Command renameFileCommand; + private Command deleteFileCommand; + + #endregion + + private void InitializeComponent() + { + #region Initialization + + searchTextBox = new TextBox + { + Size=new Size(268,-1) + }; + + #region Commands + + searchClearCommand = new Command { MenuText = "Clear", Image = ImageResources.Actions.Delete }; + + cancelCommand = new Command { MenuText = "Cancel" }; + + openCommand = new Command { MenuText = "Open", Image = ImageResources.Actions.Open }; + openWithCommand = new Command { MenuText = "Open with", Image = ImageResources.Actions.OpenWith }; + + saveCommand = new Command { MenuText = "Save", Shortcut = SaveHotKey, Image = ImageResources.Actions.Save }; + saveAsCommand = new Command { MenuText = "Save As", Shortcut = SaveAsHotKey, Image = ImageResources.Actions.SaveAs }; + + extractDirectoryCommand = new Command { MenuText = "Extract", Image = ImageResources.Actions.FolderExport }; + replaceDirectoryCommand = new Command { MenuText = "Replace", Image = ImageResources.Actions.FolderImport }; + renameDirectoryCommand = new Command { MenuText = "Rename", Image = ImageResources.Actions.Rename }; + deleteDirectoryCommand = new Command { MenuText = "Delete", Image = ImageResources.Actions.Delete }; + addDirectoryCommand = new Command { MenuText = "Add", Image = ImageResources.Actions.Add }; + + extractFileCommand = new Command { MenuText = "Extract", Image = ImageResources.Actions.FileExport }; + replaceFileCommand = new Command { MenuText = "Replace", Image = ImageResources.Actions.FileImport }; + renameFileCommand = new Command { MenuText = "Rename", Image = ImageResources.Actions.Rename }; + deleteFileCommand = new Command { MenuText = "Delete", Image = ImageResources.Actions.Delete }; + + #endregion + + #region Folders + + var folderContext = new ContextMenu + { + Items = + { + extractDirectoryCommand, + replaceDirectoryCommand, + renameDirectoryCommand, + addDirectoryCommand, + deleteDirectoryCommand + } + }; + + folders = new TreeGridItemCollection(); + folderView = new TreeGridView + { + ContextMenu=folderContext, + + DataStore = folders, + Columns = + { + new GridColumn + { + DataCell = new ImageTextCell(0, 1) + } + }, + AllowColumnReordering = false + }; + + #endregion + + #region Files + + //NOTE Image has to be set explicitly, I think the Command is not used anymore as soon as sub-items are added + openWithMenuItem = new ButtonMenuItem { Text = "Open with", Command = openWithCommand, Image = openWithCommand.Image }; + var fileContext = new ContextMenu + { + Items = + { + openCommand, + openWithMenuItem, + + new SeparatorMenuItem(), + + extractFileCommand, + replaceFileCommand, + renameFileCommand, + deleteFileCommand + } + }; + + files = new ObservableCollection(); + fileView = new GridView + { + ShowHeader = true, + AllowMultipleSelection=true, + BackgroundColor = KnownColors.White, + + ContextMenu=fileContext, + + Columns = + { + new GridColumn + { + DataCell = new TextBoxCell(nameof(FileElement.Name)), + HeaderText = "Name", + Sortable = true, + AutoSize = true + }, + new GridColumn + { + DataCell = new TextBoxCell(nameof(FileElement.Size)), + HeaderText = "Size", + Sortable = true, + AutoSize = true + } + }, + + DataStore = files + }; + + #endregion + + #region Buttons + + searchClearButton = new Button + { + Image = ImageResources.Actions.Clear, + ToolTip = "Reset search", + Command = searchClearCommand, + Size = new Size(22,-1) + }; + + cancelButton = new Button + { + Text = "Cancel", + Command = cancelCommand + }; + + saveButton = new ButtonToolStripItem + { + ToolTip = "Save", + Command = saveCommand, + }; + + saveAsButton = new ButtonToolStripItem + { + ToolTip = "Save As", + Command = saveAsCommand, + }; + + extractButton = new ButtonToolStripItem + { + ToolTip = "Extract file(s)", + Command = extractFileCommand, + }; + + replaceButton = new ButtonToolStripItem + { + ToolTip = "Replace file(s)", + Command = replaceFileCommand, + }; + + renameButton = new ButtonToolStripItem + { + ToolTip = "Rename file", + Command = renameFileCommand, + }; + + deleteButton = new ButtonToolStripItem + { + ToolTip = "Delete file", + Command = deleteFileCommand, + }; + + #endregion + + #endregion + + #region Content + + var archiveToolStrip = new ToolStrip + { + Padding = 3, + Items = + { + saveButton, + saveAsButton + } + }; + + var mainContent = new TableLayout + { + Spacing = new Size(3,3), + Rows = + { + // Searchbar and file toolstrip + new TableRow + { + Cells = + { + // Searchbar + new StackLayout + { + Spacing=3, + Orientation = Orientation.Horizontal, + Items = + { + searchTextBox, + searchClearButton + } + }, + + // file toolstrip + new ToolStrip + { + Items = + { + extractButton, + replaceButton, + renameButton, + deleteButton + } + }, + } + }, + + // Folder and file view + new TableRow + { + Cells = + { + folderView, + fileView + } + } + } + }; + + Content = new TableLayout + { + Spacing = new Size(3, 3), + Rows = + { + new TableRow(archiveToolStrip), + new TableRow { Cells = { new TableCell(mainContent) { ScaleWidth = true } }, ScaleHeight = true } + } + }; + + #endregion + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource mainContent of type Eto.Forms.TableLayout, Leaked resource this.Kuriimu2.EtoForms.Forms.Formats.ArchiveForm.searchTextBox of type Eto.Forms.TextBox, Leaked resource this.Kuriimu2.EtoForms.Forms.Formats.ArchiveForm.searchClearButton of type Eto.Forms.Button, Leaked resource this.Kuriimu2.EtoForms.Forms.Formats.ArchiveForm.openWithMenuItem of type Eto.Forms.ButtonMenuItem, Leaked resource this.Kuriimu2.EtoForms.Forms.Formats.ArchiveForm.folderView of type Eto.Forms.TreeGridView, Leaked resource this.Kuriimu2.EtoForms.Forms.Formats.ArchiveForm.cancelButton of type Eto.Forms.Button, Leaked resource %4 of type Eto.Forms.TableLayout, Leaked resource fileContext of type Eto.Forms.ContextMenu, Leaked resource folderContext of type Eto.Forms.ContextMenu, Leaked resource archiveToolStrip of type Eto.Forms.Panel, Leaked resource (output of Kuriimu2.EtoForms.Controls.ToolStrip::.ctor() at Line 244) of type Eto.Forms.Panel, Leaked resource (output of Eto.Forms.StackLayout::.ctor() at Line 244) of type Eto.Forms.StackLayout, Leaked resource (output of Eto.Forms.TextBoxCell::.ctor() at Line 145) of type Eto.Forms.TextBoxCell, Leaked resource (output of Eto.Forms.GridColumn::.ctor() at Line 145) of type Eto.Forms.GridColumn, Leaked resource (output of Eto.Forms.TextBoxCell::.ctor() at Line 145) of type Eto.Forms.TextBoxCell, Leaked resource (output of Eto.Forms.GridColumn::.ctor() at Line 145) of type Eto.Forms.GridColumn, Leaked resource (output of Eto.Forms.SeparatorMenuItem::.ctor() at Line 128) of type Eto.Forms.SeparatorMenuItem, Leaked resource (output of Eto.Forms.ImageTextCell::.ctor() at Line 107) of type Eto.Forms.ImageTextCell, Leaked resource (output of Eto.Forms.GridColumn::.ctor() at Line 107) of type Eto.Forms.GridColumn in method "Void ArchiveForm.InitializeComponent()". + +### Severity: +ERROR + +### Procedure: +Void ArchiveForm.InitializeComponent() + +### File: +src/Kuriimu2.EtoForms/Kuriimu2.EtoForms/Forms/Formats/ArchiveForm.eto.cs + +### Key: +ArchiveForm.eto.cs|InitializeComponent|DOTNET_RESOURCE_LEAK + +### Hash: +36d3c5136ac4a05d307d1730a5d03cee + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2690/instruction.md b/inferredbugs-2690/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b0499b79ce8e733cb2ab9091b36964a2328211dc --- /dev/null +++ b/inferredbugs-2690/instruction.md @@ -0,0 +1,148 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** yopngs +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Amazon.S3; +using Amazon.S3.Model; +using Iimages.IStore; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Configuration; +using System.Collections.Generic; + +namespace Iimages.Stores +{ + public class S3Store : StoreBase + { + AmazonS3Client Client; + + string Domain; + + public S3Store(string secretID, string secretKey, string region, string domain) + { + Domain = domain; + + var endPoint = new AmazonS3Config(); + endPoint.ServiceURL = region; + // endPoint.AuthenticationRegion = region; + Client = new AmazonS3Client(secretID, secretKey, endPoint); + + + } + + public override bool Up(byte[] maps, string localName, string localUrl, ref string cdnUrl) + { + var files= Client.ListBucketsAsync().Result ; + var putRequest2 = new PutObjectRequest + { + BucketName = "xpnas-assets", + //获取和设置键属性。此键用于标识S3中的对象,上传到s3的路径+文件名, + //S3上没有文件夹可以创建一个,参考https://www.cnblogs.com/web424/p/6840207.html + Key = localName, + //所有者获得完全控制权,匿名主体被授予读访问权。如果 + //此策略用于对象,它可以从浏览器中读取,无需验证 + CannedACL = S3CannedACL.PublicRead, + //上传的文件路径 + FilePath = @"C:\Users\Administrator\Desktop\favicon.png", + //为对象设置的标记。标记集必须编码为URL查询参数 + TagSet = new List{ new Tag { Key = "Test", Value = "S3Test"} } + //ContentType = "image/png" + }; + // putRequest2.Metadata.Add("x-amz-meta-title", "AwsS3Net"); + PutObjectResponse response2 = Client.PutObjectAsync(putRequest2).Result; + return false; + } + + } + + public class S3StoreFactory : IStoreFactory + { + public IDataStore[] GetStores(IApplicationBuilder app, IConfiguration configuration) + { + + var results = new List(); + var selection = configuration.GetSection("S3Stores"); + foreach (IConfigurationSection section in selection.GetChildren()) + { + var active = section.GetValue("active"); + if (active) + { + var secretID = section.GetValue("secretID"); + var secretKey = section.GetValue("secretKey"); + var region = section.GetValue("region"); + var domain = section.GetValue("Domain"); + + var index = section.GetValue("index"); + var name = section.GetValue("name"); + var type = section.GetValue("type"); + + + var diskStore = new S3Store(secretID, secretKey, region, domain) + { + Name = name, + Type = type, + Index = index + }; + + results.Add(diskStore); + } + } + + return results.ToArray(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource diskStore.Iimages.Stores.S3Store.Client of type Amazon.S3.AmazonS3Client in method "IDataStore[] S3StoreFactory.GetStores(IApplicationBuilder,IConfiguration)". + +### Severity: +ERROR + +### Procedure: +IDataStore[] S3StoreFactory.GetStores(IApplicationBuilder,IConfiguration) + +### File: +yopngs/Stores/S3Store.cs + +### Key: +S3Store.cs|GetStores|DOTNET_RESOURCE_LEAK + +### Hash: +2631ad65383055008a3697fdd52e44fd + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2697/instruction.md b/inferredbugs-2697/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c08cf15615f20bf194f5ee9ef7bafaa46683d4a --- /dev/null +++ b/inferredbugs-2697/instruction.md @@ -0,0 +1,1366 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** c-raft +**Bug ID:** 5 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +#region C#raft License +// This file is part of C#raft. Copyright C#raft Team +// +// C#raft is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . +#endregion +using System; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using Chraft.Interfaces.Containers; +using Chraft.Net; +using Chraft.Net.Packets; +using Chraft.Plugins.Events; +using Chraft.Properties; +using System.IO; +using Chraft.Entity; +using Chraft.World.Blocks; +using Chraft.World.Blocks.Physics; +using Chraft.World.Weather; +using Chraft.Plugins.Events.Args; +using System.Threading.Tasks; +using Chraft.Utils; +using System.Collections.Generic; +using Chraft.WorldGen; +using System.Collections.Concurrent; +using java.util; +using Timer = System.Threading.Timer; + +namespace Chraft.World +{ + public partial class WorldManager : IDisposable + { + private Timer _globalTick; + private IChunkGenerator _generator; + public object ChunkGenLock = new object(); + private ChunkProvider _chunkProvider; + + public sbyte Dimension { get { return 0; } } + public long Seed { get; private set; } + public UniversalCoords Spawn { get; set; } + public bool Running { get; private set; } + public Server Server { get; private set; } + public Logger Logger { get { return Server.Logger; } } + public string Name { get { return Settings.Default.DefaultWorldName; } } + public string Folder { get { return Settings.Default.WorldsFolder + Path.DirectorySeparatorChar + Name; } } + public string SignsFolder { get { return Folder + Path.DirectorySeparatorChar + "Signs"; } } + + public WeatherManager Weather { get; private set; } + + private readonly ChunkSet _chunks; + private ChunkSet Chunks { get { return _chunks; } } + + public ConcurrentQueue ChunksToRecalculate; + + public ConcurrentDictionary PhysicsBlocks; + private Task _physicsSimulationTask; + private Task _entityUpdateTask; + private Task _mobSpawnerTask; + + public ConcurrentQueue ChunksToSave; + + public ConcurrentDictionary PendingChunks = new ConcurrentDictionary(); + + private CancellationTokenSource _saveToken; + public bool NeedsFullSave; + public bool FullSaving; + + private Task _growStuffTask; + private Task _collectTask; + private Task _saveTask; + private Task _profile; + + private int _time; + private Chunk[] _chunksCache; + /// + /// In units of 0.05 seconds (between 0 and 23999) + /// + public int Time + { + get { + int time = _time; + + return time; } + set { + _time = value; + } + } + + private int _worldTicks; + + /// + /// The current World Tick independant of the world's current Time (1 tick = 0.05 secs with a max value of 4,294,967,295 gives approx. 6.9 years of ticks) + /// + public int WorldTicks + { + get + { + return _worldTicks; + } + } + + public Chunk GetChunk(UniversalCoords coords, bool create = false, bool load = false) + { + Chunk chunk; + if ((chunk = Chunks[coords]) != null) + return chunk; + + return load ? LoadChunk(coords, create) : null; + } + + public Chunk GetChunkFromChunkSync(int chunkX, int chunkZ, bool create = false, bool load = false) + { + Chunk chunk; + if ((chunk = Chunks[chunkX, chunkZ]) != null) + return chunk; + + return load ? LoadChunk(UniversalCoords.FromChunk(chunkX, chunkZ), create) : null; + } + + public Chunk GetChunkFromChunkAsync(int chunkX, int chunkZ, Client client, bool create = false, bool load = false) + { + Chunk chunk; + if ((chunk = Chunks[chunkX, chunkZ]) != null) + return chunk; + + return load ? LoadChunk(UniversalCoords.FromChunk(chunkX, chunkZ), create, client, false) : null; + } + + public Chunk GetChunkFromWorld(int worldX, int worldZ, bool create = false, bool load = false) + { + Chunk chunk; + if ((chunk = Chunks[worldX >> 4, worldZ >> 4]) != null) + return chunk; + + return load ? LoadChunk(UniversalCoords.FromWorld(worldX, 0, worldZ), create) : null; + } + + public Chunk GetChunkFromAbs(double absX, double absZ, bool create = false, bool load = false) + { + int worldX = (int) Math.Floor(absX); + int worldZ = (int)Math.Floor(absZ); + + Chunk chunk; + if ((chunk = Chunks[worldX >> 4, worldZ >> 4]) != null) + return chunk; + + return load ? LoadChunk(UniversalCoords.FromWorld(worldX, 0, worldZ), create) : null; + } + + public IEnumerable GetEntitiesWithinBoundingBoxExcludingEntity(EntityBase entity, BoundingBox boundingBox) + { + return (from e in Server.GetEntitiesWithinBoundingBox(boundingBox) + where e != entity + select e); + } + + public BoundingBox[] GetCollidingBoundingBoxes(EntityBase entity, BoundingBox boundingBox) + { + List collidingBoundingBoxes = new List(); + + UniversalCoords minimumBlockXYZ = UniversalCoords.FromAbsWorld(boundingBox.Minimum.X, boundingBox.Minimum.Y, boundingBox.Minimum.Z); + UniversalCoords maximumBlockXYZ = UniversalCoords.FromAbsWorld(boundingBox.Maximum.X + 1.0D, boundingBox.Maximum.Y + 1.0D, boundingBox.Maximum.Z + 1.0D); + + for (int x = minimumBlockXYZ.WorldX; x < maximumBlockXYZ.WorldX; x++) + { + for (int z = minimumBlockXYZ.WorldZ; z < maximumBlockXYZ.WorldZ; z++) + { + Chunk chunk = GetChunkFromWorld(x, z); + + if (chunk == null) + continue; + + for (int y = minimumBlockXYZ.WorldY - 1; y < maximumBlockXYZ.WorldY; y++) + { + StructBlock block = chunk.GetBlock(UniversalCoords.FromWorld(x, y, z)); + + BlockBase blockInstance = BlockHelper.Instance(block.Type); + + if (blockInstance != null && blockInstance.IsCollidable) + { + BoundingBox blockBox = blockInstance.GetCollisionBoundingBox(block); + if (blockBox.IntersectsWith(boundingBox)) + { + collidingBoundingBoxes.Add(blockBox); + } + } + } + } + } + + foreach (var e in GetEntitiesWithinBoundingBoxExcludingEntity(entity, boundingBox.Expand(new Vector3(0.25, 0.25, 0.25)))) + { + collidingBoundingBoxes.Add(e.BoundingBox); + + // TODO: determine if overridable collision boxes between two entities is necessary + BoundingBox? collisionBox = entity.GetCollisionBox(e); + if (collisionBox != null && collisionBox.Value != e.BoundingBox && collisionBox.Value.IntersectsWith(boundingBox)) + { + collidingBoundingBoxes.Add(collisionBox.Value); + } + } + + return collidingBoundingBoxes.ToArray(); + } + double[] _lightBrightnessTable = new double[16]; + public WorldManager(Server server) + { + _chunks = new ChunkSet(); + Server = server; + ChunksToRecalculate = new ConcurrentQueue(); + ChunksToSave = new ConcurrentQueue(); + Load(); + + // Create the light brightness table + double d = 0.0; + for(int i = 0; i < 16; i++) + { + double d1 = 1.0 - (double)i / 15.0; + _lightBrightnessTable[i] = ((1.0 - d1) / (d1 * 3.0 + 1.0)) * (1.0 - d) + d; + } + } + + public bool Load() + { + EnsureDirectory(); + + //Event + WorldLoadEventArgs e = new WorldLoadEventArgs(this); + Server.PluginManager.CallEvent(Event.WorldLoad, e); + if (e.EventCanceled) return false; + //End Event + + _chunkProvider = new ChunkProvider(this); + _generator = _chunkProvider.GetNewGenerator(GeneratorType.Custom, GetSeed()); + PhysicsBlocks = new ConcurrentDictionary(); + + InitializeSpawn(); + InitializeThreads(); + InitializeWeather(); + return true; + } + + private void InitializeWeather() + { + Weather = new WeatherManager(this); + } + + public int GetHeight(UniversalCoords coords) + { + Chunk chunk = GetChunk(coords); + if (chunk == null) + return -1; + + return GetChunk(coords).HeightMap[coords.BlockX, coords.BlockZ]; + } + + public int GetHeight(int x, int z) + { + Chunk chunk = GetChunkFromWorld(x, z); + + if(chunk == null) + return -1; + return chunk.HeightMap[x & 0xf, z & 0xf]; + } + + public void AddChunk(Chunk c) + { + c.CreationDate = DateTime.Now; + Chunks.Add(c); + } + + public ConcurrentDictionary TempPendingChunks = new ConcurrentDictionary(); + + private Chunk LoadChunk(UniversalCoords coords, bool create, Client client = null, bool sync = true) + { + ChunkEntry newEntry = new ChunkEntry(); + ChunkEntry entry; + ChunkEntry removedEntry; + + entry = PendingChunks.GetOrAdd(coords.ChunkPackedCoords, newEntry); + int state = Interlocked.CompareExchange(ref entry.State, ChunkEntry.InProgress, ChunkEntry.NotInitialized); + Chunk chunk; + + if (state == ChunkEntry.NotInitialized) + { + int threads; + + Interlocked.Increment(ref entry.ThreadsWaiting); + // The entry could have been just readded but the chunk is already initialized + if ((chunk = Chunks[coords]) != null) + { + threads = Interlocked.Decrement(ref entry.ThreadsWaiting); + if (threads == 0) + PendingChunks.TryRemove(coords.ChunkPackedCoords, out removedEntry); + + entry.ChunkRequested = chunk; + entry.State = ChunkEntry.Initialized; + + NotifyChunkToClients(entry); + + entry.ChunkLock.Set(); + + return chunk; + + } + + + if ((chunk = Chunk.Load(coords, this)) != null) + AddChunk(chunk); + else if (create) + chunk = _generator.ProvideChunk(coords.ChunkX, coords.ChunkZ, this); + + if(chunk == null) + { + threads = Interlocked.Decrement(ref entry.ThreadsWaiting); + + if (threads == 0) + PendingChunks.TryRemove(coords.ChunkPackedCoords, out removedEntry); + + entry.ChunkLock.Set(); + + return chunk; + } + + entry.ChunkRequested = chunk; + entry.State = ChunkEntry.Initialized; + + threads = Interlocked.Decrement(ref entry.ThreadsWaiting); + + if (threads == 0) + PendingChunks.TryRemove(coords.ChunkPackedCoords, out removedEntry); + + NotifyChunkToClients(entry); + entry.ChunkLock.Set(); + + if (chunk != null) + { + chunk.InitGrowableCache(); + ContainerFactory.LoadContainersFromDisk(chunk); + } + + return chunk; + } + + if (state == ChunkEntry.InProgress) + { + Interlocked.Increment(ref entry.ThreadsWaiting); + + if (!sync) + entry.Requests.Enqueue(new ClientRequest { ClientRequesting = client }); + else + entry.ChunkLock.WaitOne(); + + + int threads = Interlocked.Decrement(ref entry.ThreadsWaiting); + if (threads == 0) + PendingChunks.TryRemove(coords.ChunkPackedCoords, out removedEntry); + + if(!sync) + { + if (entry.State == ChunkEntry.Initialized) + NotifyChunkToClients(entry); + + return null; + } + + if (entry.State == ChunkEntry.Initialized) + chunk = Chunks[coords]; + else + return null; + + Debug.Assert(chunk != null, "RETURNING NULL CHUNK"); + return chunk; + } + + chunk = Chunks[coords]; + + Debug.Assert(chunk != null, "RETURNING NULL CHUNK"); + Debug.Assert(!PendingChunks.TryGetValue(coords.ChunkPackedCoords, out entry), "ENTRY INITIALIZED AND STILL LISTED"); + + return chunk; + } + + private void NotifyChunkToClients(ChunkEntry entry) + { + int notifyState = Interlocked.CompareExchange(ref entry.NotifyStatus, ChunkEntry.Notified, + ChunkEntry.NotNotified); + + if (notifyState == ChunkEntry.Notified || entry.Requests.IsEmpty) + return; + + Task.Factory.StartNew(() => + { + Parallel.For(0, entry.Requests.Count, (i) => + { + ClientRequest req; + + if (!entry.Requests.TryDequeue(out req)) + return; + + if (entry.ChunkRequested.LightToRecalculate) + entry.ChunkRequested.RecalculateSky(); + + req.ClientRequesting.Owner.LoadedChunks.TryUpdate(entry.ChunkRequested.Coords.ChunkPackedCoords, + entry.ChunkRequested, null); + entry.ChunkRequested.AddClient(req.ClientRequesting); + req.ClientRequesting.SendPreChunk(entry.ChunkRequested.Coords.ChunkX, entry.ChunkRequested.Coords.ChunkZ, true, false); + req.ClientRequesting.SendChunk(entry.ChunkRequested, false); + }); + }); + } + + private void InitializeThreads() + { + Running = true; + _globalTick = new Timer(GlobalTickProc, null, 50, 50); + } + + private void InitializeSpawn() + { + Logger.LogOnOneLine(Logger.LogLevel.Info, "Initializing spawn area...", true); + Spawn = UniversalCoords.FromWorld(Settings.Default.SpawnX, Settings.Default.SpawnY, Settings.Default.SpawnZ); + + Queue toRecalculate = new Queue(); + Chunk chunk = GetChunkFromWorld(Spawn.WorldX, Spawn.WorldZ, true, true); + chunk.Persistent = true; + toRecalculate.Enqueue(chunk); + + Spawn = UniversalCoords.FromWorld(Spawn.WorldX, chunk.HeightMap[Spawn.WorldX, Spawn.WorldZ] + 4, Spawn.WorldZ); + + int chunkX = Spawn.ChunkX; + int chunkZ = Spawn.ChunkZ; + + + for(int x = chunkX - 4; x < chunkX + 4; ++x) + { + for(int z = chunkZ - 4; z < chunkZ + 4; ++z) + { + if(x == chunkX && z == chunkZ) + continue; + + chunk = GetChunkFromChunkSync(x, z, true, true); + chunk.Persistent = true; + toRecalculate.Enqueue(chunk); + } + } + + while(toRecalculate.Count > 0) + { + chunk = toRecalculate.Dequeue(); + + if (chunk.LightToRecalculate) + chunk.RecalculateSky(); + + AddChunk(chunk); + } + + Logger.LogOnOneLine(Logger.LogLevel.Info, " Done\n", false); + } + + private void CollectProc() + { + CheckAliveClients(); + Chunk[] chunks = GetChunks(); + foreach (Chunk c in chunks) + { + if (c.Persistent) + continue; + if (c.GetClients().Length > 0 || (DateTime.Now - c.CreationDate) < TimeSpan.FromSeconds(20.0)) + continue; + + c.Save(); + Chunks.Remove(c); + } + } + + public void CheckAliveClients() + { + Parallel.ForEach(Server.GetClients(), c => c.CheckAlive()); + } + + private void FullSave() + { + // Wait until the task has been canceled + _saveTask.Wait(); + + int count = ChunksToSave.Count; + _saveTask = Task.Factory.StartNew(() => SaveProc(count, CancellationToken.None)); + NeedsFullSave = false; + FullSaving = false; + } + + private void SaveProc(int chunkToSave, CancellationToken token) + { + if (token.IsCancellationRequested) + return; + + int count = ChunksToSave.Count; + + if (count > chunkToSave) + count = chunkToSave; + + for (int i = 0; i < count && Running && !token.IsCancellationRequested; ++i) + { + ChunkBase chunk; + ChunksToSave.TryDequeue(out chunk); + + if (chunk == null) + continue; + + /* Better to "signal" that the chunk can be queued again before saving, + * we don't know which signaled changes will be saved during the save */ + Interlocked.Exchange(ref chunk.ChangesToSave, 0); + + chunk.Save(); + + } + } + + private void EnsureDirectory() + { + if (!Directory.Exists(Settings.Default.WorldsFolder)) + Directory.CreateDirectory(Settings.Default.WorldsFolder); + if (!Directory.Exists(Folder)) + Directory.CreateDirectory(Folder); + } + + public static int LightUpdateCounter; + + private void GlobalTickProc(object state) + { + // Increment the world tick count + Interlocked.Increment(ref _worldTicks); + + int time = Interlocked.Increment(ref _time); + + if (time == 24000) + { // A day has passed. + // MUST interface directly with _Time to bypass the write lock, which we hold. + _time = 0; + } + + // Using this.WorldTick here as it is independant of this.Time. "this.Time" can be changed outside of the WorldManager. + if (WorldTicks % 10 == 0) + { + // Triggered once every half second + Task.Factory.StartNew(Server.DoPulse); + } + + if (NeedsFullSave) + { + FullSaving = true; + if(_saveTask != null && !_saveTask.IsCompleted) + _saveToken.Cancel(); + + Task.Factory.StartNew(FullSave); + } + else if(WorldTicks % 20 == 0 && !FullSaving && ChunksToSave.Count > 0) + { + if(_saveTask == null || _saveTask.IsCompleted) + { + _saveToken = new CancellationTokenSource(); + var token = _saveToken.Token; + _saveTask = Task.Factory.StartNew(() => SaveProc(20, token), token); + } + } + + // Every 5 seconds + if(WorldTicks % 100 == 0) + { + if(_collectTask == null || _collectTask.IsCompleted) + { + _collectTask = Task.Factory.StartNew(CollectProc); + } + } + + // Every 10 seconds + if (WorldTicks % 200 == 0) + { + if (_growStuffTask == null || _growStuffTask.IsCompleted) + { + _growStuffTask = Task.Factory.StartNew(GrowProc); + } + } + + // Every Tick (50ms) + if (_physicsSimulationTask == null || _physicsSimulationTask.IsCompleted) + { + _physicsSimulationTask = Task.Factory.StartNew(PhysicsProc); + } + + if (_entityUpdateTask == null || _entityUpdateTask.IsCompleted) + { + _entityUpdateTask = Task.Factory.StartNew(EntityProc); + } + + // Every 2 Ticks (100ms) + if (WorldTicks % 2 == 0) + { + if (_mobSpawnerTask == null || _mobSpawnerTask.IsCompleted) + { + _mobSpawnerTask = Task.Factory.StartNew(MobSpawnerProc); + } + } + +#if PROFILE + // Must wait at least one second between calls to perf counter + if (WorldTicks % 20 == 0) + { + if(_profile == null || _profile.IsCompleted) + { + _profile = Task.Factory.StartNew(Profile); + } + } +#endif + } + +#if PROFILE + private void Profile() + { + if (Server.ProfileStartTime == DateTime.MinValue) + Server.ProfileStartTime = DateTime.Now; + + using (StreamWriter writer = new StreamWriter("cpu.csv", true)) + { + writer.WriteLine("{0};{1}", (DateTime.Now - Server.ProfileStartTime).TotalSeconds, Server.CpuPerfCounter.NextValue() / Environment.ProcessorCount); + } + } +#endif + + public void Dispose() + { + this.Running = false; + this._globalTick.Change(Timeout.Infinite, Timeout.Infinite); + } + + public byte GetBlockOrLoad(int x, int y, int z) + { + return GetChunkFromWorld(x, z, true, true)[x & 0xf, y, z & 0xf]; + } + + public Chunk[] GetChunks() + { + int changes = Interlocked.Exchange(ref Chunks.Changes, 0); + if(_chunksCache == null || changes > 0) + _chunksCache = Chunks.Values.ToArray(); + + return _chunksCache; + } + + private void GrowProc() + { + foreach (Chunk c in GetChunks()) + { + c.Grow(); + } + } + + private void PhysicsProc() + { + foreach (var physicsBlock in PhysicsBlocks) + { + physicsBlock.Value.Simulate(); + } + } + + private void EntityProc() + { + Parallel.ForEach(Server.GetEntities().Where((entity) => entity.World == this), (e) => + { + e.Update(); + }); + } + + private void MobSpawnerProc() + { + WorldMobSpawner.SpawnMobs(this, true, this.WorldTicks % 400 == 0); + } + + /// + /// Yields each found within the bounds of a + /// + /// + /// + public IEnumerable GetBlocksInBoundingBox(BoundingBox boundingBox) + { + UniversalCoords minimum = + UniversalCoords.FromAbsWorld( + boundingBox.Minimum.X < 0.0 ? boundingBox.Minimum.X - 1.0 : boundingBox.Minimum.X, + boundingBox.Minimum.Y < 0.0 ? boundingBox.Minimum.Y - 1.0 : boundingBox.Minimum.Y, + boundingBox.Minimum.Z < 0.0 ? boundingBox.Minimum.Z - 1.0 : boundingBox.Minimum.Z); + UniversalCoords maximum = UniversalCoords.FromAbsWorld(boundingBox.Maximum.X + 1.0, + boundingBox.Maximum.Y + 1.0, + boundingBox.Maximum.Z + 1.0); + + return GetBlocksBetweenCoords(minimum, maximum); + } + + /// + /// Yields each found between two coordinates + /// + /// Start here + /// Stop here + /// Yields a for each coordinate between minimum and maximum + public IEnumerable GetBlocksBetweenCoords(UniversalCoords minimum, UniversalCoords maximum) + { + if (minimum.WorldX >= maximum.WorldX || minimum.WorldY >= maximum.WorldY || minimum.WorldZ >= maximum.WorldZ) + throw new ArgumentOutOfRangeException("minimum", "minimum X, Y and Z must be less than maximum X, Y and Z"); + + for (int x = minimum.WorldX; x < maximum.WorldX; x++) + { + for (int y = minimum.WorldY; y < maximum.WorldY; y++) + { + for (int z = minimum.WorldZ; z < maximum.WorldZ; z++) + { + yield return this.GetBlock(x, y, z); + } + } + } + } + + public StructBlock GetBlock(UniversalCoords coords) + { + Chunk chunk = GetChunk(coords); + + if(chunk == null) + return StructBlock.Empty; + + byte blockId = (byte)chunk.GetType(coords); + byte blockData = chunk.GetData(coords); + + return new StructBlock(coords, blockId, blockData, this); + } + + public StructBlock GetBlock(int worldX, int worldY, int worldZ) + { + Chunk chunk = GetChunkFromWorld(worldX, worldZ); + + if (chunk == null) + return StructBlock.Empty; + + byte blockId = (byte)chunk.GetType(worldX & 0xF, worldY, worldZ & 0xF); + byte blockData = chunk.GetData(worldX & 0xF, worldY, worldZ & 0xF); + + return new StructBlock(worldX, worldY, worldZ, blockId, blockData, this); + } + + public byte? GetBlockId(UniversalCoords coords) + { + Chunk chunk = Chunks[coords]; + + if (chunk != null) + return chunk[coords]; + + return null; + } + + public byte? GetBlockId(int worldX, int worldY, int worldZ) + { + Chunk chunk = Chunks[worldX >> 4, worldZ >> 4]; + + if (chunk != null) + return chunk[worldX & 0xF, worldY, worldZ & 0xF]; + + return null; + } + + public byte? GetBlockData(UniversalCoords coords) + { + Chunk chunk = Chunks[coords]; + if (chunk != null) + return chunk.GetData(coords); + + return null; + } + + public byte? GetBlockData(int worldX, int worldY, int worldZ) + { + Chunk chunk = Chunks[worldX >> 4, worldZ >> 4]; + if (chunk != null) + return chunk.GetData(worldX & 0xF, worldY, worldZ & 0xF); + + return null; + } + + public double GetBlockLightBrightness(UniversalCoords coords) + { + byte? effectiveLight = GetEffectiveLight(coords); + if(effectiveLight == null) + return 0.0; + + return _lightBrightnessTable[(byte)effectiveLight]; + } + + public byte? GetFullBlockLight(UniversalCoords coords) + { + Chunk chunk = GetChunk(coords, false, false); + + if (chunk == null) + return null; + + return Math.Max(chunk.GetSkyLight(coords), chunk.GetBlockLight(coords)); + } + + /// + /// Get the Effective light at a coordinate + /// + /// + /// + public byte? GetEffectiveLight(UniversalCoords coords) + { + // TODO: this needs to return the effective light for a block, taking into consideration the time of day etc... see calculateSkylightSubtracted and getBlockLightValue_do + return GetFullBlockLight(coords); // THIS HAS TO BE REMOVED AND CHANGED TO PROPER TIME CALCULATION TOO + } + + public byte? GetBlockLight(UniversalCoords coords) + { + Chunk chunk = Chunks[coords]; + if (chunk != null) + return chunk.GetBlockLight(coords); + + return null; + } + + public byte? GetBlockLight(int worldX, int worldY, int worldZ) + { + Chunk chunk = Chunks[worldX >> 4, worldZ >> 4]; + if (chunk != null) + return chunk.GetBlockLight(worldX & 0xF, worldY, worldZ & 0xF); + + return null; + } + + public byte? GetSkyLight(UniversalCoords coords) + { + Chunk chunk = Chunks[coords]; + if (chunk != null) + return chunk.GetSkyLight(coords); + + return null; + } + + public byte? GetSkyLight(int worldX, int worldY, int worldZ) + { + Chunk chunk = Chunks[worldX >> 4, worldZ >> 4]; + if (chunk != null) + return chunk.GetSkyLight(worldX & 0xF, worldY, worldZ & 0xF); + + return null; + } + + public IEnumerable GetEntities() + { + return Server.GetEntities().Where((e) => e != null && e.World == this); + } + + public Player GetClosestPlayer(AbsWorldCoords coords, double radius) + { + var radiusSqrd = radius * radius; + Vector3 coordVector = coords.ToVector(); + return (from c in Server.GetAuthenticatedClients().Where(client => client.Owner.World == this) + let distance = coordVector.DistanceSquared(c.Owner.Position.ToVector()) + where distance <= radiusSqrd + orderby distance + select c.Owner).FirstOrDefault(); + } + + private RayTraceHitBlock DoRayTraceBlock(UniversalCoords coords, Vector3 rayStart, Vector3 rayEnd) + { + Chunk chunk = GetChunk(coords); + + if (chunk == null) + return null; + + byte blockType = (byte)chunk.GetType(coords); // only get the block type first to save time + if (blockType > 0) + { + byte blockData = chunk.GetData(coords); + + StructBlock block = new StructBlock(coords, (byte)blockType, (byte)blockData, this); + BlockBase blockClass = BlockHelper.Instance(block.Type); + RayTraceHitBlock blockRayTrace = blockClass.RayTraceIntersection(block, rayStart, rayEnd); + if (blockRayTrace != null) + { + return blockRayTrace; + } + } + return null; + } + + /// + /// Ray traces the blocks along the ray. This method takes approx 0.1ms per 50-60 metres. + /// + /// + /// The first block hit + /// + /// + /// Ray start. + /// + /// + /// Ray end. + /// + public RayTraceHitBlock RayTraceBlocks(AbsWorldCoords rayStart, AbsWorldCoords rayEnd) + { + UniversalCoords startCoord = UniversalCoords.FromAbsWorld(rayStart); + UniversalCoords endCoord = UniversalCoords.FromAbsWorld(rayEnd); + + UniversalCoords previousPoint; + UniversalCoords currentPoint = startCoord; + + Vector3 rayStartVec = rayStart.ToVector(); + Vector3 rayEndVec = rayEnd.ToVector(); + + Vector3 stepVector = (rayEndVec - rayStartVec).Normalize(); + + bool xDirectionPositive = stepVector.X > 0; + bool yDirectionPositive = stepVector.Y > 0; + bool zDirectionPositive = stepVector.Z > 0; + + Vector3 currentVec = rayStartVec; + previousPoint = currentPoint; + + RayTraceHitBlock blockTrace = null; + int blockCheckCount = 0; + try + { + // Step along the ray looking for block collisions + while (true) + { + #region Check adjacent blocks if necessary (to prevent skipping over the corner of one) + bool xChanged = currentPoint.WorldX - previousPoint.WorldX != 0; + bool yChanged = currentPoint.WorldY - previousPoint.WorldY != 0; + bool zChanged = currentPoint.WorldZ - previousPoint.WorldZ != 0; + + // When we change a coord, need to check which adjacent block also needs to be checked (to prevent missing blocks when jumping over their corners) + if (xChanged && yChanged && zChanged) + { + // -X,Y,Z + blockCheckCount++; + blockTrace = DoRayTraceBlock(UniversalCoords.FromWorld(previousPoint.WorldX, currentPoint.WorldY, currentPoint.WorldZ), rayStartVec, rayEndVec); + if (blockTrace != null) + return blockTrace; + // X,-Y,Z + blockCheckCount++; + blockTrace = DoRayTraceBlock(UniversalCoords.FromWorld(currentPoint.WorldX, previousPoint.WorldY, currentPoint.WorldZ), rayStartVec, rayEndVec); + if (blockTrace != null) + return blockTrace; + // X,Y,-Z + blockCheckCount++; + blockTrace = DoRayTraceBlock(UniversalCoords.FromWorld(currentPoint.WorldX, currentPoint.WorldY, previousPoint.WorldZ), rayStartVec, rayEndVec); + if (blockTrace != null) + return blockTrace; + + // -X,Y,-Z + blockCheckCount++; + blockTrace = DoRayTraceBlock(UniversalCoords.FromWorld(previousPoint.WorldX, currentPoint.WorldY, previousPoint.WorldZ), rayStartVec, rayEndVec); + if (blockTrace != null) + return blockTrace; + // -X,-Y,Z + blockCheckCount++; + blockTrace = DoRayTraceBlock(UniversalCoords.FromWorld(previousPoint.WorldX, previousPoint.WorldY, currentPoint.WorldZ), rayStartVec, rayEndVec); + if (blockTrace != null) + return blockTrace; + // X,-Y,-Z + blockCheckCount++; + blockTrace = DoRayTraceBlock(UniversalCoords.FromWorld(currentPoint.WorldX, previousPoint.WorldY, previousPoint.WorldZ), rayStartVec, rayEndVec); + if (blockTrace != null) + return blockTrace; + } + else if (xChanged && zChanged) + { + // -X,Y,Z + blockCheckCount++; + blockTrace = DoRayTraceBlock(UniversalCoords.FromWorld(previousPoint.WorldX, currentPoint.WorldY, currentPoint.WorldZ), rayStartVec, rayEndVec); + if (blockTrace != null) + return blockTrace; + // X,Y,-Z + blockCheckCount++; + blockTrace = DoRayTraceBlock(UniversalCoords.FromWorld(currentPoint.WorldX, currentPoint.WorldY, previousPoint.WorldZ), rayStartVec, rayEndVec); + if (blockTrace != null) + return blockTrace; + } + else if (xChanged && yChanged) + { + // -X,Y,Z + blockCheckCount++; + blockTrace = DoRayTraceBlock(UniversalCoords.FromWorld(previousPoint.WorldX, currentPoint.WorldY, currentPoint.WorldZ), rayStartVec, rayEndVec); + if (blockTrace != null) + return blockTrace; + // X,-Y,Z + blockCheckCount++; + blockTrace = DoRayTraceBlock(UniversalCoords.FromWorld(currentPoint.WorldX, previousPoint.WorldY, currentPoint.WorldZ), rayStartVec, rayEndVec); + if (blockTrace != null) + return blockTrace; + } + else if (zChanged && yChanged) + { + // X,Y,-Z + blockCheckCount++; + blockTrace = DoRayTraceBlock(UniversalCoords.FromWorld(currentPoint.WorldX, currentPoint.WorldY, previousPoint.WorldZ), rayStartVec, rayEndVec); + if (blockTrace != null) + return blockTrace; + // X,-Y,Z + blockCheckCount++; + blockTrace = DoRayTraceBlock(UniversalCoords.FromWorld(currentPoint.WorldX, previousPoint.WorldY, currentPoint.WorldZ), rayStartVec, rayEndVec); + if (blockTrace != null) + return blockTrace; + } + #endregion + + // Check the currentPoint + blockCheckCount++; + blockTrace = DoRayTraceBlock(currentPoint, rayStartVec, rayEndVec); + if (blockTrace != null) + return blockTrace; + + if (currentPoint == endCoord) + { + //Console.WriteLine("Reach endCoord with no hits"); + break; + } + + #region Get the next coordinate + previousPoint = currentPoint; + do + { + currentVec += stepVector; + currentPoint = UniversalCoords.FromAbsWorld(currentVec.X, currentVec.Y, currentVec.Z); + } while(previousPoint == currentPoint); + + // check we haven't gone past the endCoord + if ((xDirectionPositive && currentPoint.WorldX > endCoord.WorldX) || (!xDirectionPositive && currentPoint.WorldX < endCoord.WorldX) || + (yDirectionPositive && currentPoint.WorldY > endCoord.WorldY) || (!yDirectionPositive && currentPoint.WorldY < endCoord.WorldY) || + (zDirectionPositive && currentPoint.WorldZ > endCoord.WorldZ) || (!zDirectionPositive && currentPoint.WorldZ < endCoord.WorldZ)) + { + //Console.WriteLine("Went past endCoord: {0}, {1}", startCoord, endCoord); + break; + } + #endregion + } + } + finally + { + //Console.WriteLine("Block check count {0}", blockCheckCount); + } + return null; + } + + public long GetSeed() + { + return Settings.Default.WorldSeed.GetHashCode(); + } + + public void SetBlockAndData(UniversalCoords coords, byte type, byte data, bool needsUpdate = true) + { + Chunk chunk = GetChunk(coords); + + if(chunk == null) + return; + + chunk.SetType(coords, (BlockData.Blocks)type, false); + chunk.SetData(coords, data, false); + + if(needsUpdate) + chunk.BlockNeedsUpdate(coords.BlockX, coords.BlockY, coords.BlockZ); + } + + public void SetBlockAndData(int worldX, int worldY, int worldZ, byte type, byte data, bool needsUpdate = true) + { + Chunk chunk = GetChunkFromWorld(worldX, worldZ); + + if (chunk == null) + return; + + chunk.SetType(worldX & 0xF, worldY, worldZ & 0xF, (BlockData.Blocks)type, false); + chunk.SetData(worldX & 0xF, worldY, worldZ & 0xF, data, false); + + if (needsUpdate) + chunk.BlockNeedsUpdate(worldX & 0xF, worldY, worldZ & 0xF); + } + + public void SetBlockData(UniversalCoords coords, byte data, bool needsUpdate = true) + { + Chunk chunk = GetChunk(coords); + + if(chunk != null) + chunk.SetData(coords, data, needsUpdate); + } + + public void SetBlockData(int worldX, int worldY, int worldZ, byte data, bool needsUpdate = true) + { + Chunk chunk = GetChunkFromWorld(worldX, worldZ); + + if(chunk != null) + chunk.SetData(worldX & 0xF, worldY, worldZ & 0xF, data, needsUpdate); + } + + public bool ChunkExists(UniversalCoords coords) + { + return (Chunks[coords] != null); + } + + public bool ChunkExists(int chunkX, int chunkZ) + { + return (Chunks[chunkX, chunkZ] != null); + } + + public void RemoveChunk(Chunk c) + { + Chunks.Remove(c); + } + + internal void Update(UniversalCoords coords, bool updateClients = true) + { + Chunk chunk = GetChunk(coords); + + if (chunk == null) + return; + + if (updateClients) + chunk.BlockNeedsUpdate(coords.BlockX, coords.BlockY, coords.BlockZ); + + UpdatePhysics(coords); + chunk.ForAdjacent(coords, uc => UpdatePhysics(uc)); + } + + private void UpdatePhysics(UniversalCoords coords, bool updateClients = true) + { + Chunk chunk = GetChunk(coords); + + if (chunk == null) + return; + + BlockData.Blocks type = chunk.GetType(coords); + UniversalCoords oneDown = UniversalCoords.FromWorld(coords.WorldX, coords.WorldY - 1, coords.WorldZ); + + if (type == BlockData.Blocks.Water) + { + byte water = 8; + chunk.ForNSEW(coords, delegate(UniversalCoords uc) + { + Chunk nearbyChunk = GetChunk(uc); + + if (nearbyChunk == null) + return; + + BlockData.Blocks blockId = nearbyChunk.GetType(uc); + byte blockData; + if (blockId == BlockData.Blocks.Still_Water) + water = 0; + else if (blockId == BlockData.Blocks.Water && (blockData = nearbyChunk.GetData(uc)) < water) + water = (byte)(blockData + 1); + }); + + if (water != chunk.GetData(coords)) + { + if (water == 8) + chunk.SetBlockAndData(coords, 0, 0); + else + chunk.SetBlockAndData(coords, (byte)BlockData.Blocks.Water, water); + //Update(x, y, z, updateClients); + return; + } + } + + if (type == BlockData.Blocks.Air) + { + UniversalCoords oneUp = UniversalCoords.FromWorld(coords.WorldX, coords.WorldY + 1, coords.WorldZ); + BlockData.Blocks blockIdOneUp = chunk.GetType(oneUp); + if (coords.WorldY < 127 && (blockIdOneUp == BlockData.Blocks.Water || blockIdOneUp == BlockData.Blocks.Still_Water)) + { + chunk.SetBlockAndData(coords, (byte)BlockData.Blocks.Water, 0); + //Update(x, y, z, updateClients); + return; + } + + if (coords.WorldY < 127 && (blockIdOneUp == BlockData.Blocks.Lava || blockIdOneUp == BlockData.Blocks.Still_Lava)) + { + chunk.SetBlockAndData(coords, (byte)BlockData.Blocks.Lava, 0); + //Update(x, y, z, updateClients); + return; + } + + byte water = 8; + + chunk.ForNSEW(coords, delegate(UniversalCoords uc) + { + Chunk nearbyChunk = GetChunk(uc); + + if (nearbyChunk == null) + return; + + BlockData.Blocks blockId = nearbyChunk.GetType(uc); + byte blockData; + + if (blockId == BlockData.Blocks.Still_Water) + water = 0; + else if (blockId == BlockData.Blocks.Water && (blockData = nearbyChunk.GetData(uc)) < water) + water = (byte)(blockData + 1); + }); + if (water < 8) + { + chunk.SetBlockAndData(coords, (byte)BlockData.Blocks.Water, water); + //Update(x, y, z, updateClients); + return; + } + + byte lava = 8; + chunk.ForNSEW(coords, delegate(UniversalCoords uc) + { + Chunk nearbyChunk = GetChunk(uc); + + if (nearbyChunk == null) + return; + + BlockData.Blocks blockId = nearbyChunk.GetType(uc); + byte blockData; + + if (blockId == BlockData.Blocks.Still_Lava) + lava = 0; + else if (blockId == BlockData.Blocks.Lava && (blockData = nearbyChunk.GetData(uc)) < lava) + lava = (byte)(blockData + 1); + }); + if (water < 4) + { + chunk.SetBlockAndData(coords, (byte)BlockData.Blocks.Lava, lava); + //Update(x, y, z, updateClients); + return; + } + } + } + + internal UniversalCoords FromFace(UniversalCoords coords, BlockFace blockFace) + { + int bx = coords.WorldX; + int by = coords.WorldY; + int bz = coords.WorldZ; + + switch (blockFace) + { + case BlockFace.Self: + break; + + case BlockFace.Up: + by++; + break; + + case BlockFace.Down: + by--; + break; + + case BlockFace.North: + bx--; + break; + + case BlockFace.South: + bx++; + break; + + case BlockFace.East: + bz--; + break; + + case BlockFace.West: + bz++; + break; + + case BlockFace.NorthEast: + bx--; + bz--; + break; + + case BlockFace.NorthWest: + bx--; + bz++; + break; + + case BlockFace.SouthEast: + bx++; + bz--; + break; + + case BlockFace.SouthWest: + bx++; + bz++; + break; + } + + return UniversalCoords.FromWorld(bx, by, bz); + } + } +} + + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `chunk` last assigned on line 453 could be null and is dereferenced at line 454, column 21. + +### Severity: +ERROR + +### Procedure: +Void WorldManager.InitializeSpawn() + +### File: +Chraft/World/WorldManager.cs + +### Key: +WorldManager.cs|InitializeSpawn|NULL_DEREFERENCE + +### Node Key: +b34ba4f9627ab82a4c31e4bc155b159b + +### Hash: +8cc37a103595615afffddd6c1c5c9ca5 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2699/instruction.md b/inferredbugs-2699/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ea19b80b367721a6c9217971f161138c8cb9b5f6 --- /dev/null +++ b/inferredbugs-2699/instruction.md @@ -0,0 +1,227 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** sdk-csharp +**Bug ID:** 11 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// Copyright 2021 Cloud Native Foundation. +// Licensed under the Apache 2.0 license. +// See LICENSE file in the project root for full license information. + +using CloudNative.CloudEvents.UnitTests; +using Newtonsoft.Json.Linq; +using System; +using System.Net.Mime; +using System.Text; +using Xunit; + +namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests +{ + /// + /// Tests for + /// + public class GenericJsonEventFormatterTest + { + [Fact] + public void DecodeStructuredMode() + { + var obj = JsonEventFormatterTest.CreateMinimalValidJObject(); + obj["data"] = new JObject { [AttributedModel.JsonPropertyName] = "test" }; + byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); + + var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); + var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, null, null); + + var model = (AttributedModel) cloudEvent.Data; + Assert.Equal("test", model.AttributedProperty); + } + + [Fact] + public void DecodeStructuredMode_ContentTypeIgnored() + { + var obj = JsonEventFormatterTest.CreateMinimalValidJObject(); + obj["data"] = new JObject { [AttributedModel.JsonPropertyName] = "test" }; + byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); + + var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); + var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, new ContentType("text/plain"), null); + + var model = (AttributedModel)cloudEvent.Data; + Assert.Equal("test", model.AttributedProperty); + } + + [Fact] + public void DecodeStructuredMode_NoData() + { + var obj = JsonEventFormatterTest.CreateMinimalValidJObject(); + byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); + + var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); + var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, null, null); + Assert.Null(cloudEvent.Data); + } + + [Fact] + public void DecodeStructuredMode_Base64Data() + { + var obj = JsonEventFormatterTest.CreateMinimalValidJObject(); + obj["data_base64"] = Convert.ToBase64String(Encoding.UTF8.GetBytes("{}")); + byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); + + var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); + Assert.Throws(() => formatter.DecodeStructuredModeMessage(bytes, null, null)); + } + + [Fact] + public void DecodeBinaryEventModeData() + { + var obj = new JObject { [AttributedModel.JsonPropertyName] = "test" }; + byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); + + var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); + var cloudEvent = new CloudEvent(); + formatter.DecodeBinaryModeEventData(bytes, cloudEvent); + + var model = (AttributedModel)cloudEvent.Data; + Assert.Equal("test", model.AttributedProperty); + } + + [Fact] + public void DecodeBinaryEventModeData_NoData() + { + var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); + var cloudEvent = new CloudEvent { Data = "original" }; + formatter.DecodeBinaryModeEventData(new byte[0], cloudEvent); + Assert.Null(cloudEvent.Data); + } + + [Fact] + public void EncodeStructuredMode() + { + var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); + cloudEvent.Data = new AttributedModel { AttributedProperty = "test" }; + var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); + var body = formatter.EncodeStructuredModeMessage(cloudEvent, out _); + var jobject = JsonEventFormatterTest.ParseJson(body); + Assert.False(jobject.ContainsKey("data_base64")); + var data = (JObject)jobject["data"]; + + new JTokenAsserter + { + { AttributedModel.JsonPropertyName, JTokenType.String, "test" } + }.AssertProperties(data, assertCount: true); + } + + [Fact] + public void EncodeStructuredMode_NoData() + { + var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); + + var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); + var body = formatter.EncodeStructuredModeMessage(cloudEvent, out _); + var jobject = JsonEventFormatterTest.ParseJson(body); + Assert.False(jobject.ContainsKey("data")); + Assert.False(jobject.ContainsKey("data_base64")); + } + + [Fact] + public void EncodeStructuredMode_WrongType() + { + var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); + cloudEvent.Data = new OtherModelClass { Text = "Wrong type" }; + var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); + Assert.Throws(() => formatter.EncodeStructuredModeMessage(cloudEvent, out _)); + } + + [Fact] + public void EncodeBinaryModeEventData() + { + var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); + cloudEvent.Data = new AttributedModel { AttributedProperty = "test" }; + var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); + var body = formatter.EncodeBinaryModeEventData(cloudEvent); + var jobject = JsonEventFormatterTest.ParseJson(body); + + new JTokenAsserter + { + { AttributedModel.JsonPropertyName, JTokenType.String, "test" } + }.AssertProperties(jobject, assertCount: true); + } + + [Fact] + public void EncodeBinaryModeEventData_NoData() + { + var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); + var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); + var bytes = formatter.EncodeBinaryModeEventData(cloudEvent); + Assert.True(bytes.IsEmpty); + } + + [Fact] + public void EncodeBinaryModeEventData_WrongType() + { + var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); + cloudEvent.Data = new OtherModelClass { Text = "Wrong type" }; + var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); + Assert.Throws(() => formatter.EncodeBinaryModeEventData(cloudEvent)); + } + + private class OtherModelClass + { + public string Text { get; set; } + } + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`formatter` could be null (from the call to `CloudEventFormatterAttribute.CreateFormatter(...)` on line 75) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +Void GenericJsonEventFormatterTest.DecodeBinaryEventModeData() + +### File: +test/CloudNative.CloudEvents.UnitTests/NewtonsoftJson/GenericJsonEventFormatterTest.cs + +### Key: +GenericJsonEventFormatterTest.cs|DecodeBinaryEventModeData|NULLPTR_DEREFERENCE + +### Hash: +e293b077aceaabaee39b903ff3b02845 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2773/instruction.md b/inferredbugs-2773/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e8ff6dcbdfcf0e10da306ed62834e86bbb93d2b6 --- /dev/null +++ b/inferredbugs-2773/instruction.md @@ -0,0 +1,82 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** data-accelerator +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// ********************************************************************* +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License +// ********************************************************************* +using DataX.Contract; + +namespace DataX.Utilities.EventHub +{ + public static class EventHub + { + public static ApiResult CreateConsumerGroup(string subscriptionId, string keyvaultName, string resourceGroup, string resourceGroupLocation, string eventHubNamespace, string eventHubName, string consumerGroupName, string inputType, string clientId, string tenantId, string secretPrefix) + { + EventHubUtil eventHubUtil = new EventHubUtil(subscriptionId, resourceGroupLocation, keyvaultName, clientId, tenantId, secretPrefix); + return eventHubUtil.CreateConsumerGroup(resourceGroup, eventHubNamespace, eventHubName, consumerGroupName, inputType); + } + + public static ApiResult DeleteConsumerGroup(string subscriptionId, string keyvaultName, string resourceGroup, string resourceGroupLocation, string eventHubNamespace, string eventHubName, string consumerGroupName, string inputType, string clientId, string tenantId, string secretPrefix) + { + EventHubUtil eventHubUtil = new EventHubUtil(subscriptionId, resourceGroupLocation, keyvaultName, clientId, tenantId, secretPrefix); + return eventHubUtil.DeleteConsumerGroup(resourceGroup, eventHubNamespace, eventHubName, consumerGroupName, inputType); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource eventHubUtil of type DataX.Utilities.EventHub.EventHubUtil in method "ApiResult EventHub.CreateConsumerGroup(String,String,String,String,String,String,String,String,String,String,String)". + +### Severity: +ERROR + +### Procedure: +ApiResult EventHub.CreateConsumerGroup(String,String,String,String,String,String,String,String,String,String,String) + +### File: +Services/DataX.Utilities/DataX.Utilities.EventHub/EventHub.cs + +### Key: +EventHub.cs|CreateConsumerGroup|DOTNET_RESOURCE_LEAK + +### Hash: +444c09f3676ba2a67ed5213f6fb443f2 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2774/instruction.md b/inferredbugs-2774/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8a3d62bd1df6efc81c8b9f944100d02bf7a3a30f --- /dev/null +++ b/inferredbugs-2774/instruction.md @@ -0,0 +1,82 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** data-accelerator +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// ********************************************************************* +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License +// ********************************************************************* +using DataX.Contract; + +namespace DataX.Utilities.EventHub +{ + public static class EventHub + { + public static ApiResult CreateConsumerGroup(string subscriptionId, string keyvaultName, string resourceGroup, string resourceGroupLocation, string eventHubNamespace, string eventHubName, string consumerGroupName, string inputType, string clientId, string tenantId, string secretPrefix) + { + EventHubUtil eventHubUtil = new EventHubUtil(subscriptionId, resourceGroupLocation, keyvaultName, clientId, tenantId, secretPrefix); + return eventHubUtil.CreateConsumerGroup(resourceGroup, eventHubNamespace, eventHubName, consumerGroupName, inputType); + } + + public static ApiResult DeleteConsumerGroup(string subscriptionId, string keyvaultName, string resourceGroup, string resourceGroupLocation, string eventHubNamespace, string eventHubName, string consumerGroupName, string inputType, string clientId, string tenantId, string secretPrefix) + { + EventHubUtil eventHubUtil = new EventHubUtil(subscriptionId, resourceGroupLocation, keyvaultName, clientId, tenantId, secretPrefix); + return eventHubUtil.DeleteConsumerGroup(resourceGroup, eventHubNamespace, eventHubName, consumerGroupName, inputType); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource eventHubUtil of type DataX.Utilities.EventHub.EventHubUtil in method "ApiResult EventHub.DeleteConsumerGroup(String,String,String,String,String,String,String,String,String,String,String)". + +### Severity: +ERROR + +### Procedure: +ApiResult EventHub.DeleteConsumerGroup(String,String,String,String,String,String,String,String,String,String,String) + +### File: +Services/DataX.Utilities/DataX.Utilities.EventHub/EventHub.cs + +### Key: +EventHub.cs|DeleteConsumerGroup|DOTNET_RESOURCE_LEAK + +### Hash: +51d66b1a6b73468de0ccc5b62fd0b5ca + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2780/instruction.md b/inferredbugs-2780/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ac82a3a77eb9c2d4eddada84dc555c00f9150bfd --- /dev/null +++ b/inferredbugs-2780/instruction.md @@ -0,0 +1,204 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Binance +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; + +// ReSharper disable once CheckNamespace +namespace Binance +{ + public sealed class ApiRateLimiter : IApiRateLimiter + { + #region Public Constants + + public static readonly bool EnabledDefault = true; + + #endregion Public Constants + + #region Public Properties + + public bool IsEnabled { get => _isEnabled; set => _isEnabled = value; } + + #endregion Public Properties + + #region Private Fields + + private readonly IServiceProvider _services; + + private volatile bool _isEnabled = EnabledDefault; + + private readonly IDictionary _limiters + = new Dictionary(); + + private readonly object _sync = new object(); + + #endregion Private Fields + + #region Constructors + + /// + /// Constructor. + /// + /// + public ApiRateLimiter(IServiceProvider services = null) + { + _services = services; + } + + #endregion Constructors + + #region Public Methods + + public void Configure(TimeSpan duration, int count) + { + if (count < 0) + throw new ArgumentException($"{nameof(IApiRateLimiter)} count must be greater than 0 (or equal to 0 to disable).", nameof(count)); + + ThrowIfDisposed(); + + lock (_sync) + { + if (count == 0) + { + if (_limiters.ContainsKey(duration)) + { + _limiters.Remove(duration); + } + return; + } + + if (_limiters.ContainsKey(duration)) + { + _limiters[duration].Count = count; + return; + } + + var limiter = _services?.GetService() ?? new RateLimiter(); + + limiter.Duration = duration; + limiter.Count = count; + + _limiters[duration] = limiter; + } + } + + public async Task DelayAsync(int count = 1, CancellationToken token = default) + { + if (!IsEnabled) + return; + + ThrowIfDisposed(); + + IEnumerable limiters; + + lock (_sync) + { + limiters = _limiters.Values.ToArray(); + } + + foreach (var limiter in limiters) + { + await limiter.DelayAsync(count, token) + .ConfigureAwait(false); + } + } + + #endregion Public Methods + + #region IDisposable + + private bool _disposed; + + private void ThrowIfDisposed() + { + if (_disposed) + throw new ObjectDisposedException(nameof(ApiRateLimiter)); + } + + private void Dispose(bool disposing) + { + if (_disposed) + return; + + if (disposing) + { + lock (_sync) + { + foreach (var limiter in _limiters.Values) + { + limiter.Dispose(); + } + } + } + + _disposed = true; + } + + public void Dispose() + { + Dispose(true); + } + + #endregion IDisposable + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource limiter of type Binance.RateLimiter in method "Void ApiRateLimiter.Configure(TimeSpan,Int32)". + +### Severity: +ERROR + +### Procedure: +Void ApiRateLimiter.Configure(TimeSpan,Int32) + +### File: +src/Binance/Api/RateLimit/ApiRateLimiter.cs + +### Key: +ApiRateLimiter.cs|Configure|DOTNET_RESOURCE_LEAK + +### Hash: +10de3202e816c07901f6841816acc673 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2787/instruction.md b/inferredbugs-2787/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..171b9c1a8e6c59a13148ebba9f172214a0863e15 --- /dev/null +++ b/inferredbugs-2787/instruction.md @@ -0,0 +1,271 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** couchbase-net-client +**Bug ID:** 51 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using Couchbase.Configuration.Client; +using Couchbase.Configuration.Server.Serialization; +using Couchbase.Tests.Core.Buckets; +using Couchbase.Tests.Documents; +using Couchbase.Views; +using NUnit.Framework; + +namespace Couchbase.Tests.Views +{ + [TestFixture] + public class ViewClientTests + { + [Test] + public void When_Row_Is_Dynamic_Query_By_Key_Succeeds() + { + var query = new ViewQuery(). + From("beer", "all_beers"). + Bucket("beer-sample").Limit(1); + + var client = new ViewClient(new HttpClient(), + new JsonDataMapper(new ClientConfiguration()), + new BucketConfig { Name = "beer-sample" }, + new ClientConfiguration()); + + var result = client.Execute(query); + + var query2 = new ViewQuery(). + From("beer", "all_beers"). + Bucket("beer-sample").Key(result.Rows.First().Id); + + var result2 = client.Execute(query2); + Assert.AreEqual(result.Rows.First().Id, result2.Rows.First().Id); + } + + [Test] + public void When_Poco_Is_Supplied_Map_Results_To_It() + { + var query = new ViewQuery(). + From("beer", "all_beers"). + Bucket("beer-sample").Limit(10); + + var client = new ViewClient(new HttpClient(), + new JsonDataMapper(new ClientConfiguration()), + new BucketConfig { Name = "beer-sample" }, + new ClientConfiguration()); + + var result = client.Execute(query); + foreach (var viewRow in result.Rows) + { + Assert.IsNotNull(viewRow.Id); + } + Console.WriteLine(result.Error); + Assert.IsNotNull(result.Rows); + Assert.IsTrue(result.Success); + Assert.AreEqual(result.Rows.Count(), result.Values.Count()); + } + + [Test] + public void When_Query_Is_Succesful_Rows_Are_Returned() + { + var query = new ViewQuery(). + From("beer", "brewery_beers"). + Bucket("beer-sample"). + Limit(10); + + var client = new ViewClient(new HttpClient(), + new JsonDataMapper(new ClientConfiguration()), + new BucketConfig { Name = "beer-sample" }, + new ClientConfiguration()); + + var result = client.Execute(query); + Assert.IsNotNull(result.Rows); + foreach (var viewRow in result.Rows) + { + Assert.IsNotNull(viewRow.Id); + } + Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); + } + + [Test] + public void When_View_Is_Not_Found_404_Is_Returned() + { + var query = new ViewQuery(). + From("beer", "view_that_does_not_exist"). + Bucket("beer-sample"); + + var client = new ViewClient(new HttpClient(), + new JsonDataMapper(new ClientConfiguration()), + new BucketConfig { Name = "beer-sample" }, + new ClientConfiguration()); + + var result = client.Execute(query); + + Assert.IsNotNull(result.Message); + Assert.AreEqual(HttpStatusCode.NotFound, result.StatusCode); + Assert.IsFalse(result.Success); + + Console.WriteLine(result.Message); + } + + [Test] + public void When_View_Is_Called_With_Invalid_Parameters_Error_Is_Returned() + { + var query = new ViewQuery(). + From("beer", "brewery_beers"). + Bucket("beer-sample"). + Group(true); + + var client = new ViewClient(new HttpClient(), + new JsonDataMapper(new ClientConfiguration()), + new BucketConfig { Name = "beer-sample" }, + new ClientConfiguration()); + + var result = client.Execute(query); + + Assert.AreEqual("query_parse_error", result.Error); + Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode); + Assert.IsFalse(result.Success); + + Console.WriteLine(result.Message); + } + + [Test] + public void When_Url_Is_Invalid_WebException_Is_Returned() + { + var query = new ViewQuery(). + From("beer", "brewery_beers"). + Bucket("beer-sample"). + BaseUri("http://192.168.56.105:8092/"); + + var client = new ViewClient(new HttpClient(), + new JsonDataMapper(new ClientConfiguration()), + new BucketConfig { Name = "beer-sample" }, + new ClientConfiguration{ViewRequestTimeout = 30000}); + + var result = client.Execute(query); + Assert.IsNotNull(result.Rows); + Assert.IsFalse(result.Success); + Assert.AreEqual(HttpStatusCode.ServiceUnavailable, result.StatusCode); + Assert.AreEqual(typeof(WebException), result.Exception.GetType()); + } + + [Test] + public void When_Url_Is_Invalid_WebException_Is_Returned_2() + { + var query = new ViewQuery(). + From("beer", "brewery_beers"). + Bucket("beer-sample"). + BaseUri("http://192.168.62.200:8092/"); + + var client = new ViewClient(new HttpClient(), + new JsonDataMapper(new ClientConfiguration()), + new BucketConfig { Name = "beer-sample" }, + new ClientConfiguration{ViewRequestTimeout = 30000}); + + var result = client.Execute(query); + Assert.IsNotNull(result.Rows); + Assert.IsFalse(result.Success); + Assert.AreEqual(HttpStatusCode.ServiceUnavailable, result.StatusCode); + Assert.AreEqual(typeof(WebException), result.Exception.GetType()); + } + + [Test] + public void Test_ExecuteAsync() + { + var query = new ViewQuery(). + From("docs", "all_docs"). + Bucket("default"); + + var client = new ViewClient(new HttpClient(), + new JsonDataMapper(new ClientConfiguration()), + new BucketConfig { Name = "beer-sample" }, + new ClientConfiguration()); + + int n = 10000; + var options = new ParallelOptions { MaxDegreeOfParallelism = 4}; + + Parallel.For(0, n, options, async i => + { + var result = await client.ExecuteAsync(query); + Console.WriteLine("{0} {1} {2}", i, result.Success, result.Message); + }); + } + } +} + +#region [ License information ] + +/* ************************************************************ + * + * @author Couchbase + * @copyright 2014 Couchbase, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ************************************************************/ + +#endregion +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of System.Net.Http.HttpClient::.ctor() at Line 47) of type System.Net.Http.HttpClient in method "Void ViewClientTests.When_Poco_Is_Supplied_Map_Results_To_It()". + +### Severity: +ERROR + +### Procedure: +Void ViewClientTests.When_Poco_Is_Supplied_Map_Results_To_It() + +### File: +Src/Couchbase.Tests/Views/ViewClientTests.cs + +### Key: +ViewClientTests.cs|When_Poco_Is_Supplied_Map_Results_To_It|DOTNET_RESOURCE_LEAK + +### Hash: +6412a30fb1c2a352532daef839b0a8a1 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2789/instruction.md b/inferredbugs-2789/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c2baca1bc2425c3a5380b57f29ff2d82d813b476 --- /dev/null +++ b/inferredbugs-2789/instruction.md @@ -0,0 +1,162 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** couchbase-net-client +**Bug ID:** 33 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using Couchbase.Views; +using NUnit.Framework; + +namespace Couchbase.Tests.Views +{ + [TestFixture] + public class ViewClientTests + { + [Test] + public void When_Query_Is_Succesful_Rows_Are_Returned() + { + var query = new ViewQuery(). + From("beer", "brewery_beers"). + Bucket("beer-sample"); + + var client = new ViewClient(new HttpClient(), new JsonDataMapper()); + var result = client.Execute(query); + Assert.IsNotNull(result.Rows); + Assert.AreEqual(result.StatusCode, HttpStatusCode.OK); + } + + [Test] + public void When_View_Is_Not_Found_404_Is_Returned() + { + var query = new ViewQuery(). + From("beer", "view_that_does_not_exist"). + Bucket("beer-sample"); + + var client = new ViewClient(new HttpClient(), new JsonDataMapper()); + var result = client.Execute(query); + + Assert.IsNotNull(result.Message); + Assert.AreEqual(HttpStatusCode.NotFound, result.StatusCode); + Assert.IsFalse(result.Success); + + Console.WriteLine(result.Message); + } + + [Test] + public void When_View_Is_Called_With_Invalid_Parameters_Error_Is_Returned() + { + var query = new ViewQuery(). + From("beer", "brewery_beers"). + Bucket("beer-sample"). + Group(true); + + var client = new ViewClient(new HttpClient(), new JsonDataMapper()); + var result = client.Execute(query); + + Assert.AreEqual("query_parse_error", result.Error); + Assert.AreEqual("Invalid URL parameter 'group' or 'group_level' for non-reduce view.", result.Message); + Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode); + Assert.IsFalse(result.Success); + + Console.WriteLine(result.Message); + } + + [Test] + public void When_Url_Is_Invalid_WebException_Is_Returned() + { + var query = new ViewQuery(). + From("beer", "brewery_beers"). + Bucket("beer-sample"). + BaseUri("http://192.168.56.105:8092/"); + + var client = new ViewClient(new HttpClient(), new JsonDataMapper()); + var result = client.Execute(query); + Assert.IsNotNull(result.Rows); + Assert.IsFalse(result.Success); + Assert.AreEqual(HttpStatusCode.ServiceUnavailable, result.StatusCode); + Assert.AreEqual(typeof(HttpRequestException), result.Exception.GetType()); + } + } +} + +#region [ License information ] + +/* ************************************************************ + * + * @author Couchbase + * @copyright 2014 Couchbase, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ************************************************************/ + +#endregion +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of System.Net.Http.HttpClient::.ctor() at Line 36) of type System.Net.Http.HttpClient in method "Void ViewClientTests.When_View_Is_Not_Found_404_Is_Returned()". + +### Severity: +ERROR + +### Procedure: +Void ViewClientTests.When_View_Is_Not_Found_404_Is_Returned() + +### File: +Src/Couchbase.Tests/Views/ViewClientTests.cs + +### Key: +ViewClientTests.cs|When_View_Is_Not_Found_404_Is_Returned|DOTNET_RESOURCE_LEAK + +### Hash: +d1e239941694ee78c7bbb67550328a14 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2800/instruction.md b/inferredbugs-2800/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5ba80e0c8fc5e9689af513779f99da11e02d4df2 --- /dev/null +++ b/inferredbugs-2800/instruction.md @@ -0,0 +1,115 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** couchbase-net-client +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Collections.Generic; +using System.Linq; +using Couchbase.Configuration; +using Couchbase.Configuration.Server.Providers.FileSystem; +using Couchbase.Core; +using Couchbase.Core.Buckets; +using Couchbase.Tests.Configuration.Client; +using NUnit.Framework; + +namespace Couchbase.Tests.Configuration +{ + [TestFixture] + public class ConfigInfoTests + { + private IConfigInfo _configInfo; + + [TestFixtureSetUp] + public void SetUp() + { + var clientConfig = new FakeClientConfig(); + var serverConfig = new FileSystemConfig(clientConfig.BootstrapPath); + serverConfig.Initialize(); + _configInfo = new ConfigInfo(serverConfig, clientConfig); + } + + [Test] + public void Test_GetKeyMapper() + { + var keyMapper = _configInfo.GetKeyMapper("default"); + Assert.IsNotNull(keyMapper); + } + + [Test] + public void Test_MapKey() + { + const string key = "TheKey"; + var keyMapper = _configInfo.GetKeyMapper("default"); + var vBucket = keyMapper.MapKey(key); + Assert.IsNotNull(vBucket); + } + + [Test] + public void Test_BucketType() + { + Assert.AreEqual(BucketTypeEnum.Couchbase, _configInfo.BucketType); + } + + [Test] + [ExpectedException(typeof(NullConfigException))] + public void Test_BucketType_Throws_NullConfigException_When_Config_Is_Null() + { + var configInfo = new PersistentConfigContext(null, null); + Assert.AreEqual(BucketTypeEnum.Couchbase, configInfo.BucketType); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource configInfo of type Couchbase.Configuration.PersistentConfigContext in method "Void ConfigInfoTests.Test_BucketType_Throws_NullConfigException_When_Config_Is_Null()". + +### Severity: +ERROR + +### Procedure: +Void ConfigInfoTests.Test_BucketType_Throws_NullConfigException_When_Config_Is_Null() + +### File: +Src/Couchbase.Tests/Configuration/ConfigInfoTests.cs + +### Key: +ConfigInfoTests.cs|Test_BucketType_Throws_NullConfigException_When_Config_Is_Null|DOTNET_RESOURCE_LEAK + +### Hash: +4b0edb81dc21bdcf659c418e09a14fcd + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2807/instruction.md b/inferredbugs-2807/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..92312164e43cde470843337122cc91a67b02199a --- /dev/null +++ b/inferredbugs-2807/instruction.md @@ -0,0 +1,90 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** couchbase-net-client +**Bug ID:** 8 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Couchbase.Configuration.Client; +using Couchbase.Configuration.Server.Serialization; +using Couchbase.Core; +using Couchbase.IO; +using Couchbase.IO.Strategies.Awaitable; + +namespace Couchbase.Tests.Helpers +{ + public static class ObjectFactory + { + internal static IOStrategy CreateIOStrategy(string server) + { + var connectionPool = new DefaultConnectionPool(new PoolConfiguration(), Server.GetEndPoint(server)); + var ioStrategy = new AwaitableIOStrategy(connectionPool, null); + return ioStrategy; + } + + internal static IOStrategy CreateIOStrategy(Node node) + { + var server = node.Hostname.Replace("8091", node.Ports.Direct.ToString()); + var connectionPool = new DefaultConnectionPool(new PoolConfiguration(), Server.GetEndPoint(server)); + var ioStrategy = new AwaitableIOStrategy(connectionPool, null); + return ioStrategy; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type Couchbase.IO.Strategies.Awaitable.AwaitableIOStrategy, Leaked resource connectionPool of type Couchbase.IO.DefaultConnectionPool in method "IOStrategy ObjectFactory.CreateIOStrategy(String)". + +### Severity: +ERROR + +### Procedure: +IOStrategy ObjectFactory.CreateIOStrategy(String) + +### File: +Src/Couchbase.Tests/Helpers/ObjectFactory.cs + +### Key: +ObjectFactory.cs|CreateIOStrategy|DOTNET_RESOURCE_LEAK + +### Hash: +9cedda9d6982e4a8703e7704d7f18d5a + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2809/instruction.md b/inferredbugs-2809/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..68a2a6a6c15d6ac259a65d57c45b86af8d1c400a --- /dev/null +++ b/inferredbugs-2809/instruction.md @@ -0,0 +1,410 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** couchbase-net-client +**Bug ID:** 44 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Configuration; +using System.Diagnostics; +using System.Linq; +using System.Net.Http; +using Couchbase.Configuration.Client; +using Couchbase.N1QL; +using Couchbase.Tests.Documents; +using Couchbase.Views; +using Newtonsoft.Json.Bson; +using NUnit.Framework; + +namespace Couchbase.Tests.N1QL +{ + [TestFixture] + public class QueryClientTests + { + private readonly string _server = ConfigurationManager.AppSettings["serverIp"]; + + [Test] + public void Test_Create_Index() + { + var config = new ClientConfiguration(); + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var uri = new Uri(string.Format("http://{0}:8093/query", _server)); + + var indexes = client.Query(uri, "SELECT name FROM system:keyspaces"); + foreach (var row in indexes.Rows) + { + if (row.name == "beer-sample") + { + client.Query(uri, "DROP PRIMARY INDEX ON `beer-sample`"); + } + } + const string query = "CREATE PRIMARY INDEX ON `beer-sample`"; + + var result = client.Query(uri, query); + Assert.IsNotNull(result); + Assert.IsTrue(result.Success); + Assert.IsNotNull(result.Rows); + } + + [Test] + public void Test_Query_HelloWorld() + { + var config = new ClientConfiguration(); + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var uri = new Uri(string.Format("http://{0}:8093/query", _server)); + const string query = "SELECT 'Hello World' AS Greeting"; + + var result = client.Query(uri, query); + Assert.IsNotNull(result); + Assert.AreEqual("Hello World", result.Rows.First().Greeting.ToString()); + } + + [Test] + public void Test_Query_Incorrect_Syntax() + { + var config = new ClientConfiguration(); + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var uri = new Uri(string.Format("http://{0}:8093/query", _server)); + const string query = "SELECT 'Hello World' ASB Greeting"; + + var result = client.Query(uri, query); + Assert.IsNotNull(result); + Assert.IsFalse(result.Success); + Assert.IsEmpty(result.Rows); + } + + [Test] + public void Test_Query_Select_Where_Type_Is_Beer_As_Poco() + { + var config = new ClientConfiguration(); + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var uri = new Uri(string.Format("http://{0}:8093/query", _server)); + const string query = "SELECT abv, brewery_id, category, description, ibu, name, srm, style, type, upc, updated " + + "FROM `beer-sample` as beer " + + "WHERE beer.type='beer' LIMIT 10"; + + var result = client.Query(uri, query); + Assert.IsNotNull(result); + Assert.IsTrue(result.Success); + Assert.IsNotNull(result.Rows); + + var beer = result.Rows.First(); + Assert.IsNotNullOrEmpty(beer.Name); + } + + [Test] + public void Test_Query_Select_All() + { + var config = new ClientConfiguration(); + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var uri = new Uri(string.Format("http://{0}:8093/query", _server)); + const string query = "SELECT * FROM `beer-sample` as d LIMIT 10"; + + var result = client.Query(uri, query); + Assert.IsNotNull(result); + Assert.IsTrue(result.Success); + Assert.IsNotNull(result.Rows); + } + + [Test] + public void Test_Query_Select_All_Where_Type_Is_Beer() + { + var config = new ClientConfiguration(); + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var uri = new Uri(string.Format("http://{0}:8093/query", _server)); + const string query = "SELECT type, meta FROM `beer-sample` as d WHERE d.type='beer' LIMIT 10"; + + var result = client.Query(uri, query); + Assert.IsNotNull(result); + Assert.IsTrue(result.Success); + Assert.IsNotNull(result.Rows); + } + + [Test] + public void Test_Query_POST_Positional_Parameters() + { + var config = new ClientConfiguration(); + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var request = QueryRequest.Create("SELECT * from `beer-sample` WHERE type=$1 LIMIT 10"). + BaseUri(new Uri(string.Format("http://{0}:8093/query", _server))). + Pretty(false). + AddPositionalParameter("beer"). + HttpMethod(Method.Post); + + var result = client.Query(request); + Assert.AreEqual(QueryStatus.Success, result.Status); + Assert.AreEqual(10, result.Rows.Count); + foreach (var row in result.Rows) + { + Console.WriteLine(row); + } + } + + [Test] + public void Test_Query_POST_Named_Parameters() + { + var config = new ClientConfiguration(); + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var request = QueryRequest.Create("SELECT * from `beer-sample` WHERE type=$type LIMIT 10"). + BaseUri(new Uri(string.Format("http://{0}:8093/query", _server))). + Pretty(false). + AddNamedParameter("type", "beer"). + HttpMethod(Method.Post); + + var result = client.Query(request); + Assert.AreEqual(QueryStatus.Success, result.Status); + Assert.AreEqual(10, result.Rows.Count); + foreach (var row in result.Rows) + { + Console.WriteLine(row); + } + } + + [Test] + public void Test_Query_GET_Positional_Parameters() + { + var config = new ClientConfiguration(); + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var request = QueryRequest.Create("SELECT * from `beer-sample` WHERE type=$1 LIMIT 10"). + BaseUri(new Uri(string.Format("http://{0}:8093/query", _server))). + Pretty(false). + AddPositionalParameter("beer"). + HttpMethod(Method.Get); + + var result = client.Query(request); + Assert.AreEqual(QueryStatus.Success, result.Status); + Assert.AreEqual(10, result.Rows.Count); + foreach (var row in result.Rows) + { + Console.WriteLine(row); + } + } + + [Test] + public void Test_Query_GET_Named_Parameters() + { + var config = new ClientConfiguration(); + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var request = QueryRequest.Create("SELECT * from `beer-sample` WHERE type=$type LIMIT 10"). + BaseUri(new Uri(string.Format("http://{0}:8093/query", _server))). + Pretty(false). + AddNamedParameter("type", "beer"). + HttpMethod(Method.Get); + + var result = client.Query(request); + Assert.AreEqual(QueryStatus.Success, result.Status); + Assert.AreEqual(10, result.Rows.Count); + foreach (var row in result.Rows) + { + Console.WriteLine(row); + } + } + + [Test] + public async void Test_QueryAsync_POST_Named_Parameters() + { + var config = new ClientConfiguration(); + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var request = QueryRequest.Create("SELECT * from `beer-sample` WHERE type=$type LIMIT 10"). + BaseUri(new Uri(string.Format("http://{0}:8093/query", _server))). + Pretty(false). + AddNamedParameter("type", "beer"). + HttpMethod(Method.Post); + + var result = await client.QueryAsync(request); + Assert.AreEqual(QueryStatus.Success, result.Status); + Assert.AreEqual(10, result.Rows.Count); + foreach (var row in result.Rows) + { + Console.WriteLine(row); + } + } + + [Test] + public async void Test_QueryAsync_GET_Positional_Parameters() + { + var config = new ClientConfiguration(); + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var request = QueryRequest.Create("SELECT * from `beer-sample` WHERE type=$1 LIMIT 10"). + BaseUri(new Uri(string.Format("http://{0}:8093/query", _server))). + Pretty(false). + AddPositionalParameter("beer"). + HttpMethod(Method.Get); + + var result = await client.QueryAsync(request); + Assert.AreEqual(QueryStatus.Success, result.Status); + Assert.AreEqual(10, result.Rows.Count); + foreach (var row in result.Rows) + { + Console.WriteLine(row); + } + } + + [Test] + public async void Test_QueryAsync_GET_Named_Parameters() + { + var config = new ClientConfiguration(); + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var request = QueryRequest.Create("SELECT * from `beer-sample` WHERE type=$type LIMIT 10"). + BaseUri(new Uri(string.Format("http://{0}:8093/query", _server))). + Pretty(false). + AddNamedParameter("type", "beer"). + HttpMethod(Method.Get); + + var result = await client.QueryAsync(request); + Assert.AreEqual(QueryStatus.Success, result.Status); + Assert.AreEqual(10, result.Rows.Count); + foreach (var row in result.Rows) + { + Console.WriteLine(row); + } + } + + [Test] + public void When_Prepared_Is_True_Client_Uses_Prepared_Statement() + { + var config = new ClientConfiguration(); + var serverUri = new Uri(string.Format("http://{0}:8093/query", _server)); + const string statement = "SELECT * from `beer-sample` LIMIT 100"; + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var normalRequest = QueryRequest.Create(statement). + BaseUri(serverUri). + Pretty(false); + var preparedRequest = QueryRequest.Create(). //will set the plan later + BaseUri(serverUri). + Pretty(false); + + var stopWatch = new Stopwatch(); + stopWatch.Start(); + var resultNormal = client.Query(normalRequest); + stopWatch.Stop(); + Console.WriteLine("Elasped time normal request:{0}", stopWatch.ElapsedMilliseconds); + + stopWatch = new Stopwatch(); + stopWatch.Restart(); + var plan = client.Prepare(serverUri, statement).Rows.First(); + preparedRequest.Prepared(plan). + BaseUri(serverUri). + Pretty(false); + var resultPrepareExecute = client.Query(preparedRequest); + stopWatch.Stop(); + Console.WriteLine("Elasped time prepare statement + execute 1:{0}", stopWatch.ElapsedMilliseconds); + + stopWatch = new Stopwatch(); + stopWatch.Restart(); + var resultExecute = client.Query(preparedRequest); + stopWatch.Stop(); + Console.WriteLine("Elasped time execute 2:{0}", stopWatch.ElapsedMilliseconds); + + Assert.IsTrue(preparedRequest.IsPrepared); + Assert.IsFalse(normalRequest.IsPrepared); + Assert.AreEqual(QueryStatus.Success, resultNormal.Status); + Assert.AreEqual(QueryStatus.Success, resultPrepareExecute.Status); + Assert.AreEqual(QueryStatus.Success, resultExecute.Status); + } + + [Test] + public void When_Prepared_Is_False_Client_Doesnt_Cache() + { + var config = new ClientConfiguration(); + var client = new QueryClient(new HttpClient(), new JsonDataMapper(config), config); + var request = QueryRequest.Create("SELECT * from `beer-sample` LIMIT 100"). + BaseUri(new Uri(string.Format("http://{0}:8093/query", _server))). + Pretty(false); + + var stopWatch = new Stopwatch(); + stopWatch.Start(); + var result = client.Query(request); + stopWatch.Stop(); + Console.WriteLine("Elasped time 1:{0}", stopWatch.ElapsedMilliseconds); + + stopWatch = new Stopwatch(); + stopWatch.Restart(); + result = client.Query(request); + stopWatch.Stop(); + Console.WriteLine("Elasped time 2:{0}", stopWatch.ElapsedMilliseconds); + + stopWatch = new Stopwatch(); + stopWatch.Restart(); + result = client.Query(request); + stopWatch.Stop(); + Console.WriteLine("Elasped time 3:{0}", stopWatch.ElapsedMilliseconds); + Assert.AreEqual(QueryStatus.Success, result.Status); + } + } +} + +#region [ License information ] + +/* ************************************************************ + * + * @author Couchbase + * @copyright 2014 Couchbase, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ************************************************************/ + +#endregion +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of System.Net.Http.HttpClient::.ctor() at Line 107) of type System.Net.Http.HttpClient in method "Void QueryClientTests.Test_Query_Select_All_Where_Type_Is_Beer()". + +### Severity: +ERROR + +### Procedure: +Void QueryClientTests.Test_Query_Select_All_Where_Type_Is_Beer() + +### File: +Src/Couchbase.Tests/N1QL/QueryClientTests.cs + +### Key: +QueryClientTests.cs|Test_Query_Select_All_Where_Type_Is_Beer|DOTNET_RESOURCE_LEAK + +### Hash: +df926b7054334ba13a976dc55f96cef2 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2831/instruction.md b/inferredbugs-2831/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..83db88ef61527c6e5ebc60936d3237ab2b141cd7 --- /dev/null +++ b/inferredbugs-2831/instruction.md @@ -0,0 +1,115 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** couchbase-net-client +**Bug ID:** 13 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Couchbase.Authentication.SASL; +using Couchbase.Configuration.Client; +using Couchbase.Configuration.Server.Serialization; +using Couchbase.Core; +using Couchbase.IO; +using Couchbase.IO.Strategies.Async; +using Couchbase.IO.Strategies.Awaitable; + +namespace Couchbase.Tests.Helpers +{ + public static class ObjectFactory + { + internal static IOStrategy CreateIOStrategy(string server) + { + var connectionPool = new DefaultConnectionPool(new PoolConfiguration(), Server.GetEndPoint(server)); + var ioStrategy = new SocketAsyncStrategy(connectionPool); + return ioStrategy; + } + + internal static IOStrategy CreateIOStrategy(Node node) + { + var server = node.Hostname.Replace("8091", node.Ports.Direct.ToString()); + var connectionPool = new DefaultConnectionPool(new PoolConfiguration(), Server.GetEndPoint(server)); + var ioStrategy = new SocketAsyncStrategy(connectionPool); + return ioStrategy; + } + } +} + +#region [ License information ] + +/* ************************************************************ + * + * @author Couchbase + * @copyright 2014 Couchbase, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ************************************************************/ + +#endregion + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type Couchbase.IO.Strategies.Async.SocketAsyncStrategy, Leaked resource connectionPool of type Couchbase.IO.DefaultConnectionPool in method "IOStrategy ObjectFactory.CreateIOStrategy(String)". + +### Severity: +ERROR + +### Procedure: +IOStrategy ObjectFactory.CreateIOStrategy(String) + +### File: +Src/Couchbase.Tests/Helpers/ObjectFactory.cs + +### Key: +ObjectFactory.cs|CreateIOStrategy|DOTNET_RESOURCE_LEAK + +### Hash: +109d0ca7ab1aa2ac9d3639a15a27be55 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2838/instruction.md b/inferredbugs-2838/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..36c9e093de51db8b0522de80f95b1561bd8f5cc3 --- /dev/null +++ b/inferredbugs-2838/instruction.md @@ -0,0 +1,241 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** UniTask +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +using System; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public static class CancellationTokenExtensions + { + static readonly Action cancellationTokenCallback = Callback; + static readonly Action disposeCallback = DisposeCallback; + + public static CancellationToken ToCancellationToken(this UniTask task) + { + var cts = new CancellationTokenSource(); + ToCancellationTokenCore(task, cts).Forget(); + return cts.Token; + } + + public static CancellationToken ToCancellationToken(this UniTask task, CancellationToken linkToken) + { + if (linkToken.IsCancellationRequested) + { + return linkToken; + } + + if (!linkToken.CanBeCanceled) + { + return ToCancellationToken(task); + } + + var cts = new CancellationTokenSource(); + ToCancellationTokenCore(task, cts).Forget(); + + return CancellationTokenSource.CreateLinkedTokenSource(cts.Token, linkToken).Token; + } + + public static CancellationToken ToCancellationToken(this UniTask task) + { + return ToCancellationToken(task.AsUniTask()); + } + + public static CancellationToken ToCancellationToken(this UniTask task, CancellationToken linkToken) + { + return ToCancellationToken(task.AsUniTask(), linkToken); + } + + static async UniTaskVoid ToCancellationTokenCore(UniTask task, CancellationTokenSource cts) + { + try + { + await task; + } + catch (Exception ex) + { + UniTaskScheduler.PublishUnobservedTaskException(ex); + } + cts.Cancel(); + cts.Dispose(); + } + + public static (UniTask, CancellationTokenRegistration) ToUniTask(this CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return (UniTask.FromCanceled(cancellationToken), default(CancellationTokenRegistration)); + } + + var promise = new UniTaskCompletionSource(); + return (promise.Task, cancellationToken.RegisterWithoutCaptureExecutionContext(cancellationTokenCallback, promise)); + } + + static void Callback(object state) + { + var promise = (UniTaskCompletionSource)state; + promise.TrySetResult(); + } + + public static CancellationTokenAwaitable WaitUntilCanceled(this CancellationToken cancellationToken) + { + return new CancellationTokenAwaitable(cancellationToken); + } + + public static CancellationTokenRegistration RegisterWithoutCaptureExecutionContext(this CancellationToken cancellationToken, Action callback) + { + var restoreFlow = false; + if (!ExecutionContext.IsFlowSuppressed()) + { + ExecutionContext.SuppressFlow(); + restoreFlow = true; + } + + try + { + return cancellationToken.Register(callback, false); + } + finally + { + if (restoreFlow) + { + ExecutionContext.RestoreFlow(); + } + } + } + + public static CancellationTokenRegistration RegisterWithoutCaptureExecutionContext(this CancellationToken cancellationToken, Action callback, object state) + { + var restoreFlow = false; + if (!ExecutionContext.IsFlowSuppressed()) + { + ExecutionContext.SuppressFlow(); + restoreFlow = true; + } + + try + { + return cancellationToken.Register(callback, state, false); + } + finally + { + if (restoreFlow) + { + ExecutionContext.RestoreFlow(); + } + } + } + + public static CancellationTokenRegistration AddTo(this IDisposable disposable, CancellationToken cancellationToken) + { + return cancellationToken.RegisterWithoutCaptureExecutionContext(disposeCallback, disposable); + } + + static void DisposeCallback(object state) + { + var d = (IDisposable)state; + d.Dispose(); + } + } + + public struct CancellationTokenAwaitable + { + CancellationToken cancellationToken; + + public CancellationTokenAwaitable(CancellationToken cancellationToken) + { + this.cancellationToken = cancellationToken; + } + + public Awaiter GetAwaiter() + { + return new Awaiter(cancellationToken); + } + + public struct Awaiter : ICriticalNotifyCompletion + { + CancellationToken cancellationToken; + + public Awaiter(CancellationToken cancellationToken) + { + this.cancellationToken = cancellationToken; + } + + public bool IsCompleted => !cancellationToken.CanBeCanceled || cancellationToken.IsCancellationRequested; + + public void GetResult() + { + } + + public void OnCompleted(Action continuation) + { + UnsafeOnCompleted(continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + cancellationToken.RegisterWithoutCaptureExecutionContext(continuation); + } + } + } +} + + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource cts of type System.Threading.CancellationTokenSource in method "CancellationToken CancellationTokenExtensions.ToCancellationToken(UniTask,CancellationToken)". + +### Severity: +ERROR + +### Procedure: +CancellationToken CancellationTokenExtensions.ToCancellationToken(UniTask,CancellationToken) + +### File: +src/UniTask/Assets/Plugins/UniTask/Runtime/CancellationTokenExtensions.cs + +### Key: +CancellationTokenExtensions.cs|ToCancellationToken|DOTNET_RESOURCE_LEAK + +### Hash: +0b8e2a79c06cc343404b9889cacfe7a6 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2852/instruction.md b/inferredbugs-2852/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dde7abd485b40fb498825dfb43a40a35e0c85566 --- /dev/null +++ b/inferredbugs-2852/instruction.md @@ -0,0 +1,1624 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** P +**Bug ID:** 24 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using Microsoft.Pc.Backend.ASTExt; +using Microsoft.Pc.TypeChecker; +using Microsoft.Pc.TypeChecker.AST; +using Microsoft.Pc.TypeChecker.AST.Declarations; +using Microsoft.Pc.TypeChecker.AST.Expressions; +using Microsoft.Pc.TypeChecker.AST.Statements; +using Microsoft.Pc.TypeChecker.AST.States; +using Microsoft.Pc.TypeChecker.Types; + +namespace Microsoft.Pc.Backend.Prt +{ + public class PrtCodeGenerator : ICodeGenerator + { + public IEnumerable GenerateCode(ICompilationJob job, Scope globalScope) + { + return PrtCodeGeneratorImpl.GenerateCode(job, globalScope); + } + } + + internal class PrtCodeGeneratorImpl + { + private readonly CompilationContext context; + + private PrtCodeGeneratorImpl(CompilationContext context) + { + this.context = context; + } + + public static IEnumerable GenerateCode(ICompilationJob job, Scope globalScope) + { + var context = new CompilationContext(job); + var generator = new PrtCodeGeneratorImpl(context); + CompiledFile cHeader = generator.GenerateHeaderFile(globalScope); + CompiledFile cSource = generator.GenerateSourceFile(globalScope); + return new List {cHeader, cSource}; + } + + private const string FunCallArgsArrayName = "_P_GEN_funargs"; + private const string FunCallRetValName = "_P_GEN_funval"; + private const string FunResultValName = "_P_GEN_retval"; + private const string FunNullStaticName = "_P_GEN_null"; + + #region Top-level generation methods + + private CompiledFile GenerateHeaderFile(Scope globalScope) + { + var cHeader = new CompiledFile(context.HeaderFileName); + + WriteHeaderPrologue(cHeader.Stream); + foreach (IPDecl decl in globalScope.AllDecls) + { + WriteExternDeclaration(cHeader.Stream, decl); + } + + WriteHeaderEpilogue(cHeader.Stream); + return cHeader; + } + + private CompiledFile GenerateSourceFile(Scope globalScope) + { + var cSource = new CompiledFile(context.SourceFileName); + // Write includes and common macros, if any + WriteSourcePrologue(cSource.Stream); + + // Write the machine and function bodies into temporary buffer + var bodyWriter = new StringWriter(); + foreach (IPDecl decl in globalScope.AllDecls) + { + WriteSourceDecl(bodyWriter, decl); + } + + // Write all the type definitions and function implementation prototypes + context.WriteLine(cSource.Stream, "// Type universe for program:"); + foreach (PLanguageType type in context.UsedTypes.ToArray()) + { + WriteTypeDefinition(cSource.Stream, type); + } + + context.WriteLine(cSource.Stream); + + context.WriteLine(cSource.Stream, "// Function implementation prototypes:"); + foreach (Function function in globalScope.GetAllMethods()) + { + string functionName = context.Names.GetNameForFunctionImpl(function); + context.WriteLine(cSource.Stream, + $"PRT_VALUE* {functionName}(PRT_MACHINEINST* context, PRT_VALUE*** argRefs);"); + if (!function.IsForeign) + { + context.WriteLine(cSource.Stream, $"extern PRT_FUNDECL {context.Names.GetNameForDecl(function)};"); + } + + context.WriteLine(cSource.Stream); + } + + context.WriteLine(cSource.Stream); + + // Append all the function bodies and declaration structs (which have forward declarations in the header) + cSource.Stream.GetStringBuilder().Append(bodyWriter); + + // Finally, write the overall program decl + WriteProgramDecl(cSource.Stream, globalScope); + return cSource; + } + + #endregion + + #region Declaration level methods + + private void WriteSourcePrologue(TextWriter output) + { + context.WriteLine(output, $"#include \"{context.HeaderFileName}\""); + context.WriteLine(output); + } + + private void WriteSourceDecl(TextWriter output, IPDecl decl) + { + string declName = context.Names.GetNameForDecl(decl); + var declLocation = context.LocationResolver.GetLocation(decl); + switch (decl) + { + case EnumElem _: + // Member of a type. Instantitated by usage. + return; + case PEnum _: + // Declares a type. Instantitated by usage. + return; + case Function function: + if (!function.IsForeign) + { + WriteNormalFunction(output, function); + } + + break; + case Implementation _: + // does not produce a struct definition - aside from ProgramDecl + return; + case Interface @interface: + string ifaceRecvSetName; + if (@interface.ReceivableEvents is NamedEventSet set) + { + ifaceRecvSetName = context.Names.GetNameForDecl(set); + } + else + { + var interfaceEventSet = new NamedEventSet(@interface.Name + "_RECV", @interface.SourceLocation); + interfaceEventSet.AddEvents(@interface.ReceivableEvents.Events); + WriteSourceDecl(output, interfaceEventSet); + ifaceRecvSetName = context.Names.GetNameForDecl(interfaceEventSet); + } + + context.WriteLine(output, $"#line {declLocation.Line} \"{declLocation.File.Name}\""); + context.WriteLine(output, $"PRT_INTERFACEDECL {declName} ="); + context.WriteLine(output, "{"); + context.WriteLine(output, $"{context.GetDeclNumber(@interface)}U,"); + context.WriteLine(output, $"\"{@interface.Name}\","); + context.WriteLine(output, $"&{context.Names.GetNameForType(@interface.PayloadType)},"); + context.WriteLine(output, $"&{ifaceRecvSetName}"); + context.WriteLine(output, "};"); + break; + case Machine machine: + var machineFields = machine.Fields.ToList(); + var fieldArrayName = "NULL"; + if (machineFields.Any()) + { + fieldArrayName = context.Names.GetTemporaryName($"{machine.Name}_VARS"); + context.WriteLine(output, $"PRT_VARDECL {fieldArrayName}[] = {{"); + for (var i = 0; i < machineFields.Count; i++) + { + Variable field = machineFields[i]; + string sep = i == machineFields.Count - 1 ? "" : ","; + context.WriteLine(output, + $"{{ \"{field.Name}\", &{context.Names.GetNameForType(field.Type)} }}{sep}"); + } + + context.WriteLine(output, "};"); + context.WriteLine(output); + } + + var machineStates = machine.AllStates().ToList(); + var machineStatesInOrder = new State[machineStates.Count]; + foreach (State state in machineStates) + { + WriteSourceDecl(output, state); + machineStatesInOrder[context.GetDeclNumber(state)] = state; + } + + string stateArrayName = context.Names.GetTemporaryName($"{machine.Name}_STATES"); + string stateArrayBody = + string.Join(", ", machineStatesInOrder.Select(st => context.Names.GetNameForDecl(st))); + context.WriteLine(output, $"PRT_STATEDECL {stateArrayName}[] = {{ {stateArrayBody} }};"); + context.WriteLine(output); + + var machineMethods = machine.Methods.ToList(); + foreach (Function machineMethod in machineMethods) + { + WriteSourceDecl(output, machineMethod); + } + + var methodArrayName = "NULL"; + if (machineMethods.Any()) + { + methodArrayName = context.Names.GetTemporaryName($"{machine.Name}_METHODS"); + string methodArrayBody = + string.Join(", ", machineMethods.Select(m => $"&{context.Names.GetNameForDecl(m)}")); + context.WriteLine(output, $"PRT_FUNDECL* {methodArrayName}[] = {{ {methodArrayBody} }};"); + context.WriteLine(output); + } + + string machineRecvSetName = GetReceivesNameOrMkTemp(output, machine); + string machineSendSetName = GetSendsNameOrMkTemp(output, machine); + var machineCreatesName = "NULL"; + if (machine.Creates.Interfaces.Any()) + { + var createsInterfaces = machine.Creates.Interfaces.ToList(); + machineCreatesName = context.Names.GetTemporaryName($"{machine.Name}_CREATES"); + string createsArrayName = context.Names.GetTemporaryName($"{machine.Name}_CREATES_ARR"); + string createsArrayBody = string.Join(", ", createsInterfaces.Select(context.GetDeclNumber)); + context.WriteLine(output, $"PRT_UINT32 {createsArrayName}[] = {{ {createsArrayBody} }};"); + context.WriteLine( + output, + $"PRT_INTERFACESETDECL {machineCreatesName} = {{ {createsInterfaces.Count}, {createsArrayName} }};"); + machineCreatesName = "&" + machineCreatesName; + } + + uint maxQueueSize = machine.Assert ?? uint.MaxValue; + context.WriteLine(output, $"#line {declLocation.Line} \"{declLocation.File.Name}\""); + context.WriteLine(output, $"PRT_MACHINEDECL {declName} = "); + context.WriteLine(output, "{"); + context.WriteLine(output, $"{context.GetDeclNumber(machine)}U,"); + context.WriteLine(output, $"\"{machine.Name}\","); + context.WriteLine(output, $"&{machineRecvSetName},"); + context.WriteLine(output, $"&{machineSendSetName},"); + context.WriteLine(output, $"{machineCreatesName},"); + context.WriteLine(output, $"{machineFields.Count}U,"); + context.WriteLine(output, $"{machineStatesInOrder.Length}U,"); + context.WriteLine(output, $"{machineMethods.Count}U,"); + context.WriteLine(output, $"{maxQueueSize}U,"); + context.WriteLine(output, $"{context.GetDeclNumber(machine.StartState)}U,"); + context.WriteLine(output, $"{fieldArrayName},"); + context.WriteLine(output, $"{stateArrayName},"); + context.WriteLine(output, $"{methodArrayName}"); + context.WriteLine(output, "};"); + + break; + case NamedEventSet namedEventSet: + string innerSetName = context.Names.GetTemporaryName(namedEventSet.Name + "_INNER"); + var eventDeclNames = namedEventSet.Events.Select(x => "&" + context.Names.GetNameForDecl(x)) + .ToList(); + string eventDeclArrBody = string.Join(", ", eventDeclNames); + eventDeclArrBody = string.IsNullOrEmpty(eventDeclArrBody) ? "NULL" : eventDeclArrBody; + context.WriteLine(output, $"#line {declLocation.Line} \"{declLocation.File.Name}\""); + context.WriteLine(output, $"PRT_EVENTDECL* {innerSetName}[] = {{ {eventDeclArrBody} }};"); + context.WriteLine(output, $"PRT_EVENTSETDECL {declName} ="); + context.WriteLine(output, "{"); + context.WriteLine(output, $"{eventDeclNames.Count}U,"); + context.WriteLine(output, $"{innerSetName},"); + context.WriteLine(output, "NULL"); + context.WriteLine(output, "};"); + break; + case NamedModule _: + // does not produce a struct definition + return; + case PEvent pEvent when pEvent.IsBuiltIn: + return; + case PEvent pEvent when !pEvent.IsBuiltIn: + long eventBound = Math.Min(pEvent.Assert == -1 ? uint.MaxValue : (uint) pEvent.Assert, + pEvent.Assume == -1 ? uint.MaxValue : (uint) pEvent.Assume); + + context.WriteLine(output, $"#line {declLocation.Line} \"{declLocation.File.Name}\""); + context.WriteLine(output, $"PRT_EVENTDECL {declName} = "); + context.WriteLine(output, "{"); + context.WriteLine(output, "{ PRT_VALUE_KIND_EVENT, 0U },"); + context.WriteLine(output, $"\"{pEvent.Name}\","); + context.WriteLine(output, $"{eventBound}U,"); + context.WriteLine(output, $"&{context.Names.GetNameForType(pEvent.PayloadType)}"); + context.WriteLine(output, "};"); + break; + case RefinementTest _: + // does not produce a struct definition + return; + case SafetyTest _: + // does not produce a struct definition + return; + case TypeDef typeDef: + context.WriteLine(output, $"#line {declLocation.Line} \"{declLocation.File.Name}\""); + context.WriteLine(output, $"PRT_TYPE* {declName} = &{context.Names.GetNameForType(typeDef.Type)};"); + return; + case Variable _: + // does not produce a struct definition + // handled by MachineDecl. + return; + case State state: + string stateEntryFunName = state.Entry == null + ? "&_P_NO_OP" + : $"&{context.Names.GetNameForDecl(state.Entry)}"; + string stateExitFunName = + state.Exit == null ? "&_P_NO_OP" : $"&{context.Names.GetNameForDecl(state.Exit)}"; + + int stateIndex = context.GetDeclNumber(state); + PrtTranslationUtils.StateActionResults stateData = + PrtTranslationUtils.BuildActionSets(context, state); + + WriteSourceDecl(output, stateData.DefersSet); + WriteSourceDecl(output, stateData.TransSet); + WriteSourceDecl(output, stateData.DosSet); + + var transArrName = "NULL"; + if (stateData.Trans.Count != 0) + { + transArrName = context.Names.GetTemporaryName("TRANS"); + context.WriteLine(output, $"PRT_TRANSDECL {transArrName}[] ="); + context.WriteLine(output, "{"); + for (var i = 0; i < stateData.Trans.Count; i++) + { + (PEvent triggerEvent, int destIndex, string transFunRef) = stateData.Trans[i]; + string triggerName = context.Names.GetNameForDecl(triggerEvent); + string comma = i == stateData.Trans.Count - 1 ? "" : ","; + context.WriteLine(output, + $"{{ {stateIndex}, &{triggerName}, {destIndex}, {transFunRef} }}{comma}"); + } + + context.WriteLine(output, "};"); + context.WriteLine(output); + } + + + var dosArrName = "NULL"; + if (stateData.Dos.Count != 0) + { + dosArrName = context.Names.GetTemporaryName("DOS"); + context.WriteLine(output, $"PRT_DODECL {dosArrName}[] ="); + context.WriteLine(output, "{"); + for (var i = 0; i < stateData.Dos.Count; i++) + { + (PEvent triggerEvent, Function doFun) = stateData.Dos[i]; + string triggerName = context.Names.GetNameForDecl(triggerEvent); + string comma = i == stateData.Dos.Count - 1 ? "" : ","; + string funName = doFun != null ? $"&{context.Names.GetNameForDecl(doFun)}" : "NULL"; + context.WriteLine(output, $"{{ {stateIndex}, &{triggerName}, {funName} }}{comma}"); + } + + context.WriteLine(output, "};"); + context.WriteLine(output); + } + + context.WriteLine(output, $"#line {declLocation.Line} \"{declLocation.File.Name}\""); + context.WriteLine(output, $"#define {declName} \\"); + context.WriteLine(output, "{ \\"); + context.WriteLine(output, $"\"{state.QualifiedName}\", \\"); + context.WriteLine(output, $"{stateData.Trans.Count}U, \\"); + context.WriteLine(output, $"{stateData.Dos.Count}U, \\"); + context.WriteLine(output, $"&{context.Names.GetNameForDecl(stateData.DefersSet)}, \\"); + context.WriteLine(output, $"&{context.Names.GetNameForDecl(stateData.TransSet)}, \\"); + context.WriteLine(output, $"&{context.Names.GetNameForDecl(stateData.DosSet)}, \\"); + context.WriteLine(output, $"{transArrName}, \\"); + context.WriteLine(output, $"{dosArrName}, \\"); + context.WriteLine(output, $"{stateEntryFunName}, \\"); + context.WriteLine(output, $"{stateExitFunName}, \\"); + context.WriteLine(output, "}"); + break; + case StateGroup stateGroup: + foreach (State state in stateGroup.States) + { + WriteSourceDecl(output, state); + } + + foreach (StateGroup subGroup in stateGroup.Groups) + { + WriteSourceDecl(output, subGroup); + } + + break; + } + + context.WriteLine(output); + } + + private void WriteNormalFunction(TextWriter output, Function function) + { + string declName = context.Names.GetNameForDecl(function); + var declLocation = context.LocationResolver.GetLocation(function); + + string functionImplName = context.Names.GetNameForFunctionImpl(function); + bool isAnon = string.IsNullOrEmpty(function.Name); + string functionName = isAnon ? "NULL" : $"\"{function.Name}\""; + var signature = function.Signature.ParameterTypes.ToList(); + Debug.Assert((isAnon && signature.Count <= 1) || !isAnon); + string payloadType = isAnon && signature.Count == 1 + ? $"&{context.Names.GetNameForType(signature[0])}" + : "NULL"; + + context.WriteLine(output, $"#line {declLocation.Line} \"{declLocation.File.Name}\""); + context.WriteLine(output, $"PRT_VALUE* {functionImplName}(PRT_MACHINEINST* context, PRT_VALUE*** argRefs)"); + context.WriteLine(output, "{"); + WriteFunctionBody(output, function); + context.WriteLine(output, "}"); + context.WriteLine(output); + context.WriteLine(output, $"PRT_FUNDECL {declName} ="); + context.WriteLine(output, "{"); + context.WriteLine(output, $"{functionName},"); // name of function in original program, NULL if anon + context.WriteLine(output, $"&{functionImplName},"); // pointer to implementation + context.WriteLine(output, $"{payloadType}"); // payload type for anonymous functions + context.WriteLine(output, "};"); + context.WriteLine(output); + } + + private string WriteTypeDefinition(TextWriter output, PLanguageType type) + { + type = type.Canonicalize(); + + string typeGenName = context.Names.GetNameForType(type); + + if (context.WrittenTypes.Contains(type)) + { + return typeGenName; + } + + switch (type) + { + case BoundedType boundedType: + context.WriteLine(output, $"// TODO: implement types like {boundedType.CanonicalRepresentation}"); + break; + case EnumType _: + context.WriteLine(output, $"static PRT_TYPE {typeGenName} = {{ PRT_KIND_INT, {{ NULL }} }};"); + break; + case ForeignType foreignType: + string foreignTypeName = foreignType.CanonicalRepresentation; + + context.WriteLine(output, $"extern PRT_UINT64 PRT_FOREIGN_MKDEF_{foreignTypeName}_IMPL(void);"); + context.WriteLine(output, + $"extern PRT_UINT64 PRT_FOREIGN_CLONE_{foreignTypeName}_IMPL(PRT_UINT64);"); + context.WriteLine(output, $"extern void PRT_FOREIGN_FREE_{foreignTypeName}_IMPL(PRT_UINT64);"); + context.WriteLine(output, + $"extern PRT_UINT32 PRT_FOREIGN_GETHASHCODE_{foreignTypeName}_IMPL(PRT_UINT64);"); + context.WriteLine(output, + $"extern PRT_BOOLEAN PRT_FOREIGN_ISEQUAL_{foreignTypeName}_IMPL(PRT_UINT64, PRT_UINT64);"); + context.WriteLine(output, + $"extern PRT_STRING PRT_FOREIGN_TOSTRING_{foreignTypeName}_IMPL(PRT_UINT64);"); + + string foreignTypeDeclName = context.Names.GetNameForForeignTypeDecl(foreignType); + context.WriteLine(output, $"static PRT_FOREIGNTYPEDECL {foreignTypeDeclName} = {{"); + context.WriteLine(output, "0U,"); + context.WriteLine(output, $"\"{foreignTypeName}\","); + context.WriteLine(output, $"PRT_FOREIGN_MKDEF_{foreignTypeName}_IMPL,"); + context.WriteLine(output, $"PRT_FOREIGN_CLONE_{foreignTypeName}_IMPL,"); + context.WriteLine(output, $"PRT_FOREIGN_FREE_{foreignTypeName}_IMPL,"); + context.WriteLine(output, $"PRT_FOREIGN_GETHASHCODE_{foreignTypeName}_IMPL,"); + context.WriteLine(output, $"PRT_FOREIGN_ISEQUAL_{foreignTypeName}_IMPL,"); + context.WriteLine(output, $"PRT_FOREIGN_TOSTRING_{foreignTypeName}_IMPL,"); + context.WriteLine(output, "};"); + context.WriteLine(output, + $"PRT_TYPE {typeGenName} = {{ PRT_KIND_FOREIGN, {{ .foreignType = &{foreignTypeDeclName} }} }};"); + break; + case MapType mapType: + string mapKeyTypeName = WriteTypeDefinition(output, mapType.KeyType); + string mapValueTypeName = WriteTypeDefinition(output, mapType.ValueType); + string mapTypeDeclName = context.Names.GetTemporaryName("MAPTYPE"); + context.WriteLine(output, + $"static PRT_MAPTYPE {mapTypeDeclName} = {{ &{mapKeyTypeName}, &{mapValueTypeName} }};"); + context.WriteLine(output, + $"static PRT_TYPE {typeGenName} = {{ PRT_KIND_MAP, {{ .map = &{mapTypeDeclName} }} }};"); + break; + case NamedTupleType namedTupleType: + string ntNamesArrayName = context.Names.GetTemporaryName("NMDTUP_N"); + string ntTypesArrayName = context.Names.GetTemporaryName("NMDTUP_T"); + string ntStructName = context.Names.GetTemporaryName("NMDTUP"); + var typeDeclNames = namedTupleType.Types.Select(t => WriteTypeDefinition(output, t)); + context.WriteLine( + output, + $"static PRT_STRING {ntNamesArrayName}[] = {{ {string.Join(", ", namedTupleType.Names.Select(name => "\"" + name + "\""))} }};"); + context.WriteLine( + output, + $"static PRT_TYPE* {ntTypesArrayName}[] = {{ {string.Join(", ", typeDeclNames.Select(name => "&" + name))} }};"); + context.WriteLine( + output, + $"static PRT_NMDTUPTYPE {ntStructName} = {{ {namedTupleType.Types.Count}U, {ntNamesArrayName}, {ntTypesArrayName} }};"); + context.WriteLine(output, + $"static PRT_TYPE {typeGenName} = {{ PRT_KIND_NMDTUP, {{ .nmTuple = &{ntStructName} }} }};"); + break; + case PermissionType _: + // TODO: implement full permission types in runtime + context.WriteLine(output, "// TODO: implement full permission types in runtime"); + context.WriteLine(output, $"static PRT_TYPE {typeGenName} = {{ PRT_KIND_MACHINE, {{ NULL }} }};"); + break; + case PrimitiveType primitiveType when Equals(primitiveType, PrimitiveType.Null): + context.WriteLine(output, $"static PRT_TYPE {typeGenName} = {{ PRT_KIND_NULL, {{ NULL }} }};"); + break; + case PrimitiveType primitiveType when Equals(primitiveType, PrimitiveType.Int): + context.WriteLine(output, $"static PRT_TYPE {typeGenName} = {{ PRT_KIND_INT, {{ NULL }} }};"); + break; + case PrimitiveType primitiveType when Equals(primitiveType, PrimitiveType.Float): + context.WriteLine(output, $"static PRT_TYPE {typeGenName} = {{ PRT_KIND_FLOAT, {{ NULL }} }};"); + break; + case PrimitiveType primitiveType when Equals(primitiveType, PrimitiveType.Bool): + context.WriteLine(output, $"static PRT_TYPE {typeGenName} = {{ PRT_KIND_BOOL, {{ NULL }} }};"); + break; + case PrimitiveType primitiveType when Equals(primitiveType, PrimitiveType.Machine): + context.WriteLine(output, $"static PRT_TYPE {typeGenName} = {{ PRT_KIND_MACHINE, {{ NULL }} }};"); + break; + case PrimitiveType primitiveType when Equals(primitiveType, PrimitiveType.Event): + context.WriteLine(output, $"static PRT_TYPE {typeGenName} = {{ PRT_KIND_EVENT, {{ NULL }} }};"); + break; + case PrimitiveType primitiveType when Equals(primitiveType, PrimitiveType.Any): + context.WriteLine(output, $"static PRT_TYPE {typeGenName} = {{ PRT_KIND_ANY, {{ NULL }} }};"); + break; + case PrimitiveType primitiveType: + context.WriteLine(output, $"// TODO: implement types like {primitiveType.CanonicalRepresentation}"); + break; + case SequenceType sequenceType: + string seqElementTypeName = WriteTypeDefinition(output, sequenceType.ElementType); + string seqTypeDeclName = context.Names.GetTemporaryName("SEQTYPE"); + context.WriteLine(output, $"static PRT_SEQTYPE {seqTypeDeclName} = {{ &{seqElementTypeName} }};"); + context.WriteLine(output, + $"static PRT_TYPE {typeGenName} = {{ PRT_KIND_SEQ, {{ .seq = &{seqTypeDeclName} }} }};"); + break; + case TupleType tupleType: + string tupTypesArrayName = context.Names.GetTemporaryName("TUP_T"); + string tupStructName = context.Names.GetTemporaryName("TUP"); + var tupTypeDeclNames = tupleType.Types.Select(t => WriteTypeDefinition(output, t)); + context.WriteLine( + output, + $"static PRT_TYPE* {tupTypesArrayName}[] = {{ {string.Join(", ", tupTypeDeclNames.Select(n => "&" + n))} }};"); + context.WriteLine(output, + $"static PRT_TUPTYPE {tupStructName} = {{ {tupleType.Types.Count}U, {tupTypesArrayName} }};"); + context.WriteLine(output, + $"static PRT_TYPE {typeGenName} = {{ PRT_KIND_TUPLE, {{ .tuple = &{tupStructName} }} }};"); + break; + case TypeDefType _: + Debug.Fail("typedefs shouldn't be possible after canonicalization"); + throw new ArgumentOutOfRangeException(nameof(type), + "typedefs shouldn't be possible after canonicalization"); + } + + context.WrittenTypes.Add(type); + return typeGenName; + } + + private void WriteProgramDecl(TextWriter output, Scope globalScope) + { + // generate event array + string eventArrayName = context.Names.GetTemporaryName("ALL_EVENTS"); + var eventsInOrder = PrtTranslationUtils.ToOrderedListByPermutation(globalScope.Events, context.GetDeclNumber); + string eventArrayBody = string.Join(", ", eventsInOrder.Select(ev => "&" + context.Names.GetNameForDecl(ev))); + eventArrayBody = string.IsNullOrEmpty(eventArrayBody) ? "NULL" : eventArrayBody; + context.WriteLine(output, $"PRT_EVENTDECL* {eventArrayName}[] = {{ {eventArrayBody} }};"); + + // generate machine array + string machineArrayName = context.Names.GetTemporaryName("ALL_MACHINES"); + string machineArrayBody = string.Join(", ", PrtTranslationUtils + .ToOrderedListByPermutation(globalScope.Machines, context.GetDeclNumber) + .Select(ev => "&" + context.Names.GetNameForDecl(ev))); + machineArrayBody = string.IsNullOrEmpty(machineArrayBody) ? "NULL" : machineArrayBody; + context.WriteLine(output, $"PRT_MACHINEDECL* {machineArrayName}[] = {{ {machineArrayBody} }};"); + + // generate interface array + string interfaceArrayName = context.Names.GetTemporaryName("ALL_INTERFACES"); + string interfaceArrayBody = string.Join(", ", PrtTranslationUtils + .ToOrderedListByPermutation(globalScope.Interfaces, context.GetDeclNumber) + .Select(ev => "&" + context.Names.GetNameForDecl(ev))); + interfaceArrayBody = string.IsNullOrEmpty(interfaceArrayBody) ? "NULL" : interfaceArrayBody; + context.WriteLine(output, $"PRT_INTERFACEDECL* {interfaceArrayName}[] = {{ {interfaceArrayBody} }};"); + + // generate functions array + var allFunctions = globalScope.Functions.Where(f => !f.IsForeign).ToList(); + string funcArrayName = context.Names.GetTemporaryName("ALL_FUNCTIONS"); + string funcArrayBody = + string.Join(", ", allFunctions.Select(ev => "&" + context.Names.GetNameForDecl(ev))); + funcArrayBody = string.IsNullOrEmpty(funcArrayBody) ? "NULL" : funcArrayBody; + context.WriteLine(output, $"PRT_FUNDECL* {funcArrayName}[] = {{ {funcArrayBody} }};"); + + // generate foreign types array + var foreignTypes = context.WrittenTypes.Where(t => t is ForeignType).Cast().ToList(); + string foreignTypesArrayName = context.Names.GetTemporaryName("ALL_FOREIGN_TYPES"); + string foreignTypesArrayBody = string.Join(", ", + foreignTypes + .Select(t => $"&{context.Names.GetNameForForeignTypeDecl(t)}")); + foreignTypesArrayBody = string.IsNullOrEmpty(foreignTypesArrayBody) ? "NULL" : foreignTypesArrayBody; + context.WriteLine(output, + $"PRT_FOREIGNTYPEDECL* {foreignTypesArrayName}[] = {{ {foreignTypesArrayBody} }};"); + + foreach (Implementation impl in globalScope.Implementations) + { + var linkMap = impl.ModExpr.ModuleInfo.LinkMap; + + var trueLinkMap = ResolveLinkMap(globalScope, linkMap); + var mapNames = Enumerable.Repeat("NULL", trueLinkMap.Length).ToArray(); + for (var i = 0; i < trueLinkMap.Length; i++) + { + var iMap = trueLinkMap[i]; + if (iMap != null) + { + string mapTmpName = context.Names.GetTemporaryName($"{impl.Name}_LME_{i}"); + mapNames[i] = mapTmpName; + context.WriteLine(output, $"int {mapTmpName}[] = {{ {string.Join(",", iMap)} }};"); + } + } + + string linkMapName = context.Names.GetTemporaryName($"{impl.Name}_LINKMAP"); + context.WriteLine(output, $"int* {linkMapName}[] = {{ {string.Join(", ", mapNames)} }};"); + + var machineDefMap = impl.ModExpr.ModuleInfo.InterfaceDef; + string machineDefMapName = context.Names.GetTemporaryName($"{impl.Name}_DEFMAP"); + var realMachineDefMap = Enumerable.Repeat(-1, trueLinkMap.Length).ToArray(); + foreach (var linking in machineDefMap) + { + realMachineDefMap[context.GetDeclNumber(linking.Key)] = context.GetDeclNumber(linking.Value); + } + + context.WriteLine(output, $"int {machineDefMapName}[] = {{ {string.Join(",", realMachineDefMap)} }};"); + + context.WriteLine(output, $"PRT_PROGRAMDECL {context.Names.GetNameForDecl(impl)} = {{"); + context.WriteLine(output, $"{globalScope.Events.Count()}U,"); + context.WriteLine(output, $"{globalScope.Machines.Count()}U,"); + context.WriteLine(output, $"{globalScope.Interfaces.Count()}U,"); + context.WriteLine(output, $"{allFunctions.Count}U,"); + context.WriteLine(output, $"{foreignTypes.Count}U,"); + context.WriteLine(output, $"{eventArrayName},"); + context.WriteLine(output, $"{machineArrayName},"); + context.WriteLine(output, $"{interfaceArrayName},"); + context.WriteLine(output, $"{funcArrayName},"); + context.WriteLine(output, $"{foreignTypesArrayName},"); + context.WriteLine(output, $"{linkMapName},"); + context.WriteLine(output, $"{machineDefMapName}"); + context.WriteLine(output, "};"); + } + } + + private int[][] ResolveLinkMap(Scope globalScope, IDictionary> linkMap) + { + int nInterfaces = globalScope.Interfaces.Count(); + var maps = new int[nInterfaces][]; + foreach (var keyValuePair in linkMap) + { + int firstInterfaceIndex = context.GetDeclNumber(keyValuePair.Key); + Debug.Assert(maps[firstInterfaceIndex] == null); + maps[firstInterfaceIndex] = Enumerable.Repeat(-1, nInterfaces).ToArray(); + + foreach (var finalMapping in keyValuePair.Value) + { + int secondInterfaceIndex = context.GetDeclNumber(finalMapping.Key); + int finalInterfaceIndex = context.GetDeclNumber(finalMapping.Value); + maps[firstInterfaceIndex][secondInterfaceIndex] = finalInterfaceIndex; + } + } + + return maps; + } + + private string GetReceivesNameOrMkTemp(TextWriter output, Machine machine) + { + string eventSetName; + if (machine.Receives is NamedEventSet mRecvSet) + { + eventSetName = context.Names.GetNameForDecl(mRecvSet); + } + else + { + var machineTempRecvSet = new NamedEventSet(machine.Name + "_RECV", machine.SourceLocation); + machineTempRecvSet.AddEvents(machine.Receives.Events); + WriteSourceDecl(output, machineTempRecvSet); + eventSetName = context.Names.GetNameForDecl(machineTempRecvSet); + } + + return eventSetName; + } + + private string GetSendsNameOrMkTemp(TextWriter output, Machine machine) + { + string eventSetName; + if (machine.Sends is NamedEventSet mSendSet) + { + eventSetName = context.Names.GetNameForDecl(mSendSet); + } + else + { + var machineTempSendSet = new NamedEventSet(machine.Name + "_SEND", machine.SourceLocation); + machineTempSendSet.AddEvents(machine.Sends.Events); + WriteSourceDecl(output, machineTempSendSet); + eventSetName = context.Names.GetNameForDecl(machineTempSendSet); + } + + return eventSetName; + } + + #endregion + + #region Function body methods + + private void WriteFunctionBody(TextWriter output, Function function) + { + var funLocation = context.LocationResolver.GetLocation(function); + context.WriteLine(output, $"#line {funLocation.Line} \"{funLocation.File.Name}\""); + + for (var i = 0; i < function.Signature.Parameters.Count; i++) + { + Variable argument = function.Signature.Parameters[i]; + string varName = context.Names.GetNameForDecl(argument); + context.WriteLine(output, $"PRT_VALUE** {varName} = argRefs[{i}];"); + } + + foreach (Variable localVariable in function.LocalVariables) + { + string varName = context.Names.GetNameForDecl(localVariable); + string varTypeName = context.Names.GetNameForType(localVariable.Type); + // TODO: optimize away PrtMkDefaultValue if liveness shows no usages before assignments. + context.WriteLine(output, $"PRT_VALUE* {varName} = PrtMkDefaultValue(&{varTypeName});"); + } + + context.WriteLine(output, $"PRT_VALUE* {FunCallRetValName} = NULL;"); + // TODO: figure out how many args are actually necessary based on function calls. + context.WriteLine(output, $"PRT_VALUE** {FunCallArgsArrayName}[32];"); + context.WriteLine(output, "PRT_MACHINEINST_PRIV* p_this = (PRT_MACHINEINST_PRIV*)context;"); + if (function.Signature.ReturnType.IsSameTypeAs(PrimitiveType.Null)) + { + context.WriteLine(output, $"PRT_VALUE* {FunResultValName} = NULL;"); + } + else + { + string nameForReturnType = context.Names.GetNameForType(function.Signature.ReturnType); + context.WriteLine(output, $"PRT_VALUE* {FunResultValName} = PrtMkDefaultValue(&{nameForReturnType});"); + } + + context.WriteLine(output); + + // Write the body into a temporary buffer so that forward declarations can be found and added + var bodyWriter = new StringWriter(); + var bodyLocation = context.LocationResolver.GetLocation(function.Body); + context.WriteLine(bodyWriter, $"#line {bodyLocation.Line} \"{bodyLocation.File.Name}\""); + + foreach (IPStmt stmt in function.Body.Statements) + { + WriteStmt(bodyWriter, function, stmt); + } + + bodyWriter.WriteLine($"{context.Names.GetReturnLabel(function)}:"); + foreach (Variable localVariable in function.LocalVariables) + { + string varName = context.Names.GetNameForDecl(localVariable); + context.WriteLine(bodyWriter, $"PrtFreeValue({varName}); {varName} = NULL;"); + } + + context.WriteLine(bodyWriter, $"return {FunResultValName};"); + + // Write gathered literals to the prologue + context.WriteLine(output, + $"PRT_VALUE {FunNullStaticName} = {{ PRT_VALUE_KIND_NULL, {{ .ev = PRT_SPECIAL_EVENT_NULL }} }};"); + + foreach (var literal in context.GetRegisteredIntLiterals(function)) + { + context.WriteLine(output, + $"PRT_VALUE {literal.Value} = {{ PRT_VALUE_KIND_INT, {{ .nt = {literal.Key} }} }};"); + } + + foreach (var literal in context.GetRegisteredFloatLiterals(function)) + { + context.WriteLine(output, + $"PRT_VALUE {literal.Value} = {{ PRT_VALUE_KIND_FLOAT, {{ .ft = {literal.Key} }} }};"); + } + + foreach (var literal in context.GetRegisteredBoolLiterals(function)) + { + context.WriteLine( + output, + $"PRT_VALUE {literal.Value} = {{ PRT_VALUE_KIND_BOOL, {{ .bl = {(literal.Key ? "PRT_TRUE" : "PRT_FALSE")} }} }};"); + } + + output.Write(bodyWriter); + } + + private string GetVariableReference(Function function, IVariableRef variableRef) + { + return $"&({GetVariablePointer(function, variableRef.Variable)})"; + } + + private void WriteStmt(TextWriter output, Function function, IPStmt stmt) + { + var stmtLocation = context.LocationResolver.GetLocation(stmt); + context.WriteLine(output, $"#line {stmtLocation.Line} \"{stmtLocation.File.Name}\""); + switch (stmt) + { + case AnnounceStmt _: + // TODO: Ankush needs to implement this in Prt + break; + case AssertStmt assertStmt: + context.Write(output, "PrtAssert(PrtPrimGetBool("); + WriteExpr(output, function, assertStmt.Assertion); + context.WriteLine(output, $"), \"{assertStmt.Message}\");"); + break; + case AssignStmt assignStmt: + // Lookup lvalue + string lvalName = context.Names.GetTemporaryName("LVALUE"); + context.Write(output, $"PRT_VALUE** {lvalName} = &("); + WriteLValue(output, function, assignStmt.Location); + context.WriteLine(output, ");"); + + // Free old value + context.WriteLine(output, $"PrtFreeValue(*{lvalName});"); + + // Assign new value + context.Write(output, $"*{lvalName} = "); + WriteExpr(output, function, assignStmt.Value); + context.WriteLine(output, ";"); + break; + case CompoundStmt compoundStmt: + context.WriteLine(output, "{"); + foreach (IPStmt pStmt in compoundStmt.Statements) + { + WriteStmt(output, function, pStmt); + } + + context.WriteLine(output, "}"); + break; + case CtorStmt ctorStmt: + context.Write( + output, + $"PrtMkInterface(context, {context.GetDeclNumber(ctorStmt.Interface)}, {ctorStmt.Arguments.Count}"); + foreach (IPExpr pExpr in ctorStmt.Arguments) + { + Debug.Assert(pExpr is IVariableRef); + var argVar = (IVariableRef) pExpr; + context.Write(output, $", {GetVariableReference(function, argVar)}"); + } + + context.WriteLine(output, ");"); + break; + case FunCallStmt funCallStmt: + string funImplName = context.Names.GetNameForFunctionImpl(funCallStmt.Fun); + var funArgs = funCallStmt.ArgsList.Cast().ToList(); + + // Put all the arguments in the args array + foreach (var arg in funArgs.Select((arg, i) => new {arg, i})) + { + context.WriteLine( + output, $"{FunCallArgsArrayName}[{arg.i}] = {GetVariableReference(function, arg.arg)};"); + } + + // Call the function and immediately free the value + context.WriteLine(output, $"PrtFreeValue({funImplName}(context, {FunCallArgsArrayName}));"); + + // Free and set to null all the moved arguments + var toFree = funArgs.Where(arg => arg.LinearType.Equals(LinearType.Move)) + .Select(arg => GetVariablePointer(function, arg.Variable)); + foreach (string argName in toFree) + { + context.WriteLine(output, $"PrtFreeValue({argName});"); + context.WriteLine(output, $"{argName} = NULL;"); + } + + break; + case GotoStmt gotoStmt: + context.WriteLine(output, "PrtFreeTriggerPayload(p_this);"); + + int destStateIndex = context.GetDeclNumber(gotoStmt.State); + context.Write(output, $"PrtGoto(p_this, {destStateIndex}U, "); + if (gotoStmt.Payload != null) + { + Debug.Assert(gotoStmt.Payload is IVariableRef); + var gotoArg = (IVariableRef) gotoStmt.Payload; + context.Write(output, $"1, {GetVariableReference(function, gotoArg)}"); + } + else + { + context.Write(output, "0"); + } + + context.WriteLine(output, ");"); + break; + case IfStmt ifStmt: + context.Write(output, "if (PrtPrimGetBool("); + WriteExpr(output, function, ifStmt.Condition); + context.WriteLine(output, "))"); + WriteStmt(output, function, ifStmt.ThenBranch); + if (ifStmt.ElseBranch != null) + { + context.WriteLine(output, "else"); + WriteStmt(output, function, ifStmt.ElseBranch); + } + + break; + case InsertStmt insertStmt: + context.Write(output, "PrtSeqInsertEx("); + WriteLValue(output, function, insertStmt.Variable); + context.Write(output, ", "); + WriteExpr(output, function, insertStmt.Index); + context.Write(output, ", "); + Debug.Assert(insertStmt.Value is IVariableRef); + WriteExpr(output, function, insertStmt.Value); + context.WriteLine(output, ", PRT_FALSE);"); + var insertValueVar = (IVariableRef) insertStmt.Value; + context.WriteLine(output, $"*({GetVariableReference(function, insertValueVar)}) = NULL;"); + break; + case MoveAssignStmt moveAssignStmt: + context.WriteLine(output, "{"); + string movedVarName = GetVariablePointer(function, moveAssignStmt.FromVariable); + + // Get reference to old value + string movedLValue = context.Names.GetTemporaryName("LVALUE"); + context.Write(output, $"PRT_VALUE** {movedLValue} = &("); + WriteLValue(output, function, moveAssignStmt.ToLocation); + context.WriteLine(output, ");"); + + // Free old value + context.WriteLine(output, $"PrtFreeValue(*{movedLValue});"); + + // Move variable to lvalue location + context.WriteLine(output, $"*{movedLValue} = {movedVarName};"); + + // Null out old variable + context.WriteLine(output, $"{movedVarName} = NULL;"); + + context.WriteLine(output, "}"); + break; + case NoStmt _: + return; + case PopStmt _: + context.WriteLine(output, "PrtFreeTriggerPayload(p_this);"); + context.WriteLine(output, "PrtPop(p_this);"); + context.WriteLine(output, $"goto {context.Names.GetReturnLabel(function)};"); + break; + case PrintStmt printStmt: + WritePrintStmt(output, printStmt, function); + break; + case RaiseStmt raiseStmt: + context.WriteLine(output, "PrtFreeTriggerPayload(p_this);"); + context.Write(output, "PrtRaise(p_this, "); + WriteExpr(output, function, raiseStmt.PEvent); + context.Write(output, $", {raiseStmt.Payload.Count}"); + foreach (IPExpr pExpr in raiseStmt.Payload) + { + Debug.Assert(pExpr is IVariableRef); + var argVar = (IVariableRef) pExpr; + context.Write(output, $", {GetVariableReference(function, argVar)}"); + } + + context.WriteLine(output, ");"); + + Debug.Assert(raiseStmt.PEvent is IVariableRef); + var raiseEventVar = (IVariableRef) raiseStmt.PEvent; + context.WriteLine(output, $"*({GetVariableReference(function, raiseEventVar)}) = NULL;"); + context.WriteLine(output, $"goto {context.Names.GetReturnLabel(function)};"); + break; + case ReceiveStmt receiveStmt: + string allowedEventIdsName = context.Names.GetTemporaryName("allowedEventIds"); + string allowedEventIdsValue = + string.Join(", ", receiveStmt.Cases.Keys.Select(context.GetDeclNumber)); + context.WriteLine(output, $"PRT_UINT32 {allowedEventIdsName}[] = {{ {allowedEventIdsValue} }};"); + + string payloadName = context.Names.GetTemporaryName("allowedEventIds"); + context.WriteLine(output, $"PRT_VALUE* {payloadName} = NULL;"); + + // TODO: implement PrtReceiveAsync. Daan's the man! + string eventIdName = context.Names.GetTemporaryName("eventId"); + context.WriteLine(output, + $"PRT_UINT32 {eventIdName} = PrtReceiveAsync(context, {allowedEventIdsName}, &{payloadName});"); + + context.WriteLine(output, $"switch ({eventIdName}) {{"); + foreach (var receiveCase in receiveStmt.Cases) + { + var ev = receiveCase.Key; + var fn = receiveCase.Value; + context.WriteLine(output, $"case {context.GetDeclNumber(ev)}: {{"); + + Debug.Assert(fn.Signature.Parameters.Count <= 1); + + if (fn.Signature.Parameters.Any()) + { + string realPayloadName = context.Names.GetNameForDecl(fn.Signature.Parameters[0]); + context.WriteLine(output, $"PRT_VALUE* {realPayloadName} = {payloadName};"); + + // Get the return label just for the side effect of setting a nice name + context.Names.GetReturnLabel(fn, $"recv_{ev.Name.ToLowerInvariant()}_ret"); + } + + context.WriteLine(output, "} break;"); + } + + context.WriteLine(output, "default: {"); + context.WriteLine(output, "PrtAssert(PRT_FALSE, \"receive returned unhandled event\");"); + context.WriteLine(output, "}"); + context.WriteLine(output, "}"); + break; + case RemoveStmt removeStmt: + context.Write(output, "PrtRemoveByKey("); + WriteLValue(output, function, removeStmt.Variable); + context.Write(output, ", "); + WriteExpr(output, function, removeStmt.Value); + context.WriteLine(output, ");"); + break; + case ReturnStmt returnStmt: + if (returnStmt.ReturnValue != null) + { + context.WriteLine(output, $"PrtFreeValue({FunResultValName});"); + context.Write(output, $"{FunResultValName} = "); + WriteExpr(output, function, returnStmt.ReturnValue); + context.WriteLine(output, ";"); + } + + context.WriteLine(output, $"goto {context.Names.GetReturnLabel(function)};"); + break; + case SendStmt sendStmt: + context.Write(output, "PrtSendInternal(context, PrtGetMachine(context->process, "); + WriteExpr(output, function, sendStmt.MachineExpr); + context.Write(output, "), "); + WriteExpr(output, function, sendStmt.Evt); + context.Write(output, $", {sendStmt.ArgsList.Count}"); + foreach (IPExpr sendArgExpr in sendStmt.ArgsList) + { + Debug.Assert(sendArgExpr is IVariableRef); + var argVar = (IVariableRef) sendArgExpr; + context.Write(output, $", {GetVariableReference(function, argVar)}"); + } + + context.WriteLine(output, ");"); + + Debug.Assert(sendStmt.Evt is IVariableRef); + var sendEventVar = (IVariableRef) sendStmt.Evt; + context.WriteLine(output, $"*({GetVariableReference(function, sendEventVar)}) = NULL;"); + break; + case SwapAssignStmt swapAssignStmt: + context.WriteLine(output, "{"); + string lvName = context.Names.GetTemporaryName("LVALUE"); + string tmpName = context.Names.GetTemporaryName("SWAP"); + + // Can only swap local variables, so this is safe. Otherwise would have to call a second WriteLValue + string swappedName = GetVariablePointer(function, swapAssignStmt.OldLocation); + + // Save l-value + context.Write(output, $"PRT_VALUE** {lvName} = &("); + WriteLValue(output, function, swapAssignStmt.NewLocation); + context.WriteLine(output, ");"); + context.WriteLine(output, $"PRT_VALUE* {tmpName} = *{lvName};"); + + // Overwrite l-value with var + context.WriteLine(output, $"*{lvName} = {swappedName};"); + + // Complete the swap + context.WriteLine(output, $"{swappedName} = {tmpName};"); + context.WriteLine(output, "}"); + break; + case WhileStmt whileStmt: + context.Write(output, "while (PrtPrimGetBool("); + WriteExpr(output, function, whileStmt.Condition); + context.WriteLine(output, "))"); + WriteStmt(output, function, whileStmt.Body); + break; + } + + context.WriteLine(output); + } + + private void WritePrintStmt(TextWriter output, PrintStmt printStmt, Function function) + { + // format is {str0, n1, str1, n2, ..., nK, strK} + var printMessageParts = PrtTranslationUtils.ParsePrintMessage(printStmt.Message); + + // Optimize for simple case. + if (printMessageParts.Length == 1) + { + context.Write(output, "PrtPrintf(\""); + context.Write(output, (string) printMessageParts[0]); + context.WriteLine(output, "\");"); + return; + } + + // Otherwise build full parameter pack... + int k = (printMessageParts.Length - 1) / 2; + context.Write(output, "PrtFormatPrintf(\""); + context.Write(output, (string) printMessageParts[0]); + context.Write(output, "\", "); + context.Write(output, printStmt.Args.Count.ToString()); + foreach (IPExpr printArg in printStmt.Args) + { + context.Write(output, ", "); + WriteExpr(output, function, printArg); + } + + context.Write(output, ", "); + context.Write(output, k.ToString()); + for (var i = 0; i < k; i++) + { + var n = (int) printMessageParts[1 + 2 * i]; + var s = (string) printMessageParts[1 + 2 * i + 1]; + context.Write(output, ", "); + context.Write(output, n.ToString()); + context.Write(output, ", \""); + context.Write(output, s); + context.Write(output, "\""); + } + + context.WriteLine(output, ");"); + } + + private void WriteLValue(TextWriter output, Function function, IPExpr expr) + { + switch (expr) + { + case MapAccessExpr mapAccessExpr: + // TODO: optimize out key copy when possible + context.Write(output, "*(PrtMapGetLValue("); + WriteLValue(output, function, mapAccessExpr.MapExpr); + context.Write(output, ", "); + WriteExpr(output, function, mapAccessExpr.IndexExpr); + context.Write(output, $", PRT_TRUE, &{context.Names.GetNameForType(mapAccessExpr.MapExpr.Type)}))"); + break; + case NamedTupleAccessExpr namedTupleAccessExpr: + context.Write(output, "*(PrtTupleGetLValue("); + WriteLValue(output, function, namedTupleAccessExpr.SubExpr); + context.Write(output, $", {namedTupleAccessExpr.Entry.FieldNo}))"); + break; + case SeqAccessExpr seqAccessExpr: + context.Write(output, "*(PrtSeqGetLValue("); + WriteLValue(output, function, seqAccessExpr.SeqExpr); + context.Write(output, ", "); + WriteExpr(output, function, seqAccessExpr.IndexExpr); + context.Write(output, "))"); + break; + case TupleAccessExpr tupleAccessExpr: + context.Write(output, "*(PrtTupleGetLValue("); + WriteLValue(output, function, tupleAccessExpr.SubExpr); + context.Write(output, $", {tupleAccessExpr.FieldNo}))"); + break; + case VariableAccessExpr variableAccessExpr: + WriteVariableAccess(output, function, variableAccessExpr.Variable); + break; + default: + throw context.Handler.InternalError(expr.SourceLocation, + new ArgumentOutOfRangeException(nameof(expr))); + } + } + + private void WriteExpr(TextWriter output, Function function, IPExpr expr) + { + switch (expr) + { + case CloneExpr cloneExpr: + context.Write(output, "PrtCloneValue("); + WriteExpr(output, function, cloneExpr.Term); + context.Write(output, ")"); + break; + case BinOpExpr binOpExpr: + IPExpr binOpLhs = binOpExpr.Lhs; + IPExpr binOpRhs = binOpExpr.Rhs; + BinOpType binOpType = binOpExpr.Operation; + + // TODO: if getting a literal, replace with literal. + if (binOpType == BinOpType.Eq || binOpType == BinOpType.Neq) + { + string negate = binOpType == BinOpType.Eq ? "" : "!"; + context.Write(output, $"PrtMkBoolValue({negate}PrtIsEqualValue("); + WriteExpr(output, function, binOpLhs); + context.Write(output, ", "); + WriteExpr(output, function, binOpRhs); + context.Write(output, "))"); + } + else + { + (string binOpGetter, _) = GetTypeStructureFuns(binOpLhs.Type); + (_, string binOpBuilder) = GetTypeStructureFuns(binOpExpr.Type); + + context.Write(output, $"{binOpBuilder}("); + + context.Write(output, $"{binOpGetter}("); + WriteExpr(output, function, binOpLhs); + context.Write(output, ")"); + + context.Write(output, $" {BinOpToStr(binOpType)} "); + + context.Write(output, $"{binOpGetter}("); + WriteExpr(output, function, binOpRhs); + context.Write(output, ")"); + + context.Write(output, ")"); + } + + break; + case BoolLiteralExpr boolLiteralExpr: + string boolLiteralName = context.RegisterLiteral(function, boolLiteralExpr.Value); + context.Write(output, $"(&{boolLiteralName})"); + break; + case CastExpr castExpr: + string castTypeName = context.Names.GetNameForType(castExpr.Type); + context.Write(output, "PrtCloneValue(PrtCastValue("); + WriteExpr(output, function, castExpr.SubExpr); + context.Write(output, $", &{castTypeName}))"); + break; + case CoerceExpr coerceExpr: + string coerceCtor; + switch (coerceExpr.NewType) + { + case PrimitiveType primitiveType when PrimitiveType.Int.IsSameTypeAs(primitiveType): + case PLanguageType type when PLanguageType.TypeIsOfKind(type, TypeKind.Enum): + coerceCtor = "PrtMkIntValue"; + break; + case PrimitiveType primitiveType when PrimitiveType.Float.IsSameTypeAs(primitiveType): + coerceCtor = "PrtMkFloatValue"; + break; + default: + throw context.Handler.InternalError(coerceExpr.SourceLocation, + new ArgumentOutOfRangeException(nameof(coerceExpr.NewType))); + } + + string coerceUnpack; + switch (coerceExpr.SubExpr.Type) + { + case PrimitiveType primitiveType when PrimitiveType.Int.IsSameTypeAs(primitiveType): + case PLanguageType type when PLanguageType.TypeIsOfKind(type, TypeKind.Enum): + coerceUnpack = "PrtPrimGetInt"; + break; + case PrimitiveType primitiveType when PrimitiveType.Float.IsSameTypeAs(primitiveType): + coerceUnpack = "PrtPrimGetFloat"; + break; + default: + throw context.Handler.InternalError(coerceExpr.SourceLocation, + new ArgumentOutOfRangeException(nameof(coerceExpr.SubExpr.Type))); + } + + context.Write(output, $"{coerceCtor}({coerceUnpack}("); + WriteExpr(output, function, coerceExpr.SubExpr); + context.Write(output, "))"); + break; + case ContainsKeyExpr containsKeyExpr: + context.Write(output, "PrtMkBoolValue(PrtMapExists("); + WriteExpr(output, function, containsKeyExpr.Map); + context.Write(output, ", "); + WriteExpr(output, function, containsKeyExpr.Key); + context.Write(output, "));"); + break; + case CtorExpr ctorExpr: + context.Write( + output, + $"PrtCloneValue(PrtMkInterface(context, {context.GetDeclNumber(ctorExpr.Interface)}, {ctorExpr.Arguments.Count}"); + foreach (IPExpr pExpr in ctorExpr.Arguments) + { + Debug.Assert(pExpr is IVariableRef); + var argVar = (IVariableRef) pExpr; + context.Write(output, $", {GetVariableReference(function, argVar)}"); + } + + context.Write(output, ")->id)"); + break; + case DefaultExpr defaultExpr: + string nameForDefaultType = context.Names.GetNameForType(defaultExpr.Type); + context.Write(output, $"PrtMkDefaultValue(&{nameForDefaultType})"); + break; + case EnumElemRefExpr enumElemRefExpr: + string enumLiteralName = context.RegisterLiteral(function, enumElemRefExpr.Value.Value); + context.Write(output, $"(&{enumLiteralName})"); + break; + case EventRefExpr eventRefExpr: + context.Write(output, $"(&{context.Names.GetNameForDecl(eventRefExpr.Value)}.value)"); + break; + case FairNondetExpr _: + context.Write(output, "(PrtMkNondetBoolValue())"); + break; + case FloatLiteralExpr floatLiteralExpr: + string floaLiteralName = context.RegisterLiteral(function, floatLiteralExpr.Value); + context.Write(output, $"(&{floaLiteralName})"); + break; + case FunCallExpr funCallExpr: + string funImplName = context.Names.GetNameForFunctionImpl(funCallExpr.Function); + var funArgs = funCallExpr.Arguments.Cast().ToList(); + var argSetup = funArgs.Select((arg, i) => + $"({FunCallArgsArrayName}[{i}] = {GetVariableReference(function, arg)})"); + var funCall = new[] {$"({FunCallRetValName} = {funImplName}(context, {FunCallArgsArrayName}))"}; + var argsFree = funArgs.Where(arg => arg.LinearType.Equals(LinearType.Move)) + .Select(arg => GetVariablePointer(function, arg.Variable)) + .Select(varName => $"(PrtFreeValue({varName}), {varName} = NULL)"); + var resRetrieve = new[] {$"({FunCallRetValName})"}; + string fullCall = string.Join(", ", argSetup.Concat(funCall).Concat(argsFree).Concat(resRetrieve)); + context.Write(output, $"({fullCall})"); + break; + case IntLiteralExpr intLiteralExpr: + string intLiteralName = context.RegisterLiteral(function, intLiteralExpr.Value); + context.Write(output, $"(&{intLiteralName})"); + break; + case KeysExpr keysExpr: + context.Write(output, "PrtMapGetKeys("); + WriteExpr(output, function, keysExpr.Expr); + context.Write(output, ")"); + break; + case LinearAccessRefExpr linearAccessRefExpr: + // TODO: what's special about linear refs here? + WriteVariableAccess(output, function, linearAccessRefExpr.Variable); + break; + case MapAccessExpr mapAccessExpr: + context.Write(output, "PrtMapGet("); + WriteExpr(output, function, mapAccessExpr.MapExpr); + context.Write(output, ", "); + WriteExpr(output, function, mapAccessExpr.IndexExpr); + context.Write(output, ")"); + break; + case NamedTupleAccessExpr namedTupleAccessExpr: + context.Write(output, "PrtTupleGet("); + WriteExpr(output, function, namedTupleAccessExpr.SubExpr); + context.Write(output, $", {namedTupleAccessExpr.Entry.FieldNo})"); + break; + case NamedTupleExpr namedTupleExpr: + var ntArgs = (IReadOnlyList) namedTupleExpr.TupleFields; + string ntTypeName = context.Names.GetNameForType(namedTupleExpr.Type); + string namedTupleBody = + string.Join(", ", ntArgs.Select(v => GetVariableReference(function, v))); + context.Write(output, $"(PrtMkTuple(&{ntTypeName}, {namedTupleBody}))"); + break; + case NondetExpr _: + context.Write(output, "(PrtMkNondetBoolValue())"); + break; + case NullLiteralExpr _: + context.Write(output, $"(&{FunNullStaticName})"); + break; + case SeqAccessExpr seqAccessExpr: + context.Write(output, "PrtSeqGet("); + WriteExpr(output, function, seqAccessExpr.SeqExpr); + context.Write(output, ", "); + WriteExpr(output, function, seqAccessExpr.IndexExpr); + context.Write(output, ")"); + break; + case SizeofExpr sizeofExpr: + var sizeofFun = PLanguageType.TypeIsOfKind(sizeofExpr.Expr.Type, TypeKind.Map) + ? "PrtMapSizeOf" + : "PrtSeqSizeOf"; + context.Write(output, $"PrtMkIntValue({sizeofFun}("); + WriteExpr(output, function, sizeofExpr.Expr); + context.Write(output, "))"); + break; + case ThisRefExpr _: + context.Write(output, "(p_this->id)"); + break; + case TupleAccessExpr tupleAccessExpr: + context.Write(output, "PrtTupleGet("); + WriteExpr(output, function, tupleAccessExpr.SubExpr); + context.Write(output, $", {tupleAccessExpr.FieldNo})"); + break; + case UnaryOpExpr unaryOpExpr: + (string unOpGetter, string unOpBuilder) = GetTypeStructureFuns(unaryOpExpr.Type); + context.Write(output, $"{unOpBuilder}("); + + context.Write(output, UnOpToStr(unaryOpExpr.Operation)); + context.Write(output, $"{unOpGetter}("); + WriteExpr(output, function, unaryOpExpr.SubExpr); + context.Write(output, ")"); + + context.Write(output, ")"); + break; + case UnnamedTupleExpr unnamedTupleExpr: + var utArgs = (IReadOnlyList) unnamedTupleExpr.TupleFields; + string utTypeName = context.Names.GetNameForType(unnamedTupleExpr.Type); + string tupleBody = + string.Join(", ", utArgs.Select(v => GetVariableReference(function, v))); + context.Write(output, $"(PrtMkTuple(&{utTypeName}, {tupleBody}))"); + break; + case ValuesExpr valuesExpr: + context.Write(output, "PrtMapGetValues("); + WriteExpr(output, function, valuesExpr.Expr); + context.Write(output, ")"); + break; + case VariableAccessExpr variableAccessExpr: + WriteVariableAccess(output, function, variableAccessExpr.Variable); + break; + } + } + + private string GetVariablePointer(Function function, Variable variable) + { + if (variable.Role.HasFlag(VariableRole.Param)) + { + // dereference, since params are passed by reference. + return $"*{context.Names.GetNameForDecl(variable)}"; + } + + if (variable.Role.HasFlag(VariableRole.Field)) + { + // TODO: is this always correct? I think the iterator ordering of a List should be consistent... + int varIdx = function.Owner.Fields.ToList().IndexOf(variable); + return $"p_this->varValues[{varIdx}]"; + } + + if (variable.Role.HasFlag(VariableRole.Temp) || variable.Role.HasFlag(VariableRole.Local)) + { + return context.Names.GetNameForDecl(variable); + } + + throw context.Handler.InternalError(variable.SourceLocation, + new ArgumentOutOfRangeException(nameof(variable))); + } + + private void WriteVariableAccess(TextWriter output, Function function, Variable variable) + { + context.Write(output, GetVariablePointer(function, variable)); + } + + private static string UnOpToStr(UnaryOpType operation) + { + switch (operation) + { + case UnaryOpType.Negate: + return "-"; + case UnaryOpType.Not: + return "!"; + default: + throw new ArgumentOutOfRangeException(nameof(operation)); + } + } + + private static (string, string) GetTypeStructureFuns(PLanguageType type) + { + string binOpGetter; + string binOpBuilder; + if (type.IsSameTypeAs(PrimitiveType.Int) || type.TypeKind.Equals(TypeKind.Enum)) + { + binOpGetter = "PrtPrimGetInt"; + binOpBuilder = "PrtMkIntValue"; + } + else if (type.IsSameTypeAs(PrimitiveType.Bool)) + { + binOpGetter = "PrtPrimGetBool"; + binOpBuilder = "PrtMkBoolValue"; + } + else if (type.IsSameTypeAs(PrimitiveType.Float)) + { + binOpGetter = "PrtPrimGetFloat"; + binOpBuilder = "PrtMkFloatValue"; + } + else + { + throw new ArgumentException($"cannot destructure type {type.CanonicalRepresentation}", nameof(type)); + } + + return (binOpGetter, binOpBuilder); + } + + private static string BinOpToStr(BinOpType binOpType) + { + switch (binOpType) + { + case BinOpType.Add: + return "+"; + case BinOpType.Sub: + return "-"; + case BinOpType.Mul: + return "*"; + case BinOpType.Div: + return "/"; + case BinOpType.Eq: + return "=="; + case BinOpType.Neq: + return "!="; + case BinOpType.Lt: + return "<"; + case BinOpType.Le: + return "<="; + case BinOpType.Gt: + return ">"; + case BinOpType.Ge: + return ">="; + case BinOpType.And: + return "&&"; + case BinOpType.Or: + return "||"; + default: + throw new ArgumentOutOfRangeException(nameof(binOpType)); + } + } + + #endregion + + #region Header methods + + private void WriteHeaderPrologue(TextWriter output) + { + string includeGuardMacro = $"P_{Regex.Replace(context.ProjectName.ToUpperInvariant(), @"\s+", "")}_H_"; + context.WriteLine(output, "#pragma once"); + context.WriteLine(output, $"#ifndef {includeGuardMacro}"); + context.WriteLine(output, $"#define {includeGuardMacro}"); + context.WriteLine(output, "#include \"Prt.h\""); + context.WriteLine(output); + context.WriteLine(output, "#ifdef __cplusplus"); + context.WriteLine(output, "extern \"C\" {"); + context.WriteLine(output, "#endif"); + context.WriteLine(output); + } + + private void WriteExternDeclaration(TextWriter output, IPDecl decl) + { + string declName = context.Names.GetNameForDecl(decl); + switch (decl) + { + case EnumElem _: + break; + case Function function when !function.IsForeign: + context.WriteLine(output, $"extern PRT_FUNDECL {declName};"); + break; + case Implementation _: + context.WriteLine(output, $"extern PRT_PROGRAMDECL {declName};"); + break; + case Interface _: + context.WriteLine(output, $"extern PRT_INTERFACEDECL {declName};"); + break; + case Machine _: + context.WriteLine(output, $"extern PRT_MACHINEDECL {declName};"); + break; + case NamedEventSet namedEventSet: + // TODO: what to do here? + context.WriteLine(output, $"// DECL(NamedEventSet, {decl.Name}) => {declName}"); + break; + case NamedModule namedModule: + // TODO: what to do here? + context.WriteLine(output, $"// DECL(NamedModule, {decl.Name}) => {declName}"); + break; + case PEnum pEnum: + string enumBody = string.Join(", ", + pEnum.Values.Select(val => $"{context.Names.GetNameForDecl(val)} = {val.Value}")); + context.WriteLine(output, $"typedef enum {declName} {{ {enumBody} }} {declName};"); + context.WriteLine(output); + break; + case PEvent pEvent: + if (!pEvent.IsBuiltIn) + { + context.WriteLine(output, $"extern PRT_EVENTDECL {declName};"); + } + + break; + case RefinementTest refinementTest: + // TODO: what to do here? + context.WriteLine(output, $"// DECL(RefinementTest, {decl.Name}) => {declName}"); + break; + case SafetyTest safetyTest: + // TODO: what to do here? + context.WriteLine(output, $"// DECL(SafetyTest, {decl.Name}) => {declName}"); + break; + case TypeDef _: + context.WriteLine(output, $"extern PRT_TYPE* {declName};"); + break; + case Variable variable: + throw context.Handler.InternalError(variable.SourceLocation, + new ArgumentOutOfRangeException(nameof(decl), "can't have global P variables")); + case State state: + // TODO: what to do here? + context.WriteLine(output, $"// DECL(State, {decl.Name}) => {declName}"); + break; + case StateGroup stateGroup: + // TODO: what to do here? + context.WriteLine(output, $"// DECL(StateGroup, {decl.Name}) => {declName}"); + break; + } + } + + private void WriteHeaderEpilogue(TextWriter output) + { + string includeGuardMacro = $"P_{Regex.Replace(context.ProjectName.ToUpperInvariant(), @"\s+", "")}_H_"; + context.WriteLine(output); + context.WriteLine(output, "#ifdef __cplusplus"); + context.WriteLine(output, "}"); + context.WriteLine(output, "#endif"); + context.WriteLine(output); + context.WriteLine(output, $"#endif // {includeGuardMacro}"); + } + + #endregion + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource bodyWriter of type System.IO.StringWriter in method "Void PrtCodeGeneratorImpl.WriteFunctionBody(TextWriter,Function)". + +### Severity: +ERROR + +### Procedure: +Void PrtCodeGeneratorImpl.WriteFunctionBody(TextWriter,Function) + +### File: +Src/Pc/CompilerCore/Backend/Prt/PrtCodeGenerator.cs + +### Key: +PrtCodeGenerator.cs|WriteFunctionBody|DOTNET_RESOURCE_LEAK + +### Hash: +7936f0b2bf412eb07e3f8a1e581afb98 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2854/instruction.md b/inferredbugs-2854/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..450f737909997a5df5a1f7f59ed05b4be501647f --- /dev/null +++ b/inferredbugs-2854/instruction.md @@ -0,0 +1,730 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** P +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; + +namespace P.Runtime +{ + public abstract class PrtValue + { + public static PrtNullValue NullValue = new PrtNullValue(); + public static PrtEventValue HaltEvent = new PrtEventValue(new PrtEvent("Halt", new PrtNullType(), PrtEvent.DefaultMaxInstances, false)); + + public abstract PrtValue Clone(); + + public static PrtValue PrtMkDefaultValue(PrtType type) + { + if (type is PrtAnyType || type is PrtNullType || type is PrtEventType || type is PrtMachineType) + return new PrtNullValue(); + + else if(type is PrtIntType) + { + return new PrtIntValue(); + } + else if(type is PrtBoolType) + { + return new PrtBoolValue(); + } + else if (type is PrtMapType) + { + return new PrtMapValue(); + } + else if (type is PrtSeqType) + { + return new PrtSeqValue(); + } + else if (type is PrtNamedTupleType) + { + return new PrtNamedTupleValue(type as PrtNamedTupleType); + } + else if(type is PrtTupleType) + { + return new PrtTupleValue(type as PrtTupleType); + } + else + { + Debug.Assert(false, "Invalid type !!"); + return null; + } + } + + public abstract string GetString(); + + public abstract bool IsEqual(PrtValue value); + + public static bool PrtInhabitsType(PrtValue value, PrtType type) + { + if (type is PrtAnyType) + { + return true; + } + + if (value is PrtNullValue) + { + if (type is PrtEventType || type is PrtMachineType) + { + return true; + } + else + { + return false; + } + } + + if (type is PrtIntType) + { + return value is PrtIntValue; + } + else if (type is PrtBoolType) + { + return value is PrtBoolValue; + } + else if (type is PrtEventType) + { + return value is PrtEventValue; + } + else if (type is PrtMachineType) + { + return value is PrtMachineValue; + } + else if (type is PrtTupleType) + { + if ((!(value is PrtTupleValue)) || (value as PrtTupleValue).fieldValues.Count != (type as PrtTupleType).fieldTypes.Count) + { + return false; + } + else + { + int index = 0; + var tupVal = (value as PrtTupleValue); + var tupType = (type as PrtTupleType); + while (index < tupVal.fieldValues.Count) + { + if (!PrtInhabitsType(tupVal.fieldValues[index], tupType.fieldTypes[index])) + { + return false; + } + index++; + } + + return true; + } + } + else if (type is PrtNamedTupleType) + { + if ((!(value is PrtNamedTupleValue)) || (value as PrtNamedTupleValue).fieldValues.Count != (type as PrtNamedTupleType).fieldTypes.Count) + { + return false; + } + else + { + int index = 0; + var nmtupVal = (value as PrtNamedTupleValue); + var nmtupType = (type as PrtNamedTupleType); + while (index < nmtupVal.fieldValues.Count) + { + if (nmtupVal.fieldNames[index] != nmtupType.fieldNames[index]) + { + return false; + } + else if (!PrtInhabitsType(nmtupVal.fieldValues[index], nmtupType.fieldTypes[index])) + { + return false; + } + index++; + } + + return true; + } + } + else if (type is PrtMapType) + { + if (!(value is PrtMapValue)) + { + return false; + } + else + { + var mapVal = (value as PrtMapValue); + foreach (var key in mapVal.keys) + { + if (!PrtInhabitsType(key, (type as PrtMapType).keyType)) + { + return false; + } + } + foreach (var val in mapVal.values) + { + if (!PrtInhabitsType(val, (type as PrtMapType).valType)) + { + return false; + } + } + + return true; + } + } + else if (type is PrtSeqType) + { + if (!(value is PrtSeqValue)) + { + return false; + } + else + { + var seqVal = (value as PrtSeqValue); + foreach (var elem in seqVal.elements) + { + if (!PrtInhabitsType(elem, (type as PrtSeqType).elemType)) + { + return false; + } + } + + return true; + } + } + else + { + Debug.Assert(false, "Unknown type"); + return false; + } + } + + public static PrtValue PrtCastValue(PrtValue value, PrtType type) + { + if (!PrtInhabitsType(value, type)) + throw new PrtInhabitsTypeException(String.Format("value {0} is not a member of type {1}", value.GetString(), type.GetString())); + return value.Clone(); + } + + } + + public class PrtNullValue : PrtValue + { + public override PrtValue Clone() + { + return this; + } + + public override string GetString() + { + return "null"; + } + + public override bool IsEqual(PrtValue value) + { + if (value is PrtNullValue) + return true; + else + return false; + } + } + + public class PrtIntValue : PrtValue + { + public int nt; + + public PrtIntValue() + { + nt = 0; + } + + public PrtIntValue(int val) + { + nt = val; + } + + public override PrtValue Clone() + { + return new PrtIntValue(this.nt); + } + + public override bool IsEqual(PrtValue val) + { + Debug.Assert(val is PrtIntValue, "Error in type checking, invalid equals invocation"); + return this.nt == (val as PrtIntValue).nt; + } + + public override string GetString() + { + return nt.ToString(); + } + } + + public class PrtBoolValue : PrtValue + { + public bool bl; + + public PrtBoolValue() + { + bl = false; + } + + public PrtBoolValue(bool val) + { + this.bl = val; + } + + public override PrtValue Clone() + { + return new PrtBoolValue(this.bl); + } + + public override bool IsEqual(PrtValue val) + { + Debug.Assert(val is PrtBoolValue, "Error in type checking, invalid equals invocation"); + return this.bl == (val as PrtBoolValue).bl; + } + + public override string GetString() + { + return bl.ToString(); + } + } + + public class PrtEventValue : PrtValue + { + public PrtEvent evt; + + public PrtEventValue(PrtEvent val) + { + this.evt = val; + } + + public override PrtValue Clone() + { + return new PrtEventValue(this.evt); + } + + public override bool IsEqual(PrtValue val) + { + Debug.Assert(val is PrtEventValue, "Error in type checking, invalid equals invocation"); + return this.evt == (val as PrtEventValue).evt; + } + + public override string GetString() + { + return evt.name; + } + } + + public class PrtMachineValue : PrtValue + { + public PrtImplMachine mach; + + public PrtMachineValue(PrtImplMachine mach) + { + this.mach = mach; + } + + public override PrtValue Clone() + { + return new PrtMachineValue(this.mach); + } + + public override bool IsEqual(PrtValue val) + { + Debug.Assert(val is PrtMachineValue, "Error in type checking, invalid equals invocation"); + return this.mach == (val as PrtMachineValue).mach; + } + + public override string GetString() + { + return String.Format("{0}({1})", mach.Name, mach.instanceNumber); + } + } + + public class PrtTupleValue : PrtValue + { + public List fieldValues; + + public PrtTupleValue() + { + fieldValues = new List(); + } + + public PrtTupleValue(PrtTupleType tupType) + { + foreach(var ft in tupType.fieldTypes) + { + fieldValues.Add(PrtMkDefaultValue(ft)); + } + } + + public PrtTupleValue(PrtTupleType tupType, params PrtValue[] elems) + { + foreach (var elem in elems) + { + fieldValues.Add(elem.Clone()); + } + } + + public override PrtValue Clone() + { + var clone = new PrtTupleValue(); + foreach (var val in fieldValues) + { + clone.fieldValues.Add(val.Clone()); + } + return clone; + } + + public override bool IsEqual(PrtValue val) + { + Debug.Assert(val is PrtTupleValue, "Error in type checking, invalid equals invocation"); + var tupValue = (val as PrtTupleValue); + Debug.Assert(tupValue.fieldValues.Count == this.fieldValues.Count, "Error in type checking, tuple sizes not equal"); + + int index = 0; + while (index < fieldValues.Count) + { + if (!this.fieldValues[index].IsEqual(tupValue.fieldValues[index])) + return false; + + index++; + } + return true; + } + + public override string GetString() + { + string retStr = "<"; + foreach (var field in fieldValues) + { + retStr = retStr + field.GetString() + ","; + } + retStr += ">"; + return retStr; + } + } + + public class PrtNamedTupleValue : PrtValue + { + public List fieldNames; + public List fieldValues; + + public PrtNamedTupleValue() + { + fieldValues = new List(); + fieldNames = new List(); + } + + public PrtNamedTupleValue(PrtNamedTupleType tupType) + { + foreach (var fn in tupType.fieldNames) + { + fieldNames.Add(fn); + } + foreach (var ft in tupType.fieldTypes) + { + fieldValues.Add(PrtMkDefaultValue(ft)); + } + } + + public PrtNamedTupleValue(PrtNamedTupleType tupType, params PrtValue[] elems) + { + foreach (var fn in tupType.fieldNames) + { + fieldNames.Add(fn); + } + foreach (var elem in elems) + { + fieldValues.Add(elem); + } + } + + public override PrtValue Clone() + { + var clone = new PrtNamedTupleValue(); + clone.fieldNames = this.fieldNames; + foreach (var val in fieldValues) + { + clone.fieldValues.Add(val.Clone()); + } + return clone; + } + + public override bool IsEqual(PrtValue val) + { + Debug.Assert(val is PrtNamedTupleValue, "Error in type checking, invalid equals invocation"); + var tup = (val as PrtNamedTupleValue); + var tupValues = tup.fieldValues; + Debug.Assert(tup.fieldValues.Count == this.fieldValues.Count, "Error in type checking, tuple sizes not equal"); + + int index = 0; + + while (index < tupValues.Count) + { + if (!this.fieldValues[index].IsEqual(tupValues[index])) + return false; + + index++; + } + return true; + } + + public override string GetString() + { + string retStr = "<"; + int index = 0; + + while (index < fieldValues.Count) + { + retStr += fieldNames[index] + ":" + fieldValues[index].GetString() + ", "; + index++; + } + retStr += ">"; + return retStr; + } + } + + public class PrtSeqValue : PrtValue + { + public List elements; + + public PrtSeqValue() + { + elements = new List(); + } + + public override PrtValue Clone() + { + var clone = new PrtSeqValue(); + foreach (var val in elements) + { + clone.elements.Add(val.Clone()); + } + + return clone; + } + + public void Insert(int index, PrtValue val) + { + //TODO: raise an exception for invalid index + elements.Insert(index, val.Clone()); + } + + public void Remove(int index) + { + //TODO: raise an exception for invalid index + elements.RemoveAt(index); + } + + public int SizeOf() + { + return elements.Count(); + } + + public override bool IsEqual(PrtValue val) + { + Debug.Assert(val is PrtSeqValue, "Error in type checking, invalid equals invocation"); + var seqVal = val as PrtSeqValue; + if (seqVal.elements.Count != this.elements.Count) + { + return false; + } + else + { + int index = 0; + while (index < this.elements.Count) + { + if (!this.elements[index].IsEqual(seqVal.elements[index])) + return false; + + index++; + } + } + return true; + } + + public override string GetString() + { + string retStr = "("; + int index = 0; + + while (index < elements.Count) + { + retStr += elements[index] + ", "; + index++; + } + retStr += ")"; + return retStr; + } + } + + public class PrtMapValue : PrtValue + { + public List keys; + public List values; + + public PrtMapValue() + { + values = new List(); + keys = new List(); + } + + public override PrtValue Clone() + { + var clone = new PrtMapValue(); + foreach (var v in values) + { + clone.values.Add(v.Clone()); + } + foreach (var k in keys) + { + clone.keys.Add(k.Clone()); + } + return clone; + } + + public int SizeOf() + { + return values.Count(); + } + + public bool Contains(PrtValue key) + { + return keys.Where(k => k.IsEqual(key)).Count() > 0; + } + + public void Add(PrtValue key, PrtValue val) + { + if (Contains(key)) + { + //TODO: raise an exception for invalid add + } + else + { + keys.Add(key.Clone()); + values.Add(val.Clone()); + } + } + + public void Remove(PrtValue key) + { + if (!Contains(key)) + { + //TODO: raise an exception for invalid remove + } + var index = keys.FindIndex((k => k.Equals(key))); + keys.RemoveAt(index); + values.RemoveAt(index); + } + + public void Update(PrtValue key, PrtValue val) + { + if (!Contains(key)) + { + //TODO: raise an exception for invalid update + } + var index = keys.FindIndex((k => k.Equals(key))); + values[index] = val.Clone(); + } + + public override bool IsEqual(PrtValue val) + { + Debug.Assert(val is PrtMapValue, "Error in type checking, invalid equals invocation"); + var mapVal = val as PrtMapValue; + if (mapVal.keys.Count != this.keys.Count) + { + return false; + } + else + { + foreach (var k in this.keys) + { + if (!mapVal.Contains(k)) + { + return false; + } + else + { + var index = this.keys.FindIndex(_k => _k.IsEqual(k)); + var _index = mapVal.keys.FindIndex(_k => _k.IsEqual(k)); + if (this.values[index].IsEqual(mapVal.values[_index])) + { + return false; + } + } + } + return true; + } + } + + public override string GetString() + { + string retStr = "("; + int index = 0; + + while (index < values.Count) + { + retStr += "(" + keys[index].GetString() + "," + values[index].GetString() + "), "; + index++; + } + retStr += ")"; + return retStr; + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `tup` last assigned on line 451 could be null and is dereferenced at line 452, column 13. + +### Severity: +ERROR + +### Procedure: +Boolean PrtNamedTupleValue.IsEqual(PrtValue) + +### File: +Src/PTester/PRuntime/PrtValue.cs + +### Key: +PrtValue.cs|IsEqual|NULL_DEREFERENCE + +### Node Key: +80a3f4fac40ce0a4f4eeae76df2cf5c1 + +### Hash: +7561e658968c2fca3b063520aec574ed + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2855/instruction.md b/inferredbugs-2855/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c94d8803a1d7b7b187c9c0b91dc4bc2bd132f96 --- /dev/null +++ b/inferredbugs-2855/instruction.md @@ -0,0 +1,588 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** P +**Bug ID:** 15 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Linq; +using System.Collections.Generic; +using System.Diagnostics; + +namespace P.Runtime +{ + public enum PrtMachineStatus + { + Enabled, // The state machine is enabled + Blocked, // The state machine is blocked on a dequeue or receive + Halted, // The state machine has halted + }; + public enum PrtNextStatemachineOperation + { + EntryOperation, + DequeueOperation, + HandleEventOperation, + ReceiveOperation + }; + public enum PrtStateExitReason + { + NotExit, + OnTransition, + OnTransitionAfterExit, + OnPopStatement, + OnGotoStatement, + OnUnhandledEvent + }; + public enum PrtDequeueReturnStatus { SUCCESS, NULL, BLOCKED }; + + public abstract class PrtImplMachine : PrtMachine + { + #region Fields + + public PrtEventBuffer eventQueue; + public HashSet receiveSet; + public int maxBufferSize; + public bool doAssume; + #endregion + + #region Clone and Undo + public PrtImplMachine Clone() + { + var clonedMachine = MakeSkeleton(); + clonedMachine.instanceNumber = this.instanceNumber; + foreach(var fd in fields) + { + clonedMachine.fields.Add(fd.Clone()); + } + clonedMachine.eventValue = this.eventValue; + clonedMachine.stateStack = this.stateStack.Clone(); + clonedMachine.invertedFunStack = this.invertedFunStack.Clone(); + clonedMachine.continuation = this.continuation.Clone(); + clonedMachine.currentTrigger = this.currentTrigger; + clonedMachine.currentPayload = this.currentPayload.Clone(); + clonedMachine.eventQueue = this.eventQueue.Clone(); + foreach(var ev in this.receiveSet) + { + clonedMachine.receiveSet.Add(ev); + } + clonedMachine.currentStatus = this.currentStatus; + clonedMachine.nextSMOperation = this.nextSMOperation; + clonedMachine.stateExitReason = this.stateExitReason; + clonedMachine.maxBufferSize = this.maxBufferSize; + clonedMachine.doAssume = this.doAssume; + clonedMachine.stateImpl = this.stateImpl; + return clonedMachine; + } + #endregion + + #region Constructor + public abstract PrtImplMachine MakeSkeleton(); + + public PrtImplMachine() : base() + { + this.maxBufferSize = 0; + this.doAssume = false; + this.eventQueue = new PrtEventBuffer(); + this.receiveSet = new HashSet(); + } + + public PrtImplMachine(StateImpl app, int maxBuff, bool assume) : base() + { + this.instanceNumber = this.NextInstanceNumber(app); + this.eventQueue = new PrtEventBuffer(); + this.receiveSet = new HashSet(); + this.maxBufferSize = maxBuff; + this.doAssume = assume; + this.stateImpl = app; + //Push the start state function on the funStack. + PrtPushState(StartState); + } + #endregion + + #region getters and setters + public abstract int NextInstanceNumber(StateImpl app); + #endregion + + #region State machine helper functions + public void PrtResetTriggerAndPayload() + { + currentTrigger = PrtValue.@null; + currentPayload = PrtValue.@null; + } + + public override void PrtEnqueueEvent(PrtValue e, PrtValue arg, PrtMachine source) + { + PrtEventValue ev = e as PrtEventValue; + if (ev.evt.name == "null") + { + throw new PrtIllegalEnqueueException("Enqueued event must not be null"); + } + PrtType prtType = ev.evt.payloadType; + + //assertion to check if argument passed inhabits the payload type. + if (prtType is PrtNullType) + { + if (!arg.Equals(PrtValue.@null)) + { + throw new PrtIllegalEnqueueException("Did not expect a payload value"); + } + } + else if (!PrtValue.PrtInhabitsType(arg, prtType)) + { + throw new PrtInhabitsTypeException(String.Format("Payload <{0}> does not match the expected type <{1}> with event <{2}>", arg.ToString(), prtType.ToString(), ev.evt.name)); + } + + if (currentStatus == PrtMachineStatus.Halted) + { + stateImpl.Trace( + @" {0}-{1} Machine has been halted and Event {2} is dropped", + this.Name, this.instanceNumber, ev.evt.name); + } + else + { + stateImpl.Trace( + @" Enqueued Event <{0}, {1}> in {2}-{3} by {4}-{5}", + ev.evt.name, arg.ToString(), this.Name, this.instanceNumber, source.Name, source.instanceNumber); + + this.eventQueue.EnqueueEvent(e, arg); + if (this.maxBufferSize != -1 && this.eventQueue.Size() > this.maxBufferSize) + { + if (this.doAssume) + { + throw new PrtAssumeFailureException(); + } + else + { + throw new PrtMaxBufferSizeExceededException( + String.Format(@" Event Buffer Size Exceeded {0} in Machine {1}-{2}", + this.maxBufferSize, this.Name, this.instanceNumber)); + } + } + if (currentStatus == PrtMachineStatus.Blocked && this.eventQueue.IsEnabled(this)) + { + currentStatus = PrtMachineStatus.Enabled; + } + } + + //Announce it to all the monitors + stateImpl.Announce(e, arg, source); + } + + public PrtDequeueReturnStatus PrtDequeueEvent(bool hasNullTransition) + { + if (eventQueue.DequeueEvent(this)) + { + if (currentStatus == PrtMachineStatus.Blocked) + { + throw new PrtInternalException("Internal error: Tyring to execute blocked machine"); + } + + stateImpl.Trace( + " Dequeued Event < {0}, {1} > at Machine {2}-{3}\n", + (currentTrigger as PrtEventValue).evt.name, currentPayload.ToString(), Name, instanceNumber); + receiveSet = new HashSet(); + return PrtDequeueReturnStatus.SUCCESS; + } + else if (hasNullTransition || receiveSet.Contains(currentTrigger)) + { + if (currentStatus == PrtMachineStatus.Blocked) + { + throw new PrtInternalException("Internal error: Tyring to execute blocked machine"); + } + stateImpl.Trace( + " Null transition taken by Machine {0}-{1}\n", + Name, instanceNumber); + currentPayload = PrtValue.@null; + currentTrigger = PrtValue.@null; + receiveSet = new HashSet(); + return PrtDequeueReturnStatus.NULL; + } + else + { + if (currentStatus == PrtMachineStatus.Blocked) + { + throw new PrtAssumeFailureException(); + } + currentStatus = PrtMachineStatus.Blocked; + if (stateImpl.Deadlock) + { + throw new PrtDeadlockException("Deadlock detected"); + } + return PrtDequeueReturnStatus.BLOCKED; + } + } + + public void PrtExecuteReceiveCase(PrtValue ev) + { + var currRecIndex = continuation.receiveIndex; + var currFun = invertedFunStack.TopOfStack.fun.receiveCases[currRecIndex][ev]; + if(currFun.IsAnonFun) + PrtPushFunStackFrame(currFun, currFun.CreateLocals(currentPayload)); + else + PrtPushFunStackFrame(currFun, currFun.CreateLocals()); + + currFun.Execute(stateImpl, this); + } + + public bool PrtIsPushTransitionPresent(PrtValue ev) + { + if (CurrentState.transitions.ContainsKey(ev)) + return CurrentState.transitions[ev].isPushTran; + else + return false; + } + + public bool PrtHasNullReceiveCase() + { + return receiveSet.Contains(PrtValue.halt); + } + #endregion + + + public void PrtRunStateMachine() + { + int numOfStepsTaken = 0; + Debug.Assert(currentStatus == PrtMachineStatus.Enabled, "Invoked PrtRunStateMachine on a blocked or a halted machine"); + + try + { + while (PrtStepStateMachine()) + { + if (numOfStepsTaken > 100000) + { + throw new PrtInfiniteRaiseLoop(); + } + numOfStepsTaken++; + } + } + catch(PrtException ex) + { + stateImpl.Exception = ex; + } + + } + + public bool PrtStepStateMachine() + { + PrtValue currEventValue; + PrtFun currAction; + bool hasMoreWork = false; + + switch(nextSMOperation) + { + case PrtNextStatemachineOperation.EntryOperation: + goto DoEntry; + case PrtNextStatemachineOperation.DequeueOperation: + goto DoDequeue; + case PrtNextStatemachineOperation.HandleEventOperation: + goto DoHandleEvent; + case PrtNextStatemachineOperation.ReceiveOperation: + goto DoReceive; + } + + DoEntry: + /* + * Note that we have made an assumption that when a state is pushed on state stack or a transition is taken (update to a state) + * the action set and deferred set is updated appropriately + */ + if(invertedFunStack.TopOfStack == null) + { + //Trace: entered state + if(CurrentState.entryFun.IsAnonFun) + PrtPushFunStackFrame(CurrentState.entryFun, CurrentState.entryFun.CreateLocals(currentPayload)); + else + PrtPushFunStackFrame(CurrentState.entryFun, CurrentState.entryFun.CreateLocals()); + } + //invoke the function + invertedFunStack.TopOfStack.fun.Execute(stateImpl, this); + goto CheckFunLastOperation; + + DoAction: + currAction = PrtFindActionHandler(eventValue); + if(currAction == PrtCommonFunctions.IgnoreFun) + { + //Trace: Performed ignore action for the event + PrtResetTriggerAndPayload(); + } + else + { + if(invertedFunStack.TopOfStack == null) + { + //Trace: executed the action handler for event + PrtPushFunStackFrame(currAction, currAction.CreateLocals(currentPayload)); + } + //invoke the action handler + invertedFunStack.TopOfStack.fun.Execute(stateImpl, this); + } + goto CheckFunLastOperation; + + CheckFunLastOperation: + if(receiveSet.Count != 0) + { + // We are at a blocking "receive"; so do receive operation + nextSMOperation = PrtNextStatemachineOperation.ReceiveOperation; + goto Finish; + + } + + switch(continuation.reason) + { + case PrtContinuationReason.Pop: + { + stateExitReason = PrtStateExitReason.OnPopStatement; + PrtExecuteExitFunction(); + goto CheckFunLastOperation; + } + case PrtContinuationReason.Goto: + { + stateExitReason = PrtStateExitReason.OnGotoStatement; + PrtExecuteExitFunction(); + goto CheckFunLastOperation; + } + case PrtContinuationReason.Raise: + { + nextSMOperation = PrtNextStatemachineOperation.HandleEventOperation; + hasMoreWork = true; + goto Finish; + } + case PrtContinuationReason.NewMachine: + { + stateExitReason = PrtStateExitReason.NotExit; + hasMoreWork = false; + goto Finish; + } + case PrtContinuationReason.Nondet: + { + stateExitReason = PrtStateExitReason.NotExit; + stateImpl.SetPendingChoicesAsBoolean(this); + continuation.nondet = ((Boolean)stateImpl.GetSelectedChoiceValue(this)); + hasMoreWork = false; + goto Finish; + } + case PrtContinuationReason.Receive: + { + stateExitReason = PrtStateExitReason.NotExit; + nextSMOperation = PrtNextStatemachineOperation.ReceiveOperation; + hasMoreWork = true; + goto Finish; + } + case PrtContinuationReason.Send: + { + stateExitReason = PrtStateExitReason.NotExit; + hasMoreWork = false; + goto Finish; + } + case PrtContinuationReason.Return: + { + switch (stateExitReason) + { + case PrtStateExitReason.NotExit: + { + nextSMOperation = PrtNextStatemachineOperation.DequeueOperation; + hasMoreWork = true; + goto Finish; + } + case PrtStateExitReason.OnPopStatement: + { + hasMoreWork = !PrtPopState(true); + nextSMOperation = PrtNextStatemachineOperation.DequeueOperation; + stateExitReason = PrtStateExitReason.NotExit; + goto Finish; + } + case PrtStateExitReason.OnGotoStatement: + { + PrtChangeState(destOfGoto); + nextSMOperation = PrtNextStatemachineOperation.EntryOperation; + stateExitReason = PrtStateExitReason.NotExit; + hasMoreWork = true; + goto Finish; + } + case PrtStateExitReason.OnUnhandledEvent: + { + hasMoreWork = !PrtPopState(false); + nextSMOperation = PrtNextStatemachineOperation.HandleEventOperation; + stateExitReason = PrtStateExitReason.NotExit; + goto Finish; + } + case PrtStateExitReason.OnTransition: + { + stateExitReason = PrtStateExitReason.OnTransitionAfterExit; + PrtExecuteTransitionFun(eventValue); + goto CheckFunLastOperation; + } + case PrtStateExitReason.OnTransitionAfterExit: + { + PrtChangeState(CurrentState.transitions[eventValue].gotoState); + stateExitReason = PrtStateExitReason.NotExit; + nextSMOperation = PrtNextStatemachineOperation.EntryOperation; + hasMoreWork = true; + goto Finish; + } + default: + { + Debug.Assert(false, "Unexpected value for exit reason"); + goto Finish; + } + } + + } + default: + { + Debug.Assert(false, "Unexpected value for continuation reason"); + goto Finish; + } + } + + DoDequeue: + Debug.Assert(receiveSet.Count == 0, "Machine cannot be blocked at receive when here"); + var dequeueStatus = PrtDequeueEvent(CurrentState.hasNullTransition); + if(dequeueStatus == PrtDequeueReturnStatus.BLOCKED) + { + nextSMOperation = PrtNextStatemachineOperation.DequeueOperation; + hasMoreWork = false; + goto Finish; + + } + else if (dequeueStatus == PrtDequeueReturnStatus.SUCCESS) + { + nextSMOperation = PrtNextStatemachineOperation.HandleEventOperation; + hasMoreWork = true; + goto Finish; + } + else // NULL transition + { + nextSMOperation = PrtNextStatemachineOperation.HandleEventOperation; + hasMoreWork = false; + goto Finish; + } + + + DoHandleEvent: + Debug.Assert(receiveSet.Count == 0, "The machine must not be blocked on a receive"); + if(!currentTrigger.Equals(PrtValue.@null)) + { + currEventValue = currentTrigger; + currentTrigger = PrtValue.@null; + } + else + { + currEventValue = eventValue; + } + + if(PrtIsPushTransitionPresent(currEventValue)) + { + PrtPushState(CurrentState.transitions[currEventValue].gotoState); + goto DoEntry; + } + else if(PrtIsTransitionPresent(currEventValue)) + { + stateExitReason = PrtStateExitReason.OnTransition; + eventValue = currEventValue; + PrtExecuteExitFunction(); + goto CheckFunLastOperation; + } + else if(PrtIsActionInstalled(currEventValue)) + { + goto DoAction; + } + else + { + stateExitReason = PrtStateExitReason.OnUnhandledEvent; + eventValue = currEventValue; + PrtExecuteExitFunction(); + goto CheckFunLastOperation; + } + + DoReceive: + Debug.Assert(receiveSet.Count == 0 && PrtHasNullReceiveCase(), "Receive set empty and at receive !!"); + if(receiveSet.Count == 0) + { + stateExitReason = PrtStateExitReason.NotExit; + PrtExecuteReceiveCase(PrtValue.@null); + goto CheckFunLastOperation; + } + dequeueStatus = PrtDequeueEvent(false); + if (dequeueStatus == PrtDequeueReturnStatus.BLOCKED) + { + nextSMOperation = PrtNextStatemachineOperation.ReceiveOperation; + hasMoreWork = false; + goto Finish; + + } + else if (dequeueStatus == PrtDequeueReturnStatus.SUCCESS) + { + stateExitReason = PrtStateExitReason.NotExit; + PrtExecuteReceiveCase(currentTrigger); + goto CheckFunLastOperation; + } + else // NULL case + { + nextSMOperation = PrtNextStatemachineOperation.ReceiveOperation; + hasMoreWork = false; + goto Finish; + } + + Finish: + Debug.Assert(!hasMoreWork || currentStatus == PrtMachineStatus.Enabled, "hasMoreWork is true but the statemachine is blocked"); + return hasMoreWork; + + } + + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `ev` last assigned on line 109 could be null and is dereferenced at line 110, column 13. + +### Severity: +ERROR + +### Procedure: +Void PrtImplMachine.PrtEnqueueEvent(PrtValue,PrtValue,PrtMachine) + +### File: +Src/PTester/PRuntime/PrtImplMachine.cs + +### Key: +PrtImplMachine.cs|PrtEnqueueEvent|NULL_DEREFERENCE + +### Node Key: +df8f2a64f2f49e1bc05729fd4440eed4 + +### Hash: +2295a870af592b757de09e09d5419138 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2862/instruction.md b/inferredbugs-2862/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5a742701cde7a20e8cfc1fe62ac8784c4eeb4d8b --- /dev/null +++ b/inferredbugs-2862/instruction.md @@ -0,0 +1,144 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** P +**Bug ID:** 22 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; +using Microsoft.Pc.TypeChecker; +using Microsoft.Pc.TypeChecker.AST; + +namespace Microsoft.Pc.Backend +{ + public class PrtCodeGenerator : ICodeGenerator + { + public IReadOnlyList GenerateCode(ITranslationErrorHandler handler, ICompilerOutput log, string projectName, + Scope globalScope) + { + // Manages job-specific state so that jobs can be parallelized + var context = new CompilationContext(projectName); + + // Create header and source files. + var cHeader = new CompiledFile($"{projectName}.h"); + var cSource = new CompiledFile($"{projectName}.c"); + + // Write the header file + WriteGenericHeader(context, cHeader.Stream); + + foreach (IPDecl decl in globalScope.AllDecls) + { + WriteForwardDeclaration(context, cHeader.Stream, decl); + } + + WriteGenericFooter(context, cHeader.Stream); + + // TODO: write the source + + // All done! Return the compiled files. + return new List {cHeader, cSource}; + } + + #region Header writing routines + + private static void WriteGenericHeader(CompilationContext context, TextWriter output) + { + string includeGuardMacro = $"P_{Regex.Replace(context.ProjectName.ToUpperInvariant(), @"\s+", "")}_H_"; + output.WriteLine("#pragma once"); + output.WriteLine($"#ifndef {includeGuardMacro}"); + output.WriteLine($"#define {includeGuardMacro}"); + output.WriteLine("#include \"Prt.h\""); + output.WriteLine(); + output.WriteLine("#ifdef __cplusplus"); + output.WriteLine("extern \"C\" {"); + output.WriteLine("#endif"); + output.WriteLine(); + } + + private static void WriteForwardDeclaration(CompilationContext context, TextWriter output, IPDecl decl) + { + string declName = context.Names.GetNameForNode(decl); + output.WriteLine($"DECL({decl.GetType().Name}, {decl.Name}) => {declName}"); + } + + private static void WriteGenericFooter(CompilationContext context, TextWriter output) + { + string includeGuardMacro = $"P_{Regex.Replace(context.ProjectName.ToUpperInvariant(), @"\s+", "")}_H_"; + output.WriteLine(); + output.WriteLine("#ifdef __cplusplus"); + output.WriteLine("}"); + output.WriteLine("#endif"); + output.WriteLine(); + output.WriteLine($"#endif // {includeGuardMacro}"); + } + + #endregion + + private class CompilationContext + { + public string ProjectName { get; } + public NameManager Names { get; } + public int IndentationLevel { get; set; } = 0; + + public CompilationContext(string projectName) + { + ProjectName = projectName; + Names = new NameManager($"P_{projectName.ToUpperInvariant()}_"); + } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource cSource.Microsoft.Pc.Backend.CompiledFile.k__BackingField of type System.IO.StringWriter, Leaked resource cHeader.Microsoft.Pc.Backend.CompiledFile.k__BackingField of type System.IO.StringWriter in method "IReadOnlyList`1 PrtCodeGenerator.GenerateCode(ITranslationErrorHandler,ICompilerOutput,String,Scope)". + +### Severity: +ERROR + +### Procedure: +IReadOnlyList`1 PrtCodeGenerator.GenerateCode(ITranslationErrorHandler,ICompilerOutput,String,Scope) + +### File: +Src/Pc/CompilerCore/Backend/PrtCodeGenerator.cs + +### Key: +PrtCodeGenerator.cs|GenerateCode|DOTNET_RESOURCE_LEAK + +### Hash: +dbbd8a934d1504613b454a9eb5e64102 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2863/instruction.md b/inferredbugs-2863/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..017d28eb6bc2d9d41962c5aaa8710804d4848d8a --- /dev/null +++ b/inferredbugs-2863/instruction.md @@ -0,0 +1,141 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Buildalyzer +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Buildalyzer; +using Microsoft.Build.Evaluation; +using Microsoft.Build.Execution; +using Microsoft.Extensions.Logging; +using NUnit.Framework; +using Shouldly; + +namespace NetCoreTests +{ + [TestFixture] + public class NetCoreTestFixture + { + private static string[] _projectFiles = + { + @"LegacyFrameworkProject\LegacyFrameworkProject.csproj", + @"SdkNetCoreProject\SdkNetCoreProject.csproj", + @"SdkNetStandardProject\SdkNetStandardProject.csproj" + }; + + [TestCaseSource(nameof(_projectFiles))] + public void LoadsProject(string projectFile) + { + // Given + StringBuilder log = new StringBuilder(); + ProjectAnalyzer analyzer = GetProjectAnalyzer(projectFile, log); + + // When + Project project = analyzer.Load(); + + // Then + project.ShouldNotBeNull(log.ToString()); + } + + [TestCaseSource(nameof(_projectFiles))] + public void CompilesProject(string projectFile) + { + // Given + StringBuilder log = new StringBuilder(); + ProjectAnalyzer analyzer = GetProjectAnalyzer(projectFile, log); + + // When + ProjectInstance projectInstance = analyzer.Compile(); + + // Then + projectInstance.ShouldNotBeNull(log.ToString()); + } + + [TestCaseSource(nameof(_projectFiles))] + public void GetsSourceFiles(string projectFile) + { + // Given + StringBuilder log = new StringBuilder(); + ProjectAnalyzer analyzer = GetProjectAnalyzer(projectFile, log); + + // When + IReadOnlyList sourceFiles = analyzer.GetSourceFiles(); + + // Then + sourceFiles.ShouldContain(x => x.EndsWith("Class1.cs")); + } + + private ProjectAnalyzer GetProjectAnalyzer(string projectFile, StringBuilder log) + { + string projectPath = Path.GetFullPath( + Path.Combine( + Path.GetDirectoryName(typeof(NetCoreTestFixture).Assembly.Location), + @"..\..\..\..\" + projectFile)); + LoggerFactory loggerFactory = null; + if (log != null) + { + loggerFactory = new LoggerFactory(); + loggerFactory.AddProvider(new StringBuilderLoggerProvider(log)); + } + Analyzer analyzer = new Analyzer(loggerFactory); + return analyzer.GetProject(projectPath); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Buildalyzer.StringBuilderLoggerProvider::.ctor() at Line 76) of type Buildalyzer.StringBuilderLoggerProvider in method "ProjectAnalyzer NetCoreTestFixture.GetProjectAnalyzer(String,StringBuilder)". + +### Severity: +ERROR + +### Procedure: +ProjectAnalyzer NetCoreTestFixture.GetProjectAnalyzer(String,StringBuilder) + +### File: +NetCoreTests/NetCoreTestFixture.cs + +### Key: +NetCoreTestFixture.cs|GetProjectAnalyzer|DOTNET_RESOURCE_LEAK + +### Hash: +a7893522692f65ea11832d8fc11fad1a + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2864/instruction.md b/inferredbugs-2864/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..00c079c4c7a2d72eab9af3eef1d7b72ddda55e6a --- /dev/null +++ b/inferredbugs-2864/instruction.md @@ -0,0 +1,271 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Buildalyzer +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Buildalyzer.Environment; +using LibGit2Sharp; +using Microsoft.Build.Construction; +using Microsoft.Build.Framework; +using NUnit.Framework; +using Shouldly; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; + +namespace Buildalyzer.Tests.Integration +{ + [TestFixture] + [NonParallelizable] + public class OpenSourceProjectsFixture + { + private const LoggerVerbosity Verbosity = LoggerVerbosity.Normal; + private const bool BinaryLog = false; + + private static EnvironmentPreference[] Preferences = + { +#if Is_Windows + EnvironmentPreference.Framework, +#endif + EnvironmentPreference.Core + }; + + private static TestRepository[] Repositories = + { + new TestRepository("https://github.com/autofac/Autofac.git"), + new TestRepository("https://github.com/AutoMapper/AutoMapper.git"), + new TestRepository(EnvironmentPreference.Framework, "https://github.com/JamesNK/Newtonsoft.Json.git"), // Contains portable project, can't build using SDK + new TestRepository("https://github.com/nodatime/nodatime.git", + @"\src\NodaTime.Web.Blazor\NodaTime.Web.Blazor.csproj"), + new TestRepository(EnvironmentPreference.Framework, "https://github.com/serilog/serilog.git"), // SourceLink messed up from AppVeyor on SDK: "SourceLink.Create.CommandLine.dll. Assembly with same name is already loaded Confirm that the declaration is correct" + new TestRepository("https://github.com/cake-build/cake"), + new TestRepository("https://github.com/Wyamio/Wyam.git"), + }; + + public class TestRepository + { + public EnvironmentPreference? Preference { get; } + + public string Url { get; } + + public string[] Excluded { get; } + + public TestRepository(string url, params string[] excluded) + : this(null, url, excluded) + { + } + + public TestRepository(EnvironmentPreference? preference, string url, params string[] excluded) + { + Preference = preference; + Url = url; + Excluded = excluded ?? Array.Empty(); + } + + public override string ToString() => Url; + } + + private static List ProjectTestCases = new List(); + + // Do setup in a static constructor since the TestCaseSource depends on it + // See https://stackoverflow.com/a/40507964/807064 + static OpenSourceProjectsFixture() + { + foreach (TestRepository repository in Repositories) + { + string path = GetRepositoryPath(repository.Url); + CloneRepository(repository.Url, path); + } + + // Iterate all repositories + foreach (TestRepository repository in Repositories) + { + // Iterate all available preferences + foreach (EnvironmentPreference preference in Preferences) + { + // Only build the desired preferences + if (!repository.Preference.HasValue || repository.Preference.Value == preference) + { + // Iterate all solution files in the repository + foreach (string solutionPath in + Directory.EnumerateFiles(GetRepositoryPath(repository.Url), "*.sln", SearchOption.AllDirectories)) + { + // Exclude any solution files we don't want to build + if (!repository.Excluded.Any(x => solutionPath.EndsWith(x))) + { + // Get all the projects in this solution + SolutionFile solutionFile = SolutionFile.Parse(solutionPath); + foreach (string projectPath in + solutionFile.ProjectsInOrder + .Where(x => AnalyzerManager.SupportedProjectTypes.Contains(x.ProjectType)) + .Select(x => x.AbsolutePath)) + { + // Exclude any project files we don't want to build + if (!repository.Excluded.Any(x => projectPath.EndsWith(x))) + { + ProjectTestCases.Add(new object[] + { + preference, + solutionPath, + projectPath + }); + } + } + } + } + } + } + } + } + + [TestCaseSource(nameof(ProjectTestCases))] + public void CompilesProject(EnvironmentPreference preference, string solutionPath, string projectPath) + { + // Given + StringWriter log = new StringWriter(); + AnalyzerManager manager = new AnalyzerManager(solutionPath, new AnalyzerManagerOptions + { + LogWriter = log + }); + ProjectAnalyzer analyzer = manager.GetProject(projectPath); + EnvironmentOptions options = new EnvironmentOptions + { + Preference = preference + }; + + // Set some enviornment variables to make it seem like we're not in a CI build + // Sometimes this messes up libraries like SourceLink since we're building as part of a test and not for CI + options.EnvironmentVariables.Add("APPVEYOR", "False"); + options.EnvironmentVariables.Add("ContinuousIntegrationBuild", null); + options.EnvironmentVariables.Add("CI", "False"); + options.EnvironmentVariables.Add("CI_LINUX", "False"); + options.EnvironmentVariables.Add("CI_WINDOWS", "False"); + + // When + DeleteProjectDirectory(analyzer.ProjectFile.Path, "obj"); + DeleteProjectDirectory(analyzer.ProjectFile.Path, "bin"); + analyzer.IgnoreFaultyImports = false; + +#pragma warning disable 0162 + if (BinaryLog) + { + analyzer.AddBinaryLogger($@"E:\Temp\{Path.GetFileNameWithoutExtension(solutionPath)}.{Path.GetFileNameWithoutExtension(analyzer.ProjectFile.Path)}.core.binlog"); + } +#pragma warning restore 0162 + + AnalyzerResults results = analyzer.Build(options); + + // Then + results.Count.ShouldBeGreaterThan(0, log.ToString()); + results.OverallSuccess.ShouldBeTrue(log.ToString()); + results.ShouldAllBe(x => x.Succeeded, log.ToString()); + } + + private static void CloneRepository(string repository, string path) + { + if (!Directory.Exists(path)) + { + TestContext.Progress.WriteLine($"Cloning { path }"); + Directory.CreateDirectory(path); + string clonedPath = Repository.Clone(repository, path); + TestContext.Progress.WriteLine($"Cloned into { clonedPath }"); + } + else if (!Repository.IsValid(path)) + { + TestContext.Progress.WriteLine($"Recloning { path }"); + Directory.Delete(path, true); + Thread.Sleep(1000); + Directory.CreateDirectory(path); + string clonedPath = Repository.Clone(repository, path); + TestContext.Progress.WriteLine($"Cloned into { clonedPath }"); + } + else + { + TestContext.Progress.WriteLine($"Updating { path }"); + Repository repo = new Repository(path); + foreach (Remote remote in repo.Network.Remotes) + { + IEnumerable refSpecs = remote.FetchRefSpecs.Select(x => x.Specification); + Commands.Fetch(repo, remote.Name, refSpecs, null, string.Empty); + } + } + } + + private static string GetRepositoryPath(string repository) + { + string path = Path.GetFullPath( + Path.Combine( + Path.GetDirectoryName(typeof(OpenSourceProjectsFixture).Assembly.Location), + @"..\..\..\..\repos\" + Path.GetFileNameWithoutExtension(repository))); + + return path.Replace('\\', Path.DirectorySeparatorChar); + } + + private static void DeleteProjectDirectory(string projectPath, string directory) + { + string path = Path.Combine(Path.GetDirectoryName(projectPath), directory); + if (Directory.Exists(path)) + { + Directory.Delete(path, true); + } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource log of type System.IO.StringWriter in method "Void OpenSourceProjectsFixture.CompilesProject(EnvironmentPreference,String,String)". + +### Severity: +ERROR + +### Procedure: +Void OpenSourceProjectsFixture.CompilesProject(EnvironmentPreference,String,String) + +### File: +tests/Buildalyzer.Tests/Integration/OpenSourceProjectsFixture.cs + +### Key: +OpenSourceProjectsFixture.cs|CompilesProject|DOTNET_RESOURCE_LEAK + +### Hash: +4097356181d27ecc7162b30ae2c3dbae + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2865/instruction.md b/inferredbugs-2865/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..40210460f406e71606ab6a012ed65e0d61758488 --- /dev/null +++ b/inferredbugs-2865/instruction.md @@ -0,0 +1,165 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Buildalyzer +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Buildalyzer; +using LibGit2Sharp; +using Microsoft.Build.Execution; +using Microsoft.Build.Framework; +using NUnit.Framework; +using Shouldly; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace NetCoreIntegrationTests +{ + [TestFixture] + public class NetCoreIntegrationTestFixture + { + private const LoggerVerbosity Verbosity = LoggerVerbosity.Normal; + private const bool BinaryLog = true; + + private static string[] _repositories = + { + // "https://github.com/AngleSharp/AngleSharp.git", contains portable project, can't build + "https://github.com/autofac/Autofac.git", + "https://github.com/AutoMapper/AutoMapper.git", + //"https://github.com/MarimerLLC/csla.git", contains portable project, can't build + "https://github.com/SixLabors/ImageSharp.git", + "https://github.com/moq/moq.git", + "https://github.com/JamesNK/Newtonsoft.Json.git", + "https://github.com/nodatime/nodatime.git", + "https://github.com/JasonBock/Rocks.git", + "https://github.com/dotnet/roslyn.git", + "https://github.com/Reactive-Extensions/Rx.NET.git", + "https://github.com/serilog/serilog.git", + "https://github.com/Abc-Arbitrage/ZeroLog.git", + "https://github.com/cake-build/cake" + }; + + [TestCaseSource(nameof(_repositories))] + public void CompilesProject(string repository) + { + // Given + string solutionFile = CloneOrFetchRepository(repository); + StringWriter log = new StringWriter(); + AnalyzerManager manager = new AnalyzerManager(solutionFile, new AnalyzerManagerOptions + { + LogWriter = log, + LoggerVerbosity = Verbosity + }); + + foreach (ProjectAnalyzer analyzer in manager.Projects.Values) + { + // When + Console.WriteLine(analyzer.ProjectFile.Path); + if (BinaryLog) + { + analyzer.AddBinaryLogger(Path.Combine(@"E:\Temp\", Path.ChangeExtension(Path.GetFileName(analyzer.ProjectFile.Path), ".integration.core.binlog"))); + } + AnalyzerResults results = analyzer.Build(); + + // Then + results.Count.ShouldBeGreaterThan(0, log.ToString()); + results.First().OverallSuccess.ShouldBeTrue(log.ToString()); + results.First().ProjectInstance.ShouldNotBeNull(log.ToString()); + results.First().GetSourceFiles().Count.ShouldBeGreaterThan(0); + } + } + + private static ProjectAnalyzer GetProjectAnalyzer(string projectFile, StringWriter log) => + new AnalyzerManager(new AnalyzerManagerOptions + { + LogWriter = log + }) + .GetProject(projectFile); + + private static string CloneOrFetchRepository(string repository) + { + string path = GetRepositoryPath(repository); + if(!Directory.Exists(path)) + { + Directory.CreateDirectory(path); + Repository.Clone(repository, path); + } + else + { + Repository repo = new Repository(path); + foreach(Remote remote in repo.Network.Remotes) + { + IEnumerable refSpecs = remote.FetchRefSpecs.Select(x => x.Specification); + Commands.Fetch(repo, remote.Name, refSpecs, null, string.Empty); + } + } + return Directory.GetFiles(path, "*.sln", SearchOption.AllDirectories)[0]; + } + + private static string GetRepositoryPath(string repository) + { + string path = Path.GetFullPath( + Path.Combine( + Path.GetDirectoryName(typeof(NetCoreIntegrationTestFixture).Assembly.Location), + @"..\..\..\..\repos\" + Path.GetFileNameWithoutExtension(repository))); + + return path.Replace('\\', Path.DirectorySeparatorChar); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource log of type System.IO.StringWriter in method "Void NetCoreIntegrationTestFixture.CompilesProject(String)". + +### Severity: +ERROR + +### Procedure: +Void NetCoreIntegrationTestFixture.CompilesProject(String) + +### File: +tests/NetCoreIntegrationTests/NetCoreIntegrationTestFixture.cs + +### Key: +NetCoreIntegrationTestFixture.cs|CompilesProject|DOTNET_RESOURCE_LEAK + +### Hash: +d04e050dd6dc854fc3dac4117a246759 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2890/instruction.md b/inferredbugs-2890/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..96c3124ec39b842e168f72e93739928307edb33d --- /dev/null +++ b/inferredbugs-2890/instruction.md @@ -0,0 +1,712 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Industrial-IoT +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp + +using Opc.Ua; +using Opc.Ua.Server; +using System; +using System.Collections.Generic; + +namespace OpcPublisher +{ + using Newtonsoft.Json; + using System.Linq; + using System.Net; + using static OpcApplicationConfiguration; + using static OpcPublisher.Program; + using static PublisherNodeConfiguration; + + public class PublisherNodeManager : CustomNodeManager2 + { + public PublisherNodeManager(Opc.Ua.Server.IServerInternal server, ApplicationConfiguration configuration) + : base(server, configuration, Namespaces.PublisherApplications) + { + SystemContext.NodeIdFactory = this; + } + + /// + /// Creates the NodeId for the specified node. + /// + public override NodeId New(ISystemContext context, NodeState node) + { + BaseInstanceState instance = node as BaseInstanceState; + + if (instance != null && instance.Parent != null) + { + string id = instance.Parent.NodeId.Identifier as string; + + if (id != null) + { + return new NodeId(id + "_" + instance.SymbolicName, instance.Parent.NodeId.NamespaceIndex); + } + } + + return node.NodeId; + } + + /// + /// Creates a new folder. + /// + private FolderState CreateFolder(NodeState parent, string path, string name) + { + FolderState folder = new FolderState(parent) + { + SymbolicName = name, + ReferenceTypeId = ReferenceTypes.Organizes, + TypeDefinitionId = ObjectTypeIds.FolderType, + NodeId = new NodeId(path, NamespaceIndex), + BrowseName = new QualifiedName(path, NamespaceIndex), + DisplayName = new LocalizedText("en", name), + WriteMask = AttributeWriteMask.None, + UserWriteMask = AttributeWriteMask.None, + EventNotifier = EventNotifiers.None + }; + + if (parent != null) + { + parent.AddChild(folder); + } + + return folder; + } + + + /// + /// Does any initialization required before the address space can be used. + /// + /// + /// The externalReferences is an out parameter that allows the node manager to link to nodes + /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and + /// should have a reference to the root folder node(s) exposed by this node manager. + /// + public override void CreateAddressSpace(IDictionary> externalReferences) + { + lock (Lock) + { + IList references = null; + + if (!externalReferences.TryGetValue(ObjectIds.ObjectsFolder, out references)) + { + externalReferences[ObjectIds.ObjectsFolder] = references = new List(); + } + + FolderState root = CreateFolder(null, "OpcPublisher", "OpcPublisher"); + root.AddReference(ReferenceTypes.Organizes, true, ObjectIds.ObjectsFolder); + references.Add(new NodeStateReference(ReferenceTypes.Organizes, false, root.NodeId)); + root.EventNotifier = EventNotifiers.SubscribeToEvents; + AddRootNotifier(root); + + List variables = new List(); + + try + { + FolderState dataFolder = CreateFolder(root, "Data", "Data"); + + const string connectionStringItemName = "ConnectionString"; + DataItemState item = CreateDataItemVariable(dataFolder, connectionStringItemName, connectionStringItemName, BuiltInType.String, ValueRanks.Scalar, AccessLevels.CurrentWrite); + item.Value = String.Empty; + + FolderState methodsFolder = CreateFolder(root, "Methods", "Methods"); + + MethodState publishNodeMethod = CreateMethod(methodsFolder, "PublishNode", "PublishNode"); + SetPublishNodeMethodProperties(ref publishNodeMethod); + + MethodState unpublishNodeMethod = CreateMethod(methodsFolder, "UnpublishNode", "UnpublishNode"); + SetUnpublishNodeMethodProperties(ref unpublishNodeMethod); + + MethodState getPublishedNodesLegacyMethod = CreateMethod(methodsFolder, "GetPublishedNodes", "GetPublishedNodes"); + SetGetPublishedNodesLegacyMethodProperties(ref getPublishedNodesLegacyMethod); + } + catch (Exception e) + { + Utils.Trace(e, "Error creating the address space."); + } + + AddPredefinedNode(SystemContext, root); + } + } + + /// + /// Sets properties of the PublishNode method. + /// + private void SetPublishNodeMethodProperties(ref MethodState method) + { + // define input arguments + method.InputArguments = new PropertyState(method) + { + NodeId = new NodeId(method.BrowseName.Name + "InArgs", NamespaceIndex), + BrowseName = BrowseNames.InputArguments + }; + method.InputArguments.DisplayName = method.InputArguments.BrowseName.Name; + method.InputArguments.TypeDefinitionId = VariableTypeIds.PropertyType; + method.InputArguments.ReferenceTypeId = ReferenceTypeIds.HasProperty; + method.InputArguments.DataType = DataTypeIds.Argument; + method.InputArguments.ValueRank = ValueRanks.OneDimension; + + method.InputArguments.Value = new Argument[] + { + new Argument() { Name = "NodeId", Description = "NodeId of the node to publish in NodeId format.", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar }, + new Argument() { Name = "EndpointUrl", Description = "Endpoint URI of the OPC UA server owning the node.", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } + }; + + method.OnCallMethod = new GenericMethodCalledEventHandler(OnPublishNodeCall); + } + + /// + /// Sets properies of the UnpublishNode method. + /// + private void SetUnpublishNodeMethodProperties(ref MethodState method) + { + // define input arguments + method.InputArguments = new PropertyState(method) + { + NodeId = new NodeId(method.BrowseName.Name + "InArgs", NamespaceIndex), + BrowseName = BrowseNames.InputArguments + }; + method.InputArguments.DisplayName = method.InputArguments.BrowseName.Name; + method.InputArguments.TypeDefinitionId = VariableTypeIds.PropertyType; + method.InputArguments.ReferenceTypeId = ReferenceTypeIds.HasProperty; + method.InputArguments.DataType = DataTypeIds.Argument; + method.InputArguments.ValueRank = ValueRanks.OneDimension; + + method.InputArguments.Value = new Argument[] + { + new Argument() { Name = "NodeId", Description = "NodeId of the node to publish in NodeId format.", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar }, + new Argument() { Name = "EndpointUrl", Description = "Endpoint URI of the OPC UA server owning the node.", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar }, + }; + + method.OnCallMethod = new GenericMethodCalledEventHandler(OnUnpublishNodeCall); + } + + /// + /// Sets properies of the GetPublishedNodes method, which is only there for backward compatibility. + /// This method is acutally returning the configured nodes in NodeId syntax. + /// + private void SetGetPublishedNodesLegacyMethodProperties(ref MethodState method) + { + // define input arguments + method.InputArguments = new PropertyState(method) + { + NodeId = new NodeId(method.BrowseName.Name + "InArgs", NamespaceIndex), + BrowseName = BrowseNames.InputArguments + }; + method.InputArguments.DisplayName = method.InputArguments.BrowseName.Name; + method.InputArguments.TypeDefinitionId = VariableTypeIds.PropertyType; + method.InputArguments.ReferenceTypeId = ReferenceTypeIds.HasProperty; + method.InputArguments.DataType = DataTypeIds.Argument; + method.InputArguments.ValueRank = ValueRanks.OneDimension; + + method.InputArguments.Value = new Argument[] + { + new Argument() { Name = "EndpointUrl", Description = "Endpoint URI of the OPC UA server to return the published nodes for.", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } + }; + + // set output arguments + method.OutputArguments = new PropertyState(method) + { + NodeId = new NodeId(method.BrowseName.Name + "OutArgs", NamespaceIndex), + BrowseName = BrowseNames.OutputArguments + }; + method.OutputArguments.DisplayName = method.OutputArguments.BrowseName.Name; + method.OutputArguments.TypeDefinitionId = VariableTypeIds.PropertyType; + method.OutputArguments.ReferenceTypeId = ReferenceTypeIds.HasProperty; + method.OutputArguments.DataType = DataTypeIds.Argument; + method.OutputArguments.ValueRank = ValueRanks.OneDimension; + + method.OutputArguments.Value = new Argument[] + { + new Argument() { Name = "Published nodes", Description = "List of the nodes configured to publish in OPC Publisher in NodeId format", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } + }; + method.OnCallMethod = new GenericMethodCalledEventHandler(OnGetPublishedNodesLegacyCall); + } + + /// + /// Creates a new variable. + /// + private DataItemState CreateDataItemVariable(NodeState parent, string path, string name, BuiltInType dataType, int valueRank, byte accessLevel) + { + DataItemState variable = new DataItemState(parent); + variable.ValuePrecision = new PropertyState(variable); + variable.Definition = new PropertyState(variable); + + variable.Create( + SystemContext, + null, + variable.BrowseName, + null, + true); + + variable.SymbolicName = name; + variable.ReferenceTypeId = ReferenceTypes.Organizes; + variable.NodeId = new NodeId(path, NamespaceIndex); + variable.BrowseName = new QualifiedName(path, NamespaceIndex); + variable.DisplayName = new LocalizedText("en", name); + variable.WriteMask = AttributeWriteMask.None; + variable.UserWriteMask = AttributeWriteMask.None; + variable.DataType = (uint)dataType; + variable.ValueRank = valueRank; + variable.AccessLevel = accessLevel; + variable.UserAccessLevel = AccessLevels.CurrentReadOrWrite; + variable.Historizing = false; + variable.Value = Opc.Ua.TypeInfo.GetDefaultValue((uint)dataType, valueRank, Server.TypeTree); + variable.StatusCode = StatusCodes.Good; + variable.Timestamp = DateTime.UtcNow; + + if (valueRank == ValueRanks.OneDimension) + { + variable.ArrayDimensions = new ReadOnlyList(new List { 0 }); + } + else if (valueRank == ValueRanks.TwoDimensions) + { + variable.ArrayDimensions = new ReadOnlyList(new List { 0, 0 }); + } + + variable.ValuePrecision.Value = 2; + variable.ValuePrecision.AccessLevel = AccessLevels.CurrentReadOrWrite; + variable.ValuePrecision.UserAccessLevel = AccessLevels.CurrentReadOrWrite; + variable.Definition.Value = String.Empty; + variable.Definition.AccessLevel = AccessLevels.CurrentReadOrWrite; + variable.Definition.UserAccessLevel = AccessLevels.CurrentReadOrWrite; + + if (parent != null) + { + parent.AddChild(variable); + } + + return variable; + } + + /// + /// Creates a new variable using type Numeric as NodeId. + /// + private DataItemState CreateDataItemVariable(NodeState parent, uint id, string name, BuiltInType dataType, int valueRank, byte accessLevel) + { + DataItemState variable = new DataItemState(parent); + variable.ValuePrecision = new PropertyState(variable); + variable.Definition = new PropertyState(variable); + + variable.Create( + SystemContext, + null, + variable.BrowseName, + null, + true); + + variable.SymbolicName = name; + variable.ReferenceTypeId = ReferenceTypes.Organizes; + variable.NodeId = new NodeId(id, NamespaceIndex); + variable.BrowseName = new QualifiedName(name, NamespaceIndex); + variable.DisplayName = new LocalizedText("en", name); + variable.WriteMask = AttributeWriteMask.None; + variable.UserWriteMask = AttributeWriteMask.None; + variable.DataType = (uint)dataType; + variable.ValueRank = valueRank; + variable.AccessLevel = accessLevel; + variable.UserAccessLevel = AccessLevels.CurrentReadOrWrite; + variable.Historizing = false; + variable.Value = Opc.Ua.TypeInfo.GetDefaultValue((uint)dataType, valueRank, Server.TypeTree); + variable.StatusCode = StatusCodes.Good; + variable.Timestamp = DateTime.UtcNow; + + if (valueRank == ValueRanks.OneDimension) + { + variable.ArrayDimensions = new ReadOnlyList(new List { 0 }); + } + else if (valueRank == ValueRanks.TwoDimensions) + { + variable.ArrayDimensions = new ReadOnlyList(new List { 0, 0 }); + } + + variable.ValuePrecision.Value = 2; + variable.ValuePrecision.AccessLevel = AccessLevels.CurrentReadOrWrite; + variable.ValuePrecision.UserAccessLevel = AccessLevels.CurrentReadOrWrite; + variable.Definition.Value = String.Empty; + variable.Definition.AccessLevel = AccessLevels.CurrentReadOrWrite; + variable.Definition.UserAccessLevel = AccessLevels.CurrentReadOrWrite; + + if (parent != null) + { + parent.AddChild(variable); + } + + return variable; + } + + /// + /// Creates a new variable. + /// + private BaseDataVariableState CreateVariable(NodeState parent, string path, string name, NodeId dataType, int valueRank) + { + BaseDataVariableState variable = new BaseDataVariableState(parent) + { + SymbolicName = name, + ReferenceTypeId = ReferenceTypes.Organizes, + TypeDefinitionId = VariableTypeIds.BaseDataVariableType, + NodeId = new NodeId(path, NamespaceIndex), + BrowseName = new QualifiedName(path, NamespaceIndex), + DisplayName = new LocalizedText("en", name), + WriteMask = AttributeWriteMask.DisplayName | AttributeWriteMask.Description, + UserWriteMask = AttributeWriteMask.DisplayName | AttributeWriteMask.Description, + DataType = dataType, + ValueRank = valueRank, + AccessLevel = AccessLevels.CurrentReadOrWrite, + UserAccessLevel = AccessLevels.CurrentReadOrWrite, + Historizing = false, + StatusCode = StatusCodes.Good, + Timestamp = DateTime.UtcNow + }; + + if (valueRank == ValueRanks.OneDimension) + { + variable.ArrayDimensions = new ReadOnlyList(new List { 0 }); + } + else if (valueRank == ValueRanks.TwoDimensions) + { + variable.ArrayDimensions = new ReadOnlyList(new List { 0, 0 }); + } + + if (parent != null) + { + parent.AddChild(variable); + } + + return variable; + } + + /// + /// Creates a new method. + /// + private MethodState CreateMethod(NodeState parent, string path, string name) + { + MethodState method = new MethodState(parent) + { + SymbolicName = name, + ReferenceTypeId = ReferenceTypeIds.HasComponent, + NodeId = new NodeId(path, NamespaceIndex), + BrowseName = new QualifiedName(path, NamespaceIndex), + DisplayName = new LocalizedText("en", name), + WriteMask = AttributeWriteMask.None, + UserWriteMask = AttributeWriteMask.None, + Executable = true, + UserExecutable = true + }; + + if (parent != null) + { + parent.AddChild(method); + } + + return method; + } + + /// + /// Creates a new method using type Numeric for the NodeId. + /// + private MethodState CreateMethod(NodeState parent, uint id, string name) + { + MethodState method = new MethodState(parent) + { + SymbolicName = name, + ReferenceTypeId = ReferenceTypeIds.HasComponent, + NodeId = new NodeId(id, NamespaceIndex), + BrowseName = new QualifiedName(name, NamespaceIndex), + DisplayName = new LocalizedText("en", name), + WriteMask = AttributeWriteMask.None, + UserWriteMask = AttributeWriteMask.None, + Executable = true, + UserExecutable = true + }; + + if (parent != null) + { + parent.AddChild(method); + } + + return method; + } + + /// + /// Method to start monitoring a node and publish the data to IoTHub. Executes synchronously. + /// + private ServiceResult OnPublishNodeCall(ISystemContext context, MethodState method, IList inputArguments, IList outputArguments) + { + string logPrefix = "OnPublishNodeCall:"; + if (string.IsNullOrEmpty(inputArguments[0] as string) || string.IsNullOrEmpty(inputArguments[1] as string)) + { + Logger.Error($"{logPrefix} Invalid Arguments when trying to publish a node."); + return ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide all arguments as strings!"); + } + + HttpStatusCode statusCode = HttpStatusCode.InternalServerError; + NodeId nodeId = null; + ExpandedNodeId expandedNodeId = null; + Uri endpointUri = null; + bool isNodeIdFormat = true; + try + { + string id = inputArguments[0] as string; + if (id.Contains("nsu=", StringComparison.InvariantCulture)) + { + expandedNodeId = ExpandedNodeId.Parse(id); + isNodeIdFormat = false; + } + else + { + nodeId = NodeId.Parse(id); + isNodeIdFormat = true; + } + endpointUri = new Uri(inputArguments[1] as string); + } + catch (UriFormatException) + { + Logger.Error($"{logPrefix} The EndpointUrl has an invalid format '{inputArguments[1] as string}'!"); + return ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA endpoint URL as second argument!"); + } + catch (Exception e) + { + Logger.Error(e, $"{logPrefix} The NodeId has an invalid format '{inputArguments[0] as string}'!"); + return ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA NodeId in NodeId or ExpandedNodeId format as first argument!"); + } + + // find/create a session to the endpoint URL and start monitoring the node. + try + { + // lock the publishing configuration till we are done + OpcSessionsListSemaphore.Wait(); + + if (ShutdownTokenSource.IsCancellationRequested) + { + return ServiceResult.Create(StatusCodes.BadUnexpectedError, $"Publisher shutdown in progress."); + } + + // find the session we need to monitor the node + OpcSession opcSession = null; + opcSession = OpcSessions.FirstOrDefault(s => s.EndpointUrl.Equals(endpointUri.OriginalString, StringComparison.OrdinalIgnoreCase)); + + // add a new session. + if (opcSession == null) + { + // create new session info. + opcSession = new OpcSession(endpointUri.OriginalString, true, OpcSessionCreationTimeout); + OpcSessions.Add(opcSession); + Logger.Information($"OnPublishNodeCall: No matching session found for endpoint '{endpointUri.OriginalString}'. Requested to create a new one."); + } + + if (isNodeIdFormat) + { + // add the node info to the subscription with the default publishing interval, execute syncronously + Logger.Debug($"{logPrefix} Request to monitor item with NodeId '{nodeId.ToString()}' (with default PublishingInterval and SamplingInterval)"); + statusCode = opcSession.AddNodeForMonitoringAsync(nodeId, null, null, null, null, ShutdownTokenSource.Token).Result; + } + else + { + // add the node info to the subscription with the default publishing interval, execute syncronously + Logger.Debug($"{logPrefix} Request to monitor item with ExpandedNodeId '{expandedNodeId.ToString()}' (with default PublishingInterval and SamplingInterval)"); + statusCode = opcSession.AddNodeForMonitoringAsync(null, expandedNodeId, null, null, null, ShutdownTokenSource.Token).Result; + } + } + catch (Exception e) + { + Logger.Error(e, $"{logPrefix} Exception while trying to configure publishing node '{(isNodeIdFormat ? nodeId.ToString() : expandedNodeId.ToString())}'"); + return ServiceResult.Create(e, StatusCodes.BadUnexpectedError, $"Unexpected error publishing node: {e.Message}"); + } + finally + { + OpcSessionsListSemaphore.Release(); + } + + if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted) + { + return ServiceResult.Good; + } + return ServiceResult.Create(StatusCodes.Bad, "Can not start monitoring node! Reason unknown."); + } + + /// + /// Method to remove the node from the subscription and stop publishing telemetry to IoTHub. Executes synchronously. + /// + private ServiceResult OnUnpublishNodeCall(ISystemContext context, MethodState method, IList inputArguments, IList outputArguments) + { + string logPrefix = "OnUnpublishNodeCall:"; + if (string.IsNullOrEmpty(inputArguments[0] as string) || string.IsNullOrEmpty(inputArguments[1] as string)) + { + Logger.Error($"{logPrefix} Invalid arguments!"); + return ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide all arguments!"); + } + + HttpStatusCode statusCode = HttpStatusCode.InternalServerError; + NodeId nodeId = null; + ExpandedNodeId expandedNodeId = null; + Uri endpointUri = null; + bool isNodeIdFormat = true; + try + { + string id = inputArguments[0] as string; + if (id.Contains("nsu=", StringComparison.InvariantCulture)) + { + expandedNodeId = ExpandedNodeId.Parse(id); + isNodeIdFormat = false; + } + else + { + nodeId = NodeId.Parse(id); + isNodeIdFormat = true; + } + endpointUri = new Uri(inputArguments[1] as string); + } + catch (UriFormatException) + { + Logger.Error($"{logPrefix} The endpointUrl is invalid '{inputArguments[1] as string}'!"); + return ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA endpoint URL as second argument!"); + } + catch (Exception e) + { + Logger.Error(e, $"{logPrefix} The NodeId has an invalid format '{inputArguments[0] as string}'!"); + return ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA NodeId in NodeId or ExpandedNodeId format as first argument!"); + } + + // find the session and stop monitoring the node. + try + { + OpcSessionsListSemaphore.Wait(); + if (ShutdownTokenSource.IsCancellationRequested) + { + return ServiceResult.Create(StatusCodes.BadUnexpectedError, $"Publisher shutdown in progress."); + } + + // find the session we need to monitor the node + OpcSession opcSession = null; + try + { + opcSession = OpcSessions.FirstOrDefault(s => s.EndpointUrl.Equals(endpointUri.OriginalString, StringComparison.OrdinalIgnoreCase)); + } + catch + { + opcSession = null; + } + + if (opcSession == null) + { + // do nothing if there is no session for this endpoint. + Logger.Error($"{logPrefix} Session for endpoint '{endpointUri.OriginalString}' not found."); + return ServiceResult.Create(StatusCodes.BadSessionIdInvalid, "Session for endpoint of node to unpublished not found!"); + } + else + { + if (isNodeIdFormat) + { + // stop monitoring the node, execute syncronously + Logger.Information($"{logPrefix} Request to stop monitoring item with NodeId '{nodeId.ToString()}')"); + statusCode = opcSession.RequestMonitorItemRemovalAsync(nodeId, null, ShutdownTokenSource.Token).Result; + } + else + { + // stop monitoring the node, execute syncronously + Logger.Information($"{logPrefix} Request to stop monitoring item with ExpandedNodeId '{expandedNodeId.ToString()}')"); + statusCode = opcSession.RequestMonitorItemRemovalAsync(null, expandedNodeId, ShutdownTokenSource.Token).Result; + } + } + } + catch (Exception e) + { + Logger.Error(e, $"{logPrefix} Exception while trying to configure publishing node '{nodeId.ToString()}'"); + return ServiceResult.Create(e, StatusCodes.BadUnexpectedError, $"Unexpected error unpublishing node: {e.Message}"); + } + finally + { + OpcSessionsListSemaphore.Release(); + } + return (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted ? ServiceResult.Good : ServiceResult.Create(StatusCodes.Bad, "Can not stop monitoring node!")); + } + + /// + /// Method to get the list of configured nodes and is only there for backward compatibility. Executes synchronously. + /// The format of the returned node description is using NodeId format. The assumption + /// is that the caller is able to access the namespace array of the server + /// on the endpoint URL(s) themselve and do the correct mapping. + /// + private ServiceResult OnGetPublishedNodesLegacyCall(ISystemContext context, MethodState method, IList inputArguments, IList outputArguments) + { + string logPrefix = "OnGetPublishedNodesLegacyCall:"; + Uri endpointUri = null; + + if (string.IsNullOrEmpty(inputArguments[0] as string)) + { + Logger.Information($"{logPrefix} returning all nodes of all endpoints'!"); + } + else + { + try + { + endpointUri = new Uri(inputArguments[0] as string); + } + catch (UriFormatException) + { + Logger.Error($"{logPrefix} The endpointUrl is invalid '{inputArguments[0] as string}'!"); + return ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA endpoint URL as first argument!"); + } + } + + // get the list of published nodes in NodeId format + List configFileEntries = GetPublisherConfigurationFileEntriesAsNodeIdsAsync(endpointUri.OriginalString).Result; + outputArguments[0] = JsonConvert.SerializeObject(configFileEntries); + Logger.Information($"{logPrefix} Success (number of entries: {configFileEntries.Count})"); + return ServiceResult.Good; + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource item of type Opc.Ua.DataItemState, Leaked resource publishNodeMethod of type Opc.Ua.MethodState, Leaked resource getPublishedNodesLegacyMethod of type Opc.Ua.MethodState, Leaked resource unpublishNodeMethod of type Opc.Ua.MethodState in method "Void PublisherNodeManager.CreateAddressSpace(IDictionary`2)". + +### Severity: +ERROR + +### Procedure: +Void PublisherNodeManager.CreateAddressSpace(IDictionary`2) + +### File: +opcpublisher/PublisherNodeManager.cs + +### Key: +PublisherNodeManager.cs|CreateAddressSpace|DOTNET_RESOURCE_LEAK + +### Hash: +d09324135fe4601e274bf53d6963a464 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2891/instruction.md b/inferredbugs-2891/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5bc59e6e1665910ca57eef1da2ede89af348916a --- /dev/null +++ b/inferredbugs-2891/instruction.md @@ -0,0 +1,224 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** shadowsocks-java +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package cn.wowspeeder.encryption; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.SecureRandom; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Logger; + +import javax.crypto.SecretKey; + +import org.bouncycastle.crypto.StreamBlockCipher; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.ParametersWithIV; + +public abstract class CryptBase implements ICrypt { + + protected final String _name; + protected final SecretKey _key; + protected final ShadowSocksKey _ssKey; + protected final int _ivLength; + protected final int _keyLength; + protected boolean _ignoreIVSet; + protected boolean _encryptIVSet; + protected boolean _decryptIVSet; + protected byte[] _encryptIV; + protected byte[] _decryptIV; + protected final Lock encLock = new ReentrantLock(); + protected final Lock decLock = new ReentrantLock(); + protected StreamBlockCipher encCipher; + protected StreamBlockCipher decCipher; + private Logger logger = Logger.getLogger(CryptBase.class.getName()); + + public CryptBase(String name, String password) { + _name = name.toLowerCase(); + _ivLength = getIVLength(); + _keyLength = getKeyLength(); + _ssKey = new ShadowSocksKey(password, _keyLength); + _key = getKey(); + } + + @Override + public void ivSetIgnore(boolean ignore) { + this._ignoreIVSet = ignore; + } + + protected void setIV(byte[] iv, boolean isEncrypt) { + if (_ivLength == 0) { + return; + } + + if (isEncrypt) { + try { + _encryptIV = new byte[_ivLength]; + System.arraycopy(iv, 0, _encryptIV, 0, _ivLength); + encCipher = getCipher(isEncrypt); + ParametersWithIV parameterIV = new ParametersWithIV( + new KeyParameter(_key.getEncoded()), _encryptIV); + encCipher.init(isEncrypt, parameterIV); + } catch (InvalidAlgorithmParameterException e) { + logger.info(e.toString()); + } + } else { + try { + _decryptIV = new byte[_ivLength]; + System.arraycopy(iv, 0, _decryptIV, 0, _ivLength); + decCipher = getCipher(isEncrypt); + ParametersWithIV parameterIV = new ParametersWithIV( + new KeyParameter(_key.getEncoded()), _decryptIV); + decCipher.init(isEncrypt, parameterIV); + } catch (InvalidAlgorithmParameterException e) { + logger.info(e.toString()); + } + } + } + + @Override + public void encrypt(byte[] data, ByteArrayOutputStream stream) { + synchronized (encLock) { + stream.reset(); + if (!_encryptIVSet || _ignoreIVSet) { + _encryptIVSet = true; + byte[] iv = randomBytes(_ivLength); + setIV(iv, true); + try { + stream.write(iv); + } catch (IOException e) { + logger.info(e.toString()); + } + + } + + _encrypt(data, stream); + } + } + + @Override + public void encrypt(byte[] data, int length, ByteArrayOutputStream stream) { + byte[] d = new byte[length]; + System.arraycopy(data, 0, d, 0, length); + encrypt(d, stream); + } + + @Override + public void decrypt(byte[] data, ByteArrayOutputStream stream) { + byte[] temp; + synchronized (decLock) { + stream.reset(); + if (!_decryptIVSet || _ignoreIVSet) { + _decryptIVSet = true; + setIV(data, false); + temp = new byte[data.length - _ivLength]; + System.arraycopy(data, _ivLength, temp, 0, data.length + - _ivLength); + } else { + temp = data; + } + + _decrypt(temp, stream); + } + } + + @Override + public void decrypt(byte[] data, int length, ByteArrayOutputStream stream) { + byte[] d = new byte[length]; + System.arraycopy(data, 0, d, 0, length); + decrypt(d, stream); + } + + private byte[] randomBytes(int size) { + byte[] bytes = new byte[size]; + new SecureRandom().nextBytes(bytes); + return bytes; + } + + protected abstract StreamBlockCipher getCipher(boolean isEncrypted) + throws InvalidAlgorithmParameterException; + + protected abstract SecretKey getKey(); + + protected abstract void _encrypt(byte[] data, ByteArrayOutputStream stream); + + protected abstract void _decrypt(byte[] data, ByteArrayOutputStream stream); + + protected abstract int getIVLength(); + + protected abstract int getKeyLength(); +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `cn.wowspeeder.encryption.CryptBase.setIV` writes to field `this.cn.wowspeeder.encryption.CryptBase._encryptIV` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CryptBase.setIV(byte[],boolean) + +### Procedure Id: +cn.wowspeeder.encryption.CryptBase.setIV(byte[],boolean):void.9c65d3cdf0eeee1c9e56c987f715ac95 + +### File: +src/main/java/cn/wowspeeder/encryption/CryptBase.java + +### Key: +CryptBase.java|setIV|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +43b8be23a9ea635eb7c45d27ce06d707 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2896/instruction.md b/inferredbugs-2896/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f65baea43f77e6a3cb4f3b2348fd126ac92f12fe --- /dev/null +++ b/inferredbugs-2896/instruction.md @@ -0,0 +1,206 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** find-sec-bugs +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Find Security Bugs + * Copyright (c) Philippe Arteau, All rights reserved. + * + * 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 3.0 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. + */ +package com.h3xstream.findbugs.test.service; + +import edu.umd.cs.findbugs.*; +import edu.umd.cs.findbugs.config.ProjectFilterSettings; +import edu.umd.cs.findbugs.config.UserPreferences; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.concurrent.NotThreadSafe; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.Random; +import java.util.jar.JarOutputStream; +import java.util.zip.ZipEntry; + +import static org.mockito.Mockito.mock; + +@NotThreadSafe +public class FindBugsLauncher { + + private static final Logger log = LoggerFactory.getLogger(FindBugsLauncher.class); + + + static Plugin loadedPlugin; + + /** + * Launch an analysis on the given source files. + * + * @param classFiles + * @param bugReporter + * @throws java.io.IOException + * @throws InterruptedException + * @throws edu.umd.cs.findbugs.PluginException + * + */ + public void analyze(String[] classFiles, BugReporter bugReporter) throws IOException, InterruptedException, + PluginException, NoSuchFieldException, IllegalAccessException { + + final ClassLoader cl = getClass().getClassLoader(); + + Project project = new Project(); + project.setProjectName("automate-test-project"); + for (String file : classFiles) { + project.addFile(file); + } + + if (loadedPlugin == null) { + //Initialize the plugin base on the findbugs.xml + byte[] archive = buildFakePluginJar(); + + File f = new File(System.getProperty("java.io.tmpdir"), "plugin.jar"); + log.info("Writing " + f.getCanonicalPath()); + f.deleteOnExit(); + FileOutputStream out = new FileOutputStream(f); + out.write(archive); + out.close(); + + loadedPlugin = Plugin.loadCustomPlugin(f.toURL(), project); + } + //FindBugs engine + FindBugs2 engine = new FindBugs2(); + engine.setNoClassOk(true); + engine.setMergeSimilarWarnings(false); + engine.setBugReporter(bugReporter); + engine.setProject(project); + engine.setProgressCallback(mock(FindBugsProgress.class)); + + engine.setDetectorFactoryCollection(DetectorFactoryCollection.instance()); + + //User preferences set to miss no bugs report + UserPreferences prefs = UserPreferences.createDefaultUserPreferences(); + + ProjectFilterSettings filter = prefs.getFilterSettings(); + filter.setMinRank(20); + filter.setDisplayFalseWarnings(true); + filter.setMinPriority("Low"); + + engine.setUserPreferences(prefs); + + log.info("Analyzing... {}", classFiles); + engine.execute(); + } + + /** + * The minimum requirement to have a "valid" archive plugin is to include + * findbugs.xml, messages.xml and MANIFEST.MF files. The rest of the + * resources are load using the parent ClassLoader (Not requires to be in + * the jar). + *

+ * Instead of building a file on disk, the result of the stream is kept in + * memory and return as a byte array. + * + * @return + * @throws IOException + */ + private byte[] buildFakePluginJar() throws IOException { + ClassLoader cl = getClass().getClassLoader(); + + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + JarOutputStream jar = new JarOutputStream(buffer); + + //Add files to the jar stream + for (String resource : Arrays.asList("findbugs.xml", "messages.xml", "META-INF/MANIFEST.MF")) { + jar.putNextEntry(new ZipEntry(resource)); + jar.write(IOUtils.toByteArray(cl.getResourceAsStream("metadata/" + resource))); + } + jar.finish(); + + return buffer.toByteArray(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.util.jar.JarOutputStream` acquired to `jar` by call to `JarOutputStream(...)` at line 121 is not released after line 128. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +byte[] FindBugsLauncher.buildFakePluginJar() + +### Procedure Id: +com.h3xstream.findbugs.test.service.FindBugsLauncher.buildFakePluginJar():byte[].dc6397b795836ffb82a086daafae8005 + +### File: +findbugs-test-util/src/test/java/com/h3xstream/findbugs/test/service/FindBugsLauncher.java + +### Key: +FindBugsLauncher.java|buildFakePluginJar|RESOURCE_LEAK + +### Node Key: +f32d2aa1db1d0ee92b12180ab1e88081 + +### Hash: +cce4981e8dee9a29e22df2772c09a5aa + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2897/instruction.md b/inferredbugs-2897/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..620c9b4c79e83659aeb4c8f7a961be2af6d92e07 --- /dev/null +++ b/inferredbugs-2897/instruction.md @@ -0,0 +1,357 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** find-sec-bugs +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Find Security Bugs + * Copyright (c) Philippe Arteau, All rights reserved. + * + * 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 3.0 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. + */ +package com.h3xstream.findsecbugs.taintanalysis; + +import com.h3xstream.findsecbugs.FindSecBugsGlobalConfig; +import com.h3xstream.findsecbugs.taintanalysis.data.UnknownSource; +import com.h3xstream.findsecbugs.taintanalysis.data.UnknownSourceType; +import edu.umd.cs.findbugs.ba.BasicBlock; +import edu.umd.cs.findbugs.ba.DataflowAnalysisException; +import edu.umd.cs.findbugs.ba.DepthFirstSearch; +import edu.umd.cs.findbugs.ba.Edge; +import edu.umd.cs.findbugs.ba.FrameDataflowAnalysis; +import edu.umd.cs.findbugs.ba.Location; +import edu.umd.cs.findbugs.ba.generic.GenericSignatureParser; +import edu.umd.cs.findbugs.classfile.MethodDescriptor; +import edu.umd.cs.findbugs.classfile.analysis.AnnotationValue; +import edu.umd.cs.findbugs.classfile.analysis.MethodInfo; +import edu.umd.cs.findbugs.io.IO; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import org.apache.bcel.generic.InstructionHandle; +import org.apache.bcel.generic.MethodGen; + +/** + * Implements taint dataflow operations, in particular meeting facts, transfer + * function is delegated to {@link TaintFrameModelingVisitor} + * + * @author David Formanek (Y Soft Corporation, a.s.) + */ +public class TaintAnalysis extends FrameDataflowAnalysis { + + private final MethodGen methodGen; + private final MethodInfo methodDescriptor; + private final TaintFrameModelingVisitor visitor; + private int parameterStackSize; + private List slotToParameter; + + private static final List TAINTED_ANNOTATIONS = loadFileContent( + "taint-config/taint-param-annotations.txt" + ); + + /** + * Constructs analysis for the given method + * + * @param methodGen method to analyze + * @param dfs DFS algorithm + * @param descriptor descriptor of the method to analyze + * @param taintConfig configured and derived taint summaries + */ + public TaintAnalysis(MethodGen methodGen, DepthFirstSearch dfs, + MethodDescriptor descriptor, TaintConfig taintConfig, List visitors) { + super(dfs); + this.methodGen = methodGen; + this.methodDescriptor = (MethodInfo) descriptor; + this.visitor = new TaintFrameModelingVisitor(methodGen.getConstantPool(), descriptor, taintConfig, visitors, methodGen); + computeParametersInfo(descriptor.getSignature(), descriptor.isStatic()); + } + + @Override + protected void mergeValues(TaintFrame frame, TaintFrame result, int i) + throws DataflowAnalysisException { + result.setValue(i, Taint.merge(result.getValue(i), frame.getValue(i))); + } + + @Override + public void transferInstruction(InstructionHandle handle, BasicBlock block, TaintFrame fact) + throws DataflowAnalysisException { + visitor.setFrameAndLocation(fact, new Location(handle, block)); + visitor.analyzeInstruction(handle.getInstruction()); + } + + @Override + public TaintFrame createFact() { + return new TaintFrame(methodGen.getMaxLocals()); + } + + /** + * Initialize the initial state of a TaintFrame. + * @param fact Initial frame + */ + @Override + public void initEntryFact(TaintFrame fact) { + fact.setValid(); + fact.clearStack(); + String methodFullSignature = methodDescriptor.getSlashedClassName() + "." + methodDescriptor.getName() + methodDescriptor.getSignature(); + boolean inMainMethod = isInMainMethod(); + int numSlots = fact.getNumSlots(); + int numLocals = fact.getNumLocals(); + for (int i = 0; i < numSlots; ++i) { + Taint value = new Taint(Taint.State.UNKNOWN); + if (i < numLocals) { + if (i < parameterStackSize) { + int stackOffset = parameterStackSize - i - 1; + if (isTaintedByAnnotation(i - 1)) { + value = new Taint(Taint.State.TAINTED); + // this would add line number for the first instruction in the method + //value.addLocation(new TaintLocation(methodDescriptor, 0,""), true); + } else if (inMainMethod) { + if (FindSecBugsGlobalConfig.getInstance().isTaintedMainArgument()) { + value = new Taint(Taint.State.TAINTED); + } else { + value = new Taint(Taint.State.SAFE); + } + } else { + value.addParameter(stackOffset); + } + value.addSource(new UnknownSource(UnknownSourceType.PARAMETER,value.getState()).setSignatureMethod(methodFullSignature).setParameterIndex(stackOffset)); + } + value.setVariableIndex(i); + } + fact.setValue(i, value); + } + } + + /** + * @return true if the method is the startup point of a console or gui application + * ("public static void main(String[] args)"), false otherwise + */ + private boolean isInMainMethod() { + return methodDescriptor.isStatic() + && "main".equals(methodDescriptor.getName()) + && "([Ljava/lang/String;)V".equals(methodDescriptor.getSignature()) + && methodGen.getMethod().isPublic(); + } + + /** + * Determine if the slot value is tainted based on added framework annotations. + *


+ * Example of mapping done:
+ * + * Method analyzed: "test(String,String,double)V" + * For the slot no 2, it look at annotations on the parameter 2. + *
+     *          0               1               2               3
+     *                                    +++++++++++++
+     *  [ double param3 | double param3 | String param2 | String param1 ]
+     * 
+ *
+ * (Reminder : double and long take two slots for one parameter) + * + * @param slotNo + * @return + */ + private boolean isTaintedByAnnotation(int slotNo) { + if (slotNo >= 0 && methodDescriptor.hasParameterAnnotations()) { + int parameter = slotToParameter.get(slotNo); + Collection annotations = methodDescriptor.getParameterAnnotations(parameter); + for (AnnotationValue annotation : annotations) { + if (TAINTED_ANNOTATIONS.contains(annotation.getAnnotationClass().getClassName())) { + return true; + } + } + } + return false; + } + + @Override + public void meetInto(TaintFrame fact, Edge edge, TaintFrame result) + throws DataflowAnalysisException { + if (fact.isValid() && edge.isExceptionEdge()) { + TaintFrame copy = null; + // creates modifiable copy + copy = modifyFrame(fact, copy); + copy.clearStack(); + // do not trust values that are safe just when an exception occurs + copy.pushValue(new Taint(Taint.State.UNKNOWN)); + fact = copy; + } + mergeInto(fact, result); + } + + /** + * This method must be called after executing the data flow + */ + public void finishAnalysis() { + visitor.finishAnalysis(); + } + + /** + * Compute two values: + *
  • The number of values required on the stack for a specific call.
  • + *
  • The parameter association with each slot.
  • + * + *
    + * + * For exemple : "(I[Ljava/lang/String;Ljava/lang/Object;)V" => void a(Integer, String, Object)

    + * Expected Stack prior the method invocation :
    + *
    +     * +--------------+
    +     * | 0: Object    |
    +     * +--------------+
    +     * | 1: String    |
    +     * +--------------+
    +     * | 2: int       |
    +     * +--------------+
    +     * 
    + *
    + * + * Special note: double and long (primitive types) value take two slots.
    + * For exemple : "(IDJ)V" => void a(Integer, Double, Long) + *
    +     * +--------------+
    +     * | 0: long  pt1 |
    +     * +--------------+
    +     * | 1: long  pt2 |
    +     * +--------------+
    +     * | 2: double pt1|
    +     * +--------------+
    +     * | 3: double pt2|
    +     * +--------------+
    +     * | 4: int       |
    +     * +--------------+
    +     * 
    + * + * @param signature + * @param isStatic + * @return + */ + private void computeParametersInfo(String signature, boolean isStatic) { + assert signature != null && !signature.isEmpty(); + // static methods does not have reference to this + int stackSize = isStatic ? 0 : 1; + GenericSignatureParser parser = new GenericSignatureParser(signature); + Iterator iterator = parser.parameterSignatureIterator(); + int paramIdx = 0; + slotToParameter = new ArrayList(); + while (iterator.hasNext()) { + String parameter = iterator.next(); + if (parameter.equals("D") || parameter.equals("J")) { + // double and long types takes two slots + stackSize += 2; + slotToParameter.add(paramIdx); + slotToParameter.add(paramIdx); + } else { + stackSize++; + slotToParameter.add(paramIdx); + } + paramIdx++; + } + parameterStackSize = stackSize; + } + + private static List loadFileContent(String path) { + BufferedReader stream = null; + try { + InputStream in = TaintAnalysis.class.getClassLoader().getResourceAsStream(path); + stream = new BufferedReader(new InputStreamReader(in, "utf-8")); + String line; + List content = new ArrayList(); + while ((line = stream.readLine()) != null) { + content.add(line.trim()); + } + return content; + } catch (IOException ex) { + assert false : ex.getMessage(); + } finally { + IO.close(stream); + } + return new ArrayList(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `InputStreamReader(...)` at line 268 is not released after line 278. +**Note**: potential exception at line 271 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List TaintAnalysis.loadFileContent(String) + +### Procedure Id: +com.h3xstream.findsecbugs.taintanalysis.TaintAnalysis.loadFileContent(java.lang.String):java.util.Li.1a5c0fb5c5dc0e85175d82bcebbbc7a7 + +### File: +findsecbugs-plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/TaintAnalysis.java + +### Key: +TaintAnalysis.java|loadFileContent|RESOURCE_LEAK + +### Node Key: +1a78488839e2ed780ff0b3c131d62750 + +### Hash: +cba4b49fd19838a258b2ef8b7f3291f2 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2898/instruction.md b/inferredbugs-2898/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d11636801fb7e78d90368cab008b9b8e256c7faa --- /dev/null +++ b/inferredbugs-2898/instruction.md @@ -0,0 +1,532 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** find-sec-bugs +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Find Security Bugs + * Copyright (c) Philippe Arteau, All rights reserved. + * + * 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 3.0 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. + */ +package com.h3xstream.findsecbugs.taintanalysis; + +import edu.umd.cs.findbugs.ba.AbstractFrameModelingVisitor; +import edu.umd.cs.findbugs.ba.DataflowAnalysisException; +import edu.umd.cs.findbugs.ba.InvalidBytecodeException; +import edu.umd.cs.findbugs.ba.generic.GenericSignatureParser; +import edu.umd.cs.findbugs.classfile.MethodDescriptor; +import edu.umd.cs.findbugs.util.ClassName; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; +import org.apache.bcel.Constants; +import org.apache.bcel.generic.AALOAD; +import org.apache.bcel.generic.AASTORE; +import org.apache.bcel.generic.ACONST_NULL; +import org.apache.bcel.generic.ANEWARRAY; +import org.apache.bcel.generic.ARETURN; +import org.apache.bcel.generic.CHECKCAST; +import org.apache.bcel.generic.ConstantPoolGen; +import org.apache.bcel.generic.FieldOrMethod; +import org.apache.bcel.generic.INVOKEINTERFACE; +import org.apache.bcel.generic.INVOKESPECIAL; +import org.apache.bcel.generic.INVOKESTATIC; +import org.apache.bcel.generic.INVOKEVIRTUAL; +import org.apache.bcel.generic.InvokeInstruction; +import org.apache.bcel.generic.LDC; +import org.apache.bcel.generic.LDC2_W; +import org.apache.bcel.generic.LoadInstruction; +import org.apache.bcel.generic.NEW; +import org.apache.bcel.generic.StoreInstruction; + +/** + * Visitor to make instruction transfer of taint values easier + * + * @author David Formanek (Y Soft Corporation, a.s.) + */ +public class TaintFrameModelingVisitor extends AbstractFrameModelingVisitor { + + private static final String TO_STRING_METHOD = "toString()Ljava/lang/String;"; + private static final String EQUALS_METHOD = "equals(Ljava/lang/Object;)Z"; + private static final Set SAFE_OBJECT_TYPES; + private static final Set IMMUTABLE_OBJECT_TYPES; + private final MethodDescriptor methodDescriptor; + private final int parameterStackSize; + private final TaintMethodSummaryMap methodSummaries; + private final TaintMethodSummary analyzedMethodSummary; + private final Set writtenIndeces; + + static { + // these data types cannot have taint state other than SAFE or NULL + SAFE_OBJECT_TYPES = new HashSet(9); + SAFE_OBJECT_TYPES.add("Ljava/lang/Boolean;"); + SAFE_OBJECT_TYPES.add("Ljava/lang/Character;"); + SAFE_OBJECT_TYPES.add("Ljava/lang/Double;"); + SAFE_OBJECT_TYPES.add("Ljava/lang/Float;"); + SAFE_OBJECT_TYPES.add("Ljava/lang/Integer;"); + SAFE_OBJECT_TYPES.add("Ljava/lang/Long;"); + SAFE_OBJECT_TYPES.add("Ljava/lang/Byte;"); + SAFE_OBJECT_TYPES.add("Ljava/lang/Short;"); + SAFE_OBJECT_TYPES.add("Ljava/lang/BigDecimal;"); + // these data types are not modified, when passed as a parameter to an unknown method + IMMUTABLE_OBJECT_TYPES = new HashSet(SAFE_OBJECT_TYPES.size() + 1); + IMMUTABLE_OBJECT_TYPES.addAll(SAFE_OBJECT_TYPES); + IMMUTABLE_OBJECT_TYPES.add("Ljava/lang/String;"); + } + + public TaintFrameModelingVisitor(ConstantPoolGen cpg, MethodDescriptor method, + TaintMethodSummaryMap methodSummaries) { + super(cpg); + if (method == null) { + throw new NullPointerException("null method descriptor"); + } + if (methodSummaries == null) { + throw new NullPointerException("null method summaries"); + } + this.methodDescriptor = method; + this.methodSummaries = methodSummaries; + this.parameterStackSize = getParameterStackSize(method.getSignature(), method.isStatic()); + this.analyzedMethodSummary = new TaintMethodSummary(); + this.writtenIndeces = new HashSet(); + } + + private static int getParameterStackSize(String signature, boolean isStatic) { + assert signature != null && !signature.isEmpty(); + // static methods does not have reference to this + int stackSize = isStatic ? 0 : 1; + GenericSignatureParser parser = new GenericSignatureParser(signature); + Iterator iterator = parser.parameterSignatureIterator(); + while (iterator.hasNext()) { + String parameter = iterator.next(); + if (parameter.equals("D") || parameter.equals("J")) { + // double and long types takes two slots + stackSize += 2; + } else { + stackSize++; + } + } + return stackSize; + } + + private static Collection getMutableStackIndices(String signature) { + assert signature != null && !signature.isEmpty(); + ArrayList indices = new ArrayList(); + int stackIndex = 0; + GenericSignatureParser parser = new GenericSignatureParser(signature); + Iterator iterator = parser.parameterSignatureIterator(); + while (iterator.hasNext()) { + String parameter = iterator.next(); + if ((parameter.startsWith("L") || parameter.startsWith("[")) + && !IMMUTABLE_OBJECT_TYPES.contains(parameter)) { + indices.add(stackIndex); + } + if (parameter.equals("D") || parameter.equals("J")) { + // double and long types takes two slots + stackIndex += 2; + } else { + stackIndex++; + } + } + for (int i = 0; i < indices.size(); i++) { + int reverseIndex = stackIndex - indices.get(i) - 1; + assert reverseIndex >= 0; + indices.set(i, reverseIndex); + } + return indices; + } + + @Override + public Taint getDefaultValue() { + return new Taint(Taint.State.UNKNOWN); + } + + @Override + public void visitLDC(LDC obj) { + pushSafe(); + } + + @Override + public void visitLDC2_W(LDC2_W obj) { + // double and long type takes two slots in BCEL + pushSafe(); + pushSafe(); + } + + @Override + public void visitACONST_NULL(ACONST_NULL obj) { + getFrame().pushValue(new Taint(Taint.State.NULL)); + } + + @Override + public void visitNEW(NEW obj) { + pushSafe(); + } + + @Override + public void handleStoreInstruction(StoreInstruction obj) { + try { + int numConsumed = obj.consumeStack(cpg); + if (numConsumed == Constants.UNPREDICTABLE) { + throw new InvalidBytecodeException("Unpredictable stack consumption"); + } + int index = obj.getIndex(); + while (numConsumed-- > 0) { + Taint value = getFrame().popValue(); + writtenIndeces.add(index); + getFrame().setValue(index++, value); + } + } catch (DataflowAnalysisException ex) { + throw new InvalidBytecodeException(ex.toString(), ex); + } + } + + @Override + public void handleLoadInstruction(LoadInstruction obj) { + int numProduced = obj.produceStack(cpg); + if (numProduced == Constants.UNPREDICTABLE) { + throw new InvalidBytecodeException("Unpredictable stack production"); + } + int index = obj.getIndex() + numProduced; + while (numProduced-- > 0) { + Taint value = getFrame().getValue(--index); + // set local variable origin of a stack value + value.setLocalVariableIndex(index); + if (!writtenIndeces.contains(index)) { + // it must be parameter if not written to local variable + int stackOffset = parameterStackSize - index - 1; + assert stackOffset >= 0; // since there is unwritten index + value.addTaintParameter(stackOffset); + } + getFrame().pushValue(new Taint(value)); + } + } + + @Override + public void visitINVOKEINTERFACE(INVOKEINTERFACE obj) { + visitInvoke(obj); + } + + @Override + public void visitINVOKESPECIAL(INVOKESPECIAL obj) { + visitInvoke(obj); + } + + @Override + public void visitINVOKESTATIC(INVOKESTATIC obj) { + visitInvoke(obj); + } + + @Override + public void visitINVOKEVIRTUAL(INVOKEVIRTUAL obj) { + visitInvoke(obj); + } + + @Override + public void visitANEWARRAY(ANEWARRAY obj) { + try { + getFrame().popValue(); + pushSafe(); + } catch (DataflowAnalysisException ex) { + throw new InvalidBytecodeException("Array length not in the stack", ex); + } + } + + @Override + public void visitAASTORE(AASTORE obj) { + try { + Taint valueTaint = getFrame().popValue(); + getFrame().popValue(); // array index + Taint arrayTaint = getFrame().popValue(); + Taint merge = Taint.merge(valueTaint, arrayTaint); + setLocalVariableTaint(merge, arrayTaint); + Taint stackTop = null; + if (getFrame().getStackDepth() > 0) { + stackTop = getFrame().getTopValue(); + } + // varargs use duplicated values + if (stackTop == arrayTaint) { + getFrame().popValue(); + getFrame().pushValue(new Taint(merge)); + } + } catch (DataflowAnalysisException ex) { + throw new InvalidBytecodeException("Not enough values on the stack", ex); + } + } + + @Override + public void visitAALOAD(AALOAD obj) { + try { + getFrame().popValue(); // array index + // just transfer the taint from array to value at any index + } catch (DataflowAnalysisException ex) { + throw new InvalidBytecodeException("Not enough values on the stack", ex); + } + } + + @Override + public void visitCHECKCAST(CHECKCAST obj) { + // keep the top of stack unchanged + } + + /** + * Regroup the method invocations (INVOKEINTERFACE, INVOKESPECIAL, + * INVOKESTATIC, INVOKEVIRTUAL) + * + * @param obj one of the invoke instructions + */ + private void visitInvoke(InvokeInstruction obj) { + assert obj != null; + TaintMethodSummary methodSummary = getMethodSummary(obj); + Taint taint = getMethodTaint(methodSummary); + assert taint != null; + if (taint.isUnknown()) { + taint.addTaintLocation(getTaintLocation(), false); + } + taintMutableArguments(methodSummary, obj); + transferTaintToMutables(methodSummary, taint); // adds variable index to taint too + modelInstruction(obj, getNumWordsConsumed(obj), getNumWordsProduced(obj), new Taint(taint)); + } + + private TaintMethodSummary getMethodSummary(InvokeInstruction obj) { + String signature = obj.getSignature(cpg); + String returnType = getReturnType(signature); + if (SAFE_OBJECT_TYPES.contains(returnType)) { + return TaintMethodSummary.SAFE_SUMMARY; + } + String className = getSlashedClassName(obj); + String methodName = obj.getMethodName(cpg); + String methodNameWithSig = methodName + signature; + String fullMethodName = className + "." + methodNameWithSig; + TaintMethodSummary methodSummary = methodSummaries.get(fullMethodName); + if (methodSummary != null) { + return methodSummary; + } + if (TO_STRING_METHOD.equals(methodNameWithSig)) { + return TaintMethodSummary.DEFAULT_TOSTRING_SUMMARY; + } + if (EQUALS_METHOD.equals(methodNameWithSig)) { + return TaintMethodSummary.DEFAULT_EQUALS_SUMMARY; + } + if (Constants.CONSTRUCTOR_NAME.equals(methodName) + && !SAFE_OBJECT_TYPES.contains("L" + className + ";")) { + int stackSize = getParameterStackSize(signature, false); + return TaintMethodSummary.getDefaultConstructorSummary(stackSize); + } + return methodSummary; + } + + private static String getReturnType(String signature) { + assert signature != null && signature.contains(")"); + return signature.substring(signature.indexOf(')') + 1); + } + + private String getSlashedClassName(FieldOrMethod obj) { + assert obj != null; + String className = obj.getReferenceType(cpg).toString(); + return ClassName.toSlashedClassName(className); + } + + private Taint getMethodTaint(TaintMethodSummary methodSummary) { + if (methodSummary == null) { + return getDefaultValue(); + } + Taint taint = methodSummary.getOutputTaint(); + assert taint != null; + assert taint != methodSummary.getOutputTaint() : "defensive copy not made"; + if (taint.isUnknown() && taint.hasTaintParameters()) { + Taint merge = mergeTransferParameters(taint.getTaintParameters()); + assert merge != null; + return Taint.merge(taint.getNonParametricTaint(), merge); + } + if (taint.isTainted()) { + taint.addTaintLocation(getTaintLocation(), true); + } + return taint; + } + + private void taintMutableArguments(TaintMethodSummary methodSummary, InvokeInstruction obj) { + if (methodSummary != null + && methodSummary != TaintMethodSummary.SAFE_SUMMARY + && !Constants.CONSTRUCTOR_NAME.equals(obj.getMethodName(cpg))) { + return; + } + Collection mutableStackIndices = getMutableStackIndices(obj.getSignature(cpg)); + for (Integer index : mutableStackIndices) { + assert index >= 0 && index < getFrame().getStackDepth(); + try { + Taint taint = new Taint(getFrame().getStackValue(index)); + taint.setState(Taint.State.merge(taint.getState(), Taint.State.UNKNOWN)); + getFrame().setValue(getFrame().getStackLocation(index), taint); + setLocalVariableTaint(taint, taint); + } catch (DataflowAnalysisException ex) { + throw new InvalidBytecodeException("Not enough values on the stack", ex); + } + } + } + + private Taint mergeTransferParameters(Collection transferParameters) { + assert transferParameters != null && !transferParameters.isEmpty(); + Taint taint = null; + for (Integer transferParameter : transferParameters) { + try { + Taint value = getFrame().getStackValue(transferParameter); + taint = Taint.merge(taint, value); + } catch (DataflowAnalysisException ex) { + throw new RuntimeException("Bad transfer parameter specification", ex); + } + } + assert taint != null; + return taint; + } + + private void transferTaintToMutables(TaintMethodSummary methodSummary, Taint taint) { + assert taint != null; + if (methodSummary == null || !methodSummary.hasMutableStackIndeces()) { + return; + } + try { + int stackDepth = getFrame().getStackDepth(); + for (Integer mutableStackIndex : methodSummary.getMutableStackIndeces()) { + assert mutableStackIndex >= 0; + if (mutableStackIndex >= stackDepth) { + if (!Constants.CONSTRUCTOR_NAME.equals(methodDescriptor.getName())) { + assert false : "Out of bounds mutables in " + methodDescriptor; + } + continue; // ignore if assertions disabled or if in constructor + } + Taint stackValue = getFrame().getStackValue(mutableStackIndex); + setLocalVariableTaint(taint, stackValue); + getFrame().setValue(getFrame().getStackLocation(mutableStackIndex), new Taint(taint)); + } + } catch (DataflowAnalysisException ex) { + assert false; // stack depth is checked + } + } + + private void setLocalVariableTaint(Taint valueTaint, Taint indexTaint) { + assert valueTaint != null && indexTaint != null; + if (!indexTaint.hasValidLocalVariableIndex()) { + return; + } + int index = indexTaint.getLocalVariableIndex(); + if (index >= getFrame().getNumLocals()) { + assert false : "Out of bounds local variable index in " + methodDescriptor; + return; // ignore if assertions disabled + } + valueTaint.setLocalVariableIndex(index); + getFrame().setValue(index, valueTaint); + } + + private void pushSafe() { + getFrame().pushValue(new Taint(Taint.State.SAFE)); + } + + private TaintLocation getTaintLocation() { + return new TaintLocation(methodDescriptor, getLocation().getHandle().getPosition()); + } + + @Override + public void visitARETURN(ARETURN obj) { + try { + Taint returnTaint = getFrame().getTopValue(); + Taint currentTaint = analyzedMethodSummary.getOutputTaint(); + analyzedMethodSummary.setOuputTaint(Taint.merge(returnTaint, currentTaint)); + } catch (DataflowAnalysisException ex) { + throw new InvalidBytecodeException("empty stack before reference return", ex); + } + handleNormalInstruction(obj); + } + + public TaintMethodSummary getAnalyzedMethodSummary() { + assert analyzedMethodSummary != null; + if (SAFE_OBJECT_TYPES.contains(getReturnType(methodDescriptor.getSignature())) + && (analyzedMethodSummary.getOutputTaint() == null + || analyzedMethodSummary.getOutputTaint().getState() != Taint.State.NULL)) { + return TaintMethodSummary.SAFE_SUMMARY; + } + return analyzedMethodSummary; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `methodSummary` last assigned on line 288 could be null and is dereferenced by call to `getMethodTaint(...)` at line 289. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TaintFrameModelingVisitor.visitInvoke(InvokeInstruction) + +### Procedure Id: +com.h3xstream.findsecbugs.taintanalysis.TaintFrameModelingVisitor.visitInvoke(org.apache.bcel.generi.649fbe64c19bdb61a18ec525169c5f2d + +### File: +plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/TaintFrameModelingVisitor.java + +### Key: +TaintFrameModelingVisitor.java|visitInvoke|NULL_DEREFERENCE + +### Node Key: +caa019c8ddef04a2dfd4f76137e22b94 + +### Hash: +ff65c5b82a4c04d0b146aa7653d546c1 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2899/instruction.md b/inferredbugs-2899/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a38f55c03aa10198a3558ad3d92653948e2a7bcc --- /dev/null +++ b/inferredbugs-2899/instruction.md @@ -0,0 +1,144 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** find-sec-bugs +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Find Security Bugs + * Copyright (c) Philippe Arteau, All rights reserved. + * + * 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 3.0 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. + */ +package com.h3xstream.findsecbugs.taintanalysis; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.util.HashMap; +import java.util.TreeSet; + +/** + * Map of taint summaries for all known methods + * + * @author David Formanek (Y Soft Corporation, a.s.) + */ +public class TaintMethodSummaryMap extends HashMap { + private static final long serialVersionUID = 1L; + + public void load(InputStream input) throws IOException { + BufferedReader reader = new BufferedReader(new InputStreamReader(input)); + for (;;) { + String line = reader.readLine(); + if (line == null) { + break; + } + line = line.trim(); + if (line.isEmpty()) { + continue; + } + putFromLine(line); + } + } + + public void dump(PrintStream output) { + TreeSet keys = new TreeSet(keySet()); + for (String key : keys) { + output.println(key + ":" + get(key)); + } + } + + private void putFromLine(String line) throws IOException { + if (line.startsWith("-")) { + // for comments or removing summary temporarily + return; + } + String[] tuple = line.split("\\:"); + if (tuple.length != 2) { + throw new IOException("Line format is not 'method name:summary info'"); + } + put(tuple[0].trim(), TaintMethodSummary.load(tuple[1])); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 37 is not released after line 49. +**Note**: potential exception at line 39 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TaintMethodSummaryMap.load(InputStream) + +### Procedure Id: +com.h3xstream.findsecbugs.taintanalysis.TaintMethodSummaryMap.load(java.io.InputStream):void.0c9d919d0cbaffd5185f18247c484725 + +### File: +plugin/src/main/java/com/h3xstream/findsecbugs/taintanalysis/TaintMethodSummaryMap.java + +### Key: +TaintMethodSummaryMap.java|load|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +65f5733488849f4f208055e36d0e57fd + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2919/instruction.md b/inferredbugs-2919/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4704c1a02d1c93c4a50bb3f9d6d66595f09f4dc7 --- /dev/null +++ b/inferredbugs-2919/instruction.md @@ -0,0 +1,303 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** antares +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package me.hao0.antares.server.schedule.executor; + +import com.google.common.base.Throwables; +import me.hao0.antares.common.dto.JobDetail; +import me.hao0.antares.common.dto.JobFireTime; +import me.hao0.antares.common.dto.JobInstanceWaitResp; +import me.hao0.antares.common.exception.JobStateTransferInvalidException; +import me.hao0.antares.common.log.Logs; +import me.hao0.antares.common.model.JobInstance; +import me.hao0.antares.common.model.enums.JobInstanceStatus; +import me.hao0.antares.common.model.enums.JobState; +import me.hao0.antares.common.model.enums.JobTriggerType; +import me.hao0.antares.common.util.Constants; +import me.hao0.antares.common.util.Executors; +import me.hao0.antares.common.util.Systems; +import me.hao0.antares.server.cluster.client.ClientCluster; +import me.hao0.antares.server.cluster.server.ServerHost; +import me.hao0.antares.server.event.core.EventDispatcher; +import me.hao0.antares.server.event.job.JobFailedEvent; +import me.hao0.antares.server.event.job.JobFinishedEvent; +import me.hao0.antares.server.event.job.JobTimeoutEvent; +import me.hao0.antares.server.exception.JobInstanceCreateException; +import me.hao0.antares.store.util.Dates; +import me.hao0.antares.store.service.JobService; +import me.hao0.antares.store.support.JobSupport; +import me.hao0.antares.common.util.Response; +import org.quartz.JobExecutionContext; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import java.util.Date; +import java.util.concurrent.ExecutorService; + +/** + * Author: haolin + * Email: haolin.h0@gmail.com + */ +@Component +public class DefaultJobExecutor implements JobExecutor { + + @Autowired + private JobService jobService; + + @Autowired + private ServerHost serverHost; + + @Autowired + private ClientCluster clientCluster; + + @Autowired + private JobSupport jobSupport; + + @Autowired + private EventDispatcher eventDispatcher; + + private final ExecutorService asyncExecutor = + Executors.newExecutor(Systems.cpuNum(), 10000, "DEFAULT-JOB-ASYNC-EXECUTOR-"); + + @Override + public void execute(final JobDetail jobDetail, JobTriggerType triggerType, JobExecutionContext context) { + + final String appName = jobDetail.getApp().getAppName(); + final String jobClass = jobDetail.getJob().getClazz(); + + JobInstance instance = null; + try { + + Logs.info("The job({}/{}) is fired.", appName, jobClass); + + if (triggerType == JobTriggerType.DEFAULT){ + // refresh the job fire time if triggered by scheduler + asyncExecutor.submit(new RefreshJobFireTimeTask(appName, jobClass, context)); + } + + if (!canRunJobInstance(appName, jobClass)){ + return; + } + + // job is running + jobSupport.updateJobStateDirectly(appName, jobClass, JobState.RUNNING); + + // create the job instance and shards + instance = createInstanceAndShards(jobDetail, triggerType); + + // trigger the clients to pull shards + jobSupport.triggerJobInstance(appName, jobClass, instance); + + // blocking until all shards to be finished or timeout + Long timeout = jobDetail.getConfig().getTimeout(); + timeout = timeout == null ? 0L : timeout; + JobInstanceWaitResp finishResp = jobSupport.waitingJobInstanceFinish(appName, jobClass, timeout, instance.getId()); + if (finishResp.isSuccess()){ + // job instance is finished successfully + // publish job finish event + eventDispatcher.publish(new JobFinishedEvent(instance.getJobId(), instance.getId())); + } else if (finishResp.isTimeout()){ + // job instance is timeout + eventDispatcher.publish(new JobTimeoutEvent(instance.getJobId(), instance.getId(), buildJobTimeoutDetail(instance))); + } + + // maybe now the job is paused, stopped, ..., so need to expect the job state + jobSupport.updateJobStateSafely(appName, jobClass, JobState.WAITING); + + // job has finished + } catch (JobStateTransferInvalidException e){ + // job state transfer error + Logs.warn("failed to update job state(instances={}), cause: {}.", instance, e.toString()); + } catch (JobInstanceCreateException e){ + // handle when job instance create failed + String cause = Throwables.getStackTraceAsString(e); + Logs.error("failed to create job instance when execute job(jobDetail={}, instance={}), cause: {}", + jobDetail, instance, cause); + handleJobExecuteFailed(jobDetail, instance, appName, jobClass, cause); + } catch (Exception e){ + // handle other exceptions + String cause = Throwables.getStackTraceAsString(e); + Logs.error("failed to execute job(jobDetail={}, instance={}), cause: {}", + jobDetail, instance, cause); + handleJobExecuteFailed(jobDetail, instance, appName, jobClass, cause); + } + } + + private String buildJobTimeoutDetail(JobInstance instance) { + return "startTime:" + Dates.format(instance.getStartTime()) + ", " + + "elapsedTime:" + Dates.timeIntervalStr(instance.getStartTime(), new Date()); + } + + private boolean canRunJobInstance(String appName, String jobClass) { + + if (!clientCluster.hasAliveClients(appName)){ + // there aren't alive clients + Logs.warn("Invalid job({}/{}) fired, because there are no available clients.", appName, jobClass); + return Boolean.FALSE; + } + + if (jobSupport.hasJobInstance(appName, jobClass)){ + Logs.warn("The job({}/{}) has a running instance, so ignore this execution.", appName, jobClass); + return Boolean.FALSE; + } + + return Boolean.TRUE; + } + + private void handleJobExecuteFailed(JobDetail jobDetail, JobInstance instance, String appName, String jobClass, String cause) { + try { + + if (instance == null){ + return; + } + + if (cause.length() > Constants.MAX_ERROR_LENGTH){ + cause = cause.substring(0, Constants.MAX_ERROR_LENGTH); + } + + // save the job instance + jobService.failedJobInstance(instance.getId(), cause); + + // delete the instance + jobSupport.deleteJobInstance(appName, jobClass, instance); + + // update the job state + jobSupport.updateJobStateDirectly(appName, jobClass, JobState.WAITING); + + } catch (Exception e){ + Logs.error("failed to handle the job(instance={}, appName={}, jobClass={}) execute failed, cause: {}", + instance, appName, jobClass, Throwables.getStackTraceAsString(e)); + } finally { + + // publish job failed event + Long instanceId = instance == null ? null : instance.getId(); + eventDispatcher.publish(new JobFailedEvent(jobDetail.getJob().getId(), instanceId, cause)); + } + } + + /** + * Create a new job instance and shards + * @param detail the job detail + * @return the new job instance + */ + private JobInstance createInstanceAndShards(JobDetail detail, JobTriggerType triggerType) { + + JobInstance instance = new JobInstance(); + instance.setJobId(detail.getJob().getId()); + instance.setStatus(JobInstanceStatus.RUNNING.value()); + instance.setTriggerType(triggerType.value()); + instance.setServer(serverHost.get()); + instance.setStartTime(new Date()); + + Response saveResp = jobService.createJobInstanceAndShards(instance, detail.getConfig()); + if (!saveResp.isSuccess() || !saveResp.getData()){ + throw new JobInstanceCreateException(saveResp.getErr().toString()); + } + + return instance; + } + + private class RefreshJobFireTimeTask implements Runnable { + + private final String appName; + + private final String jobClass; + + private final JobExecutionContext context; + + public RefreshJobFireTimeTask(String appName, String jobClass, JobExecutionContext context) { + this.appName = appName; + this.jobClass = jobClass; + this.context = context; + } + + @Override + public void run() { + try { + + // update job fire time info + JobFireTime jobFireTime = new JobFireTime(); + + jobFireTime.setCurrent(Dates.format(context.getFireTime())); + jobFireTime.setPrev(Dates.format(context.getPreviousFireTime())); + jobFireTime.setNext(Dates.format(context.getNextFireTime())); + + jobSupport.updateJobFireTime(appName, jobClass, jobFireTime); + + } catch (Exception e){ + Logs.error("failed to execute async task when execute job({}/{}), cause: {}.", + appName, jobClass, Throwables.getStackTraceAsString(e)); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `instance.getId()` could be null and is dereferenced at line 90. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DefaultJobExecutor.execute(JobDetail,JobTriggerType,JobExecutionContext) + +### Procedure Id: +me.hao0.antares.server.schedule.executor.DefaultJobExecutor.execute(me.hao0.antares.common.dto.JobDe.eda8e9255f9160e90d73389d872c04b4 + +### File: +antares-server/src/main/java/me/hao0/antares/server/schedule/executor/DefaultJobExecutor.java + +### Key: +DefaultJobExecutor.java|execute|NULL_DEREFERENCE + +### Node Key: +be1f268892945b6a5fa1087da17aa7bb + +### Hash: +fe5bc39e139bc22abb8f60e453aadde7 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2921/instruction.md b/inferredbugs-2921/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..399982a9ac1581b20890120f4aa6ee33c1bbdf84 --- /dev/null +++ b/inferredbugs-2921/instruction.md @@ -0,0 +1,298 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** testcontainers-spring-boot +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * The MIT License (MIT) + * + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.playtika.test.selenium; + +import com.google.common.net.InetAddresses; +import com.playtika.test.common.spring.DockerPresenceBootstrapConfiguration; +import com.playtika.test.common.utils.ContainerUtils; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.openqa.selenium.MutableCapabilities; +import org.openqa.selenium.chrome.ChromeOptions; +import org.openqa.selenium.firefox.FirefoxOptions; +import org.openqa.selenium.remote.RemoteWebDriver; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; +import org.testcontainers.containers.BrowserWebDriverContainer; +import org.testcontainers.containers.Container; +import org.testcontainers.containers.ContainerLaunchException; +import org.testcontainers.containers.DefaultRecordingFileFactory; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.RecordingFileFactory; + + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.URL; +import java.nio.file.Files; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; + +import static com.playtika.test.selenium.SeleniumProperties.BEAN_NAME_EMBEDDED_SELENIUM; +import static com.playtika.test.selenium.SeleniumProperties.BEAN_NAME_EMBEDDED_SELENIUM_DRIVER; + + +@Slf4j +@Configuration +@ConditionalOnExpression("${embedded.containers.enabled:true}") +@AutoConfigureAfter(DockerPresenceBootstrapConfiguration.class) +@ConditionalOnProperty(name = "embedded.selenium.enabled", matchIfMissing = true) +@EnableConfigurationProperties(SeleniumProperties.class) +@RequiredArgsConstructor +public class EmbeddedSeleniumBootstrapConfiguration { + + private static final String TC_TEMP_DIR_PREFIX = "tc"; + public static final String DEFINED_VNC_USERNAME = "vnc"; + public static final String DEFINED_VNC_PASSWORD = "secret"; + + public static final String DOCKER_FOR_LINUX_STATIC_IP = "172.17.0.1"; + + @Bean + @ConditionalOnMissingBean(MutableCapabilities.class) + @ConditionalOnProperty(value = "embedded.selenium.browser", havingValue = "CHROMIUM", matchIfMissing = true) + public ChromeOptions chromeOptions(SeleniumProperties properties) { + ChromeOptions options = new ChromeOptions(); + properties.apply(options); + return options; + } + + @Bean + @ConditionalOnMissingBean(MutableCapabilities.class) + @ConditionalOnProperty(value = "embedded.selenium.browser", havingValue = "FIREFOX") + public FirefoxOptions firefoxOptions(SeleniumProperties properties) { + FirefoxOptions options = new FirefoxOptions(); + properties.apply(options); + return options; + } + + + @Bean(name = BEAN_NAME_EMBEDDED_SELENIUM, destroyMethod = "stop") + @ConditionalOnMissingBean + public BrowserWebDriverContainer selenium( + ConfigurableEnvironment environment, + SeleniumProperties properties, + MutableCapabilities capabilities + ) { + + BrowserWebDriverContainer container = new BrowserWebDriverContainer<>().withCapabilities(capabilities); + container.withRecordingFileFactory(getRecordingFileFactory()); + + File recordingDirOrNull = null; + if (properties.getVnc().getMode().convert() != BrowserWebDriverContainer.VncRecordingMode.SKIP) { + recordingDirOrNull = getOrCreateTempDir(properties.getVnc().getRecordingDir()); + } + container.withRecordingMode(properties.getVnc().getMode().convert(), recordingDirOrNull); + + + log.info("Starting Selenium. Docker image: {}", container.getDockerImageName()); + ContainerUtils.configureCommonsAndStart(container, properties, log); + + Map seleniumEnv = registerSeleniumEnvironment(environment, container, properties.getVnc().getMode().convert(), recordingDirOrNull); + log.info("Started Selenium server. Connection details: {}", seleniumEnv); + return container; + } + + /** + * Testcontainers does not expose its default vnc dir when it is not + * defined, so we recreate this implementation here. + * + * @param vncRecordingDirProperty + * @return + */ + private File getOrCreateTempDir(File vncRecordingDirProperty) { + if (vncRecordingDirProperty != null) { + return vncRecordingDirProperty; + } + + try { + return Files.createTempDirectory(TC_TEMP_DIR_PREFIX).toFile(); + } catch (IOException e) { + // should never happen as per javadoc, since we use valid prefix + log.error("Exception while trying to create temp directory ", e); + throw new ContainerLaunchException("Exception while trying to create temp directory", e); + } + } + + /** + * Users can redefine this to create other strategies of saving + * vnc recordings + * @return + */ + @Bean + @ConditionalOnMissingBean + public RecordingFileFactory getRecordingFileFactory() { + return new DefaultRecordingFileFactory(); + } + + private Map registerSeleniumEnvironment(ConfigurableEnvironment environment, BrowserWebDriverContainer container, BrowserWebDriverContainer.VncRecordingMode vncMode, File recordingDirOrNull) { + URL seleniumAddress = container.getSeleniumAddress(); + String vncAddress = container.getVncAddress(); + URI vncURI = URI.create(vncAddress); + + LinkedHashMap map = new LinkedHashMap<>(); + map.put("embedded.selenium.port", seleniumAddress.getPort()); + map.put("embedded.selenium.host", seleniumAddress.getHost()); + map.put("embedded.selenium.vnc.port", vncURI.getPort()); + map.put("embedded.selenium.vnc.host", vncURI.getHost()); + map.put("embedded.selenium.vnc.username", DEFINED_VNC_USERNAME); + map.put("embedded.selenium.vnc.password", DEFINED_VNC_PASSWORD); + map.put("embedded.selenium.vnc.recording-dir", recordingDirOrNull); + map.put("embedded.selenium.vnc.mode", vncMode); + map.put("embedded.selenium.dockerhost", getHostName(container)); + + MapPropertySource propertySource = new MapPropertySource("embeddedSeleniumInfo", map); + environment.getPropertySources().addFirst(propertySource); + return map; + } + + + /** + * Implementation partly based upon + * + * https://stackoverflow.com/questions/22944631/how-to-get-the-ip-address-of-the-docker-host-from-inside-a-docker-container + * @param container + * @return + */ + public String getHostName(GenericContainer container) { + // unfortunately host.docker.internal only works for mac and windows :( + // and we need to work out the hostname for linux. + String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); + if ((OS.indexOf("mac") >= 0) || (OS.indexOf("darwin") >= 0)) { + return "host.docker.internal"; + } else if (OS.indexOf("win") >= 0) { + return "host.docker.internal"; + } else if (OS.indexOf("nux") >= 0) { + Container.ExecResult execResult; + try { + execResult = container.execInContainer("/sbin/ip route|awk '/default/ { print $3 }'"); + } catch (IOException e) { + log.warn("Cannot find host ip", e); + return DOCKER_FOR_LINUX_STATIC_IP; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return DOCKER_FOR_LINUX_STATIC_IP; + } + String hostIpAddress = execResult.getStdout(); + if(isValidIpAddress(hostIpAddress)) { + return hostIpAddress; + } else { + return DOCKER_FOR_LINUX_STATIC_IP; + } + } + + // currently only supported if docker machine is installed. + // otherwise throws an UnsupportedOpertaion exception + return container.getTestHostIpAddress(); + } + + private boolean isValidIpAddress(String ipAddress) { + if (ipAddress == null) { + return false; + } + return InetAddresses.isInetAddress(ipAddress); + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.testcontainers.containers.BrowserWebDriverContainer` acquired by call to `new()` at line 108 is not released after line 108. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +BrowserWebDriverContainer EmbeddedSeleniumBootstrapConfiguration.selenium(ConfigurableEnvironment,SeleniumProperties,MutableCapabilities) + +### Procedure Id: +com.playtika.test.selenium.EmbeddedSeleniumBootstrapConfiguration.selenium(org.springframework.core..3a2a4e356935b9e046eab1bc7aaf45f4 + +### File: +embedded-selenium/src/main/java/com/playtika/test/selenium/EmbeddedSeleniumBootstrapConfiguration.java + +### Key: +EmbeddedSeleniumBootstrapConfiguration.java|selenium|RESOURCE_LEAK + +### Node Key: +2f97b1fc6f8a8fb00a85579cce991a66 + +### Hash: +ec66661089963f01e1cc631c4010b08a + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-2926/instruction.md b/inferredbugs-2926/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f0251ee6cddfbd57afbcd7479f9aba7202576f66 --- /dev/null +++ b/inferredbugs-2926/instruction.md @@ -0,0 +1,1441 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** webdrivermanager +**Bug ID:** 68 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * (C) Copyright 2015 Boni Garcia (http://bonigarcia.github.io/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package io.github.bonigarcia.wdm; + +import static io.github.bonigarcia.wdm.Architecture.X32; +import static io.github.bonigarcia.wdm.Architecture.X64; +import static io.github.bonigarcia.wdm.Config.isNullOrEmpty; +import static io.github.bonigarcia.wdm.DriverManagerType.CHROME; +import static io.github.bonigarcia.wdm.DriverManagerType.CHROMIUM; +import static io.github.bonigarcia.wdm.DriverManagerType.EDGE; +import static io.github.bonigarcia.wdm.DriverManagerType.FIREFOX; +import static io.github.bonigarcia.wdm.DriverManagerType.IEXPLORER; +import static io.github.bonigarcia.wdm.DriverManagerType.OPERA; +import static io.github.bonigarcia.wdm.DriverManagerType.PHANTOMJS; +import static io.github.bonigarcia.wdm.DriverManagerType.SELENIUM_SERVER_STANDALONE; +import static io.github.bonigarcia.wdm.OperatingSystem.WIN; +import static io.github.bonigarcia.wdm.Shell.getVersionFromPosixOutput; +import static io.github.bonigarcia.wdm.Shell.getVersionFromWmicOutput; +import static io.github.bonigarcia.wdm.Shell.runAndWait; +import static java.io.File.separator; +import static java.lang.Integer.parseInt; +import static java.lang.Integer.signum; +import static java.lang.Integer.valueOf; +import static java.lang.invoke.MethodHandles.lookup; +import static java.nio.charset.Charset.defaultCharset; +import static java.util.Collections.sort; +import static java.util.Optional.empty; +import static java.util.regex.Pattern.CASE_INSENSITIVE; +import static java.util.regex.Pattern.compile; +import static javax.xml.xpath.XPathConstants.NODESET; +import static javax.xml.xpath.XPathFactory.newInstance; +import static org.apache.commons.io.FileUtils.deleteDirectory; +import static org.apache.commons.io.FileUtils.listFiles; +import static org.apache.commons.io.FilenameUtils.removeExtension; +import static org.apache.commons.lang3.StringUtils.isNumeric; +import static org.apache.commons.lang3.SystemUtils.IS_OS_LINUX; +import static org.apache.commons.lang3.SystemUtils.IS_OS_MAC; +import static org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS; +import static org.slf4j.LoggerFactory.getLogger; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Properties; +import java.util.regex.Matcher; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.IOUtils; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.jsoup.Jsoup; +import org.slf4j.Logger; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.internal.LinkedTreeMap; + +/** + * Parent driver manager. + * + * @author Boni Garcia (boni.gg@gmail.com) + * @since 2.1.0 + */ +public abstract class WebDriverManager { + + static final Logger log = getLogger(lookup().lookupClass()); + + protected static final String SLASH = "/"; + protected static final String BETA = "beta"; + protected static final String ONLINE = "online"; + protected static final String LOCAL = "local"; + protected static final String LATEST_RELEASE = "LATEST_RELEASE"; + + protected abstract List getDrivers() throws IOException; + + protected abstract Optional getBrowserVersion(); + + protected abstract DriverManagerType getDriverManagerType(); + + protected abstract String getDriverName(); + + protected abstract void setDriverVersion(String version); + + protected abstract String getDriverVersion(); + + protected abstract void setDriverUrl(URL url); + + protected abstract URL getDriverUrl(); + + protected abstract Optional getMirrorUrl(); + + protected abstract Optional getExportParameter(); + + protected static Map instanceMap = new EnumMap<>( + DriverManagerType.class); + + protected HttpClient httpClient; + protected Downloader downloader; + protected UrlFilter urlFilter; + protected String versionToDownload; + protected String downloadedVersion; + protected String binaryPath; + protected boolean mirrorLog; + protected boolean forcedArch; + protected boolean forcedOs; + protected boolean isSnap; + protected int retryCount = 0; + protected Config config = new Config(); + protected Preferences preferences = new Preferences(config); + protected String preferenceKey; + protected Properties versionsProperties; + + public static Config globalConfig() { + Config global = new Config(); + global.setAvoidAutoReset(true); + for (DriverManagerType type : DriverManagerType.values()) { + WebDriverManager.getInstance(type).setConfig(global); + } + return global; + } + + public Config config() { + return config; + } + + public static synchronized WebDriverManager chromedriver() { + instanceMap.putIfAbsent(CHROME, new ChromeDriverManager()); + return instanceMap.get(CHROME); + } + + public static synchronized WebDriverManager chromiumdriver() { + instanceMap.putIfAbsent(CHROMIUM, new ChromiumDriverManager()); + return instanceMap.get(CHROMIUM); + } + + public static synchronized WebDriverManager firefoxdriver() { + instanceMap.putIfAbsent(FIREFOX, new FirefoxDriverManager()); + return instanceMap.get(FIREFOX); + } + + public static synchronized WebDriverManager operadriver() { + instanceMap.putIfAbsent(OPERA, new OperaDriverManager()); + return instanceMap.get(OPERA); + } + + public static synchronized WebDriverManager edgedriver() { + instanceMap.putIfAbsent(EDGE, new EdgeDriverManager()); + return instanceMap.get(EDGE); + } + + public static synchronized WebDriverManager iedriver() { + instanceMap.putIfAbsent(IEXPLORER, new InternetExplorerDriverManager()); + return instanceMap.get(IEXPLORER); + } + + public static synchronized WebDriverManager phantomjs() { + instanceMap.putIfAbsent(PHANTOMJS, new PhantomJsDriverManager()); + return instanceMap.get(PHANTOMJS); + } + + public static synchronized WebDriverManager seleniumServerStandalone() { + instanceMap.putIfAbsent(SELENIUM_SERVER_STANDALONE, + new SeleniumServerStandaloneManager()); + return instanceMap.get(SELENIUM_SERVER_STANDALONE); + } + + protected static synchronized WebDriverManager voiddriver() { + return new VoidDriverManager(); + } + + public static synchronized WebDriverManager getInstance( + DriverManagerType driverManagerType) { + if (driverManagerType == null) { + return voiddriver(); + } + switch (driverManagerType) { + case CHROME: + return chromedriver(); + case CHROMIUM: + return chromiumdriver(); + case FIREFOX: + return firefoxdriver(); + case OPERA: + return operadriver(); + case IEXPLORER: + return iedriver(); + case EDGE: + return edgedriver(); + case PHANTOMJS: + return phantomjs(); + case SELENIUM_SERVER_STANDALONE: + return seleniumServerStandalone(); + default: + return voiddriver(); + } + } + + public static synchronized WebDriverManager getInstance( + Class webDriverClass) { + switch (webDriverClass.getName()) { + case "org.openqa.selenium.chrome.ChromeDriver": + return chromedriver(); + case "org.openqa.selenium.firefox.FirefoxDriver": + return firefoxdriver(); + case "org.openqa.selenium.opera.OperaDriver": + return operadriver(); + case "org.openqa.selenium.ie.InternetExplorerDriver": + return iedriver(); + case "org.openqa.selenium.edge.EdgeDriver": + return edgedriver(); + case "org.openqa.selenium.phantomjs.PhantomJSDriver": + return phantomjs(); + default: + return voiddriver(); + } + } + + public synchronized void setup() { + DriverManagerType driverManagerType = getDriverManagerType(); + if (driverManagerType != null) { + try { + if (config().getClearPreferences()) { + clearPreferences(); + } + String driverVersion = getDriverVersion(); + manage(driverVersion); + } finally { + if (!config().isAvoidAutoReset()) { + reset(); + } + } + } + } + + public WebDriverManager version(String version) { + setDriverVersion(version); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager architecture(Architecture architecture) { + config().setArchitecture(architecture); + forcedArch = true; + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager arch32() { + architecture(X32); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager arch64() { + architecture(X64); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager operatingSystem(OperatingSystem os) { + config().setOs(os.name()); + forcedOs = true; + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager forceCache() { + config().setForceCache(true); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager forceDownload() { + config().setOverride(true); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager driverRepositoryUrl(URL url) { + setDriverUrl(url); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager useMirror() { + Optional mirrorUrl = getMirrorUrl(); + if (!mirrorUrl.isPresent()) { + throw new WebDriverManagerException("Mirror URL not available"); + } + config().setUseMirror(true); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager proxy(String proxy) { + config().setProxy(proxy); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager proxyUser(String proxyUser) { + config().setProxyUser(proxyUser); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager proxyPass(String proxyPass) { + config().setProxyPass(proxyPass); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager useBetaVersions() { + config().setUseBetaVersions(true); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager ignoreVersions(String... versions) { + config().setIgnoreVersions(versions); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager gitHubTokenSecret(String gitHubTokenSecret) { + config().setGitHubTokenSecret(gitHubTokenSecret); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager gitHubTokenName(String gitHubTokenName) { + config().setGitHubTokenName(gitHubTokenName); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager localRepositoryUser(String localRepositoryUser) { + config().setLocalRepositoryUser(localRepositoryUser); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager localRepositoryPassword( + String localRepositoryPassword) { + config().setLocalRepositoryPassword(localRepositoryPassword); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager timeout(int timeout) { + config().setTimeout(timeout); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager properties(String properties) { + config().setProperties(properties); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager targetPath(String targetPath) { + config().setTargetPath(targetPath); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager avoidExport() { + config().setAvoidExport(true); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager avoidOutputTree() { + config().setAvoidOutputTree(true); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager avoidAutoVersion() { + config().setAvoidAutoVersion(true); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager avoidPreferences() { + config().setAvoidPreferences(true); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager ttl(int seconds) { + config().setTtl(seconds); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager browserPath(String browserPath) { + config().setBinaryPath(browserPath); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager useLocalVersionsPropertiesFirst() { + config().setVersionsPropertiesOnlineFirst(false); + return instanceMap.get(getDriverManagerType()); + } + + public WebDriverManager clearPreferences() { + instanceMap.get(getDriverManagerType()).preferences.clear(); + return instanceMap.get(getDriverManagerType()); + } + + // ------------ + + public String getBinaryPath() { + return instanceMap.get(getDriverManagerType()).binaryPath; + } + + public String getDownloadedVersion() { + return instanceMap.get(getDriverManagerType()).downloadedVersion; + } + + public List getVersions() { + httpClient = new HttpClient(config()); + try { + List drivers = getDrivers(); + List versions = new ArrayList<>(); + for (URL url : drivers) { + String version = getCurrentVersion(url); + if (version.isEmpty() || version.equalsIgnoreCase("icons")) { + continue; + } + if (!versions.contains(version)) { + versions.add(version); + } + } + log.trace("Version list before sorting {}", versions); + sort(versions, new VersionComparator()); + return versions; + } catch (IOException e) { + throw new WebDriverManagerException(e); + } + } + + public void clearCache() { + String targetPath = config().getTargetPath(); + try { + log.debug("Clearing cache at {}", targetPath); + deleteDirectory(new File(targetPath)); + } catch (Exception e) { + log.warn("Exception deleting cache at {}", targetPath, e); + } + } + + // ------------ + + protected void manage(String driverVersion) { + httpClient = new HttpClient(config()); + try (HttpClient wdmHttpClient = httpClient) { + downloader = new Downloader(getDriverManagerType()); + urlFilter = new UrlFilter(); + + if (isUnknown(driverVersion)) { + driverVersion = resolveDriverVersion(driverVersion); + } + + downloadAndExport(driverVersion); + + } catch (Exception e) { + handleException(e, driverVersion); + } + } + + protected String resolveDriverVersion(String driverVersion) { + preferenceKey = getDriverManagerType().getNameInLowerCase(); + Optional browserVersion = empty(); + browserVersion = getValueFromPreferences(browserVersion); + if (!browserVersion.isPresent()) { + browserVersion = detectBrowserVersion(); + } + if (browserVersion.isPresent()) { + preferenceKey = getDriverManagerType().getNameInLowerCase() + + browserVersion.get(); + driverVersion = preferences.getValueFromPreferences(preferenceKey); + + Optional optionalDriverVersion = empty(); + if (isUnknown(driverVersion)) { + optionalDriverVersion = getDriverVersionFromRepository( + browserVersion); + } + if (isUnknown(driverVersion)) { + optionalDriverVersion = getDriverVersionFromProperties( + preferenceKey); + } + if (optionalDriverVersion.isPresent()) { + driverVersion = optionalDriverVersion.get(); + } + if (isUnknown(driverVersion)) { + log.debug( + "The driver version for {} {} is unknown ... trying with latest", + getDriverManagerType(), browserVersion.get()); + } else if (!isUnknown(driverVersion)) { + log.info( + "Using {} {} (since {} {} is installed in your machine)", + getDriverName(), driverVersion, getDriverManagerType(), + browserVersion.get()); + storeInPreferences(driverVersion, browserVersion.get()); + } + } + + // if driverVersion is still unknown, try with latest + if (isUnknown(driverVersion)) { + Optional latestDriverVersionFromRepository = getLatestDriverVersionFromRepository(); + if (latestDriverVersionFromRepository.isPresent()) { + driverVersion = latestDriverVersionFromRepository.get(); + } + } + return driverVersion; + } + + protected void storeInPreferences(String driverVersion, + String browserVersion) { + if (usePreferences()) { + preferences.putValueInPreferencesIfEmpty( + getDriverManagerType().getNameInLowerCase(), + browserVersion); + preferences.putValueInPreferencesIfEmpty(preferenceKey, + driverVersion); + } + } + + protected Optional getValueFromPreferences( + Optional browserVersion) { + if (usePreferences() + && preferences.checkKeyInPreferences(preferenceKey)) { + browserVersion = Optional + .of(preferences.getValueFromPreferences(preferenceKey)); + } + return browserVersion; + } + + protected String preDownload(String target, String version) { + log.trace("Pre-download. target={}, version={}", target, version); + return target; + } + + protected File postDownload(File archive) { + File parentFolder = archive.getParentFile(); + File[] ls = parentFolder.listFiles(); + for (File f : ls) { + if (getDriverName().contains(removeExtension(f.getName()))) { + log.trace("Found binary in post-download: {}", f); + return f; + } + } + throw new WebDriverManagerException("Driver " + getDriverName() + + " not found (using temporal folder " + parentFolder + ")"); + } + + protected String getCurrentVersion(URL url) { + String currentVersion = ""; + String pattern = "/([^/]*?)/[^/]*?" + getShortDriverName(); + Matcher matcher = compile(pattern, CASE_INSENSITIVE) + .matcher(url.getFile()); + boolean find = matcher.find(); + if (find) { + currentVersion = matcher.group(1); + } else { + log.trace("Version not found in URL {}", url); + } + return currentVersion; + } + + protected void downloadAndExport(String driverVersion) throws IOException { + Optional driverInCache = searchDriverInCache(driverVersion); + String versionStr = isUnknown(driverVersion) ? "(latest version)" + : driverVersion; + + if (driverInCache.isPresent() && !config().isOverride()) { + storeVersionToDownload(driverVersion); + downloadedVersion = driverVersion; + log.debug("Driver {} {} found in cache", getDriverName(), + versionStr); + exportDriver(driverInCache.get()); + } else { + List candidateUrls = getCandidateUrls(driverVersion); + if (candidateUrls.isEmpty()) { + Architecture arch = config().getArchitecture(); + String os = config().getOs(); + String errorMessage = getDriverName() + " " + versionStr + + " for " + os + arch.toString() + " not found in " + + getDriverUrl(); + log.error(errorMessage); + throw new WebDriverManagerException(errorMessage); + } + + // Download first candidate URL + URL url = candidateUrls.iterator().next(); + String exportValue = downloader.download(url, versionToDownload, + getDriverName()); + exportDriver(exportValue); + downloadedVersion = versionToDownload; + } + } + + protected Optional detectBrowserVersion() { + if (config().isAvoidAutoVersion()) { + return empty(); + } + + String driverManagerTypeLowerCase = getDriverManagerType().name() + .toLowerCase(); + Optional browserVersion; + if (usePreferences() && preferences + .checkKeyInPreferences(driverManagerTypeLowerCase)) { + browserVersion = Optional.of(preferences + .getValueFromPreferences(driverManagerTypeLowerCase)); + + log.trace("Detected {} version {}", getDriverManagerType(), + browserVersion); + } else { + browserVersion = getBrowserVersion(); + } + return browserVersion; + } + + protected boolean usePreferences() { + return !config().isAvoidPreferences() && !config().isOverride() + && !forcedArch && !forcedOs; + } + + protected boolean isUnknown(String driverVersion) { + return isNullOrEmpty(driverVersion) + || driverVersion.equalsIgnoreCase("latest"); + } + + protected Optional getDriverVersionFromProperties(String key) { + boolean online = config().getVersionsPropertiesOnlineFirst(); + String onlineMessage = online ? ONLINE : LOCAL; + log.debug("Getting driver version for {} from {} versions.properties", + key, onlineMessage); + String value = getVersionFromProperties(online).getProperty(key); + if (value == null) { + String notOnlineMessage = online ? LOCAL : ONLINE; + log.debug( + "Driver for {} not found in {} properties (using {} version)", + key, onlineMessage, notOnlineMessage); + versionsProperties = null; + value = getVersionFromProperties(!online).getProperty(key); + } + return value == null ? empty() : Optional.of(value); + } + + protected Properties getVersionFromProperties(boolean online) { + if (versionsProperties != null) { + log.trace("Already created versions.properties"); + return versionsProperties; + } else { + try (InputStream inputStream = getVersionsInputStream(online)) { + versionsProperties = new Properties(); + versionsProperties.load(inputStream); + } catch (Exception e) { + versionsProperties = null; + throw new IllegalStateException( + "Cannot read versions.properties", e); + } + return versionsProperties; + } + } + + protected InputStream getVersionsInputStream(boolean online) + throws IOException { + String onlineMessage = online ? ONLINE : LOCAL; + log.trace("Reading {} version.properties to find out driver version", + onlineMessage); + InputStream inputStream; + try { + if (online) { + inputStream = getOnlineVersionsInputStream(); + } else { + inputStream = getLocalVersionsInputStream(); + } + } catch (Exception e) { + String exceptionMessage = online ? LOCAL : ONLINE; + log.warn("Error reading version.properties, using {} instead", + exceptionMessage); + if (online) { + inputStream = getLocalVersionsInputStream(); + } else { + inputStream = getOnlineVersionsInputStream(); + } + } + return inputStream; + } + + protected InputStream getLocalVersionsInputStream() { + InputStream inputStream; + inputStream = Config.class.getResourceAsStream("/versions.properties"); + return inputStream; + } + + protected InputStream getOnlineVersionsInputStream() throws IOException { + return httpClient + .execute(httpClient + .createHttpGet(config().getVersionsPropertiesUrl())) + .getEntity().getContent(); + } + + protected void handleException(Exception e, String version) { + String versionStr = isNullOrEmpty(version) ? "(latest version)" + : version; + String errorMessage = String.format( + "There was an error managing %s %s (%s)", getDriverName(), + versionStr, e.getMessage()); + if (!config().isForceCache() && retryCount == 0) { + config().setForceCache(true); + config().setUseMirror(true); + retryCount++; + log.warn("{} ... trying again using mirror", errorMessage); + manage(version); + } else if (retryCount == 1) { + config().setAvoidAutoVersion(true); + version = ""; + retryCount++; + log.warn("{} ... trying again using latest from cache", + errorMessage); + manage(version); + } else { + log.error("{}", errorMessage, e); + throw new WebDriverManagerException(e); + } + } + + protected List getCandidateUrls(String driverVersion) + throws IOException { + List urls = getDrivers(); + List candidateUrls; + log.trace("All URLs: {}", urls); + boolean getLatest = isUnknown(driverVersion); + Architecture arch = config().getArchitecture(); + boolean continueSearchingVersion; + + do { + // Get the latest or concrete version + String filterName = getShortDriverName(); + candidateUrls = getLatest ? checkLatest(urls, filterName) + : getVersion(urls, filterName, driverVersion); + log.trace("Candidate URLs: {}", candidateUrls); + if (versionToDownload == null) { + break; + } + + // Filter by OS + if (!getDriverName().equalsIgnoreCase("IEDriverServer") + && !getDriverName() + .equalsIgnoreCase("selenium-server-standalone")) { + candidateUrls = urlFilter.filterByOs(candidateUrls, + config().getOs()); + } + + // Filter by architecture + candidateUrls = urlFilter.filterByArch(candidateUrls, arch, + forcedArch); + + // Filter by distro + candidateUrls = filterByDistro(candidateUrls); + + // Filter by ignored versions + candidateUrls = filterByIgnoredVersions(candidateUrls); + + // Filter by beta + candidateUrls = urlFilter.filterByBeta(candidateUrls, + config().isUseBetaVersions()); + + // Find out if driver version has been found or not + continueSearchingVersion = candidateUrls.isEmpty() && getLatest; + if (continueSearchingVersion) { + log.info( + "No binary found for {} {} ... seeking another version", + getDriverName(), versionToDownload); + urls = removeFromList(urls, versionToDownload); + versionToDownload = null; + } + } while (continueSearchingVersion); + return candidateUrls; + } + + protected List filterByIgnoredVersions(List candidateUrls) { + if (config().getIgnoreVersions() != null && !candidateUrls.isEmpty()) { + candidateUrls = urlFilter.filterByIgnoredVersions(candidateUrls, + config().getIgnoreVersions()); + } + return candidateUrls; + } + + protected List filterByDistro(List candidateUrls) + throws IOException { + // Filter phantomjs 2.5.0 in Linux + if (config().getOs().equalsIgnoreCase("linux") + && getDriverName().contains("phantomjs")) { + candidateUrls = urlFilter.filterByDistro(candidateUrls, "2.5.0"); + } + return candidateUrls; + } + + protected Optional searchDriverInCache(String driverVersion) { + Optional driverInCache = empty(); + boolean getLatest = isUnknown(driverVersion); + boolean cache = config().isForceCache(); + + if (cache || !getLatest) { + driverInCache = getDriverFromCache(driverVersion); + } + storeVersionToDownload(driverVersion); + return driverInCache; + } + + protected Optional getDriverFromCache(String driverVersion) { + log.trace("Checking if {} exists in cache", getDriverName()); + Architecture arch = config().getArchitecture(); + String os = config().getOs(); + List filesInCache = getFilesInCache(); + if (!filesInCache.isEmpty()) { + // Filter by name + filesInCache = filterCacheBy(filesInCache, getDriverName(), false); + + // Filter by version + filesInCache = filterCacheBy(filesInCache, driverVersion, true); + + // Filter by OS + filesInCache = filterCacheBy(filesInCache, os, false); + + if (filesInCache.size() == 1) { + return Optional.of(filesInCache.get(0).toString()); + } + + // Filter by arch + if (IS_OS_WINDOWS && (getDriverManagerType() == CHROME + || getDriverManagerType() == CHROMIUM)) { + log.trace( + "Avoid filtering for architecture {} with {} in Windows", + arch, getDriverName()); + } else { + filesInCache = filterCacheBy(filesInCache, arch.toString(), + false); + } + + if (!filesInCache.isEmpty()) { + return Optional.of( + filesInCache.get(filesInCache.size() - 1).toString()); + } + } + + log.trace("{} not found in cache", getDriverName()); + return empty(); + } + + protected List filterCacheBy(List input, String key, + boolean isVersion) { + String pathSeparator = isVersion ? separator : ""; + List output = new ArrayList<>(input); + if (!key.isEmpty() && !input.isEmpty()) { + String keyInLowerCase = key.toLowerCase(); + for (File f : input) { + if (!f.toString().toLowerCase() + .contains(pathSeparator + keyInLowerCase)) { + output.remove(f); + } + } + } + log.trace("Filter cache by {} -- input list {} -- output list {} ", key, + input, output); + return output; + } + + protected List getFilesInCache() { + List listFiles = (List) listFiles( + new File(downloader.getTargetPath()), null, true); + sort(listFiles); + return listFiles; + } + + protected List removeFromList(List list, String version) { + List out = new ArrayList<>(list); + for (URL url : list) { + if (url.getFile().contains(version)) { + out.remove(url); + } + } + return out; + } + + protected List getVersion(List list, String driver, + String version) { + List out = new ArrayList<>(); + for (URL url : list) { + if (url.getFile().contains(driver) + && url.getFile().contains(version) + && !url.getFile().contains("-symbols")) { + out.add(url); + } + } + + if (versionToDownload != null && !versionToDownload.equals(version)) { + versionToDownload = version; + log.info("Using {} {}", driver, version); + } + return out; + } + + protected List checkLatest(List list, String driver) { + log.trace("Checking the lastest version of {} with URL list {}", driver, + list); + List out = new ArrayList<>(); + List copyOfList = new ArrayList<>(list); + + for (URL url : copyOfList) { + try { + if (!config().isUseBetaVersions() + && (url.getFile().toLowerCase().contains(BETA))) { + continue; + } + if (url.getFile().contains(driver)) { + String currentVersion = getCurrentVersion(url); + if (versionToDownload == null) { + versionToDownload = currentVersion; + } + if (versionCompare(currentVersion, versionToDownload) > 0) { + versionToDownload = currentVersion; + out.clear(); + } + if (url.getFile().contains(versionToDownload)) { + out.add(url); + } + } + } catch (Exception e) { + log.trace("There was a problem with URL {} : {}", url, + e.getMessage()); + list.remove(url); + } + } + storeVersionToDownload(versionToDownload); + log.info("Latest version of {} is {}", driver, versionToDownload); + return out; + } + + protected Integer versionCompare(String str1, String str2) { + String[] vals1 = str1.replace("v", "").replace("-beta", "") + .split("\\."); + String[] vals2 = str2.replace("v", "").replace("-beta", "") + .split("\\."); + + if (vals1[0].equals("")) { + vals1[0] = "0"; + } + if (vals2[0].equals("")) { + vals2[0] = "0"; + } + + int i = 0; + while (i < vals1.length && i < vals2.length + && vals1[i].equals(vals2[i])) { + i++; + } + + if (i < vals1.length && i < vals2.length) { + return signum(valueOf(vals1[i]).compareTo(valueOf(vals2[i]))); + } else { + return signum(vals1.length - vals2.length); + } + } + + /** + * This method works also for http://npm.taobao.org/ and + * https://bitbucket.org/ mirrors. + */ + protected List getDriversFromMirror(URL driverUrl) throws IOException { + if (mirrorLog) { + log.info("Crawling driver list from mirror {}", driverUrl); + mirrorLog = true; + } else { + log.trace("[Recursive call] Crawling driver list from mirror {}", + driverUrl); + } + + String driverStr = driverUrl.toString(); + String driverOrigin = String.format("%s://%s", driverUrl.getProtocol(), + driverUrl.getAuthority()); + + try (CloseableHttpResponse response = httpClient + .execute(httpClient.createHttpGet(driverUrl))) { + InputStream in = response.getEntity().getContent(); + org.jsoup.nodes.Document doc = Jsoup.parse(in, null, driverStr); + Iterator iterator = doc.select("a") + .iterator(); + List urlList = new ArrayList<>(); + + while (iterator.hasNext()) { + String link = iterator.next().attr("abs:href"); + if (link.startsWith(driverStr) && link.endsWith(SLASH)) { + urlList.addAll(getDriversFromMirror(new URL(link))); + } else if (link.startsWith(driverOrigin) + && !link.contains("icons") + && (link.toLowerCase().endsWith(".bz2") + || link.toLowerCase().endsWith(".zip") + || link.toLowerCase().endsWith(".gz"))) { + urlList.add(new URL(link)); + } + } + return urlList; + } + } + + protected List getDriversFromXml(URL driverUrl, String xpath) + throws IOException { + log.info("Reading {} to seek {}", driverUrl, getDriverName()); + List urls = new ArrayList<>(); + try { + try (CloseableHttpResponse response = httpClient + .execute(httpClient.createHttpGet(driverUrl))) { + Document xml = loadXML(response.getEntity().getContent()); + NodeList nodes = (NodeList) newInstance().newXPath() + .evaluate(xpath, xml.getDocumentElement(), NODESET); + + for (int i = 0; i < nodes.getLength(); ++i) { + Element e = (Element) nodes.item(i); + urls.add(new URL(driverUrl.toURI().resolve(".") + + e.getChildNodes().item(0).getNodeValue())); + } + } + } catch (Exception e) { + throw new WebDriverManagerException(e); + } + return urls; + } + + protected Document loadXML(InputStream inputStream) + throws SAXException, IOException, ParserConfigurationException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + return builder.parse(new InputSource( + new ByteArrayInputStream(IOUtils.toByteArray(inputStream)))); + } + + protected void exportDriver(String variableValue) { + binaryPath = variableValue; + Optional exportParameter = getExportParameter(); + if (!config.isAvoidExport() && exportParameter.isPresent()) { + String variableName = exportParameter.get(); + log.info("Exporting {} as {}", variableName, variableValue); + System.setProperty(variableName, variableValue); + } else { + log.info("Resulting binary {}", variableValue); + } + } + + protected InputStream openGitHubConnection(URL driverUrl) + throws IOException { + HttpGet get = httpClient.createHttpGet(driverUrl); + + String gitHubTokenName = config().getGitHubTokenName(); + String gitHubTokenSecret = config().getGitHubTokenSecret(); + if (!isNullOrEmpty(gitHubTokenName) + && !isNullOrEmpty(gitHubTokenSecret)) { + String userpass = gitHubTokenName + ":" + gitHubTokenSecret; + String basicAuth = "Basic " + + new String(new Base64().encode(userpass.getBytes())); + get.addHeader("Authorization", basicAuth); + } + + return httpClient.execute(get).getEntity().getContent(); + } + + protected List getDriversFromGitHub() throws IOException { + List urls; + URL driverUrl = getDriverUrl(); + log.info("Reading {} to seek {}", driverUrl, getDriverName()); + + Optional mirrorUrl = getMirrorUrl(); + if (mirrorUrl.isPresent() && config.isUseMirror()) { + urls = getDriversFromMirror(mirrorUrl.get()); + + } else { + String driverVersion = versionToDownload; + + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(openGitHubConnection(driverUrl)))) { + + GsonBuilder gsonBuilder = new GsonBuilder(); + Gson gson = gsonBuilder.create(); + GitHubApi[] releaseArray = gson.fromJson(reader, + GitHubApi[].class); + + if (driverVersion != null) { + releaseArray = new GitHubApi[] { + getVersion(releaseArray, driverVersion) }; + } + + urls = new ArrayList<>(); + for (GitHubApi release : releaseArray) { + if (release != null) { + List> assets = release + .getAssets(); + for (LinkedTreeMap asset : assets) { + urls.add(new URL(asset.get("browser_download_url") + .toString())); + } + } + } + } + } + return urls; + } + + protected GitHubApi getVersion(GitHubApi[] releaseArray, String version) { + GitHubApi out = null; + for (GitHubApi release : releaseArray) { + log.trace("Get version {} of {}", version, release); + if ((release.getName() != null + && release.getName().contains(version)) + || (release.getTagName() != null + && release.getTagName().contains(version))) { + out = release; + break; + } + } + return out; + } + + protected HttpClient getHttpClient() { + return httpClient; + } + + protected FilenameFilter getFolderFilter() { + return (dir, name) -> dir.isDirectory() + && name.toLowerCase().contains(getDriverName()); + } + + protected Optional getDefaultBrowserVersion( + String[] programFilesEnvs, String[] winBrowserNames, + String linuxBrowserName, String macBrowserName, String versionFlag, + String browserNameInOutput) { + + String browserBinaryPath = config().getBinaryPath(); + if (IS_OS_WINDOWS) { + String winName = ""; + for (int i = 0; i < programFilesEnvs.length; i++) { + winName = winBrowserNames.length > 1 ? winBrowserNames[0] + : winBrowserNames[i]; + String browserVersionOutput = getBrowserVersionInWindows( + programFilesEnvs[i], winName, browserBinaryPath); + if (!isNullOrEmpty(browserVersionOutput)) { + return Optional + .of(getVersionFromWmicOutput(browserVersionOutput)); + } + } + } else if (IS_OS_LINUX || IS_OS_MAC) { + String browserPath = getPosixBrowserPath(linuxBrowserName, + macBrowserName, browserBinaryPath); + String browserVersionOutput = runAndWait(browserPath, versionFlag); + if (browserVersionOutput.toLowerCase().contains("snap")) { + isSnap = true; + } + if (!isNullOrEmpty(browserVersionOutput)) { + return Optional.of(getVersionFromPosixOutput( + browserVersionOutput, browserNameInOutput)); + } + } + return empty(); + } + + protected String getPosixBrowserPath(String linuxBrowserName, + String macBrowserName, String browserBinaryPath) { + if (!isNullOrEmpty(browserBinaryPath)) { + return browserBinaryPath; + } else { + return IS_OS_LINUX ? linuxBrowserName : macBrowserName; + } + } + + protected String getBrowserVersionInWindows(String programFilesEnv, + String winBrowserName, String browserBinaryPath) { + String programFiles = System.getenv(programFilesEnv).replaceAll("\\\\", + "\\\\\\\\"); + String browserPath = isNullOrEmpty(browserBinaryPath) + ? programFiles + winBrowserName + : browserBinaryPath; + String wmic = "wmic.exe"; + return runAndWait(findFileLocation(wmic), wmic, "datafile", "where", + "name='" + browserPath + "'", "get", "Version", "/value"); + } + + protected File findFileLocation(String filename) { + // Alternative #1: in System32 folder + File system32Folder = new File(System.getenv("SystemRoot"), "System32"); + File system32File = new File(system32Folder, filename); + if (checkFileAndFolder(system32Folder, system32File)) { + return system32Folder; + } + // Alternative #2: in wbem folder + File wbemFolder = new File(system32Folder, "wbem"); + File wbemFile = new File(wbemFolder, filename); + if (checkFileAndFolder(wbemFolder, wbemFile)) { + return wbemFolder; + } + return new File("."); + } + + protected boolean checkFileAndFolder(File folder, File file) { + return folder.exists() && folder.isDirectory() && file.exists() + && file.isFile(); + } + + protected Charset getVersionCharset() { + return defaultCharset(); + } + + protected String getLatestVersionLabel() { + return LATEST_RELEASE; + } + + protected void reset() { + config().reset(); + mirrorLog = false; + versionToDownload = null; + forcedArch = false; + forcedOs = false; + retryCount = 0; + isSnap = false; + } + + protected String getProgramFilesEnv() { + return System.getProperty("os.arch").contains("64") + ? "PROGRAMFILES(X86)" + : "PROGRAMFILES"; + } + + protected String getOtherProgramFilesEnv() { + return System.getProperty("os.arch").contains("64") ? "PROGRAMFILES" + : "PROGRAMFILES(X86)"; + } + + protected URL getDriverUrlCkeckingMirror(URL url) { + if (config().isUseMirror()) { + Optional mirrorUrl = getMirrorUrl(); + if (mirrorUrl.isPresent()) { + return mirrorUrl.get(); + } + } + return url; + } + + protected static void resolveLocal(String validBrowsers, String arg) { + log.info("Using WebDriverManager to resolve {}", arg); + try { + DriverManagerType driverManagerType = DriverManagerType + .valueOf(arg.toUpperCase()); + WebDriverManager wdm = WebDriverManager + .getInstance(driverManagerType).avoidExport() + .targetPath(".").forceDownload(); + if (arg.equalsIgnoreCase("edge") + || arg.equalsIgnoreCase("iexplorer")) { + wdm.operatingSystem(WIN); + } + wdm.avoidOutputTree().setup(); + } catch (Exception e) { + log.error("Driver for {} not found (valid browsers {})", arg, + validBrowsers); + } + } + + protected static void startServer(String[] args) { + int port = new Config().getServerPort(); + if (args.length > 1 && isNumeric(args[1])) { + port = parseInt(args[1]); + } + new Server(port); + } + + protected static void logCliError(String validBrowsers) { + log.error("There are 3 options to run WebDriverManager CLI"); + log.error( + "1. WebDriverManager used to resolve binary drivers locally:"); + log.error("\tWebDriverManager browserName"); + log.error("\t(where browserName={})", validBrowsers); + + log.error("2. WebDriverManager as a server:"); + log.error("\tWebDriverManager server "); + log.error("\t(where default port is 4041)"); + + log.error( + "3. To clear previously resolved driver versions (as Java preferences):"); + log.error("\tWebDriverManager clear-preferences"); + } + + protected void storeVersionToDownload(String version) { + if (!isNullOrEmpty(version)) { + if (version.startsWith(".")) { + version = version.substring(1); + } + versionToDownload = version; + } + } + + protected void setConfig(Config config) { + this.config = config; + } + + protected Optional getLatestDriverVersionFromRepository() { + return empty(); + } + + protected Optional getDriverVersionFromRepository( + Optional version) { + String url = version.isPresent() + ? getDriverUrl() + LATEST_RELEASE + "_" + version.get() + : getDriverUrl() + getLatestVersionLabel(); + Optional result = Optional.empty(); + try (InputStream response = httpClient + .execute(httpClient.createHttpGet(new URL(url))).getEntity() + .getContent()) { + result = Optional.of(IOUtils.toString(response, getVersionCharset()) + .replaceAll("\r\n", "")); + } catch (Exception e) { + log.warn("Exception reading {} to get latest version of {} ({})", + url, getDriverName(), e.getMessage()); + } + if (result.isPresent()) { + log.debug("Latest version of {} according to {} is {}", + getDriverName(), url, result.get()); + } + return result; + } + + protected String getShortDriverName() { + return getDriverName(); + } + + public static void main(String[] args) { + String validBrowsers = "chrome|firefox|opera|edge|phantomjs|iexplorer|selenium_server_standalone"; + if (args.length <= 0) { + logCliError(validBrowsers); + } else { + String arg = args[0]; + if (arg.equalsIgnoreCase("server")) { + startServer(args); + } else if (arg.equalsIgnoreCase("clear-preferences")) { + new Preferences(new Config()).clear(); + } else { + resolveLocal(validBrowsers, arg); + } + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `io.github.bonigarcia.wdm.WebDriverManager.getDriverVersionFromProperties` indirectly writes to field `$T1_103.io.github.bonigarcia.wdm.WebDriverManager.versionsProperties` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +Note that the prefix path $T1_103 has been contaminated during the execution, so the reported race on $T1_103.io.github.bonigarcia.wdm.WebDriverManager.versionsProperties might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Optional WebDriverManager.getDriverVersionFromProperties(String) + +### Procedure Id: +io.github.bonigarcia.wdm.WebDriverManager.getDriverVersionFromProperties(java.lang.String):java.util.deacd4dcd2197c62cda83e23d0bcf3d8 + +### File: +src/main/java/io/github/bonigarcia/wdm/WebDriverManager.java + +### Key: +WebDriverManager.java|getDriverVersionFromProperties|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +742e5a3bedf2ac0eb80c07eb95b66923 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3003/instruction.md b/inferredbugs-3003/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d2969b346a3d963be72df99fa3e857cb1f6ff91a --- /dev/null +++ b/inferredbugs-3003/instruction.md @@ -0,0 +1,246 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** webdrivermanager +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * (C) Copyright 2015 Boni Garcia (http://bonigarcia.github.io/) + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser General Public License + * (LGPL) version 2.1 which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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. + * + */ +package io.github.bonigarcia.wdm; + +import static io.github.bonigarcia.wdm.WdmConfig.getString; +import static java.io.File.separator; +import static java.util.Arrays.asList; +import static org.apache.commons.io.FileUtils.deleteDirectory; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.internal.LinkedTreeMap; + +/** + * Manager for Opera. + * + * @author Boni Garcia (boni.gg@gmail.com) + * @since 1.0.0 + */ +public class OperaDriverManager extends BrowserManager { + + public static synchronized BrowserManager getInstance() { + if (instance == null + || !instance.getClass().equals(OperaDriverManager.class)) { + instance = new OperaDriverManager(); + } + return instance; + } + + @Override + protected List getDrivers() throws IOException { + URL driverUrl = getDriverUrl(); + List urls; + if (isUsingTaobaoMirror()) { + urls = getDriversFromMirror(driverUrl); + + } else { + String driverVersion = versionToDownload; + + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(openGitHubConnection(driverUrl)))) { + + GsonBuilder gsonBuilder = new GsonBuilder(); + Gson gson = gsonBuilder.create(); + GitHubApi[] releaseArray = gson.fromJson(reader, + GitHubApi[].class); + if (driverVersion != null) { + releaseArray = new GitHubApi[] { + getVersion(releaseArray, driverVersion) }; + } + + urls = new ArrayList<>(); + for (GitHubApi release : releaseArray) { + if (release != null) { + List> assets = release + .getAssets(); + for (LinkedTreeMap asset : assets) { + urls.add(new URL(asset.get("browser_download_url") + .toString())); + } + } + } + } + } + return urls; + } + + @Override + protected String getExportParameter() { + return getString("wdm.operaDriverExport"); + } + + protected GitHubApi getVersion(GitHubApi[] releaseArray, String version) { + GitHubApi out = null; + for (GitHubApi release : releaseArray) { + if (release.getName() != null + && release.getName().equalsIgnoreCase(version)) { + out = release; + break; + } + } + return out; + } + + @Override + protected List getDriverName() { + return asList("operadriver"); + } + + @Override + protected String getDriverVersionKey() { + return "wdm.operaDriverVersion"; + } + + @Override + protected String getDriverUrlKey() { + return "wdm.operaDriverUrl"; + } + + @Override + protected String getCurrentVersion(URL url, String driverName) + throws MalformedURLException { + if (isUsingTaobaoMirror()) { + int i = url.getFile().lastIndexOf(SEPARATOR); + int j = url.getFile().substring(0, i).lastIndexOf(SEPARATOR) + 1; + return url.getFile().substring(j, i); + } else { + return url.getFile().substring( + url.getFile().indexOf(SEPARATOR + "v") + 2, + url.getFile().lastIndexOf(SEPARATOR)); + } + } + + @Override + protected File postDownload(File archive) throws IOException { + log.trace("Post processing for Opera: {}", archive); + + File extractFolder = archive.getParentFile().listFiles()[0]; + if (!extractFolder.isFile()) { + log.trace("Opera extract folder (to be deleted): {}", + extractFolder); + File operadriver = extractFolder.listFiles()[0]; + log.trace("Operadriver binary: {}", operadriver); + + File target = new File(archive.getParentFile().getAbsolutePath() + + separator + operadriver.getName()); + log.trace("Operadriver target: {}", target); + + downloader.renameFile(operadriver, target); + deleteDirectory(extractFolder); + return target; + } else { + return super.postDownload(archive); + } + } + + @Override + public BrowserManager useTaobaoMirror() { + String taobaoUrl = null; + try { + taobaoUrl = getString(getString("wdm.operaDriverTaobaoUrl")); + driverUrl = new URL(taobaoUrl); + } catch (MalformedURLException e) { + String errorMessage = "Malformed URL " + taobaoUrl; + log.error(errorMessage, e); + throw new WebDriverManagerException(errorMessage, e); + } + return instance; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `io.github.bonigarcia.wdm.OperaDriverManager.useTaobaoMirror` reads without synchronization from `wdm.OperaDriverManager.io.github.bonigarcia.wdm.BrowserManager.instance`. Potentially races with write in method `OperaDriverManager.getInstance()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +BrowserManager OperaDriverManager.useTaobaoMirror() + +### Procedure Id: +io.github.bonigarcia.wdm.OperaDriverManager.useTaobaoMirror():io.github.bonigarcia.wdm.BrowserManage.5dc5f203ee1ad22d081b1ff523e9714c + +### File: +src/main/java/io/github/bonigarcia/wdm/OperaDriverManager.java + +### Key: +OperaDriverManager.java|useTaobaoMirror|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +7b92361e1c4f08c4ddb132e0ae6534af + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3004/instruction.md b/inferredbugs-3004/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d119adc18d7c03677becf50450c8abde227f7e07 --- /dev/null +++ b/inferredbugs-3004/instruction.md @@ -0,0 +1,394 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** webdrivermanager +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * (C) Copyright 2015 Boni Garcia (http://bonigarcia.github.io/) + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser General Public License + * (LGPL) version 2.1 which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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. + * + */ +package io.github.bonigarcia.wdm; + +import static org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.util.Collection; +import java.util.Enumeration; +import java.util.zip.GZIPInputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import org.apache.commons.io.FileUtils; +import org.rauschig.jarchivelib.ArchiveFormat; +import org.rauschig.jarchivelib.Archiver; +import org.rauschig.jarchivelib.ArchiverFactory; +import org.rauschig.jarchivelib.CompressionType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.io.Files; + +/** + * Downloader class. + * + * @author Boni Garcia (boni.gg@gmail.com) + * @since 1.0.0 + */ +public class Downloader { + protected static final Logger log = LoggerFactory + .getLogger(Downloader.class); + + private static final String HOME = "~"; + + public static final synchronized void download(URL url, String version, + String export, String driverName) throws IOException { + File targetFile = new File(getTarget(version, url)); + File binary = null; + + // Check if binary exists + boolean download = !targetFile.getParentFile().exists() + || (targetFile.getParentFile().exists() + && targetFile.getParentFile().list().length == 0) + || WdmConfig.getBoolean("wdm.override"); + + if (!download) { + // Check if existing binary is valid + Collection listFiles = FileUtils + .listFiles(targetFile.getParentFile(), null, true); + for (File file : listFiles) { + if (file.getName().startsWith(driverName) + && file.canExecute()) { + binary = file; + log.debug("Using binary driver previously downloaded {}", + binary); + download = false; + break; + } else { + download = true; + } + } + } + + if (download) { + log.info("Downloading {} to {}", url, targetFile); + URLConnection conn = url.openConnection(); + conn.setRequestProperty("User-Agent", "Mozilla/5.0"); + conn.addRequestProperty("Connection", "keep-alive"); + conn.connect(); + FileUtils.copyInputStreamToFile(conn.getInputStream(), targetFile); + + if (!export.contains("edge")) { + binary = extract(targetFile, export); + targetFile.delete(); + } else { + binary = targetFile; + } + + } + if (export != null) { + BrowserManager.exportDriver(export, binary.toString()); + } + + } + + public static final File extractMsi(File msi) throws IOException { + File tmpMsi = new File(Files.createTempDir().getAbsoluteFile() + + File.separator + msi.getName()); + Files.move(msi, tmpMsi); + log.trace("Temporal msi file: {}", tmpMsi); + + Process process = Runtime.getRuntime() + .exec(new String[] { "msiexec", "/a", tmpMsi.toString(), "/qb", + "TARGETDIR=" + msi.getParent() }); + try { + process.waitFor(); + } catch (InterruptedException e) { + log.error("Exception waiting to msiexec to be finished", e); + } finally { + process.destroy(); + } + + tmpMsi.delete(); + + Collection listFiles = FileUtils.listFiles( + new File(msi.getParent()), new String[] { "exe" }, true); + return listFiles.iterator().next(); + } + + public static final File extract(File compressedFile, String export) + throws IOException { + log.trace("Compressed file {}", compressedFile); + + File file = null; + if (compressedFile.getName().toLowerCase().endsWith("tar.bz2")) { + file = unBZip2(compressedFile, export); + } else if (compressedFile.getName().toLowerCase().endsWith("gz")) { + file = unGzip(compressedFile); + } else { + + ZipFile zipFolder = new ZipFile(compressedFile); + Enumeration enu = zipFolder.entries(); + + while (enu.hasMoreElements()) { + ZipEntry zipEntry = (ZipEntry) enu.nextElement(); + + String name = zipEntry.getName(); + long size = zipEntry.getSize(); + long compressedSize = zipEntry.getCompressedSize(); + log.trace("Unzipping {} (size: {} KB, compressed size: {} KB)", + name, size, compressedSize); + + file = new File( + compressedFile.getParentFile() + File.separator + name); + if (!file.exists() || WdmConfig.getBoolean("wdm.override")) { + if (name.endsWith("/")) { + file.mkdirs(); + continue; + } + + File parent = file.getParentFile(); + if (parent != null) { + parent.mkdirs(); + } + + InputStream is = zipFolder.getInputStream(zipEntry); + FileOutputStream fos = new FileOutputStream(file); + byte[] bytes = new byte[1024]; + int length; + while ((length = is.read(bytes)) >= 0) { + fos.write(bytes, 0, length); + } + is.close(); + fos.close(); + file.setExecutable(true); + } else { + log.debug(file + " already exists"); + } + + } + zipFolder.close(); + } + + file = checkPhantom(compressedFile, export); + + log.trace("Resulting binary file {}", file.getAbsoluteFile()); + return file.getAbsoluteFile(); + } + + public static File unGzip(File archive) throws IOException { + + log.trace("UnGzip {}", archive); + File target = new File( + archive.getParentFile() + File.separator + "wires"); + + try (GZIPInputStream in = new GZIPInputStream( + new FileInputStream(archive))) { + try (FileOutputStream out = new FileOutputStream(target)) { + for (int c = in.read(); c != -1; c = in.read()) { + out.write(c); + } + } + } + + if (!target.getName().toLowerCase().contains(".exe") && target.exists()) + target.setExecutable(true); + + return target; + } + + public static File unBZip2(File archive, String export) throws IOException { + Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, + CompressionType.BZIP2); + archiver.extract(archive, archive.getParentFile()); + log.trace("Unbzip2 {}", archive); + File target = checkPhantom(archive, export); + + return target; + } + + private static File checkPhantom(File archive, String export) + throws IOException { + File target; + String phantomName = "phantomjs"; + if (export.contains(phantomName)) { + String fileNoExtension = archive.getName().replace(".tar.bz2", "") + .replace(".zip", ""); + + File phantomjs = null; + try { + phantomjs = new File(archive.getParentFile().getAbsolutePath() + + File.separator + fileNoExtension + File.separator + + "bin" + File.separator).listFiles()[0]; + } catch (Exception e) { + String extension = IS_OS_WINDOWS ? ".exe" : ""; + phantomjs = new File(archive.getParentFile().getAbsolutePath() + + File.separator + fileNoExtension + File.separator + + phantomName + extension); + } + + target = new File(archive.getParentFile().getAbsolutePath() + + File.separator + phantomjs.getName()); + phantomjs.renameTo(target); + + File delete = new File(archive.getParentFile().getAbsolutePath() + + File.separator + fileNoExtension); + log.trace("Folder to be deleted: {}", delete); + FileUtils.deleteDirectory(delete); + } else { + target = archive.getParentFile().listFiles()[0]; + } + + return target; + } + + public static final String getTarget(String version, URL url) + throws IOException { + + log.trace("getTarget {} {}", version, url); + + String zip = url.getFile().substring(url.getFile().lastIndexOf("/")); + + int iFirst = zip.indexOf("_"); + int iSecond = zip.indexOf("-"); + int iLast = iFirst != zip.lastIndexOf("_") ? zip.lastIndexOf("_") + : iSecond != -1 ? iSecond : zip.length(); + String folder = zip.substring(0, iLast).replace(".zip", "") + .replace(".tar.bz2", "").replace(".tar.gz", "") + .replace(".msi", "").replace(".exe", "") + .replace("_", File.separator); + + String target = getTargetPath() + folder + File.separator + version + + zip; + + // Exception for PhantomJS + if (target.contains("phantomjs")) { + int iSeparator = target.indexOf(version) - 1; + int iDash = target.lastIndexOf(version) + version.length(); + int iPoint = target.lastIndexOf(".tar") != -1 + ? target.lastIndexOf(".tar") : target.lastIndexOf(".zip"); + target = target.substring(0, iSeparator + 1) + + target.substring(iDash + 1, iPoint) + + target.substring(iSeparator); + } + + // Exception for Marionette + else if (target.contains("wires")) { + int iSeparator = target.indexOf(version) - 1; + int iDash = target.lastIndexOf(version) + version.length(); + int iPoint = target.lastIndexOf("tar.gz") != -1 + ? target.lastIndexOf(".tar.gz") + : target.lastIndexOf(".gz") != -1 + ? target.lastIndexOf(".gz") + : target.lastIndexOf(".zip"); + target = target.substring(0, iSeparator + 1) + + target.substring(iDash + 1, iPoint).toLowerCase() + + target.substring(iSeparator); + } + + log.trace("Target file for URL {} version {} = {}", url, version, + target); + + return target; + } + + public static String getTargetPath() { + String targetPath = WdmConfig.getString("wdm.targetPath"); + if (targetPath.contains(HOME)) { + targetPath = targetPath.replace(HOME, + System.getProperty("user.home")); + } + + // Create repository folder if not exits + File repository = new File(targetPath); + if (!repository.exists()) { + repository.mkdirs(); + } + return targetPath; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `archive.getParentFile().listFiles()` could be null and is dereferenced at line 249. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +File Downloader.checkPhantom(File,String) + +### Procedure Id: +io.github.bonigarcia.wdm.Downloader.checkPhantom(java.io.File,java.lang.String):java.io.File.09d5518e76d3c48dc8ea4508d26703a8 + +### File: +src/main/java/io/github/bonigarcia/wdm/Downloader.java + +### Key: +Downloader.java|checkPhantom|NULL_DEREFERENCE + +### Node Key: +96aa42d39c16d8c3ca9bc4be65b323da + +### Hash: +08ee875501924b30dfc5019d2321278c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3113/instruction.md b/inferredbugs-3113/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..15b8f3ea2088033e72d5a3e6f9dbe1b05c32865b --- /dev/null +++ b/inferredbugs-3113/instruction.md @@ -0,0 +1,1056 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** farm +**Bug ID:** 101 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2016-2019 Zerocracy + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to read + * the Software only. Permissions is hereby NOT GRANTED to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.zerocracy.pmo; + +import com.zerocracy.Farm; +import com.zerocracy.Item; +import com.zerocracy.Par; +import com.zerocracy.Project; +import com.zerocracy.SoftException; +import com.zerocracy.Xocument; +import com.zerocracy.cash.Cash; +import java.io.IOException; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import org.cactoos.collection.CollectionOf; +import org.cactoos.iterable.Mapped; +import org.cactoos.list.ListOf; +import org.cactoos.list.SolidList; +import org.cactoos.scalar.IoCheckedScalar; +import org.cactoos.scalar.Reduced; +import org.cactoos.time.DateAsText; +import org.xembly.Directives; + +/** + * Catalog of all projects. + * + * @since 1.0 + * @todo #1305:30min Continue replacing old Date classes with Instant. + * Remember also to remove instances of `DateAsText` (Instant.toString should + * be used). Be careful to ensure Groovy classes are properly updated since + * typing is sometimes dodgy in there. There is a lot of classes to change so + * try to find a good small cluster of related classes that can be updated. + * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) + */ +@SuppressWarnings( + { + "PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals", "PMD.GodClass" + } +) +public final class Catalog { + + /** + * Title. + */ + private static final String PRJ_TITLE = "title"; + + /** + * PMO. + */ + private final Project pmo; + + /** + * Ctor. + * @param farm Farm + */ + public Catalog(final Farm farm) { + this(new Pmo(farm)); + } + + /** + * Ctor. + * @param pkt PMO + */ + public Catalog(final Project pkt) { + this.pmo = pkt; + } + + /** + * Bootstrap it. + * @return Itself + * @throws IOException If fails + */ + public Catalog bootstrap() throws IOException { + try (final Item team = this.item()) { + new Xocument(team).bootstrap("pmo/catalog"); + } + return this; + } + + /** + * Return all sandbox projects. + * @return List of sandbox projects + * @checkstyle NonStaticMethodCheck (3 lines) + */ + public Collection sandbox() { + return new CollectionOf<>( + "CAZPZR9FS", "C63314D6Z", "C7JGJ00DP" + ); + } + + /** + * Delete it entirely. + * @param pid Project ID + * @throws IOException If fails + */ + public void delete(final String pid) throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par("Project %s doesn't exist, can't delete").say(pid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format("/catalog/project[@id='%s'] ", pid) + ).strict(1).remove() + ); + } + } + + /** + * Create a project with the given ID. + * @param pid Project ID + * @param prefix The prefix + * @throws IOException If fails + */ + public void add(final String pid, final String prefix) throws IOException { + if (this.exists(pid)) { + throw new IllegalArgumentException( + new Par("Project %s already exists").say(pid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives() + .xpath("/catalog") + .add("project") + .attr("id", pid) + .add(Catalog.PRJ_TITLE).set(pid).up() + .add("created") + .set(new DateAsText().asString()).up() + .add("prefix").set(prefix).up() + .add("alive").set(true).up() + .add("fee").set(Cash.ZERO).up() + .add("publish").set(Boolean.toString(false)).up() + .add("adviser").set("0crat").up() + .add("architect").set("0crat").up() + .add("members").up() + .add("jobs").set(0).up() + .add("orders").set(0).up() + .add("cash").attr("deficit", false).set(Cash.ZERO).up() + .add("languages").up() + ); + } + } + + /** + * Project's architect. + * @param pid Project id + * @return Architect login + * @throws IOException If fails + */ + public String architect(final String pid) throws IOException { + this.checkExist(pid); + try (final Item item = this.item()) { + return new Xocument(item.path()) + .xpath( + String.format( + "/catalog/project[@id = '%s']/architect/text()", + pid + ) + ).iterator().next(); + } + } + + /** + * Change project architect. + * @param pid Project id + * @param arc New architect + * @throws IOException If fails + */ + public void architect(final String pid, final String arc) + throws IOException { + this.checkExist(pid); + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives() + .xpath(String.format("/catalog/project[@id = '%s']", pid)) + .strict(1) + .addIf("architect") + .set(arc) + ); + } + } + + /** + * Project jobs count. + * @param pid Project id + * @return Jobs count + * @throws IOException If fails + */ + public int jobs(final String pid) throws IOException { + this.checkExist(pid); + try (final Item item = this.item()) { + return Integer.parseInt( + new Xocument(item.path()) + .xpath( + String.format( + "/catalog/project[@id = '%s']/jobs/text()", + pid + ) + ).iterator().next() + ); + } + } + + /** + * Change project jobs count. + * @param pid Project id + * @param cnt Jobs count + * @throws IOException If fails + */ + public void jobs(final String pid, final int cnt) + throws IOException { + this.checkExist(pid); + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives() + .xpath(String.format("/catalog/project[@id = '%s']", pid)) + .strict(1) + .addIf("jobs") + .set(cnt) + ); + } + } + + /** + * Project orders count. + * @param pid Project id + * @return Architect login + * @throws IOException If fails + */ + public int orders(final String pid) throws IOException { + this.checkExist(pid); + try (final Item item = this.item()) { + return Integer.parseInt( + new Xocument(item.path()) + .xpath( + String.format( + "/catalog/project[@id = '%s']/orders/text()", + pid + ) + ).iterator().next() + ); + } + } + + /** + * Change project orders count. + * @param pid Project id + * @param cnt New order count + * @throws IOException If fails + */ + public void orders(final String pid, final int cnt) + throws IOException { + this.checkExist(pid); + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives() + .xpath(String.format("/catalog/project[@id = '%s']", pid)) + .strict(1) + .addIf("orders") + .set(cnt) + ); + } + } + + /** + * Does project under deficit. + * @param pid Project id + * @return TRUE if in deficit + * @throws IOException If fails + */ + public boolean deficit(final String pid) throws IOException { + this.checkExist(pid); + try (final Item item = this.item()) { + return Boolean.parseBoolean( + new Xocument(item.path()) + .xpath( + String.format( + "/catalog/project[@id = '%s']/cash/@deficit", + pid + ) + ).iterator().next() + ); + } + } + + /** + * Available cash in project. + * @param pid Project id + * @return Cash amount + * @throws IOException If fails + */ + public Cash cash(final String pid) throws IOException { + this.checkExist(pid); + try (final Item item = this.item()) { + return new Cash.S( + new Xocument(item.path()) + .xpath( + String.format( + "/catalog/project[@id = '%s']/cash/text()", + pid + ) + ).iterator().next() + ); + } + } + + /** + * Change project cash. + * @param pid Project id + * @param cash New cash + * @param deficit TRUE if under deficit + * @throws IOException If fails + */ + public void cash(final String pid, final Cash cash, final boolean deficit) + throws IOException { + this.checkExist(pid); + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives() + .xpath(String.format("/catalog/project[@id = '%s']", pid)) + .strict(1) + .push() + .xpath("cash") + .remove() + .pop() + .add("cash") + .attr("deficit", deficit) + .set(cash) + ); + } + } + + /** + * All project members. + * @param pid Project id + * @return Members logins + * @throws IOException If fails + */ + public Collection members(final String pid) throws IOException { + this.checkExist(pid); + try (final Item item = this.item()) { + return new Xocument(item.path()).xpath( + String.format( + "/catalog/project[@id='%s']/members/member/text()", + pid + ) + ); + } + } + + /** + * All project members. + * @param pid Project id. + * @param members Members + * @throws IOException If fails + */ + public void members(final String pid, final Iterable members) + throws IOException { + this.checkExist(pid); + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives() + .xpath(String.format("/catalog/project[@id = '%s']", pid)) + .strict(1) + .push() + .xpath("members/member") + .remove() + .pop() + .addIf("members") + .append( + new IoCheckedScalar<>( + new Reduced<>( + new Directives(), + (dirs, member) -> dirs + .add("member") + .set(member) + .up(), + members + ) + ).value() + ) + ); + } + } + + /** + * Project's language stack. + * @param pid Project id + * @return Languages set + * @throws IOException If fails + */ + public Set languages(final String pid) throws IOException { + this.checkExist(pid); + try (final Item item = this.item()) { + return new HashSet<>( + new ListOf<>( + new Xocument(item.path()).xpath( + String.format( + "/catalog/project[@id = '%s']/languages/text()", + pid + ) + ).iterator().next().split(",") + ) + ); + } + } + + /** + * Change project language stack. + * @param pid Project id + * @param langs New laguages + * @throws IOException If fails + */ + public void languages(final String pid, final Set langs) + throws IOException { + this.checkExist(pid); + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives() + .xpath(String.format("/catalog/project[@id = '%s']", pid)) + .strict(1) + .addIf("languages") + .set(String.join(",", langs)) + ); + } + } + + /** + * Project exists? + * @param pid Project ID + * @return TRUE if it exists + * @throws IOException If fails + */ + public boolean exists(final String pid) throws IOException { + try (final Item item = this.item()) { + return !new Xocument(item).nodes( + String.format("//project[@id ='%s']", pid) + ).isEmpty(); + } + } + + /** + * Find a project by XPath query. + * @param xpath XPath query + * @return Prefixes found, if found + * @throws IOException If fails + */ + public Collection findByXPath(final String xpath) + throws IOException { + String term = xpath; + if (!term.isEmpty()) { + term = String.format("[%s]", term); + } + try (final Item item = this.item()) { + return new Xocument(item).xpath( + String.format("//project%s/prefix/text()", term) + ); + } + } + + /** + * Is it on pause? + * @param pid Project ID + * @return TRUE if on pause + * @throws IOException If fails + */ + public boolean pause(final String pid) throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par("Project %s doesn't exist").say(pid) + ); + } + try (final Item item = this.item()) { + return !Boolean.parseBoolean( + new Xocument(item.path()).xpath( + String.format( + "/catalog/project[@id='%s']/alive/text()", + pid + ) + ).get(0) + ); + } + } + + /** + * Set it on pause. + * @param pid Project ID + * @param pause TRUE if it has to go on pause + * @throws IOException If fails + */ + public void pause(final String pid, + final boolean pause) throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par("Project %s doesn't exist, can't pause").say(pid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format("/catalog/project[@id='%s']/alive", pid) + ).strict(1).set(!pause) + ); + } + } + + /** + * Get project fee or Zero. + * @param pid Project ID + * @return Per transaction fee + * @throws IOException If fails + */ + public Cash fee(final String pid) throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par( + "Project %s doesn't exist, can't get fee" + ).say(pid) + ); + } + try (final Item item = this.item()) { + final Iterator fees = new Xocument(item.path()).xpath( + String.format("/catalog/project[@id='%s']/fee/text()", pid) + ).iterator(); + final Cash fee; + if (fees.hasNext()) { + fee = new Cash.S(fees.next()); + } else { + fee = Cash.ZERO; + } + return fee; + } + } + + /** + * Set project fee. + * @param pid Project ID + * @param fee Fee to set + * @throws IOException If fails + */ + public void fee(final String pid, final Cash fee) throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par( + "Project %s doesn't exist, can't set fee" + ).say(pid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format("/catalog/project[@id='%s']/fee", pid) + ).strict(1).set(fee) + ); + } + } + + /** + * Publish or unpublish this project. + * @param pid Project ID + * @param status Publication success to set + * @throws IOException If fails + */ + public void publish(final String pid, final boolean status) + throws IOException { + if (this.links(pid, "github").isEmpty()) { + throw new SoftException( + new Par( + "Project %s is not linked to any GitHub repositories,", + "it can't be published on the board, see §26" + ).say(pid) + ); + } + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par( + "Project %s doesn't exist, can't publish, see §26" + ).say(pid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format("/catalog/project[@id='%s']/publish", pid) + ).strict(1).set(Boolean.toString(status)) + ); + } + } + + /** + * This project is published? + * @param pid Project ID + * @return TRUE if published + * @throws IOException If fails + */ + public boolean published(final String pid) throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par( + "Project \"%s\" doesn't exist, can't check publish" + ).say(pid) + ); + } + try (final Item item = this.item()) { + return Boolean.parseBoolean( + new Xocument(item).xpath( + String.format( + "/catalog/project[@id='%s']/publish/text()", + pid + ) + ).get(0) + ); + } + } + + /** + * Add a link to the pmo. + * @param pid Project ID + * @param rel REL + * @param href HREF + * @throws IOException If fails + */ + public void link(final String pid, final String rel, final String href) + throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par( + "Project %s doesn't exist, can't add link" + ).say(pid) + ); + } + if (this.hasLink(pid, rel, href)) { + throw new SoftException( + new Par( + "Project %s already has link, rel=`%s`, href=`%s`" + ).say(pid, rel, href) + ); + } + if (this.linkExists(rel, href)) { + throw new SoftException( + new Par( + "Some other project already has `%s/%s` link" + ).say(rel, href) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives() + .xpath(String.format("/catalog/project[@id='%s']", pid)) + .strict(1) + .addIf("links") + .add("link") + .attr("rel", rel) + .attr("href", href) + ); + } + } + + /** + * Remove a link from the pmo. + * @param pid Project ID + * @param rel REL + * @param href HREF + * @throws IOException If fails + */ + public void unlink(final String pid, final String rel, final String href) + throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par( + "Project %s doesn't exist, can't unlink" + ).say(pid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives() + .xpath(String.format("/catalog/project[@id= '%s']", pid)) + .strict(1) + .xpath( + String.format( + "links/link[@rel='%s' and @href='%s']", + rel, href + ) + ) + .strict(1) + .remove() + ); + } + } + + /** + * Get all project links. + * @param pid Project ID + * @return Links found + * @throws IOException If fails + */ + public Collection links(final String pid) throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par( + "Project %s doesn't exist, can't get links" + ).say(pid) + ); + } + try (final Item item = this.item()) { + return new SolidList<>( + new Mapped<>( + xml -> String.format( + "%s:%s", + xml.xpath("@rel").get(0), + xml.xpath("@href").get(0) + ), + new Xocument(item).nodes( + String.format( + "/catalog/project[@id='%s']/links/link", + pid + ) + ) + ) + ); + } + } + + /** + * Get project links by REL. + * @param pid Project ID + * @param rel REL to look for + * @return Links found + * @throws IOException If fails + */ + public Collection links(final String pid, final String rel) + throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par( + "Project %s doesn't exist, can't get links" + ).say(pid) + ); + } + try (final Item item = this.item()) { + return new Xocument(item).xpath( + String.format( + "/catalog/project[@id='%s']/links/link[@rel='%s']/@href", + pid, rel + ) + ); + } + } + + /** + * Project has this link? + * @param pid Project ID + * @param rel REL + * @param href HREF + * @return TRUE if it has a link + * @throws IOException If fails + */ + public boolean hasLink(final String pid, final String rel, + final String href) throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par( + "Project %s doesn't exist, can't check link" + ).say(pid) + ); + } + try (final Item item = this.item()) { + return !new Xocument(item.path()).nodes( + String.format( + // @checkstyle LineLength (1 line) + "/catalog/project[@id='%s' and links/link[@rel='%s' and @href='%s']]", + pid, rel, href + ) + ).isEmpty(); + } + } + + /** + * This link exists in any project? + * @param rel REL + * @param href HREF + * @return TRUE if it exists already + * @throws IOException If fails + */ + public boolean linkExists(final String rel, final String href) + throws IOException { + try (final Item item = this.item()) { + return !new Xocument(item.path()).nodes( + String.format( + "/catalog/project/links/link[@rel='%s' and @href='%s']", + rel, href + ) + ).isEmpty(); + } + } + + /** + * Change project title. + * @param pid Project id + * @param title New title + * @throws IOException If fails + */ + public void title(final String pid, final String title) + throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par( + "Project %s doesn't exist, can't change title" + ).say(pid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives() + .xpath(String.format("/catalog/project[@id = '%s']", pid)) + .strict(1) + .addIf(Catalog.PRJ_TITLE) + .set(title) + ); + } + } + + /** + * Project title. + * @param pid Project id + * @return Title string + * @throws IOException If fails + */ + public String title(final String pid) throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par( + "Project %s doesn't exist, can't get title" + ).say(pid) + ); + } + try (final Item item = this.item()) { + final Iterator items = new Xocument(item.path()) + .xpath( + String.format( + "/catalog/project[@id = '%s']/title/text()", + pid + ) + ).iterator(); + String title = pid; + if (items.hasNext()) { + title = items.next(); + } + return title; + } + } + + /** + * Has project adviser. + * + * @param pid Project id + * @return True if has + * @throws IOException If fails + */ + public boolean hasAdviser(final String pid) throws IOException { + try (final Item item = this.item()) { + final List xpath = new Xocument(item.path()).xpath( + String.format( + "/catalog/project[@id = '%s']/adviser/text()", + pid + ) + ); + return !xpath.isEmpty() && !"0crat".equals(xpath.get(0)); + } + } + + /** + * Project adviser. + * @param pid Project id + * @return Adviser id + * @throws IOException If fails + */ + public String adviser(final String pid) throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par( + "Project %s doesn't exist, can't get adviser" + ).say(pid) + ); + } + try (final Item item = this.item()) { + return new Xocument(item.path()).xpath( + String.format( + "/catalog/project[@id = '%s']/adviser/text()", + pid + ) + ).get(0); + } + } + + /** + * Change project's adviser. + * @param pid Project id + * @param adviser Adviser id + * @throws IOException If fails + */ + public void adviser(final String pid, final String adviser) + throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par( + "Project %s doesn't exist, can't get adviser" + ).say(pid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format( + "/catalog/project[@id = '%s']", + pid + ) + ).addIf("adviser").set(adviser) + ); + } + } + + /** + * Active project IDs. + * @return Set of project IDs + * @throws IOException If fails + */ + public Set active() throws IOException { + try (final Item item = this.item()) { + return new HashSet<>( + new Xocument(item).xpath( + "/catalog/project[alive = 'true']/@id" + ) + ); + } + } + + /** + * Check project exists, or throw exception. + * @param pid Project id + * @throws IOException If not exist + */ + private void checkExist(final String pid) throws IOException { + if (!this.exists(pid)) { + throw new IllegalArgumentException( + new Par( + "Project %s doesn't exist" + ).say(pid) + ); + } + } + + /** + * The item. + * @return Item + * @throws IOException If fails + */ + private Item item() throws IOException { + return this.pmo.acq("catalog.xml"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.zerocracy.farm.fake.FkFarm` acquired by call to `Par(...)` at line 827 is not released after line 830. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Catalog.title(String,String) + +### Procedure Id: +com.zerocracy.pmo.Catalog.title(java.lang.String,java.lang.String):void.ca15b04105376b6015fbaa35c3fc0329 + +### File: +src/main/java/com/zerocracy/pmo/Catalog.java + +### Key: +Catalog.java|title|RESOURCE_LEAK + +### Node Key: +da4621e3cd0bc306162ff2464b4e3806 + +### Hash: +c9100e062168a0b6221d7c2bb1f4c697 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3114/instruction.md b/inferredbugs-3114/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e332a90a16cbfe93bf419166d1fbd330a48cefce --- /dev/null +++ b/inferredbugs-3114/instruction.md @@ -0,0 +1,147 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** farm +**Bug ID:** 55 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) 2016-2018 Zerocracy + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to read + * the Software only. Permissions is hereby NOT GRANTED to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.zerocracy.tk.project; + +import com.jcabi.matchers.XhtmlMatchers; +import com.zerocracy.Farm; +import com.zerocracy.farm.fake.FkFarm; +import com.zerocracy.farm.footprint.FtFarm; +import com.zerocracy.farm.props.PropsFarm; +import com.zerocracy.pm.ClaimOut; +import com.zerocracy.tk.RqWithUser; +import com.zerocracy.tk.TkApp; +import org.hamcrest.MatcherAssert; +import org.junit.Test; +import org.takes.rq.RqFake; +import org.takes.rq.RqWithHeaders; +import org.takes.rs.RsPrint; + +/** + * Test case for {@link TkReport}. + * @author Yegor Bugayenko (yegor256@gmail.com) + * @version $Id$ + * @since 0.18 + * @checkstyle JavadocMethodCheck (500 lines) + * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) + */ +public final class TkReportTest { + + @Test + public void rendersReport() throws Exception { + final Farm farm = new FtFarm(new PropsFarm(new FkFarm())); + final String uid = "yegor256"; + new ClaimOut() + .type("Order was given") + .param("login", uid) + .postTo(farm.find("@id='C00000000'").iterator().next()); + MatcherAssert.assertThat( + XhtmlMatchers.xhtml( + new RsPrint( + new TkApp(farm).act( + new RqWithHeaders( + new RqWithUser( + farm, + new RqFake( + "GET", + // @checkstyle LineLength (1 line) + "/report/C00000000?report=orders-given-by-week" + ) + ), + "Accept: application/vnd.zerocracy+xml" + ) + ) + ).printBody() + ), + XhtmlMatchers.hasXPaths("/page/rows/row[week]") + ); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.zerocracy.farm.footprint.FtFarm` acquired by call to `new()` at line 45 is not released after line 51. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TkReportTest.rendersReport() + +### Procedure Id: +com.zerocracy.tk.project.TkReportTest.rendersReport():void.06c206903f5e133abdb4e784b359cb52 + +### File: +src/test/java/com/zerocracy/tk/project/TkReportTest.java + +### Key: +TkReportTest.java|rendersReport|RESOURCE_LEAK + +### Node Key: +4160223c1fee3e4ba08cafd59bc559f6 + +### Hash: +c440925b164922db157a9c034d6025ef + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3122/instruction.md b/inferredbugs-3122/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7ac880072b69a7869a72e3a6193f0ed861e311ce --- /dev/null +++ b/inferredbugs-3122/instruction.md @@ -0,0 +1,194 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** farm +**Bug ID:** 46 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) 2016-2018 Zerocracy + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to read + * the Software only. Permissions is hereby NOT GRANTED to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.zerocracy.radars.viber; + +import com.zerocracy.Farm; +import com.zerocracy.Par; +import com.zerocracy.tk.RsParFlash; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.HttpURLConnection; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.logging.Level; +import javax.json.Json; +import javax.json.JsonException; +import javax.json.JsonObject; +import javax.json.JsonReader; +import org.takes.Request; +import org.takes.Response; +import org.takes.Take; +import org.takes.facets.forward.RsForward; +import org.takes.rs.RsWithStatus; + +/** + * Viber webhook entry point. + * + * @author Carlos Miranda (miranda.cma@gmail.com) + * @version $Id$ + * @since 0.22 + * @checkstyle ClassDataAbstractionCouplingCheck (2 lines) + */ +public final class TkViber implements Take { + + /** + * Farm to use. + */ + private final Farm farm; + + /** + * Reactions. + */ + private final Reaction reaction; + + /** + * Constructor. + * @param farm Farm to use + */ + public TkViber(final Farm farm) { + this(farm, new ReProfile()); + } + + /** + * Constructor. + * @param farm Farm to use + * @param react Reaction to use + */ + TkViber(final Farm farm, final Reaction react) { + this.farm = farm; + this.reaction = react; + } + + @Override + public Response act(final Request req) throws IOException { + final JsonObject json = TkViber.json( + new InputStreamReader(req.body(), StandardCharsets.UTF_8) + ); + if (json.isEmpty()) { + throw new RsForward( + new RsParFlash( + new Par( + "We expect this URL to be called by Viber", + "with JSON as body of the request" + ).say(), + Level.WARNING + ) + ); + } + if (Objects.equals(json.getString("event"), "message")) { + this.reaction.react( + new VbBot(), this.farm, new VbEvent.Simple(json) + ); + } + return new RsWithStatus( + HttpURLConnection.HTTP_OK + ); + } + + /** + * Read JSON from body. + * @param body The body + * @return The JSON object + */ + private static JsonObject json(final Reader body) { + try ( + final JsonReader reader = Json.createReader(body) + ) { + return reader.readObject(); + } catch (final JsonException ex) { + throw new IllegalArgumentException( + String.format("Can't parse JSON: %s", body), + ex + ); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.zerocracy.farm.fake.FkFarm` acquired by call to `Par(...)` at line 83 is not released after line 88. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Response TkViber.act(Request) + +### Procedure Id: +com.zerocracy.radars.viber.TkViber.act(org.takes.Request):org.takes.Response.0d91e6abf7e4e3ae9ebb9f9733262aa5 + +### File: +src/main/java/com/zerocracy/radars/viber/TkViber.java + +### Key: +TkViber.java|act|RESOURCE_LEAK + +### Node Key: +3eedcda6f33b682d953b6334ca7158ad + +### Hash: +f21d70f941b10c777ce97856a4a4e962 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3125/instruction.md b/inferredbugs-3125/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..21cd46d8fb23b83b04b18a2b47d64975e5370598 --- /dev/null +++ b/inferredbugs-3125/instruction.md @@ -0,0 +1,1002 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** farm +**Bug ID:** 41 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) 2016-2018 Zerocracy + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to read + * the Software only. Permissions is hereby NOT GRANTED to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.zerocracy.pmo; + +import com.jcabi.xml.XML; +import com.zerocracy.Farm; +import com.zerocracy.Item; +import com.zerocracy.Par; +import com.zerocracy.Policy; +import com.zerocracy.SoftException; +import com.zerocracy.Xocument; +import com.zerocracy.cash.Cash; +import com.zerocracy.cash.CashParsingException; +import com.zerocracy.pm.staff.Roles; +import java.io.IOException; +import java.util.Date; +import java.util.Iterator; +import org.cactoos.iterable.ItemAt; +import org.cactoos.iterable.Mapped; +import org.cactoos.scalar.NumberOf; +import org.cactoos.scalar.UncheckedScalar; +import org.cactoos.time.DateAsText; +import org.cactoos.time.DateOf; +import org.xembly.Directives; + +/** + * Data about people. + * @author Yegor Bugayenko (yegor256@gmail.com) + * @version $Id$ + * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) + * @since 0.1 + * @todo #552:30min Let's keep agenda inside `people.xml` and update it + * when agenda changed as described in + * https://github.com/zerocracy/farm/issues/366#issuecomment-359568311 + * Also put it as 'agenda' element in TkGang xml. + */ +@SuppressWarnings + ( + { + "PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals", + "PMD.NPathComplexity", "PMD.CyclomaticComplexity" + } + ) +public final class People { + + /** + * PMO. + */ + private final Pmo pmo; + + /** + * Ctor. + * @param farm Farm + */ + public People(final Farm farm) { + this(new Pmo(farm)); + } + + /** + * Ctor. + * @param pkt PMO + */ + public People(final Pmo pkt) { + this.pmo = pkt; + } + + /** + * Bootstrap it. + * @return Itself + * @throws IOException If fails + */ + public People bootstrap() throws IOException { + try (final Item item = this.item()) { + new Xocument(item.path()).bootstrap("pmo/people"); + } + return this; + } + + /** + * Get them all. + * @return List of them + * @throws IOException If fails + */ + public Iterable iterate() throws IOException { + try (final Item item = this.item()) { + return new Xocument(item.path()).xpath( + "/people/person/@id" + ); + } + } + + /** + * Remove person. + * @param uid Person id + * @throws IOException If fails + */ + public void remove(final String uid) throws IOException { + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format("/people/person[@id='%s']", uid) + ).remove() + ); + } + } + + /** + * Touch this dude. + * @param uid User ID + * @throws IOException If fails + */ + public void touch(final String uid) throws IOException { + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + People.start(uid) + ); + } + } + + /** + * Set mentor to '0crat'. + * @param uid User ID + * @throws IOException If fails + */ + public void graduate(final String uid) throws IOException { + if (!this.hasMentor(uid)) { + throw new SoftException( + new Par( + "User @%s is not with us yet" + ).say(uid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + People.start(uid) + .addIf("mentor") + .set("0crat") + ); + } + } + + /** + * Set details. + * @param uid User ID + * @param text Text to save + * @throws IOException If fails + */ + public void details(final String uid, final String text) + throws IOException { + if (!this.hasMentor(uid)) { + throw new SoftException( + new Par( + "User @%s is not with us yet" + ).say(uid) + ); + } + if (text.isEmpty()) { + throw new SoftException( + new Par( + "User @%s details can't be empty" + ).say(uid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + People.start(uid) + .addIf("details") + .set(text) + ); + } + } + + /** + * Get user details. + * @param uid User ID + * @return Details of the user + * @throws IOException If fails + */ + public String details(final String uid) throws IOException { + try (final Item item = this.item()) { + final Iterator items = new Xocument(item.path()).xpath( + String.format( + "/people/person[@id='%s']/details/text()", + uid + ) + ).iterator(); + final String text; + if (items.hasNext()) { + text = items.next(); + } else { + text = ""; + } + return text; + } + } + + /** + * Invite that person and set a mentor. + * @param uid User ID + * @param mentor User ID of the mentor + * @throws IOException If fails + */ + public void invite(final String uid, final String mentor) + throws IOException { + if (this.hasMentor(uid)) { + throw new SoftException( + new Par( + "@%s is already with us, no need to invite again" + ).say(uid) + ); + } + try (final Item item = this.item()) { + final int max = new Policy().get("1.max-students", 16); + final int current = new Xocument(item.path()) + .nodes( + String.format( + "/people/person[mentor/text()='%s']", + mentor + ) + ).size(); + if (current >= max + && !new Roles(this.pmo).bootstrap().hasAnyRole(mentor)) { + throw new SoftException( + new Par( + "You can not invite more than %d students;", + "you already have %d, see §1" + ).say(max, current) + ); + } + new Xocument(item.path()).modify( + People.start(uid) + .push() + .xpath("mentor") + .strict(0) + .pop() + .add("mentor") + .set(mentor) + ); + } + } + + /** + * This person has a mentor? + * @param uid User ID + * @return TRUE if he has a mentor + * @throws IOException If fails + */ + public boolean hasMentor(final String uid) throws IOException { + try (final Item item = this.item()) { + return !new Xocument(item.path()).nodes( + String.format( + "/people/person[@id='%s']/mentor", + uid + ) + ).isEmpty(); + } + } + + /** + * Person's mentor. + * @param uid User ID + * @return Id of person's mentor + * @throws IOException If fails + */ + public String mentor(final String uid) throws IOException { + try (final Item item = this.item()) { + return new Xocument(item.path()).xpath( + String.format( + "/people/person[@id='%s']/mentor/text()", + uid + ) + ).get(0); + } + } + + /** + * Breakup with a person. + * @param uid User ID + * @throws IOException If fails + */ + public void breakup(final String uid) throws IOException { + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format("/people/person[@id='%s']/mentor", uid) + ).remove() + ); + } + } + + /** + * Set rate. + * @param uid User ID + * @param rate Rate of the user + * @throws IOException If fails + */ + public void rate(final String uid, final Cash rate) throws IOException { + final Cash max = new Policy().get("16.max", new Cash.S("$256")); + if (rate.compareTo(max) > 0) { + throw new SoftException( + new Par( + "This is too high (%s),", + "we do not work with rates higher than %s, see §16" + ).say(rate, max) + ); + } + final Cash min = new Policy().get("16.min", Cash.ZERO); + if (rate.compareTo(min) < 0) { + throw new SoftException( + new Par( + "This is too low (%s),", + "we do not work with rates lower than %s, see §16" + ).say(rate, min) + ); + } + if (this.wallet(uid).isEmpty()) { + throw new SoftException( + new Par( + "You must configure your wallet first,", + "before setting the rate to %s, see §20" + ).say(rate) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + People.start(uid) + .addIf("rate") + .set(rate) + ); + } + } + + /** + * Get user rate. + * @param uid User ID + * @return Rate of the user + * @throws IOException If fails + */ + public Cash rate(final String uid) throws IOException { + try (final Item item = this.item()) { + final Iterator rates = new Xocument(item.path()).nodes( + String.format( + "/people/person[@id='%s']/rate", + uid + ) + ).iterator(); + final String rate; + if (rates.hasNext()) { + rate = rates.next().xpath("text()").get(0); + } else { + rate = Cash.ZERO.toString(); + } + return new Cash.S(rate); + } catch (final CashParsingException ex) { + throw new IllegalStateException(ex); + } + } + + /** + * Set wallet. + * @param uid User ID + * @param bank Bank + * @param wallet Wallet value + * @throws IOException If fails + * @checkstyle CyclomaticComplexityCheck (100 lines) + */ + public void wallet(final String uid, final String bank, + final String wallet) throws IOException { + if (!bank.matches("paypal|btc|bch|eth|ltc")) { + throw new SoftException( + new Par( + "Bank name `%s` is invalid, we accept only", + "`paypal`, `btc`, `bch`, `eth`, or `ltc`, see §20" + ).say(bank) + ); + } + if ("paypal".equals(bank) + && !wallet.matches("\\b[\\w.%-]+@[-.\\w]+\\.[A-Za-z]{2,4}\\b")) { + throw new SoftException( + new Par("Email address is not valid: `%s`").say(wallet) + ); + } + if ("btc".equals(bank) + && !wallet.matches("(1|3|bc1)[a-zA-Z0-9]{20,40}")) { + throw new SoftException( + new Par("Bitcoin address is not valid: `%s`").say(wallet) + ); + } + if ("bch".equals(bank) + && !wallet.matches("[pq][a-z0-9]{41}")) { + throw new SoftException( + new Par("Bitcoin Cash address is not valid: `%s`").say(wallet) + ); + } + if ("eth".equals(bank) + && !wallet.matches("(0x)?[0-9a-fA-F]{40}")) { + throw new SoftException( + new Par("Ethereum address is not valid: `%s`").say(wallet) + ); + } + if ("ltc".equals(bank) + && !wallet.matches("[0-9a-zA-Z]{34}")) { + throw new SoftException( + new Par("Litecoin address is not valid: `%s`").say(wallet) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + People.start(uid) + .addIf("wallet") + .set(wallet) + .attr("bank", bank) + ); + } + } + + /** + * Get user wallet. + * @param uid User ID + * @return Wallet of the user or empty string if it's not set + * @throws IOException If fails + */ + public String wallet(final String uid) throws IOException { + try (final Item item = this.item()) { + final Iterator wallet = new Xocument(item.path()).xpath( + String.format( + "/people/person[@id='%s']/wallet/text()", + uid + ) + ).iterator(); + final String value; + if (wallet.hasNext()) { + value = wallet.next(); + } else { + value = ""; + } + return value; + } + } + + /** + * Get user bank (like "paypal"). + * @param uid User ID + * @return Wallet of the user + * @throws IOException If fails + */ + public String bank(final String uid) throws IOException { + try (final Item item = this.item()) { + final Iterator banks = new Xocument(item.path()).xpath( + String.format( + "/people/person[@id='%s']/wallet/@bank", + uid + ) + ).iterator(); + final String value; + if (banks.hasNext()) { + value = banks.next(); + } else { + value = ""; + } + return value; + } + } + + /** + * Add alias. + * + *

    There can be multiple aliases for a single user ID. Each alias + * comes from some other system, where that user is present. For example, + * "email", "twitter", "github", "jira", etc. + * @param uid User ID + * @param rel REL for the alias, e.g. "github" + * @param alias Alias, e.g. "yegor256" + * @throws IOException If fails + */ + public void link(final String uid, final String rel, + final String alias) throws IOException { + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + People.start(uid) + .addIf("links") + .add("link") + .attr("rel", rel) + .attr("href", alias) + ); + } + } + + /** + * Find user ID by alias. + * @param rel REL + * @param alias Alias + * @return Found user ID or empty iterable + * @throws IOException If fails + */ + public Iterable find(final String rel, + final String alias) throws IOException { + try (final Item item = this.item()) { + return new Xocument(item).xpath( + String.format( + "/people/person[links/link[@rel='%s' and @href='%s']]/@id", + rel, alias + ) + ); + } + } + + /** + * Get all aliases of a user. + * @param uid User ID + * @return Aliases found + * @throws IOException If fails + */ + public Iterable links(final String uid) throws IOException { + try (final Item item = this.item()) { + return new Mapped<>( + xml -> String.format( + "%s:%s", + xml.xpath("@rel").get(0), + xml.xpath("@href").get(0) + ), + new Xocument(item).nodes( + String.format( + "/people/person[@id='%s']/links/link", + uid + ) + ) + ); + } + } + + /** + * Get all aliases of a user by fixed REL. + * @param uid User ID + * @param rel The REL + * @return HREFs found + * @throws IOException If fails + */ + public Iterable links(final String uid, final String rel) + throws IOException { + try (final Item item = this.item()) { + return new Xocument(item).xpath( + String.format( + "/people/person[@id='%s']/links/link[@rel='%s']/@href", + uid, rel + ) + ); + } + } + + /** + * Get single link by REL. + * @param uid User id + * @param rel Link rel + * @return Single link href + * @throws IOException If there is no links or too many + */ + @SuppressWarnings("PMD.PrematureDeclaration") + public String link(final String uid, final String rel) + throws IOException { + final Iterator links = this.links(uid, rel).iterator(); + if (!links.hasNext()) { + throw new IOException( + String.format("No such link '%s' for '%s'", rel, uid) + ); + } + final String link = links.next(); + if (links.hasNext()) { + throw new IOException( + String.format("Too many links '%s' for '%s'", rel, uid) + ); + } + return link; + } + + /** + * Set vacation mode. + * @param uid User ID + * @param mode TRUE if vacation mode on + * @throws IOException If fails + */ + public void vacation(final String uid, + final boolean mode) throws IOException { + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + People.start(uid) + .addIf("vacation") + .set(mode) + ); + } + } + + /** + * Check vacation mode. + * @param uid User ID + * @return TRUE if person on vacation + * @throws IOException If fails + */ + public boolean vacation(final String uid) throws IOException { + try (final Item item = this.item()) { + return new UncheckedScalar<>( + new ItemAt<>( + false, + new Mapped<>( + Boolean::parseBoolean, + new Xocument(item).xpath( + String.format( + "/people/person[@id='%s']/vacation/text()", + uid + ) + ) + ) + ) + ).value(); + } + } + + /** + * Students of a person. + * @param uid Person's login + * @return Iterable with student ids + * @throws IOException If fails + */ + public Iterable students(final String uid) throws IOException { + try (final Item item = this.item()) { + return new Xocument(item.path()).xpath( + String.format( + "/people/person[mentor/text()='%s']/@id", + uid + ) + ); + } + } + + /** + * Update person reputation. + * @param uid User id + * @param rep Reputation + * @throws IOException If fails + */ + public void reputation(final String uid, final int rep) + throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format( + "/people/person[@id='%s']", + uid + ) + ).addIf("reputation").set(rep) + ); + } + } + + /** + * Get person reputation. + * @param uid User id + * @return Reputation + * @throws IOException If fails + */ + public int reputation(final String uid) throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + return new NumberOf( + new Xocument(item.path()).xpath( + String.format( + "/people/person[@id='%s']/reputation/text()", + uid + ), + "0" + ) + ).intValue(); + } + } + + /** + * Update number of jobs in person's agenda. + * @param uid User id + * @param jobs Jobs + * @throws IOException If fails + */ + public void jobs(final String uid, final int jobs) + throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format( + "/people/person[@id='%s']", + uid + ) + ).addIf("jobs").set(jobs) + ); + } + } + + /** + * Get number of jobs in person's agenda. + * @param uid User id + * @return Number of jobs in agenda + * @throws IOException If fails + */ + public int jobs(final String uid) throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + return new NumberOf( + new Xocument(item.path()).xpath( + String.format( + "/people/person[@id='%s']/jobs/text()", + uid + ), + "0" + ) + ).intValue(); + } + } + + /** + * Update person's speed. + * @param uid User id + * @param speed Speed + * @throws IOException If fails + * @todo #1121:30min We should periodically compute average speed for each + * person and update it. This stat will be displayed in Team page. + * Probably the most logical time to do this is after "Order was finished" + * claim. We can add this logic to compute_speed.groovy stakeholder. We + * should also add tests for it. + */ + public void speed(final String uid, final double speed) + throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format( + "/people/person[@id='%s']", + uid + ) + ).addIf("speed").set(speed) + ); + } + } + + /** + * Get person's speed. + * @param uid User id + * @return Speed + * @throws IOException If fails + */ + public double speed(final String uid) throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + return new NumberOf( + new Xocument(item.path()).xpath( + String.format( + "/people/person[@id='%s']/speed/text()", + uid + ), + "0.0" + ) + ).doubleValue(); + } + } + + /** + * Person exists? + * @param uid User ID + * @return TRUE if it exists + * @throws IOException If fails + */ + public boolean exists(final String uid) throws IOException { + try (final Item item = this.item()) { + return !new Xocument(item).nodes( + String.format("//people/person[@id ='%s']", uid) + ).isEmpty(); + } + } + + /** + * Apply. + * @param uid User id + * @param when When applied (UTC) + * @throws IOException If fails + */ + public void apply(final String uid, final Date when) throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format("//people/person[@id ='%s']", uid) + ).addIf("applied").set(new DateAsText(when).asString()) + ); + } + } + + /** + * Does user apply. + * @param uid User id + * @return True if applied + * @throws IOException If fails + */ + public boolean applied(final String uid) throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + return !new Xocument(item).nodes( + String.format("//people/person[@id ='%s']/applied", uid) + ).isEmpty(); + } + } + + /** + * When user applied. + * @param uid User id + * @return Applied time (UTC) + * @throws IOException If fails + */ + public Date appliedTime(final String uid) throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + if (!this.applied(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't have apply-time").say(uid) + ); + } + try (final Item item = this.item()) { + return new DateOf( + new Xocument(item).xpath( + String.format( + "//people/person[@id ='%s']/applied/text()", + uid + ) + ).get(0) + ).value(); + } + } + + /** + * The item. + * @return Item + * @throws IOException If fails + */ + private Item item() throws IOException { + return this.pmo.acq("people.xml"); + } + + /** + * Start directives, to make sure this user is in XML. + * @param uid User ID + * @return Directives + */ + private static Directives start(final String uid) { + return new Directives() + .xpath( + String.format( + "/people[not(person[@id='%s'])]", + uid + ) + ) + .add("person") + .attr("id", uid) + .add("reputation").set("0").up() + .add("jobs").set("0").up() + .add("projects").set("0").up() + .add("speed").set("0.0").up() + .add("skills").attr("updated", new DateAsText().asString()).up() + .add("links") + .add("link") + .attr("rel", "github") + .attr("href", uid) + .xpath( + String.format( + "/people/person[@id='%s']", + uid + ) + ) + .strict(1); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.zerocracy.farm.fake.FkFarm` acquired by call to `Par(...)` at line 787 is not released after line 788. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +double People.speed(String) + +### Procedure Id: +com.zerocracy.pmo.People.speed(java.lang.String):double.0cec05c61f41bc2a77ef360f1d8300e7 + +### File: +src/main/java/com/zerocracy/pmo/People.java + +### Key: +People.java|speed|RESOURCE_LEAK + +### Node Key: +da4621e3cd0bc306162ff2464b4e3806 + +### Hash: +94186817357f93c03cb1e751b95927dd + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3141/instruction.md b/inferredbugs-3141/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..341148859c04d32e7d608e167f3cbf85e2cbf8ee --- /dev/null +++ b/inferredbugs-3141/instruction.md @@ -0,0 +1,164 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** farm +**Bug ID:** 85 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2016-2018 Zerocracy + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to read + * the Software only. Permissions is hereby NOT GRANTED to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.zerocracy.pm.in; + +import com.zerocracy.Project; +import com.zerocracy.cash.Cash; +import com.zerocracy.farm.fake.FkProject; +import com.zerocracy.farm.props.PropsFarm; +import com.zerocracy.pm.cost.Estimates; +import com.zerocracy.pm.cost.Ledger; +import com.zerocracy.pm.cost.Rates; +import com.zerocracy.pm.scope.Wbs; +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; +import org.hamcrest.collection.IsEmptyCollection; +import org.junit.Test; + +/** + * Test case for {@link Orders}. + * @since 1.0 + * @checkstyle JavadocMethodCheck (500 lines) + * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) + */ +@SuppressWarnings("PMD.AvoidDuplicateLiterals") +public final class OrdersTest { + + @Test + public void assignsAndResigns() throws Exception { + final Project project = new FkProject(); + final Orders orders = new Orders(new PropsFarm(), project).bootstrap(); + final String job = "gh:yegor256/0pdd#13"; + new Wbs(project).bootstrap().add(job); + orders.assign(job, "yegor256", "0"); + } + + @Test + public void setsEstimatesOnAssign() throws Exception { + final Project project = new FkProject(); + final PropsFarm farm = new PropsFarm(); + new Ledger(farm, project).bootstrap().add( + new Ledger.Transaction( + new Cash.S("$1000"), + "assets", "cash", + "income", "sponsor", + "There is some funding just arrived" + ) + ); + final String login = "dmarkov"; + new Rates(project).bootstrap().set(login, new Cash.S("$50")); + final String job = "gh:yegor256/0pdd#19"; + final Wbs wbs = new Wbs(project).bootstrap(); + wbs.add(job); + wbs.role(job, "REV"); + final Orders orders = new Orders(farm, project).bootstrap(); + orders.assign(job, login, "0"); + MatcherAssert.assertThat( + new Estimates(farm, project).bootstrap().get(job), + Matchers.equalTo(new Cash.S("$12.50")) + ); + } + + @Test + public void removesOrder() throws Exception { + final Project project = new FkProject(); + final Orders orders = new Orders(new PropsFarm(), project).bootstrap(); + final String job = "gh:yegor256/0pdd#13"; + new Wbs(project).bootstrap().add(job); + orders.assign(job, "yegor256", "0"); + orders.remove(job); + MatcherAssert.assertThat( + "Order not removed", + orders.iterate(), + new IsEmptyCollection<>() + ); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.zerocracy.farm.fake.FkFarm` acquired by call to `PropsFarm()` at line 79 is not released after line 86. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void OrdersTest.removesOrder() + +### Procedure Id: +com.zerocracy.pm.in.OrdersTest.removesOrder():void.26742cdae7630145980f564cba2d8749 + +### File: +src/test/java/com/zerocracy/pm/in/OrdersTest.java + +### Key: +OrdersTest.java|removesOrder|RESOURCE_LEAK + +### Node Key: +14442cc3be013c833ab63ae2401ac83a + +### Hash: +55add812e54e3f1ef26ee3d1c1862d4d + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3146/instruction.md b/inferredbugs-3146/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..88f75fc7e515409d1c530908725fdd59e8771663 --- /dev/null +++ b/inferredbugs-3146/instruction.md @@ -0,0 +1,193 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** farm +**Bug ID:** 49 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) 2016-2018 Zerocracy + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to read + * the Software only. Permissions is hereby NOT GRANTED to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.zerocracy.radars.github; + +import com.jcabi.github.Issue; +import com.jcabi.github.Pull; +import com.jcabi.github.Repo; +import com.jcabi.github.Repos; +import com.jcabi.github.mock.MkGithub; +import com.zerocracy.farm.fake.FkFarm; +import com.zerocracy.farm.fake.FkProject; +import com.zerocracy.pm.staff.Roles; +import java.io.IOException; +import javax.json.Json; +import javax.json.JsonObjectBuilder; +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; +import org.junit.Test; + +/** + * Tests for {@link RbPingArchitect}. + * + * @author Krzysztof Krason (Krzysztof.Krason@gmail.com) + * @version $Id$ + * @since 0.25 + * @checkstyle JavadocMethodCheck (500 lines) + */ +@SuppressWarnings("PMD.AvoidDuplicateLiterals") +public final class RbPingArchitectTest { + + @Test + public void informsAboutMissingArc() throws IOException { + final MkGithub github = new MkGithub(); + final JsonObjectBuilder builder = + RbPingArchitectTest.event(true, github, "random"); + MatcherAssert.assertThat( + new RbPingArchitect().react(new FkFarm(), github, builder.build()), + Matchers.is("No architects here") + ); + } + + @Test + public void handlesPullRequest() throws IOException { + final MkGithub github = new MkGithub("jeff"); + final JsonObjectBuilder builder = + RbPingArchitectTest.event(false, github, "smith"); + final FkProject pkt = new FkProject(); + final FkFarm farm = new FkFarm(pkt.pid(), pkt); + final Roles roles = new Roles(pkt).bootstrap(); + roles.assign("jeff", "ARC"); + roles.assign("john", "REV"); + MatcherAssert.assertThat( + new RbPingArchitect().react(farm, github, builder.build()), + Matchers.is("Some REV will pick it up") + ); + } + + @Test + public void handlesArcIssue() throws IOException { + final MkGithub github = new MkGithub("jeff"); + final JsonObjectBuilder builder = + RbPingArchitectTest.event(true, github, "jeff"); + final FkProject pkt = new FkProject(); + final FkFarm farm = new FkFarm(pkt.pid(), pkt); + new Roles(pkt).bootstrap().assign("jeff", "ARC"); + MatcherAssert.assertThat( + new RbPingArchitect().react(farm, github, builder.build()), + Matchers.is("The architect is speaking") + ); + } + + private static JsonObjectBuilder event(final boolean iss, + final MkGithub github, final String author) + throws IOException { + final Repo repo = github.repos().create( + new Repos.RepoCreate("test", false) + ); + final JsonObjectBuilder builder = Json.createObjectBuilder() + .add( + "repository", + Json.createObjectBuilder() + .add("full_name", repo.coordinates().toString()) + .build() + ); + if (iss) { + final Issue issue = + github.relogin(author).repos().get(repo.coordinates()) + .issues().create("Some issue", "Body of issue"); + builder.add( + "issue", + Json.createObjectBuilder().add("number", issue.number()).build() + ); + } else { + github.relogin(author); + final Pull pull = + github.relogin(author).repos().get(repo.coordinates()) + .pulls().create("Some PR", "1", "2"); + builder.add( + "pull_request", + Json.createObjectBuilder().add("number", pull.number()).build() + ); + } + return builder; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.zerocracy.farm.fake.FkFarm` acquired to `farm` by call to `FkFarm(...)` at line 62 is not released after line 67. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RbPingArchitectTest.handlesPullRequest() + +### Procedure Id: +com.zerocracy.radars.github.RbPingArchitectTest.handlesPullRequest():void.bbe5723075795eb9dab765731efb6f40 + +### File: +src/test/java/com/zerocracy/radars/github/RbPingArchitectTest.java + +### Key: +RbPingArchitectTest.java|handlesPullRequest|RESOURCE_LEAK + +### Node Key: +60ed9468a41e3ec4b128da9c0342bc89 + +### Hash: +f47b32d3c6d0198173d08ad3b6d8926a + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3148/instruction.md b/inferredbugs-3148/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14fc0f2392d9fd553aca3b39c8ae997f5694a02c --- /dev/null +++ b/inferredbugs-3148/instruction.md @@ -0,0 +1,1002 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** farm +**Bug ID:** 40 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) 2016-2018 Zerocracy + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to read + * the Software only. Permissions is hereby NOT GRANTED to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.zerocracy.pmo; + +import com.jcabi.xml.XML; +import com.zerocracy.Farm; +import com.zerocracy.Item; +import com.zerocracy.Par; +import com.zerocracy.Policy; +import com.zerocracy.SoftException; +import com.zerocracy.Xocument; +import com.zerocracy.cash.Cash; +import com.zerocracy.cash.CashParsingException; +import com.zerocracy.pm.staff.Roles; +import java.io.IOException; +import java.util.Date; +import java.util.Iterator; +import org.cactoos.iterable.ItemAt; +import org.cactoos.iterable.Mapped; +import org.cactoos.scalar.NumberOf; +import org.cactoos.scalar.UncheckedScalar; +import org.cactoos.time.DateAsText; +import org.cactoos.time.DateOf; +import org.xembly.Directives; + +/** + * Data about people. + * @author Yegor Bugayenko (yegor256@gmail.com) + * @version $Id$ + * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) + * @since 0.1 + * @todo #552:30min Let's keep agenda inside `people.xml` and update it + * when agenda changed as described in + * https://github.com/zerocracy/farm/issues/366#issuecomment-359568311 + * Also put it as 'agenda' element in TkGang xml. + */ +@SuppressWarnings + ( + { + "PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals", + "PMD.NPathComplexity", "PMD.CyclomaticComplexity" + } + ) +public final class People { + + /** + * PMO. + */ + private final Pmo pmo; + + /** + * Ctor. + * @param farm Farm + */ + public People(final Farm farm) { + this(new Pmo(farm)); + } + + /** + * Ctor. + * @param pkt PMO + */ + public People(final Pmo pkt) { + this.pmo = pkt; + } + + /** + * Bootstrap it. + * @return Itself + * @throws IOException If fails + */ + public People bootstrap() throws IOException { + try (final Item item = this.item()) { + new Xocument(item.path()).bootstrap("pmo/people"); + } + return this; + } + + /** + * Get them all. + * @return List of them + * @throws IOException If fails + */ + public Iterable iterate() throws IOException { + try (final Item item = this.item()) { + return new Xocument(item.path()).xpath( + "/people/person/@id" + ); + } + } + + /** + * Remove person. + * @param uid Person id + * @throws IOException If fails + */ + public void remove(final String uid) throws IOException { + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format("/people/person[@id='%s']", uid) + ).remove() + ); + } + } + + /** + * Touch this dude. + * @param uid User ID + * @throws IOException If fails + */ + public void touch(final String uid) throws IOException { + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + People.start(uid) + ); + } + } + + /** + * Set mentor to '0crat'. + * @param uid User ID + * @throws IOException If fails + */ + public void graduate(final String uid) throws IOException { + if (!this.hasMentor(uid)) { + throw new SoftException( + new Par( + "User @%s is not with us yet" + ).say(uid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + People.start(uid) + .addIf("mentor") + .set("0crat") + ); + } + } + + /** + * Set details. + * @param uid User ID + * @param text Text to save + * @throws IOException If fails + */ + public void details(final String uid, final String text) + throws IOException { + if (!this.hasMentor(uid)) { + throw new SoftException( + new Par( + "User @%s is not with us yet" + ).say(uid) + ); + } + if (text.isEmpty()) { + throw new SoftException( + new Par( + "User @%s details can't be empty" + ).say(uid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + People.start(uid) + .addIf("details") + .set(text) + ); + } + } + + /** + * Get user details. + * @param uid User ID + * @return Details of the user + * @throws IOException If fails + */ + public String details(final String uid) throws IOException { + try (final Item item = this.item()) { + final Iterator items = new Xocument(item.path()).xpath( + String.format( + "/people/person[@id='%s']/details/text()", + uid + ) + ).iterator(); + final String text; + if (items.hasNext()) { + text = items.next(); + } else { + text = ""; + } + return text; + } + } + + /** + * Invite that person and set a mentor. + * @param uid User ID + * @param mentor User ID of the mentor + * @throws IOException If fails + */ + public void invite(final String uid, final String mentor) + throws IOException { + if (this.hasMentor(uid)) { + throw new SoftException( + new Par( + "@%s is already with us, no need to invite again" + ).say(uid) + ); + } + try (final Item item = this.item()) { + final int max = new Policy().get("1.max-students", 16); + final int current = new Xocument(item.path()) + .nodes( + String.format( + "/people/person[mentor/text()='%s']", + mentor + ) + ).size(); + if (current >= max + && !new Roles(this.pmo).bootstrap().hasAnyRole(mentor)) { + throw new SoftException( + new Par( + "You can not invite more than %d students;", + "you already have %d, see §1" + ).say(max, current) + ); + } + new Xocument(item.path()).modify( + People.start(uid) + .push() + .xpath("mentor") + .strict(0) + .pop() + .add("mentor") + .set(mentor) + ); + } + } + + /** + * This person has a mentor? + * @param uid User ID + * @return TRUE if he has a mentor + * @throws IOException If fails + */ + public boolean hasMentor(final String uid) throws IOException { + try (final Item item = this.item()) { + return !new Xocument(item.path()).nodes( + String.format( + "/people/person[@id='%s']/mentor", + uid + ) + ).isEmpty(); + } + } + + /** + * Person's mentor. + * @param uid User ID + * @return Id of person's mentor + * @throws IOException If fails + */ + public String mentor(final String uid) throws IOException { + try (final Item item = this.item()) { + return new Xocument(item.path()).xpath( + String.format( + "/people/person[@id='%s']/mentor/text()", + uid + ) + ).get(0); + } + } + + /** + * Breakup with a person. + * @param uid User ID + * @throws IOException If fails + */ + public void breakup(final String uid) throws IOException { + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format("/people/person[@id='%s']/mentor", uid) + ).remove() + ); + } + } + + /** + * Set rate. + * @param uid User ID + * @param rate Rate of the user + * @throws IOException If fails + */ + public void rate(final String uid, final Cash rate) throws IOException { + final Cash max = new Policy().get("16.max", new Cash.S("$256")); + if (rate.compareTo(max) > 0) { + throw new SoftException( + new Par( + "This is too high (%s),", + "we do not work with rates higher than %s, see §16" + ).say(rate, max) + ); + } + final Cash min = new Policy().get("16.min", Cash.ZERO); + if (rate.compareTo(min) < 0) { + throw new SoftException( + new Par( + "This is too low (%s),", + "we do not work with rates lower than %s, see §16" + ).say(rate, min) + ); + } + if (this.wallet(uid).isEmpty()) { + throw new SoftException( + new Par( + "You must configure your wallet first,", + "before setting the rate to %s, see §20" + ).say(rate) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + People.start(uid) + .addIf("rate") + .set(rate) + ); + } + } + + /** + * Get user rate. + * @param uid User ID + * @return Rate of the user + * @throws IOException If fails + */ + public Cash rate(final String uid) throws IOException { + try (final Item item = this.item()) { + final Iterator rates = new Xocument(item.path()).nodes( + String.format( + "/people/person[@id='%s']/rate", + uid + ) + ).iterator(); + final String rate; + if (rates.hasNext()) { + rate = rates.next().xpath("text()").get(0); + } else { + rate = Cash.ZERO.toString(); + } + return new Cash.S(rate); + } catch (final CashParsingException ex) { + throw new IllegalStateException(ex); + } + } + + /** + * Set wallet. + * @param uid User ID + * @param bank Bank + * @param wallet Wallet value + * @throws IOException If fails + * @checkstyle CyclomaticComplexityCheck (100 lines) + */ + public void wallet(final String uid, final String bank, + final String wallet) throws IOException { + if (!bank.matches("paypal|btc|bch|eth|ltc")) { + throw new SoftException( + new Par( + "Bank name `%s` is invalid, we accept only", + "`paypal`, `btc`, `bch`, `eth`, or `ltc`, see §20" + ).say(bank) + ); + } + if ("paypal".equals(bank) + && !wallet.matches("\\b[\\w.%-]+@[-.\\w]+\\.[A-Za-z]{2,4}\\b")) { + throw new SoftException( + new Par("Email address is not valid: `%s`").say(wallet) + ); + } + if ("btc".equals(bank) + && !wallet.matches("(1|3|bc1)[a-zA-Z0-9]{20,40}")) { + throw new SoftException( + new Par("Bitcoin address is not valid: `%s`").say(wallet) + ); + } + if ("bch".equals(bank) + && !wallet.matches("[pq][a-z0-9]{41}")) { + throw new SoftException( + new Par("Bitcoin Cash address is not valid: `%s`").say(wallet) + ); + } + if ("eth".equals(bank) + && !wallet.matches("(0x)?[0-9a-fA-F]{40}")) { + throw new SoftException( + new Par("Ethereum address is not valid: `%s`").say(wallet) + ); + } + if ("ltc".equals(bank) + && !wallet.matches("[0-9a-zA-Z]{34}")) { + throw new SoftException( + new Par("Litecoin address is not valid: `%s`").say(wallet) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + People.start(uid) + .addIf("wallet") + .set(wallet) + .attr("bank", bank) + ); + } + } + + /** + * Get user wallet. + * @param uid User ID + * @return Wallet of the user or empty string if it's not set + * @throws IOException If fails + */ + public String wallet(final String uid) throws IOException { + try (final Item item = this.item()) { + final Iterator wallet = new Xocument(item.path()).xpath( + String.format( + "/people/person[@id='%s']/wallet/text()", + uid + ) + ).iterator(); + final String value; + if (wallet.hasNext()) { + value = wallet.next(); + } else { + value = ""; + } + return value; + } + } + + /** + * Get user bank (like "paypal"). + * @param uid User ID + * @return Wallet of the user + * @throws IOException If fails + */ + public String bank(final String uid) throws IOException { + try (final Item item = this.item()) { + final Iterator banks = new Xocument(item.path()).xpath( + String.format( + "/people/person[@id='%s']/wallet/@bank", + uid + ) + ).iterator(); + final String value; + if (banks.hasNext()) { + value = banks.next(); + } else { + value = ""; + } + return value; + } + } + + /** + * Add alias. + * + *

    There can be multiple aliases for a single user ID. Each alias + * comes from some other system, where that user is present. For example, + * "email", "twitter", "github", "jira", etc. + * @param uid User ID + * @param rel REL for the alias, e.g. "github" + * @param alias Alias, e.g. "yegor256" + * @throws IOException If fails + */ + public void link(final String uid, final String rel, + final String alias) throws IOException { + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + People.start(uid) + .addIf("links") + .add("link") + .attr("rel", rel) + .attr("href", alias) + ); + } + } + + /** + * Find user ID by alias. + * @param rel REL + * @param alias Alias + * @return Found user ID or empty iterable + * @throws IOException If fails + */ + public Iterable find(final String rel, + final String alias) throws IOException { + try (final Item item = this.item()) { + return new Xocument(item).xpath( + String.format( + "/people/person[links/link[@rel='%s' and @href='%s']]/@id", + rel, alias + ) + ); + } + } + + /** + * Get all aliases of a user. + * @param uid User ID + * @return Aliases found + * @throws IOException If fails + */ + public Iterable links(final String uid) throws IOException { + try (final Item item = this.item()) { + return new Mapped<>( + xml -> String.format( + "%s:%s", + xml.xpath("@rel").get(0), + xml.xpath("@href").get(0) + ), + new Xocument(item).nodes( + String.format( + "/people/person[@id='%s']/links/link", + uid + ) + ) + ); + } + } + + /** + * Get all aliases of a user by fixed REL. + * @param uid User ID + * @param rel The REL + * @return HREFs found + * @throws IOException If fails + */ + public Iterable links(final String uid, final String rel) + throws IOException { + try (final Item item = this.item()) { + return new Xocument(item).xpath( + String.format( + "/people/person[@id='%s']/links/link[@rel='%s']/@href", + uid, rel + ) + ); + } + } + + /** + * Get single link by REL. + * @param uid User id + * @param rel Link rel + * @return Single link href + * @throws IOException If there is no links or too many + */ + @SuppressWarnings("PMD.PrematureDeclaration") + public String link(final String uid, final String rel) + throws IOException { + final Iterator links = this.links(uid, rel).iterator(); + if (!links.hasNext()) { + throw new IOException( + String.format("No such link '%s' for '%s'", rel, uid) + ); + } + final String link = links.next(); + if (links.hasNext()) { + throw new IOException( + String.format("Too many links '%s' for '%s'", rel, uid) + ); + } + return link; + } + + /** + * Set vacation mode. + * @param uid User ID + * @param mode TRUE if vacation mode on + * @throws IOException If fails + */ + public void vacation(final String uid, + final boolean mode) throws IOException { + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + People.start(uid) + .addIf("vacation") + .set(mode) + ); + } + } + + /** + * Check vacation mode. + * @param uid User ID + * @return TRUE if person on vacation + * @throws IOException If fails + */ + public boolean vacation(final String uid) throws IOException { + try (final Item item = this.item()) { + return new UncheckedScalar<>( + new ItemAt<>( + false, + new Mapped<>( + Boolean::parseBoolean, + new Xocument(item).xpath( + String.format( + "/people/person[@id='%s']/vacation/text()", + uid + ) + ) + ) + ) + ).value(); + } + } + + /** + * Students of a person. + * @param uid Person's login + * @return Iterable with student ids + * @throws IOException If fails + */ + public Iterable students(final String uid) throws IOException { + try (final Item item = this.item()) { + return new Xocument(item.path()).xpath( + String.format( + "/people/person[mentor/text()='%s']/@id", + uid + ) + ); + } + } + + /** + * Update person reputation. + * @param uid User id + * @param rep Reputation + * @throws IOException If fails + */ + public void reputation(final String uid, final int rep) + throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format( + "/people/person[@id='%s']", + uid + ) + ).addIf("reputation").set(rep) + ); + } + } + + /** + * Get person reputation. + * @param uid User id + * @return Reputation + * @throws IOException If fails + */ + public int reputation(final String uid) throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + return new NumberOf( + new Xocument(item.path()).xpath( + String.format( + "/people/person[@id='%s']/reputation/text()", + uid + ), + "0" + ) + ).intValue(); + } + } + + /** + * Update number of jobs in person's agenda. + * @param uid User id + * @param jobs Jobs + * @throws IOException If fails + */ + public void jobs(final String uid, final int jobs) + throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format( + "/people/person[@id='%s']", + uid + ) + ).addIf("jobs").set(jobs) + ); + } + } + + /** + * Get number of jobs in person's agenda. + * @param uid User id + * @return Number of jobs in agenda + * @throws IOException If fails + */ + public int jobs(final String uid) throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + return new NumberOf( + new Xocument(item.path()).xpath( + String.format( + "/people/person[@id='%s']/jobs/text()", + uid + ), + "0" + ) + ).intValue(); + } + } + + /** + * Update person's speed. + * @param uid User id + * @param speed Speed + * @throws IOException If fails + * @todo #1121:30min We should periodically compute average speed for each + * person and update it. This stat will be displayed in Team page. + * Probably the most logical time to do this is after "Order was finished" + * claim. We can add this logic to compute_speed.groovy stakeholder. We + * should also add tests for it. + */ + public void speed(final String uid, final double speed) + throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format( + "/people/person[@id='%s']", + uid + ) + ).addIf("speed").set(speed) + ); + } + } + + /** + * Get person's speed. + * @param uid User id + * @return Speed + * @throws IOException If fails + */ + public double speed(final String uid) throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + return new NumberOf( + new Xocument(item.path()).xpath( + String.format( + "/people/person[@id='%s']/speed/text()", + uid + ), + "0.0" + ) + ).doubleValue(); + } + } + + /** + * Person exists? + * @param uid User ID + * @return TRUE if it exists + * @throws IOException If fails + */ + public boolean exists(final String uid) throws IOException { + try (final Item item = this.item()) { + return !new Xocument(item).nodes( + String.format("//people/person[@id ='%s']", uid) + ).isEmpty(); + } + } + + /** + * Apply. + * @param uid User id + * @param when When applied (UTC) + * @throws IOException If fails + */ + public void apply(final String uid, final Date when) throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + new Xocument(item.path()).modify( + new Directives().xpath( + String.format("//people/person[@id ='%s']", uid) + ).addIf("applied").set(new DateAsText(when).asString()) + ); + } + } + + /** + * Does user apply. + * @param uid User id + * @return True if applied + * @throws IOException If fails + */ + public boolean applied(final String uid) throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + try (final Item item = this.item()) { + return !new Xocument(item).nodes( + String.format("//people/person[@id ='%s']/applied", uid) + ).isEmpty(); + } + } + + /** + * When user applied. + * @param uid User id + * @return Applied time (UTC) + * @throws IOException If fails + */ + public Date appliedTime(final String uid) throws IOException { + if (!this.exists(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't exist").say(uid) + ); + } + if (!this.applied(uid)) { + throw new IllegalArgumentException( + new Par("Person @%s doesn't have apply-time").say(uid) + ); + } + try (final Item item = this.item()) { + return new DateOf( + new Xocument(item).xpath( + String.format( + "//people/person[@id ='%s']/applied/text()", + uid + ) + ).get(0) + ).value(); + } + } + + /** + * The item. + * @return Item + * @throws IOException If fails + */ + private Item item() throws IOException { + return this.pmo.acq("people.xml"); + } + + /** + * Start directives, to make sure this user is in XML. + * @param uid User ID + * @return Directives + */ + private static Directives start(final String uid) { + return new Directives() + .xpath( + String.format( + "/people[not(person[@id='%s'])]", + uid + ) + ) + .add("person") + .attr("id", uid) + .add("reputation").set("0").up() + .add("jobs").set("0").up() + .add("projects").set("0").up() + .add("speed").set("0.0").up() + .add("skills").attr("updated", new DateAsText().asString()).up() + .add("links") + .add("link") + .attr("rel", "github") + .attr("href", uid) + .xpath( + String.format( + "/people/person[@id='%s']", + uid + ) + ) + .strict(1); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.zerocracy.farm.fake.FkFarm` acquired by call to `Par(...)` at line 763 is not released after line 764. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void People.speed(String,double) + +### Procedure Id: +com.zerocracy.pmo.People.speed(java.lang.String,double):void.f9aba51780c661589b023be29e8476c0 + +### File: +src/main/java/com/zerocracy/pmo/People.java + +### Key: +People.java|speed|RESOURCE_LEAK + +### Node Key: +da4621e3cd0bc306162ff2464b4e3806 + +### Hash: +94186817357f93c03cb1e751b95927dd + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3170/instruction.md b/inferredbugs-3170/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..387e27e349cd68d117853a364f488d1145607757 --- /dev/null +++ b/inferredbugs-3170/instruction.md @@ -0,0 +1,174 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** hank +**Bug ID:** 20 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright 2011 Rapleaf + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rapleaf.hank.storage.cueball; + +import com.rapleaf.hank.compress.CompressionCodec; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.util.List; + + +public final class CueballMerger implements ICueballMerger { + + public void merge(final CueballFilePath base, + final List deltas, + final String newBasePath, + final int keyHashSize, + final int valueSize, + ValueTransformer transformer, + int hashIndexBits, + CompressionCodec compressionCodec) throws IOException { + // Perform merging + + StreamBuffer[] sbs = new StreamBuffer[deltas.size() + 1]; + + // open the current base + StreamBuffer baseBuffer = new StreamBuffer(base.getPath(), 0, + keyHashSize, valueSize, hashIndexBits, compressionCodec); + sbs[0] = baseBuffer; + + // open all the deltas + int i = 1; + for (CueballFilePath delta : deltas) { + StreamBuffer db = new StreamBuffer(delta.getPath(), i, + keyHashSize, valueSize, hashIndexBits, compressionCodec); + sbs[i++] = db; + } + + // output stream for the new base to be written. intentionally unbuffered - + // the writer below will do that on its own. + OutputStream newBaseStream = new FileOutputStream(newBasePath); + + // note that we intentionally omit the hasher here, since it will *not* be + // used + CueballWriter writer = new CueballWriter(newBaseStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits); + + while (true) { + StreamBuffer least = null; + for (i = 0; i < sbs.length; i++) { + boolean remaining = sbs[i].anyRemaining(); + if (remaining) { + if (least == null) { + least = sbs[i]; + } else { + int comparison = least.compareTo(sbs[i]); + if (comparison == 0) { + least.consume(); + least = sbs[i]; + } else if (comparison == 1) { + least = sbs[i]; + } + } + } + } + + if (least == null) { + break; + } + + if (transformer != null) { + transformer.transform(least.getBuffer(), least.getCurrentOffset() + keyHashSize, least.getIndex()); + } + final ByteBuffer keyHash = ByteBuffer.wrap(least.getBuffer(), least.getCurrentOffset(), keyHashSize); + final ByteBuffer valueBytes = ByteBuffer.wrap(least.getBuffer(), least.getCurrentOffset() + keyHashSize, valueSize); + writer.writeHash(keyHash, valueBytes); + least.consume(); + } + + for (StreamBuffer sb : sbs) { + sb.close(); + } + + writer.close(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired by call to `StreamBuffer(...)` at line 42 is not released after line 98. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CueballMerger.merge(CueballFilePath,List,String,int,int,ValueTransformer,int,CompressionCodec) + +### Procedure Id: +com.rapleaf.hank.storage.cueball.CueballMerger.merge(com.rapleaf.hank.storage.cueball.CueballFilePat.f50289f4ecf49c83da663db79fd5435b + +### File: +src/java/com/rapleaf/hank/storage/cueball/CueballMerger.java + +### Key: +CueballMerger.java|merge|RESOURCE_LEAK + +### Node Key: +e750639a3212731ac04d264329f25a2b + +### Hash: +286108b36d7eeea2913897734cae5865 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3176/instruction.md b/inferredbugs-3176/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..769f5f6f8f7491acd50d57f86b1ce61dd18aab4d --- /dev/null +++ b/inferredbugs-3176/instruction.md @@ -0,0 +1,185 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** hank +**Bug ID:** 29 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright 2011 Rapleaf + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rapleaf.hank.storage.cueball; + +import com.rapleaf.hank.compress.CompressionCodec; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.util.List; + + +public final class CueballMerger implements ICueballMerger { + + public void merge(final CueballFilePath base, + final List deltas, + final String newBasePath, + final int keyHashSize, + final int valueSize, + ValueTransformer transformer, + int hashIndexBits, + CompressionCodec compressionCodec) throws IOException { + // Array of stream buffers for the base and all deltas in order + CueballStreamBuffer[] cueballStreamBuffers = new CueballStreamBuffer[deltas.size() + 1]; + + // Open the current base + CueballStreamBuffer cueballBaseStreamBuffer = new CueballStreamBuffer(base.getPath(), 0, + keyHashSize, valueSize, hashIndexBits, compressionCodec); + cueballStreamBuffers[0] = cueballBaseStreamBuffer; + + // Open all the deltas + int i = 1; + for (CueballFilePath delta : deltas) { + CueballStreamBuffer cueballStreamBuffer = + new CueballStreamBuffer(delta.getPath(), i, keyHashSize, valueSize, hashIndexBits, compressionCodec); + cueballStreamBuffers[i++] = cueballStreamBuffer; + } + + // Output stream for the new base to be written. intentionally unbuffered, the writer below will do that on its own. + OutputStream newCueballBaseOutputStream = new FileOutputStream(newBasePath); + + // Note that we intentionally omit the hasher here, since it will *not* be used + CueballWriter newCueballBaseWriter = + new CueballWriter(newCueballBaseOutputStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits); + + while (true) { + // Find the stream buffer with the next smallest key hash + CueballStreamBuffer cueballStreamBufferToUse = null; + for (i = 0; i < cueballStreamBuffers.length; i++) { + if (cueballStreamBuffers[i].anyRemaining()) { + if (cueballStreamBufferToUse == null) { + cueballStreamBufferToUse = cueballStreamBuffers[i]; + } else { + int comparison = cueballStreamBufferToUse.compareTo(cueballStreamBuffers[i]); + if (comparison == 0) { + // If two equal key hashes are found, use the most recent value (i.e. the one from the lastest delta) + // and skip (consume) the older ones + cueballStreamBufferToUse.consume(); + cueballStreamBufferToUse = cueballStreamBuffers[i]; + } else if (comparison == 1) { + // Found a stream buffer with a smaller key hash + cueballStreamBufferToUse = cueballStreamBuffers[i]; + } + } + } + } + + if (cueballStreamBufferToUse == null) { + // Nothing more to write + break; + } + + // Transform if necessary + if (transformer != null) { + transformer.transform(cueballStreamBufferToUse.getBuffer(), + cueballStreamBufferToUse.getCurrentOffset() + keyHashSize, + cueballStreamBufferToUse.getIndex()); + } + + // Get next key hash and value + final ByteBuffer keyHash = ByteBuffer.wrap(cueballStreamBufferToUse.getBuffer(), + cueballStreamBufferToUse.getCurrentOffset(), keyHashSize); + final ByteBuffer valueBytes = ByteBuffer.wrap(cueballStreamBufferToUse.getBuffer(), + cueballStreamBufferToUse.getCurrentOffset() + keyHashSize, valueSize); + + // Write next key hash and value + newCueballBaseWriter.writeHash(keyHash, valueBytes); + cueballStreamBufferToUse.consume(); + } + + // Close all buffers and the base writer + for (CueballStreamBuffer cueballStreamBuffer : cueballStreamBuffers) { + cueballStreamBuffer.close(); + } + newCueballBaseWriter.close(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired by call to `CueballStreamBuffer(...)` at line 41 is not released after line 109. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CueballMerger.merge(CueballFilePath,List,String,int,int,ValueTransformer,int,CompressionCodec) + +### Procedure Id: +com.rapleaf.hank.storage.cueball.CueballMerger.merge(com.rapleaf.hank.storage.cueball.CueballFilePat.f50289f4ecf49c83da663db79fd5435b + +### File: +src/java/com/rapleaf/hank/storage/cueball/CueballMerger.java + +### Key: +CueballMerger.java|merge|RESOURCE_LEAK + +### Node Key: +e750639a3212731ac04d264329f25a2b + +### Hash: +863d3ad5d4a172194e5d1f12738c56aa + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3178/instruction.md b/inferredbugs-3178/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..80153bd49b3e65845b642c620556587761307ecd --- /dev/null +++ b/inferredbugs-3178/instruction.md @@ -0,0 +1,275 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** hank +**Bug ID:** 42 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright 2011 Rapleaf + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rapleaf.hank.ring_group_conductor; + +import com.rapleaf.hank.config.RingGroupConductorConfigurator; +import com.rapleaf.hank.config.yaml.YamlRingGroupConductorConfigurator; +import com.rapleaf.hank.coordinator.*; +import com.rapleaf.hank.partition_assigner.ModPartitionAssigner; +import com.rapleaf.hank.util.CommandLineChecker; +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; + +import java.io.IOException; + +public class RingGroupConductor implements RingGroupChangeListener, DomainGroupChangeListener { + + private static final Logger LOG = Logger.getLogger(RingGroupConductor.class); + + private final RingGroupConductorConfigurator configurator; + private final String ringGroupName; + private final Coordinator coordinator; + private final Object lock = new Object(); + + private RingGroup ringGroup; + private DomainGroup domainGroup; + + private final RingGroupUpdateTransitionFunction transFunc; + + private boolean stopping = false; + private boolean claimedRingGroupConductor; + + private Thread shutdownHook; + + public RingGroupConductor(RingGroupConductorConfigurator configurator) throws IOException { + this(configurator, new RingGroupUpdateTransitionFunctionImpl(new ModPartitionAssigner())); + } + + RingGroupConductor(RingGroupConductorConfigurator configurator, RingGroupUpdateTransitionFunction transFunc) throws IOException { + this.configurator = configurator; + this.transFunc = transFunc; + ringGroupName = configurator.getRingGroupName(); + this.coordinator = configurator.createCoordinator(); + } + + public void run() throws IOException { + // Add shutdown hook + addShutdownHook(); + claimedRingGroupConductor = false; + LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting."); + try { + ringGroup = coordinator.getRingGroup(ringGroupName); + + // attempt to claim the ring group conductor title + if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) { + claimedRingGroupConductor = true; + + // we are now *the* ring group conductor for this ring group. + domainGroup = ringGroup.getDomainGroup(); + + // set a watch on the ring group + ringGroup.setListener(this); + + // set a watch on the domain group version + domainGroup.setListener(this); + + // loop until we're taken down + stopping = false; + try { + while (!stopping) { + // take a snapshot of the current ring, since it might get changed + // while we're processing the current update. + RingGroup snapshotRingGroup; + synchronized (lock) { + snapshotRingGroup = ringGroup; + } + + // Only process updates if ring group conductor is configured to be active/proactive + if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE || + snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.PROACTIVE) { + processUpdates(snapshotRingGroup); + } + Thread.sleep(configurator.getSleepInterval()); + } + } catch (InterruptedException e) { + // daemon is going down. + } + } else { + LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!"); + } + } catch (Throwable t) { + LOG.fatal("unexpected exception!", t); + } finally { + releaseIfClaimed(); + } + LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down."); + // Remove shutdown hook. We don't need it anymore + removeShutdownHook(); + } + + void processUpdates(RingGroup ringGroup) throws IOException { + RingGroupConductorMode ringGroupConductorMode = ringGroup.getRingGroupConductorMode(); + if (ringGroupConductorMode != null && ringGroupConductorMode.equals(RingGroupConductorMode.PROACTIVE)) { + // Check if there is a new version available for this ring group (only in PROACTIVE mode) + final DomainGroupVersion domainGroupVersion = DomainGroups.getLatestVersion(ringGroup.getDomainGroup()); + if (domainGroupVersion != null && + (ringGroup.getTargetVersionNumber() == null || + ringGroup.getTargetVersionNumber() < domainGroupVersion.getVersionNumber())) { + // There is a more recent version available + LOG.info("There is a new domain group version available for ring group " + ringGroupName + + ": " + domainGroupVersion); + // We can change the target version of this ring group + LOG.info("Changing target version of ring group " + ringGroupName + + " to domain group version " + domainGroupVersion); + RingGroups.setTargetVersion(ringGroup, domainGroupVersion); + } + } + transFunc.manageTransitions(ringGroup); + } + + @Override + public void onRingGroupChange(RingGroup newRingGroup) { + synchronized (lock) { + if (LOG.isDebugEnabled()) { + LOG.debug("Got an updated ring group version!"); + } + ringGroup = newRingGroup; + } + } + + @Override + public void onDomainGroupChange(DomainGroup newDomainGroup) { + synchronized (lock) { + if (LOG.isDebugEnabled()) { + LOG.debug("Got an updated domain group version: " + newDomainGroup + "!"); + } + domainGroup = newDomainGroup; + } + } + + private void releaseIfClaimed() throws IOException { + if (claimedRingGroupConductor) { + ringGroup.releaseRingGroupConductor(); + claimedRingGroupConductor = false; + } + } + + // Give up ring group conductor status on VM exit + private void addShutdownHook() { + if (shutdownHook == null) { + shutdownHook = new Thread() { + @Override + public void run() { + try { + releaseIfClaimed(); + } catch (IOException e) { + // When VM is exiting and we fail to release ring group conductor status, swallow the exception + } + } + }; + Runtime.getRuntime().addShutdownHook(shutdownHook); + } + } + + private void removeShutdownHook() { + if (shutdownHook != null) { + Runtime.getRuntime().removeShutdownHook(shutdownHook); + } + } + + /** + * @param args + * @throws Exception + */ + public static void main(String[] args) throws Exception { + CommandLineChecker.check(args, new String[]{"configuration_file_path", "log4j_properties_file_path"}, RingGroupConductor.class); + String configPath = args[0]; + String log4jprops = args[1]; + + RingGroupConductorConfigurator configurator = new YamlRingGroupConductorConfigurator(configPath); + PropertyConfigurator.configure(log4jprops); + new RingGroupConductor(configurator).run(); + } + + public void stop() { + stopping = true; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.rapleaf.hank.ring_group_conductor.RingGroupConductor.run` writes to field `this.com.rapleaf.hank.ring_group_conductor.RingGroupConductor.domainGroup` outside of synchronization. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RingGroupConductor.run() + +### Procedure Id: +com.rapleaf.hank.ring_group_conductor.RingGroupConductor.run():void.2d356068d96d10e3e687d858a273c102 + +### File: +src/java/com/rapleaf/hank/ring_group_conductor/RingGroupConductor.java + +### Key: +RingGroupConductor.java|run|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +a92a80212921fc5ea6ce4c3bf903c05b + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3179/instruction.md b/inferredbugs-3179/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..97ef794c869a6292f0eb69eef67a62faed5fb073 --- /dev/null +++ b/inferredbugs-3179/instruction.md @@ -0,0 +1,355 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** hank +**Bug ID:** 45 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright 2011 Rapleaf + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.rapleaf.hank.partition_server; + +import java.text.DecimalFormat; +import java.util.Arrays; + +public class DoublePopulationStatisticsAggregator { + + private static DecimalFormat format3 = new DecimalFormat("#.###"); + private static DecimalFormat format1 = new DecimalFormat("#.#"); + private static DecimalFormat format0 = new DecimalFormat("#"); + + private double minimum; + private double maximum; + private long numValues; + private double total; + private double[] deciles; + + public DoublePopulationStatisticsAggregator() { + minimum = Double.MAX_VALUE; + maximum = Double.MIN_VALUE; + numValues = 0; + total = 0.0; + deciles = new double[]{0, 0, 0, 0, 0, 0, 0, 0, 0}; + } + + public DoublePopulationStatisticsAggregator(double minimum, + double maximum, + long numValues, + double total, + double[] deciles) { + if (deciles.length != 9) { + throw new RuntimeException("Invalid population statistics: num deciles =" + deciles.length); + } + this.minimum = minimum; + this.maximum = maximum; + this.numValues = numValues; + this.total = total; + this.deciles = deciles; + } + + public void clear() { + minimum = Double.MAX_VALUE; + maximum = Double.MIN_VALUE; + numValues = 0; + total = 0.0; + Arrays.fill(deciles, 0); + } + + public void aggregate(double minimum, double maximum, long numValues, double total, double[] deciles) { + if (numValues < 10 || deciles.length != 9) { + throw new RuntimeException("Invalid population statistics to aggregate. numValues=" + + numValues + ", deciles.length=" + deciles.length); + } + if (this.numValues == 0) { + // Copy deciles directly + System.arraycopy(deciles, 0, this.deciles, 0, 9); + } else if (numValues == 0) { + // Do nothing + } else { + aggregateDeciles(this.deciles, this.numValues, this.getMaximum(), + deciles, numValues, maximum, + this.deciles); + } + if (maximum > this.maximum) { + this.maximum = maximum; + } + if (minimum < this.minimum) { + this.minimum = minimum; + } + this.numValues += numValues; + this.total += total; + } + + public void aggregate(DoublePopulationStatisticsAggregator other) { + if (numValues == 0) { + // Copy deciles directly + System.arraycopy(other.deciles, 0, deciles, 0, 9); + } else if (other.numValues == 0) { + // Keep this deciles unchanged + } else { + // Aggregate both deciles + aggregateDeciles(this.deciles, this.numValues, this.getMaximum(), + other.deciles, other.numValues, other.getMaximum(), + this.deciles); + } + if (other.maximum > this.maximum) { + this.maximum = other.maximum; + } + if (other.minimum < this.minimum) { + this.minimum = other.minimum; + } + this.numValues += other.numValues; + this.total += other.total; + } + + private static void aggregateDeciles(double[] decilesA, long numValuesA, double maximumA, + double[] decilesB, long numValuesB, double maximumB, + double[] outputDeciles) { + // Compute all deciles + ValueAndCount[] allDeciles = new ValueAndCount[2 * 10]; + // Load all decile values and counts into one array + for (int i = 0; i < 9; ++i) { + allDeciles[i] = new ValueAndCount(decilesA[i], numValuesA); + allDeciles[i + 9] = new ValueAndCount(decilesB[i], numValuesB); + } + + // Fake deciles to fill in voids + allDeciles[18] = new ValueAndCount(maximumA, numValuesA); + allDeciles[19] = new ValueAndCount(maximumB, numValuesB); + + // Sort all deciles + Arrays.sort(allDeciles); + + // Update deciles + final long numValuesCombined = 10 * (numValuesA + numValuesB); + long previousRank = 0; + int j = 0; + for (int i = 0; i < 9; ++i) { + final long decileRank = Math.round(getDecileRank(numValuesCombined, i + 1)); + while (previousRank + allDeciles[j].count < decileRank) { + previousRank += allDeciles[j].count; + j += 1; + } + + // j point to the current segment where the correct decile rank lies + if (j == 0) { + // For the first decile, consider all value to be equal (no interpolation) + outputDeciles[i] = allDeciles[j].value; + } else { + // Interpolate value for other deciles + outputDeciles[i] = + interpolateValueWithinValueAndCounts(allDeciles[j - 1].value, + allDeciles[j], + decileRank - previousRank); + } + } + } + + public static double interpolateValueWithinValueAndCounts(double value, ValueAndCount segment, long indexInSegment) { + double remainder = (double) (indexInSegment + 1) / (double) segment.count; + return value + remainder * (segment.value - value); + } + + public Double getMaximum() { + if (maximum == Double.MIN_VALUE) { + return null; + } + return maximum; + } + + public Double getMinimum() { + if (minimum == Double.MAX_VALUE) { + return null; + } + return minimum; + } + + public double getMean() { + if (numValues != 0) { + return total / numValues; + } else { + return 0; + } + } + + public double[] getDeciles() { + return deciles; + } + + public static String toString(DoublePopulationStatisticsAggregator populationStatistics) { + StringBuilder result = new StringBuilder(); + result.append(populationStatistics.minimum); + result.append(' '); + result.append(populationStatistics.maximum); + result.append(' '); + result.append(populationStatistics.numValues); + result.append(' '); + result.append(populationStatistics.total); + for (int i = 0; i < 9; ++i) { + result.append(' '); + result.append(populationStatistics.deciles[i]); + } + return result.toString(); + } + + public static String formatDouble(double value) { + if (value < 1) { + return format3.format(value); + } else if (value < 100) { + return format1.format(value); + } else { + return format0.format(value); + } + } + + public String format() { + StringBuilder result = new StringBuilder(); + // Compute median on the fly + double median = numValues == 0 ? 0 : deciles[4]; + // Compute 90% percentile on the fly + double ninetiethPercentile = numValues == 0 ? 0 : deciles[8]; + result.append(formatDouble(getMean())); + result.append(" / "); + result.append(formatDouble(median)); + result.append(" / "); + result.append(formatDouble(ninetiethPercentile)); + result.append(" ms"); + return result.toString(); + } + + public static class ValueAndCount implements Comparable { + + public final double value; + public final long count; + + public ValueAndCount(double value, long count) { + this.value = value; + this.count = count; + } + + @Override + public int compareTo(DoublePopulationStatisticsAggregator.ValueAndCount other) { + return Double.compare(value, other.value); + } + + @Override + public String toString() { + return value + "(" + count + ")"; + } + } + + public static double getSortedPopulationDecile(double[] population, int decile) { + return getInterpolatedValueAtIndex(population, getDecileRank(population.length, decile)); + } + + public static double getSortedPopulationDecile(long[] population, int decile) { + return getInterpolatedValueAtIndex(population, getDecileRank(population.length, decile)); + } + + public static double getDecileRank(long size, int decile) { + if (decile < 1 || decile > 9) { + throw new RuntimeException("Invalid decile: " + decile); + } + if (size < 10) { + throw new RuntimeException("Population is too small to compute deciles. Size: " + size); + } + return ((size / 10.0) * decile) - 1; + } + + public static double getInterpolatedValueAtIndex(double[] population, double rank) { + double rankFloored = Math.floor(rank); + double remainder = rank - rankFloored; + + // Return interpolated value at index + return population[(int) rankFloored] + (remainder * (population[(int) rankFloored + 1] - population[(int) rankFloored])); + } + + public static double getInterpolatedValueAtIndex(long[] population, double rank) { + double rankFloored = Math.floor(rank); + double remainder = rank - rankFloored; + + // Return interpolated value at index + return population[(int) rankFloored] + (remainder * (population[(int) rankFloored + 1] - population[(int) rankFloored])); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `other.getMaximum()` could be null and is dereferenced at line 99. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DoublePopulationStatisticsAggregator.aggregate(DoublePopulationStatisticsAggregator) + +### Procedure Id: +com.rapleaf.hank.partition_server.DoublePopulationStatisticsAggregator.aggregate(com.rapleaf.hank.pa.a5278a249dcc942610ca2ff7ca81ad54 + +### File: +src/java/com/rapleaf/hank/partition_server/DoublePopulationStatisticsAggregator.java + +### Key: +DoublePopulationStatisticsAggregator.java|aggregate|NULL_DEREFERENCE + +### Node Key: +4e40cf4b057cfc6102ca2104f1fe79e1 + +### Hash: +9f3ce91f3fbec8f088980df5da63012a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3182/instruction.md b/inferredbugs-3182/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8c2fbd6243b323a263eebe1181b12b9d77fd42b0 --- /dev/null +++ b/inferredbugs-3182/instruction.md @@ -0,0 +1,358 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** hank +**Bug ID:** 17 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright 2011 Rapleaf + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rapleaf.hank.coordinator.zk; + +import com.rapleaf.hank.coordinator.*; +import com.rapleaf.hank.zookeeper.WatchedInt; +import com.rapleaf.hank.zookeeper.WatchedMap; +import com.rapleaf.hank.zookeeper.WatchedMap.ElementLoader; +import com.rapleaf.hank.zookeeper.ZkPath; +import com.rapleaf.hank.zookeeper.ZooKeeperPlus; +import org.apache.log4j.Logger; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.data.Stat; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class ZkRingGroup extends AbstractRingGroup { + private static final String UPDATING_TO_VERSION_PATH_SEGMENT = "updating_to_version"; + private static final String CURRENT_VERSION_PATH_SEGMENT = "current_version"; + protected static final String RING_GROUP_CONDUCTOR_ONLINE_PATH_SEGMENT = "ring_group_conductor_online"; + private static final Logger LOG = Logger.getLogger(ZkRingGroup.class); + + private final String ringGroupName; + private DomainGroup domainGroup; + private final Map ringsByNumber; + private final String ringGroupPath; + private final String currentVerPath; + private final String updatingToVersionPath; + private final String ringGroupConductorOnlinePath; + private final ZooKeeperPlus zk; + private final Coordinator coordinator; + + private final WatchedInt currentVersion; + private final WatchedInt updatingToVersion; + + public static ZkRingGroup create(ZooKeeperPlus zk, String path, ZkDomainGroup domainGroup, Coordinator coordinator) throws KeeperException, InterruptedException, IOException { + if (domainGroup.getVersions().isEmpty()) { + throw new IllegalStateException( + "You cannot create a ring group for a domain group that has no versions!"); + } + zk.create(path, domainGroup.getName().getBytes()); + zk.create(ZkPath.append(path, CURRENT_VERSION_PATH_SEGMENT), null); + zk.create(ZkPath.append(path, UPDATING_TO_VERSION_PATH_SEGMENT), + (Integer.toString(domainGroup.getLatestVersion().getVersionNumber())).getBytes()); + return new ZkRingGroup(zk, path, domainGroup, coordinator); + } + + public ZkRingGroup(ZooKeeperPlus zk, String ringGroupPath, DomainGroup domainGroup, final Coordinator coordinator) + throws InterruptedException, KeeperException { + this.zk = zk; + this.ringGroupPath = ringGroupPath; + this.domainGroup = domainGroup; + this.coordinator = coordinator; + + if (coordinator == null) { + throw new IllegalArgumentException("Cannot initialize a ZkRingGroup with a null Coordinator."); + } + + ringGroupName = ZkPath.getFilename(ringGroupPath); + ringsByNumber = new WatchedMap(zk, ringGroupPath, new ElementLoader() { + @Override + public ZkRing load(ZooKeeperPlus zk, String basePath, String relPath) throws KeeperException, InterruptedException { + if (relPath.matches("ring-\\d+")) { + return new ZkRing(zk, ZkPath.append(basePath, relPath), ZkRingGroup.this, coordinator); + } + return null; + } + }); + + currentVerPath = ZkPath.append(ringGroupPath, CURRENT_VERSION_PATH_SEGMENT); + updatingToVersionPath = ZkPath.append(ringGroupPath, UPDATING_TO_VERSION_PATH_SEGMENT); + ringGroupConductorOnlinePath = ZkPath.append(ringGroupPath, RING_GROUP_CONDUCTOR_ONLINE_PATH_SEGMENT); + + currentVersion = new WatchedInt(zk, currentVerPath, true, null); + updatingToVersion = new WatchedInt(zk, updatingToVersionPath, true, null); + } + + private final class StateChangeListener implements Watcher { + private final RingGroupChangeListener listener; + + public StateChangeListener(RingGroupChangeListener listener) + throws KeeperException, InterruptedException { + this.listener = listener; + reregister(); + } + + @Override + public void process(WatchedEvent event) { + switch (event.getType()) { + case NodeChildrenChanged: + // ring group was added OR currentversion was set for the first time + LOG.debug("NodeChildrenChanged fired"); + fireListener(); + break; + + case NodeDataChanged: + // one of the versions was updated + LOG.debug("NodeDataChanged fired"); + fireListener(); + break; + + case NodeDeleted: + // updatingToVersion was whacked + LOG.debug("NodeDeleted fired"); + fireListener(); + break; + + default: + LOG.debug("Unexpected event type " + event.getType()); + } + } + + private void fireListener() { + listener.onRingGroupChange(ZkRingGroup.this); + try { + reregister(); + } catch (Exception e) { + LOG.error("Unexpected error registering watch!", e); + } + } + + private void reregister() throws KeeperException, InterruptedException { + zk.getChildren(ringGroupPath, this); + if (zk.exists(currentVerPath, this) != null) { + zk.getData(currentVerPath, this, new Stat()); + } + if (zk.exists(updatingToVersionPath, this) != null) { + zk.getData(updatingToVersionPath, this, new Stat()); + } + } + } + + @Override + public DomainGroup getDomainGroup() { + return domainGroup; + } + + @Override + public String getName() { + return ringGroupName; + } + + @Override + public Ring getRing(int ringNumber) { + return ringsByNumber.get("ring-" + ringNumber); + } + + @Override + public Ring getRingForHost(PartitionServerAddress hostAddress) { + for (Ring ring : ringsByNumber.values()) { + if (ring.getHostByAddress(hostAddress) != null) { + return ring; + } + } + return null; + } + + @Override + public Set getRings() { + return new HashSet(ringsByNumber.values()); + } + + @Override + public boolean claimRingGroupConductor() throws IOException { + try { + if (zk.exists(ringGroupConductorOnlinePath, false) == null) { + zk.create(ringGroupConductorOnlinePath, null, CreateMode.EPHEMERAL); + return true; + } + return false; + } catch (Exception e) { + throw new IOException(e); + } + } + + @Override + public void releaseRingGroupConductor() throws IOException { + try { + if (zk.exists(ringGroupConductorOnlinePath, false) != null) { + zk.delete(ringGroupConductorOnlinePath, -1); + return; + } + throw new IllegalStateException( + "Can't release the ring group conductor lock when it's not currently set!"); + } catch (Exception e) { + throw new IOException(e); + } + } + + @Override + public Integer getCurrentVersion() throws IOException { + try { + return currentVersion.get(); + } catch (Exception e) { + throw new IOException(e); + } + } + + @Override + public void setUpdatingToVersion(Integer versionNumber) throws IOException { + try { + updatingToVersion.set(versionNumber); + } catch (Exception e) { + throw new IOException(e); + } + } + + @Override + public void updateComplete() throws IOException { + try { + currentVersion.set(getUpdatingToVersion()); + } catch (Exception e) { + throw new IOException(e); + } + setUpdatingToVersion(null); + } + + @Override + public void setListener(RingGroupChangeListener listener) throws IOException { + try { + new StateChangeListener(listener); + } catch (Exception e) { + throw new IOException(e); + } + } + + @Override + public Integer getUpdatingToVersion() throws IOException { + try { + return updatingToVersion.get(); + } catch (Exception e) { + throw new IOException(e); + } + } + + @Override + public Ring addRing(int ringNum) throws IOException { + try { + ZkRing rc = ZkRing.create(zk, coordinator, ringGroupPath, ringNum, this, + isUpdating() ? getUpdatingToVersion() : getCurrentVersion()); + ringsByNumber.put("ring-" + Integer.toString(rc.getRingNumber()), rc); + return rc; + } catch (Exception e) { + throw new IOException(e); + } + } + + @Override + public boolean isRingGroupConductorOnline() throws IOException { + try { + return zk.exists(ringGroupConductorOnlinePath, false) != null; + } catch (Exception e) { + throw new IOException(e); + } + } + + public boolean delete() throws IOException { + try { + zk.deleteNodeRecursively(ringGroupPath); + return true; + } catch (Exception e) { + throw new IOException(e); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `domainGroup.getLatestVersion()` could be null and is dereferenced at line 63. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +ZkRingGroup ZkRingGroup.create(ZooKeeperPlus,String,ZkDomainGroup,ZooKeeperCoordinator) + +### Procedure Id: +com.rapleaf.hank.coordinator.zk.ZkRingGroup.create(com.rapleaf.hank.zookeeper.ZooKeeperPlus,java.lan.4ee6a9b61a39e16df0f0343cb0970a4d + +### File: +src/java/com/rapleaf/hank/coordinator/zk/ZkRingGroup.java + +### Key: +ZkRingGroup.java|create|NULL_DEREFERENCE + +### Node Key: +98e48d8af36063b905de6168fc1ae17c + +### Hash: +8906d3ad99aecc19281e8f1c13650ce3 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3183/instruction.md b/inferredbugs-3183/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..680c557b6c86e2aa569ae45051f4d0b80b727540 --- /dev/null +++ b/inferredbugs-3183/instruction.md @@ -0,0 +1,292 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** hank +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.rapleaf.hank.update_daemon; +/** + * Copyright 2011 Rapleaf + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.net.UnknownHostException; +import java.util.Queue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; + +import com.rapleaf.hank.config.DomainConfig; +import com.rapleaf.hank.config.DomainConfigVersion; +import com.rapleaf.hank.config.DomainGroupConfig; +import com.rapleaf.hank.config.PartDaemonAddress; +import com.rapleaf.hank.config.RingConfig; +import com.rapleaf.hank.config.RingGroupConfig; +import com.rapleaf.hank.config.UpdateDaemonConfigurator; +import com.rapleaf.hank.coordinator.Coordinator; +import com.rapleaf.hank.coordinator.DaemonState; +import com.rapleaf.hank.coordinator.DaemonType; +import com.rapleaf.hank.coordinator.Coordinator.DaemonStateChangeListener; +import com.rapleaf.hank.exception.DataNotFoundException; +import com.rapleaf.hank.storage.StorageEngine; +import com.rapleaf.hank.util.HostUtils; + +public class UpdateDaemon implements DaemonStateChangeListener { + private static final Logger LOG = Logger.getLogger(UpdateDaemon.class); + + private static final String HOST_NAME; + static { + try { + HOST_NAME = HostUtils.getHostName(); + } catch (UnknownHostException e) { + throw new RuntimeException(e); + } + } + + private final class UpdateToDo implements Runnable { + private final StorageEngine engine; + private final int partNum; + private final Queue exceptionQueue; + + public UpdateToDo(StorageEngine engine, int partNum, Queue exceptionQueue) { + this.engine = engine; + this.partNum = partNum; + this.exceptionQueue = exceptionQueue; + } + + @Override + public void run() { + try { + LOG.debug(String.format("UpdateToDo %s part %d starting...", engine.toString(), partNum)); + engine.getUpdater(configurator, partNum).update(); + LOG.debug(String.format("UpdateToDo %s part %d completed.", engine.toString(), partNum)); + } catch (Throwable e) { + // TODO: i just *know* that i'm going to end up wishing i toStringed the + // storage engine and part num here + LOG.fatal("Failed to complete an UpdateToDo!", e); + exceptionQueue.add(e); + } + } + } + + private final UpdateDaemonConfigurator configurator; + private final Coordinator coord; + private boolean goingDown; + + private final int ringNumber; + + private final String ringGroupName; + + private final PartDaemonAddress hostAddress; + + public UpdateDaemon(UpdateDaemonConfigurator configurator, String hostName) throws UnknownHostException { + this.configurator = configurator; + this.coord = configurator.getCoordinator(); + this.ringGroupName = configurator.getRingGroupName(); + this.ringNumber = configurator.getRingNumber(); + hostAddress = new PartDaemonAddress(hostName, configurator.getServicePort()); + coord.addDaemonStateChangeListener(ringGroupName, ringNumber, hostAddress, DaemonType.UPDATE_DAEMON, this); + } + + void run() throws UnknownHostException { + goingDown = false; + + // prime things the process by querying the current state and feeding it to + // the event handler + DaemonState state = coord.getDaemonState(ringGroupName, ringNumber, hostAddress, DaemonType.UPDATE_DAEMON); + onDaemonStateChange(ringGroupName, ringNumber, hostAddress, DaemonType.UPDATE_DAEMON, state); + + while (!goingDown) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + LOG.debug("Interrupted while waiting for watching thread to go to wake up!", e); + break; + } + } + } + + @Override + public void onDaemonStateChange(String ringGroupName, int ringNumber, PartDaemonAddress hostAddress, DaemonType type, DaemonState newState) { + // we only pay attention to state changes for *this* daemon, so don't need + // to be concerned with the identification stuff + switch (newState) { + case UPDATING: + // we must have crashed while updating in a prior iteration. just pick + // up where we left off. + case UPDATEABLE: + setUpdating(); + try { + update(); + setIdle(); + } catch (DataNotFoundException e) { + LOG.fatal("Caught an unexpected exception during update process!", e); + goingDown = true; + } + break; + + default: + // we don't care about other state changes, because they're not relevant + // to us. but let's log them anyways for the sake of completeness + LOG.info("Notified of uninteresting state change: " + newState + ". Ignoring."); + } + } + + private void update() throws DataNotFoundException { + ThreadFactory factory = new ThreadFactory() { + private int x = 0; + + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "Updater Thread Pool Thread #" + ++x); + } + }; + + ExecutorService executor = new ThreadPoolExecutor( + configurator.getNumConcurrentUpdates(), + configurator.getNumConcurrentUpdates(), + 1, TimeUnit.DAYS, + new LinkedBlockingQueue(), + factory); + Queue exceptionQueue = new LinkedBlockingQueue(); + + RingGroupConfig ringGroupConfig = coord.getRingGroupConfig(configurator.getRingGroupName()); + RingConfig ringConfig = ringGroupConfig.getRingConfigForHost(hostAddress); + + DomainGroupConfig domainGroupConfig = ringGroupConfig.getDomainGroupConfig(); + for (DomainConfigVersion dcv : domainGroupConfig.getLatestVersion().getDomainConfigVersions()) { + DomainConfig domainConfig = dcv.getDomainConfig(); + StorageEngine engine = domainConfig.getStorageEngine(); + + int domainId = domainGroupConfig.getDomainId(domainConfig.getName()); + for (Integer part : ringConfig.getDomainPartitionsForHost(hostAddress, domainId)) { + LOG.debug(String.format("Configuring update task for group-%s/ring-%d/domain-%s/part-%d", ringGroupConfig.getName(), ringConfig.getRingNumber(), domainConfig.getName(), part)); + executor.execute(new UpdateToDo(engine, part, exceptionQueue)); + } + } + + try { + boolean terminated = false; + executor.shutdown(); + while (!terminated) { + LOG.debug("Waiting for update executor to complete..."); + terminated = executor.awaitTermination(100, TimeUnit.MILLISECONDS); + // TODO: report on progress? + // TODO: check exception queue + } + } catch (InterruptedException e) { + // TODO: log and quit + } + } + + private void setIdle() { + setState(DaemonState.IDLE); + } + + private void setUpdating() { + setState(DaemonState.UPDATING); + } + + private void setState(DaemonState state) { + coord.setDaemonState(ringGroupName, ringNumber, hostAddress, DaemonType.UPDATE_DAEMON, state); + } + + /** + * Main method. + * @param args + * @throws IOException + */ + public static void main(String[] args) throws IOException { + String configPath = args[0]; + String log4jprops = args[1]; + + PropertyConfigurator.configure(log4jprops); + + new UpdateDaemon(null, HostUtils.getHostName()).run(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `UpdateDaemon(...)` at line 216. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void UpdateDaemon.main(java.lang.String[]) + +### Procedure Id: +com.rapleaf.hank.update_daemon.UpdateDaemon.main(java.lang.String[]):void.0d5f78289cd15780a0d5a5744d86821c + +### File: +src/java/com/rapleaf/hank/update_daemon/UpdateDaemon.java + +### Key: +UpdateDaemon.java|main|NULL_DEREFERENCE + +### Node Key: +3c7d22e48063b90f665efd8de7d66306 + +### Hash: +04a9ba03f1b533be37d06dd28309b85d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3209/instruction.md b/inferredbugs-3209/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9f86124e8f134025e6597a0a6aa67d278f83bdd8 --- /dev/null +++ b/inferredbugs-3209/instruction.md @@ -0,0 +1,255 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** hank +**Bug ID:** 12 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright 2011 Rapleaf + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rapleaf.hank.data_deployer; + +import java.io.IOException; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; + +import com.rapleaf.hank.config.DataDeployerConfigurator; +import com.rapleaf.hank.config.yaml.YamlDataDeployerConfigurator; +import com.rapleaf.hank.coordinator.Coordinator; +import com.rapleaf.hank.coordinator.DomainGroup; +import com.rapleaf.hank.coordinator.DomainGroupChangeListener; +import com.rapleaf.hank.coordinator.Host; +import com.rapleaf.hank.coordinator.HostDomain; +import com.rapleaf.hank.coordinator.HostDomainPartition; +import com.rapleaf.hank.coordinator.Ring; +import com.rapleaf.hank.coordinator.RingGroup; +import com.rapleaf.hank.coordinator.RingGroupChangeListener; +import com.rapleaf.hank.util.CommandLineChecker; + +public class DataDeployer implements RingGroupChangeListener, DomainGroupChangeListener { + private static final Logger LOG = Logger.getLogger(DataDeployer.class); + + private final DataDeployerConfigurator config; + private final String ringGroupName; + private final Coordinator coord; + private final Object lock = new Object(); + + private RingGroup ringGroupConfig; + private DomainGroup domainGroup; + + private final RingGroupUpdateTransitionFunction transFunc; + + private boolean goingDown = false; + + public DataDeployer(DataDeployerConfigurator config) { + this(config, new RingGroupUpdateTransitionFunctionImpl()); + } + + DataDeployer(DataDeployerConfigurator config, RingGroupUpdateTransitionFunction transFunc) { + this.config = config; + this.transFunc = transFunc; + ringGroupName = config.getRingGroupName(); + coord = config.getCoordinator(); + } + + public void run() throws IOException { + LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " starting."); + boolean claimedDataDeployer = false; + try { + ringGroupConfig = coord.getRingGroup(ringGroupName); + + // attempt to claim the data deployer title + if (ringGroupConfig.claimDataDeployer()) { + claimedDataDeployer = true; + + // we are now *the* data deployer for this ring group. + domainGroup = ringGroupConfig.getDomainGroup(); + + // set a watch on the ring group + ringGroupConfig.setListener(this); + + // set a watch on the domain group version + domainGroup.setListener(this); + + // loop until we're taken down + goingDown = false; + try { + while (!goingDown) { + // take a snapshot of the current ring/domain group configs, since + // they might get changed while we're processing the current update. + RingGroup snapshotRingGroupConfig; + DomainGroup snapshotDomainGroup; + synchronized (lock) { + snapshotRingGroupConfig = ringGroupConfig; + snapshotDomainGroup = domainGroup; + } + + processUpdates(snapshotRingGroupConfig, snapshotDomainGroup); + Thread.sleep(config.getSleepInterval()); + } + } catch (InterruptedException e) { + // daemon is going down. + } + } else { + LOG.info("Attempted to claim data deployer status, but there was already a lock in place!"); + } + } catch (Throwable t) { + LOG.fatal("unexpected exception!", t); + } finally { + if (claimedDataDeployer) { + ringGroupConfig.releaseDataDeployer(); + } + } + LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " shutting down."); + } + + void processUpdates(RingGroup ringGroup, DomainGroup domainGroup) throws IOException { + if (ringGroup.isUpdating()) { + LOG.info("Ring group " + ringGroupName + + " is currently updating from version " + + ringGroup.getCurrentVersion() + " to version " + + ringGroup.getUpdatingToVersion() + "."); + // There's already an update in progress. Let's just move that one along as necessary. + transFunc.manageTransitions(ringGroup); + } else { + int latestVersionNumber = domainGroup.getLatestVersion().getVersionNumber(); + if (ringGroup.getCurrentVersion() < latestVersionNumber) { + // We can start a new update of this ring group. + + // set the ring group's updating version to the new domain group version + // this will mark all the subordinate rings and hosts for update as well. + LOG.info("Ring group " + ringGroupName + " is in need of an update. Starting the update now..."); + for (Ring ringConfig : ringGroup.getRings()) { + for (Host hostConfig : ringConfig.getHosts()) { + for (HostDomain hdc : hostConfig.getAssignedDomains()) { + for (HostDomainPartition hdpc : hdc.getPartitions()) { + hdpc.setUpdatingToDomainGroupVersion(latestVersionNumber); + } + } + } + ringConfig.setUpdatingToVersion(latestVersionNumber); + } + ringGroup.setUpdatingToVersion(latestVersionNumber); + } else { + LOG.info("No updates in process and no updates pending."); + } + } + } + + + @Override + public void onRingGroupChange(RingGroup newRingGroup) { + synchronized(lock) { + LOG.debug("Got an updated ring group config version!"); + ringGroupConfig = newRingGroup; + } + } + + @Override + public void onDomainGroupChange(DomainGroup newDomainGroup) { + synchronized (lock) { + LOG.debug("Got an updated domain group config version: " + newDomainGroup + "!" ); + domainGroup = newDomainGroup; + } + } + + /** + * @param args + * @throws Exception + */ + public static void main(String[] args) throws Exception { + CommandLineChecker.check(args, new String[]{"configuration_file_path", "log4j_properties_file_path"}, DataDeployer.class); + String configPath = args[0]; + String log4jprops = args[1]; + + DataDeployerConfigurator configurator = new YamlDataDeployerConfigurator(configPath); + PropertyConfigurator.configure(log4jprops); + new DataDeployer(configurator).run(); + } + + public void stop() { + goingDown = true; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.rapleaf.hank.data_deployer.DataDeployer.run` reads with synchronization from `this.com.rapleaf.hank.data_deployer.DataDeployer.ringGroupConfig`. Potentially races with unsynchronized write in method `DataDeployer.run()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DataDeployer.run() + +### Procedure Id: +com.rapleaf.hank.data_deployer.DataDeployer.run():void.5f61500e1474da1e9e0a8a7280ac2c3e + +### File: +src/java/com/rapleaf/hank/data_deployer/DataDeployer.java + +### Key: +DataDeployer.java|run|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +b06555484d1066fa5dbcc776f9cb95b1 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3231/instruction.md b/inferredbugs-3231/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..322ea1c6ad420802d53a0c8772dd41d86c564a77 --- /dev/null +++ b/inferredbugs-3231/instruction.md @@ -0,0 +1,280 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jmxtrans-agent +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2010-2013 the original author or authors + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.jmxtrans.agent; + +import java.io.*; +import java.nio.channels.FileChannel; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static org.jmxtrans.agent.util.ConfigurationUtils.getString; + +/** + * @author Cyrille Le Clerc + */ +public class FileOverwriterOutputWriter extends AbstractOutputWriter { + + public final static String SETTING_FILE_NAME = "fileName"; + public final static String SETTING_FILE_NAME_DEFAULT_VALUE = "jmxtrans-agent.data"; + private final Logger logger = Logger.getLogger(getClass().getName()); + protected Writer temporaryFileWriter; + protected File temporaryFile; + protected File file = new File(SETTING_FILE_NAME_DEFAULT_VALUE); + + @Override + public synchronized void postConstruct(Map settings) { + super.postConstruct(settings); + file = new File(getString(settings, SETTING_FILE_NAME, SETTING_FILE_NAME_DEFAULT_VALUE)); + logger.info("FileOverwriterOutputWriter configured with file " + file.getAbsolutePath()); + } + + protected Writer getTemporaryFileWriter() throws IOException { + if (temporaryFile == null) { + temporaryFile = File.createTempFile("jmxtrans-agent-", ".data"); + temporaryFile.deleteOnExit(); + if (logger.isLoggable(Level.FINE)) + logger.fine("Created temporary file " + temporaryFile.getAbsolutePath()); + + temporaryFileWriter = null; + } + if (temporaryFileWriter == null) { + temporaryFileWriter = new BufferedWriter(new FileWriter(temporaryFile, false)); + } + + return temporaryFileWriter; + } + + @Override + public synchronized void writeQueryResult(String metricName, Object value) throws IOException { + writeResult(metricName, value); + } + + @Override + public void writeInvocationResult(String invocationName, Object value) throws IOException { + writeResult(invocationName, value); + } + + protected void writeResult(String name, Object value) throws IOException { + try { + getTemporaryFileWriter().write(name + " " + value + "\n"); + } catch (IOException e) { + releaseTemporaryWriter(); + throw e; + } + } + + protected void releaseTemporaryWriter() { + try { + IoUtils.closeQuietly(getTemporaryFileWriter()); + } catch (IOException e) { + // silently skip + } + if (temporaryFile != null) { + temporaryFile.delete(); + } + temporaryFile = null; + + } + + @Override + public synchronized void postCollect() throws IOException { + try { + getTemporaryFileWriter().close(); + if (logger.isLoggable(Level.FINE)) + logger.fine("Overwrite " + file.getAbsolutePath() + " by " + temporaryFile.getAbsolutePath()); + IoUtils.replaceFile(temporaryFile, file); + } finally { + temporaryFileWriter = null; + } + } + + public static class IoUtils { + + /** + * Simple implementation without chunking if the source file is big. + * + * @param source + * @param destination + * @throws java.io.IOException + */ + private static void doCopySmallFile(File source, File destination) throws IOException { + if (destination.exists() && destination.isDirectory()) { + throw new IOException("Can not copy file, destination is a directory: " + destination.getAbsolutePath()); + } + + FileInputStream fis = null; + FileOutputStream fos = null; + FileChannel input = null; + FileChannel output = null; + try { + fis = new FileInputStream(source); + fos = new FileOutputStream(destination, false); + input = fis.getChannel(); + output = fos.getChannel(); + output.transferFrom(input, 0, input.size()); + } finally { + closeQuietly(output); + closeQuietly(input); + closeQuietly(fis); + closeQuietly(fos); + } + if (destination.length() != source.length()) { + throw new IOException("Failed to copy content from '" + + source + "' (" + source.length() + "bytes) to '" + destination + "' (" + destination.length() + ")"); + } + + } + + public static void closeQuietly(Closeable closeable) { + if (closeable == null) + return; + try { + closeable.close(); + } catch (Exception e) { + // ignore silently + } + } + + public static void closeQuietly(Writer writer) { + if (writer == null) + return; + try { + writer.close(); + } catch (Exception e) { + // ignore silently + } + } + + /** + * Needed for old JVMs where {@link java.io.InputStream} does not implement {@link java.io.Closeable}. + */ + public static void closeQuietly(InputStream inputStream) { + if (inputStream == null) + return; + try { + inputStream.close(); + } catch (Exception e) { + // ignore silently + } + } + + private static void replaceFile(File source, File destination) throws IOException { + boolean destinationExists; + if (destination.exists()) { + boolean deleted = destination.delete(); + if (deleted) { + destinationExists = false; + } else { + destinationExists = true; + } + } else { + destinationExists = false; + } + if (destinationExists) { + doCopySmallFile(source, destination); + } else { + boolean renamed = source.renameTo(destination); + if (!renamed) { + doCopySmallFile(source, destination); + } + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.jmxtrans.agent.FileOverwriterOutputWriter.releaseTemporaryWriter` reads without synchronization from `this.org.jmxtrans.agent.FileOverwriterOutputWriter.temporaryFile`. Potentially races with write in method `FileOverwriterOutputWriter.writeQueryResult(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void FileOverwriterOutputWriter.releaseTemporaryWriter() + +### Procedure Id: +org.jmxtrans.agent.FileOverwriterOutputWriter.releaseTemporaryWriter():void.f44c26c69bedc0f2eebd200547efb994 + +### File: +src/main/java/org/jmxtrans/agent/FileOverwriterOutputWriter.java + +### Key: +FileOverwriterOutputWriter.java|releaseTemporaryWriter|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +c3df944aab1d15417c69435b56d820d9 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3236/instruction.md b/inferredbugs-3236/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cab45608d5f959e290ec64b2e8da87f619fddc4f --- /dev/null +++ b/inferredbugs-3236/instruction.md @@ -0,0 +1,112 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** FastDFS_Client +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.tobato.soket.server; + +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; + +public class SoketServer { + private int port = 22122; + private ServerSocket serverSocket; + + public void service() { + int i = 0; + try { + serverSocket = new ServerSocket(port); + } catch (IOException e1) { + e1.printStackTrace(); + } + + while (true) { + Socket socket = null; + try { + i++; + socket = serverSocket.accept(); // 主线程获取客户端连接 + System.out.println("第" + i + "个客户端成功连接!"); + Thread workThread = new Thread(new Handler(socket)); // 创建线程 + workThread.start(); // 启动线程 + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + public static void main(String[] agrs) { + SoketServer server = new SoketServer(); + System.out.println("------服务启动--------"); + server.service(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.net.Socket` acquired by call to `accept()` at line 23 is not released after line 25. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SoketServer.service() + +### Procedure Id: +com.github.tobato.soket.server.SoketServer.service():void.342c1bea71f7816f64a6e9f17fa881f3 + +### File: +src/test/java/com/github/tobato/soket/server/SoketServer.java + +### Key: +SoketServer.java|service|RESOURCE_LEAK + +### Node Key: +2fbf5d3b704883b75cc1cd09cffebc55 + +### Hash: +baddade0e6106b8550cb1db421573e18 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3310/instruction.md b/inferredbugs-3310/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aee0219d3e65ba3a58b564df56ff87dde431a8fe --- /dev/null +++ b/inferredbugs-3310/instruction.md @@ -0,0 +1,422 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** azure-maven-plugins +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.auth; + +import com.microsoft.azure.AzureEnvironment; +import com.microsoft.azure.auth.configuration.AuthConfiguration; +import com.microsoft.azure.credentials.ApplicationTokenCredentials; +import com.microsoft.azure.credentials.AzureCliCredentials; +import com.microsoft.azure.credentials.AzureTokenCredentials; +import com.microsoft.azure.credentials.MSICredentials; +import org.apache.commons.io.FileUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.concurrent.ExecutionException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.eq; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.when; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({AzureLoginHelper.class}) +public class AzureAuthHelperTest { + private File tempDirectory; + + @Before + public void setup() throws IOException { + tempDirectory = Files.createTempDirectory("azure-auth-helper-test").toFile(); + // avoid write test data to the actual file: azure-secret.json + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, tempDirectory.getAbsolutePath()); + } + + @After + public void afterEachTestMethod() throws IOException { + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, null); + FileUtils.deleteDirectory(tempDirectory); + } + + @Test + public void testOAuthLogin() throws Exception { + final AzureEnvironment env = AzureEnvironment.AZURE; + final AzureCredential credExpected = AzureCredential.fromAuthenticationResult(TestHelper.createAuthenticationResult()); + mockStatic(AzureLoginHelper.class); + when(AzureLoginHelper.oAuthLogin(env)).thenReturn(credExpected); + + final AzureCredential cred = AzureAuthHelper.oAuthLogin(env); + assertEquals(credExpected, cred); + } + + @Test + public void testDeviceLogin() throws Exception { + final AzureEnvironment env = AzureEnvironment.AZURE; + final AzureCredential credExpected = AzureCredential.fromAuthenticationResult(TestHelper.createAuthenticationResult()); + mockStatic(AzureLoginHelper.class); + when(AzureLoginHelper.deviceLogin(env)).thenReturn(credExpected); + + final AzureCredential cred = AzureAuthHelper.deviceLogin(env); + assertEquals(credExpected, cred); + } + + @Test + public void testRefreshToken() throws Exception { + final AzureEnvironment env = AzureEnvironment.AZURE; + final AzureCredential credExpected = AzureCredential.fromAuthenticationResult(TestHelper.createAuthenticationResult()); + mockStatic(AzureLoginHelper.class); + when(AzureLoginHelper.refreshToken(env, "token for power mock")).thenReturn(credExpected); + + final AzureCredential cred = AzureAuthHelper.refreshToken(env, "token for power mock"); + assertEquals(credExpected, cred); + } + + @Test + public void testRefreshTokenInvalidToken() throws Exception { + try { + AzureAuthHelper.refreshToken(AzureEnvironment.AZURE, "invalid"); + fail("Should throw AzureLoginFailureException when refreshToken is invalid."); + } catch (ExecutionException e) { + // ignore + } + } + + @Test + public void testRefreshTokenInvalidParameter() throws Exception { + try { + AzureAuthHelper.refreshToken(null, "abc"); + fail("Should throw IAE when env is null."); + } catch (IllegalArgumentException e) { + // ignore + } + + try { + AzureAuthHelper.refreshToken(AzureEnvironment.AZURE_CHINA, ""); + fail("Should throw IAE when refreshToken is empty."); + } catch (IllegalArgumentException e) { + // ignore + } + } + + @Test + public void testGetAzureEnvironment() { + assertEquals(AzureEnvironment.AZURE, AzureAuthHelper.getAzureEnvironment(null)); + assertEquals(AzureEnvironment.AZURE, AzureAuthHelper.getAzureEnvironment(" ")); + assertEquals(AzureEnvironment.AZURE, AzureAuthHelper.getAzureEnvironment("azure")); + assertEquals(AzureEnvironment.AZURE, AzureAuthHelper.getAzureEnvironment("aZUre")); + + assertEquals(AzureEnvironment.AZURE, AzureAuthHelper.getAzureEnvironment("AZURE_CLOUD")); + + assertEquals(AzureEnvironment.AZURE_GERMANY, AzureAuthHelper.getAzureEnvironment("AZURE_GERMANY")); + assertEquals(AzureEnvironment.AZURE_GERMANY, AzureAuthHelper.getAzureEnvironment("AzureGermanCloud")); + assertEquals(AzureEnvironment.AZURE_GERMANY, AzureAuthHelper.getAzureEnvironment("AZUREGERMANCLOUD")); + + assertEquals(AzureEnvironment.AZURE_US_GOVERNMENT, AzureAuthHelper.getAzureEnvironment("AZURE_US_GOVERNMENT")); + assertEquals(AzureEnvironment.AZURE_US_GOVERNMENT, AzureAuthHelper.getAzureEnvironment("AZUREUSGOVERNMENT")); + + assertEquals(AzureEnvironment.AZURE_CHINA, AzureAuthHelper.getAzureEnvironment("AzureChinaCloud")); + assertEquals(AzureEnvironment.AZURE_CHINA, AzureAuthHelper.getAzureEnvironment("Azure_China")); + + assertEquals(AzureEnvironment.AZURE, AzureAuthHelper.getAzureEnvironment("AzureChinaCloud ")); + } + + @Test + public void testEnvironmentValidation() { + assertTrue(AzureAuthHelper.validateEnvironment(null)); + assertTrue(AzureAuthHelper.validateEnvironment("")); + assertTrue(AzureAuthHelper.validateEnvironment(" ")); + assertTrue(AzureAuthHelper.validateEnvironment("azure")); + assertFalse(AzureAuthHelper.validateEnvironment("azure ")); + assertTrue(AzureAuthHelper.validateEnvironment("azure_cloud")); + assertTrue(AzureAuthHelper.validateEnvironment("AZURE_CLOUD")); + assertTrue(AzureAuthHelper.validateEnvironment("aZURe")); + assertFalse(AzureAuthHelper.validateEnvironment("aZURe ")); + assertFalse(AzureAuthHelper.validateEnvironment("foo")); + + } + + @Test + public void testGetAzureSecretFile() { + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, null); + final File azureSecretFile = AzureAuthHelper.getAzureSecretFile(); + assertEquals(Paths.get(System.getProperty("user.home"), ".azure", "azure-secret.json").toString(), azureSecretFile.getAbsolutePath()); + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, "test_dir"); + assertEquals(Paths.get("test_dir", "azure-secret.json").toFile().getAbsolutePath(), AzureAuthHelper.getAzureSecretFile().getAbsolutePath()); + } + + @Test + public void testGetAzureConfigFolder() { + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, null); + final File azureConfigFolder = AzureAuthHelper.getAzureConfigFolder(); + assertEquals(Paths.get(System.getProperty("user.home"), ".azure").toString(), azureConfigFolder.getAbsolutePath()); + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, "test_dir"); + assertEquals(Paths.get("test_dir").toFile().getAbsolutePath(), AzureAuthHelper.getAzureConfigFolder().getAbsolutePath()); + } + + @Test + public void testExistsAzureSecretFile() { + final File testConfigDir = new File(this.getClass().getResource("/azure-login/azure-secret.json").getFile()).getParentFile(); + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); + assertTrue(AzureAuthHelper.existsAzureSecretFile()); + + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getParentFile().getAbsolutePath()); + assertFalse(AzureAuthHelper.existsAzureSecretFile()); + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, ""); + } + + @Test + public void testReadAzureCredentials() throws Exception { + final File testConfigDir = new File(this.getClass().getResource("/azure-login/azure-secret.json").getFile()).getParentFile(); + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); + assertTrue(AzureAuthHelper.existsAzureSecretFile()); + assertNotNull(AzureAuthHelper.readAzureCredentials()); + + try { + AzureAuthHelper.readAzureCredentials(null); + fail("Should throw IAE"); + } catch (IllegalArgumentException ex) { + // expect + } + } + + @Test + public void testWriteAzureCredentials() throws Exception { + final File testConfigDir = new File(this.getClass().getResource("/azure-login/azure-secret.json").getFile()).getParentFile(); + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); + assertTrue(AzureAuthHelper.existsAzureSecretFile()); + final AzureCredential cred = AzureAuthHelper.readAzureCredentials(); + final File tempFile = new File(tempDirectory, "azure-secret.json"); + AzureAuthHelper.writeAzureCredentials(cred, tempFile); + final AzureCredential cred2 = AzureAuthHelper.readAzureCredentials(tempFile); + assertEquals(cred.getAccessToken(), cred2.getAccessToken()); + assertEquals(cred.getAccessTokenType(), cred2.getAccessTokenType()); + assertEquals(cred.getRefreshToken(), cred2.getRefreshToken()); + assertEquals(cred.getDefaultSubscription(), cred2.getDefaultSubscription()); + assertEquals(cred.getEnvironment(), cred2.getEnvironment()); + assertEquals(cred.getIdToken(), cred2.getIdToken()); + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, tempDirectory.getAbsolutePath()); + assertTrue(AzureAuthHelper.existsAzureSecretFile()); + AzureAuthHelper.deleteAzureSecretFile(); + assertFalse(AzureAuthHelper.existsAzureSecretFile()); + assertFalse(AzureAuthHelper.deleteAzureSecretFile()); + } + + @Test + public void testWriteAzureCredentialsBadParameter() throws Exception { + final File tempFile = File.createTempFile("azure-auth-helper-test", ".json"); + try { + AzureAuthHelper.writeAzureCredentials(null, tempFile); + fail("Should throw IAE here."); + } catch (IllegalArgumentException ex) { + // expected + } + + try { + AzureAuthHelper.writeAzureCredentials(AzureCredential.fromAuthenticationResult(TestHelper.createAuthenticationResult()), null); + fail("Should throw IAE here."); + } catch (IllegalArgumentException ex) { + // expected + } + } + + @Test + public void testIsInCloudShell() { + TestHelper.injectEnvironmentVariable(Constants.CLOUD_SHELL_ENV_KEY, "azure"); + assertTrue(AzureAuthHelper.isInCloudShell()); + TestHelper.injectEnvironmentVariable(Constants.CLOUD_SHELL_ENV_KEY, null); + assertFalse(AzureAuthHelper.isInCloudShell()); + } + + @Test + public void testGetAzureTokenCredentials() throws Exception { + // 1. use azure-secret.json + File testConfigDir = new File(this.getClass().getResource("/azure-login/azure-secret.json").getFile()).getParentFile(); + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); + AzureTokenCredentials cred = AzureAuthHelper.getAzureTokenCredentials(null); + assertNotNull(cred); + assertEquals("00000000-0000-0000-0000-000000000001", cred.defaultSubscriptionId()); + + // 2. use azure cli(non SP) + testConfigDir = new File(this.getClass().getResource("/azure-cli/default/azureProfile.json").getFile()).getParentFile(); + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); + cred = AzureAuthHelper.getAzureTokenCredentials(null); + assertNotNull(cred); + assertTrue(cred instanceof AzureCliCredentials); + final AzureCliCredentials cliCred = (AzureCliCredentials) cred; + assertEquals("00000000-0000-0000-0000-000000000001", cliCred.defaultSubscriptionId()); + assertEquals("00000000-0000-0000-0000-000000000002", cliCred.clientId()); + assertEquals("00000000-0000-0000-0000-000000000003", cliCred.domain()); + assertEquals(AzureEnvironment.AZURE_CHINA, cliCred.environment()); + + // 3. use azure cli(SP) + testConfigDir = new File(this.getClass().getResource("/azure-cli/sp/azureProfile.json").getFile()).getParentFile(); + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); + cred = AzureAuthHelper.getAzureTokenCredentials(null); + assertNotNull(cred); + assertTrue(cred instanceof AzureCliCredentials); + final AzureCliCredentials azureCliCredential = (AzureCliCredentials) cred; + assertEquals("00000000-0000-0000-0000-000000000001", cred.defaultSubscriptionId()); + assertEquals("00000000-0000-0000-0000-000000000002", azureCliCredential.clientId()); + assertEquals("00000000-0000-0000-0000-000000000003", cred.domain()); + assertEquals(AzureEnvironment.AZURE_CHINA, cliCred.environment()); + + // 4. use cloud shell + TestHelper.injectEnvironmentVariable(Constants.CLOUD_SHELL_ENV_KEY, "azure"); + assertTrue(AzureAuthHelper.isInCloudShell()); + TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, "non-exist-folder"); + cred = AzureAuthHelper.getAzureTokenCredentials(null); + assertNotNull(cred); + assertTrue(cred instanceof MSICredentials); + + // 5. all of the ways have been tried + TestHelper.injectEnvironmentVariable(Constants.CLOUD_SHELL_ENV_KEY, null); + assertNull(AzureAuthHelper.getAzureTokenCredentials(null)); + } + + @Test + public void testGetAzureTokenCredentialsFromConfiguration() throws Exception { + final AuthConfiguration auth = new AuthConfiguration(); + auth.setClient("client_id"); + auth.setTenant("tenant_id"); + auth.setKey("key"); + auth.setEnvironment("azure_germany"); + final AzureTokenCredentials cred = AzureAuthHelper.getAzureTokenCredentials(auth); + assertNotNull(cred); + assertTrue(cred instanceof ApplicationTokenCredentials); + assertNull(cred.defaultSubscriptionId()); + assertEquals(AzureEnvironment.AZURE_GERMANY, cred.environment()); + assertEquals("tenant_id", cred.domain()); + assertEquals("client_id", ((ApplicationTokenCredentials) cred).clientId()); + } + + @Test + public void testGetToken() throws Exception { + final AzureCredential credExpected = AzureCredential.fromAuthenticationResult(TestHelper.createAuthenticationResult()); + credExpected.setAccessToken("token refreshed"); + mockStatic(AzureLoginHelper.class); + + final AzureEnvironment env = AzureEnvironment.AZURE; + final AzureCredential cred = AzureCredential.fromAuthenticationResult(TestHelper.createAuthenticationResult()); + when(AzureLoginHelper.refreshToken(eq(env), eq("refresh token"))).thenReturn(credExpected); + cred.setRefreshToken("refresh token"); + // sample token from https://medium.com/@siddharthac6/json-web-token-jwt-the-right-way-of-implementing-with-node-js-65b8915d550e + final String expiredToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhMSI6IkRhdGEgMSIsImRhdGEyIjoiRGF0YSAyIiwiZGF0YTMiOiJEYXRhIDMiLCJkYXRhNCI6Ik" + + "RhdGEgNCIsImlhdCI6MTUyNTE5MzM3NywiZXhwIjoxNTI1MjM2NTc3LCJhdWQiOiJodHRwOi8vbXlzb2Z0Y29ycC5pbiIsImlzcyI6Ik15c29mdCBjb3JwIiwic3ViIjoic29tZUB1c2" + + "VyLmNvbSJ9.ID2fn6t0tcoXeTgkG2AivnG1skctbCAyY8M1ZF38kFvUJozRWSbdVc7FLwot-bwV8k1imV8o0fqdv5sVY0Yzmg"; + cred.setAccessToken(expiredToken); + assertEquals("token refreshed", AzureAuthHelper.getMavenAzureLoginCredentials(cred, env).getToken(env.resourceManagerEndpoint())); + + // token created by site: http://jwtbuilder.jamiekurtz.com/, + //{ + // "iss": "Online JWT Builder", + // "iat": 1566201321, + // "exp": 4090722921, + // "aud": "www.example.com", + // "sub": "jrocket@example.com", + // "GivenName": "Johnny", + // "Surname": "Rocket", + // "Email": "jrocket@example.com", + // "Role": [ + // "Manager", + // "Project Administrator" + // ] + //} + final String validToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE1NjYyMDEzMjEsImV4cCI6NDA5MDcyMjkyMSw" + + "iYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6IkpvaG5ueSIsIlN1cm5hbWUiOiJSb2NrZXQiLCJFbWFpbCI6Impyb2" + + "NrZXRAZXhhbXBsZS5jb20iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.m0yY1rRd9-zo9pUKWdkuuCSIj48K-X8IPr1-3gj-dGQ"; + cred.setAccessToken(validToken); + + assertEquals(validToken, AzureAuthHelper.getMavenAzureLoginCredentials(cred, env).getToken(env.resourceManagerEndpoint())); + + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `cred` last assigned on line 251 could be null and is dereferenced at line 253. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AzureAuthHelperTest.testGetAzureTokenCredentials() + +### Procedure Id: +com.microsoft.azure.auth.AzureAuthHelperTest.testGetAzureTokenCredentials():void.51e71b36d32eac5050381dc3adf918f2 + +### File: +azure-auth-helper/src/test/java/com/microsoft/azure/auth/AzureAuthHelperTest.java + +### Key: +AzureAuthHelperTest.java|testGetAzureTokenCredentials|NULL_DEREFERENCE + +### Node Key: +032299521a58ea574b18a1357a739565 + +### Hash: +1f83c926c3d2478f6e800a5f0da6cc8a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3319/instruction.md b/inferredbugs-3319/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5eb165e4ca667dc20621bf59a710313d39e84689 --- /dev/null +++ b/inferredbugs-3319/instruction.md @@ -0,0 +1,1312 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-codec +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.codec.binary; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.UnsupportedEncodingException; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Random; + +import org.apache.commons.codec.DecoderException; +import org.apache.commons.codec.EncoderException; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Test cases for Base64 class. + * + * @see RFC 2045 + * @version $Id$ + */ +public class Base64Test { + + private final Random _random = new Random(); + + /** + * @return Returns the _random. + */ + public Random getRandom() { + return this._random; + } + + /** + * Test the isStringBase64 method. + */ + @Test + public void testIsStringBase64() { + String nullString = null; + String emptyString = ""; + String validString = "abc===defg\n\r123456\r789\r\rABC\n\nDEF==GHI\r\nJKL=============="; + String invalidString = validString + (char)0; // append null character + + try { + Base64.isBase64(nullString); + fail("Base64.isStringBase64() should not be null-safe."); + } catch (NullPointerException npe) { + assertNotNull("Base64.isStringBase64() should not be null-safe.", npe); + } + + assertTrue("Base64.isStringBase64(empty-string) is true", Base64.isBase64(emptyString)); + assertTrue("Base64.isStringBase64(valid-string) is true", Base64.isBase64(validString)); + assertFalse("Base64.isStringBase64(invalid-string) is false", Base64.isBase64(invalidString)); + } + + /** + * Test the Base64 implementation + */ + @Test + public void testBase64() { + String content = "Hello World"; + String encodedContent; + byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content)); + encodedContent = StringUtils.newStringUtf8(encodedBytes); + assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); + + Base64 b64 = new Base64(BaseNCodec.MIME_CHUNK_SIZE, null); // null lineSeparator same as saying no-chunking + encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); + encodedContent = StringUtils.newStringUtf8(encodedBytes); + assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); + + b64 = new Base64(0, null); // null lineSeparator same as saying no-chunking + encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); + encodedContent = StringUtils.newStringUtf8(encodedBytes); + assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); + + // bogus characters to decode (to skip actually) {e-acute*6} + byte[] decode = b64.decode("SGVsbG{\u00e9\u00e9\u00e9\u00e9\u00e9\u00e9}8gV29ybGQ="); + String decodeString = StringUtils.newStringUtf8(decode); + assertEquals("decode hello world", "Hello World", decodeString); + } + + /** + * Tests Base64.encodeBase64(). + */ + @Test + public void testChunkedEncodeMultipleOf76() { + byte[] expectedEncode = Base64.encodeBase64(Base64TestData.DECODED, true); + // convert to "\r\n" so we're equal to the old openssl encoding test stored + // in Base64TestData.ENCODED_76_CHARS_PER_LINE: + String actualResult = Base64TestData.ENCODED_76_CHARS_PER_LINE.replaceAll("\n", "\r\n"); + byte[] actualEncode = StringUtils.getBytesUtf8(actualResult); + assertTrue("chunkedEncodeMultipleOf76", Arrays.equals(expectedEncode, actualEncode)); + } + + /** + * CODEC-68: isBase64 throws ArrayIndexOutOfBoundsException on some non-BASE64 bytes + */ + @Test + public void testCodec68() { + byte[] x = new byte[]{'n', 'A', '=', '=', (byte) 0x9c}; + Base64.decodeBase64(x); + } + + @Test + public void testCodeInteger1() throws UnsupportedEncodingException { + String encodedInt1 = "li7dzDacuo67Jg7mtqEm2TRuOMU="; + BigInteger bigInt1 = new BigInteger("85739377120809420210425962799" + "0318636601332086981"); + + assertEquals(encodedInt1, new String(Base64.encodeInteger(bigInt1))); + assertEquals(bigInt1, Base64.decodeInteger(encodedInt1.getBytes("UTF-8"))); + } + + @Test + public void testCodeInteger2() throws UnsupportedEncodingException { + String encodedInt2 = "9B5ypLY9pMOmtxCeTDHgwdNFeGs="; + BigInteger bigInt2 = new BigInteger("13936727572861167254666467268" + "91466679477132949611"); + + assertEquals(encodedInt2, new String(Base64.encodeInteger(bigInt2))); + assertEquals(bigInt2, Base64.decodeInteger(encodedInt2.getBytes("UTF-8"))); + } + + @Test + public void testCodeInteger3() throws UnsupportedEncodingException { + String encodedInt3 = "FKIhdgaG5LGKiEtF1vHy4f3y700zaD6QwDS3IrNVGzNp2" + "rY+1LFWTK6D44AyiC1n8uWz1itkYMZF0/aKDK0Yjg=="; + BigInteger bigInt3 = new BigInteger("10806548154093873461951748545" + + "1196989136416448805819079363524309897749044958112417136240557" + + "4495062430572478766856090958495998158114332651671116876320938126"); + + assertEquals(encodedInt3, new String(Base64.encodeInteger(bigInt3))); + assertEquals(bigInt3, Base64.decodeInteger(encodedInt3.getBytes("UTF-8"))); + } + + @Test + public void testCodeInteger4() throws UnsupportedEncodingException { + String encodedInt4 = "ctA8YGxrtngg/zKVvqEOefnwmViFztcnPBYPlJsvh6yKI" + + "4iDm68fnp4Mi3RrJ6bZAygFrUIQLxLjV+OJtgJAEto0xAs+Mehuq1DkSFEpP3o" + + "DzCTOsrOiS1DwQe4oIb7zVk/9l7aPtJMHW0LVlMdwZNFNNJoqMcT2ZfCPrfvYv" + + "Q0="; + BigInteger bigInt4 = new BigInteger("80624726256040348115552042320" + + "6968135001872753709424419772586693950232350200555646471175944" + + "519297087885987040810778908507262272892702303774422853675597" + + "748008534040890923814202286633163248086055216976551456088015" + + "338880713818192088877057717530169381044092839402438015097654" + + "53542091716518238707344493641683483917"); + + assertEquals(encodedInt4, new String(Base64.encodeInteger(bigInt4))); + assertEquals(bigInt4, Base64.decodeInteger(encodedInt4.getBytes("UTF-8"))); + } + + @Test + public void testCodeIntegerEdgeCases() { + // TODO + } + + @Test + public void testCodeIntegerNull() { + try { + Base64.encodeInteger(null); + fail("Exception not thrown when passing in null to encodeInteger(BigInteger)"); + } catch (NullPointerException npe) { + // expected + } catch (Exception e) { + fail("Incorrect Exception caught when passing in null to encodeInteger(BigInteger)"); + } + } + + @Test + public void testConstructors() { + Base64 base64; + base64 = new Base64(); + base64 = new Base64(-1); + base64 = new Base64(-1, new byte[]{}); + base64 = new Base64(64, new byte[]{}); + try { + base64 = new Base64(-1, new byte[]{'A'}); // TODO do we need to check sep if len = -1? + fail("Should have rejected attempt to use 'A' as a line separator"); + } catch (IllegalArgumentException ignored) { + // Expected + } + try { + base64 = new Base64(64, new byte[]{'A'}); + fail("Should have rejected attempt to use 'A' as a line separator"); + } catch (IllegalArgumentException ignored) { + // Expected + } + try { + base64 = new Base64(64, new byte[]{'='}); + fail("Should have rejected attempt to use '=' as a line separator"); + } catch (IllegalArgumentException ignored) { + // Expected + } + base64 = new Base64(64, new byte[]{'$'}); // OK + try { + base64 = new Base64(64, new byte[]{'A', '$'}); + fail("Should have rejected attempt to use 'A$' as a line separator"); + } catch (IllegalArgumentException ignored) { + // Expected + } + base64 = new Base64(64, new byte[]{' ', '$', '\n', '\r', '\t'}); // OK + assertNotNull(base64); + } + + @Test + public void testConstructor_Int_ByteArray_Boolean() { + Base64 base64 = new Base64(65, new byte[]{'\t'}, false); + byte[] encoded = base64.encode(Base64TestData.DECODED); + String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE; + expectedResult = expectedResult.replace('\n', '\t'); + String result = StringUtils.newStringUtf8(encoded); + assertEquals("new Base64(65, \\t, false)", expectedResult, result); + } + + @Test + public void testConstructor_Int_ByteArray_Boolean_UrlSafe() { + // url-safe variation + Base64 base64 = new Base64(64, new byte[]{'\t'}, true); + byte[] encoded = base64.encode(Base64TestData.DECODED); + String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE; + expectedResult = expectedResult.replaceAll("=", ""); // url-safe has no == padding. + expectedResult = expectedResult.replace('\n', '\t'); + expectedResult = expectedResult.replace('+', '-'); + expectedResult = expectedResult.replace('/', '_'); + String result = StringUtils.newStringUtf8(encoded); + assertEquals("new Base64(64, \\t, true)", result, expectedResult); + } + + /** + * Tests conditional true branch for "marker0" test. + */ + @Test + public void testDecodePadMarkerIndex2() throws UnsupportedEncodingException { + assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes("UTF-8")))); + } + + /** + * Tests conditional branches for "marker1" test. + */ + @Test + public void testDecodePadMarkerIndex3() throws UnsupportedEncodingException { + assertEquals("AA", new String(Base64.decodeBase64("QUE=".getBytes("UTF-8")))); + assertEquals("AAA", new String(Base64.decodeBase64("QUFB".getBytes("UTF-8")))); + } + + @Test + public void testDecodePadOnly() throws UnsupportedEncodingException { + assertEquals(0, Base64.decodeBase64("====".getBytes("UTF-8")).length); + assertEquals("", new String(Base64.decodeBase64("====".getBytes("UTF-8")))); + // Test truncated padding + assertEquals(0, Base64.decodeBase64("===".getBytes("UTF-8")).length); + assertEquals(0, Base64.decodeBase64("==".getBytes("UTF-8")).length); + assertEquals(0, Base64.decodeBase64("=".getBytes("UTF-8")).length); + assertEquals(0, Base64.decodeBase64("".getBytes("UTF-8")).length); + } + + @Test + public void testDecodePadOnlyChunked() throws UnsupportedEncodingException { + assertEquals(0, Base64.decodeBase64("====\n".getBytes("UTF-8")).length); + assertEquals("", new String(Base64.decodeBase64("====\n".getBytes("UTF-8")))); + // Test truncated padding + assertEquals(0, Base64.decodeBase64("===\n".getBytes("UTF-8")).length); + assertEquals(0, Base64.decodeBase64("==\n".getBytes("UTF-8")).length); + assertEquals(0, Base64.decodeBase64("=\n".getBytes("UTF-8")).length); + assertEquals(0, Base64.decodeBase64("\n".getBytes("UTF-8")).length); + } + + @Test + public void testDecodeWithWhitespace() throws Exception { + + String orig = "I am a late night coder."; + + byte[] encodedArray = Base64.encodeBase64(orig.getBytes("UTF-8")); + StringBuffer intermediate = new StringBuffer(new String(encodedArray)); + + intermediate.insert(2, ' '); + intermediate.insert(5, '\t'); + intermediate.insert(10, '\r'); + intermediate.insert(15, '\n'); + + byte[] encodedWithWS = intermediate.toString().getBytes("UTF-8"); + byte[] decodedWithWS = Base64.decodeBase64(encodedWithWS); + + String dest = new String(decodedWithWS); + + assertEquals("Dest string doesn't equal the original", orig, dest); + } + + /** + * Test encode and decode of empty byte array. + */ + @Test + public void testEmptyBase64() { + byte[] empty = new byte[0]; + byte[] result = Base64.encodeBase64(empty); + assertEquals("empty base64 encode", 0, result.length); + assertEquals("empty base64 encode", null, Base64.encodeBase64(null)); + + empty = new byte[0]; + result = Base64.decodeBase64(empty); + assertEquals("empty base64 decode", 0, result.length); + assertEquals("empty base64 encode", null, Base64.decodeBase64((byte[]) null)); + } + + // encode/decode a large random array + @Test + public void testEncodeDecodeRandom() { + for (int i = 1; i < 5; i++) { + byte[] data = new byte[this.getRandom().nextInt(10000) + 1]; + this.getRandom().nextBytes(data); + byte[] enc = Base64.encodeBase64(data); + assertTrue(Base64.isBase64(enc)); + byte[] data2 = Base64.decodeBase64(enc); + assertTrue(Arrays.equals(data, data2)); + } + } + + // encode/decode random arrays from size 0 to size 11 + @Test + public void testEncodeDecodeSmall() { + for (int i = 0; i < 12; i++) { + byte[] data = new byte[i]; + this.getRandom().nextBytes(data); + byte[] enc = Base64.encodeBase64(data); + assertTrue("\"" + new String(enc) + "\" is Base64 data.", Base64.isBase64(enc)); + byte[] data2 = Base64.decodeBase64(enc); + assertTrue(toString(data) + " equals " + toString(data2), Arrays.equals(data, data2)); + } + } + + @Test + public void testEncodeOverMaxSize() throws Exception { + testEncodeOverMaxSize(-1); + testEncodeOverMaxSize(0); + testEncodeOverMaxSize(1); + testEncodeOverMaxSize(2); + } + + @Test + public void testCodec112() { // size calculation assumes always chunked + byte[] in = new byte[] {0}; + byte[] out=Base64.encodeBase64(in); + Base64.encodeBase64(in, false, false, out.length); + } + + private void testEncodeOverMaxSize(int maxSize) throws Exception { + try { + Base64.encodeBase64(Base64TestData.DECODED, true, false, maxSize); + fail("Expected " + IllegalArgumentException.class.getName()); + } catch (IllegalArgumentException e) { + // Expected + } + } + + @Test + public void testIgnoringNonBase64InDecode() throws Exception { + assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 + .decodeBase64("VGhlIH@$#$@%F1aWN@#@#@@rIGJyb3duIGZve\n\r\t%#%#%#%CBqd##$#$W1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes("UTF-8")))); + } + + @Test + public void testIsArrayByteBase64() { + assertFalse(Base64.isBase64(new byte[]{Byte.MIN_VALUE})); + assertFalse(Base64.isBase64(new byte[]{-125})); + assertFalse(Base64.isBase64(new byte[]{-10})); + assertFalse(Base64.isBase64(new byte[]{0})); + assertFalse(Base64.isBase64(new byte[]{64, Byte.MAX_VALUE})); + assertFalse(Base64.isBase64(new byte[]{Byte.MAX_VALUE})); + assertTrue(Base64.isBase64(new byte[]{'A'})); + assertFalse(Base64.isBase64(new byte[]{'A', Byte.MIN_VALUE})); + assertTrue(Base64.isBase64(new byte[]{'A', 'Z', 'a'})); + assertTrue(Base64.isBase64(new byte[]{'/', '=', '+'})); + assertFalse(Base64.isBase64(new byte[]{'$'})); + } + + /** + * Tests isUrlSafe. + */ + @Test + public void testIsUrlSafe() { + Base64 base64Standard = new Base64(false); + Base64 base64URLSafe = new Base64(true); + + assertFalse("Base64.isUrlSafe=false", base64Standard.isUrlSafe()); + assertTrue("Base64.isUrlSafe=true", base64URLSafe.isUrlSafe()); + + byte[] whiteSpace = {' ', '\n', '\r', '\t'}; + assertTrue("Base64.isBase64(whiteSpace)=true", Base64.isBase64(whiteSpace)); + } + + @Test + public void testKnownDecodings() throws UnsupportedEncodingException { + assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 + .decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes("UTF-8")))); + assertEquals("It was the best of times, it was the worst of times.", new String(Base64 + .decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes("UTF-8")))); + assertEquals("http://jakarta.apache.org/commmons", new String(Base64 + .decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes("UTF-8")))); + assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64 + .decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes("UTF-8")))); + assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=" + .getBytes("UTF-8")))); + assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes("UTF-8")))); + } + + @Test + public void testKnownEncodings() throws UnsupportedEncodingException { + assertEquals("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==", new String(Base64 + .encodeBase64("The quick brown fox jumped over the lazy dogs.".getBytes("UTF-8")))); + assertEquals( + "YmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJs\r\nYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFo\r\nIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBi\r\nbGFoIGJsYWg=\r\n", + new String( + Base64 + .encodeBase64Chunked("blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah" + .getBytes("UTF-8")))); + assertEquals("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==", new String(Base64 + .encodeBase64("It was the best of times, it was the worst of times.".getBytes("UTF-8")))); + assertEquals("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==", new String(Base64 + .encodeBase64("http://jakarta.apache.org/commmons".getBytes("UTF-8")))); + assertEquals("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==", new String(Base64 + .encodeBase64("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".getBytes("UTF-8")))); + assertEquals("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=", new String(Base64.encodeBase64("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }" + .getBytes("UTF-8")))); + assertEquals("eHl6enkh", new String(Base64.encodeBase64("xyzzy!".getBytes("UTF-8")))); + } + + @Test + public void testNonBase64Test() throws Exception { + + byte[] bArray = {'%'}; + + assertFalse("Invalid Base64 array was incorrectly validated as " + "an array of Base64 encoded data", Base64 + .isBase64(bArray)); + + try { + Base64 b64 = new Base64(); + byte[] result = b64.decode(bArray); + + assertEquals("The result should be empty as the test encoded content did " + "not contain any valid base 64 characters", + 0, result.length); + } catch (Exception e) { + fail("Exception was thrown when trying to decode " + + "invalid base64 encoded data - RFC 2045 requires that all " + + "non base64 character be discarded, an exception should not" + + " have been thrown"); + } + } + + @Test + public void testObjectDecodeWithInvalidParameter() throws Exception { + Base64 b64 = new Base64(); + + try { + b64.decode(Integer.valueOf(5)); + fail("decode(Object) didn't throw an exception when passed an Integer object"); + } catch (DecoderException e) { + // ignored + } + + } + + @Test + public void testObjectDecodeWithValidParameter() throws Exception { + + String original = "Hello World!"; + Object o = Base64.encodeBase64(original.getBytes("UTF-8")); + + Base64 b64 = new Base64(); + Object oDecoded = b64.decode(o); + byte[] baDecoded = (byte[]) oDecoded; + String dest = new String(baDecoded); + + assertEquals("dest string does not equal original", original, dest); + } + + @Test + public void testObjectEncodeWithInvalidParameter() throws Exception { + Base64 b64 = new Base64(); + try { + b64.encode("Yadayadayada"); + fail("encode(Object) didn't throw an exception when passed a String object"); + } catch (EncoderException e) { + // Expected + } + } + + @Test + public void testObjectEncodeWithValidParameter() throws Exception { + + String original = "Hello World!"; + Object origObj = original.getBytes("UTF-8"); + + Base64 b64 = new Base64(); + Object oEncoded = b64.encode(origObj); + byte[] bArray = Base64.decodeBase64((byte[]) oEncoded); + String dest = new String(bArray); + + assertEquals("dest string does not equal original", original, dest); + } + + @Test + public void testObjectEncode() throws Exception { + Base64 b64 = new Base64(); + assertEquals("SGVsbG8gV29ybGQ=", new String(b64.encode("Hello World".getBytes("UTF-8")))); + } + + @Test + public void testPairs() { + assertEquals("AAA=", new String(Base64.encodeBase64(new byte[]{0, 0}))); + for (int i = -128; i <= 127; i++) { + byte test[] = {(byte) i, (byte) i}; + assertTrue(Arrays.equals(test, Base64.decodeBase64(Base64.encodeBase64(test)))); + } + } + + /** + * Tests RFC 2045 section 2.1 CRLF definition. + */ + @Test + public void testRfc2045Section2Dot1CrLfDefinition() { + assertTrue(Arrays.equals(new byte[]{13, 10}, Base64.CHUNK_SEPARATOR)); + } + + /** + * Tests RFC 2045 section 6.8 chuck size definition. + */ + @Test + public void testRfc2045Section6Dot8ChunkSizeDefinition() { + assertEquals(76, BaseNCodec.MIME_CHUNK_SIZE); + } + + /** + * Tests RFC 1421 section 4.3.2.4 chuck size definition. + */ + @Test + public void testRfc1421Section6Dot8ChunkSizeDefinition() { + assertEquals(64, BaseNCodec.PEM_CHUNK_SIZE); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *

      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + @Test + public void testRfc4648Section10Decode() { + assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64(""))); + assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg=="))); + assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8="))); + assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v"))); + assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg=="))); + assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE="))); + assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy"))); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *
      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + @Test + public void testRfc4648Section10DecodeWithCrLf() { + String CRLF = StringUtils.newStringUsAscii(Base64.CHUNK_SEPARATOR); + assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64("" + CRLF))); + assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg==" + CRLF))); + assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8=" + CRLF))); + assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v" + CRLF))); + assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg==" + CRLF))); + assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE=" + CRLF))); + assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy" + CRLF))); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *
      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + @Test + public void testRfc4648Section10Encode() { + assertEquals("", Base64.encodeBase64String(StringUtils.getBytesUtf8(""))); + assertEquals("Zg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("f"))); + assertEquals("Zm8=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fo"))); + assertEquals("Zm9v", Base64.encodeBase64String(StringUtils.getBytesUtf8("foo"))); + assertEquals("Zm9vYg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("foob"))); + assertEquals("Zm9vYmE=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fooba"))); + assertEquals("Zm9vYmFy", Base64.encodeBase64String(StringUtils.getBytesUtf8("foobar"))); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *
      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + @Test + public void testRfc4648Section10DecodeEncode() { + testDecodeEncode(""); + //testDecodeEncode("Zg=="); + //testDecodeEncode("Zm8="); + //testDecodeEncode("Zm9v"); + //testDecodeEncode("Zm9vYg=="); + //testDecodeEncode("Zm9vYmE="); + //testDecodeEncode("Zm9vYmFy"); + } + + private void testDecodeEncode(String encodedText) { + String decodedText = StringUtils.newStringUsAscii(Base64.decodeBase64(encodedText)); + String encodedText2 = Base64.encodeBase64String(StringUtils.getBytesUtf8(decodedText)); + assertEquals(encodedText, encodedText2); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *
      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + @Test + public void testRfc4648Section10EncodeDecode() { + testEncodeDecode(""); + testEncodeDecode("f"); + testEncodeDecode("fo"); + testEncodeDecode("foo"); + testEncodeDecode("foob"); + testEncodeDecode("fooba"); + testEncodeDecode("foobar"); + } + + private void testEncodeDecode(String plainText) { + String encodedText = Base64.encodeBase64String(StringUtils.getBytesUtf8(plainText)); + String decodedText = StringUtils.newStringUsAscii(Base64.decodeBase64(encodedText)); + assertEquals(plainText, decodedText); + } + + @Test + public void testSingletons() { + assertEquals("AA==", new String(Base64.encodeBase64(new byte[]{(byte) 0}))); + assertEquals("AQ==", new String(Base64.encodeBase64(new byte[]{(byte) 1}))); + assertEquals("Ag==", new String(Base64.encodeBase64(new byte[]{(byte) 2}))); + assertEquals("Aw==", new String(Base64.encodeBase64(new byte[]{(byte) 3}))); + assertEquals("BA==", new String(Base64.encodeBase64(new byte[]{(byte) 4}))); + assertEquals("BQ==", new String(Base64.encodeBase64(new byte[]{(byte) 5}))); + assertEquals("Bg==", new String(Base64.encodeBase64(new byte[]{(byte) 6}))); + assertEquals("Bw==", new String(Base64.encodeBase64(new byte[]{(byte) 7}))); + assertEquals("CA==", new String(Base64.encodeBase64(new byte[]{(byte) 8}))); + assertEquals("CQ==", new String(Base64.encodeBase64(new byte[]{(byte) 9}))); + assertEquals("Cg==", new String(Base64.encodeBase64(new byte[]{(byte) 10}))); + assertEquals("Cw==", new String(Base64.encodeBase64(new byte[]{(byte) 11}))); + assertEquals("DA==", new String(Base64.encodeBase64(new byte[]{(byte) 12}))); + assertEquals("DQ==", new String(Base64.encodeBase64(new byte[]{(byte) 13}))); + assertEquals("Dg==", new String(Base64.encodeBase64(new byte[]{(byte) 14}))); + assertEquals("Dw==", new String(Base64.encodeBase64(new byte[]{(byte) 15}))); + assertEquals("EA==", new String(Base64.encodeBase64(new byte[]{(byte) 16}))); + assertEquals("EQ==", new String(Base64.encodeBase64(new byte[]{(byte) 17}))); + assertEquals("Eg==", new String(Base64.encodeBase64(new byte[]{(byte) 18}))); + assertEquals("Ew==", new String(Base64.encodeBase64(new byte[]{(byte) 19}))); + assertEquals("FA==", new String(Base64.encodeBase64(new byte[]{(byte) 20}))); + assertEquals("FQ==", new String(Base64.encodeBase64(new byte[]{(byte) 21}))); + assertEquals("Fg==", new String(Base64.encodeBase64(new byte[]{(byte) 22}))); + assertEquals("Fw==", new String(Base64.encodeBase64(new byte[]{(byte) 23}))); + assertEquals("GA==", new String(Base64.encodeBase64(new byte[]{(byte) 24}))); + assertEquals("GQ==", new String(Base64.encodeBase64(new byte[]{(byte) 25}))); + assertEquals("Gg==", new String(Base64.encodeBase64(new byte[]{(byte) 26}))); + assertEquals("Gw==", new String(Base64.encodeBase64(new byte[]{(byte) 27}))); + assertEquals("HA==", new String(Base64.encodeBase64(new byte[]{(byte) 28}))); + assertEquals("HQ==", new String(Base64.encodeBase64(new byte[]{(byte) 29}))); + assertEquals("Hg==", new String(Base64.encodeBase64(new byte[]{(byte) 30}))); + assertEquals("Hw==", new String(Base64.encodeBase64(new byte[]{(byte) 31}))); + assertEquals("IA==", new String(Base64.encodeBase64(new byte[]{(byte) 32}))); + assertEquals("IQ==", new String(Base64.encodeBase64(new byte[]{(byte) 33}))); + assertEquals("Ig==", new String(Base64.encodeBase64(new byte[]{(byte) 34}))); + assertEquals("Iw==", new String(Base64.encodeBase64(new byte[]{(byte) 35}))); + assertEquals("JA==", new String(Base64.encodeBase64(new byte[]{(byte) 36}))); + assertEquals("JQ==", new String(Base64.encodeBase64(new byte[]{(byte) 37}))); + assertEquals("Jg==", new String(Base64.encodeBase64(new byte[]{(byte) 38}))); + assertEquals("Jw==", new String(Base64.encodeBase64(new byte[]{(byte) 39}))); + assertEquals("KA==", new String(Base64.encodeBase64(new byte[]{(byte) 40}))); + assertEquals("KQ==", new String(Base64.encodeBase64(new byte[]{(byte) 41}))); + assertEquals("Kg==", new String(Base64.encodeBase64(new byte[]{(byte) 42}))); + assertEquals("Kw==", new String(Base64.encodeBase64(new byte[]{(byte) 43}))); + assertEquals("LA==", new String(Base64.encodeBase64(new byte[]{(byte) 44}))); + assertEquals("LQ==", new String(Base64.encodeBase64(new byte[]{(byte) 45}))); + assertEquals("Lg==", new String(Base64.encodeBase64(new byte[]{(byte) 46}))); + assertEquals("Lw==", new String(Base64.encodeBase64(new byte[]{(byte) 47}))); + assertEquals("MA==", new String(Base64.encodeBase64(new byte[]{(byte) 48}))); + assertEquals("MQ==", new String(Base64.encodeBase64(new byte[]{(byte) 49}))); + assertEquals("Mg==", new String(Base64.encodeBase64(new byte[]{(byte) 50}))); + assertEquals("Mw==", new String(Base64.encodeBase64(new byte[]{(byte) 51}))); + assertEquals("NA==", new String(Base64.encodeBase64(new byte[]{(byte) 52}))); + assertEquals("NQ==", new String(Base64.encodeBase64(new byte[]{(byte) 53}))); + assertEquals("Ng==", new String(Base64.encodeBase64(new byte[]{(byte) 54}))); + assertEquals("Nw==", new String(Base64.encodeBase64(new byte[]{(byte) 55}))); + assertEquals("OA==", new String(Base64.encodeBase64(new byte[]{(byte) 56}))); + assertEquals("OQ==", new String(Base64.encodeBase64(new byte[]{(byte) 57}))); + assertEquals("Og==", new String(Base64.encodeBase64(new byte[]{(byte) 58}))); + assertEquals("Ow==", new String(Base64.encodeBase64(new byte[]{(byte) 59}))); + assertEquals("PA==", new String(Base64.encodeBase64(new byte[]{(byte) 60}))); + assertEquals("PQ==", new String(Base64.encodeBase64(new byte[]{(byte) 61}))); + assertEquals("Pg==", new String(Base64.encodeBase64(new byte[]{(byte) 62}))); + assertEquals("Pw==", new String(Base64.encodeBase64(new byte[]{(byte) 63}))); + assertEquals("QA==", new String(Base64.encodeBase64(new byte[]{(byte) 64}))); + assertEquals("QQ==", new String(Base64.encodeBase64(new byte[]{(byte) 65}))); + assertEquals("Qg==", new String(Base64.encodeBase64(new byte[]{(byte) 66}))); + assertEquals("Qw==", new String(Base64.encodeBase64(new byte[]{(byte) 67}))); + assertEquals("RA==", new String(Base64.encodeBase64(new byte[]{(byte) 68}))); + assertEquals("RQ==", new String(Base64.encodeBase64(new byte[]{(byte) 69}))); + assertEquals("Rg==", new String(Base64.encodeBase64(new byte[]{(byte) 70}))); + assertEquals("Rw==", new String(Base64.encodeBase64(new byte[]{(byte) 71}))); + assertEquals("SA==", new String(Base64.encodeBase64(new byte[]{(byte) 72}))); + assertEquals("SQ==", new String(Base64.encodeBase64(new byte[]{(byte) 73}))); + assertEquals("Sg==", new String(Base64.encodeBase64(new byte[]{(byte) 74}))); + assertEquals("Sw==", new String(Base64.encodeBase64(new byte[]{(byte) 75}))); + assertEquals("TA==", new String(Base64.encodeBase64(new byte[]{(byte) 76}))); + assertEquals("TQ==", new String(Base64.encodeBase64(new byte[]{(byte) 77}))); + assertEquals("Tg==", new String(Base64.encodeBase64(new byte[]{(byte) 78}))); + assertEquals("Tw==", new String(Base64.encodeBase64(new byte[]{(byte) 79}))); + assertEquals("UA==", new String(Base64.encodeBase64(new byte[]{(byte) 80}))); + assertEquals("UQ==", new String(Base64.encodeBase64(new byte[]{(byte) 81}))); + assertEquals("Ug==", new String(Base64.encodeBase64(new byte[]{(byte) 82}))); + assertEquals("Uw==", new String(Base64.encodeBase64(new byte[]{(byte) 83}))); + assertEquals("VA==", new String(Base64.encodeBase64(new byte[]{(byte) 84}))); + assertEquals("VQ==", new String(Base64.encodeBase64(new byte[]{(byte) 85}))); + assertEquals("Vg==", new String(Base64.encodeBase64(new byte[]{(byte) 86}))); + assertEquals("Vw==", new String(Base64.encodeBase64(new byte[]{(byte) 87}))); + assertEquals("WA==", new String(Base64.encodeBase64(new byte[]{(byte) 88}))); + assertEquals("WQ==", new String(Base64.encodeBase64(new byte[]{(byte) 89}))); + assertEquals("Wg==", new String(Base64.encodeBase64(new byte[]{(byte) 90}))); + assertEquals("Ww==", new String(Base64.encodeBase64(new byte[]{(byte) 91}))); + assertEquals("XA==", new String(Base64.encodeBase64(new byte[]{(byte) 92}))); + assertEquals("XQ==", new String(Base64.encodeBase64(new byte[]{(byte) 93}))); + assertEquals("Xg==", new String(Base64.encodeBase64(new byte[]{(byte) 94}))); + assertEquals("Xw==", new String(Base64.encodeBase64(new byte[]{(byte) 95}))); + assertEquals("YA==", new String(Base64.encodeBase64(new byte[]{(byte) 96}))); + assertEquals("YQ==", new String(Base64.encodeBase64(new byte[]{(byte) 97}))); + assertEquals("Yg==", new String(Base64.encodeBase64(new byte[]{(byte) 98}))); + assertEquals("Yw==", new String(Base64.encodeBase64(new byte[]{(byte) 99}))); + assertEquals("ZA==", new String(Base64.encodeBase64(new byte[]{(byte) 100}))); + assertEquals("ZQ==", new String(Base64.encodeBase64(new byte[]{(byte) 101}))); + assertEquals("Zg==", new String(Base64.encodeBase64(new byte[]{(byte) 102}))); + assertEquals("Zw==", new String(Base64.encodeBase64(new byte[]{(byte) 103}))); + assertEquals("aA==", new String(Base64.encodeBase64(new byte[]{(byte) 104}))); + for (int i = -128; i <= 127; i++) { + byte test[] = {(byte) i}; + assertTrue(Arrays.equals(test, Base64.decodeBase64(Base64.encodeBase64(test)))); + } + } + + @Test + public void testSingletonsChunked() { + assertEquals("AA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0}))); + assertEquals("AQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 1}))); + assertEquals("Ag==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 2}))); + assertEquals("Aw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 3}))); + assertEquals("BA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 4}))); + assertEquals("BQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 5}))); + assertEquals("Bg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 6}))); + assertEquals("Bw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 7}))); + assertEquals("CA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 8}))); + assertEquals("CQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 9}))); + assertEquals("Cg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 10}))); + assertEquals("Cw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 11}))); + assertEquals("DA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 12}))); + assertEquals("DQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 13}))); + assertEquals("Dg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 14}))); + assertEquals("Dw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 15}))); + assertEquals("EA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 16}))); + assertEquals("EQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 17}))); + assertEquals("Eg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 18}))); + assertEquals("Ew==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 19}))); + assertEquals("FA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 20}))); + assertEquals("FQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 21}))); + assertEquals("Fg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 22}))); + assertEquals("Fw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 23}))); + assertEquals("GA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 24}))); + assertEquals("GQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 25}))); + assertEquals("Gg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 26}))); + assertEquals("Gw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 27}))); + assertEquals("HA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 28}))); + assertEquals("HQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 29}))); + assertEquals("Hg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 30}))); + assertEquals("Hw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 31}))); + assertEquals("IA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 32}))); + assertEquals("IQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 33}))); + assertEquals("Ig==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 34}))); + assertEquals("Iw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 35}))); + assertEquals("JA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 36}))); + assertEquals("JQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 37}))); + assertEquals("Jg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 38}))); + assertEquals("Jw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 39}))); + assertEquals("KA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 40}))); + assertEquals("KQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 41}))); + assertEquals("Kg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 42}))); + assertEquals("Kw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 43}))); + assertEquals("LA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 44}))); + assertEquals("LQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 45}))); + assertEquals("Lg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 46}))); + assertEquals("Lw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 47}))); + assertEquals("MA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 48}))); + assertEquals("MQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 49}))); + assertEquals("Mg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 50}))); + assertEquals("Mw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 51}))); + assertEquals("NA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 52}))); + assertEquals("NQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 53}))); + assertEquals("Ng==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 54}))); + assertEquals("Nw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 55}))); + assertEquals("OA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 56}))); + assertEquals("OQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 57}))); + assertEquals("Og==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 58}))); + assertEquals("Ow==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 59}))); + assertEquals("PA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 60}))); + assertEquals("PQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 61}))); + assertEquals("Pg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 62}))); + assertEquals("Pw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 63}))); + assertEquals("QA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 64}))); + assertEquals("QQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 65}))); + assertEquals("Qg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 66}))); + assertEquals("Qw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 67}))); + assertEquals("RA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 68}))); + assertEquals("RQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 69}))); + assertEquals("Rg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 70}))); + assertEquals("Rw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 71}))); + assertEquals("SA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 72}))); + assertEquals("SQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 73}))); + assertEquals("Sg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 74}))); + assertEquals("Sw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 75}))); + assertEquals("TA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 76}))); + assertEquals("TQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 77}))); + assertEquals("Tg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 78}))); + assertEquals("Tw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 79}))); + assertEquals("UA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 80}))); + assertEquals("UQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 81}))); + assertEquals("Ug==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 82}))); + assertEquals("Uw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 83}))); + assertEquals("VA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 84}))); + assertEquals("VQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 85}))); + assertEquals("Vg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 86}))); + assertEquals("Vw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 87}))); + assertEquals("WA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 88}))); + assertEquals("WQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 89}))); + assertEquals("Wg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 90}))); + assertEquals("Ww==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 91}))); + assertEquals("XA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 92}))); + assertEquals("XQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 93}))); + assertEquals("Xg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 94}))); + assertEquals("Xw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 95}))); + assertEquals("YA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 96}))); + assertEquals("YQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 97}))); + assertEquals("Yg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 98}))); + assertEquals("Yw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 99}))); + assertEquals("ZA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 100}))); + assertEquals("ZQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 101}))); + assertEquals("Zg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 102}))); + assertEquals("Zw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 103}))); + assertEquals("aA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 104}))); + } + + @Test + public void testTriplets() { + assertEquals("AAAA", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 0}))); + assertEquals("AAAB", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 1}))); + assertEquals("AAAC", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 2}))); + assertEquals("AAAD", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 3}))); + assertEquals("AAAE", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 4}))); + assertEquals("AAAF", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 5}))); + assertEquals("AAAG", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 6}))); + assertEquals("AAAH", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 7}))); + assertEquals("AAAI", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 8}))); + assertEquals("AAAJ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 9}))); + assertEquals("AAAK", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 10}))); + assertEquals("AAAL", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 11}))); + assertEquals("AAAM", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 12}))); + assertEquals("AAAN", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 13}))); + assertEquals("AAAO", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 14}))); + assertEquals("AAAP", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 15}))); + assertEquals("AAAQ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 16}))); + assertEquals("AAAR", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 17}))); + assertEquals("AAAS", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 18}))); + assertEquals("AAAT", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 19}))); + assertEquals("AAAU", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 20}))); + assertEquals("AAAV", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 21}))); + assertEquals("AAAW", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 22}))); + assertEquals("AAAX", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 23}))); + assertEquals("AAAY", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 24}))); + assertEquals("AAAZ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 25}))); + assertEquals("AAAa", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 26}))); + assertEquals("AAAb", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 27}))); + assertEquals("AAAc", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 28}))); + assertEquals("AAAd", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 29}))); + assertEquals("AAAe", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 30}))); + assertEquals("AAAf", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 31}))); + assertEquals("AAAg", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 32}))); + assertEquals("AAAh", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 33}))); + assertEquals("AAAi", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 34}))); + assertEquals("AAAj", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 35}))); + assertEquals("AAAk", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 36}))); + assertEquals("AAAl", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 37}))); + assertEquals("AAAm", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 38}))); + assertEquals("AAAn", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 39}))); + assertEquals("AAAo", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 40}))); + assertEquals("AAAp", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 41}))); + assertEquals("AAAq", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 42}))); + assertEquals("AAAr", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 43}))); + assertEquals("AAAs", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 44}))); + assertEquals("AAAt", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 45}))); + assertEquals("AAAu", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 46}))); + assertEquals("AAAv", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 47}))); + assertEquals("AAAw", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 48}))); + assertEquals("AAAx", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 49}))); + assertEquals("AAAy", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 50}))); + assertEquals("AAAz", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 51}))); + assertEquals("AAA0", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 52}))); + assertEquals("AAA1", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 53}))); + assertEquals("AAA2", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 54}))); + assertEquals("AAA3", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 55}))); + assertEquals("AAA4", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 56}))); + assertEquals("AAA5", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 57}))); + assertEquals("AAA6", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 58}))); + assertEquals("AAA7", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 59}))); + assertEquals("AAA8", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 60}))); + assertEquals("AAA9", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 61}))); + assertEquals("AAA+", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 62}))); + assertEquals("AAA/", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 63}))); + } + + @Test + public void testTripletsChunked() { + assertEquals("AAAA\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 0}))); + assertEquals("AAAB\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 1}))); + assertEquals("AAAC\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 2}))); + assertEquals("AAAD\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 3}))); + assertEquals("AAAE\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 4}))); + assertEquals("AAAF\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 5}))); + assertEquals("AAAG\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 6}))); + assertEquals("AAAH\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 7}))); + assertEquals("AAAI\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 8}))); + assertEquals("AAAJ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 9}))); + assertEquals("AAAK\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 10}))); + assertEquals("AAAL\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 11}))); + assertEquals("AAAM\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 12}))); + assertEquals("AAAN\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 13}))); + assertEquals("AAAO\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 14}))); + assertEquals("AAAP\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 15}))); + assertEquals("AAAQ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 16}))); + assertEquals("AAAR\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 17}))); + assertEquals("AAAS\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 18}))); + assertEquals("AAAT\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 19}))); + assertEquals("AAAU\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 20}))); + assertEquals("AAAV\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 21}))); + assertEquals("AAAW\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 22}))); + assertEquals("AAAX\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 23}))); + assertEquals("AAAY\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 24}))); + assertEquals("AAAZ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 25}))); + assertEquals("AAAa\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 26}))); + assertEquals("AAAb\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 27}))); + assertEquals("AAAc\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 28}))); + assertEquals("AAAd\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 29}))); + assertEquals("AAAe\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 30}))); + assertEquals("AAAf\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 31}))); + assertEquals("AAAg\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 32}))); + assertEquals("AAAh\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 33}))); + assertEquals("AAAi\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 34}))); + assertEquals("AAAj\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 35}))); + assertEquals("AAAk\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 36}))); + assertEquals("AAAl\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 37}))); + assertEquals("AAAm\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 38}))); + assertEquals("AAAn\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 39}))); + assertEquals("AAAo\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 40}))); + assertEquals("AAAp\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 41}))); + assertEquals("AAAq\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 42}))); + assertEquals("AAAr\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 43}))); + assertEquals("AAAs\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 44}))); + assertEquals("AAAt\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 45}))); + assertEquals("AAAu\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 46}))); + assertEquals("AAAv\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 47}))); + assertEquals("AAAw\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 48}))); + assertEquals("AAAx\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 49}))); + assertEquals("AAAy\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 50}))); + assertEquals("AAAz\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 51}))); + assertEquals("AAA0\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 52}))); + assertEquals("AAA1\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 53}))); + assertEquals("AAA2\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 54}))); + assertEquals("AAA3\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 55}))); + assertEquals("AAA4\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 56}))); + assertEquals("AAA5\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 57}))); + assertEquals("AAA6\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 58}))); + assertEquals("AAA7\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 59}))); + assertEquals("AAA8\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 60}))); + assertEquals("AAA9\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 61}))); + assertEquals("AAA+\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 62}))); + assertEquals("AAA/\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 63}))); + } + + /** + * Tests url-safe Base64 against random data, sizes 0 to 150. + */ + @Test + public void testUrlSafe() { + // test random data of sizes 0 thru 150 + for (int i = 0; i <= 150; i++) { + byte[][] randomData = Base64TestData.randomData(i, true); + byte[] encoded = randomData[1]; + byte[] decoded = randomData[0]; + byte[] result = Base64.decodeBase64(encoded); + assertTrue("url-safe i=" + i, Arrays.equals(decoded, result)); + assertFalse("url-safe i=" + i + " no '='", Base64TestData.bytesContain(encoded, (byte) '=')); + assertFalse("url-safe i=" + i + " no '\\'", Base64TestData.bytesContain(encoded, (byte) '\\')); + assertFalse("url-safe i=" + i + " no '+'", Base64TestData.bytesContain(encoded, (byte) '+')); + } + + } + + /** + * Base64 encoding of UUID's is a common use-case, especially in URL-SAFE mode. This test case ends up being the + * "URL-SAFE" JUnit's. + * + * @throws DecoderException + * if Hex.decode() fails - a serious problem since Hex comes from our own commons-codec! + */ + @Test + public void testUUID() throws DecoderException { + // The 4 UUID's below contains mixtures of + and / to help us test the + // URL-SAFE encoding mode. + byte[][] ids = new byte[4][]; + + // ids[0] was chosen so that it encodes with at least one +. + ids[0] = Hex.decodeHex("94ed8d0319e4493399560fb67404d370".toCharArray()); + + // ids[1] was chosen so that it encodes with both / and +. + ids[1] = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray()); + + // ids[2] was chosen so that it encodes with at least one /. + ids[2] = Hex.decodeHex("64be154b6ffa40258d1a01288e7c31ca".toCharArray()); + + // ids[3] was chosen so that it encodes with both / and +, with / + // right at the beginning. + ids[3] = Hex.decodeHex("ff7f8fc01cdb471a8c8b5a9306183fe8".toCharArray()); + + byte[][] standard = new byte[4][]; + standard[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg+2dATTcA=="); + standard[1] = StringUtils.getBytesUtf8("K/fMJwH+Q5e0nr7tWsxwkA=="); + standard[2] = StringUtils.getBytesUtf8("ZL4VS2/6QCWNGgEojnwxyg=="); + standard[3] = StringUtils.getBytesUtf8("/3+PwBzbRxqMi1qTBhg/6A=="); + + byte[][] urlSafe1 = new byte[4][]; + // regular padding (two '==' signs). + urlSafe1[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA=="); + urlSafe1[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA=="); + urlSafe1[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg=="); + urlSafe1[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A=="); + + byte[][] urlSafe2 = new byte[4][]; + // single padding (only one '=' sign). + urlSafe2[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA="); + urlSafe2[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA="); + urlSafe2[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg="); + urlSafe2[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A="); + + byte[][] urlSafe3 = new byte[4][]; + // no padding (no '=' signs). + urlSafe3[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA"); + urlSafe3[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA"); + urlSafe3[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg"); + urlSafe3[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A"); + + for (int i = 0; i < 4; i++) { + byte[] encodedStandard = Base64.encodeBase64(ids[i]); + byte[] encodedUrlSafe = Base64.encodeBase64URLSafe(ids[i]); + byte[] decodedStandard = Base64.decodeBase64(standard[i]); + byte[] decodedUrlSafe1 = Base64.decodeBase64(urlSafe1[i]); + byte[] decodedUrlSafe2 = Base64.decodeBase64(urlSafe2[i]); + byte[] decodedUrlSafe3 = Base64.decodeBase64(urlSafe3[i]); + + // Very important debugging output should anyone + // ever need to delve closely into this stuff. + if (false) { + System.out.println("reference: [" + Hex.encodeHexString(ids[i]) + "]"); + System.out.println("standard: [" + + Hex.encodeHexString(decodedStandard) + + "] From: [" + + StringUtils.newStringUtf8(standard[i]) + + "]"); + System.out.println("safe1: [" + + Hex.encodeHexString(decodedUrlSafe1) + + "] From: [" + + StringUtils.newStringUtf8(urlSafe1[i]) + + "]"); + System.out.println("safe2: [" + + Hex.encodeHexString(decodedUrlSafe2) + + "] From: [" + + StringUtils.newStringUtf8(urlSafe2[i]) + + "]"); + System.out.println("safe3: [" + + Hex.encodeHexString(decodedUrlSafe3) + + "] From: [" + + StringUtils.newStringUtf8(urlSafe3[i]) + + "]"); + } + + assertTrue("standard encode uuid", Arrays.equals(encodedStandard, standard[i])); + assertTrue("url-safe encode uuid", Arrays.equals(encodedUrlSafe, urlSafe3[i])); + assertTrue("standard decode uuid", Arrays.equals(decodedStandard, ids[i])); + assertTrue("url-safe1 decode uuid", Arrays.equals(decodedUrlSafe1, ids[i])); + assertTrue("url-safe2 decode uuid", Arrays.equals(decodedUrlSafe2, ids[i])); + assertTrue("url-safe3 decode uuid", Arrays.equals(decodedUrlSafe3, ids[i])); + } + } + + @Test + public void testByteToStringVariations() throws DecoderException { + Base64 base64 = new Base64(0); + byte[] b1 = StringUtils.getBytesUtf8("Hello World"); + byte[] b2 = new byte[0]; + byte[] b3 = null; + byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray()); // for url-safe tests + + assertEquals("byteToString Hello World", "SGVsbG8gV29ybGQ=", base64.encodeToString(b1)); + assertEquals("byteToString static Hello World", "SGVsbG8gV29ybGQ=", Base64.encodeBase64String(b1)); + assertEquals("byteToString \"\"", "", base64.encodeToString(b2)); + assertEquals("byteToString static \"\"", "", Base64.encodeBase64String(b2)); + assertEquals("byteToString null", null, base64.encodeToString(b3)); + assertEquals("byteToString static null", null, Base64.encodeBase64String(b3)); + assertEquals("byteToString UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", base64.encodeToString(b4)); + assertEquals("byteToString static UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", Base64.encodeBase64String(b4)); + assertEquals("byteToString static-url-safe UUID", "K_fMJwH-Q5e0nr7tWsxwkA", Base64.encodeBase64URLSafeString(b4)); + } + + @Test + public void testStringToByteVariations() throws DecoderException { + Base64 base64 = new Base64(); + String s1 = "SGVsbG8gV29ybGQ=\r\n"; + String s2 = ""; + String s3 = null; + String s4a = "K/fMJwH+Q5e0nr7tWsxwkA==\r\n"; + String s4b = "K_fMJwH-Q5e0nr7tWsxwkA"; + byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray()); // for url-safe tests + + assertEquals("StringToByte Hello World", "Hello World", StringUtils.newStringUtf8(base64.decode(s1))); + assertEquals("StringToByte Hello World", "Hello World", StringUtils.newStringUtf8((byte[])base64.decode((Object)s1))); + assertEquals("StringToByte static Hello World", "Hello World", StringUtils.newStringUtf8(Base64.decodeBase64(s1))); + assertEquals("StringToByte \"\"", "", StringUtils.newStringUtf8(base64.decode(s2))); + assertEquals("StringToByte static \"\"", "", StringUtils.newStringUtf8(Base64.decodeBase64(s2))); + assertEquals("StringToByte null", null, StringUtils.newStringUtf8(base64.decode(s3))); + assertEquals("StringToByte static null", null, StringUtils.newStringUtf8(Base64.decodeBase64(s3))); + assertTrue("StringToByte UUID", Arrays.equals(b4, base64.decode(s4b))); + assertTrue("StringToByte static UUID", Arrays.equals(b4, Base64.decodeBase64(s4a))); + assertTrue("StringToByte static-url-safe UUID", Arrays.equals(b4, Base64.decodeBase64(s4b))); + } + + private String toString(byte[] data) { + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < data.length; i++) { + buf.append(data[i]); + if (i != data.length - 1) { + buf.append(","); + } + } + return buf.toString(); + } + + /** + * Tests a lineSeparator much bigger than DEFAULT_BUFFER_SIZE. + * + * @see dev@commons.apache.org + */ + @Test + @Ignore + public void testHugeLineSeparator() { + final int BaseNCodec_DEFAULT_BUFFER_SIZE = 8192; + final int Base64_BYTES_PER_ENCODED_BLOCK = 4; + byte[] baLineSeparator = new byte[BaseNCodec_DEFAULT_BUFFER_SIZE * 4 - 3]; + Base64 b64 = new Base64(Base64_BYTES_PER_ENCODED_BLOCK, baLineSeparator); + String strOriginal = "Hello World"; + String strDecoded = new String(b64.decode(b64.encode(StringUtils.getBytesUtf8(strOriginal)))); + assertEquals("testDEFAULT_BUFFER_SIZE", strOriginal, strDecoded); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `decodeBase64("QQ==".getBytes("UTF-8"))` could be null and is dereferenced by call to `String(...)` at line 252. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Base64Test.testDecodePadMarkerIndex2() + +### Procedure Id: +org.apache.commons.codec.binary.Base64Test.testDecodePadMarkerIndex2():void.2dedf396e8e849aeb6b9ae6bda7e8797 + +### File: +src/test/java/org/apache/commons/codec/binary/Base64Test.java + +### Key: +Base64Test.java|testDecodePadMarkerIndex2|NULL_DEREFERENCE + +### Node Key: +e7100ed3d2ec428549af314291e315ce + +### Hash: +2fca1cca759643d9af555f47d208da93 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3326/instruction.md b/inferredbugs-3326/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8cd14f591706da3fa45b7b11faba127c07ec50b7 --- /dev/null +++ b/inferredbugs-3326/instruction.md @@ -0,0 +1,628 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-codec +**Bug ID:** 42 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.codec.binary; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Arrays; + +import org.junit.Test; + +/** + * @version $Id $ + * @since 1.4 + */ +public class Base64InputStreamTest { + + /** + * Decodes to {0, 0, 0, 255, 255, 255} + */ + private static final String ENCODED_B64 = "AAAA////"; + + private final static byte[] CRLF = { (byte) '\r', (byte) '\n' }; + + private final static byte[] LF = { (byte) '\n' }; + + private static final String STRING_FIXTURE = "Hello World"; + + /** + * Tests the problem reported in CODEC-130. Missing / wrong implementation of skip. + */ + @Test + public void testCodec130() throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + Base64OutputStream base64os = new Base64OutputStream(bos); + + base64os.write(StringUtils.getBytesUtf8(STRING_FIXTURE)); + base64os.close(); + + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + Base64InputStream ins = new Base64InputStream(bis); + + // we skip the first character read from the reader + ins.skip(1); + byte[] decodedBytes = Base64TestData.streamToBytes(ins, new byte[64]); + String str = StringUtils.newStringUtf8(decodedBytes); + + assertEquals(STRING_FIXTURE.substring(1), str); + } + + /** + * Tests the bug reported in CODEC-105. Bad interactions with InputStream when reading one byte at a time. + */ + @Test + public void testCodec105() throws IOException { + Base64InputStream in = new Base64InputStream(new Codec105ErrorInputStream(), true, 0, null); + try { + for (int i = 0; i < 5; i++) { + in.read(); + } + } finally { + in.close(); + } + } + + /** + * Test for the CODEC-101 bug: InputStream.read(byte[]) should never return 0 because Java's builtin InputStreamReader hates that. + * + * @throws Exception + * for some failure scenarios. + */ + @Test + public void testCodec101() throws Exception { + byte[] codec101 = StringUtils.getBytesUtf8(Base64TestData.CODEC_101_MULTIPLE_OF_3); + ByteArrayInputStream bais = new ByteArrayInputStream(codec101); + Base64InputStream in = new Base64InputStream(bais); + byte[] result = new byte[8192]; + int c = in.read(result); + assertTrue("Codec101: First read successful [c=" + c + "]", c > 0); + + c = in.read(result); + assertTrue("Codec101: Second read should report end-of-stream [c=" + c + "]", c < 0); + } + + /** + * Another test for the CODEC-101 bug: In commons-codec-1.4 this test shows InputStreamReader explicitly hating an + * InputStream.read(byte[]) return of 0: + * + * java.io.IOException: Underlying input stream returned zero bytes at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:268) at + * sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306) at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158) at + * java.io.InputStreamReader.read(InputStreamReader.java:167) at java.io.BufferedReader.fill(BufferedReader.java:136) at + * java.io.BufferedReader.readLine(BufferedReader.java:299) at java.io.BufferedReader.readLine(BufferedReader.java:362) at + * org.apache.commons.codec.binary.Base64InputStreamTest.testInputStreamReader(Base64InputStreamTest.java:75) + * + * But in commons-codec-1.5 it's fixed. :-) + * + * @throws Exception + * for some failure scenarios. + */ + @Test + public void testInputStreamReader() throws Exception { + byte[] codec101 = StringUtils.getBytesUtf8(Base64TestData.CODEC_101_MULTIPLE_OF_3); + ByteArrayInputStream bais = new ByteArrayInputStream(codec101); + Base64InputStream in = new Base64InputStream(bais); + InputStreamReader isr = new InputStreamReader(in); + BufferedReader br = new BufferedReader(isr); + String line = br.readLine(); + assertNotNull("Codec101: InputStreamReader works!", line); + } + + /** + * Test the Base64InputStream implementation against the special NPE inducing input identified in the CODEC-98 bug. + * + * @throws Exception + * for some failure scenarios. + */ + @Test + public void testCodec98NPE() throws Exception { + byte[] codec98 = StringUtils.getBytesUtf8(Base64TestData.CODEC_98_NPE); + ByteArrayInputStream data = new ByteArrayInputStream(codec98); + Base64InputStream stream = new Base64InputStream(data); + + // This line causes an NPE in commons-codec-1.4.jar: + byte[] decodedBytes = Base64TestData.streamToBytes(stream, new byte[1024]); + + String decoded = StringUtils.newStringUtf8(decodedBytes); + assertEquals("codec-98 NPE Base64InputStream", Base64TestData.CODEC_98_NPE_DECODED, decoded); + } + + /** + * Tests skipping past the end of a stream. + * + * @throws Throwable + */ + @Test + public void testAvailable() throws Throwable { + InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); + Base64InputStream b64stream = new Base64InputStream(ins); + assertEquals(1, b64stream.available()); + assertEquals(6, b64stream.skip(10)); + // End of stream reached + assertEquals(0, b64stream.available()); + assertEquals(-1, b64stream.read()); + assertEquals(-1, b64stream.read()); + assertEquals(0, b64stream.available()); + } + + /** + * Tests the Base64InputStream implementation against empty input. + * + * @throws Exception + * for some failure scenarios. + */ + @Test + public void testBase64EmptyInputStreamMimeChuckSize() throws Exception { + testBase64EmptyInputStream(BaseNCodec.MIME_CHUNK_SIZE); + } + + /** + * Tests the Base64InputStream implementation against empty input. + * + * @throws Exception + * for some failure scenarios. + */ + @Test + public void testBase64EmptyInputStreamPemChuckSize() throws Exception { + testBase64EmptyInputStream(BaseNCodec.PEM_CHUNK_SIZE); + } + + private void testBase64EmptyInputStream(int chuckSize) throws Exception { + byte[] emptyEncoded = new byte[0]; + byte[] emptyDecoded = new byte[0]; + testByteByByte(emptyEncoded, emptyDecoded, chuckSize, CRLF); + testByChunk(emptyEncoded, emptyDecoded, chuckSize, CRLF); + } + + /** + * Tests the Base64InputStream implementation. + * + * @throws Exception + * for some failure scenarios. + */ + @Test + public void testBase64InputStreamByChunk() throws Exception { + // Hello World test. + byte[] encoded = StringUtils.getBytesUtf8("SGVsbG8gV29ybGQ=\r\n"); + byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); + testByChunk(encoded, decoded, BaseNCodec.MIME_CHUNK_SIZE, CRLF); + + // Single Byte test. + encoded = StringUtils.getBytesUtf8("AA==\r\n"); + decoded = new byte[] { (byte) 0 }; + testByChunk(encoded, decoded, BaseNCodec.MIME_CHUNK_SIZE, CRLF); + + // OpenSSL interop test. + encoded = StringUtils.getBytesUtf8(Base64TestData.ENCODED_64_CHARS_PER_LINE); + decoded = Base64TestData.DECODED; + testByChunk(encoded, decoded, BaseNCodec.PEM_CHUNK_SIZE, LF); + + // Single Line test. + String singleLine = Base64TestData.ENCODED_64_CHARS_PER_LINE.replaceAll("\n", ""); + encoded = StringUtils.getBytesUtf8(singleLine); + decoded = Base64TestData.DECODED; + testByChunk(encoded, decoded, 0, LF); + + // test random data of sizes 0 thru 150 + for (int i = 0; i <= 150; i++) { + byte[][] randomData = Base64TestData.randomData(i, false); + encoded = randomData[1]; + decoded = randomData[0]; + testByChunk(encoded, decoded, 0, LF); + } + } + + /** + * Tests the Base64InputStream implementation. + * + * @throws Exception + * for some failure scenarios. + */ + @Test + public void testBase64InputStreamByteByByte() throws Exception { + // Hello World test. + byte[] encoded = StringUtils.getBytesUtf8("SGVsbG8gV29ybGQ=\r\n"); + byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); + testByteByByte(encoded, decoded, BaseNCodec.MIME_CHUNK_SIZE, CRLF); + + // Single Byte test. + encoded = StringUtils.getBytesUtf8("AA==\r\n"); + decoded = new byte[] { (byte) 0 }; + testByteByByte(encoded, decoded, BaseNCodec.MIME_CHUNK_SIZE, CRLF); + + // OpenSSL interop test. + encoded = StringUtils.getBytesUtf8(Base64TestData.ENCODED_64_CHARS_PER_LINE); + decoded = Base64TestData.DECODED; + testByteByByte(encoded, decoded, BaseNCodec.PEM_CHUNK_SIZE, LF); + + // Single Line test. + String singleLine = Base64TestData.ENCODED_64_CHARS_PER_LINE.replaceAll("\n", ""); + encoded = StringUtils.getBytesUtf8(singleLine); + decoded = Base64TestData.DECODED; + testByteByByte(encoded, decoded, 0, LF); + + // test random data of sizes 0 thru 150 + for (int i = 0; i <= 150; i++) { + byte[][] randomData = Base64TestData.randomData(i, false); + encoded = randomData[1]; + decoded = randomData[0]; + testByteByByte(encoded, decoded, 0, LF); + } + } + + /** + * Tests method does three tests on the supplied data: 1. encoded ---[DECODE]--> decoded 2. decoded ---[ENCODE]--> encoded 3. decoded + * ---[WRAP-WRAP-WRAP-etc...] --> decoded + *

    + * By "[WRAP-WRAP-WRAP-etc...]" we mean situation where the Base64InputStream wraps itself in encode and decode mode over and over + * again. + * + * @param encoded + * base64 encoded data + * @param decoded + * the data from above, but decoded + * @param chunkSize + * chunk size (line-length) of the base64 encoded data. + * @param seperator + * Line separator in the base64 encoded data. + * @throws Exception + * Usually signifies a bug in the Base64 commons-codec implementation. + */ + private void testByChunk(byte[] encoded, byte[] decoded, int chunkSize, byte[] seperator) throws Exception { + + // Start with encode. + InputStream in = new ByteArrayInputStream(decoded); + in = new Base64InputStream(in, true, chunkSize, seperator); + byte[] output = Base64TestData.streamToBytes(in); + + assertEquals("EOF", -1, in.read()); + assertEquals("Still EOF", -1, in.read()); + assertTrue("Streaming base64 encode", Arrays.equals(output, encoded)); + + // Now let's try decode. + in = new ByteArrayInputStream(encoded); + in = new Base64InputStream(in); + output = Base64TestData.streamToBytes(in); + + assertEquals("EOF", -1, in.read()); + assertEquals("Still EOF", -1, in.read()); + assertTrue("Streaming base64 decode", Arrays.equals(output, decoded)); + + // I always wanted to do this! (wrap encoder with decoder etc etc). + in = new ByteArrayInputStream(decoded); + for (int i = 0; i < 10; i++) { + in = new Base64InputStream(in, true, chunkSize, seperator); + in = new Base64InputStream(in, false); + } + output = Base64TestData.streamToBytes(in); + + assertEquals("EOF", -1, in.read()); + assertEquals("Still EOF", -1, in.read()); + assertTrue("Streaming base64 wrap-wrap-wrap!", Arrays.equals(output, decoded)); + } + + /** + * Tests method does three tests on the supplied data: 1. encoded ---[DECODE]--> decoded 2. decoded ---[ENCODE]--> encoded 3. decoded + * ---[WRAP-WRAP-WRAP-etc...] --> decoded + *

    + * By "[WRAP-WRAP-WRAP-etc...]" we mean situation where the Base64InputStream wraps itself in encode and decode mode over and over + * again. + * + * @param encoded + * base64 encoded data + * @param decoded + * the data from above, but decoded + * @param chunkSize + * chunk size (line-length) of the base64 encoded data. + * @param seperator + * Line separator in the base64 encoded data. + * @throws Exception + * Usually signifies a bug in the Base64 commons-codec implementation. + */ + private void testByteByByte(byte[] encoded, byte[] decoded, int chunkSize, byte[] seperator) throws Exception { + + // Start with encode. + InputStream in = new ByteArrayInputStream(decoded); + in = new Base64InputStream(in, true, chunkSize, seperator); + byte[] output = new byte[encoded.length]; + for (int i = 0; i < output.length; i++) { + output[i] = (byte) in.read(); + } + + assertEquals("EOF", -1, in.read()); + assertEquals("Still EOF", -1, in.read()); + assertTrue("Streaming base64 encode", Arrays.equals(output, encoded)); + + // Now let's try decode. + in = new ByteArrayInputStream(encoded); + in = new Base64InputStream(in); + output = new byte[decoded.length]; + for (int i = 0; i < output.length; i++) { + output[i] = (byte) in.read(); + } + + assertEquals("EOF", -1, in.read()); + assertEquals("Still EOF", -1, in.read()); + assertTrue("Streaming base64 decode", Arrays.equals(output, decoded)); + + // I always wanted to do this! (wrap encoder with decoder etc etc). + in = new ByteArrayInputStream(decoded); + for (int i = 0; i < 10; i++) { + in = new Base64InputStream(in, true, chunkSize, seperator); + in = new Base64InputStream(in, false); + } + output = new byte[decoded.length]; + for (int i = 0; i < output.length; i++) { + output[i] = (byte) in.read(); + } + + assertEquals("EOF", -1, in.read()); + assertEquals("Still EOF", -1, in.read()); + assertTrue("Streaming base64 wrap-wrap-wrap!", Arrays.equals(output, decoded)); + } + + /** + * Tests markSupported. + * + * @throws Exception + */ + @Test + public void testMarkSupported() throws Exception { + byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); + ByteArrayInputStream bin = new ByteArrayInputStream(decoded); + Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); + // Always returns false for now. + assertFalse("Base64InputStream.markSupported() is false", in.markSupported()); + } + + /** + * Tests read returning 0 + * + * @throws Exception + */ + @Test + public void testRead0() throws Exception { + byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); + byte[] buf = new byte[1024]; + int bytesRead = 0; + ByteArrayInputStream bin = new ByteArrayInputStream(decoded); + Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); + bytesRead = in.read(buf, 0, 0); + assertEquals("Base64InputStream.read(buf, 0, 0) returns 0", 0, bytesRead); + } + + /** + * Tests read with null. + * + * @throws Exception + * for some failure scenarios. + */ + @Test + public void testReadNull() throws Exception { + byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); + ByteArrayInputStream bin = new ByteArrayInputStream(decoded); + Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); + try { + in.read(null, 0, 0); + fail("Base64InputStream.read(null, 0, 0) to throw a NullPointerException"); + } catch (NullPointerException e) { + // Expected + } + } + + /** + * Tests read throwing IndexOutOfBoundsException + * + * @throws Exception + */ + @Test + public void testReadOutOfBounds() throws Exception { + byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); + byte[] buf = new byte[1024]; + ByteArrayInputStream bin = new ByteArrayInputStream(decoded); + Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); + + try { + in.read(buf, -1, 0); + fail("Expected Base64InputStream.read(buf, -1, 0) to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + in.read(buf, 0, -1); + fail("Expected Base64InputStream.read(buf, 0, -1) to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + in.read(buf, buf.length + 1, 0); + fail("Base64InputStream.read(buf, buf.length + 1, 0) throws IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + in.read(buf, buf.length - 1, 2); + fail("Base64InputStream.read(buf, buf.length - 1, 2) throws IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } + + /** + * Tests skipping number of characters larger than the internal buffer. + * + * @throws Throwable + */ + @Test + public void testSkipBig() throws Throwable { + InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); + Base64InputStream b64stream = new Base64InputStream(ins); + assertEquals(6, b64stream.skip(Integer.MAX_VALUE)); + // End of stream reached + assertEquals(-1, b64stream.read()); + assertEquals(-1, b64stream.read()); + } + + /** + * Tests skipping as a noop + * + * @throws Throwable + */ + @Test + public void testSkipNone() throws Throwable { + InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); + Base64InputStream b64stream = new Base64InputStream(ins); + byte[] actualBytes = new byte[6]; + assertEquals(0, b64stream.skip(0)); + b64stream.read(actualBytes, 0, actualBytes.length); + assertArrayEquals(actualBytes, new byte[] { 0, 0, 0, (byte) 255, (byte) 255, (byte) 255 }); + // End of stream reached + assertEquals(-1, b64stream.read()); + } + + /** + * Tests skipping past the end of a stream. + * + * @throws Throwable + */ + @Test + public void testSkipPastEnd() throws Throwable { + InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); + Base64InputStream b64stream = new Base64InputStream(ins); + // due to CODEC-130, skip now skips correctly decoded characters rather than encoded + assertEquals(6, b64stream.skip(10)); + // End of stream reached + assertEquals(-1, b64stream.read()); + assertEquals(-1, b64stream.read()); + } + + /** + * Tests skipping to the end of a stream. + * + * @throws Throwable + */ + @Test + public void testSkipToEnd() throws Throwable { + InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); + Base64InputStream b64stream = new Base64InputStream(ins); + // due to CODEC-130, skip now skips correctly decoded characters rather than encoded + assertEquals(6, b64stream.skip(6)); + // End of stream reached + assertEquals(-1, b64stream.read()); + assertEquals(-1, b64stream.read()); + } + + /** + * Tests if negative arguments to skip are handled correctly. + * + * @throws Throwable + */ + @Test(expected=IllegalArgumentException.class) + public void testSkipWrongArgument() throws Throwable { + InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); + Base64InputStream b64stream = new Base64InputStream(ins); + b64stream.skip(-10); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.codec.binary.Base64InputStream` acquired to `in` by call to `Base64InputStream(...)` at line 429 is not released after line 431. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Base64InputStreamTest.testReadNull() + +### Procedure Id: +org.apache.commons.codec.binary.Base64InputStreamTest.testReadNull():void.3c7e02960679f7309286752cf1fb4560 + +### File: +src/test/java/org/apache/commons/codec/binary/Base64InputStreamTest.java + +### Key: +Base64InputStreamTest.java|testReadNull|RESOURCE_LEAK + +### Node Key: +5533a9ebb24db4f5d91393d0b35659f5 + +### Hash: +f7947cee3005991714efc240682fd36a + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3328/instruction.md b/inferredbugs-3328/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..93d606dd7b7e0d9c1288aa4d0a2ed611f9e7812d --- /dev/null +++ b/inferredbugs-3328/instruction.md @@ -0,0 +1,1244 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-codec +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.codec.binary; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Random; + +import junit.framework.TestCase; + +import org.apache.commons.codec.DecoderException; +import org.apache.commons.codec.EncoderException; + +/** + * Test cases for Base64 class. + * + * @see RFC 2045 + * @author Apache Software Foundation + * @version $Id$ + */ +public class Base64Test extends TestCase { + + private Random _random = new Random(); + + /** + * Construct a new instance of this test case. + * + * @param name + * Name of the test case + */ + public Base64Test(String name) { + super(name); + } + + /** + * @return Returns the _random. + */ + public Random getRandom() { + return this._random; + } + + /** + * Test the Base64 implementation + */ + public void testBase64() { + String content = "Hello World"; + String encodedContent; + byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content)); + encodedContent = StringUtils.newStringUtf8(encodedBytes); + assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ=")); + + Base64 b64 = new Base64(Base64.MIME_CHUNK_SIZE, null); // null lineSeparator same as saying no-chunking + encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); + encodedContent = StringUtils.newStringUtf8(encodedBytes); + assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ=")); + + b64 = new Base64(0, null); // null lineSeparator same as saying no-chunking + encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); + encodedContent = StringUtils.newStringUtf8(encodedBytes); + assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ=")); + + // bogus characters to decode (to skip actually) + byte[] decode = b64.decode("SGVsbG{}8gV29ybGQ="); + String decodeString = StringUtils.newStringUtf8(decode); + assertTrue("decode hello world", decodeString.equals("Hello World")); + } + + /** + * Tests Base64.encodeBase64(). + */ + public void testChunkedEncodeMultipleOf76() { + byte[] expectedEncode = Base64.encodeBase64(Base64TestData.DECODED, true); + // convert to "\r\n" so we're equal to the old openssl encoding test stored + // in Base64TestData.ENCODED_76_CHARS_PER_LINE: + String actualResult = Base64TestData.ENCODED_76_CHARS_PER_LINE.replaceAll("\n", "\r\n"); + byte[] actualEncode = StringUtils.getBytesUtf8(actualResult); + assertTrue("chunkedEncodeMultipleOf76", Arrays.equals(expectedEncode, actualEncode)); + } + + /** + * CODEC-68: isBase64 throws ArrayIndexOutOfBoundsException on some non-BASE64 bytes + */ + public void testCodec68() { + byte[] x = new byte[]{'n', 'A', '=', '=', (byte) 0x9c}; + Base64.decodeBase64(x); + } + + public void testCodeInteger1() { + String encodedInt1 = "li7dzDacuo67Jg7mtqEm2TRuOMU="; + BigInteger bigInt1 = new BigInteger("85739377120809420210425962799" + "0318636601332086981"); + + assertEquals(encodedInt1, new String(Base64.encodeInteger(bigInt1))); + assertEquals(bigInt1, Base64.decodeInteger(encodedInt1.getBytes())); + } + + public void testCodeInteger2() { + String encodedInt2 = "9B5ypLY9pMOmtxCeTDHgwdNFeGs="; + BigInteger bigInt2 = new BigInteger("13936727572861167254666467268" + "91466679477132949611"); + + assertEquals(encodedInt2, new String(Base64.encodeInteger(bigInt2))); + assertEquals(bigInt2, Base64.decodeInteger(encodedInt2.getBytes())); + } + + public void testCodeInteger3() { + String encodedInt3 = "FKIhdgaG5LGKiEtF1vHy4f3y700zaD6QwDS3IrNVGzNp2" + "rY+1LFWTK6D44AyiC1n8uWz1itkYMZF0/aKDK0Yjg=="; + BigInteger bigInt3 = new BigInteger("10806548154093873461951748545" + + "1196989136416448805819079363524309897749044958112417136240557" + + "4495062430572478766856090958495998158114332651671116876320938126"); + + assertEquals(encodedInt3, new String(Base64.encodeInteger(bigInt3))); + assertEquals(bigInt3, Base64.decodeInteger(encodedInt3.getBytes())); + } + + public void testCodeInteger4() { + String encodedInt4 = "ctA8YGxrtngg/zKVvqEOefnwmViFztcnPBYPlJsvh6yKI" + + "4iDm68fnp4Mi3RrJ6bZAygFrUIQLxLjV+OJtgJAEto0xAs+Mehuq1DkSFEpP3o" + + "DzCTOsrOiS1DwQe4oIb7zVk/9l7aPtJMHW0LVlMdwZNFNNJoqMcT2ZfCPrfvYv" + + "Q0="; + BigInteger bigInt4 = new BigInteger("80624726256040348115552042320" + + "6968135001872753709424419772586693950232350200555646471175944" + + "519297087885987040810778908507262272892702303774422853675597" + + "748008534040890923814202286633163248086055216976551456088015" + + "338880713818192088877057717530169381044092839402438015097654" + + "53542091716518238707344493641683483917"); + + assertEquals(encodedInt4, new String(Base64.encodeInteger(bigInt4))); + assertEquals(bigInt4, Base64.decodeInteger(encodedInt4.getBytes())); + } + + public void testCodeIntegerEdgeCases() { + // TODO + } + + public void testCodeIntegerNull() { + try { + Base64.encodeInteger(null); + fail("Exception not thrown when passing in null to encodeInteger(BigInteger)"); + } catch (NullPointerException npe) { + // expected + } catch (Exception e) { + fail("Incorrect Exception caught when passing in null to encodeInteger(BigInteger)"); + } + } + + public void testConstructors() { + Base64 base64; + base64 = new Base64(); + base64 = new Base64(-1); + base64 = new Base64(-1, new byte[]{}); + base64 = new Base64(64, new byte[]{}); + try { + base64 = new Base64(-1, new byte[]{'A'}); + fail("Should have rejected attempt to use 'A' as a line separator"); + } catch (IllegalArgumentException ignored) { + // Expected + } + try { + base64 = new Base64(64, new byte[]{'A'}); + fail("Should have rejected attempt to use 'A' as a line separator"); + } catch (IllegalArgumentException ignored) { + // Expected + } + try { + base64 = new Base64(64, new byte[]{'='}); + fail("Should have rejected attempt to use '=' as a line separator"); + } catch (IllegalArgumentException ignored) { + // Expected + } + base64 = new Base64(64, new byte[]{'$'}); // OK + try { + base64 = new Base64(64, new byte[]{'A', '$'}); + fail("Should have rejected attempt to use 'A$' as a line separator"); + } catch (IllegalArgumentException ignored) { + // Expected + } + base64 = new Base64(64, new byte[]{' ', '$', '\n', '\r', '\t'}); // OK + } + + public void testConstructor_Int_ByteArray_Boolean() { + Base64 base64 = new Base64(65, new byte[]{'\t'}, false); + byte[] encoded = base64.encode(Base64TestData.DECODED); + String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE; + expectedResult = expectedResult.replace('\n', '\t'); + String result = StringUtils.newStringUtf8(encoded); + assertEquals("new Base64(65, \\t, false)", expectedResult, result); + } + + public void testConstructor_Int_ByteArray_Boolean_UrlSafe() { + // url-safe variation + Base64 base64 = new Base64(64, new byte[]{'\t'}, true); + byte[] encoded = base64.encode(Base64TestData.DECODED); + String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE; + expectedResult = expectedResult.replaceAll("=", ""); // url-safe has no == padding. + expectedResult = expectedResult.replace('\n', '\t'); + expectedResult = expectedResult.replace('+', '-'); + expectedResult = expectedResult.replace('/', '_'); + String result = StringUtils.newStringUtf8(encoded); + assertEquals("new Base64(64, \\t, true)", result, expectedResult); + } + + /** + * Tests conditional true branch for "marker0" test. + */ + public void testDecodePadMarkerIndex2() { + assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes()))); + } + + /** + * Tests conditional branches for "marker1" test. + */ + public void testDecodePadMarkerIndex3() { + assertEquals("AA", new String(Base64.decodeBase64("QUE=".getBytes()))); + assertEquals("AAA", new String(Base64.decodeBase64("QUFB".getBytes()))); + } + + public void testDecodePadOnly() { + assertTrue(Base64.decodeBase64("====".getBytes()).length == 0); + assertEquals("", new String(Base64.decodeBase64("====".getBytes()))); + // Test truncated padding + assertTrue(Base64.decodeBase64("===".getBytes()).length == 0); + assertTrue(Base64.decodeBase64("==".getBytes()).length == 0); + assertTrue(Base64.decodeBase64("=".getBytes()).length == 0); + assertTrue(Base64.decodeBase64("".getBytes()).length == 0); + } + + public void testDecodePadOnlyChunked() { + assertTrue(Base64.decodeBase64("====\n".getBytes()).length == 0); + assertEquals("", new String(Base64.decodeBase64("====\n".getBytes()))); + // Test truncated padding + assertTrue(Base64.decodeBase64("===\n".getBytes()).length == 0); + assertTrue(Base64.decodeBase64("==\n".getBytes()).length == 0); + assertTrue(Base64.decodeBase64("=\n".getBytes()).length == 0); + assertTrue(Base64.decodeBase64("\n".getBytes()).length == 0); + } + + public void testDecodeWithWhitespace() throws Exception { + + String orig = "I am a late night coder."; + + byte[] encodedArray = Base64.encodeBase64(orig.getBytes()); + StringBuffer intermediate = new StringBuffer(new String(encodedArray)); + + intermediate.insert(2, ' '); + intermediate.insert(5, '\t'); + intermediate.insert(10, '\r'); + intermediate.insert(15, '\n'); + + byte[] encodedWithWS = intermediate.toString().getBytes(); + byte[] decodedWithWS = Base64.decodeBase64(encodedWithWS); + + String dest = new String(decodedWithWS); + + assertTrue("Dest string doesn't equal the original", dest.equals(orig)); + } + + public void testDiscardWhitespace() throws Exception { + + String orig = "I am a late night coder."; + + byte[] encodedArray = Base64.encodeBase64(orig.getBytes()); + StringBuffer intermediate = new StringBuffer(new String(encodedArray)); + + intermediate.insert(2, ' '); + intermediate.insert(5, '\t'); + intermediate.insert(10, '\r'); + intermediate.insert(15, '\n'); + + byte[] encodedWithWS = intermediate.toString().getBytes(); + byte[] encodedNoWS = Base64.discardWhitespace(encodedWithWS); + byte[] decodedWithWS = Base64.decodeBase64(encodedWithWS); + byte[] decodedNoWS = Base64.decodeBase64(encodedNoWS); + + String destFromWS = new String(decodedWithWS); + String destFromNoWS = new String(decodedNoWS); + + assertTrue("Dest string doesn't equal original", destFromWS.equals(orig)); + assertTrue("Dest string doesn't equal original", destFromNoWS.equals(orig)); + } + + /** + * Test encode and decode of empty byte array. + */ + public void testEmptyBase64() { + byte[] empty = new byte[0]; + byte[] result = Base64.encodeBase64(empty); + assertEquals("empty base64 encode", 0, result.length); + assertEquals("empty base64 encode", null, Base64.encodeBase64(null)); + + empty = new byte[0]; + result = Base64.decodeBase64(empty); + assertEquals("empty base64 decode", 0, result.length); + assertEquals("empty base64 encode", null, Base64.decodeBase64((byte[]) null)); + } + + // encode/decode a large random array + public void testEncodeDecodeRandom() { + for (int i = 1; i < 5; i++) { + byte[] data = new byte[this.getRandom().nextInt(10000) + 1]; + this.getRandom().nextBytes(data); + byte[] enc = Base64.encodeBase64(data); + assertTrue(Base64.isArrayByteBase64(enc)); + byte[] data2 = Base64.decodeBase64(enc); + assertTrue(Arrays.equals(data, data2)); + } + } + + // encode/decode random arrays from size 0 to size 11 + public void testEncodeDecodeSmall() { + for (int i = 0; i < 12; i++) { + byte[] data = new byte[i]; + this.getRandom().nextBytes(data); + byte[] enc = Base64.encodeBase64(data); + assertTrue("\"" + (new String(enc)) + "\" is Base64 data.", Base64.isArrayByteBase64(enc)); + byte[] data2 = Base64.decodeBase64(enc); + assertTrue(toString(data) + " equals " + toString(data2), Arrays.equals(data, data2)); + } + } + + public void testEncodeOverMaxSize() throws Exception { + testEncodeOverMaxSize(-1); + testEncodeOverMaxSize(0); + testEncodeOverMaxSize(1); + testEncodeOverMaxSize(2); + } + + private void testEncodeOverMaxSize(int maxSize) throws Exception { + try { + Base64.encodeBase64(Base64TestData.DECODED, true, false, maxSize); + fail("Expected " + IllegalArgumentException.class.getName()); + } catch (IllegalArgumentException e) { + // Expceted + } + } + + public void testIgnoringNonBase64InDecode() throws Exception { + assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 + .decodeBase64("VGhlIH@$#$@%F1aWN@#@#@@rIGJyb3duIGZve\n\r\t%#%#%#%CBqd##$#$W1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes()))); + } + + public void testIsArrayByteBase64() { + assertFalse(Base64.isArrayByteBase64(new byte[]{Byte.MIN_VALUE})); + assertFalse(Base64.isArrayByteBase64(new byte[]{-125})); + assertFalse(Base64.isArrayByteBase64(new byte[]{-10})); + assertFalse(Base64.isArrayByteBase64(new byte[]{0})); + assertFalse(Base64.isArrayByteBase64(new byte[]{64, Byte.MAX_VALUE})); + assertFalse(Base64.isArrayByteBase64(new byte[]{Byte.MAX_VALUE})); + assertTrue(Base64.isArrayByteBase64(new byte[]{'A'})); + assertFalse(Base64.isArrayByteBase64(new byte[]{'A', Byte.MIN_VALUE})); + assertTrue(Base64.isArrayByteBase64(new byte[]{'A', 'Z', 'a'})); + assertTrue(Base64.isArrayByteBase64(new byte[]{'/', '=', '+'})); + assertFalse(Base64.isArrayByteBase64(new byte[]{'$'})); + } + + /** + * Tests isUrlSafe. + */ + public void testIsUrlSafe() { + Base64 base64Standard = new Base64(false); + Base64 base64URLSafe = new Base64(true); + + assertFalse("Base64.isUrlSafe=false", base64Standard.isUrlSafe()); + assertTrue("Base64.isUrlSafe=true", base64URLSafe.isUrlSafe()); + + byte[] whiteSpace = {' ', '\n', '\r', '\t'}; + assertTrue("Base64.isArrayByteBase64(whiteSpace)=true", Base64.isArrayByteBase64(whiteSpace)); + } + + public void testKnownDecodings() { + assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 + .decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes()))); + assertEquals("It was the best of times, it was the worst of times.", new String(Base64 + .decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes()))); + assertEquals("http://jakarta.apache.org/commmons", new String(Base64 + .decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes()))); + assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64 + .decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes()))); + assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=" + .getBytes()))); + assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes()))); + } + + public void testKnownEncodings() { + assertEquals("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==", new String(Base64 + .encodeBase64("The quick brown fox jumped over the lazy dogs.".getBytes()))); + assertEquals( + "YmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJs\r\nYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFo\r\nIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBi\r\nbGFoIGJsYWg=\r\n", + new String( + Base64 + .encodeBase64Chunked("blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah" + .getBytes()))); + assertEquals("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==", new String(Base64 + .encodeBase64("It was the best of times, it was the worst of times.".getBytes()))); + assertEquals("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==", new String(Base64 + .encodeBase64("http://jakarta.apache.org/commmons".getBytes()))); + assertEquals("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==", new String(Base64 + .encodeBase64("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".getBytes()))); + assertEquals("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=", new String(Base64.encodeBase64("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }" + .getBytes()))); + assertEquals("eHl6enkh", new String(Base64.encodeBase64("xyzzy!".getBytes()))); + } + + public void testNonBase64Test() throws Exception { + + byte[] bArray = {'%'}; + + assertFalse("Invalid Base64 array was incorrectly validated as " + "an array of Base64 encoded data", Base64 + .isArrayByteBase64(bArray)); + + try { + Base64 b64 = new Base64(); + byte[] result = b64.decode(bArray); + + assertTrue("The result should be empty as the test encoded content did " + "not contain any valid base 64 characters", + result.length == 0); + } catch (Exception e) { + fail("Exception was thrown when trying to decode " + + "invalid base64 encoded data - RFC 2045 requires that all " + + "non base64 character be discarded, an exception should not" + + " have been thrown"); + } + } + + public void testObjectDecodeWithInvalidParameter() throws Exception { + Base64 b64 = new Base64(); + + try { + b64.decode(new Integer(5)); + fail("decode(Object) didn't throw an exception when passed an Integer object"); + } catch (DecoderException e) { + // ignored + } + + } + + public void testObjectDecodeWithValidParameter() throws Exception { + + String original = "Hello World!"; + Object o = Base64.encodeBase64(original.getBytes()); + + Base64 b64 = new Base64(); + Object oDecoded = b64.decode(o); + byte[] baDecoded = (byte[]) oDecoded; + String dest = new String(baDecoded); + + assertTrue("dest string does not equal original", dest.equals(original)); + } + + public void testObjectEncodeWithInvalidParameter() throws Exception { + Base64 b64 = new Base64(); + try { + b64.encode("Yadayadayada"); + fail("encode(Object) didn't throw an exception when passed a String object"); + } catch (EncoderException e) { + // Expected + } + } + + public void testObjectEncodeWithValidParameter() throws Exception { + + String original = "Hello World!"; + Object origObj = original.getBytes(); + + Base64 b64 = new Base64(); + Object oEncoded = b64.encode(origObj); + byte[] bArray = Base64.decodeBase64((byte[]) oEncoded); + String dest = new String(bArray); + + assertTrue("dest string does not equal original", dest.equals(original)); + } + + public void testObjectEncode() throws Exception { + Base64 b64 = new Base64(); + assertEquals("SGVsbG8gV29ybGQ=", new String(b64.encode("Hello World".getBytes("UTF-8")))); + } + + public void testPairs() { + assertEquals("AAA=", new String(Base64.encodeBase64(new byte[]{0, 0}))); + for (int i = -128; i <= 127; i++) { + byte test[] = {(byte) i, (byte) i}; + assertTrue(Arrays.equals(test, Base64.decodeBase64(Base64.encodeBase64(test)))); + } + } + + /** + * Tests RFC 2045 section 2.1 CRLF definition. + */ + public void testRfc2045Section2Dot1CrLfDefinition() { + assertTrue(Arrays.equals(new byte[]{13, 10}, Base64.CHUNK_SEPARATOR)); + } + + /** + * Tests RFC 2045 section 6.8 chuck size definition. + */ + public void testRfc2045Section6Dot8ChunkSizeDefinition() { + assertEquals(76, Base64.MIME_CHUNK_SIZE); + } + + /** + * Tests RFC 1421 section 4.3.2.4 chuck size definition. + */ + public void testRfc1421Section6Dot8ChunkSizeDefinition() { + assertEquals(64, Base64.PEM_CHUNK_SIZE); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *

      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + public void testRfc4648Section10Decode() { + assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64(""))); + assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg=="))); + assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8="))); + assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v"))); + assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg=="))); + assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE="))); + assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy"))); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *
      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + public void testRfc4648Section10DecodeWithCrLf() { + String CRLF = StringUtils.newStringUsAscii(Base64.CHUNK_SEPARATOR); + assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64("" + CRLF))); + assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg==" + CRLF))); + assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8=" + CRLF))); + assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v" + CRLF))); + assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg==" + CRLF))); + assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE=" + CRLF))); + assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy" + CRLF))); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *
      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + public void testRfc4648Section10Encode() { + assertEquals("", Base64.encodeBase64String(StringUtils.getBytesUtf8(""))); + //assertEquals("Zg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("f"))); + //assertEquals("Zm8=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fo"))); + //assertEquals("Zm9v", Base64.encodeBase64String(StringUtils.getBytesUtf8("foo"))); + //assertEquals("Zm9vYg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("foob"))); + //assertEquals("Zm9vYmE=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fooba"))); + //assertEquals("Zm9vYmFy", Base64.encodeBase64String(StringUtils.getBytesUtf8("foobar"))); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *
      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + public void testRfc4648Section10DecodeEncode() { + testDecodeEncode(""); + //testDecodeEncode("Zg=="); + //testDecodeEncode("Zm8="); + //testDecodeEncode("Zm9v"); + //testDecodeEncode("Zm9vYg=="); + //testDecodeEncode("Zm9vYmE="); + //testDecodeEncode("Zm9vYmFy"); + } + + private void testDecodeEncode(String encodedText) { + String decodedText = StringUtils.newStringUsAscii(Base64.decodeBase64(encodedText)); + String encodedText2 = Base64.encodeBase64String(StringUtils.getBytesUtf8(decodedText)); + assertEquals(encodedText, encodedText2); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *
      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + public void testRfc4648Section10EncodeDecode() { + testEncodeDecode(""); + testEncodeDecode("f"); + testEncodeDecode("fo"); + testEncodeDecode("foo"); + testEncodeDecode("foob"); + testEncodeDecode("fooba"); + testEncodeDecode("foobar"); + } + + private void testEncodeDecode(String plainText) { + String encodedText = Base64.encodeBase64String(StringUtils.getBytesUtf8(plainText)); + String decodedText = StringUtils.newStringUsAscii(Base64.decodeBase64(encodedText)); + assertEquals(plainText, decodedText); + } + + public void testSingletons() { + assertEquals("AA==", new String(Base64.encodeBase64(new byte[]{(byte) 0}))); + assertEquals("AQ==", new String(Base64.encodeBase64(new byte[]{(byte) 1}))); + assertEquals("Ag==", new String(Base64.encodeBase64(new byte[]{(byte) 2}))); + assertEquals("Aw==", new String(Base64.encodeBase64(new byte[]{(byte) 3}))); + assertEquals("BA==", new String(Base64.encodeBase64(new byte[]{(byte) 4}))); + assertEquals("BQ==", new String(Base64.encodeBase64(new byte[]{(byte) 5}))); + assertEquals("Bg==", new String(Base64.encodeBase64(new byte[]{(byte) 6}))); + assertEquals("Bw==", new String(Base64.encodeBase64(new byte[]{(byte) 7}))); + assertEquals("CA==", new String(Base64.encodeBase64(new byte[]{(byte) 8}))); + assertEquals("CQ==", new String(Base64.encodeBase64(new byte[]{(byte) 9}))); + assertEquals("Cg==", new String(Base64.encodeBase64(new byte[]{(byte) 10}))); + assertEquals("Cw==", new String(Base64.encodeBase64(new byte[]{(byte) 11}))); + assertEquals("DA==", new String(Base64.encodeBase64(new byte[]{(byte) 12}))); + assertEquals("DQ==", new String(Base64.encodeBase64(new byte[]{(byte) 13}))); + assertEquals("Dg==", new String(Base64.encodeBase64(new byte[]{(byte) 14}))); + assertEquals("Dw==", new String(Base64.encodeBase64(new byte[]{(byte) 15}))); + assertEquals("EA==", new String(Base64.encodeBase64(new byte[]{(byte) 16}))); + assertEquals("EQ==", new String(Base64.encodeBase64(new byte[]{(byte) 17}))); + assertEquals("Eg==", new String(Base64.encodeBase64(new byte[]{(byte) 18}))); + assertEquals("Ew==", new String(Base64.encodeBase64(new byte[]{(byte) 19}))); + assertEquals("FA==", new String(Base64.encodeBase64(new byte[]{(byte) 20}))); + assertEquals("FQ==", new String(Base64.encodeBase64(new byte[]{(byte) 21}))); + assertEquals("Fg==", new String(Base64.encodeBase64(new byte[]{(byte) 22}))); + assertEquals("Fw==", new String(Base64.encodeBase64(new byte[]{(byte) 23}))); + assertEquals("GA==", new String(Base64.encodeBase64(new byte[]{(byte) 24}))); + assertEquals("GQ==", new String(Base64.encodeBase64(new byte[]{(byte) 25}))); + assertEquals("Gg==", new String(Base64.encodeBase64(new byte[]{(byte) 26}))); + assertEquals("Gw==", new String(Base64.encodeBase64(new byte[]{(byte) 27}))); + assertEquals("HA==", new String(Base64.encodeBase64(new byte[]{(byte) 28}))); + assertEquals("HQ==", new String(Base64.encodeBase64(new byte[]{(byte) 29}))); + assertEquals("Hg==", new String(Base64.encodeBase64(new byte[]{(byte) 30}))); + assertEquals("Hw==", new String(Base64.encodeBase64(new byte[]{(byte) 31}))); + assertEquals("IA==", new String(Base64.encodeBase64(new byte[]{(byte) 32}))); + assertEquals("IQ==", new String(Base64.encodeBase64(new byte[]{(byte) 33}))); + assertEquals("Ig==", new String(Base64.encodeBase64(new byte[]{(byte) 34}))); + assertEquals("Iw==", new String(Base64.encodeBase64(new byte[]{(byte) 35}))); + assertEquals("JA==", new String(Base64.encodeBase64(new byte[]{(byte) 36}))); + assertEquals("JQ==", new String(Base64.encodeBase64(new byte[]{(byte) 37}))); + assertEquals("Jg==", new String(Base64.encodeBase64(new byte[]{(byte) 38}))); + assertEquals("Jw==", new String(Base64.encodeBase64(new byte[]{(byte) 39}))); + assertEquals("KA==", new String(Base64.encodeBase64(new byte[]{(byte) 40}))); + assertEquals("KQ==", new String(Base64.encodeBase64(new byte[]{(byte) 41}))); + assertEquals("Kg==", new String(Base64.encodeBase64(new byte[]{(byte) 42}))); + assertEquals("Kw==", new String(Base64.encodeBase64(new byte[]{(byte) 43}))); + assertEquals("LA==", new String(Base64.encodeBase64(new byte[]{(byte) 44}))); + assertEquals("LQ==", new String(Base64.encodeBase64(new byte[]{(byte) 45}))); + assertEquals("Lg==", new String(Base64.encodeBase64(new byte[]{(byte) 46}))); + assertEquals("Lw==", new String(Base64.encodeBase64(new byte[]{(byte) 47}))); + assertEquals("MA==", new String(Base64.encodeBase64(new byte[]{(byte) 48}))); + assertEquals("MQ==", new String(Base64.encodeBase64(new byte[]{(byte) 49}))); + assertEquals("Mg==", new String(Base64.encodeBase64(new byte[]{(byte) 50}))); + assertEquals("Mw==", new String(Base64.encodeBase64(new byte[]{(byte) 51}))); + assertEquals("NA==", new String(Base64.encodeBase64(new byte[]{(byte) 52}))); + assertEquals("NQ==", new String(Base64.encodeBase64(new byte[]{(byte) 53}))); + assertEquals("Ng==", new String(Base64.encodeBase64(new byte[]{(byte) 54}))); + assertEquals("Nw==", new String(Base64.encodeBase64(new byte[]{(byte) 55}))); + assertEquals("OA==", new String(Base64.encodeBase64(new byte[]{(byte) 56}))); + assertEquals("OQ==", new String(Base64.encodeBase64(new byte[]{(byte) 57}))); + assertEquals("Og==", new String(Base64.encodeBase64(new byte[]{(byte) 58}))); + assertEquals("Ow==", new String(Base64.encodeBase64(new byte[]{(byte) 59}))); + assertEquals("PA==", new String(Base64.encodeBase64(new byte[]{(byte) 60}))); + assertEquals("PQ==", new String(Base64.encodeBase64(new byte[]{(byte) 61}))); + assertEquals("Pg==", new String(Base64.encodeBase64(new byte[]{(byte) 62}))); + assertEquals("Pw==", new String(Base64.encodeBase64(new byte[]{(byte) 63}))); + assertEquals("QA==", new String(Base64.encodeBase64(new byte[]{(byte) 64}))); + assertEquals("QQ==", new String(Base64.encodeBase64(new byte[]{(byte) 65}))); + assertEquals("Qg==", new String(Base64.encodeBase64(new byte[]{(byte) 66}))); + assertEquals("Qw==", new String(Base64.encodeBase64(new byte[]{(byte) 67}))); + assertEquals("RA==", new String(Base64.encodeBase64(new byte[]{(byte) 68}))); + assertEquals("RQ==", new String(Base64.encodeBase64(new byte[]{(byte) 69}))); + assertEquals("Rg==", new String(Base64.encodeBase64(new byte[]{(byte) 70}))); + assertEquals("Rw==", new String(Base64.encodeBase64(new byte[]{(byte) 71}))); + assertEquals("SA==", new String(Base64.encodeBase64(new byte[]{(byte) 72}))); + assertEquals("SQ==", new String(Base64.encodeBase64(new byte[]{(byte) 73}))); + assertEquals("Sg==", new String(Base64.encodeBase64(new byte[]{(byte) 74}))); + assertEquals("Sw==", new String(Base64.encodeBase64(new byte[]{(byte) 75}))); + assertEquals("TA==", new String(Base64.encodeBase64(new byte[]{(byte) 76}))); + assertEquals("TQ==", new String(Base64.encodeBase64(new byte[]{(byte) 77}))); + assertEquals("Tg==", new String(Base64.encodeBase64(new byte[]{(byte) 78}))); + assertEquals("Tw==", new String(Base64.encodeBase64(new byte[]{(byte) 79}))); + assertEquals("UA==", new String(Base64.encodeBase64(new byte[]{(byte) 80}))); + assertEquals("UQ==", new String(Base64.encodeBase64(new byte[]{(byte) 81}))); + assertEquals("Ug==", new String(Base64.encodeBase64(new byte[]{(byte) 82}))); + assertEquals("Uw==", new String(Base64.encodeBase64(new byte[]{(byte) 83}))); + assertEquals("VA==", new String(Base64.encodeBase64(new byte[]{(byte) 84}))); + assertEquals("VQ==", new String(Base64.encodeBase64(new byte[]{(byte) 85}))); + assertEquals("Vg==", new String(Base64.encodeBase64(new byte[]{(byte) 86}))); + assertEquals("Vw==", new String(Base64.encodeBase64(new byte[]{(byte) 87}))); + assertEquals("WA==", new String(Base64.encodeBase64(new byte[]{(byte) 88}))); + assertEquals("WQ==", new String(Base64.encodeBase64(new byte[]{(byte) 89}))); + assertEquals("Wg==", new String(Base64.encodeBase64(new byte[]{(byte) 90}))); + assertEquals("Ww==", new String(Base64.encodeBase64(new byte[]{(byte) 91}))); + assertEquals("XA==", new String(Base64.encodeBase64(new byte[]{(byte) 92}))); + assertEquals("XQ==", new String(Base64.encodeBase64(new byte[]{(byte) 93}))); + assertEquals("Xg==", new String(Base64.encodeBase64(new byte[]{(byte) 94}))); + assertEquals("Xw==", new String(Base64.encodeBase64(new byte[]{(byte) 95}))); + assertEquals("YA==", new String(Base64.encodeBase64(new byte[]{(byte) 96}))); + assertEquals("YQ==", new String(Base64.encodeBase64(new byte[]{(byte) 97}))); + assertEquals("Yg==", new String(Base64.encodeBase64(new byte[]{(byte) 98}))); + assertEquals("Yw==", new String(Base64.encodeBase64(new byte[]{(byte) 99}))); + assertEquals("ZA==", new String(Base64.encodeBase64(new byte[]{(byte) 100}))); + assertEquals("ZQ==", new String(Base64.encodeBase64(new byte[]{(byte) 101}))); + assertEquals("Zg==", new String(Base64.encodeBase64(new byte[]{(byte) 102}))); + assertEquals("Zw==", new String(Base64.encodeBase64(new byte[]{(byte) 103}))); + assertEquals("aA==", new String(Base64.encodeBase64(new byte[]{(byte) 104}))); + for (int i = -128; i <= 127; i++) { + byte test[] = {(byte) i}; + assertTrue(Arrays.equals(test, Base64.decodeBase64(Base64.encodeBase64(test)))); + } + } + + public void testSingletonsChunked() { + assertEquals("AA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0}))); + assertEquals("AQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 1}))); + assertEquals("Ag==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 2}))); + assertEquals("Aw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 3}))); + assertEquals("BA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 4}))); + assertEquals("BQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 5}))); + assertEquals("Bg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 6}))); + assertEquals("Bw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 7}))); + assertEquals("CA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 8}))); + assertEquals("CQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 9}))); + assertEquals("Cg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 10}))); + assertEquals("Cw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 11}))); + assertEquals("DA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 12}))); + assertEquals("DQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 13}))); + assertEquals("Dg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 14}))); + assertEquals("Dw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 15}))); + assertEquals("EA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 16}))); + assertEquals("EQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 17}))); + assertEquals("Eg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 18}))); + assertEquals("Ew==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 19}))); + assertEquals("FA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 20}))); + assertEquals("FQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 21}))); + assertEquals("Fg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 22}))); + assertEquals("Fw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 23}))); + assertEquals("GA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 24}))); + assertEquals("GQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 25}))); + assertEquals("Gg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 26}))); + assertEquals("Gw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 27}))); + assertEquals("HA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 28}))); + assertEquals("HQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 29}))); + assertEquals("Hg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 30}))); + assertEquals("Hw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 31}))); + assertEquals("IA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 32}))); + assertEquals("IQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 33}))); + assertEquals("Ig==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 34}))); + assertEquals("Iw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 35}))); + assertEquals("JA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 36}))); + assertEquals("JQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 37}))); + assertEquals("Jg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 38}))); + assertEquals("Jw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 39}))); + assertEquals("KA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 40}))); + assertEquals("KQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 41}))); + assertEquals("Kg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 42}))); + assertEquals("Kw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 43}))); + assertEquals("LA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 44}))); + assertEquals("LQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 45}))); + assertEquals("Lg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 46}))); + assertEquals("Lw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 47}))); + assertEquals("MA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 48}))); + assertEquals("MQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 49}))); + assertEquals("Mg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 50}))); + assertEquals("Mw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 51}))); + assertEquals("NA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 52}))); + assertEquals("NQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 53}))); + assertEquals("Ng==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 54}))); + assertEquals("Nw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 55}))); + assertEquals("OA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 56}))); + assertEquals("OQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 57}))); + assertEquals("Og==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 58}))); + assertEquals("Ow==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 59}))); + assertEquals("PA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 60}))); + assertEquals("PQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 61}))); + assertEquals("Pg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 62}))); + assertEquals("Pw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 63}))); + assertEquals("QA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 64}))); + assertEquals("QQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 65}))); + assertEquals("Qg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 66}))); + assertEquals("Qw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 67}))); + assertEquals("RA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 68}))); + assertEquals("RQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 69}))); + assertEquals("Rg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 70}))); + assertEquals("Rw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 71}))); + assertEquals("SA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 72}))); + assertEquals("SQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 73}))); + assertEquals("Sg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 74}))); + assertEquals("Sw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 75}))); + assertEquals("TA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 76}))); + assertEquals("TQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 77}))); + assertEquals("Tg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 78}))); + assertEquals("Tw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 79}))); + assertEquals("UA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 80}))); + assertEquals("UQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 81}))); + assertEquals("Ug==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 82}))); + assertEquals("Uw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 83}))); + assertEquals("VA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 84}))); + assertEquals("VQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 85}))); + assertEquals("Vg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 86}))); + assertEquals("Vw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 87}))); + assertEquals("WA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 88}))); + assertEquals("WQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 89}))); + assertEquals("Wg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 90}))); + assertEquals("Ww==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 91}))); + assertEquals("XA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 92}))); + assertEquals("XQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 93}))); + assertEquals("Xg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 94}))); + assertEquals("Xw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 95}))); + assertEquals("YA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 96}))); + assertEquals("YQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 97}))); + assertEquals("Yg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 98}))); + assertEquals("Yw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 99}))); + assertEquals("ZA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 100}))); + assertEquals("ZQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 101}))); + assertEquals("Zg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 102}))); + assertEquals("Zw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 103}))); + assertEquals("aA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 104}))); + } + + public void testTriplets() { + assertEquals("AAAA", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 0}))); + assertEquals("AAAB", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 1}))); + assertEquals("AAAC", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 2}))); + assertEquals("AAAD", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 3}))); + assertEquals("AAAE", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 4}))); + assertEquals("AAAF", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 5}))); + assertEquals("AAAG", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 6}))); + assertEquals("AAAH", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 7}))); + assertEquals("AAAI", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 8}))); + assertEquals("AAAJ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 9}))); + assertEquals("AAAK", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 10}))); + assertEquals("AAAL", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 11}))); + assertEquals("AAAM", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 12}))); + assertEquals("AAAN", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 13}))); + assertEquals("AAAO", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 14}))); + assertEquals("AAAP", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 15}))); + assertEquals("AAAQ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 16}))); + assertEquals("AAAR", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 17}))); + assertEquals("AAAS", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 18}))); + assertEquals("AAAT", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 19}))); + assertEquals("AAAU", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 20}))); + assertEquals("AAAV", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 21}))); + assertEquals("AAAW", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 22}))); + assertEquals("AAAX", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 23}))); + assertEquals("AAAY", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 24}))); + assertEquals("AAAZ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 25}))); + assertEquals("AAAa", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 26}))); + assertEquals("AAAb", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 27}))); + assertEquals("AAAc", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 28}))); + assertEquals("AAAd", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 29}))); + assertEquals("AAAe", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 30}))); + assertEquals("AAAf", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 31}))); + assertEquals("AAAg", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 32}))); + assertEquals("AAAh", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 33}))); + assertEquals("AAAi", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 34}))); + assertEquals("AAAj", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 35}))); + assertEquals("AAAk", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 36}))); + assertEquals("AAAl", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 37}))); + assertEquals("AAAm", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 38}))); + assertEquals("AAAn", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 39}))); + assertEquals("AAAo", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 40}))); + assertEquals("AAAp", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 41}))); + assertEquals("AAAq", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 42}))); + assertEquals("AAAr", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 43}))); + assertEquals("AAAs", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 44}))); + assertEquals("AAAt", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 45}))); + assertEquals("AAAu", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 46}))); + assertEquals("AAAv", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 47}))); + assertEquals("AAAw", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 48}))); + assertEquals("AAAx", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 49}))); + assertEquals("AAAy", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 50}))); + assertEquals("AAAz", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 51}))); + assertEquals("AAA0", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 52}))); + assertEquals("AAA1", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 53}))); + assertEquals("AAA2", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 54}))); + assertEquals("AAA3", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 55}))); + assertEquals("AAA4", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 56}))); + assertEquals("AAA5", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 57}))); + assertEquals("AAA6", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 58}))); + assertEquals("AAA7", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 59}))); + assertEquals("AAA8", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 60}))); + assertEquals("AAA9", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 61}))); + assertEquals("AAA+", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 62}))); + assertEquals("AAA/", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 63}))); + } + + public void testTripletsChunked() { + assertEquals("AAAA\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 0}))); + assertEquals("AAAB\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 1}))); + assertEquals("AAAC\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 2}))); + assertEquals("AAAD\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 3}))); + assertEquals("AAAE\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 4}))); + assertEquals("AAAF\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 5}))); + assertEquals("AAAG\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 6}))); + assertEquals("AAAH\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 7}))); + assertEquals("AAAI\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 8}))); + assertEquals("AAAJ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 9}))); + assertEquals("AAAK\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 10}))); + assertEquals("AAAL\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 11}))); + assertEquals("AAAM\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 12}))); + assertEquals("AAAN\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 13}))); + assertEquals("AAAO\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 14}))); + assertEquals("AAAP\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 15}))); + assertEquals("AAAQ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 16}))); + assertEquals("AAAR\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 17}))); + assertEquals("AAAS\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 18}))); + assertEquals("AAAT\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 19}))); + assertEquals("AAAU\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 20}))); + assertEquals("AAAV\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 21}))); + assertEquals("AAAW\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 22}))); + assertEquals("AAAX\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 23}))); + assertEquals("AAAY\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 24}))); + assertEquals("AAAZ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 25}))); + assertEquals("AAAa\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 26}))); + assertEquals("AAAb\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 27}))); + assertEquals("AAAc\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 28}))); + assertEquals("AAAd\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 29}))); + assertEquals("AAAe\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 30}))); + assertEquals("AAAf\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 31}))); + assertEquals("AAAg\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 32}))); + assertEquals("AAAh\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 33}))); + assertEquals("AAAi\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 34}))); + assertEquals("AAAj\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 35}))); + assertEquals("AAAk\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 36}))); + assertEquals("AAAl\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 37}))); + assertEquals("AAAm\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 38}))); + assertEquals("AAAn\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 39}))); + assertEquals("AAAo\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 40}))); + assertEquals("AAAp\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 41}))); + assertEquals("AAAq\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 42}))); + assertEquals("AAAr\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 43}))); + assertEquals("AAAs\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 44}))); + assertEquals("AAAt\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 45}))); + assertEquals("AAAu\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 46}))); + assertEquals("AAAv\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 47}))); + assertEquals("AAAw\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 48}))); + assertEquals("AAAx\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 49}))); + assertEquals("AAAy\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 50}))); + assertEquals("AAAz\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 51}))); + assertEquals("AAA0\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 52}))); + assertEquals("AAA1\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 53}))); + assertEquals("AAA2\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 54}))); + assertEquals("AAA3\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 55}))); + assertEquals("AAA4\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 56}))); + assertEquals("AAA5\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 57}))); + assertEquals("AAA6\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 58}))); + assertEquals("AAA7\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 59}))); + assertEquals("AAA8\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 60}))); + assertEquals("AAA9\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 61}))); + assertEquals("AAA+\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 62}))); + assertEquals("AAA/\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 63}))); + } + + /** + * Tests url-safe Base64 against random data, sizes 0 to 150. + */ + public void testUrlSafe() { + // test random data of sizes 0 thru 150 + for (int i = 0; i <= 150; i++) { + byte[][] randomData = Base64TestData.randomData(i, true); + byte[] encoded = randomData[1]; + byte[] decoded = randomData[0]; + byte[] result = Base64.decodeBase64(encoded); + assertTrue("url-safe i=" + i, Arrays.equals(decoded, result)); + assertFalse("url-safe i=" + i + " no '='", Base64TestData.bytesContain(encoded, (byte) '=')); + assertFalse("url-safe i=" + i + " no '\\'", Base64TestData.bytesContain(encoded, (byte) '\\')); + assertFalse("url-safe i=" + i + " no '+'", Base64TestData.bytesContain(encoded, (byte) '+')); + } + + } + + /** + * Base64 encoding of UUID's is a common use-case, especially in URL-SAFE mode. This test case ends up being the + * "URL-SAFE" JUnit's. + * + * @throws DecoderException + * if Hex.decode() fails - a serious problem since Hex comes from our own commons-codec! + */ + public void testUUID() throws DecoderException { + // The 4 UUID's below contains mixtures of + and / to help us test the + // URL-SAFE encoding mode. + byte[][] ids = new byte[4][]; + + // ids[0] was chosen so that it encodes with at least one +. + ids[0] = Hex.decodeHex("94ed8d0319e4493399560fb67404d370".toCharArray()); + + // ids[1] was chosen so that it encodes with both / and +. + ids[1] = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray()); + + // ids[2] was chosen so that it encodes with at least one /. + ids[2] = Hex.decodeHex("64be154b6ffa40258d1a01288e7c31ca".toCharArray()); + + // ids[3] was chosen so that it encodes with both / and +, with / + // right at the beginning. + ids[3] = Hex.decodeHex("ff7f8fc01cdb471a8c8b5a9306183fe8".toCharArray()); + + byte[][] standard = new byte[4][]; + standard[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg+2dATTcA=="); + standard[1] = StringUtils.getBytesUtf8("K/fMJwH+Q5e0nr7tWsxwkA=="); + standard[2] = StringUtils.getBytesUtf8("ZL4VS2/6QCWNGgEojnwxyg=="); + standard[3] = StringUtils.getBytesUtf8("/3+PwBzbRxqMi1qTBhg/6A=="); + + byte[][] urlSafe1 = new byte[4][]; + // regular padding (two '==' signs). + urlSafe1[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA=="); + urlSafe1[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA=="); + urlSafe1[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg=="); + urlSafe1[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A=="); + + byte[][] urlSafe2 = new byte[4][]; + // single padding (only one '=' sign). + urlSafe2[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA="); + urlSafe2[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA="); + urlSafe2[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg="); + urlSafe2[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A="); + + byte[][] urlSafe3 = new byte[4][]; + // no padding (no '=' signs). + urlSafe3[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA"); + urlSafe3[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA"); + urlSafe3[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg"); + urlSafe3[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A"); + + for (int i = 0; i < 4; i++) { + byte[] encodedStandard = Base64.encodeBase64(ids[i]); + byte[] encodedUrlSafe = Base64.encodeBase64URLSafe(ids[i]); + byte[] decodedStandard = Base64.decodeBase64(standard[i]); + byte[] decodedUrlSafe1 = Base64.decodeBase64(urlSafe1[i]); + byte[] decodedUrlSafe2 = Base64.decodeBase64(urlSafe2[i]); + byte[] decodedUrlSafe3 = Base64.decodeBase64(urlSafe3[i]); + + // Very important debugging output should anyone + // ever need to delve closely into this stuff. + if (false) { + System.out.println("reference: [" + Hex.encodeHexString(ids[i]) + "]"); + System.out.println("standard: [" + + Hex.encodeHexString(decodedStandard) + + "] From: [" + + StringUtils.newStringUtf8(standard[i]) + + "]"); + System.out.println("safe1: [" + + Hex.encodeHexString(decodedUrlSafe1) + + "] From: [" + + StringUtils.newStringUtf8(urlSafe1[i]) + + "]"); + System.out.println("safe2: [" + + Hex.encodeHexString(decodedUrlSafe2) + + "] From: [" + + StringUtils.newStringUtf8(urlSafe2[i]) + + "]"); + System.out.println("safe3: [" + + Hex.encodeHexString(decodedUrlSafe3) + + "] From: [" + + StringUtils.newStringUtf8(urlSafe3[i]) + + "]"); + } + + assertTrue("standard encode uuid", Arrays.equals(encodedStandard, standard[i])); + assertTrue("url-safe encode uuid", Arrays.equals(encodedUrlSafe, urlSafe3[i])); + assertTrue("standard decode uuid", Arrays.equals(decodedStandard, ids[i])); + assertTrue("url-safe1 decode uuid", Arrays.equals(decodedUrlSafe1, ids[i])); + assertTrue("url-safe2 decode uuid", Arrays.equals(decodedUrlSafe2, ids[i])); + assertTrue("url-safe3 decode uuid", Arrays.equals(decodedUrlSafe3, ids[i])); + } + } + + public void testByteToStringVariations() throws DecoderException { + Base64 base64 = new Base64(0); + byte[] b1 = StringUtils.getBytesUtf8("Hello World"); + byte[] b2 = new byte[0]; + byte[] b3 = null; + byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray()); // for url-safe tests + + assertEquals("byteToString Hello World", "SGVsbG8gV29ybGQ=", base64.encodeToString(b1)); + assertEquals("byteToString static Hello World", "SGVsbG8gV29ybGQ=\r\n", Base64.encodeBase64String(b1)); + assertEquals("byteToString \"\"", "", base64.encodeToString(b2)); + assertEquals("byteToString static \"\"", "", Base64.encodeBase64String(b2)); + assertEquals("byteToString null", null, base64.encodeToString(b3)); + assertEquals("byteToString static null", null, Base64.encodeBase64String(b3)); + assertEquals("byteToString UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", base64.encodeToString(b4)); + assertEquals("byteToString static UUID", "K/fMJwH+Q5e0nr7tWsxwkA==\r\n", Base64.encodeBase64String(b4)); + assertEquals("byteToString static-url-safe UUID", "K_fMJwH-Q5e0nr7tWsxwkA", Base64.encodeBase64URLSafeString(b4)); + } + + public void testStringToByteVariations() throws DecoderException { + Base64 base64 = new Base64(); + String s1 = "SGVsbG8gV29ybGQ=\r\n"; + String s2 = ""; + String s3 = null; + String s4a = "K/fMJwH+Q5e0nr7tWsxwkA==\r\n"; + String s4b = "K_fMJwH-Q5e0nr7tWsxwkA"; + byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray()); // for url-safe tests + + assertEquals("StringToByte Hello World", "Hello World", StringUtils.newStringUtf8(base64.decode(s1))); + assertEquals("StringToByte Hello World", "Hello World", StringUtils.newStringUtf8((byte[])base64.decode((Object)s1))); + assertEquals("StringToByte static Hello World", "Hello World", StringUtils.newStringUtf8(Base64.decodeBase64(s1))); + assertEquals("StringToByte \"\"", "", StringUtils.newStringUtf8(base64.decode(s2))); + assertEquals("StringToByte static \"\"", "", StringUtils.newStringUtf8(Base64.decodeBase64(s2))); + assertEquals("StringToByte null", null, StringUtils.newStringUtf8(base64.decode(s3))); + assertEquals("StringToByte static null", null, StringUtils.newStringUtf8(Base64.decodeBase64(s3))); + assertTrue("StringToByte UUID", Arrays.equals(b4, base64.decode(s4b))); + assertTrue("StringToByte static UUID", Arrays.equals(b4, Base64.decodeBase64(s4a))); + assertTrue("StringToByte static-url-safe UUID", Arrays.equals(b4, Base64.decodeBase64(s4b))); + } + + private String toString(byte[] data) { + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < data.length; i++) { + buf.append(data[i]); + if (i != data.length - 1) { + buf.append(","); + } + } + return buf.toString(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `decodeBase64("====".getBytes())` could be null and is dereferenced at line 232. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Base64Test.testDecodePadOnly() + +### Procedure Id: +org.apache.commons.codec.binary.Base64Test.testDecodePadOnly():void.402f9e7c9e19ad22994a4705cc6b070d + +### File: +src/test/org/apache/commons/codec/binary/Base64Test.java + +### Key: +Base64Test.java|testDecodePadOnly|NULL_DEREFERENCE + +### Node Key: +c26a9a455e055d38651d28ebec106b05 + +### Hash: +c98000d494af3c50f32cad29cb9e7436 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3342/instruction.md b/inferredbugs-3342/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cb7700274018f07dcf926d92ec9ae8b1b095a862 --- /dev/null +++ b/inferredbugs-3342/instruction.md @@ -0,0 +1,1332 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-codec +**Bug ID:** 54 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.codec.binary; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Random; + +import org.apache.commons.codec.Charsets; +import org.apache.commons.codec.DecoderException; +import org.apache.commons.codec.EncoderException; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Test cases for Base64 class. + * + * @see RFC 2045 + * @version $Id$ + */ +public class Base64Test { + + private final Random random = new Random(); + + /** + * @return Returns the random. + */ + public Random getRandom() { + return this.random; + } + + /** + * Test the isStringBase64 method. + */ + @Test + public void testIsStringBase64() { + final String nullString = null; + final String emptyString = ""; + final String validString = "abc===defg\n\r123456\r789\r\rABC\n\nDEF==GHI\r\nJKL=============="; + final String invalidString = validString + (char)0; // append null character + + try { + Base64.isBase64(nullString); + fail("Base64.isStringBase64() should not be null-safe."); + } catch (final NullPointerException npe) { + assertNotNull("Base64.isStringBase64() should not be null-safe.", npe); + } + + assertTrue("Base64.isStringBase64(empty-string) is true", Base64.isBase64(emptyString)); + assertTrue("Base64.isStringBase64(valid-string) is true", Base64.isBase64(validString)); + assertFalse("Base64.isStringBase64(invalid-string) is false", Base64.isBase64(invalidString)); + } + + /** + * Test the Base64 implementation + */ + @Test + public void testBase64() { + final String content = "Hello World"; + String encodedContent; + byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content)); + encodedContent = StringUtils.newStringUtf8(encodedBytes); + assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); + + Base64 b64 = new Base64(BaseNCodec.MIME_CHUNK_SIZE, null); // null lineSeparator same as saying no-chunking + encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); + encodedContent = StringUtils.newStringUtf8(encodedBytes); + assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); + + b64 = new Base64(0, null); // null lineSeparator same as saying no-chunking + encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); + encodedContent = StringUtils.newStringUtf8(encodedBytes); + assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); + + // bogus characters to decode (to skip actually) {e-acute*6} + final byte[] decode = b64.decode("SGVsbG{\u00e9\u00e9\u00e9\u00e9\u00e9\u00e9}8gV29ybGQ="); + final String decodeString = StringUtils.newStringUtf8(decode); + assertEquals("decode hello world", "Hello World", decodeString); + } + + /** + * Test our decode with pad character in the middle. + * (Our current implementation: halt decode and return what we've got so far). + * + * The point of this test is not to say "this is the correct way to decode base64." + * The point is simply to keep us aware of the current logic since 1.4 so we + * don't accidentally break it without realizing. + * + * Note for historians. The 1.3 logic would decode to: + * "Hello World\u0000Hello World" -- null in the middle --- + * and 1.4 unwittingly changed it to current logic. + */ + @Test + public void testDecodeWithInnerPad() { + final String content = "SGVsbG8gV29ybGQ=SGVsbG8gV29ybGQ="; + final byte[] result = Base64.decodeBase64(content); + final byte[] shouldBe = StringUtils.getBytesUtf8("Hello World"); + assertTrue("decode should halt at pad (=)", Arrays.equals(result, shouldBe)); + } + + /** + * Tests Base64.encodeBase64(). + */ + @Test + public void testChunkedEncodeMultipleOf76() { + final byte[] expectedEncode = Base64.encodeBase64(Base64TestData.DECODED, true); + // convert to "\r\n" so we're equal to the old openssl encoding test stored + // in Base64TestData.ENCODED_76_CHARS_PER_LINE: + final String actualResult = Base64TestData.ENCODED_76_CHARS_PER_LINE.replaceAll("\n", "\r\n"); + final byte[] actualEncode = StringUtils.getBytesUtf8(actualResult); + assertTrue("chunkedEncodeMultipleOf76", Arrays.equals(expectedEncode, actualEncode)); + } + + /** + * CODEC-68: isBase64 throws ArrayIndexOutOfBoundsException on some non-BASE64 bytes + */ + @Test + public void testCodec68() { + final byte[] x = new byte[]{'n', 'A', '=', '=', (byte) 0x9c}; + Base64.decodeBase64(x); + } + + @Test + public void testCodeInteger1() { + final String encodedInt1 = "li7dzDacuo67Jg7mtqEm2TRuOMU="; + final BigInteger bigInt1 = new BigInteger("85739377120809420210425962799" + "0318636601332086981"); + + assertEquals(encodedInt1, new String(Base64.encodeInteger(bigInt1))); + assertEquals(bigInt1, Base64.decodeInteger(encodedInt1.getBytes(Charsets.UTF_8))); + } + + @Test + public void testCodeInteger2() { + final String encodedInt2 = "9B5ypLY9pMOmtxCeTDHgwdNFeGs="; + final BigInteger bigInt2 = new BigInteger("13936727572861167254666467268" + "91466679477132949611"); + + assertEquals(encodedInt2, new String(Base64.encodeInteger(bigInt2))); + assertEquals(bigInt2, Base64.decodeInteger(encodedInt2.getBytes(Charsets.UTF_8))); + } + + @Test + public void testCodeInteger3() { + final String encodedInt3 = "FKIhdgaG5LGKiEtF1vHy4f3y700zaD6QwDS3IrNVGzNp2" + "rY+1LFWTK6D44AyiC1n8uWz1itkYMZF0/aKDK0Yjg=="; + final BigInteger bigInt3 = new BigInteger("10806548154093873461951748545" + + "1196989136416448805819079363524309897749044958112417136240557" + + "4495062430572478766856090958495998158114332651671116876320938126"); + + assertEquals(encodedInt3, new String(Base64.encodeInteger(bigInt3))); + assertEquals(bigInt3, Base64.decodeInteger(encodedInt3.getBytes(Charsets.UTF_8))); + } + + @Test + public void testCodeInteger4() { + final String encodedInt4 = "ctA8YGxrtngg/zKVvqEOefnwmViFztcnPBYPlJsvh6yKI" + + "4iDm68fnp4Mi3RrJ6bZAygFrUIQLxLjV+OJtgJAEto0xAs+Mehuq1DkSFEpP3o" + + "DzCTOsrOiS1DwQe4oIb7zVk/9l7aPtJMHW0LVlMdwZNFNNJoqMcT2ZfCPrfvYv" + + "Q0="; + final BigInteger bigInt4 = new BigInteger("80624726256040348115552042320" + + "6968135001872753709424419772586693950232350200555646471175944" + + "519297087885987040810778908507262272892702303774422853675597" + + "748008534040890923814202286633163248086055216976551456088015" + + "338880713818192088877057717530169381044092839402438015097654" + + "53542091716518238707344493641683483917"); + + assertEquals(encodedInt4, new String(Base64.encodeInteger(bigInt4))); + assertEquals(bigInt4, Base64.decodeInteger(encodedInt4.getBytes(Charsets.UTF_8))); + } + + @Test + public void testCodeIntegerEdgeCases() { + // TODO + } + + @Test + public void testCodeIntegerNull() { + try { + Base64.encodeInteger(null); + fail("Exception not thrown when passing in null to encodeInteger(BigInteger)"); + } catch (final NullPointerException npe) { + // expected + } catch (final Exception e) { + fail("Incorrect Exception caught when passing in null to encodeInteger(BigInteger)"); + } + } + + @Test + public void testConstructors() { + Base64 base64; + base64 = new Base64(); + base64 = new Base64(-1); + base64 = new Base64(-1, new byte[]{}); + base64 = new Base64(64, new byte[]{}); + try { + base64 = new Base64(-1, new byte[]{'A'}); // TODO do we need to check sep if len = -1? + fail("Should have rejected attempt to use 'A' as a line separator"); + } catch (final IllegalArgumentException ignored) { + // Expected + } + try { + base64 = new Base64(64, new byte[]{'A'}); + fail("Should have rejected attempt to use 'A' as a line separator"); + } catch (final IllegalArgumentException ignored) { + // Expected + } + try { + base64 = new Base64(64, new byte[]{'='}); + fail("Should have rejected attempt to use '=' as a line separator"); + } catch (final IllegalArgumentException ignored) { + // Expected + } + base64 = new Base64(64, new byte[]{'$'}); // OK + try { + base64 = new Base64(64, new byte[]{'A', '$'}); + fail("Should have rejected attempt to use 'A$' as a line separator"); + } catch (final IllegalArgumentException ignored) { + // Expected + } + base64 = new Base64(64, new byte[]{' ', '$', '\n', '\r', '\t'}); // OK + assertNotNull(base64); + } + + @Test + public void testConstructor_Int_ByteArray_Boolean() { + final Base64 base64 = new Base64(65, new byte[]{'\t'}, false); + final byte[] encoded = base64.encode(Base64TestData.DECODED); + String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE; + expectedResult = expectedResult.replace('\n', '\t'); + final String result = StringUtils.newStringUtf8(encoded); + assertEquals("new Base64(65, \\t, false)", expectedResult, result); + } + + @Test + public void testConstructor_Int_ByteArray_Boolean_UrlSafe() { + // url-safe variation + final Base64 base64 = new Base64(64, new byte[]{'\t'}, true); + final byte[] encoded = base64.encode(Base64TestData.DECODED); + String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE; + expectedResult = expectedResult.replaceAll("=", ""); // url-safe has no == padding. + expectedResult = expectedResult.replace('\n', '\t'); + expectedResult = expectedResult.replace('+', '-'); + expectedResult = expectedResult.replace('/', '_'); + final String result = StringUtils.newStringUtf8(encoded); + assertEquals("new Base64(64, \\t, true)", result, expectedResult); + } + + /** + * Tests conditional true branch for "marker0" test. + */ + @Test + public void testDecodePadMarkerIndex2() { + assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes(Charsets.UTF_8)))); + } + + /** + * Tests conditional branches for "marker1" test. + */ + @Test + public void testDecodePadMarkerIndex3() { + assertEquals("AA", new String(Base64.decodeBase64("QUE=".getBytes(Charsets.UTF_8)))); + assertEquals("AAA", new String(Base64.decodeBase64("QUFB".getBytes(Charsets.UTF_8)))); + } + + @Test + public void testDecodePadOnly() { + assertEquals(0, Base64.decodeBase64("====".getBytes(Charsets.UTF_8)).length); + assertEquals("", new String(Base64.decodeBase64("====".getBytes(Charsets.UTF_8)))); + // Test truncated padding + assertEquals(0, Base64.decodeBase64("===".getBytes(Charsets.UTF_8)).length); + assertEquals(0, Base64.decodeBase64("==".getBytes(Charsets.UTF_8)).length); + assertEquals(0, Base64.decodeBase64("=".getBytes(Charsets.UTF_8)).length); + assertEquals(0, Base64.decodeBase64("".getBytes(Charsets.UTF_8)).length); + } + + @Test + public void testDecodePadOnlyChunked() { + assertEquals(0, Base64.decodeBase64("====\n".getBytes(Charsets.UTF_8)).length); + assertEquals("", new String(Base64.decodeBase64("====\n".getBytes(Charsets.UTF_8)))); + // Test truncated padding + assertEquals(0, Base64.decodeBase64("===\n".getBytes(Charsets.UTF_8)).length); + assertEquals(0, Base64.decodeBase64("==\n".getBytes(Charsets.UTF_8)).length); + assertEquals(0, Base64.decodeBase64("=\n".getBytes(Charsets.UTF_8)).length); + assertEquals(0, Base64.decodeBase64("\n".getBytes(Charsets.UTF_8)).length); + } + + @Test + public void testDecodeWithWhitespace() throws Exception { + + final String orig = "I am a late night coder."; + + final byte[] encodedArray = Base64.encodeBase64(orig.getBytes(Charsets.UTF_8)); + final StringBuilder intermediate = new StringBuilder(new String(encodedArray)); + + intermediate.insert(2, ' '); + intermediate.insert(5, '\t'); + intermediate.insert(10, '\r'); + intermediate.insert(15, '\n'); + + final byte[] encodedWithWS = intermediate.toString().getBytes(Charsets.UTF_8); + final byte[] decodedWithWS = Base64.decodeBase64(encodedWithWS); + + final String dest = new String(decodedWithWS); + + assertEquals("Dest string doesn't equal the original", orig, dest); + } + + /** + * Test encode and decode of empty byte array. + */ + @Test + public void testEmptyBase64() { + byte[] empty = new byte[0]; + byte[] result = Base64.encodeBase64(empty); + assertEquals("empty base64 encode", 0, result.length); + assertEquals("empty base64 encode", null, Base64.encodeBase64(null)); + + empty = new byte[0]; + result = Base64.decodeBase64(empty); + assertEquals("empty base64 decode", 0, result.length); + assertEquals("empty base64 encode", null, Base64.decodeBase64((byte[]) null)); + } + + // encode/decode a large random array + @Test + public void testEncodeDecodeRandom() { + for (int i = 1; i < 5; i++) { + final byte[] data = new byte[this.getRandom().nextInt(10000) + 1]; + this.getRandom().nextBytes(data); + final byte[] enc = Base64.encodeBase64(data); + assertTrue(Base64.isBase64(enc)); + final byte[] data2 = Base64.decodeBase64(enc); + assertTrue(Arrays.equals(data, data2)); + } + } + + // encode/decode random arrays from size 0 to size 11 + @Test + public void testEncodeDecodeSmall() { + for (int i = 0; i < 12; i++) { + final byte[] data = new byte[i]; + this.getRandom().nextBytes(data); + final byte[] enc = Base64.encodeBase64(data); + assertTrue("\"" + new String(enc) + "\" is Base64 data.", Base64.isBase64(enc)); + final byte[] data2 = Base64.decodeBase64(enc); + assertTrue(toString(data) + " equals " + toString(data2), Arrays.equals(data, data2)); + } + } + + @Test + public void testEncodeOverMaxSize() throws Exception { + testEncodeOverMaxSize(-1); + testEncodeOverMaxSize(0); + testEncodeOverMaxSize(1); + testEncodeOverMaxSize(2); + } + + @Test + public void testCodec112() { // size calculation assumes always chunked + final byte[] in = new byte[] {0}; + final byte[] out=Base64.encodeBase64(in); + Base64.encodeBase64(in, false, false, out.length); + } + + private void testEncodeOverMaxSize(final int maxSize) throws Exception { + try { + Base64.encodeBase64(Base64TestData.DECODED, true, false, maxSize); + fail("Expected " + IllegalArgumentException.class.getName()); + } catch (final IllegalArgumentException e) { + // Expected + } + } + + @Test + public void testIgnoringNonBase64InDecode() throws Exception { + assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 + .decodeBase64("VGhlIH@$#$@%F1aWN@#@#@@rIGJyb3duIGZve\n\r\t%#%#%#%CBqd##$#$W1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes(Charsets.UTF_8)))); + } + + @Test + public void testIsArrayByteBase64() { + assertFalse(Base64.isBase64(new byte[]{Byte.MIN_VALUE})); + assertFalse(Base64.isBase64(new byte[]{-125})); + assertFalse(Base64.isBase64(new byte[]{-10})); + assertFalse(Base64.isBase64(new byte[]{0})); + assertFalse(Base64.isBase64(new byte[]{64, Byte.MAX_VALUE})); + assertFalse(Base64.isBase64(new byte[]{Byte.MAX_VALUE})); + assertTrue(Base64.isBase64(new byte[]{'A'})); + assertFalse(Base64.isBase64(new byte[]{'A', Byte.MIN_VALUE})); + assertTrue(Base64.isBase64(new byte[]{'A', 'Z', 'a'})); + assertTrue(Base64.isBase64(new byte[]{'/', '=', '+'})); + assertFalse(Base64.isBase64(new byte[]{'$'})); + } + + /** + * Tests isUrlSafe. + */ + @Test + public void testIsUrlSafe() { + final Base64 base64Standard = new Base64(false); + final Base64 base64URLSafe = new Base64(true); + + assertFalse("Base64.isUrlSafe=false", base64Standard.isUrlSafe()); + assertTrue("Base64.isUrlSafe=true", base64URLSafe.isUrlSafe()); + + final byte[] whiteSpace = {' ', '\n', '\r', '\t'}; + assertTrue("Base64.isBase64(whiteSpace)=true", Base64.isBase64(whiteSpace)); + } + + @Test + public void testKnownDecodings() { + assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64 + .decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes(Charsets.UTF_8)))); + assertEquals("It was the best of times, it was the worst of times.", new String(Base64 + .decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes(Charsets.UTF_8)))); + assertEquals("http://jakarta.apache.org/commmons", new String(Base64 + .decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes(Charsets.UTF_8)))); + assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64 + .decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes(Charsets.UTF_8)))); + assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=" + .getBytes(Charsets.UTF_8)))); + assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes(Charsets.UTF_8)))); + } + + @Test + public void testKnownEncodings() { + assertEquals("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==", new String(Base64 + .encodeBase64("The quick brown fox jumped over the lazy dogs.".getBytes(Charsets.UTF_8)))); + assertEquals( + "YmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJs\r\nYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFo\r\nIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBi\r\nbGFoIGJsYWg=\r\n", + new String( + Base64 + .encodeBase64Chunked("blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah" + .getBytes(Charsets.UTF_8)))); + assertEquals("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==", new String(Base64 + .encodeBase64("It was the best of times, it was the worst of times.".getBytes(Charsets.UTF_8)))); + assertEquals("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==", new String(Base64 + .encodeBase64("http://jakarta.apache.org/commmons".getBytes(Charsets.UTF_8)))); + assertEquals("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==", new String(Base64 + .encodeBase64("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".getBytes(Charsets.UTF_8)))); + assertEquals("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=", new String(Base64.encodeBase64("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }" + .getBytes(Charsets.UTF_8)))); + assertEquals("eHl6enkh", new String(Base64.encodeBase64("xyzzy!".getBytes(Charsets.UTF_8)))); + } + + @Test + public void testNonBase64Test() throws Exception { + + final byte[] bArray = {'%'}; + + assertFalse("Invalid Base64 array was incorrectly validated as " + "an array of Base64 encoded data", Base64 + .isBase64(bArray)); + + try { + final Base64 b64 = new Base64(); + final byte[] result = b64.decode(bArray); + + assertEquals("The result should be empty as the test encoded content did " + "not contain any valid base 64 characters", + 0, result.length); + } catch (final Exception e) { + fail("Exception was thrown when trying to decode " + + "invalid base64 encoded data - RFC 2045 requires that all " + + "non base64 character be discarded, an exception should not" + + " have been thrown"); + } + } + + @Test + public void testObjectDecodeWithInvalidParameter() throws Exception { + final Base64 b64 = new Base64(); + + try { + b64.decode(Integer.valueOf(5)); + fail("decode(Object) didn't throw an exception when passed an Integer object"); + } catch (final DecoderException e) { + // ignored + } + + } + + @Test + public void testObjectDecodeWithValidParameter() throws Exception { + + final String original = "Hello World!"; + final Object o = Base64.encodeBase64(original.getBytes(Charsets.UTF_8)); + + final Base64 b64 = new Base64(); + final Object oDecoded = b64.decode(o); + final byte[] baDecoded = (byte[]) oDecoded; + final String dest = new String(baDecoded); + + assertEquals("dest string does not equal original", original, dest); + } + + @Test + public void testObjectEncodeWithInvalidParameter() throws Exception { + final Base64 b64 = new Base64(); + try { + b64.encode("Yadayadayada"); + fail("encode(Object) didn't throw an exception when passed a String object"); + } catch (final EncoderException e) { + // Expected + } + } + + @Test + public void testObjectEncodeWithValidParameter() throws Exception { + + final String original = "Hello World!"; + final Object origObj = original.getBytes(Charsets.UTF_8); + + final Base64 b64 = new Base64(); + final Object oEncoded = b64.encode(origObj); + final byte[] bArray = Base64.decodeBase64((byte[]) oEncoded); + final String dest = new String(bArray); + + assertEquals("dest string does not equal original", original, dest); + } + + @Test + public void testObjectEncode() throws Exception { + final Base64 b64 = new Base64(); + assertEquals("SGVsbG8gV29ybGQ=", new String(b64.encode("Hello World".getBytes(Charsets.UTF_8)))); + } + + @Test + public void testPairs() { + assertEquals("AAA=", new String(Base64.encodeBase64(new byte[]{0, 0}))); + for (int i = -128; i <= 127; i++) { + final byte test[] = {(byte) i, (byte) i}; + assertTrue(Arrays.equals(test, Base64.decodeBase64(Base64.encodeBase64(test)))); + } + } + + /** + * Tests RFC 2045 section 2.1 CRLF definition. + */ + @Test + public void testRfc2045Section2Dot1CrLfDefinition() { + assertTrue(Arrays.equals(new byte[]{13, 10}, Base64.CHUNK_SEPARATOR)); + } + + /** + * Tests RFC 2045 section 6.8 chuck size definition. + */ + @Test + public void testRfc2045Section6Dot8ChunkSizeDefinition() { + assertEquals(76, BaseNCodec.MIME_CHUNK_SIZE); + } + + /** + * Tests RFC 1421 section 4.3.2.4 chuck size definition. + */ + @Test + public void testRfc1421Section6Dot8ChunkSizeDefinition() { + assertEquals(64, BaseNCodec.PEM_CHUNK_SIZE); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *
      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + @Test + public void testRfc4648Section10Decode() { + assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64(""))); + assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg=="))); + assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8="))); + assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v"))); + assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg=="))); + assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE="))); + assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy"))); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *
      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + @Test + public void testRfc4648Section10DecodeWithCrLf() { + final String CRLF = StringUtils.newStringUsAscii(Base64.CHUNK_SEPARATOR); + assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64("" + CRLF))); + assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg==" + CRLF))); + assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8=" + CRLF))); + assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v" + CRLF))); + assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg==" + CRLF))); + assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE=" + CRLF))); + assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy" + CRLF))); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *
      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + @Test + public void testRfc4648Section10Encode() { + assertEquals("", Base64.encodeBase64String(StringUtils.getBytesUtf8(""))); + assertEquals("Zg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("f"))); + assertEquals("Zm8=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fo"))); + assertEquals("Zm9v", Base64.encodeBase64String(StringUtils.getBytesUtf8("foo"))); + assertEquals("Zm9vYg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("foob"))); + assertEquals("Zm9vYmE=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fooba"))); + assertEquals("Zm9vYmFy", Base64.encodeBase64String(StringUtils.getBytesUtf8("foobar"))); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *
      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + @Test + public void testRfc4648Section10DecodeEncode() { + testDecodeEncode(""); + testDecodeEncode("Zg=="); + testDecodeEncode("Zm8="); + testDecodeEncode("Zm9v"); + testDecodeEncode("Zm9vYg=="); + testDecodeEncode("Zm9vYmE="); + testDecodeEncode("Zm9vYmFy"); + } + + private void testDecodeEncode(final String encodedText) { + final String decodedText = StringUtils.newStringUsAscii(Base64.decodeBase64(encodedText)); + final String encodedText2 = Base64.encodeBase64String(StringUtils.getBytesUtf8(decodedText)); + assertEquals(encodedText, encodedText2); + } + + /** + * Tests RFC 4648 section 10 test vectors. + *
      + *
    • BASE64("") = ""
    • + *
    • BASE64("f") = "Zg=="
    • + *
    • BASE64("fo") = "Zm8="
    • + *
    • BASE64("foo") = "Zm9v"
    • + *
    • BASE64("foob") = "Zm9vYg=="
    • + *
    • BASE64("fooba") = "Zm9vYmE="
    • + *
    • BASE64("foobar") = "Zm9vYmFy"
    • + *
    + * + * @see http://tools.ietf.org/html/rfc4648 + */ + @Test + public void testRfc4648Section10EncodeDecode() { + testEncodeDecode(""); + testEncodeDecode("f"); + testEncodeDecode("fo"); + testEncodeDecode("foo"); + testEncodeDecode("foob"); + testEncodeDecode("fooba"); + testEncodeDecode("foobar"); + } + + private void testEncodeDecode(final String plainText) { + final String encodedText = Base64.encodeBase64String(StringUtils.getBytesUtf8(plainText)); + final String decodedText = StringUtils.newStringUsAscii(Base64.decodeBase64(encodedText)); + assertEquals(plainText, decodedText); + } + + @Test + public void testSingletons() { + assertEquals("AA==", new String(Base64.encodeBase64(new byte[]{(byte) 0}))); + assertEquals("AQ==", new String(Base64.encodeBase64(new byte[]{(byte) 1}))); + assertEquals("Ag==", new String(Base64.encodeBase64(new byte[]{(byte) 2}))); + assertEquals("Aw==", new String(Base64.encodeBase64(new byte[]{(byte) 3}))); + assertEquals("BA==", new String(Base64.encodeBase64(new byte[]{(byte) 4}))); + assertEquals("BQ==", new String(Base64.encodeBase64(new byte[]{(byte) 5}))); + assertEquals("Bg==", new String(Base64.encodeBase64(new byte[]{(byte) 6}))); + assertEquals("Bw==", new String(Base64.encodeBase64(new byte[]{(byte) 7}))); + assertEquals("CA==", new String(Base64.encodeBase64(new byte[]{(byte) 8}))); + assertEquals("CQ==", new String(Base64.encodeBase64(new byte[]{(byte) 9}))); + assertEquals("Cg==", new String(Base64.encodeBase64(new byte[]{(byte) 10}))); + assertEquals("Cw==", new String(Base64.encodeBase64(new byte[]{(byte) 11}))); + assertEquals("DA==", new String(Base64.encodeBase64(new byte[]{(byte) 12}))); + assertEquals("DQ==", new String(Base64.encodeBase64(new byte[]{(byte) 13}))); + assertEquals("Dg==", new String(Base64.encodeBase64(new byte[]{(byte) 14}))); + assertEquals("Dw==", new String(Base64.encodeBase64(new byte[]{(byte) 15}))); + assertEquals("EA==", new String(Base64.encodeBase64(new byte[]{(byte) 16}))); + assertEquals("EQ==", new String(Base64.encodeBase64(new byte[]{(byte) 17}))); + assertEquals("Eg==", new String(Base64.encodeBase64(new byte[]{(byte) 18}))); + assertEquals("Ew==", new String(Base64.encodeBase64(new byte[]{(byte) 19}))); + assertEquals("FA==", new String(Base64.encodeBase64(new byte[]{(byte) 20}))); + assertEquals("FQ==", new String(Base64.encodeBase64(new byte[]{(byte) 21}))); + assertEquals("Fg==", new String(Base64.encodeBase64(new byte[]{(byte) 22}))); + assertEquals("Fw==", new String(Base64.encodeBase64(new byte[]{(byte) 23}))); + assertEquals("GA==", new String(Base64.encodeBase64(new byte[]{(byte) 24}))); + assertEquals("GQ==", new String(Base64.encodeBase64(new byte[]{(byte) 25}))); + assertEquals("Gg==", new String(Base64.encodeBase64(new byte[]{(byte) 26}))); + assertEquals("Gw==", new String(Base64.encodeBase64(new byte[]{(byte) 27}))); + assertEquals("HA==", new String(Base64.encodeBase64(new byte[]{(byte) 28}))); + assertEquals("HQ==", new String(Base64.encodeBase64(new byte[]{(byte) 29}))); + assertEquals("Hg==", new String(Base64.encodeBase64(new byte[]{(byte) 30}))); + assertEquals("Hw==", new String(Base64.encodeBase64(new byte[]{(byte) 31}))); + assertEquals("IA==", new String(Base64.encodeBase64(new byte[]{(byte) 32}))); + assertEquals("IQ==", new String(Base64.encodeBase64(new byte[]{(byte) 33}))); + assertEquals("Ig==", new String(Base64.encodeBase64(new byte[]{(byte) 34}))); + assertEquals("Iw==", new String(Base64.encodeBase64(new byte[]{(byte) 35}))); + assertEquals("JA==", new String(Base64.encodeBase64(new byte[]{(byte) 36}))); + assertEquals("JQ==", new String(Base64.encodeBase64(new byte[]{(byte) 37}))); + assertEquals("Jg==", new String(Base64.encodeBase64(new byte[]{(byte) 38}))); + assertEquals("Jw==", new String(Base64.encodeBase64(new byte[]{(byte) 39}))); + assertEquals("KA==", new String(Base64.encodeBase64(new byte[]{(byte) 40}))); + assertEquals("KQ==", new String(Base64.encodeBase64(new byte[]{(byte) 41}))); + assertEquals("Kg==", new String(Base64.encodeBase64(new byte[]{(byte) 42}))); + assertEquals("Kw==", new String(Base64.encodeBase64(new byte[]{(byte) 43}))); + assertEquals("LA==", new String(Base64.encodeBase64(new byte[]{(byte) 44}))); + assertEquals("LQ==", new String(Base64.encodeBase64(new byte[]{(byte) 45}))); + assertEquals("Lg==", new String(Base64.encodeBase64(new byte[]{(byte) 46}))); + assertEquals("Lw==", new String(Base64.encodeBase64(new byte[]{(byte) 47}))); + assertEquals("MA==", new String(Base64.encodeBase64(new byte[]{(byte) 48}))); + assertEquals("MQ==", new String(Base64.encodeBase64(new byte[]{(byte) 49}))); + assertEquals("Mg==", new String(Base64.encodeBase64(new byte[]{(byte) 50}))); + assertEquals("Mw==", new String(Base64.encodeBase64(new byte[]{(byte) 51}))); + assertEquals("NA==", new String(Base64.encodeBase64(new byte[]{(byte) 52}))); + assertEquals("NQ==", new String(Base64.encodeBase64(new byte[]{(byte) 53}))); + assertEquals("Ng==", new String(Base64.encodeBase64(new byte[]{(byte) 54}))); + assertEquals("Nw==", new String(Base64.encodeBase64(new byte[]{(byte) 55}))); + assertEquals("OA==", new String(Base64.encodeBase64(new byte[]{(byte) 56}))); + assertEquals("OQ==", new String(Base64.encodeBase64(new byte[]{(byte) 57}))); + assertEquals("Og==", new String(Base64.encodeBase64(new byte[]{(byte) 58}))); + assertEquals("Ow==", new String(Base64.encodeBase64(new byte[]{(byte) 59}))); + assertEquals("PA==", new String(Base64.encodeBase64(new byte[]{(byte) 60}))); + assertEquals("PQ==", new String(Base64.encodeBase64(new byte[]{(byte) 61}))); + assertEquals("Pg==", new String(Base64.encodeBase64(new byte[]{(byte) 62}))); + assertEquals("Pw==", new String(Base64.encodeBase64(new byte[]{(byte) 63}))); + assertEquals("QA==", new String(Base64.encodeBase64(new byte[]{(byte) 64}))); + assertEquals("QQ==", new String(Base64.encodeBase64(new byte[]{(byte) 65}))); + assertEquals("Qg==", new String(Base64.encodeBase64(new byte[]{(byte) 66}))); + assertEquals("Qw==", new String(Base64.encodeBase64(new byte[]{(byte) 67}))); + assertEquals("RA==", new String(Base64.encodeBase64(new byte[]{(byte) 68}))); + assertEquals("RQ==", new String(Base64.encodeBase64(new byte[]{(byte) 69}))); + assertEquals("Rg==", new String(Base64.encodeBase64(new byte[]{(byte) 70}))); + assertEquals("Rw==", new String(Base64.encodeBase64(new byte[]{(byte) 71}))); + assertEquals("SA==", new String(Base64.encodeBase64(new byte[]{(byte) 72}))); + assertEquals("SQ==", new String(Base64.encodeBase64(new byte[]{(byte) 73}))); + assertEquals("Sg==", new String(Base64.encodeBase64(new byte[]{(byte) 74}))); + assertEquals("Sw==", new String(Base64.encodeBase64(new byte[]{(byte) 75}))); + assertEquals("TA==", new String(Base64.encodeBase64(new byte[]{(byte) 76}))); + assertEquals("TQ==", new String(Base64.encodeBase64(new byte[]{(byte) 77}))); + assertEquals("Tg==", new String(Base64.encodeBase64(new byte[]{(byte) 78}))); + assertEquals("Tw==", new String(Base64.encodeBase64(new byte[]{(byte) 79}))); + assertEquals("UA==", new String(Base64.encodeBase64(new byte[]{(byte) 80}))); + assertEquals("UQ==", new String(Base64.encodeBase64(new byte[]{(byte) 81}))); + assertEquals("Ug==", new String(Base64.encodeBase64(new byte[]{(byte) 82}))); + assertEquals("Uw==", new String(Base64.encodeBase64(new byte[]{(byte) 83}))); + assertEquals("VA==", new String(Base64.encodeBase64(new byte[]{(byte) 84}))); + assertEquals("VQ==", new String(Base64.encodeBase64(new byte[]{(byte) 85}))); + assertEquals("Vg==", new String(Base64.encodeBase64(new byte[]{(byte) 86}))); + assertEquals("Vw==", new String(Base64.encodeBase64(new byte[]{(byte) 87}))); + assertEquals("WA==", new String(Base64.encodeBase64(new byte[]{(byte) 88}))); + assertEquals("WQ==", new String(Base64.encodeBase64(new byte[]{(byte) 89}))); + assertEquals("Wg==", new String(Base64.encodeBase64(new byte[]{(byte) 90}))); + assertEquals("Ww==", new String(Base64.encodeBase64(new byte[]{(byte) 91}))); + assertEquals("XA==", new String(Base64.encodeBase64(new byte[]{(byte) 92}))); + assertEquals("XQ==", new String(Base64.encodeBase64(new byte[]{(byte) 93}))); + assertEquals("Xg==", new String(Base64.encodeBase64(new byte[]{(byte) 94}))); + assertEquals("Xw==", new String(Base64.encodeBase64(new byte[]{(byte) 95}))); + assertEquals("YA==", new String(Base64.encodeBase64(new byte[]{(byte) 96}))); + assertEquals("YQ==", new String(Base64.encodeBase64(new byte[]{(byte) 97}))); + assertEquals("Yg==", new String(Base64.encodeBase64(new byte[]{(byte) 98}))); + assertEquals("Yw==", new String(Base64.encodeBase64(new byte[]{(byte) 99}))); + assertEquals("ZA==", new String(Base64.encodeBase64(new byte[]{(byte) 100}))); + assertEquals("ZQ==", new String(Base64.encodeBase64(new byte[]{(byte) 101}))); + assertEquals("Zg==", new String(Base64.encodeBase64(new byte[]{(byte) 102}))); + assertEquals("Zw==", new String(Base64.encodeBase64(new byte[]{(byte) 103}))); + assertEquals("aA==", new String(Base64.encodeBase64(new byte[]{(byte) 104}))); + for (int i = -128; i <= 127; i++) { + final byte test[] = {(byte) i}; + assertTrue(Arrays.equals(test, Base64.decodeBase64(Base64.encodeBase64(test)))); + } + } + + @Test + public void testSingletonsChunked() { + assertEquals("AA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0}))); + assertEquals("AQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 1}))); + assertEquals("Ag==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 2}))); + assertEquals("Aw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 3}))); + assertEquals("BA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 4}))); + assertEquals("BQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 5}))); + assertEquals("Bg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 6}))); + assertEquals("Bw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 7}))); + assertEquals("CA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 8}))); + assertEquals("CQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 9}))); + assertEquals("Cg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 10}))); + assertEquals("Cw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 11}))); + assertEquals("DA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 12}))); + assertEquals("DQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 13}))); + assertEquals("Dg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 14}))); + assertEquals("Dw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 15}))); + assertEquals("EA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 16}))); + assertEquals("EQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 17}))); + assertEquals("Eg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 18}))); + assertEquals("Ew==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 19}))); + assertEquals("FA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 20}))); + assertEquals("FQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 21}))); + assertEquals("Fg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 22}))); + assertEquals("Fw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 23}))); + assertEquals("GA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 24}))); + assertEquals("GQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 25}))); + assertEquals("Gg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 26}))); + assertEquals("Gw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 27}))); + assertEquals("HA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 28}))); + assertEquals("HQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 29}))); + assertEquals("Hg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 30}))); + assertEquals("Hw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 31}))); + assertEquals("IA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 32}))); + assertEquals("IQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 33}))); + assertEquals("Ig==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 34}))); + assertEquals("Iw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 35}))); + assertEquals("JA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 36}))); + assertEquals("JQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 37}))); + assertEquals("Jg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 38}))); + assertEquals("Jw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 39}))); + assertEquals("KA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 40}))); + assertEquals("KQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 41}))); + assertEquals("Kg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 42}))); + assertEquals("Kw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 43}))); + assertEquals("LA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 44}))); + assertEquals("LQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 45}))); + assertEquals("Lg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 46}))); + assertEquals("Lw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 47}))); + assertEquals("MA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 48}))); + assertEquals("MQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 49}))); + assertEquals("Mg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 50}))); + assertEquals("Mw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 51}))); + assertEquals("NA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 52}))); + assertEquals("NQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 53}))); + assertEquals("Ng==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 54}))); + assertEquals("Nw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 55}))); + assertEquals("OA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 56}))); + assertEquals("OQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 57}))); + assertEquals("Og==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 58}))); + assertEquals("Ow==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 59}))); + assertEquals("PA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 60}))); + assertEquals("PQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 61}))); + assertEquals("Pg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 62}))); + assertEquals("Pw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 63}))); + assertEquals("QA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 64}))); + assertEquals("QQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 65}))); + assertEquals("Qg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 66}))); + assertEquals("Qw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 67}))); + assertEquals("RA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 68}))); + assertEquals("RQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 69}))); + assertEquals("Rg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 70}))); + assertEquals("Rw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 71}))); + assertEquals("SA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 72}))); + assertEquals("SQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 73}))); + assertEquals("Sg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 74}))); + assertEquals("Sw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 75}))); + assertEquals("TA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 76}))); + assertEquals("TQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 77}))); + assertEquals("Tg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 78}))); + assertEquals("Tw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 79}))); + assertEquals("UA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 80}))); + assertEquals("UQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 81}))); + assertEquals("Ug==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 82}))); + assertEquals("Uw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 83}))); + assertEquals("VA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 84}))); + assertEquals("VQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 85}))); + assertEquals("Vg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 86}))); + assertEquals("Vw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 87}))); + assertEquals("WA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 88}))); + assertEquals("WQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 89}))); + assertEquals("Wg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 90}))); + assertEquals("Ww==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 91}))); + assertEquals("XA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 92}))); + assertEquals("XQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 93}))); + assertEquals("Xg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 94}))); + assertEquals("Xw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 95}))); + assertEquals("YA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 96}))); + assertEquals("YQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 97}))); + assertEquals("Yg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 98}))); + assertEquals("Yw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 99}))); + assertEquals("ZA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 100}))); + assertEquals("ZQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 101}))); + assertEquals("Zg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 102}))); + assertEquals("Zw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 103}))); + assertEquals("aA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 104}))); + } + + @Test + public void testTriplets() { + assertEquals("AAAA", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 0}))); + assertEquals("AAAB", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 1}))); + assertEquals("AAAC", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 2}))); + assertEquals("AAAD", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 3}))); + assertEquals("AAAE", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 4}))); + assertEquals("AAAF", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 5}))); + assertEquals("AAAG", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 6}))); + assertEquals("AAAH", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 7}))); + assertEquals("AAAI", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 8}))); + assertEquals("AAAJ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 9}))); + assertEquals("AAAK", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 10}))); + assertEquals("AAAL", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 11}))); + assertEquals("AAAM", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 12}))); + assertEquals("AAAN", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 13}))); + assertEquals("AAAO", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 14}))); + assertEquals("AAAP", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 15}))); + assertEquals("AAAQ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 16}))); + assertEquals("AAAR", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 17}))); + assertEquals("AAAS", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 18}))); + assertEquals("AAAT", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 19}))); + assertEquals("AAAU", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 20}))); + assertEquals("AAAV", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 21}))); + assertEquals("AAAW", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 22}))); + assertEquals("AAAX", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 23}))); + assertEquals("AAAY", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 24}))); + assertEquals("AAAZ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 25}))); + assertEquals("AAAa", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 26}))); + assertEquals("AAAb", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 27}))); + assertEquals("AAAc", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 28}))); + assertEquals("AAAd", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 29}))); + assertEquals("AAAe", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 30}))); + assertEquals("AAAf", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 31}))); + assertEquals("AAAg", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 32}))); + assertEquals("AAAh", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 33}))); + assertEquals("AAAi", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 34}))); + assertEquals("AAAj", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 35}))); + assertEquals("AAAk", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 36}))); + assertEquals("AAAl", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 37}))); + assertEquals("AAAm", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 38}))); + assertEquals("AAAn", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 39}))); + assertEquals("AAAo", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 40}))); + assertEquals("AAAp", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 41}))); + assertEquals("AAAq", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 42}))); + assertEquals("AAAr", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 43}))); + assertEquals("AAAs", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 44}))); + assertEquals("AAAt", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 45}))); + assertEquals("AAAu", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 46}))); + assertEquals("AAAv", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 47}))); + assertEquals("AAAw", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 48}))); + assertEquals("AAAx", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 49}))); + assertEquals("AAAy", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 50}))); + assertEquals("AAAz", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 51}))); + assertEquals("AAA0", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 52}))); + assertEquals("AAA1", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 53}))); + assertEquals("AAA2", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 54}))); + assertEquals("AAA3", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 55}))); + assertEquals("AAA4", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 56}))); + assertEquals("AAA5", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 57}))); + assertEquals("AAA6", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 58}))); + assertEquals("AAA7", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 59}))); + assertEquals("AAA8", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 60}))); + assertEquals("AAA9", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 61}))); + assertEquals("AAA+", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 62}))); + assertEquals("AAA/", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 63}))); + } + + @Test + public void testTripletsChunked() { + assertEquals("AAAA\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 0}))); + assertEquals("AAAB\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 1}))); + assertEquals("AAAC\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 2}))); + assertEquals("AAAD\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 3}))); + assertEquals("AAAE\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 4}))); + assertEquals("AAAF\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 5}))); + assertEquals("AAAG\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 6}))); + assertEquals("AAAH\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 7}))); + assertEquals("AAAI\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 8}))); + assertEquals("AAAJ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 9}))); + assertEquals("AAAK\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 10}))); + assertEquals("AAAL\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 11}))); + assertEquals("AAAM\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 12}))); + assertEquals("AAAN\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 13}))); + assertEquals("AAAO\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 14}))); + assertEquals("AAAP\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 15}))); + assertEquals("AAAQ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 16}))); + assertEquals("AAAR\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 17}))); + assertEquals("AAAS\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 18}))); + assertEquals("AAAT\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 19}))); + assertEquals("AAAU\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 20}))); + assertEquals("AAAV\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 21}))); + assertEquals("AAAW\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 22}))); + assertEquals("AAAX\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 23}))); + assertEquals("AAAY\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 24}))); + assertEquals("AAAZ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 25}))); + assertEquals("AAAa\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 26}))); + assertEquals("AAAb\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 27}))); + assertEquals("AAAc\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 28}))); + assertEquals("AAAd\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 29}))); + assertEquals("AAAe\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 30}))); + assertEquals("AAAf\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 31}))); + assertEquals("AAAg\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 32}))); + assertEquals("AAAh\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 33}))); + assertEquals("AAAi\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 34}))); + assertEquals("AAAj\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 35}))); + assertEquals("AAAk\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 36}))); + assertEquals("AAAl\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 37}))); + assertEquals("AAAm\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 38}))); + assertEquals("AAAn\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 39}))); + assertEquals("AAAo\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 40}))); + assertEquals("AAAp\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 41}))); + assertEquals("AAAq\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 42}))); + assertEquals("AAAr\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 43}))); + assertEquals("AAAs\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 44}))); + assertEquals("AAAt\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 45}))); + assertEquals("AAAu\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 46}))); + assertEquals("AAAv\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 47}))); + assertEquals("AAAw\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 48}))); + assertEquals("AAAx\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 49}))); + assertEquals("AAAy\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 50}))); + assertEquals("AAAz\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 51}))); + assertEquals("AAA0\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 52}))); + assertEquals("AAA1\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 53}))); + assertEquals("AAA2\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 54}))); + assertEquals("AAA3\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 55}))); + assertEquals("AAA4\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 56}))); + assertEquals("AAA5\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 57}))); + assertEquals("AAA6\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 58}))); + assertEquals("AAA7\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 59}))); + assertEquals("AAA8\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 60}))); + assertEquals("AAA9\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 61}))); + assertEquals("AAA+\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 62}))); + assertEquals("AAA/\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 63}))); + } + + /** + * Tests url-safe Base64 against random data, sizes 0 to 150. + */ + @Test + public void testUrlSafe() { + // test random data of sizes 0 thru 150 + for (int i = 0; i <= 150; i++) { + final byte[][] randomData = Base64TestData.randomData(i, true); + final byte[] encoded = randomData[1]; + final byte[] decoded = randomData[0]; + final byte[] result = Base64.decodeBase64(encoded); + assertTrue("url-safe i=" + i, Arrays.equals(decoded, result)); + assertFalse("url-safe i=" + i + " no '='", Base64TestData.bytesContain(encoded, (byte) '=')); + assertFalse("url-safe i=" + i + " no '\\'", Base64TestData.bytesContain(encoded, (byte) '\\')); + assertFalse("url-safe i=" + i + " no '+'", Base64TestData.bytesContain(encoded, (byte) '+')); + } + + } + + /** + * Base64 encoding of UUID's is a common use-case, especially in URL-SAFE mode. This test case ends up being the + * "URL-SAFE" JUnit's. + * + * @throws DecoderException + * if Hex.decode() fails - a serious problem since Hex comes from our own commons-codec! + */ + @Test + public void testUUID() throws DecoderException { + // The 4 UUID's below contains mixtures of + and / to help us test the + // URL-SAFE encoding mode. + final byte[][] ids = new byte[4][]; + + // ids[0] was chosen so that it encodes with at least one +. + ids[0] = Hex.decodeHex("94ed8d0319e4493399560fb67404d370".toCharArray()); + + // ids[1] was chosen so that it encodes with both / and +. + ids[1] = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray()); + + // ids[2] was chosen so that it encodes with at least one /. + ids[2] = Hex.decodeHex("64be154b6ffa40258d1a01288e7c31ca".toCharArray()); + + // ids[3] was chosen so that it encodes with both / and +, with / + // right at the beginning. + ids[3] = Hex.decodeHex("ff7f8fc01cdb471a8c8b5a9306183fe8".toCharArray()); + + final byte[][] standard = new byte[4][]; + standard[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg+2dATTcA=="); + standard[1] = StringUtils.getBytesUtf8("K/fMJwH+Q5e0nr7tWsxwkA=="); + standard[2] = StringUtils.getBytesUtf8("ZL4VS2/6QCWNGgEojnwxyg=="); + standard[3] = StringUtils.getBytesUtf8("/3+PwBzbRxqMi1qTBhg/6A=="); + + final byte[][] urlSafe1 = new byte[4][]; + // regular padding (two '==' signs). + urlSafe1[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA=="); + urlSafe1[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA=="); + urlSafe1[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg=="); + urlSafe1[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A=="); + + final byte[][] urlSafe2 = new byte[4][]; + // single padding (only one '=' sign). + urlSafe2[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA="); + urlSafe2[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA="); + urlSafe2[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg="); + urlSafe2[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A="); + + final byte[][] urlSafe3 = new byte[4][]; + // no padding (no '=' signs). + urlSafe3[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA"); + urlSafe3[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA"); + urlSafe3[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg"); + urlSafe3[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A"); + + for (int i = 0; i < 4; i++) { + final byte[] encodedStandard = Base64.encodeBase64(ids[i]); + final byte[] encodedUrlSafe = Base64.encodeBase64URLSafe(ids[i]); + final byte[] decodedStandard = Base64.decodeBase64(standard[i]); + final byte[] decodedUrlSafe1 = Base64.decodeBase64(urlSafe1[i]); + final byte[] decodedUrlSafe2 = Base64.decodeBase64(urlSafe2[i]); + final byte[] decodedUrlSafe3 = Base64.decodeBase64(urlSafe3[i]); + + // Very important debugging output should anyone + // ever need to delve closely into this stuff. + if (false) { + System.out.println("reference: [" + Hex.encodeHexString(ids[i]) + "]"); + System.out.println("standard: [" + + Hex.encodeHexString(decodedStandard) + + "] From: [" + + StringUtils.newStringUtf8(standard[i]) + + "]"); + System.out.println("safe1: [" + + Hex.encodeHexString(decodedUrlSafe1) + + "] From: [" + + StringUtils.newStringUtf8(urlSafe1[i]) + + "]"); + System.out.println("safe2: [" + + Hex.encodeHexString(decodedUrlSafe2) + + "] From: [" + + StringUtils.newStringUtf8(urlSafe2[i]) + + "]"); + System.out.println("safe3: [" + + Hex.encodeHexString(decodedUrlSafe3) + + "] From: [" + + StringUtils.newStringUtf8(urlSafe3[i]) + + "]"); + } + + assertTrue("standard encode uuid", Arrays.equals(encodedStandard, standard[i])); + assertTrue("url-safe encode uuid", Arrays.equals(encodedUrlSafe, urlSafe3[i])); + assertTrue("standard decode uuid", Arrays.equals(decodedStandard, ids[i])); + assertTrue("url-safe1 decode uuid", Arrays.equals(decodedUrlSafe1, ids[i])); + assertTrue("url-safe2 decode uuid", Arrays.equals(decodedUrlSafe2, ids[i])); + assertTrue("url-safe3 decode uuid", Arrays.equals(decodedUrlSafe3, ids[i])); + } + } + + @Test + public void testByteToStringVariations() throws DecoderException { + final Base64 base64 = new Base64(0); + final byte[] b1 = StringUtils.getBytesUtf8("Hello World"); + final byte[] b2 = new byte[0]; + final byte[] b3 = null; + final byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray()); // for url-safe tests + + assertEquals("byteToString Hello World", "SGVsbG8gV29ybGQ=", base64.encodeToString(b1)); + assertEquals("byteToString static Hello World", "SGVsbG8gV29ybGQ=", Base64.encodeBase64String(b1)); + assertEquals("byteToString \"\"", "", base64.encodeToString(b2)); + assertEquals("byteToString static \"\"", "", Base64.encodeBase64String(b2)); + assertEquals("byteToString null", null, base64.encodeToString(b3)); + assertEquals("byteToString static null", null, Base64.encodeBase64String(b3)); + assertEquals("byteToString UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", base64.encodeToString(b4)); + assertEquals("byteToString static UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", Base64.encodeBase64String(b4)); + assertEquals("byteToString static-url-safe UUID", "K_fMJwH-Q5e0nr7tWsxwkA", Base64.encodeBase64URLSafeString(b4)); + } + + @Test + public void testStringToByteVariations() throws DecoderException { + final Base64 base64 = new Base64(); + final String s1 = "SGVsbG8gV29ybGQ=\r\n"; + final String s2 = ""; + final String s3 = null; + final String s4a = "K/fMJwH+Q5e0nr7tWsxwkA==\r\n"; + final String s4b = "K_fMJwH-Q5e0nr7tWsxwkA"; + final byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray()); // for url-safe tests + + assertEquals("StringToByte Hello World", "Hello World", StringUtils.newStringUtf8(base64.decode(s1))); + assertEquals("StringToByte Hello World", "Hello World", StringUtils.newStringUtf8((byte[])base64.decode((Object)s1))); + assertEquals("StringToByte static Hello World", "Hello World", StringUtils.newStringUtf8(Base64.decodeBase64(s1))); + assertEquals("StringToByte \"\"", "", StringUtils.newStringUtf8(base64.decode(s2))); + assertEquals("StringToByte static \"\"", "", StringUtils.newStringUtf8(Base64.decodeBase64(s2))); + assertEquals("StringToByte null", null, StringUtils.newStringUtf8(base64.decode(s3))); + assertEquals("StringToByte static null", null, StringUtils.newStringUtf8(Base64.decodeBase64(s3))); + assertTrue("StringToByte UUID", Arrays.equals(b4, base64.decode(s4b))); + assertTrue("StringToByte static UUID", Arrays.equals(b4, Base64.decodeBase64(s4a))); + assertTrue("StringToByte static-url-safe UUID", Arrays.equals(b4, Base64.decodeBase64(s4b))); + } + + private String toString(final byte[] data) { + final StringBuilder buf = new StringBuilder(); + for (int i = 0; i < data.length; i++) { + buf.append(data[i]); + if (i != data.length - 1) { + buf.append(","); + } + } + return buf.toString(); + } + + /** + * Tests a lineSeparator much bigger than DEFAULT_BUFFER_SIZE. + * + * @see "dev@commons.apache.org" + */ + @Test + @Ignore + public void testHugeLineSeparator() { + final int BaseNCodec_DEFAULT_BUFFER_SIZE = 8192; + final int Base64_BYTES_PER_ENCODED_BLOCK = 4; + final byte[] baLineSeparator = new byte[BaseNCodec_DEFAULT_BUFFER_SIZE * 4 - 3]; + final Base64 b64 = new Base64(Base64_BYTES_PER_ENCODED_BLOCK, baLineSeparator); + final String strOriginal = "Hello World"; + final String strDecoded = new String(b64.decode(b64.encode(StringUtils.getBytesUtf8(strOriginal)))); + assertEquals("testDEFAULT_BUFFER_SIZE", strOriginal, strDecoded); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `encodeBase64("The quick brown fox jumped over the lazy dogs.".getBytes(org.apache.commons.codec.Charsets.UTF_8))` could be null and is dereferenced by call to `String(...)` at line 447. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Base64Test.testKnownEncodings() + +### Procedure Id: +org.apache.commons.codec.binary.Base64Test.testKnownEncodings():void.670a68ecdebf6e9e5648d4b88c578642 + +### File: +src/test/java/org/apache/commons/codec/binary/Base64Test.java + +### Key: +Base64Test.java|testKnownEncodings|NULL_DEREFERENCE + +### Node Key: +e7100ed3d2ec428549af314291e315ce + +### Hash: +d7263b5dce92ebb04aed5ef5b5afab08 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3344/instruction.md b/inferredbugs-3344/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..13929c0def47fa29e27758ae65dfd59abde10122 --- /dev/null +++ b/inferredbugs-3344/instruction.md @@ -0,0 +1,617 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-codec +**Bug ID:** 30 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.codec.binary; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; + +import org.junit.Test; + +public class Base32InputStreamTest { + + private static final String ENCODED_FOO = "MZXW6==="; + + private final static byte[] CRLF = { (byte) '\r', (byte) '\n' }; + + private final static byte[] LF = { (byte) '\n' }; + + private static final String STRING_FIXTURE = "Hello World"; + + /** + * Tests the problem reported in CODEC-130. Missing / wrong implementation of skip. + */ + @Test + public void testCodec130() throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + Base32OutputStream base32os = new Base32OutputStream(bos); + + base32os.write(StringUtils.getBytesUtf8(STRING_FIXTURE)); + base32os.close(); + + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + Base32InputStream ins = new Base32InputStream(bis); + + // we skip the first character read from the reader + ins.skip(1); + byte[] decodedBytes = Base32TestData.streamToBytes(ins, new byte[64]); + String str = StringUtils.newStringUtf8(decodedBytes); + + assertEquals(STRING_FIXTURE.substring(1), str); + } + + /** + * Tests the bug reported in CODEC-105. Bad interactions with InputStream when reading one byte at a time. + */ + @Test + public void testCodec105() throws IOException { + Base32InputStream in = new Base32InputStream(new Codec105ErrorInputStream(), true, 0, null); + try { + for (int i = 0; i < 5; i++) { + in.read(); + } + } finally { + in.close(); + } + } + + // /** + // * Test for the CODEC-101 bug: InputStream.read(byte[]) should never return 0 + // * because Java's builtin InputStreamReader hates that. + // * + // * @throws Exception for some failure scenarios. + // */ + // @Test + // public void testCodec101() throws Exception { + // byte[] codec101 = StringUtils.getBytesUtf8(Base32TestData.CODEC_101_MULTIPLE_OF_3); + // ByteArrayInputStream bais = new ByteArrayInputStream(codec101); + // Base32InputStream in = new Base32InputStream(bais); + // byte[] result = new byte[8192]; + // int c = in.read(result); + // assertTrue("Codec101: First read successful [c=" + c + "]", c > 0); + // + // c = in.read(result); + // assertTrue("Codec101: Second read should report end-of-stream [c=" + c + "]", c < 0); + // } + + /** + * Another test for the CODEC-101 bug: In commons-codec-1.4 this test shows InputStreamReader explicitly hating an + * InputStream.read(byte[]) return of 0: + * + * java.io.IOException: Underlying input stream returned zero bytes at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:268) at + * sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306) at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158) at + * java.io.InputStreamReader.read(InputStreamReader.java:167) at java.io.BufferedReader.fill(BufferedReader.java:136) at + * java.io.BufferedReader.readLine(BufferedReader.java:299) at java.io.BufferedReader.readLine(BufferedReader.java:362) at + * org.apache.commons.codec.binary.Base32InputStreamTest.testInputStreamReader(Base32InputStreamTest.java:75) + * + * But in commons-codec-1.5 it's fixed. :-) + * + * @throws Exception + * for some failure scenarios. + */ + // @Test + // public void testInputStreamReader() throws Exception { + // byte[] codec101 = StringUtils.getBytesUtf8(Base32TestData.CODEC_101_MULTIPLE_OF_3); + // ByteArrayInputStream bais = new ByteArrayInputStream(codec101); + // Base32InputStream in = new Base32InputStream(bais); + // InputStreamReader isr = new InputStreamReader(in); + // BufferedReader br = new BufferedReader(isr); + // String line = br.readLine(); + // assertNotNull("Codec101: InputStreamReader works!", line); + // } + + /** + * Test the Base32InputStream implementation against the special NPE inducing input identified in the CODEC-98 bug. + * + * @throws Exception + * for some failure scenarios. + */ + // @Test + // public void testCodec98NPE() throws Exception { + // byte[] codec98 = StringUtils.getBytesUtf8(Base32TestData.CODEC_98_NPE); + // ByteArrayInputStream data = new ByteArrayInputStream(codec98); + // Base32InputStream stream = new Base32InputStream(data); + // + // // This line causes an NPE in commons-codec-1.4.jar: + // byte[] decodedBytes = Base32TestData.streamToBytes(stream, new byte[1024]); + // + // String decoded = StringUtils.newStringUtf8(decodedBytes); + // assertEquals( + // "codec-98 NPE Base32InputStream", Base32TestData.CODEC_98_NPE_DECODED, decoded + // ); + // } + + /** + * Tests skipping past the end of a stream. + * + * @throws Throwable + */ + @Test + public void testAvailable() throws Throwable { + InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); + Base32InputStream b32stream = new Base32InputStream(ins); + assertEquals(1, b32stream.available()); + assertEquals(3, b32stream.skip(10)); + // End of stream reached + assertEquals(0, b32stream.available()); + assertEquals(-1, b32stream.read()); + assertEquals(-1, b32stream.read()); + assertEquals(0, b32stream.available()); + } + + /** + * Tests the Base32InputStream implementation against empty input. + * + * @throws Exception + * for some failure scenarios. + */ + @Test + public void testBase32EmptyInputStreamMimeChuckSize() throws Exception { + testBase32EmptyInputStream(BaseNCodec.MIME_CHUNK_SIZE); + } + + /** + * Tests the Base32InputStream implementation against empty input. + * + * @throws Exception + * for some failure scenarios. + */ + @Test + public void testBase32EmptyInputStreamPemChuckSize() throws Exception { + testBase32EmptyInputStream(BaseNCodec.PEM_CHUNK_SIZE); + } + + private void testBase32EmptyInputStream(int chuckSize) throws Exception { + byte[] emptyEncoded = new byte[0]; + byte[] emptyDecoded = new byte[0]; + testByteByByte(emptyEncoded, emptyDecoded, chuckSize, CRLF); + testByChunk(emptyEncoded, emptyDecoded, chuckSize, CRLF); + } + + /** + * Tests the Base32InputStream implementation. + * + * @throws Exception + * for some failure scenarios. + */ + @Test + public void testBase32InputStreamByChunk() throws Exception { + // Hello World test. + byte[] encoded = StringUtils.getBytesUtf8(Base32TestData.BASE32_FIXTURE); + byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE); + testByChunk(encoded, decoded, BaseNCodec.MIME_CHUNK_SIZE, CRLF); + + // Single Byte test. + encoded = StringUtils.getBytesUtf8("AA======\r\n"); + decoded = new byte[] { (byte) 0 }; + testByChunk(encoded, decoded, BaseNCodec.MIME_CHUNK_SIZE, CRLF); + + // // OpenSSL interop test. + // encoded = StringUtils.getBytesUtf8(Base32TestData.ENCODED_32_CHARS_PER_LINE); + // decoded = Base32TestData.DECODED; + // testByChunk(encoded, decoded, Base32.PEM_CHUNK_SIZE, LF); + // + // // Single Line test. + // String singleLine = Base32TestData.ENCODED_32_CHARS_PER_LINE.replaceAll("\n", ""); + // encoded = StringUtils.getBytesUtf8(singleLine); + // decoded = Base32TestData.DECODED; + // testByChunk(encoded, decoded, 0, LF); + + // test random data of sizes 0 thru 150 + BaseNCodec codec = new Base32(); + for (int i = 0; i <= 150; i++) { + byte[][] randomData = Base32TestData.randomData(codec, i); + encoded = randomData[1]; + decoded = randomData[0]; + testByChunk(encoded, decoded, 0, LF); + } + } + + /** + * Tests the Base32InputStream implementation. + * + * @throws Exception + * for some failure scenarios. + */ + @Test + public void testBase32InputStreamByteByByte() throws Exception { + // Hello World test. + byte[] encoded = StringUtils.getBytesUtf8(Base32TestData.BASE32_FIXTURE); + byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE); + testByteByByte(encoded, decoded, BaseNCodec.MIME_CHUNK_SIZE, CRLF); + + // Single Byte test. + encoded = StringUtils.getBytesUtf8("AA======\r\n"); + decoded = new byte[] { (byte) 0 }; + testByteByByte(encoded, decoded, BaseNCodec.MIME_CHUNK_SIZE, CRLF); + + // // Single Line test. + // String singleLine = Base32TestData.ENCODED_32_CHARS_PER_LINE.replaceAll("\n", ""); + // encoded = StringUtils.getBytesUtf8(singleLine); + // decoded = Base32TestData.DECODED; + // testByteByByte(encoded, decoded, 0, LF); + + // test random data of sizes 0 thru 150 + BaseNCodec codec = new Base32(); + for (int i = 0; i <= 150; i++) { + byte[][] randomData = Base32TestData.randomData(codec, i); + encoded = randomData[1]; + decoded = randomData[0]; + testByteByByte(encoded, decoded, 0, LF); + } + } + + /** + * Tests method does three tests on the supplied data: 1. encoded ---[DECODE]--> decoded 2. decoded ---[ENCODE]--> encoded 3. decoded + * ---[WRAP-WRAP-WRAP-etc...] --> decoded + *

    + * By "[WRAP-WRAP-WRAP-etc...]" we mean situation where the Base32InputStream wraps itself in encode and decode mode over and over + * again. + * + * @param encoded + * base32 encoded data + * @param decoded + * the data from above, but decoded + * @param chunkSize + * chunk size (line-length) of the base32 encoded data. + * @param seperator + * Line separator in the base32 encoded data. + * @throws Exception + * Usually signifies a bug in the Base32 commons-codec implementation. + */ + private void testByChunk(byte[] encoded, byte[] decoded, int chunkSize, byte[] seperator) throws Exception { + + // Start with encode. + InputStream in = new ByteArrayInputStream(decoded); + in = new Base32InputStream(in, true, chunkSize, seperator); + byte[] output = Base32TestData.streamToBytes(in); + + assertEquals("EOF", -1, in.read()); + assertEquals("Still EOF", -1, in.read()); + assertTrue("Streaming base32 encode", Arrays.equals(output, encoded)); + + // Now let's try decode. + in = new ByteArrayInputStream(encoded); + in = new Base32InputStream(in); + output = Base32TestData.streamToBytes(in); + + assertEquals("EOF", -1, in.read()); + assertEquals("Still EOF", -1, in.read()); + assertTrue("Streaming base32 decode", Arrays.equals(output, decoded)); + + // I always wanted to do this! (wrap encoder with decoder etc etc). + in = new ByteArrayInputStream(decoded); + for (int i = 0; i < 10; i++) { + in = new Base32InputStream(in, true, chunkSize, seperator); + in = new Base32InputStream(in, false); + } + output = Base32TestData.streamToBytes(in); + + assertEquals("EOF", -1, in.read()); + assertEquals("Still EOF", -1, in.read()); + assertTrue("Streaming base32 wrap-wrap-wrap!", Arrays.equals(output, decoded)); + } + + /** + * Tests method does three tests on the supplied data: 1. encoded ---[DECODE]--> decoded 2. decoded ---[ENCODE]--> encoded 3. decoded + * ---[WRAP-WRAP-WRAP-etc...] --> decoded + *

    + * By "[WRAP-WRAP-WRAP-etc...]" we mean situation where the Base32InputStream wraps itself in encode and decode mode over and over + * again. + * + * @param encoded + * base32 encoded data + * @param decoded + * the data from above, but decoded + * @param chunkSize + * chunk size (line-length) of the base32 encoded data. + * @param seperator + * Line separator in the base32 encoded data. + * @throws Exception + * Usually signifies a bug in the Base32 commons-codec implementation. + */ + private void testByteByByte(byte[] encoded, byte[] decoded, int chunkSize, byte[] seperator) throws Exception { + + // Start with encode. + InputStream in = new ByteArrayInputStream(decoded); + in = new Base32InputStream(in, true, chunkSize, seperator); + byte[] output = new byte[encoded.length]; + for (int i = 0; i < output.length; i++) { + output[i] = (byte) in.read(); + } + + assertEquals("EOF", -1, in.read()); + assertEquals("Still EOF", -1, in.read()); + assertTrue("Streaming base32 encode", Arrays.equals(output, encoded)); + + // Now let's try decode. + in = new ByteArrayInputStream(encoded); + in = new Base32InputStream(in); + output = new byte[decoded.length]; + for (int i = 0; i < output.length; i++) { + output[i] = (byte) in.read(); + } + + assertEquals("EOF", -1, in.read()); + assertEquals("Still EOF", -1, in.read()); + assertTrue("Streaming base32 decode", Arrays.equals(output, decoded)); + + // I always wanted to do this! (wrap encoder with decoder etc etc). + in = new ByteArrayInputStream(decoded); + for (int i = 0; i < 10; i++) { + in = new Base32InputStream(in, true, chunkSize, seperator); + in = new Base32InputStream(in, false); + } + output = new byte[decoded.length]; + for (int i = 0; i < output.length; i++) { + output[i] = (byte) in.read(); + } + + assertEquals("EOF", -1, in.read()); + assertEquals("Still EOF", -1, in.read()); + assertTrue("Streaming base32 wrap-wrap-wrap!", Arrays.equals(output, decoded)); + } + + /** + * Tests markSupported. + * + * @throws Exception + */ + @Test + public void testMarkSupported() throws Exception { + byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE); + ByteArrayInputStream bin = new ByteArrayInputStream(decoded); + Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); + // Always returns false for now. + assertFalse("Base32InputStream.markSupported() is false", in.markSupported()); + } + + /** + * Tests read returning 0 + * + * @throws Exception + */ + @Test + public void testRead0() throws Exception { + byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE); + byte[] buf = new byte[1024]; + int bytesRead = 0; + ByteArrayInputStream bin = new ByteArrayInputStream(decoded); + Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); + bytesRead = in.read(buf, 0, 0); + assertEquals("Base32InputStream.read(buf, 0, 0) returns 0", 0, bytesRead); + } + + /** + * Tests read with null. + * + * @throws Exception + * for some failure scenarios. + */ + @Test + public void testReadNull() throws Exception { + byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE); + ByteArrayInputStream bin = new ByteArrayInputStream(decoded); + Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); + try { + in.read(null, 0, 0); + fail("Base32InputStream.read(null, 0, 0) to throw a NullPointerException"); + } catch (NullPointerException e) { + // Expected + } + } + + /** + * Tests read throwing IndexOutOfBoundsException + * + * @throws Exception + */ + @Test + public void testReadOutOfBounds() throws Exception { + byte[] decoded = StringUtils.getBytesUtf8(Base32TestData.STRING_FIXTURE); + byte[] buf = new byte[1024]; + ByteArrayInputStream bin = new ByteArrayInputStream(decoded); + Base32InputStream in = new Base32InputStream(bin, true, 4, new byte[] { 0, 0, 0 }); + + try { + in.read(buf, -1, 0); + fail("Expected Base32InputStream.read(buf, -1, 0) to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + in.read(buf, 0, -1); + fail("Expected Base32InputStream.read(buf, 0, -1) to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + in.read(buf, buf.length + 1, 0); + fail("Base32InputStream.read(buf, buf.length + 1, 0) throws IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + try { + in.read(buf, buf.length - 1, 2); + fail("Base32InputStream.read(buf, buf.length - 1, 2) throws IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } + + /** + * Tests skipping as a noop + * + * @throws Throwable + */ + @Test + public void testSkipNone() throws Throwable { + InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); + Base32InputStream b32stream = new Base32InputStream(ins); + byte[] actualBytes = new byte[6]; + assertEquals(0, b32stream.skip(0)); + b32stream.read(actualBytes, 0, actualBytes.length); + assertArrayEquals(actualBytes, new byte[] { 102, 111, 111, 0, 0, 0 }); + // End of stream reached + assertEquals(-1, b32stream.read()); + } + + /** + * Tests skipping number of characters larger than the internal buffer. + * + * @throws Throwable + */ + @Test + public void testSkipBig() throws Throwable { + InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); + Base32InputStream b32stream = new Base32InputStream(ins); + assertEquals(3, b32stream.skip(1024)); + // End of stream reached + assertEquals(-1, b32stream.read()); + assertEquals(-1, b32stream.read()); + } + + /** + * Tests skipping past the end of a stream. + * + * @throws Throwable + */ + @Test + public void testSkipPastEnd() throws Throwable { + InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); + Base32InputStream b32stream = new Base32InputStream(ins); + // due to CODEC-130, skip now skips correctly decoded characters rather than encoded + assertEquals(3, b32stream.skip(10)); + // End of stream reached + assertEquals(-1, b32stream.read()); + assertEquals(-1, b32stream.read()); + } + + /** + * Tests skipping to the end of a stream. + * + * @throws Throwable + */ + @Test + public void testSkipToEnd() throws Throwable { + InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); + Base32InputStream b32stream = new Base32InputStream(ins); + // due to CODEC-130, skip now skips correctly decoded characters rather than encoded + assertEquals(3, b32stream.skip(3)); + // End of stream reached + assertEquals(-1, b32stream.read()); + assertEquals(-1, b32stream.read()); + } + + /** + * Tests if negative arguments to skip are handled correctly. + * + * @throws Throwable + */ + @Test(expected=IllegalArgumentException.class) + public void testSkipWrongArgument() throws Throwable { + InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO)); + Base32InputStream b32stream = new Base32InputStream(ins); + b32stream.skip(-10); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.codec.binary.Base32InputStream` acquired to `in` by call to `Base32InputStream(...)` at line 403 is not released after line 404. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Base32InputStreamTest.testRead0() + +### Procedure Id: +org.apache.commons.codec.binary.Base32InputStreamTest.testRead0():void.515aed93c5a47cccd591977f19b59757 + +### File: +src/test/java/org/apache/commons/codec/binary/Base32InputStreamTest.java + +### Key: +Base32InputStreamTest.java|testRead0|RESOURCE_LEAK + +### Node Key: +5a6e208cc7f78de45b9aadcd0bcdb83f + +### Hash: +8411fe03d4963940c0e242fa4daf16ca + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3372/instruction.md b/inferredbugs-3372/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2394ff60bc87c50a72a1312ec67fbea9266b7c14 --- /dev/null +++ b/inferredbugs-3372/instruction.md @@ -0,0 +1,271 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** EMV-NFC-Paycard-Enrollment +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.devnied.emvnfccard.utils; + +import java.text.SimpleDateFormat; + +import org.fest.assertions.Assertions; +import org.junit.Test; + +import com.github.devnied.emvnfccard.model.EmvCard; +import com.github.devnied.emvnfccard.model.enums.ServiceCode1Enum; +import com.github.devnied.emvnfccard.model.enums.ServiceCode2Enum; +import com.github.devnied.emvnfccard.model.enums.ServiceCode3Enum; + +import fr.devnied.bitlib.BytesUtils; + +public class TrackUtilsTest { + + @Test + public void track1Test() { + EmvCard card = new EmvCard(); + boolean ret = TrackUtils + .extractTrack1Data( + card, + BytesUtils + .fromString("70 75 9F 6C 02 00 01 9F 62 06 00 00 00 38 00 00 9F 63 06 00 00 00 00 E0 E0 56 34 42343131313131313131313131313131313f305e202f5e31373032323031313030333f313030313030303030303030303030303f30303030 9F 64 01 03 9F 65 02 1C 00 9F 66 02 03 F0 9F 6B 13 5566887766556677 D1 81 02 01 00 00 00 00 00 10 0F 9F 67 01 03 90 00")); + + Assertions.assertThat(ret).isTrue(); + Assertions.assertThat(card).isNotNull(); + Assertions.assertThat(card.getCardNumber()).isEqualTo("4111111111111111"); + SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy"); + Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("02/2017"); + Assertions.assertThat(card.getTrack1()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC); + Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getInterchange()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getTechnology()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL); + Assertions.assertThat(card.getTrack1().getService().getServiceCode2().getAuthorizationProcessing()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION); + Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getAllowedServices()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getPinRequirements()).isNotNull(); + } + + @Test + public void track1NameTest() { + EmvCard card = new EmvCard(); + boolean ret = TrackUtils + .extractTrack1Data( + card, + BytesUtils + .fromString("563A42343131313131313131313131313131313F305E446F652F4A6F686E5E31373032323031313030333F313030313030303030303030303030303F30303030")); + + Assertions.assertThat(ret).isTrue(); + Assertions.assertThat(card).isNotNull(); + Assertions.assertThat(card.getCardNumber()).isEqualTo("4111111111111111"); + SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy"); + Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("02/2017"); + Assertions.assertThat(card.getTrack1()).isNotNull(); + Assertions.assertThat(card.getTrack1().getHolderFirstname()).isEqualTo("John"); + Assertions.assertThat(card.getTrack1().getHolderLastname()).isEqualTo("Doe"); + Assertions.assertThat(card.getTrack1().getService()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC); + Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getInterchange()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getTechnology()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL); + Assertions.assertThat(card.getTrack1().getService().getServiceCode2().getAuthorizationProcessing()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION); + Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getAllowedServices()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getPinRequirements()).isNotNull(); + } + + @Test + public void track1FormatTest() { + EmvCard card = new EmvCard(); + boolean ret = TrackUtils + .extractTrack1Data( + card, + BytesUtils + .fromString("564C42353231313131313131313131313131315E202F2020202020202020202020202020202020202020202020205E31363038323032303030303030303030303030312020303030202020202030")); + + Assertions.assertThat(ret).isTrue(); + Assertions.assertThat(card).isNotNull(); + Assertions.assertThat(card.getCardNumber()).isEqualTo("5211111111111111"); + SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy"); + Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("08/2016"); + Assertions.assertThat(card.getTrack1()).isNotNull(); + Assertions.assertThat(card.getTrack1().getHolderFirstname()).isNull(); + Assertions.assertThat(card.getTrack1().getHolderLastname()).isNull(); + Assertions.assertThat(card.getTrack1().getService()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC); + Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getInterchange()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getTechnology()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL); + Assertions.assertThat(card.getTrack1().getService().getServiceCode2().getAuthorizationProcessing()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.GOODS_SERVICES); + Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getAllowedServices()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getPinRequirements()).isNotNull(); + } + + @Test + public void track1FormatNullUser() { + EmvCard card = new EmvCard(); + boolean ret = TrackUtils + .extractTrack1Data( + card, + BytesUtils + .fromString("564C42353231313131313131313131313131315E22202020202020202020202020202020202020202020202020205E31363038323032303030303030303030303030312020303030202020202030")); + + Assertions.assertThat(ret).isTrue(); + Assertions.assertThat(card).isNotNull(); + Assertions.assertThat(card.getCardNumber()).isEqualTo("5211111111111111"); + SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy"); + Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("08/2016"); + Assertions.assertThat(card.getTrack1()).isNotNull(); + Assertions.assertThat(card.getTrack1().getHolderFirstname()).isNull(); + Assertions.assertThat(card.getTrack1().getHolderLastname()).isNull(); + Assertions.assertThat(card.getTrack1().getService()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC); + Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getInterchange()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getTechnology()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL); + Assertions.assertThat(card.getTrack1().getService().getServiceCode2().getAuthorizationProcessing()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.GOODS_SERVICES); + Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getAllowedServices()).isNotNull(); + Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getPinRequirements()).isNotNull(); + } + + @Test + public void track2Test() { + EmvCard card = new EmvCard(); + boolean ret = TrackUtils.extractTrack2Data(card, + BytesUtils.fromString("57 13 55 66 88 77 66 55 66 77 D1 50 62 01 69 28 07 65 90 00 0F")); + + Assertions.assertThat(ret).isTrue(); + Assertions.assertThat(card).isNotNull(); + Assertions.assertThat(card.getCardNumber()).isEqualTo("5566887766556677"); + SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy"); + Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("06/2015"); + Assertions.assertThat(card.getTrack2()).isNotNull(); + Assertions.assertThat(card.getTrack2().getService()).isNotNull(); + Assertions.assertThat(card.getTrack2().getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC); + Assertions.assertThat(card.getTrack2().getService().getServiceCode1().getInterchange()).isNotNull(); + Assertions.assertThat(card.getTrack2().getService().getServiceCode1().getTechnology()).isNotNull(); + Assertions.assertThat(card.getTrack2().getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL); + Assertions.assertThat(card.getTrack2().getService().getServiceCode2().getAuthorizationProcessing()).isNotNull(); + Assertions.assertThat(card.getTrack2().getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION); + Assertions.assertThat(card.getTrack2().getService().getServiceCode3().getAllowedServices()).isNotNull(); + Assertions.assertThat(card.getTrack2().getService().getServiceCode3().getPinRequirements()).isNotNull(); + } + + @Test + public void track2Test2() { + EmvCard card = new EmvCard(); + boolean ret = TrackUtils.extractTrack2Data(card, + BytesUtils.fromString("57 15 55 55 55 66 88 77 66 55 66 7D 11 05 62 01 69 28 07 65 90 00 0F")); + + Assertions.assertThat(ret).isTrue(); + Assertions.assertThat(card).isNotNull(); + Assertions.assertThat(card.getCardNumber()).isEqualTo("5555556688776655667"); + SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy"); + Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("05/2011"); + Assertions.assertThat(card.getTrack2()).isNotNull(); + Assertions.assertThat(card.getTrack2().getService()).isNotNull(); + Assertions.assertThat(card.getTrack2().getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.NATIONAL_ICC); + Assertions.assertThat(card.getTrack2().getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.BY_ISSUER); + Assertions.assertThat(card.getTrack2().getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION_PIN_REQUIRED); + } + + @Test + public void track2TestNullService() { + EmvCard card = new EmvCard(); + boolean ret = TrackUtils.extractTrack2Data(card, + BytesUtils.fromString("57 15 55 55 55 66 88 77 66 55 66 7D 11 05 FF F1 69 28 07 65 90 00 0F")); + + Assertions.assertThat(ret).isTrue(); + Assertions.assertThat(card).isNotNull(); + Assertions.assertThat(card.getCardNumber()).isEqualTo("5555556688776655667"); + SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy"); + Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("05/2011"); + Assertions.assertThat(card.getTrack2()).isNotNull(); + Assertions.assertThat(card.getTrack2().getService()).isNotNull(); + Assertions.assertThat(card.getTrack2().getService().getServiceCode1()).isNull(); + Assertions.assertThat(card.getTrack2().getService().getServiceCode2()).isNull(); + Assertions.assertThat(card.getTrack2().getService().getServiceCode3()).isNull(); + } + + @Test + public void track2TestNull() { + EmvCard card = new EmvCard(); + boolean ret = TrackUtils.extractTrack2Data(card, + BytesUtils.fromString("00")); + + Assertions.assertThat(ret).isFalse(); + Assertions.assertThat(card).isNotNull(); + Assertions.assertThat(card.getTrack2()).isNull(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `card.getTrack1()` could be null and is dereferenced at line 58. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TrackUtilsTest.track1NameTest() + +### Procedure Id: +com.github.devnied.emvnfccard.utils.TrackUtilsTest.track1NameTest():void.53e325339de4d12fd71debe3ee8a90d1 + +### File: +library/src/test/java/com/github/devnied/emvnfccard/utils/TrackUtilsTest.java + +### Key: +TrackUtilsTest.java|track1NameTest|NULL_DEREFERENCE + +### Node Key: +98e48d8af36063b905de6168fc1ae17c + +### Hash: +10ba20e0b90868175e9e7232c425c696 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3373/instruction.md b/inferredbugs-3373/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..11f6883f8c0189171765b7bb5d0bc9bb9f2da7cd --- /dev/null +++ b/inferredbugs-3373/instruction.md @@ -0,0 +1,830 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** javassist +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Javassist, a Java-bytecode translator toolkit. + * Copyright (C) 1999-2004 Shigeru Chiba. All Rights Reserved. + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. Alternatively, the contents of this file may be used under + * the terms of the GNU Lesser General Public License Version 2.1 or later. + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + */ + +package javassist.compiler; + +import javassist.CtClass; +import javassist.CtField; +import javassist.ClassPool; +import javassist.NotFoundException; +import javassist.compiler.ast.*; +import javassist.bytecode.*; + +public class TypeChecker extends Visitor implements Opcode, TokenId { + static final String javaLangObject = "java.lang.Object"; + static final String jvmJavaLangObject = "java/lang/Object"; + static final String jvmJavaLangString = "java/lang/String"; + static final String jvmJavaLangClass = "java/lang/Class"; + + /* The following fields are used by atXXX() methods + * for returning the type of the compiled expression. + */ + protected int exprType; // VOID, NULL, CLASS, BOOLEAN, INT, ... + protected int arrayDim; + protected String className; // JVM-internal representation + + protected MemberResolver resolver; + protected CtClass thisClass; + protected MethodInfo thisMethod; + + public TypeChecker(CtClass cc, ClassPool cp) { + resolver = new MemberResolver(cp); + thisClass = cc; + thisMethod = null; + } + + /** + * Records the currently compiled method. + */ + public void setThisMethod(MethodInfo m) { + thisMethod = m; + } + + protected static void fatal() throws CompileError { + throw new CompileError("fatal"); + } + + /** + * Returns the JVM-internal representation of this class name. + */ + protected String getThisName() { + return MemberResolver.javaToJvmName(thisClass.getName()); + } + + /** + * Returns the JVM-internal representation of this super class name. + */ + protected String getSuperName() throws CompileError { + return MemberResolver.javaToJvmName( + MemberResolver.getSuperclass(thisClass).getName()); + } + + /* Converts a class name into a JVM-internal representation. + * + * It may also expand a simple class name to java.lang.*. + * For example, this converts Object into java/lang/Object. + */ + protected String resolveClassName(ASTList name) throws CompileError { + return resolver.resolveClassName(name); + } + + /* Expands a simple class name to java.lang.*. + * For example, this converts Object into java/lang/Object. + */ + protected String resolveClassName(String jvmName) throws CompileError { + return resolver.resolveJvmClassName(jvmName); + } + + public void atNewExpr(NewExpr expr) throws CompileError { + if (expr.isArray()) + atNewArrayExpr(expr); + else { + CtClass clazz = resolver.lookupClassByName(expr.getClassName()); + String cname = clazz.getName(); + ASTList args = expr.getArguments(); + atMethodCallCore(clazz, MethodInfo.nameInit, args); + exprType = CLASS; + arrayDim = 0; + className = MemberResolver.javaToJvmName(cname); + } + } + + public void atNewArrayExpr(NewExpr expr) throws CompileError { + int type = expr.getArrayType(); + ASTList size = expr.getArraySize(); + ASTList classname = expr.getClassName(); + if (size.length() > 1) + atMultiNewArray(type, classname, size); + else { + size.head().accept(this); + exprType = type; + arrayDim = 1; + if (type == CLASS) + className = resolveClassName(classname); + else + className = null; + } + } + + protected void atMultiNewArray(int type, ASTList classname, ASTList size) + throws CompileError + { + int count, dim; + dim = size.length(); + for (count = 0; size != null; size = size.tail()) { + ASTree s = size.head(); + if (s == null) + break; // int[][][] a = new int[3][4][]; + + ++count; + s.accept(this); + } + + exprType = type; + arrayDim = dim; + if (type == CLASS) + className = resolveClassName(classname); + else + className = null; + } + + public void atAssignExpr(AssignExpr expr) throws CompileError { + // =, %=, &=, *=, /=, +=, -=, ^=, |=, <<=, >>=, >>>= + int op = expr.getOperator(); + ASTree left = expr.oprand1(); + ASTree right = expr.oprand2(); + if (left instanceof Variable) + atVariableAssign(expr, op, (Variable)left, + ((Variable)left).getDeclarator(), + right); + else { + if (left instanceof Expr) { + Expr e = (Expr)left; + if (e.getOperator() == ARRAY) { + atArrayAssign(expr, op, (Expr)left, right); + return; + } + } + + atFieldAssign(expr, op, left, right); + } + } + + /* op is either =, %=, &=, *=, /=, +=, -=, ^=, |=, <<=, >>=, or >>>=. + * + * expr and var can be null. + */ + private void atVariableAssign(Expr expr, int op, Variable var, + Declarator d, ASTree right) + throws CompileError + { + int varType = d.getType(); + int varArray = d.getArrayDim(); + String varClass = d.getClassName(); + + if (op != '=') + atVariable(var); + + right.accept(this); + exprType = varType; + arrayDim = varArray; + className = varClass; + } + + private void atArrayAssign(Expr expr, int op, Expr array, + ASTree right) throws CompileError + { + atArrayRead(array.oprand1(), array.oprand2()); + int aType = exprType; + int aDim = arrayDim; + String cname = className; + right.accept(this); + exprType = aType; + arrayDim = aDim; + className = cname; + } + + protected void atFieldAssign(Expr expr, int op, ASTree left, ASTree right) + throws CompileError + { + CtField f = fieldAccess(left); + atFieldRead(f); + int fType = exprType; + int fDim = arrayDim; + String cname = className; + right.accept(this); + exprType = fType; + arrayDim = fDim; + className = cname; + } + + public void atCondExpr(CondExpr expr) throws CompileError { + booleanExpr(expr.condExpr()); + expr.thenExpr().accept(this); + int type1 = exprType; + int dim1 = arrayDim; + String cname1 = className; + expr.elseExpr().accept(this); + + if (dim1 == 0 && dim1 == arrayDim) + if (CodeGen.rightIsStrong(type1, exprType)) + expr.setThen(new CastExpr(exprType, 0, expr.thenExpr())); + else if (CodeGen.rightIsStrong(exprType, type1)) { + expr.setElse(new CastExpr(type1, 0, expr.elseExpr())); + exprType = type1; + } + } + + public void atBinExpr(BinExpr expr) throws CompileError { + int token = expr.getOperator(); + int k = CodeGen.lookupBinOp(token); + if (k >= 0) { + /* arithmetic operators: +, -, *, /, %, |, ^, &, <<, >>, >>> + */ + if (token == '+') { + Expr e = atPlusExpr(expr); + if (e != null) { + /* String concatenation has been translated into + * an expression using StringBuffer. + */ + e = CallExpr.makeCall(Expr.make('.', e, + new Member("toString")), null); + expr.setLeft(e); + expr.setOprand2(null); // <---- look at this! + className = jvmJavaLangString; + } + } + else { + expr.oprand1().accept(this); + int type1 = exprType; + expr.oprand2().accept(this); + computeBinExprType(expr, token, type1); + } + } + else { + /* equation: &&, ||, ==, !=, <=, >=, <, > + */ + booleanExpr(expr); + } + } + + // expr must be a + expression. + private Expr atPlusExpr(BinExpr expr) throws CompileError { + ASTree left = expr.oprand1(); + ASTree right = expr.oprand2(); + if (right == null) { + /* this expression has been already type-checked since it is + string concatenation. + see atBinExpr() above. + */ + exprType = CLASS; + arrayDim = 0; + className = jvmJavaLangString; + return null; + } + + if (isPlusExpr(left)) { + Expr newExpr = atPlusExpr((BinExpr)left); + if (newExpr != null) { + right.accept(this); + exprType = CLASS; + arrayDim = 0; + className = "java/lang/StringBuffer"; + return makeAppendCall(newExpr, right); + } + } + else + left.accept(this); + + int type1 = exprType; + int dim1 = arrayDim; + String cname = className; + right.accept(this); + if ((type1 == CLASS && dim1 == 0 && jvmJavaLangString.equals(cname)) + || (exprType == CLASS && arrayDim == 0 + && jvmJavaLangString.equals(className))) { + ASTList sbufClass = ASTList.make(new Symbol("java"), + new Symbol("lang"), new Symbol("StringBuffer")); + ASTree e = new NewExpr(sbufClass, null); + exprType = CLASS; + arrayDim = 0; + className = "java/lang/StringBuffer"; + return makeAppendCall(makeAppendCall(e, left), right); + } + else { + computeBinExprType(expr, '+', type1); + return null; + } + } + + private static boolean isPlusExpr(ASTree expr) { + if (expr instanceof BinExpr) { + BinExpr bexpr = (BinExpr)expr; + int token = bexpr.getOperator(); + return token == '+'; + } + + return false; + } + + private static Expr makeAppendCall(ASTree target, ASTree arg) { + return CallExpr.makeCall(Expr.make('.', target, new Member("append")), + new ASTList(arg)); + } + + private void computeBinExprType(BinExpr expr, int token, int type1) + throws CompileError + { + // arrayDim should be 0. + int type2 = exprType; + if (token == LSHIFT || token == RSHIFT || token == ARSHIFT) + exprType = type1; + else + insertCast(expr, type1, type2); + + if (CodeGen.isP_INT(exprType)) + exprType = INT; // type1 may be BYTE, ... + } + + private void booleanExpr(ASTree expr) + throws CompileError + { + int op = CodeGen.getCompOperator(expr); + if (op == EQ) { // ==, !=, ... + BinExpr bexpr = (BinExpr)expr; + bexpr.oprand1().accept(this); + int type1 = exprType; + int dim1 = arrayDim; + bexpr.oprand2().accept(this); + if (dim1 == 0 && arrayDim == 0) + insertCast(bexpr, type1, exprType); + } + else if (op == '!') + ((Expr)expr).oprand1().accept(this); + else if (op == ANDAND || op == OROR) { + BinExpr bexpr = (BinExpr)expr; + bexpr.oprand1().accept(this); + bexpr.oprand2().accept(this); + } + else // others + expr.accept(this); + + exprType = BOOLEAN; + arrayDim = 0; + } + + private void insertCast(BinExpr expr, int type1, int type2) + throws CompileError + { + if (CodeGen.rightIsStrong(type1, type2)) + expr.setLeft(new CastExpr(type2, 0, expr.oprand1())); + else + exprType = type1; + } + + public void atCastExpr(CastExpr expr) throws CompileError { + String cname = resolveClassName(expr.getClassName()); + expr.getOprand().accept(this); + exprType = expr.getType(); + arrayDim = expr.getArrayDim(); + className = cname; + } + + public void atInstanceOfExpr(InstanceOfExpr expr) throws CompileError { + expr.getOprand().accept(this); + exprType = BOOLEAN; + arrayDim = 0; + } + + public void atExpr(Expr expr) throws CompileError { + // array access, member access, + // (unary) +, (unary) -, ++, --, !, ~ + + int token = expr.getOperator(); + ASTree oprand = expr.oprand1(); + if (token == '.') { + String member = ((Symbol)expr.oprand2()).get(); + if (member.equals("length")) + atArrayLength(expr); + else if (member.equals("class")) + atClassObject(expr); // .class + else + atFieldRead(expr); + } + else if (token == MEMBER) { // field read + String member = ((Symbol)expr.oprand2()).get(); + if (member.equals("class")) + atClassObject(expr); // .class + else + atFieldRead(expr); + } + else if (token == ARRAY) + atArrayRead(oprand, expr.oprand2()); + else if (token == PLUSPLUS || token == MINUSMINUS) + atPlusPlus(token, oprand, expr); + else if (token == '!') + booleanExpr(expr); + else if (token == CALL) // method call + fatal(); + else { + expr.oprand1().accept(this); + if (token == '-' || token == '~') + if (CodeGen.isP_INT(exprType)) + exprType = INT; // type may be BYTE, ... + } + } + + public void atCallExpr(CallExpr expr) throws CompileError { + String mname = null; + CtClass targetClass = null; + ASTree method = expr.oprand1(); + ASTList args = (ASTList)expr.oprand2(); + + if (method instanceof Member) { + mname = ((Member)method).get(); + targetClass = thisClass; + } + else if (method instanceof Keyword) { // constructor + mname = MethodInfo.nameInit; // + if (((Keyword)method).get() == SUPER) + targetClass = MemberResolver.getSuperclass(thisClass); + else + targetClass = thisClass; + } + else if (method instanceof Expr) { + Expr e = (Expr)method; + mname = ((Symbol)e.oprand2()).get(); + int op = e.getOperator(); + if (op == MEMBER) // static method + targetClass + = resolver.lookupClass(((Symbol)e.oprand1()).get(), + false); + else if (op == '.') { + ASTree target = e.oprand1(); + try { + target.accept(this); + } + catch (NoFieldException nfe) { + if (nfe.getExpr() != target) + throw nfe; + + // it should be a static method. + exprType = CLASS; + arrayDim = 0; + className = nfe.getField(); // JVM-internal + } + + if (arrayDim > 0) + targetClass = resolver.lookupClass(javaLangObject, true); + else if (exprType == CLASS /* && arrayDim == 0 */) + targetClass = resolver.lookupClassByJvmName(className); + else + badMethod(); + } + else + badMethod(); + } + else + fatal(); + + MemberResolver.Method minfo + = atMethodCallCore(targetClass, mname, args); + expr.setMethod(minfo); + } + + private static void badMethod() throws CompileError { + throw new CompileError("bad method"); + } + + /** + * @return a pair of the class declaring the invoked method + * and the MethodInfo of that method. Never null. + */ + public MemberResolver.Method atMethodCallCore(CtClass targetClass, + String mname, ASTList args) + throws CompileError + { + int nargs = getMethodArgsLength(args); + int[] types = new int[nargs]; + int[] dims = new int[nargs]; + String[] cnames = new String[nargs]; + atMethodArgs(args, types, dims, cnames); + + MemberResolver.Method found + = resolver.lookupMethod(targetClass, thisMethod, mname, + types, dims, cnames, false); + if (found == null) { + String msg; + if (mname.equals(MethodInfo.nameInit)) + msg = "constructor not found"; + else + msg = "Method " + mname + " not found in " + + targetClass.getName(); + + throw new CompileError(msg); + } + + String desc = found.info.getDescriptor(); + setReturnType(desc); + return found; + } + + public int getMethodArgsLength(ASTList args) { + return ASTList.length(args); + } + + public void atMethodArgs(ASTList args, int[] types, int[] dims, + String[] cnames) throws CompileError { + int i = 0; + while (args != null) { + ASTree a = args.head(); + a.accept(this); + types[i] = exprType; + dims[i] = arrayDim; + cnames[i] = className; + ++i; + args = args.tail(); + } + } + + void setReturnType(String desc) throws CompileError { + int i = desc.indexOf(')'); + if (i < 0) + badMethod(); + + char c = desc.charAt(++i); + int dim = 0; + while (c == '[') { + ++dim; + c = desc.charAt(++i); + } + + arrayDim = dim; + if (c == 'L') { + int j = desc.indexOf(';', i + 1); + if (j < 0) + badMethod(); + + exprType = CLASS; + className = desc.substring(i + 1, j); + } + else { + exprType = MemberResolver.descToType(c); + className = null; + } + } + + private void atFieldRead(ASTree expr) throws CompileError { + atFieldRead(fieldAccess(expr)); + } + + private void atFieldRead(CtField f) throws CompileError { + FieldInfo finfo = f.getFieldInfo2(); + String type = finfo.getDescriptor(); + + int i = 0; + int dim = 0; + char c = type.charAt(i); + while (c == '[') { + ++dim; + c = type.charAt(++i); + } + + arrayDim = dim; + exprType = MemberResolver.descToType(c); + + if (c == 'L') + className = type.substring(i + 1, type.indexOf(';', i + 1)); + else + className = null; + } + + protected CtField fieldAccess(ASTree expr) throws CompileError { + if (expr instanceof Member) { + String name = ((Member)expr).get(); + try { + return thisClass.getField(name); + } + catch (NotFoundException e) { + // EXPR might be part of a static member access? + throw new NoFieldException(name, expr); + } + } + else if (expr instanceof Expr) { + Expr e = (Expr)expr; + int op = e.getOperator(); + if (op == MEMBER) + return resolver.lookupField(((Symbol)e.oprand1()).get(), + (Symbol)e.oprand2()); + else if (op == '.') + try { + e.oprand1().accept(this); + if (exprType == CLASS && arrayDim == 0) + return resolver.lookupFieldByJvmName(className, + (Symbol)e.oprand2()); + } + catch (NoFieldException nfe) { + if (nfe.getExpr() != e.oprand1()) + throw nfe; + + /* EXPR should be a static field. + * If EXPR might be part of a qualified class name, + * lookupFieldByJvmName2() throws NoFieldException. + */ + Symbol fname = (Symbol)e.oprand2(); + return resolver.lookupFieldByJvmName2(nfe.getField(), + fname, expr); + } + } + + throw new CompileError("bad filed access"); + } + + public void atClassObject(Expr expr) throws CompileError { + exprType = CLASS; + arrayDim = 0; + className =jvmJavaLangClass; + } + + public void atArrayLength(Expr expr) throws CompileError { + expr.oprand1().accept(this); + exprType = INT; + arrayDim = 0; + } + + public void atArrayRead(ASTree array, ASTree index) + throws CompileError + { + array.accept(this); + int type = exprType; + int dim = arrayDim; + String cname = className; + index.accept(this); + exprType = type; + arrayDim = dim - 1; + className = cname; + } + + private void atPlusPlus(int token, ASTree oprand, Expr expr) + throws CompileError + { + boolean isPost = oprand == null; // ++i or i++? + if (isPost) + oprand = expr.oprand2(); + + if (oprand instanceof Variable) { + Declarator d = ((Variable)oprand).getDeclarator(); + exprType = d.getType(); + arrayDim = d.getArrayDim(); + } + else { + if (oprand instanceof Expr) { + Expr e = (Expr)oprand; + if (e.getOperator() == ARRAY) { + atArrayRead(e.oprand1(), e.oprand2()); + // arrayDim should be 0. + int t = exprType; + if (t == INT || t == BYTE || t == CHAR || t == SHORT) + exprType = INT; + + return; + } + } + + atFieldPlusPlus(oprand); + } + } + + protected void atFieldPlusPlus(ASTree oprand) throws CompileError + { + CtField f = fieldAccess(oprand); + atFieldRead(f); + int t = exprType; + if (t == INT || t == BYTE || t == CHAR || t == SHORT) + exprType = INT; + } + + public void atMember(Member mem) throws CompileError { + atFieldRead(mem); + } + + public void atVariable(Variable v) throws CompileError { + Declarator d = v.getDeclarator(); + exprType = d.getType(); + arrayDim = d.getArrayDim(); + className = d.getClassName(); + } + + public void atKeyword(Keyword k) throws CompileError { + arrayDim = 0; + int token = k.get(); + switch (token) { + case TRUE : + case FALSE : + exprType = BOOLEAN; + break; + case NULL : + exprType = NULL; + break; + case THIS : + case SUPER : + exprType = CLASS; + if (token == THIS) + className = getThisName(); + else + className = getSuperName(); + break; + default : + fatal(); + } + } + + public void atStringL(StringL s) throws CompileError { + exprType = CLASS; + arrayDim = 0; + className = jvmJavaLangString; + } + + public void atIntConst(IntConst i) throws CompileError { + arrayDim = 0; + int type = i.getType(); + if (type == IntConstant || type == CharConstant) + exprType = (type == IntConstant ? INT : CHAR); + else + exprType = LONG; + } + + public void atDoubleConst(DoubleConst d) throws CompileError { + arrayDim = 0; + if (d.getType() == DoubleConstant) + exprType = DOUBLE; + else + exprType = FLOAT; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `expr.oprand2()` could be null and is dereferenced at line 252. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TypeChecker.atBinExpr(BinExpr) + +### Procedure Id: +javassist.compiler.TypeChecker.atBinExpr(javassist.compiler.ast.BinExpr):void.6c6b77f49b94bea20d303dc75ee7bd77 + +### File: +src/main/javassist/compiler/TypeChecker.java + +### Key: +TypeChecker.java|atBinExpr|NULL_DEREFERENCE + +### Node Key: +a75dc278498198c713176bb8ed0c78f3 + +### Hash: +b297e77e919e13698314adebc7f3c4d4 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3374/instruction.md b/inferredbugs-3374/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f2177811ec3fc6678e8338c94f503fe1a514ceeb --- /dev/null +++ b/inferredbugs-3374/instruction.md @@ -0,0 +1,830 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** javassist +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Javassist, a Java-bytecode translator toolkit. + * Copyright (C) 1999-2004 Shigeru Chiba. All Rights Reserved. + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. Alternatively, the contents of this file may be used under + * the terms of the GNU Lesser General Public License Version 2.1 or later. + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + */ + +package javassist.compiler; + +import javassist.CtClass; +import javassist.CtField; +import javassist.ClassPool; +import javassist.NotFoundException; +import javassist.compiler.ast.*; +import javassist.bytecode.*; + +public class TypeChecker extends Visitor implements Opcode, TokenId { + static final String javaLangObject = "java.lang.Object"; + static final String jvmJavaLangObject = "java/lang/Object"; + static final String jvmJavaLangString = "java/lang/String"; + static final String jvmJavaLangClass = "java/lang/Class"; + + /* The following fields are used by atXXX() methods + * for returning the type of the compiled expression. + */ + protected int exprType; // VOID, NULL, CLASS, BOOLEAN, INT, ... + protected int arrayDim; + protected String className; // JVM-internal representation + + protected MemberResolver resolver; + protected CtClass thisClass; + protected MethodInfo thisMethod; + + public TypeChecker(CtClass cc, ClassPool cp) { + resolver = new MemberResolver(cp); + thisClass = cc; + thisMethod = null; + } + + /** + * Records the currently compiled method. + */ + public void setThisMethod(MethodInfo m) { + thisMethod = m; + } + + protected static void fatal() throws CompileError { + throw new CompileError("fatal"); + } + + /** + * Returns the JVM-internal representation of this class name. + */ + protected String getThisName() { + return MemberResolver.javaToJvmName(thisClass.getName()); + } + + /** + * Returns the JVM-internal representation of this super class name. + */ + protected String getSuperName() throws CompileError { + return MemberResolver.javaToJvmName( + MemberResolver.getSuperclass(thisClass).getName()); + } + + /* Converts a class name into a JVM-internal representation. + * + * It may also expand a simple class name to java.lang.*. + * For example, this converts Object into java/lang/Object. + */ + protected String resolveClassName(ASTList name) throws CompileError { + return resolver.resolveClassName(name); + } + + /* Expands a simple class name to java.lang.*. + * For example, this converts Object into java/lang/Object. + */ + protected String resolveClassName(String jvmName) throws CompileError { + return resolver.resolveJvmClassName(jvmName); + } + + public void atNewExpr(NewExpr expr) throws CompileError { + if (expr.isArray()) + atNewArrayExpr(expr); + else { + CtClass clazz = resolver.lookupClassByName(expr.getClassName()); + String cname = clazz.getName(); + ASTList args = expr.getArguments(); + atMethodCallCore(clazz, MethodInfo.nameInit, args); + exprType = CLASS; + arrayDim = 0; + className = MemberResolver.javaToJvmName(cname); + } + } + + public void atNewArrayExpr(NewExpr expr) throws CompileError { + int type = expr.getArrayType(); + ASTList size = expr.getArraySize(); + ASTList classname = expr.getClassName(); + if (size.length() > 1) + atMultiNewArray(type, classname, size); + else { + size.head().accept(this); + exprType = type; + arrayDim = 1; + if (type == CLASS) + className = resolveClassName(classname); + else + className = null; + } + } + + protected void atMultiNewArray(int type, ASTList classname, ASTList size) + throws CompileError + { + int count, dim; + dim = size.length(); + for (count = 0; size != null; size = size.tail()) { + ASTree s = size.head(); + if (s == null) + break; // int[][][] a = new int[3][4][]; + + ++count; + s.accept(this); + } + + exprType = type; + arrayDim = dim; + if (type == CLASS) + className = resolveClassName(classname); + else + className = null; + } + + public void atAssignExpr(AssignExpr expr) throws CompileError { + // =, %=, &=, *=, /=, +=, -=, ^=, |=, <<=, >>=, >>>= + int op = expr.getOperator(); + ASTree left = expr.oprand1(); + ASTree right = expr.oprand2(); + if (left instanceof Variable) + atVariableAssign(expr, op, (Variable)left, + ((Variable)left).getDeclarator(), + right); + else { + if (left instanceof Expr) { + Expr e = (Expr)left; + if (e.getOperator() == ARRAY) { + atArrayAssign(expr, op, (Expr)left, right); + return; + } + } + + atFieldAssign(expr, op, left, right); + } + } + + /* op is either =, %=, &=, *=, /=, +=, -=, ^=, |=, <<=, >>=, or >>>=. + * + * expr and var can be null. + */ + private void atVariableAssign(Expr expr, int op, Variable var, + Declarator d, ASTree right) + throws CompileError + { + int varType = d.getType(); + int varArray = d.getArrayDim(); + String varClass = d.getClassName(); + + if (op != '=') + atVariable(var); + + right.accept(this); + exprType = varType; + arrayDim = varArray; + className = varClass; + } + + private void atArrayAssign(Expr expr, int op, Expr array, + ASTree right) throws CompileError + { + atArrayRead(array.oprand1(), array.oprand2()); + int aType = exprType; + int aDim = arrayDim; + String cname = className; + right.accept(this); + exprType = aType; + arrayDim = aDim; + className = cname; + } + + protected void atFieldAssign(Expr expr, int op, ASTree left, ASTree right) + throws CompileError + { + CtField f = fieldAccess(left); + atFieldRead(f); + int fType = exprType; + int fDim = arrayDim; + String cname = className; + right.accept(this); + exprType = fType; + arrayDim = fDim; + className = cname; + } + + public void atCondExpr(CondExpr expr) throws CompileError { + booleanExpr(expr.condExpr()); + expr.thenExpr().accept(this); + int type1 = exprType; + int dim1 = arrayDim; + String cname1 = className; + expr.elseExpr().accept(this); + + if (dim1 == 0 && dim1 == arrayDim) + if (CodeGen.rightIsStrong(type1, exprType)) + expr.setThen(new CastExpr(exprType, 0, expr.thenExpr())); + else if (CodeGen.rightIsStrong(exprType, type1)) { + expr.setElse(new CastExpr(type1, 0, expr.elseExpr())); + exprType = type1; + } + } + + public void atBinExpr(BinExpr expr) throws CompileError { + int token = expr.getOperator(); + int k = CodeGen.lookupBinOp(token); + if (k >= 0) { + /* arithmetic operators: +, -, *, /, %, |, ^, &, <<, >>, >>> + */ + if (token == '+') { + Expr e = atPlusExpr(expr); + if (e != null) { + /* String concatenation has been translated into + * an expression using StringBuffer. + */ + e = CallExpr.makeCall(Expr.make('.', e, + new Member("toString")), null); + expr.setLeft(e); + expr.setOprand2(null); // <---- look at this! + className = jvmJavaLangString; + } + } + else { + expr.oprand1().accept(this); + int type1 = exprType; + expr.oprand2().accept(this); + computeBinExprType(expr, token, type1); + } + } + else { + /* equation: &&, ||, ==, !=, <=, >=, <, > + */ + booleanExpr(expr); + } + } + + // expr must be a + expression. + private Expr atPlusExpr(BinExpr expr) throws CompileError { + ASTree left = expr.oprand1(); + ASTree right = expr.oprand2(); + if (right == null) { + /* this expression has been already type-checked since it is + string concatenation. + see atBinExpr() above. + */ + exprType = CLASS; + arrayDim = 0; + className = jvmJavaLangString; + return null; + } + + if (isPlusExpr(left)) { + Expr newExpr = atPlusExpr((BinExpr)left); + if (newExpr != null) { + right.accept(this); + exprType = CLASS; + arrayDim = 0; + className = "java/lang/StringBuffer"; + return makeAppendCall(newExpr, right); + } + } + else + left.accept(this); + + int type1 = exprType; + int dim1 = arrayDim; + String cname = className; + right.accept(this); + if ((type1 == CLASS && dim1 == 0 && jvmJavaLangString.equals(cname)) + || (exprType == CLASS && arrayDim == 0 + && jvmJavaLangString.equals(className))) { + ASTList sbufClass = ASTList.make(new Symbol("java"), + new Symbol("lang"), new Symbol("StringBuffer")); + ASTree e = new NewExpr(sbufClass, null); + exprType = CLASS; + arrayDim = 0; + className = "java/lang/StringBuffer"; + return makeAppendCall(makeAppendCall(e, left), right); + } + else { + computeBinExprType(expr, '+', type1); + return null; + } + } + + private static boolean isPlusExpr(ASTree expr) { + if (expr instanceof BinExpr) { + BinExpr bexpr = (BinExpr)expr; + int token = bexpr.getOperator(); + return token == '+'; + } + + return false; + } + + private static Expr makeAppendCall(ASTree target, ASTree arg) { + return CallExpr.makeCall(Expr.make('.', target, new Member("append")), + new ASTList(arg)); + } + + private void computeBinExprType(BinExpr expr, int token, int type1) + throws CompileError + { + // arrayDim should be 0. + int type2 = exprType; + if (token == LSHIFT || token == RSHIFT || token == ARSHIFT) + exprType = type1; + else + insertCast(expr, type1, type2); + + if (CodeGen.isP_INT(exprType)) + exprType = INT; // type1 may be BYTE, ... + } + + private void booleanExpr(ASTree expr) + throws CompileError + { + int op = CodeGen.getCompOperator(expr); + if (op == EQ) { // ==, !=, ... + BinExpr bexpr = (BinExpr)expr; + bexpr.oprand1().accept(this); + int type1 = exprType; + int dim1 = arrayDim; + bexpr.oprand2().accept(this); + if (dim1 == 0 && arrayDim == 0) + insertCast(bexpr, type1, exprType); + } + else if (op == '!') + ((Expr)expr).oprand1().accept(this); + else if (op == ANDAND || op == OROR) { + BinExpr bexpr = (BinExpr)expr; + bexpr.oprand1().accept(this); + bexpr.oprand2().accept(this); + } + else // others + expr.accept(this); + + exprType = BOOLEAN; + arrayDim = 0; + } + + private void insertCast(BinExpr expr, int type1, int type2) + throws CompileError + { + if (CodeGen.rightIsStrong(type1, type2)) + expr.setLeft(new CastExpr(type2, 0, expr.oprand1())); + else + exprType = type1; + } + + public void atCastExpr(CastExpr expr) throws CompileError { + String cname = resolveClassName(expr.getClassName()); + expr.getOprand().accept(this); + exprType = expr.getType(); + arrayDim = expr.getArrayDim(); + className = cname; + } + + public void atInstanceOfExpr(InstanceOfExpr expr) throws CompileError { + expr.getOprand().accept(this); + exprType = BOOLEAN; + arrayDim = 0; + } + + public void atExpr(Expr expr) throws CompileError { + // array access, member access, + // (unary) +, (unary) -, ++, --, !, ~ + + int token = expr.getOperator(); + ASTree oprand = expr.oprand1(); + if (token == '.') { + String member = ((Symbol)expr.oprand2()).get(); + if (member.equals("length")) + atArrayLength(expr); + else if (member.equals("class")) + atClassObject(expr); // .class + else + atFieldRead(expr); + } + else if (token == MEMBER) { // field read + String member = ((Symbol)expr.oprand2()).get(); + if (member.equals("class")) + atClassObject(expr); // .class + else + atFieldRead(expr); + } + else if (token == ARRAY) + atArrayRead(oprand, expr.oprand2()); + else if (token == PLUSPLUS || token == MINUSMINUS) + atPlusPlus(token, oprand, expr); + else if (token == '!') + booleanExpr(expr); + else if (token == CALL) // method call + fatal(); + else { + expr.oprand1().accept(this); + if (token == '-' || token == '~') + if (CodeGen.isP_INT(exprType)) + exprType = INT; // type may be BYTE, ... + } + } + + public void atCallExpr(CallExpr expr) throws CompileError { + String mname = null; + CtClass targetClass = null; + ASTree method = expr.oprand1(); + ASTList args = (ASTList)expr.oprand2(); + + if (method instanceof Member) { + mname = ((Member)method).get(); + targetClass = thisClass; + } + else if (method instanceof Keyword) { // constructor + mname = MethodInfo.nameInit; // + if (((Keyword)method).get() == SUPER) + targetClass = MemberResolver.getSuperclass(thisClass); + else + targetClass = thisClass; + } + else if (method instanceof Expr) { + Expr e = (Expr)method; + mname = ((Symbol)e.oprand2()).get(); + int op = e.getOperator(); + if (op == MEMBER) // static method + targetClass + = resolver.lookupClass(((Symbol)e.oprand1()).get(), + false); + else if (op == '.') { + ASTree target = e.oprand1(); + try { + target.accept(this); + } + catch (NoFieldException nfe) { + if (nfe.getExpr() != target) + throw nfe; + + // it should be a static method. + exprType = CLASS; + arrayDim = 0; + className = nfe.getField(); // JVM-internal + } + + if (arrayDim > 0) + targetClass = resolver.lookupClass(javaLangObject, true); + else if (exprType == CLASS /* && arrayDim == 0 */) + targetClass = resolver.lookupClassByJvmName(className); + else + badMethod(); + } + else + badMethod(); + } + else + fatal(); + + MemberResolver.Method minfo + = atMethodCallCore(targetClass, mname, args); + expr.setMethod(minfo); + } + + private static void badMethod() throws CompileError { + throw new CompileError("bad method"); + } + + /** + * @return a pair of the class declaring the invoked method + * and the MethodInfo of that method. Never null. + */ + public MemberResolver.Method atMethodCallCore(CtClass targetClass, + String mname, ASTList args) + throws CompileError + { + int nargs = getMethodArgsLength(args); + int[] types = new int[nargs]; + int[] dims = new int[nargs]; + String[] cnames = new String[nargs]; + atMethodArgs(args, types, dims, cnames); + + MemberResolver.Method found + = resolver.lookupMethod(targetClass, thisMethod, mname, + types, dims, cnames, false); + if (found == null) { + String msg; + if (mname.equals(MethodInfo.nameInit)) + msg = "constructor not found"; + else + msg = "Method " + mname + " not found in " + + targetClass.getName(); + + throw new CompileError(msg); + } + + String desc = found.info.getDescriptor(); + setReturnType(desc); + return found; + } + + public int getMethodArgsLength(ASTList args) { + return ASTList.length(args); + } + + public void atMethodArgs(ASTList args, int[] types, int[] dims, + String[] cnames) throws CompileError { + int i = 0; + while (args != null) { + ASTree a = args.head(); + a.accept(this); + types[i] = exprType; + dims[i] = arrayDim; + cnames[i] = className; + ++i; + args = args.tail(); + } + } + + void setReturnType(String desc) throws CompileError { + int i = desc.indexOf(')'); + if (i < 0) + badMethod(); + + char c = desc.charAt(++i); + int dim = 0; + while (c == '[') { + ++dim; + c = desc.charAt(++i); + } + + arrayDim = dim; + if (c == 'L') { + int j = desc.indexOf(';', i + 1); + if (j < 0) + badMethod(); + + exprType = CLASS; + className = desc.substring(i + 1, j); + } + else { + exprType = MemberResolver.descToType(c); + className = null; + } + } + + private void atFieldRead(ASTree expr) throws CompileError { + atFieldRead(fieldAccess(expr)); + } + + private void atFieldRead(CtField f) throws CompileError { + FieldInfo finfo = f.getFieldInfo2(); + String type = finfo.getDescriptor(); + + int i = 0; + int dim = 0; + char c = type.charAt(i); + while (c == '[') { + ++dim; + c = type.charAt(++i); + } + + arrayDim = dim; + exprType = MemberResolver.descToType(c); + + if (c == 'L') + className = type.substring(i + 1, type.indexOf(';', i + 1)); + else + className = null; + } + + protected CtField fieldAccess(ASTree expr) throws CompileError { + if (expr instanceof Member) { + String name = ((Member)expr).get(); + try { + return thisClass.getField(name); + } + catch (NotFoundException e) { + // EXPR might be part of a static member access? + throw new NoFieldException(name, expr); + } + } + else if (expr instanceof Expr) { + Expr e = (Expr)expr; + int op = e.getOperator(); + if (op == MEMBER) + return resolver.lookupField(((Symbol)e.oprand1()).get(), + (Symbol)e.oprand2()); + else if (op == '.') + try { + e.oprand1().accept(this); + if (exprType == CLASS && arrayDim == 0) + return resolver.lookupFieldByJvmName(className, + (Symbol)e.oprand2()); + } + catch (NoFieldException nfe) { + if (nfe.getExpr() != e.oprand1()) + throw nfe; + + /* EXPR should be a static field. + * If EXPR might be part of a qualified class name, + * lookupFieldByJvmName2() throws NoFieldException. + */ + Symbol fname = (Symbol)e.oprand2(); + return resolver.lookupFieldByJvmName2(nfe.getField(), + fname, expr); + } + } + + throw new CompileError("bad filed access"); + } + + public void atClassObject(Expr expr) throws CompileError { + exprType = CLASS; + arrayDim = 0; + className =jvmJavaLangClass; + } + + public void atArrayLength(Expr expr) throws CompileError { + expr.oprand1().accept(this); + exprType = INT; + arrayDim = 0; + } + + public void atArrayRead(ASTree array, ASTree index) + throws CompileError + { + array.accept(this); + int type = exprType; + int dim = arrayDim; + String cname = className; + index.accept(this); + exprType = type; + arrayDim = dim - 1; + className = cname; + } + + private void atPlusPlus(int token, ASTree oprand, Expr expr) + throws CompileError + { + boolean isPost = oprand == null; // ++i or i++? + if (isPost) + oprand = expr.oprand2(); + + if (oprand instanceof Variable) { + Declarator d = ((Variable)oprand).getDeclarator(); + exprType = d.getType(); + arrayDim = d.getArrayDim(); + } + else { + if (oprand instanceof Expr) { + Expr e = (Expr)oprand; + if (e.getOperator() == ARRAY) { + atArrayRead(e.oprand1(), e.oprand2()); + // arrayDim should be 0. + int t = exprType; + if (t == INT || t == BYTE || t == CHAR || t == SHORT) + exprType = INT; + + return; + } + } + + atFieldPlusPlus(oprand); + } + } + + protected void atFieldPlusPlus(ASTree oprand) throws CompileError + { + CtField f = fieldAccess(oprand); + atFieldRead(f); + int t = exprType; + if (t == INT || t == BYTE || t == CHAR || t == SHORT) + exprType = INT; + } + + public void atMember(Member mem) throws CompileError { + atFieldRead(mem); + } + + public void atVariable(Variable v) throws CompileError { + Declarator d = v.getDeclarator(); + exprType = d.getType(); + arrayDim = d.getArrayDim(); + className = d.getClassName(); + } + + public void atKeyword(Keyword k) throws CompileError { + arrayDim = 0; + int token = k.get(); + switch (token) { + case TRUE : + case FALSE : + exprType = BOOLEAN; + break; + case NULL : + exprType = NULL; + break; + case THIS : + case SUPER : + exprType = CLASS; + if (token == THIS) + className = getThisName(); + else + className = getSuperName(); + break; + default : + fatal(); + } + } + + public void atStringL(StringL s) throws CompileError { + exprType = CLASS; + arrayDim = 0; + className = jvmJavaLangString; + } + + public void atIntConst(IntConst i) throws CompileError { + arrayDim = 0; + int type = i.getType(); + if (type == IntConstant || type == CharConstant) + exprType = (type == IntConstant ? INT : CHAR); + else + exprType = LONG; + } + + public void atDoubleConst(DoubleConst d) throws CompileError { + arrayDim = 0; + if (d.getType() == DoubleConstant) + exprType = DOUBLE; + else + exprType = FLOAT; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `expr.oprand2()` could be null and is dereferenced at line 407. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TypeChecker.atExpr(Expr) + +### Procedure Id: +javassist.compiler.TypeChecker.atExpr(javassist.compiler.ast.Expr):void.66b987b941827c31e9653c679ee8d4b2 + +### File: +src/main/javassist/compiler/TypeChecker.java + +### Key: +TypeChecker.java|atExpr|NULL_DEREFERENCE + +### Node Key: +dc678d91476904c7b1b2af11d980af71 + +### Hash: +7e9a2cda38e9d24c4fe64da5e7aa07ef + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3375/instruction.md b/inferredbugs-3375/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..74cf5fa98bba0f0c86f8bac8b365d88d20abcddd --- /dev/null +++ b/inferredbugs-3375/instruction.md @@ -0,0 +1,1024 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** javassist +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Javassist, a Java-bytecode translator toolkit. + * Copyright (C) 1999-2004 Shigeru Chiba. All Rights Reserved. + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. Alternatively, the contents of this file may be used under + * the terms of the GNU Lesser General Public License Version 2.1 or later. + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + */ + +package javassist; + +import javassist.bytecode.*; +import javassist.compiler.Javac; +import javassist.compiler.CompileError; +import javassist.expr.ExprEditor; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.List; + +/** + * Class types. + */ +class CtClassType extends CtClass { + ClassPool classPool; + boolean wasChanged; + boolean wasFrozen; + ClassFile classfile; + + private CtField fieldsCache; + private CtConstructor constructorsCache; + private CtConstructor classInitializerCache; + private CtMethod methodsCache; + + private FieldInitLink fieldInitializers; + private Hashtable hiddenMethods; // must be synchronous + private int uniqueNumberSeed; + + CtClassType(String name, ClassPool cp) { + super(name); + classPool = cp; + wasChanged = wasFrozen = false; + classfile = null; + fieldInitializers = null; + hiddenMethods = null; + uniqueNumberSeed = 0; + eraseCache(); + } + + CtClassType(InputStream ins, ClassPool cp) throws IOException { + this((String)null, cp); + classfile = new ClassFile(new DataInputStream(ins)); + qualifiedName = classfile.getName(); + } + + protected void extendToString(StringBuffer buffer) { + if (wasChanged) + buffer.append(" changed"); + + if (wasFrozen) + buffer.append(" frozen"); + + CtField field = getFieldsCache(); + buffer.append(" fields="); + while (field != null) { + buffer.append(field); + buffer.append(", "); + field = field.next; + } + + CtConstructor c = getConstructorsCache(); + buffer.append(" constructors="); + while (c != null) { + buffer.append(c); + buffer.append(", "); + c = c.next; + } + + CtMethod m = getMethodsCache(); + buffer.append(" methods="); + while (m != null) { + buffer.append(m); + buffer.append(", "); + m = m.next; + } + } + + protected void eraseCache() { + fieldsCache = null; + constructorsCache = null; + classInitializerCache = null; + methodsCache = null; + } + + public ClassFile getClassFile2() { + if (classfile != null) + return classfile; + + try { + byte[] b = classPool.readSource(getName()); + DataInputStream dis + = new DataInputStream(new ByteArrayInputStream(b)); + return (classfile = new ClassFile(dis)); + } + catch (NotFoundException e) { + throw new RuntimeException(e.toString()); + } + catch (IOException e) { + throw new RuntimeException(e.toString()); + } + catch (CannotCompileException e) { + throw new RuntimeException(e.toString()); + } + } + + public ClassPool getClassPool() { return classPool; } + + void setClassPool(ClassPool cp) { classPool = cp; } + + public URL getURL() throws NotFoundException { + URL url = classPool.find(getName()); + if (url == null) + throw new NotFoundException(getName()); + else + return url; + } + + public boolean isModified() { return wasChanged; } + + public boolean isFrozen() { return wasFrozen; } + + void freeze() { wasFrozen = true; } + + void checkModify() throws RuntimeException { + super.checkModify(); + wasChanged = true; + } + + public void defrost() { wasFrozen = false; } + + public boolean subtypeOf(CtClass clazz) throws NotFoundException { + int i; + String cname = clazz.getName(); + if (this == clazz || getName().equals(cname)) + return true; + + ClassFile file = getClassFile2(); + String supername = file.getSuperclass(); + if (supername != null && supername.equals(cname)) + return true; + + String[] ifs = file.getInterfaces(); + int num = ifs.length; + for (i = 0; i < num; ++i) + if (ifs[i].equals(cname)) + return true; + + if (supername != null && classPool.get(supername).subtypeOf(clazz)) + return true; + + for (i = 0; i < num; ++i) + if (classPool.get(ifs[i]).subtypeOf(clazz)) + return true; + + return false; + } + + public void setName(String name) throws RuntimeException { + String oldname = getName(); + if (name.equals(oldname)) + return; + + // check this in advance although classNameChanged() below does. + classPool.checkNotFrozen(name); + ClassFile cf = getClassFile2(); + super.setName(name); + cf.setName(name); + eraseCache(); + classPool.classNameChanged(oldname, this); + } + + public void replaceClassName(ClassMap classnames) + throws RuntimeException + { + String oldClassName = getName(); + String newClassName + = (String)classnames.get(Descriptor.toJvmName(oldClassName)); + if (newClassName != null) { + newClassName = Descriptor.toJavaName(newClassName); + // check this in advance although classNameChanged() below does. + classPool.checkNotFrozen(newClassName); + } + + super.replaceClassName(classnames); + ClassFile cf = getClassFile2(); + cf.renameClass(classnames); + eraseCache(); + + if (newClassName != null) { + super.setName(newClassName); + classPool.classNameChanged(oldClassName, this); + } + } + + public void replaceClassName(String oldname, String newname) + throws RuntimeException + { + String thisname = getName(); + if (thisname.equals(oldname)) + setName(newname); + else { + super.replaceClassName(oldname, newname); + getClassFile2().renameClass(oldname, newname); + eraseCache(); + } + } + + public boolean isInterface() { + return Modifier.isInterface(getModifiers()); + } + + public int getModifiers() { + int acc = getClassFile2().getAccessFlags(); + acc = AccessFlag.clear(acc, AccessFlag.SUPER); + return AccessFlag.toModifier(acc); + } + + public void setModifiers(int mod) { + checkModify(); + int acc = AccessFlag.of(mod) | AccessFlag.SUPER; + getClassFile2().setAccessFlags(acc); + } + + public boolean subclassOf(CtClass superclass) { + if (superclass == null) + return false; + + String superName = superclass.getName(); + CtClass curr = this; + try { + while (curr != null) { + if (curr.getName().equals(superName)) + return true; + + curr = curr.getSuperclass(); + } + } + catch (Exception ignored) {} + return false; + } + + public CtClass getSuperclass() throws NotFoundException { + String supername = getClassFile2().getSuperclass(); + if (supername == null) + return null; + else + return classPool.get(supername); + } + + public void setSuperclass(CtClass clazz) throws CannotCompileException { + checkModify(); + if (isInterface()) + addInterface(clazz); + else + getClassFile2().setSuperclass(clazz.getName()); + } + + public CtClass[] getInterfaces() throws NotFoundException { + String[] ifs = getClassFile2().getInterfaces(); + int num = ifs.length; + CtClass[] ifc = new CtClass[num]; + for (int i = 0; i < num; ++i) + ifc[i] = classPool.get(ifs[i]); + + return ifc; + } + + public void setInterfaces(CtClass[] list) { + checkModify(); + String[] ifs; + if (list == null) + ifs = new String[0]; + else { + int num = list.length; + ifs = new String[num]; + for (int i = 0; i < num; ++i) + ifs[i] = list[i].getName(); + } + + getClassFile2().setInterfaces(ifs); + } + + public void addInterface(CtClass anInterface) { + checkModify(); + if (anInterface != null) + getClassFile2().addInterface(anInterface.getName()); + } + + public CtField[] getFields() { + ArrayList alist = new ArrayList(); + getFields(alist, this); + return (CtField[])alist.toArray(new CtField[alist.size()]); + } + + private static void getFields(ArrayList alist, CtClass cc) { + int i, num; + if (cc == null) + return; + + try { + getFields(alist, cc.getSuperclass()); + } + catch (NotFoundException e) {} + + try { + CtClass[] ifs = cc.getInterfaces(); + num = ifs.length; + for (i = 0; i < num; ++i) + getFields(alist, ifs[i]); + } + catch (NotFoundException e) {} + + CtField cf = ((CtClassType)cc).getFieldsCache(); + while (cf != null) { + if (Modifier.isPublic(cf.getModifiers())) + alist.add(cf); + + cf = cf.next; + } + } + + public CtField getField(String name) throws NotFoundException { + CtField f = getField2(name); + if (f == null) + throw new NotFoundException("field: " + name + " in " + getName()); + else + return f; + } + + CtField getField2(String name) { + CtField df = getDeclaredField2(name); + if (df != null) + return df; + + try { + CtClass[] ifs = getInterfaces(); + int num = ifs.length; + for (int i = 0; i < num; ++i) { + CtField f = ifs[i].getField2(name); + if (f != null) + return f; + } + + CtClass s = getSuperclass(); + if (s != null) + return s.getField2(name); + } + catch (NotFoundException e) {} + return null; + } + + public CtField[] getDeclaredFields() { + CtField cf = getFieldsCache(); + int num = CtField.count(cf); + CtField[] cfs = new CtField[num]; + int i = 0; + while (cf != null) { + cfs[i++] = cf; + cf = cf.next; + } + + return cfs; + } + + protected CtField getFieldsCache() { + if (fieldsCache == null) { + List list = getClassFile2().getFields(); + int n = list.size(); + for (int i = 0; i < n; ++i) { + FieldInfo finfo = (FieldInfo)list.get(i); + fieldsCache = CtField.append(fieldsCache, + new CtField(finfo, this)); + } + } + + return fieldsCache; + } + + public CtField getDeclaredField(String name) throws NotFoundException { + CtField f = getDeclaredField2(name); + if (f == null) + throw new NotFoundException("field: " + name + " in " + getName()); + else + return f; + } + + private CtField getDeclaredField2(String name) { + CtField cf = getFieldsCache(); + while (cf != null) { + if (cf.getName().equals(name)) + return cf; + + cf = cf.next; + } + + return null; + } + + public CtBehavior[] getDeclaredBehaviors() { + CtConstructor cc = getConstructorsCache(); + CtMethod cm = getMethodsCache(); + int num = CtMethod.count(cm) + CtConstructor.count(cc); + CtBehavior[] cb = new CtBehavior[num]; + int i = 0; + while (cc != null) { + cb[i++] = cc; + cc = cc.next; + } + + while (cm != null) { + cb[i++] = cm; + cm = cm.next; + } + + return cb; + } + + public CtConstructor[] getConstructors() { + CtConstructor[] cons = getDeclaredConstructors(); + if (cons.length == 0) + return cons; + + int n = 0; + int i = cons.length; + while (--i >= 0) + if (Modifier.isPublic(cons[i].getModifiers())) + ++n; + + CtConstructor[] result = new CtConstructor[n]; + n = 0; + i = cons.length; + while (--i >= 0) { + CtConstructor c = cons[i]; + if (Modifier.isPublic(c.getModifiers())) + result[n++] = c; + } + + return result; + } + + public CtConstructor getConstructor(String desc) + throws NotFoundException + { + CtConstructor cc = getConstructorsCache(); + while (cc != null) { + if (cc.getMethodInfo2().getDescriptor().equals(desc)) + return cc; + + cc = cc.next; + } + + return super.getConstructor(desc); + } + + public CtConstructor[] getDeclaredConstructors() { + CtConstructor cc = getConstructorsCache(); + int num = CtConstructor.count(cc); + CtConstructor[] ccs = new CtConstructor[num]; + int i = 0; + while (cc != null) { + ccs[i++] = cc; + cc = cc.next; + } + + return ccs; + } + + protected CtConstructor getConstructorsCache() { + if (constructorsCache == null) { + List list = getClassFile2().getMethods(); + int n = list.size(); + for (int i = 0; i < n; ++i) { + MethodInfo minfo = (MethodInfo)list.get(i); + if (minfo.isConstructor()) + constructorsCache + = CtConstructor.append(constructorsCache, + new CtConstructor(minfo, this)); + } + } + + return constructorsCache; + } + + public CtConstructor getClassInitializer() { + if (classInitializerCache == null) { + MethodInfo minfo = getClassFile2().getStaticInitializer(); + if (minfo != null) + classInitializerCache = new CtConstructor(minfo, this); + } + + return classInitializerCache; + } + + public CtMethod[] getMethods() { + HashMap h = new HashMap(); + getMethods0(h, this); + return (CtMethod[])h.values().toArray(new CtMethod[0]); + } + + private static void getMethods0(HashMap h, CtClass cc) { + try { + CtClass[] ifs = cc.getInterfaces(); + int size = ifs.length; + for (int i = 0; i < size; ++i) + getMethods0(h, ifs[i]); + } + catch (NotFoundException e) {} + + try { + CtClass s = cc.getSuperclass(); + if (s != null) + getMethods0(h, s); + } + catch (NotFoundException e) {} + + if (cc instanceof CtClassType) { + CtMethod cm = ((CtClassType)cc).getMethodsCache(); + while (cm != null) { + if (Modifier.isPublic(cm.getModifiers())) + h.put(cm, cm); + + cm = cm.next; + } + } + } + + public CtMethod getMethod(String name, String desc) + throws NotFoundException + { + CtMethod m = getMethod0(this, name, desc); + if (m != null) + return m; + else + throw new NotFoundException(name + "(..) is not found in " + + getName()); + } + + private static CtMethod getMethod0(CtClass cc, + String name, String desc) { + if (cc instanceof CtClassType) { + CtMethod cm = ((CtClassType)cc).getMethodsCache(); + while (cm != null) { + if (cm.getName().equals(name) + && cm.getMethodInfo2().getDescriptor().equals(desc)) + return cm; + + cm = cm.next; + } + } + + try { + CtClass s = cc.getSuperclass(); + if (s != null) { + CtMethod m = getMethod0(s, name, desc); + if (m != null) + return m; + } + } + catch (NotFoundException e) {} + + try { + CtClass[] ifs = cc.getInterfaces(); + int size = ifs.length; + for (int i = 0; i < size; ++i) { + CtMethod m = getMethod0(ifs[i], name, desc); + if (m != null) + return m; + } + } + catch (NotFoundException e) {} + return null; + } + + public CtMethod[] getDeclaredMethods() { + CtMethod cm = getMethodsCache(); + int num = CtMethod.count(cm); + CtMethod[] cms = new CtMethod[num]; + int i = 0; + while (cm != null) { + cms[i++] = cm; + cm = cm.next; + } + + return cms; + } + + public CtMethod getDeclaredMethod(String name) throws NotFoundException { + CtMethod m = getMethodsCache(); + while (m != null) { + if (m.getName().equals(name)) + return m; + + m = m.next; + } + + throw new NotFoundException(name + "(..) is not found in " + + getName()); + } + + public CtMethod getDeclaredMethod(String name, CtClass[] params) + throws NotFoundException + { + String desc = Descriptor.ofParameters(params); + CtMethod m = getMethodsCache(); + while (m != null) { + if (m.getName().equals(name) + && m.getMethodInfo2().getDescriptor().startsWith(desc)) + return m; + + m = m.next; + } + + throw new NotFoundException(name + "(..) is not found in " + + getName()); + } + + protected CtMethod getMethodsCache() { + if (methodsCache == null) { + List list = getClassFile2().getMethods(); + int n = list.size(); + for (int i = 0; i < n; ++i) { + MethodInfo minfo = (MethodInfo)list.get(i); + if (minfo.isMethod()) + methodsCache = CtMethod.append(methodsCache, + new CtMethod(minfo, this)); + } + } + + return methodsCache; + } + + public void addField(CtField f, String init) + throws CannotCompileException + { + addField(f, CtField.Initializer.byExpr(init)); + } + + public void addField(CtField f, CtField.Initializer init) + throws CannotCompileException + { + checkModify(); + if (f.getDeclaringClass() != this) + throw new CannotCompileException("cannot add"); + + if (init == null) + init = f.getInit(); + + getFieldsCache(); + fieldsCache = CtField.append(fieldsCache, f); + getClassFile2().addField(f.getFieldInfo2()); + + if (init != null) { + FieldInitLink fil = new FieldInitLink(f, init); + FieldInitLink link = fieldInitializers; + if (link == null) + fieldInitializers = fil; + else { + while (link.next != null) + link = link.next; + + link.next = fil; + } + } + } + + public CtConstructor makeClassInitializer() + throws CannotCompileException + { + CtConstructor clinit = getClassInitializer(); + if (clinit != null) + return clinit; + + checkModify(); + ClassFile cf = getClassFile2(); + Bytecode code = new Bytecode(cf.getConstPool(), 0, 0); + modifyClassConstructor(cf, code, 0, 0); + return getClassInitializer(); + } + + public void addConstructor(CtConstructor c) + throws CannotCompileException + { + checkModify(); + if (c.getDeclaringClass() != this) + throw new CannotCompileException("cannot add"); + + getConstructorsCache(); + constructorsCache = CtConstructor.append(constructorsCache, c); + getClassFile2().addMethod(c.getMethodInfo2()); + } + + public void addMethod(CtMethod m) throws CannotCompileException { + checkModify(); + if (m.getDeclaringClass() != this) + throw new CannotCompileException("cannot add"); + + getMethodsCache(); + methodsCache = CtMethod.append(methodsCache, m); + getClassFile2().addMethod(m.getMethodInfo2()); + if ((m.getModifiers() & Modifier.ABSTRACT) != 0) + setModifiers(getModifiers() | Modifier.ABSTRACT); + } + + public byte[] getAttribute(String name) { + AttributeInfo ai = getClassFile2().getAttribute(name); + if (ai == null) + return null; + else + return ai.get(); + } + + public void setAttribute(String name, byte[] data) { + checkModify(); + ClassFile cf = getClassFile2(); + cf.addAttribute(new AttributeInfo(cf.getConstPool(), name, data)); + } + + public void instrument(CodeConverter converter) + throws CannotCompileException + { + checkModify(); + ClassFile cf = getClassFile2(); + ConstPool cp = cf.getConstPool(); + List list = cf.getMethods(); + int n = list.size(); + for (int i = 0; i < n; ++i) { + MethodInfo minfo = (MethodInfo)list.get(i); + converter.doit(this, minfo, cp); + } + } + + public void instrument(ExprEditor editor) + throws CannotCompileException + { + checkModify(); + ClassFile cf = getClassFile2(); + List list = cf.getMethods(); + int n = list.size(); + for (int i = 0; i < n; ++i) { + MethodInfo minfo = (MethodInfo)list.get(i); + editor.doit(this, minfo); + } + } + + public void toBytecode(DataOutputStream out) + throws CannotCompileException, IOException + { + try { + if (isModified()) { + ClassFile cf = getClassFile2(); + modifyClassConstructor(cf); + modifyConstructors(cf); + cf.write(out); + out.flush(); + } + else + classPool.writeClassfile(getName(), out); + + wasFrozen = true; + } + catch (NotFoundException e) { + throw new CannotCompileException(e); + } + catch (IOException e) { + throw new CannotCompileException(e); + } + } + + protected void modifyClassConstructor(ClassFile cf) + throws CannotCompileException, NotFoundException + { + Bytecode code = new Bytecode(cf.getConstPool(), 0, 0); + Javac jv = new Javac(code, this); + int stacksize = 0; + boolean doInit = false; + for (FieldInitLink fi = fieldInitializers; fi != null; fi = fi.next) { + CtField f = fi.field; + if (Modifier.isStatic(f.getModifiers())) { + doInit = true; + int s = fi.init.compileIfStatic(f.getType(), f.getName(), + code, jv); + if (stacksize < s) + stacksize = s; + } + } + + if (doInit) // need an initializer for static fileds. + modifyClassConstructor(cf, code, stacksize, 0); + } + + private void modifyClassConstructor(ClassFile cf, Bytecode code, + int stacksize, int localsize) + throws CannotCompileException + { + MethodInfo m = cf.getStaticInitializer(); + if (m == null) { + code.add(Bytecode.RETURN); + code.setMaxStack(stacksize); + code.setMaxLocals(localsize); + m = new MethodInfo(cf.getConstPool(), "", "()V"); + m.setAccessFlags(AccessFlag.STATIC); + m.setCodeAttribute(code.toCodeAttribute()); + cf.addMethod(m); + } + else { + CodeAttribute codeAttr = m.getCodeAttribute(); + if (codeAttr == null) + throw new CannotCompileException("empty "); + + try { + CodeIterator it = codeAttr.iterator(); + int pos = it.insertEx(code.get()); + it.insert(code.getExceptionTable(), pos); + int maxstack = codeAttr.getMaxStack(); + if (maxstack < stacksize) + codeAttr.setMaxStack(stacksize); + + int maxlocals = codeAttr.getMaxLocals(); + if (maxlocals < localsize) + codeAttr.setMaxLocals(localsize); + } + catch (BadBytecode e) { + throw new CannotCompileException(e); + } + } + } + + protected void modifyConstructors(ClassFile cf) + throws CannotCompileException, NotFoundException + { + if (fieldInitializers == null) + return; + + ConstPool cp = cf.getConstPool(); + List list = cf.getMethods(); + int n = list.size(); + for (int i = 0; i < n; ++i) { + MethodInfo minfo = (MethodInfo)list.get(i); + if (minfo.isConstructor()) { + CodeAttribute codeAttr = minfo.getCodeAttribute(); + if (codeAttr != null) + try { + Bytecode init = new Bytecode(cp, 0, + codeAttr.getMaxLocals()); + CtClass[] params + = Descriptor.getParameterTypes( + minfo.getDescriptor(), + classPool); + int stacksize = makeFieldInitializer(init, params); + insertAuxInitializer(codeAttr, init, stacksize); + } + catch (BadBytecode e) { + throw new CannotCompileException(e); + } + } + } + } + + private static void insertAuxInitializer(CodeAttribute codeAttr, + Bytecode initializer, + int stacksize) + throws BadBytecode + { + CodeIterator it = codeAttr.iterator(); + int index = it.skipSuperConstructor(); + if (index < 0) { + index = it.skipThisConstructor(); + if (index >= 0) + return; // this() is called. + + // Neither this() or super() is called. + } + + int pos = it.insertEx(initializer.get()); + it.insert(initializer.getExceptionTable(), pos); + int maxstack = codeAttr.getMaxStack(); + if (maxstack < stacksize) + codeAttr.setMaxStack(stacksize); + } + + private int makeFieldInitializer(Bytecode code, CtClass[] parameters) + throws CannotCompileException, NotFoundException + { + int stacksize = 0; + Javac jv = new Javac(code, this); + try { + jv.recordParams(parameters, false); + } + catch (CompileError e) { + throw new CannotCompileException(e); + } + + for (FieldInitLink fi = fieldInitializers; fi != null; fi = fi.next) { + CtField f = fi.field; + if (!Modifier.isStatic(f.getModifiers())) { + int s = fi.init.compile(f.getType(), f.getName(), code, + parameters, jv); + if (stacksize < s) + stacksize = s; + } + } + + return stacksize; + } + + // Methods used by CtNewWrappedMethod + + Hashtable getHiddenMethods() { + if (hiddenMethods == null) + hiddenMethods = new Hashtable(); + + return hiddenMethods; + } + + int getUniqueNumber() { return uniqueNumberSeed++; } +} + +class FieldInitLink { + FieldInitLink next; + CtField field; + CtField.Initializer init; + + FieldInitLink(CtField f, CtField.Initializer i) { + next = null; + field = f; + init = i; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.DataInputStream` acquired to `dis` by call to `new()` at line 113 is not released after line 115. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +ClassFile CtClassType.getClassFile2() + +### Procedure Id: +javassist.CtClassType.getClassFile2():javassist.bytecode.ClassFile.525406031c907fb2ca52cbc5afbd439f + +### File: +src/main/javassist/CtClassType.java + +### Key: +CtClassType.java|getClassFile2|RESOURCE_LEAK + +### Node Key: +825de8107c62456da8fa98c4641393c9 + +### Hash: +66e901faf6cb4318453247fb9e0706d2 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3381/instruction.md b/inferredbugs-3381/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..505ae2c3d0cecaed4806ae935cebc563442ab0f5 --- /dev/null +++ b/inferredbugs-3381/instruction.md @@ -0,0 +1,1123 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** javassist +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Javassist, a Java-bytecode translator toolkit. + * Copyright (C) 1999-2003 Shigeru Chiba. All Rights Reserved. + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. Alternatively, the contents of this file may be used under + * the terms of the GNU Lesser General Public License Version 2.1 or later. + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + */ + +package javassist.compiler; + +import java.util.List; +import javassist.*; +import javassist.bytecode.*; +import javassist.compiler.ast.*; + +/* Code generator methods depending on javassist.* classes. + */ +public class MemberCodeGen extends CodeGen { + protected ClassPool classPool; + protected CtClass thisClass; + protected MethodInfo thisMethod; + + protected boolean resultStatic; + + public MemberCodeGen(Bytecode b, CtClass cc, ClassPool cp) { + super(b); + classPool = cp; + thisClass = cc; + thisMethod = null; + } + + /** + * Records the currently compiled method. + */ + public void setThisMethod(CtMethod m) { + thisMethod = m.getMethodInfo2(); + } + + public CtClass getThisClass() { return thisClass; } + + /** + * Returns the JVM-internal representation of this class name. + */ + protected String getThisName() { + return javaToJvmName(thisClass.getName()); + } + + /** + * Returns the JVM-internal representation of this super class name. + */ + protected String getSuperName() throws CompileError { + return javaToJvmName(getSuperclass(thisClass).getName()); + } + + protected void insertDefaultSuperCall() throws CompileError { + bytecode.addAload(0); + bytecode.addInvokespecial(getSuperclass(thisClass), "", "()V"); + } + + protected void atTryStmnt(Stmnt st) throws CompileError { + Stmnt body = (Stmnt)st.getLeft(); + if (body == null) + return; + + int start = bytecode.currentPc(); + body.accept(this); + int end = bytecode.currentPc(); + if (start == end) + throw new CompileError("empty try block"); + + bytecode.addOpcode(Opcode.GOTO); + int pc = bytecode.currentPc(); + bytecode.addIndex(0); // correct later + + int var = getMaxLocals(); + incMaxLocals(1); + ASTList catchList = (ASTList)st.getRight().getLeft(); + while (catchList != null) { + Pair p = (Pair)catchList.head(); + catchList = catchList.tail(); + Declarator decl = (Declarator)p.getLeft(); + Stmnt block = (Stmnt)p.getRight(); + + decl.setLocalVar(var); + + CtClass type = lookupClass(decl.getClassName()); + decl.setClassName(javaToJvmName(type.getName())); + bytecode.addExceptionHandler(start, end, bytecode.currentPc(), + type); + bytecode.growStack(1); + bytecode.addAstore(var); + if (block != null) + block.accept(this); + + bytecode.addOpcode(Opcode.GOTO); + bytecode.addIndex(pc - bytecode.currentPc()); + } + + Stmnt finallyBlock = (Stmnt)st.getRight().getRight().getLeft(); + if (finallyBlock != null) + throw new CompileError( + "sorry, finally has not been supported yet"); + + bytecode.write16bit(pc, bytecode.currentPc() - pc + 1); + hasReturned = false; + } + + public void atNewExpr(NewExpr expr) throws CompileError { + if (expr.isArray()) + atNewArrayExpr(expr); + else { + CtClass clazz = lookupClass(expr.getClassName()); + String cname = clazz.getName(); + ASTList args = expr.getArguments(); + bytecode.addNew(cname); + bytecode.addOpcode(DUP); + + atMethodCall2(clazz, MethodInfo.nameInit, args, false, true); + + exprType = CLASS; + arrayDim = 0; + className = javaToJvmName(cname); + } + } + + public void atNewArrayExpr(NewExpr expr) throws CompileError { + if (expr.getInitializer() != null) + throw new CompileError("array initializer is not supported"); + + int type = expr.getArrayType(); + ASTList size = expr.getArraySize(); + ASTList classname = expr.getClassName(); + if (size.length() > 1) { + atMultiNewArray(type, classname, size); + return; + } + + size.head().accept(this); + exprType = type; + arrayDim = 1; + if (type == CLASS) { + className = resolveClassName(classname); + bytecode.addAnewarray(jvmToJavaName(className)); + } + else { + className = null; + int atype = 0; + switch (type) { + case BOOLEAN : + atype = T_BOOLEAN; + break; + case CHAR : + atype = T_CHAR; + break; + case FLOAT : + atype = T_FLOAT; + break; + case DOUBLE : + atype = T_DOUBLE; + break; + case BYTE : + atype = T_BYTE; + break; + case SHORT : + atype = T_SHORT; + break; + case INT : + atype = T_INT; + break; + case LONG : + atype = T_LONG; + break; + default : + badNewExpr(); + break; + } + + bytecode.addOpcode(NEWARRAY); + bytecode.add(atype); + } + } + + private static void badNewExpr() throws CompileError { + throw new CompileError("bad new expression"); + } + + protected void atMultiNewArray(int type, ASTList classname, ASTList size) + throws CompileError + { + int count, dim; + dim = size.length(); + for (count = 0; size != null; size = size.tail()) { + ASTree s = size.head(); + if (s == null) + break; // int[][][] a = new int[3][4][]; + + ++count; + s.accept(this); + if (exprType != INT) + throw new CompileError("bad type for array size"); + } + + String desc; + exprType = type; + arrayDim = dim; + if (type == CLASS) { + className = resolveClassName(classname); + desc = toJvmArrayName(className, dim); + } + else + desc = toJvmTypeName(type, dim); + + bytecode.addMultiNewarray(desc, count); + } + + protected void atMethodCall(Expr expr) throws CompileError { + String mname = null; + CtClass targetClass = null; + ASTree method = expr.oprand1(); + ASTList args = (ASTList)expr.oprand2(); + boolean isStatic = false; + boolean isSpecial = false; + + if (method instanceof Member) { + mname = ((Member)method).get(); + targetClass = thisClass; + if (inStaticMethod) + isStatic = true; // should be static + else + bytecode.addAload(0); // this + } + else if (method instanceof Keyword) { // constructor + isSpecial = true; + mname = MethodInfo.nameInit; // + targetClass = thisClass; + if (inStaticMethod) + throw new CompileError("a constructor cannot be static"); + else + bytecode.addAload(0); // this + + if (((Keyword)method).get() == SUPER) + targetClass = getSuperclass(targetClass); + } + else if (method instanceof Expr) { + Expr e = (Expr)method; + mname = ((Symbol)e.oprand2()).get(); + int op = e.getOperator(); + if (op == MEMBER) { // static method + targetClass = lookupClass((ASTList)e.oprand1()); + isStatic = true; + } + else if (op == '.') { + ASTree target = e.oprand1(); + if (target instanceof Keyword) + if (((Keyword)target).get() == SUPER) + isSpecial = true; + + try { + target.accept(this); + } + catch (NoFieldException nfe) { + if (nfe.getExpr() != target) + throw nfe; + + // it should be a static method. + exprType = CLASS; + arrayDim = 0; + className = nfe.getField(); // JVM-internal + isStatic = true; + } + + if (arrayDim > 0) + targetClass = lookupClass2(javaLangObject); + else if (exprType == CLASS /* && arrayDim == 0 */) + targetClass = lookupClass(className); + else + badMethod(); + } + else + badMethod(); + } + else + fatal(); + + atMethodCall2(targetClass, mname, args, isStatic, isSpecial); + } + + private static void badMethod() throws CompileError { + throw new CompileError("bad method"); + } + + private static CtClass getSuperclass(CtClass c) throws CompileError { + try { + return c.getSuperclass(); + } + catch (NotFoundException e) { + throw new CompileError("cannot find the super class of " + + c.getName()); + } + } + + public void atMethodCall2(CtClass targetClass, String mname, + ASTList args, boolean isStatic, boolean isSpecial) + throws CompileError + { + int nargs = atMethodArgsLength(args); + int[] types = new int[nargs]; + int[] dims = new int[nargs]; + String[] cnames = new String[nargs]; + + int stack = bytecode.getStackDepth(); + + atMethodArgs(args, types, dims, cnames); + + // used by invokeinterface + int count = bytecode.getStackDepth() - stack + 1; + + Object[] found = lookupMethod(targetClass, thisMethod, mname, + types, dims, cnames, false); + if (found == null) { + String msg; + if (mname.equals(MethodInfo.nameInit)) + msg = "constructor not found"; + else + msg = "Method " + mname + " not found in " + + targetClass.getName(); + + throw new CompileError(msg); + } + + CtClass declClass = (CtClass)found[0]; + MethodInfo minfo = (MethodInfo)found[1]; + String desc = minfo.getDescriptor(); + int acc = minfo.getAccessFlags(); + + if (mname.equals(MethodInfo.nameInit)) { + isSpecial = true; + if (declClass != targetClass) + throw new CompileError("no such a constructor"); + } + else if ((acc & AccessFlag.PRIVATE) != 0) { + isSpecial = true; + if (declClass != targetClass) + throw new CompileError("Method " + mname + "is private"); + } + + boolean popTarget = false; + if ((acc & AccessFlag.STATIC) != 0) { + if (!isStatic) { + /* this method is static but the target object is + on stack. It must be popped out. + */ + isStatic = true; + popTarget = true; + } + + bytecode.addInvokestatic(declClass, mname, desc); + } + else if (isSpecial) + bytecode.addInvokespecial(declClass, mname, desc); + else if (declClass.isInterface()) + bytecode.addInvokeinterface(declClass, mname, desc, count); + else + if (isStatic) + throw new CompileError(mname + " is not static"); + else + bytecode.addInvokevirtual(declClass, mname, desc); + + setReturnType(desc, isStatic, popTarget); + } + + public int atMethodArgsLength(ASTList args) { + return ASTList.length(args); + } + + public void atMethodArgs(ASTList args, int[] types, int[] dims, + String[] cnames) throws CompileError { + int i = 0; + while (args != null) { + ASTree a = args.head(); + a.accept(this); + types[i] = exprType; + dims[i] = arrayDim; + cnames[i] = className; + ++i; + args = args.tail(); + } + } + + private void setReturnType(String desc, boolean isStatic, + boolean popTarget) + throws CompileError + { + int i = desc.indexOf(')'); + if (i < 0) + badMethod(); + + char c = desc.charAt(++i); + int dim = 0; + while (c == '[') { + ++dim; + c = desc.charAt(++i); + } + + arrayDim = dim; + if (c == 'L') { + int j = desc.indexOf(';', i + 1); + if (j < 0) + badMethod(); + + exprType = CLASS; + className = desc.substring(i + 1, j); + } + else { + exprType = descToType(c); + className = null; + } + + int etype = exprType; + if (isStatic) { + if (popTarget) { + if (is2word(etype, dim)) { + bytecode.addOpcode(DUP2_X1); + bytecode.addOpcode(POP2); + bytecode.addOpcode(POP); + } + else if (etype == VOID) + bytecode.addOpcode(POP); + else { + bytecode.addOpcode(SWAP); + bytecode.addOpcode(POP); + } + } + } + } + + private Object[] lookupMethod(CtClass clazz, MethodInfo current, + String methodName, + int[] argTypes, int[] argDims, + String[] argClassNames, boolean onlyExact) + throws CompileError + { + Object[] maybe = null; + + if (current != null) + if (current.getName().equals(methodName)) { + int res = compareSignature(current.getDescriptor(), + argTypes, argDims, argClassNames); + Object[] r = new Object[] { clazz, current }; + if (res == YES) + return r; + else if (res == MAYBE && maybe == null) + maybe = r; + } + + List list = clazz.getClassFile2().getMethods(); + int n = list.size(); + for (int i = 0; i < n; ++i) { + MethodInfo minfo = (MethodInfo)list.get(i); + if (minfo.getName().equals(methodName)) { + int res = compareSignature(minfo.getDescriptor(), + argTypes, argDims, argClassNames); + Object[] r = new Object[] { clazz, minfo }; + if (res == YES) + return r; + else if (res == MAYBE && maybe == null) + maybe = r; + } + } + + try { + CtClass pclazz = clazz.getSuperclass(); + if (pclazz != null) { + Object[] r = lookupMethod(pclazz, null, methodName, argTypes, + argDims, argClassNames, + (onlyExact || maybe != null)); + if (r != null) + return r; + } + } + catch (NotFoundException e) {} + + /* -- not necessary to search implemented interfaces. + try { + CtClass[] ifs = clazz.getInterfaces(); + int size = ifs.length; + for (int i = 0; i < size; ++i) { + Object[] r = lookupMethod(ifs[i], methodName, argTypes, + argDims, argClassNames); + if (r != null) + return r; + } + } + catch (NotFoundException e) {} + */ + + if (onlyExact) + return null; + else + return maybe; + } + + private static final int YES = 2; + private static final int MAYBE = 1; + private static final int NO = 0; + + /* + * Returns YES if actual parameter types matches the given signature. + * + * argTypes, argDims, and argClassNames represent actual parameters. + * + * This method does not correctly implement the Java method dispatch + * algorithm. + */ + private int compareSignature(String desc, int[] argTypes, + int[] argDims, String[] argClassNames) + throws CompileError + { + int result = YES; + int i = 1; + int nArgs = argTypes.length; + if (nArgs != Descriptor.numOfParameters(desc)) + return NO; + + int len = desc.length(); + for (int n = 0; i < len; ++n) { + char c = desc.charAt(i++); + if (c == ')') + return (n == nArgs ? result : NO); + else if (n >= nArgs) + return NO; + + int dim = 0; + while (c == '[') { + ++dim; + c = desc.charAt(i++); + } + + if (argTypes[n] == NULL) { + if (dim == 0 && c != 'L') + return NO; + } + else if (argDims[n] != dim) { + if (!(dim == 0 && c == 'L' + && desc.startsWith("java/lang/Object;", i))) + return NO; + + // if the thread reaches here, c must be 'L'. + i = desc.indexOf(';', i) + 1; + result = MAYBE; + if (i <= 0) + return NO; // invalid descriptor? + } + else if (c == 'L') { // not compare + int j = desc.indexOf(';', i); + if (j < 0 || argTypes[n] != CLASS) + return NO; + + String cname = desc.substring(i, j); + if (!cname.equals(argClassNames[n])) { + CtClass clazz = lookupClass(argClassNames[n]); + try { + if (clazz.subtypeOf(lookupClass(cname))) + result = MAYBE; + else + return NO; + } + catch (NotFoundException e) { + result = MAYBE; // should be NO? + } + } + + i = j + 1; + } + else { + int t = descToType(c); + int at = argTypes[n]; + if (t != at) + if (t == INT + && (at == SHORT || at == BYTE || at == CHAR)) + result = MAYBE; + else + return NO; + } + } + + return NO; + } + + protected static int descToType(char c) throws CompileError { + switch (c) { + case 'Z' : + return BOOLEAN; + case 'C' : + return CHAR; + case 'B' : + return BYTE; + case 'S' : + return SHORT; + case 'I' : + return INT; + case 'J' : + return LONG; + case 'F' : + return FLOAT; + case 'D' : + return DOUBLE; + case 'V' : + return VOID; + case 'L' : + case '[' : + return CLASS; + default : + fatal(); + return VOID; + } + } + + protected void atFieldAssign(Expr expr, int op, ASTree left, + ASTree right, boolean doDup) throws CompileError + { + CtField f = fieldAccess(left); + boolean is_static = resultStatic; + if (op != '=' && !is_static) + bytecode.addOpcode(DUP); + + int fi = atFieldRead(f, is_static, op == '='); + int fType = exprType; + int fDim = arrayDim; + String cname = className; + + atAssignCore(expr, op, right, fType, fDim, cname); + + boolean is2w = is2word(fType, fDim); + if (doDup) { + int dup_code; + if (is_static) + dup_code = (is2w ? DUP2 : DUP); + else + dup_code = (is2w ? DUP2_X1 : DUP_X1); + + bytecode.addOpcode(dup_code); + } + + if (is_static) { + bytecode.add(PUTSTATIC); + bytecode.growStack(is2w ? -2 : -1); + } + else { + bytecode.add(PUTFIELD); + bytecode.growStack(is2w ? -3 : -2); + } + + bytecode.addIndex(fi); + exprType = fType; + arrayDim = fDim; + className = cname; + } + + /* overwritten in JvstCodeGen. + */ + public void atMember(Member mem) throws CompileError { + atFieldRead(mem); + } + + protected void atFieldRead(ASTree expr) throws CompileError + { + CtField f = fieldAccess(expr); + boolean is_static = resultStatic; + atFieldRead(f, is_static, false); + } + + private int atFieldRead(CtField f, boolean isStatic, boolean noRead) + throws CompileError + { + FieldInfo finfo = f.getFieldInfo2(); + String type = finfo.getDescriptor(); + + int fi = addFieldrefInfo(f, finfo, type); + + int i = 0; + int dim = 0; + char c = type.charAt(i); + while (c == '[') { + ++dim; + c = type.charAt(++i); + } + + arrayDim = dim; + boolean is2byte = (c == 'J' || c == 'D'); + exprType = descToType(c); + + if (c == 'L') + className = type.substring(i + 1, type.indexOf(';', i + 1)); + else + className = null; + + if (noRead) + return fi; + + if (isStatic) { + bytecode.add(GETSTATIC); + bytecode.growStack(is2byte ? 2 : 1); + } + else { + bytecode.add(GETFIELD); + bytecode.growStack(is2byte ? 1 : 0); + } + + bytecode.addIndex(fi); + return fi; + } + + protected int addFieldrefInfo(CtField f, FieldInfo finfo, String type) { + ConstPool cp = bytecode.getConstPool(); + String cname = f.getDeclaringClass().getName(); + int ci = cp.addClassInfo(cname); + String name = finfo.getName(); + return cp.addFieldrefInfo(ci, name, type); + } + + protected void atFieldPlusPlus(int token, boolean isPost, + ASTree oprand, Expr expr, boolean doDup) + throws CompileError + { + CtField f = fieldAccess(oprand); + boolean is_static = resultStatic; + if (!is_static) + bytecode.addOpcode(DUP); + + int fi = atFieldRead(f, is_static, false); + int t = exprType; + boolean is2w = is2word(t, arrayDim); + + int dup_code; + if (is_static) + dup_code = (is2w ? DUP2 : DUP); + else + dup_code = (is2w ? DUP2_X1 : DUP_X1); + + atPlusPlusCore(dup_code, doDup, token, isPost, expr); + + if (is_static) { + bytecode.add(PUTSTATIC); + bytecode.growStack(is2w ? -2 : -1); + } + else { + bytecode.add(PUTFIELD); + bytecode.growStack(is2w ? -3 : -2); + } + + bytecode.addIndex(fi); + } + + /* This method also returns a value in resultStatic. + */ + protected CtField fieldAccess(ASTree expr) throws CompileError { + CtField f = null; + boolean is_static = false; + if (expr instanceof Member) { + String name = ((Member)expr).get(); + try { + f = thisClass.getField(name); + } + catch (NotFoundException e) { + // EXPR might be part of a static member access? + throw new NoFieldException(name, expr); + } + + is_static = Modifier.isStatic(f.getModifiers()); + if (!is_static) + if (inStaticMethod) + throw new CompileError( + "not available in a static method: " + name); + else + bytecode.addAload(0); // this + } + else if (expr instanceof Expr) { + Expr e = (Expr)expr; + int op = e.getOperator(); + if (op == MEMBER) { + f = lookupField((ASTList)e.oprand1(), (Symbol)e.oprand2()); + is_static = true; + } + else if (op == '.') { + try { + e.oprand1().accept(this); + if (exprType == CLASS && arrayDim == 0) + f = lookupField(className, (Symbol)e.oprand2()); + else + badLvalue(); + + is_static = Modifier.isStatic(f.getModifiers()); + if (is_static) + bytecode.addOpcode(POP); + } + catch (NoFieldException nfe) { + if (nfe.getExpr() != e.oprand1()) + throw nfe; + + Symbol fname = (Symbol)e.oprand2(); + // it should be a static field. + try { + f = lookupField(nfe.getField(), fname); + is_static = true; + } + catch (CompileError ce) { + // EXPR might be part of a qualified class name. + throw new NoFieldException(nfe.getField() + "/" + + fname.get(), expr); + } + } + } + else + badLvalue(); + } + else + badLvalue(); + + resultStatic = is_static; + return f; + } + + private static void badLvalue() throws CompileError { + throw new CompileError("bad l-value"); + } + + public CtClass[] makeParamList(MethodDecl md) throws CompileError { + CtClass[] params; + ASTList plist = md.getParams(); + if (plist == null) + params = new CtClass[0]; + else { + int i = 0; + params = new CtClass[plist.length()]; + while (plist != null) { + params[i++] = lookupClass((Declarator)plist.head()); + plist = plist.tail(); + } + } + + return params; + } + + public CtClass[] makeThrowsList(MethodDecl md) throws CompileError { + CtClass[] clist; + ASTList list = md.getThrows(); + if (list == null) + return null; + else { + int i = 0; + clist = new CtClass[list.length()]; + while (list != null) { + clist[i++] = lookupClass((ASTList)list.head()); + list = list.tail(); + } + + return clist; + } + } + + public static int getModifiers(ASTList mods) { + int m = 0; + while (mods != null) { + Keyword k = (Keyword)mods.head(); + mods = mods.tail(); + switch (k.get()) { + case STATIC : + m |= Modifier.STATIC; + break; + case FINAL : + m |= Modifier.FINAL; + break; + case SYNCHRONIZED : + m |= Modifier.SYNCHRONIZED; + break; + case ABSTRACT : + m |= Modifier.ABSTRACT; + break; + case PUBLIC : + m |= Modifier.PUBLIC; + break; + case PROTECTED : + m |= Modifier.PROTECTED; + break; + case PRIVATE : + m |= Modifier.PRIVATE; + break; + case VOLATILE : + m |= Modifier.VOLATILE; + break; + case TRANSIENT : + m |= Modifier.TRANSIENT; + break; + case STRICT : + m |= Modifier.STRICT; + break; + } + } + + return m; + } + + /* Converts a class name into a JVM-internal representation. + * + * It may also expand a simple class name to java.lang.*. + * For example, this converts Object into java/lang/Object. + */ + protected String resolveClassName(ASTList name) throws CompileError { + if (name == null) + return null; + else + return javaToJvmName(lookupClass(name).getName()); + } + + /* Expands a simple class name to java.lang.*. + * For example, this converts Object into java/lang/Object. + */ + protected String resolveClassName(String jvmName) throws CompileError { + if (jvmName == null) + return null; + else + return javaToJvmName(lookupClass(jvmName).getName()); + } + + protected CtClass lookupClass(Declarator decl) throws CompileError { + return lookupClass(decl.getType(), decl.getArrayDim(), + decl.getClassName()); + } + + protected CtClass lookupClass(int type, int dim, String classname) + throws CompileError + { + String cname = ""; + CtClass clazz; + switch (type) { + case CLASS : + clazz = lookupClass(classname); + if (dim > 0) + cname = clazz.getName(); + else + return clazz; + + break; + case BOOLEAN : + cname = "boolean"; + break; + case CHAR : + cname = "char"; + break; + case BYTE : + cname = "byte"; + break; + case SHORT : + cname = "short"; + break; + case INT : + cname = "int"; + break; + case LONG : + cname = "long"; + break; + case FLOAT : + cname = "float"; + break; + case DOUBLE : + cname = "double"; + break; + case VOID : + cname = "void"; + break; + default : + fatal(); + } + + while (dim-- > 0) + cname += "[]"; + + return lookupClass2(cname); + } + + protected CtClass lookupClass(ASTList name) throws CompileError { + return lookupClass2(Declarator.astToClassName(name, '.')); + } + + protected CtClass lookupClass(String jvmName) throws CompileError { + return lookupClass2(jvmToJavaName(jvmName)); + } + + /** + * @param name a qualified class name. e.g. java.lang.String + */ + private CtClass lookupClass2(String name) throws CompileError { + try { + return classPool.get(name); + } + catch (NotFoundException e) {} + + try { + if (name.indexOf('.') < 0) + return classPool.get("java.lang." + name); + } + catch (NotFoundException e) {} + + throw new CompileError("no such class: " + name); + } + + public CtField lookupField(ASTList className, Symbol fieldName) + throws CompileError + { + return lookupField2(Declarator.astToClassName(className, '.'), + fieldName); + } + + public CtField lookupField(String className, Symbol fieldName) + throws CompileError + { + return lookupField2(jvmToJavaName(className), fieldName); + } + + /** + * @param name a qualified class name. e.g. java.lang.String + */ + private CtField lookupField2(String className, Symbol fieldName) + throws CompileError + { + CtClass cc = lookupClass(className); + try { + return cc.getField(fieldName.get()); + } + catch (NotFoundException e) {} + throw new CompileError("no such field: " + fieldName.get()); + } + + protected static String javaToJvmName(String classname) { + return classname.replace('.', '/'); + } + + protected static String jvmToJavaName(String classname) { + return classname.replace('/', '.'); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `astToClassName(className,46)` could be null and is dereferenced by call to `lookupField2(...)` at line 1018. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +CtField MemberCodeGen.lookupField(ASTList,Symbol) + +### Procedure Id: +javassist.compiler.MemberCodeGen.lookupField(javassist.compiler.ast.ASTList,javassist.compiler.ast.S.8e9e2eb92e3ae1e685273094c7ee6b44 + +### File: +src/main/javassist/compiler/MemberCodeGen.java + +### Key: +MemberCodeGen.java|lookupField|NULL_DEREFERENCE + +### Node Key: +df64850a52332193bad448f8258efd03 + +### Hash: +2d2b67ce37493e1d9919cbd7dccd4e87 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3386/instruction.md b/inferredbugs-3386/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1819a3bd87912d518a9918ec7a9d8e823305748e --- /dev/null +++ b/inferredbugs-3386/instruction.md @@ -0,0 +1,830 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** javassist +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Javassist, a Java-bytecode translator toolkit. + * Copyright (C) 1999-2004 Shigeru Chiba. All Rights Reserved. + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. Alternatively, the contents of this file may be used under + * the terms of the GNU Lesser General Public License Version 2.1 or later. + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + */ + +package javassist.compiler; + +import javassist.CtClass; +import javassist.CtField; +import javassist.ClassPool; +import javassist.NotFoundException; +import javassist.compiler.ast.*; +import javassist.bytecode.*; + +public class TypeChecker extends Visitor implements Opcode, TokenId { + static final String javaLangObject = "java.lang.Object"; + static final String jvmJavaLangObject = "java/lang/Object"; + static final String jvmJavaLangString = "java/lang/String"; + static final String jvmJavaLangClass = "java/lang/Class"; + + /* The following fields are used by atXXX() methods + * for returning the type of the compiled expression. + */ + protected int exprType; // VOID, NULL, CLASS, BOOLEAN, INT, ... + protected int arrayDim; + protected String className; // JVM-internal representation + + protected MemberResolver resolver; + protected CtClass thisClass; + protected MethodInfo thisMethod; + + public TypeChecker(CtClass cc, ClassPool cp) { + resolver = new MemberResolver(cp); + thisClass = cc; + thisMethod = null; + } + + /** + * Records the currently compiled method. + */ + public void setThisMethod(MethodInfo m) { + thisMethod = m; + } + + protected static void fatal() throws CompileError { + throw new CompileError("fatal"); + } + + /** + * Returns the JVM-internal representation of this class name. + */ + protected String getThisName() { + return MemberResolver.javaToJvmName(thisClass.getName()); + } + + /** + * Returns the JVM-internal representation of this super class name. + */ + protected String getSuperName() throws CompileError { + return MemberResolver.javaToJvmName( + MemberResolver.getSuperclass(thisClass).getName()); + } + + /* Converts a class name into a JVM-internal representation. + * + * It may also expand a simple class name to java.lang.*. + * For example, this converts Object into java/lang/Object. + */ + protected String resolveClassName(ASTList name) throws CompileError { + return resolver.resolveClassName(name); + } + + /* Expands a simple class name to java.lang.*. + * For example, this converts Object into java/lang/Object. + */ + protected String resolveClassName(String jvmName) throws CompileError { + return resolver.resolveJvmClassName(jvmName); + } + + public void atNewExpr(NewExpr expr) throws CompileError { + if (expr.isArray()) + atNewArrayExpr(expr); + else { + CtClass clazz = resolver.lookupClassByName(expr.getClassName()); + String cname = clazz.getName(); + ASTList args = expr.getArguments(); + atMethodCallCore(clazz, MethodInfo.nameInit, args); + exprType = CLASS; + arrayDim = 0; + className = MemberResolver.javaToJvmName(cname); + } + } + + public void atNewArrayExpr(NewExpr expr) throws CompileError { + int type = expr.getArrayType(); + ASTList size = expr.getArraySize(); + ASTList classname = expr.getClassName(); + if (size.length() > 1) + atMultiNewArray(type, classname, size); + else { + size.head().accept(this); + exprType = type; + arrayDim = 1; + if (type == CLASS) + className = resolveClassName(classname); + else + className = null; + } + } + + protected void atMultiNewArray(int type, ASTList classname, ASTList size) + throws CompileError + { + int count, dim; + dim = size.length(); + for (count = 0; size != null; size = size.tail()) { + ASTree s = size.head(); + if (s == null) + break; // int[][][] a = new int[3][4][]; + + ++count; + s.accept(this); + } + + exprType = type; + arrayDim = dim; + if (type == CLASS) + className = resolveClassName(classname); + else + className = null; + } + + public void atAssignExpr(AssignExpr expr) throws CompileError { + // =, %=, &=, *=, /=, +=, -=, ^=, |=, <<=, >>=, >>>= + int op = expr.getOperator(); + ASTree left = expr.oprand1(); + ASTree right = expr.oprand2(); + if (left instanceof Variable) + atVariableAssign(expr, op, (Variable)left, + ((Variable)left).getDeclarator(), + right); + else { + if (left instanceof Expr) { + Expr e = (Expr)left; + if (e.getOperator() == ARRAY) { + atArrayAssign(expr, op, (Expr)left, right); + return; + } + } + + atFieldAssign(expr, op, left, right); + } + } + + /* op is either =, %=, &=, *=, /=, +=, -=, ^=, |=, <<=, >>=, or >>>=. + * + * expr and var can be null. + */ + private void atVariableAssign(Expr expr, int op, Variable var, + Declarator d, ASTree right) + throws CompileError + { + int varType = d.getType(); + int varArray = d.getArrayDim(); + String varClass = d.getClassName(); + + if (op != '=') + atVariable(var); + + right.accept(this); + exprType = varType; + arrayDim = varArray; + className = varClass; + } + + private void atArrayAssign(Expr expr, int op, Expr array, + ASTree right) throws CompileError + { + atArrayRead(array.oprand1(), array.oprand2()); + int aType = exprType; + int aDim = arrayDim; + String cname = className; + right.accept(this); + exprType = aType; + arrayDim = aDim; + className = cname; + } + + protected void atFieldAssign(Expr expr, int op, ASTree left, ASTree right) + throws CompileError + { + CtField f = fieldAccess(left); + atFieldRead(f); + int fType = exprType; + int fDim = arrayDim; + String cname = className; + right.accept(this); + exprType = fType; + arrayDim = fDim; + className = cname; + } + + public void atCondExpr(CondExpr expr) throws CompileError { + booleanExpr(expr.condExpr()); + expr.thenExpr().accept(this); + int type1 = exprType; + int dim1 = arrayDim; + String cname1 = className; + expr.elseExpr().accept(this); + + if (dim1 == 0 && dim1 == arrayDim) + if (CodeGen.rightIsStrong(type1, exprType)) + expr.setThen(new CastExpr(exprType, 0, expr.thenExpr())); + else if (CodeGen.rightIsStrong(exprType, type1)) { + expr.setElse(new CastExpr(type1, 0, expr.elseExpr())); + exprType = type1; + } + } + + public void atBinExpr(BinExpr expr) throws CompileError { + int token = expr.getOperator(); + int k = CodeGen.lookupBinOp(token); + if (k >= 0) { + /* arithmetic operators: +, -, *, /, %, |, ^, &, <<, >>, >>> + */ + if (token == '+') { + Expr e = atPlusExpr(expr); + if (e != null) { + /* String concatenation has been translated into + * an expression using StringBuffer. + */ + e = CallExpr.makeCall(Expr.make('.', e, + new Member("toString")), null); + expr.setLeft(e); + expr.setOprand2(null); // <---- look at this! + className = jvmJavaLangString; + } + } + else { + expr.oprand1().accept(this); + int type1 = exprType; + expr.oprand2().accept(this); + computeBinExprType(expr, token, type1); + } + } + else { + /* equation: &&, ||, ==, !=, <=, >=, <, > + */ + booleanExpr(expr); + } + } + + // expr must be a + expression. + private Expr atPlusExpr(BinExpr expr) throws CompileError { + ASTree left = expr.oprand1(); + ASTree right = expr.oprand2(); + if (right == null) { + /* this expression has been already type-checked since it is + string concatenation. + see atBinExpr() above. + */ + exprType = CLASS; + arrayDim = 0; + className = jvmJavaLangString; + return null; + } + + if (isPlusExpr(left)) { + Expr newExpr = atPlusExpr((BinExpr)left); + if (newExpr != null) { + right.accept(this); + exprType = CLASS; + arrayDim = 0; + className = "java/lang/StringBuffer"; + return makeAppendCall(newExpr, right); + } + } + else + left.accept(this); + + int type1 = exprType; + int dim1 = arrayDim; + String cname = className; + right.accept(this); + if ((type1 == CLASS && dim1 == 0 && jvmJavaLangString.equals(cname)) + || (exprType == CLASS && arrayDim == 0 + && jvmJavaLangString.equals(className))) { + ASTList sbufClass = ASTList.make(new Symbol("java"), + new Symbol("lang"), new Symbol("StringBuffer")); + ASTree e = new NewExpr(sbufClass, null); + exprType = CLASS; + arrayDim = 0; + className = "java/lang/StringBuffer"; + return makeAppendCall(makeAppendCall(e, left), right); + } + else { + computeBinExprType(expr, '+', type1); + return null; + } + } + + private static boolean isPlusExpr(ASTree expr) { + if (expr instanceof BinExpr) { + BinExpr bexpr = (BinExpr)expr; + int token = bexpr.getOperator(); + return token == '+'; + } + + return false; + } + + private static Expr makeAppendCall(ASTree target, ASTree arg) { + return CallExpr.makeCall(Expr.make('.', target, new Member("append")), + new ASTList(arg)); + } + + private void computeBinExprType(BinExpr expr, int token, int type1) + throws CompileError + { + // arrayDim should be 0. + int type2 = exprType; + if (token == LSHIFT || token == RSHIFT || token == ARSHIFT) + exprType = type1; + else + insertCast(expr, type1, type2); + + if (CodeGen.isP_INT(exprType)) + exprType = INT; // type1 may be BYTE, ... + } + + private void booleanExpr(ASTree expr) + throws CompileError + { + int op = CodeGen.getCompOperator(expr); + if (op == EQ) { // ==, !=, ... + BinExpr bexpr = (BinExpr)expr; + bexpr.oprand1().accept(this); + int type1 = exprType; + int dim1 = arrayDim; + bexpr.oprand2().accept(this); + if (dim1 == 0 && arrayDim == 0) + insertCast(bexpr, type1, exprType); + } + else if (op == '!') + ((Expr)expr).oprand1().accept(this); + else if (op == ANDAND || op == OROR) { + BinExpr bexpr = (BinExpr)expr; + bexpr.oprand1().accept(this); + bexpr.oprand2().accept(this); + } + else // others + expr.accept(this); + + exprType = BOOLEAN; + arrayDim = 0; + } + + private void insertCast(BinExpr expr, int type1, int type2) + throws CompileError + { + if (CodeGen.rightIsStrong(type1, type2)) + expr.setLeft(new CastExpr(type2, 0, expr.oprand1())); + else + exprType = type1; + } + + public void atCastExpr(CastExpr expr) throws CompileError { + String cname = resolveClassName(expr.getClassName()); + expr.getOprand().accept(this); + exprType = expr.getType(); + arrayDim = expr.getArrayDim(); + className = cname; + } + + public void atInstanceOfExpr(InstanceOfExpr expr) throws CompileError { + expr.getOprand().accept(this); + exprType = BOOLEAN; + arrayDim = 0; + } + + public void atExpr(Expr expr) throws CompileError { + // array access, member access, + // (unary) +, (unary) -, ++, --, !, ~ + + int token = expr.getOperator(); + ASTree oprand = expr.oprand1(); + if (token == '.') { + String member = ((Symbol)expr.oprand2()).get(); + if (member.equals("length")) + atArrayLength(expr); + else if (member.equals("class")) + atClassObject(expr); // .class + else + atFieldRead(expr); + } + else if (token == MEMBER) { // field read + String member = ((Symbol)expr.oprand2()).get(); + if (member.equals("class")) + atClassObject(expr); // .class + else + atFieldRead(expr); + } + else if (token == ARRAY) + atArrayRead(oprand, expr.oprand2()); + else if (token == PLUSPLUS || token == MINUSMINUS) + atPlusPlus(token, oprand, expr); + else if (token == '!') + booleanExpr(expr); + else if (token == CALL) // method call + fatal(); + else { + expr.oprand1().accept(this); + if (token == '-' || token == '~') + if (CodeGen.isP_INT(exprType)) + exprType = INT; // type may be BYTE, ... + } + } + + public void atCallExpr(CallExpr expr) throws CompileError { + String mname = null; + CtClass targetClass = null; + ASTree method = expr.oprand1(); + ASTList args = (ASTList)expr.oprand2(); + + if (method instanceof Member) { + mname = ((Member)method).get(); + targetClass = thisClass; + } + else if (method instanceof Keyword) { // constructor + mname = MethodInfo.nameInit; // + if (((Keyword)method).get() == SUPER) + targetClass = MemberResolver.getSuperclass(thisClass); + else + targetClass = thisClass; + } + else if (method instanceof Expr) { + Expr e = (Expr)method; + mname = ((Symbol)e.oprand2()).get(); + int op = e.getOperator(); + if (op == MEMBER) // static method + targetClass + = resolver.lookupClass(((Symbol)e.oprand1()).get(), + false); + else if (op == '.') { + ASTree target = e.oprand1(); + try { + target.accept(this); + } + catch (NoFieldException nfe) { + if (nfe.getExpr() != target) + throw nfe; + + // it should be a static method. + exprType = CLASS; + arrayDim = 0; + className = nfe.getField(); // JVM-internal + } + + if (arrayDim > 0) + targetClass = resolver.lookupClass(javaLangObject, true); + else if (exprType == CLASS /* && arrayDim == 0 */) + targetClass = resolver.lookupClassByJvmName(className); + else + badMethod(); + } + else + badMethod(); + } + else + fatal(); + + MemberResolver.Method minfo + = atMethodCallCore(targetClass, mname, args); + expr.setMethod(minfo); + } + + private static void badMethod() throws CompileError { + throw new CompileError("bad method"); + } + + /** + * @return a pair of the class declaring the invoked method + * and the MethodInfo of that method. Never null. + */ + public MemberResolver.Method atMethodCallCore(CtClass targetClass, + String mname, ASTList args) + throws CompileError + { + int nargs = getMethodArgsLength(args); + int[] types = new int[nargs]; + int[] dims = new int[nargs]; + String[] cnames = new String[nargs]; + atMethodArgs(args, types, dims, cnames); + + MemberResolver.Method found + = resolver.lookupMethod(targetClass, thisMethod, mname, + types, dims, cnames, false); + if (found == null) { + String msg; + if (mname.equals(MethodInfo.nameInit)) + msg = "constructor not found"; + else + msg = "Method " + mname + " not found in " + + targetClass.getName(); + + throw new CompileError(msg); + } + + String desc = found.info.getDescriptor(); + setReturnType(desc); + return found; + } + + public int getMethodArgsLength(ASTList args) { + return ASTList.length(args); + } + + public void atMethodArgs(ASTList args, int[] types, int[] dims, + String[] cnames) throws CompileError { + int i = 0; + while (args != null) { + ASTree a = args.head(); + a.accept(this); + types[i] = exprType; + dims[i] = arrayDim; + cnames[i] = className; + ++i; + args = args.tail(); + } + } + + void setReturnType(String desc) throws CompileError { + int i = desc.indexOf(')'); + if (i < 0) + badMethod(); + + char c = desc.charAt(++i); + int dim = 0; + while (c == '[') { + ++dim; + c = desc.charAt(++i); + } + + arrayDim = dim; + if (c == 'L') { + int j = desc.indexOf(';', i + 1); + if (j < 0) + badMethod(); + + exprType = CLASS; + className = desc.substring(i + 1, j); + } + else { + exprType = MemberResolver.descToType(c); + className = null; + } + } + + private void atFieldRead(ASTree expr) throws CompileError { + atFieldRead(fieldAccess(expr)); + } + + private void atFieldRead(CtField f) throws CompileError { + FieldInfo finfo = f.getFieldInfo2(); + String type = finfo.getDescriptor(); + + int i = 0; + int dim = 0; + char c = type.charAt(i); + while (c == '[') { + ++dim; + c = type.charAt(++i); + } + + arrayDim = dim; + exprType = MemberResolver.descToType(c); + + if (c == 'L') + className = type.substring(i + 1, type.indexOf(';', i + 1)); + else + className = null; + } + + protected CtField fieldAccess(ASTree expr) throws CompileError { + if (expr instanceof Member) { + String name = ((Member)expr).get(); + try { + return thisClass.getField(name); + } + catch (NotFoundException e) { + // EXPR might be part of a static member access? + throw new NoFieldException(name, expr); + } + } + else if (expr instanceof Expr) { + Expr e = (Expr)expr; + int op = e.getOperator(); + if (op == MEMBER) + return resolver.lookupField(((Symbol)e.oprand1()).get(), + (Symbol)e.oprand2()); + else if (op == '.') + try { + e.oprand1().accept(this); + if (exprType == CLASS && arrayDim == 0) + return resolver.lookupFieldByJvmName(className, + (Symbol)e.oprand2()); + } + catch (NoFieldException nfe) { + if (nfe.getExpr() != e.oprand1()) + throw nfe; + + /* EXPR should be a static field. + * If EXPR might be part of a qualified class name, + * lookupFieldByJvmName2() throws NoFieldException. + */ + Symbol fname = (Symbol)e.oprand2(); + return resolver.lookupFieldByJvmName2(nfe.getField(), + fname, expr); + } + } + + throw new CompileError("bad filed access"); + } + + public void atClassObject(Expr expr) throws CompileError { + exprType = CLASS; + arrayDim = 0; + className =jvmJavaLangClass; + } + + public void atArrayLength(Expr expr) throws CompileError { + expr.oprand1().accept(this); + exprType = INT; + arrayDim = 0; + } + + public void atArrayRead(ASTree array, ASTree index) + throws CompileError + { + array.accept(this); + int type = exprType; + int dim = arrayDim; + String cname = className; + index.accept(this); + exprType = type; + arrayDim = dim - 1; + className = cname; + } + + private void atPlusPlus(int token, ASTree oprand, Expr expr) + throws CompileError + { + boolean isPost = oprand == null; // ++i or i++? + if (isPost) + oprand = expr.oprand2(); + + if (oprand instanceof Variable) { + Declarator d = ((Variable)oprand).getDeclarator(); + exprType = d.getType(); + arrayDim = d.getArrayDim(); + } + else { + if (oprand instanceof Expr) { + Expr e = (Expr)oprand; + if (e.getOperator() == ARRAY) { + atArrayRead(e.oprand1(), e.oprand2()); + // arrayDim should be 0. + int t = exprType; + if (t == INT || t == BYTE || t == CHAR || t == SHORT) + exprType = INT; + + return; + } + } + + atFieldPlusPlus(oprand); + } + } + + protected void atFieldPlusPlus(ASTree oprand) throws CompileError + { + CtField f = fieldAccess(oprand); + atFieldRead(f); + int t = exprType; + if (t == INT || t == BYTE || t == CHAR || t == SHORT) + exprType = INT; + } + + public void atMember(Member mem) throws CompileError { + atFieldRead(mem); + } + + public void atVariable(Variable v) throws CompileError { + Declarator d = v.getDeclarator(); + exprType = d.getType(); + arrayDim = d.getArrayDim(); + className = d.getClassName(); + } + + public void atKeyword(Keyword k) throws CompileError { + arrayDim = 0; + int token = k.get(); + switch (token) { + case TRUE : + case FALSE : + exprType = BOOLEAN; + break; + case NULL : + exprType = NULL; + break; + case THIS : + case SUPER : + exprType = CLASS; + if (token == THIS) + className = getThisName(); + else + className = getSuperName(); + break; + default : + fatal(); + } + } + + public void atStringL(StringL s) throws CompileError { + exprType = CLASS; + arrayDim = 0; + className = jvmJavaLangString; + } + + public void atIntConst(IntConst i) throws CompileError { + arrayDim = 0; + int type = i.getType(); + if (type == IntConstant || type == CharConstant) + exprType = (type == IntConstant ? INT : CHAR); + else + exprType = LONG; + } + + public void atDoubleConst(DoubleConst d) throws CompileError { + arrayDim = 0; + if (d.getType() == DoubleConstant) + exprType = DOUBLE; + else + exprType = FLOAT; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `e.oprand2()` could be null and is dereferenced by call to `lookupField(...)` at line 609. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +CtField TypeChecker.fieldAccess(ASTree) + +### Procedure Id: +javassist.compiler.TypeChecker.fieldAccess(javassist.compiler.ast.ASTree):javassist.CtField.8fcbc61edbc1e81c6769989bde2e618b + +### File: +src/main/javassist/compiler/TypeChecker.java + +### Key: +TypeChecker.java|fieldAccess|NULL_DEREFERENCE + +### Node Key: +3145a50fff89abe83491a437b1d1dd9a + +### Hash: +1d2e28d51076d9396b5d3696ee66b146 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3387/instruction.md b/inferredbugs-3387/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c2b3ec6dba5f92896e69f834159b983a3db03d88 --- /dev/null +++ b/inferredbugs-3387/instruction.md @@ -0,0 +1,217 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** javassist +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Javassist, a Java-bytecode translator toolkit. + * Copyright (C) 1999-2003 Shigeru Chiba. All Rights Reserved. + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. Alternatively, the contents of this file may be used under + * the terms of the GNU Lesser General Public License Version 2.1 or later. + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + */ + +package javassist; + +import java.io.*; +import java.net.*; + +/** + * A class search-path specified with URL (http). + * + * @see javassist.ClassPath + * @see ClassPool#insertClassPath(ClassPath) + * @see ClassPool#appendClassPath(ClassPath) + */ +public class URLClassPath implements ClassPath { + protected String hostname; + protected int port; + protected String directory; + protected String packageName; + + /** + * Creates a search path specified with URL (http). + * + *

    This search path is used only if a requested + * class name starts with the name specified by packageName. + * If packageName is "mypack" and a requested class is + * "mypack.sub.Test", then the given URL is used for loading that class. + * If packageName is null, the URL is used + * for loading any class. + * + * @param host host name + * @param port port number + * @param directory directory name ending with "/". + * It can be "/" (root directory). + * @param packageName package name. + */ + public URLClassPath(String host, int port, + String directory, String packageName) { + hostname = host; + this.port = port; + this.directory = directory; + this.packageName = packageName; + } + + public String toString() { + return hostname + ":" + port + directory; + } + + /** + * Opens a class file with http. + * + * @return null if the class file is not found. + */ + public InputStream openClassfile(String classname) { + try { + if (packageName == null || classname.startsWith(packageName)) { + String jarname + = directory + classname.replace('.', '/') + ".class"; + URLConnection con = fetchClass0(hostname, port, jarname); + return con.getInputStream(); + } + } + catch (IOException e) {} + return null; // not found + } + + /** + * Closes this class path. + */ + public void close() {} + + /** + * Reads a class file on an http server. + * + * @param host host name + * @param port port number + * @param directory directory name ending with "/". + * It can be "/" (root directory). + * @param classname fully-qualified class name + */ + public static byte[] fetchClass(String host, int port, + String directory, String classname) + throws IOException + { + byte[] b; + URLConnection con = fetchClass0(host, port, + directory + classname.replace('.', '/') + ".class"); + int size = con.getContentLength(); + InputStream s = con.getInputStream(); + try { + if (size <= 0) + b = ClassPoolTail.readStream(s); + else { + b = new byte[size]; + int len = 0; + do { + int n = s.read(b, len, size - len); + if (n < 0) + throw new IOException("the stream was closed: " + + classname); + + len += n; + } while (len < size); + } + } + finally { + s.close(); + } + + return b; + } + + private static URLConnection fetchClass0(String host, int port, + String filename) + throws IOException + { + URL url; + try { + url = new URL("http", host, port, filename); + } + catch (MalformedURLException e) { + // should never reache here. + throw new IOException("invalid URL?"); + } + + URLConnection con = url.openConnection(); + con.connect(); + return con; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.net.HttpURLConnection` acquired by call to `fetchClass0(...)` at line 72 is not released after line 73. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +InputStream URLClassPath.openClassfile(String) + +### Procedure Id: +javassist.URLClassPath.openClassfile(java.lang.String):java.io.InputStream.cb8c6566c172cb70b1c636de56a5a368 + +### File: +src/main/javassist/URLClassPath.java + +### Key: +URLClassPath.java|openClassfile|RESOURCE_LEAK + +### Node Key: +cd917e0854ab05a03701b589d85cd12c + +### Hash: +6962be88a012285a01306f850552d992 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3388/instruction.md b/inferredbugs-3388/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c8139f51ef086a7deb278bc4b785a7648b1f8d8f --- /dev/null +++ b/inferredbugs-3388/instruction.md @@ -0,0 +1,1509 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** javassist +**Bug ID:** 14 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Javassist, a Java-bytecode translator toolkit. + * Copyright (C) 1999-2005 Shigeru Chiba. All Rights Reserved. + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. Alternatively, the contents of this file may be used under + * the terms of the GNU Lesser General Public License Version 2.1 or later. + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + */ + +package javassist.bytecode; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.PrintWriter; +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javassist.CtClass; + +/** + * Constant pool table. + */ +public final class ConstPool { + LongVector items; + int numOfItems; + HashMap classes; + HashMap strings; + int thisClassInfo; + + /** + * CONSTANT_Class + */ + public static final int CONST_Class = ClassInfo.tag; + + /** + * CONSTANT_Fieldref + */ + public static final int CONST_Fieldref = FieldrefInfo.tag; + + /** + * CONSTANT_Methodref + */ + public static final int CONST_Methodref = MethodrefInfo.tag; + + /** + * CONSTANT_InterfaceMethodref + */ + public static final int CONST_InterfaceMethodref + = InterfaceMethodrefInfo.tag; + + /** + * CONSTANT_String + */ + public static final int CONST_String = StringInfo.tag; + + /** + * CONSTANT_Integer + */ + public static final int CONST_Integer = IntegerInfo.tag; + + /** + * CONSTANT_Float + */ + public static final int CONST_Float = FloatInfo.tag; + + /** + * CONSTANT_Long + */ + public static final int CONST_Long = LongInfo.tag; + + /** + * CONSTANT_Double + */ + public static final int CONST_Double = DoubleInfo.tag; + + /** + * CONSTANT_NameAndType + */ + public static final int CONST_NameAndType = NameAndTypeInfo.tag; + + /** + * CONSTANT_Utf8 + */ + public static final int CONST_Utf8 = Utf8Info.tag; + + /** + * Represents the class using this constant pool table. + */ + public static final CtClass THIS = null; + + /** + * Constructs a constant pool table. + * + * @param thisclass the name of the class using this constant + * pool table + */ + public ConstPool(String thisclass) { + items = new LongVector(); + numOfItems = 0; + addItem(null); // index 0 is reserved by the JVM. + classes = new HashMap(); + strings = new HashMap(); + thisClassInfo = addClassInfo(thisclass); + } + + /** + * Constructs a constant pool table from the given byte stream. + * + * @param in byte stream. + */ + public ConstPool(DataInputStream in) throws IOException { + classes = new HashMap(); + strings = new HashMap(); + thisClassInfo = 0; + /* read() initializes items and numOfItems, and do addItem(null). + */ + read(in); + } + + void prune() { + classes = new HashMap(); + strings = new HashMap(); + } + + /** + * Returns the number of entries in this table. + */ + public int getSize() { + return numOfItems; + } + + /** + * Returns the name of the class using this constant pool table. + */ + public String getClassName() { + return getClassInfo(thisClassInfo); + } + + /** + * Returns the index of CONSTANT_Class_info structure + * specifying the class using this constant pool table. + */ + public int getThisClassInfo() { + return thisClassInfo; + } + + void setThisClassInfo(int i) { + thisClassInfo = i; + } + + ConstInfo getItem(int n) { + return (ConstInfo)items.elementAt(n); + } + + /** + * Returns the tag field of the constant pool table + * entry at the given index. + */ + public int getTag(int index) { + return getItem(index).getTag(); + } + + /** + * Reads CONSTANT_Class_info structure + * at the given index. + * + * @return a fully-qualified class or interface name specified + * by name_index. + */ + public String getClassInfo(int index) { + ClassInfo c = (ClassInfo)getItem(index); + if (c == null) + return null; + else + return Descriptor.toJavaName(getUtf8Info(c.name)); + } + + /** + * Reads the name_index field of the + * CONSTANT_NameAndType_info structure + * at the given index. + */ + public int getNameAndTypeName(int index) { + NameAndTypeInfo ntinfo = (NameAndTypeInfo)getItem(index); + return ntinfo.memberName; + } + + /** + * Reads the descriptor_index field of the + * CONSTANT_NameAndType_info structure + * at the given index. + */ + public int getNameAndTypeDescriptor(int index) { + NameAndTypeInfo ntinfo = (NameAndTypeInfo)getItem(index); + return ntinfo.typeDescriptor; + } + + /** + * Reads the class_index field of the + * CONSTANT_Fieldref_info structure + * at the given index. + */ + public int getFieldrefClass(int index) { + FieldrefInfo finfo = (FieldrefInfo)getItem(index); + return finfo.classIndex; + } + + /** + * Reads the class_index field of the + * CONSTANT_Fieldref_info structure + * at the given index. + * + * @return the name of the class at that class_index. + */ + public String getFieldrefClassName(int index) { + FieldrefInfo f = (FieldrefInfo)getItem(index); + if (f == null) + return null; + else + return getClassInfo(f.classIndex); + } + + /** + * Reads the name_and_type_index field of the + * CONSTANT_Fieldref_info structure + * at the given index. + */ + public int getFieldrefNameAndType(int index) { + FieldrefInfo finfo = (FieldrefInfo)getItem(index); + return finfo.nameAndTypeIndex; + } + + /** + * Reads the name_index field of the + * CONSTANT_NameAndType_info structure + * indirectly specified by the given index. + * + * @param index an index to a CONSTANT_Fieldref_info. + * @return the name of the field. + */ + public String getFieldrefName(int index) { + FieldrefInfo f = (FieldrefInfo)getItem(index); + if (f == null) + return null; + else { + NameAndTypeInfo n = (NameAndTypeInfo)getItem(f.nameAndTypeIndex); + if(n == null) + return null; + else + return getUtf8Info(n.memberName); + } + } + + /** + * Reads the descriptor_index field of the + * CONSTANT_NameAndType_info structure + * indirectly specified by the given index. + * + * @param index an index to a CONSTANT_Fieldref_info. + * @return the type descriptor of the field. + */ + public String getFieldrefType(int index) { + FieldrefInfo f = (FieldrefInfo)getItem(index); + if (f == null) + return null; + else { + NameAndTypeInfo n = (NameAndTypeInfo) getItem(f.nameAndTypeIndex); + if(n == null) + return null; + else + return getUtf8Info(n.typeDescriptor); + } + } + + /** + * Reads the class_index field of the + * CONSTANT_Methodref_info structure + * at the given index. + */ + public int getMethodrefClass(int index) { + MethodrefInfo minfo = (MethodrefInfo)getItem(index); + return minfo.classIndex; + } + + /** + * Reads the class_index field of the + * CONSTANT_Methodref_info structure + * at the given index. + * + * @return the name of the class at that class_index. + */ + public String getMethodrefClassName(int index) { + MethodrefInfo minfo = (MethodrefInfo)getItem(index); + if (minfo == null) + return null; + else + return getClassInfo(minfo.classIndex); + } + + /** + * Reads the name_and_type_index field of the + * CONSTANT_Methodref_info structure + * at the given index. + */ + public int getMethodrefNameAndType(int index) { + MethodrefInfo minfo = (MethodrefInfo)getItem(index); + return minfo.nameAndTypeIndex; + } + + /** + * Reads the name_index field of the + * CONSTANT_NameAndType_info structure + * indirectly specified by the given index. + * + * @param index an index to a CONSTANT_Methodref_info. + * @return the name of the method. + */ + public String getMethodrefName(int index) { + MethodrefInfo minfo = (MethodrefInfo)getItem(index); + if (minfo == null) + return null; + else { + NameAndTypeInfo n + = (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex); + if(n == null) + return null; + else + return getUtf8Info(n.memberName); + } + } + + /** + * Reads the descriptor_index field of the + * CONSTANT_NameAndType_info structure + * indirectly specified by the given index. + * + * @param index an index to a CONSTANT_Methodref_info. + * @return the descriptor of the method. + */ + public String getMethodrefType(int index) { + MethodrefInfo minfo = (MethodrefInfo)getItem(index); + if (minfo == null) + return null; + else { + NameAndTypeInfo n + = (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex); + if(n == null) + return null; + else + return getUtf8Info(n.typeDescriptor); + } + } + + /** + * Reads the class_index field of the + * CONSTANT_InterfaceMethodref_info structure + * at the given index. + */ + public int getInterfaceMethodrefClass(int index) { + InterfaceMethodrefInfo minfo + = (InterfaceMethodrefInfo)getItem(index); + return minfo.classIndex; + } + + /** + * Reads the class_index field of the + * CONSTANT_InterfaceMethodref_info structure + * at the given index. + * + * @return the name of the class at that class_index. + */ + public String getInterfaceMethodrefClassName(int index) { + InterfaceMethodrefInfo minfo + = (InterfaceMethodrefInfo)getItem(index); + return getClassInfo(minfo.classIndex); + } + + /** + * Reads the name_and_type_index field of the + * CONSTANT_InterfaceMethodref_info structure + * at the given index. + */ + public int getInterfaceMethodrefNameAndType(int index) { + InterfaceMethodrefInfo minfo + = (InterfaceMethodrefInfo)getItem(index); + return minfo.nameAndTypeIndex; + } + + /** + * Reads the name_index field of the + * CONSTANT_NameAndType_info structure + * indirectly specified by the given index. + * + * @param index an index to + * a CONSTANT_InterfaceMethodref_info. + * @return the name of the method. + */ + public String getInterfaceMethodrefName(int index) { + InterfaceMethodrefInfo minfo + = (InterfaceMethodrefInfo)getItem(index); + if (minfo == null) + return null; + else { + NameAndTypeInfo n + = (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex); + if(n == null) + return null; + else + return getUtf8Info(n.memberName); + } + } + + /** + * Reads the descriptor_index field of the + * CONSTANT_NameAndType_info structure + * indirectly specified by the given index. + * + * @param index an index to + * a CONSTANT_InterfaceMethodref_info. + * @return the descriptor of the method. + */ + public String getInterfaceMethodrefType(int index) { + InterfaceMethodrefInfo minfo + = (InterfaceMethodrefInfo)getItem(index); + if (minfo == null) + return null; + else { + NameAndTypeInfo n + = (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex); + if(n == null) + return null; + else + return getUtf8Info(n.typeDescriptor); + } + } + /** + * Reads CONSTANT_Integer_info, _Float_info, + * _Long_info, _Double_info, or + * _String_info structure. + * These are used with the LDC instruction. + * + * @return a String value or a wrapped primitive-type + * value. + */ + public Object getLdcValue(int index) { + ConstInfo constInfo = this.getItem(index); + Object value = null; + if (constInfo instanceof StringInfo) + value = this.getStringInfo(index); + else if (constInfo instanceof FloatInfo) + value = new Float(getFloatInfo(index)); + else if (constInfo instanceof IntegerInfo) + value = new Integer(getIntegerInfo(index)); + else if (constInfo instanceof LongInfo) + value = new Long(getLongInfo(index)); + else if (constInfo instanceof DoubleInfo) + value = new Double(getDoubleInfo(index)); + else + value = null; + + return value; + } + + /** + * Reads CONSTANT_Integer_info structure + * at the given index. + * + * @return the value specified by this entry. + */ + public int getIntegerInfo(int index) { + IntegerInfo i = (IntegerInfo)getItem(index); + return i.value; + } + + /** + * Reads CONSTANT_Float_info structure + * at the given index. + * + * @return the value specified by this entry. + */ + public float getFloatInfo(int index) { + FloatInfo i = (FloatInfo)getItem(index); + return i.value; + } + + /** + * Reads CONSTANT_Long_info structure + * at the given index. + * + * @return the value specified by this entry. + */ + public long getLongInfo(int index) { + LongInfo i = (LongInfo)getItem(index); + return i.value; + } + + /** + * Reads CONSTANT_Double_info structure + * at the given index. + * + * @return the value specified by this entry. + */ + public double getDoubleInfo(int index) { + DoubleInfo i = (DoubleInfo)getItem(index); + return i.value; + } + + /** + * Reads CONSTANT_String_info structure + * at the given index. + * + * @return the string specified by string_index. + */ + public String getStringInfo(int index) { + StringInfo si = (StringInfo)getItem(index); + return getUtf8Info(si.string); + } + + /** + * Reads CONSTANT_utf8_info structure + * at the given index. + * + * @return the string specified by this entry. + */ + public String getUtf8Info(int index) { + Utf8Info utf = (Utf8Info)getItem(index); + return utf.string; + } + + /** + * Determines whether CONSTANT_Methodref_info + * structure at the given index represents the constructor + * of the given class. + * + * @return the descriptor_index specifying + * the type descriptor of the that constructor. + * If it is not that constructor, + * isConstructor() returns 0. + */ + public int isConstructor(String classname, int index) { + return isMember(classname, MethodInfo.nameInit, index); + } + + /** + * Determines whether CONSTANT_Methodref_info, + * CONSTANT_Fieldref_info, or + * CONSTANT_InterfaceMethodref_info structure + * at the given index represents the member with the specified + * name and declaring class. + * + * @param classname the class declaring the member + * @param membername the member name + * @param index the index into the constant pool table + * + * @return the descriptor_index specifying + * the type descriptor of that member. + * If it is not that member, + * isMember() returns 0. + */ + public int isMember(String classname, String membername, int index) { + MemberrefInfo minfo = (MemberrefInfo)getItem(index); + if (getClassInfo(minfo.classIndex).equals(classname)) { + NameAndTypeInfo ntinfo + = (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex); + if (getUtf8Info(ntinfo.memberName).equals(membername)) + return ntinfo.typeDescriptor; + } + + return 0; // false + } + + private int addItem(ConstInfo info) { + items.addElement(info); + return numOfItems++; + } + + /** + * Copies the n-th item in this ConstPool object into the destination + * ConstPool object. + * The class names that the item refers to are renamed according + * to the given map. + * + * @param n the n-th item + * @param dest destination constant pool table + * @param classnames the map or null. + * @return the index of the copied item into the destination ClassPool. + */ + public int copy(int n, ConstPool dest, Map classnames) { + if (n == 0) + return 0; + + ConstInfo info = getItem(n); + return info.copy(this, dest, classnames); + } + + int addConstInfoPadding() { + return addItem(new ConstInfoPadding()); + } + + /** + * Adds a new CONSTANT_Class_info structure. + * + *

    This also adds a CONSTANT_Utf8_info structure + * for storing the class name. + * + * @return the index of the added entry. + */ + public int addClassInfo(CtClass c) { + if (c == THIS) + return thisClassInfo; + else if (!c.isArray()) + return addClassInfo(c.getName()); + else { + // an array type is recorded in the hashtable with + // the key "[L;" instead of "". + // + // note: toJvmName(toJvmName(c)) is equal to toJvmName(c). + + return addClassInfo(Descriptor.toJvmName(c)); + } + } + + /** + * Adds a new CONSTANT_Class_info structure. + * + *

    This also adds a CONSTANT_Utf8_info structure + * for storing the class name. + * + * @param qname a fully-qualified class name + * (or the JVM-internal representation of that name). + * @return the index of the added entry. + */ + public int addClassInfo(String qname) { + ClassInfo info = (ClassInfo)classes.get(qname); + if (info != null) + return info.index; + else { + int utf8 = addUtf8Info(Descriptor.toJvmName(qname)); + info = new ClassInfo(utf8, numOfItems); + classes.put(qname, info); + return addItem(info); + } + } + + /** + * Adds a new CONSTANT_NameAndType_info structure. + * + *

    This also adds CONSTANT_Utf8_info structures. + * + * @param name name_index + * @param type descriptor_index + * @return the index of the added entry. + */ + public int addNameAndTypeInfo(String name, String type) { + return addNameAndTypeInfo(addUtf8Info(name), addUtf8Info(type)); + } + + /** + * Adds a new CONSTANT_NameAndType_info structure. + * + * @param name name_index + * @param type descriptor_index + * @return the index of the added entry. + */ + public int addNameAndTypeInfo(int name, int type) { + return addItem(new NameAndTypeInfo(name, type)); + } + + /** + * Adds a new CONSTANT_Fieldref_info structure. + * + *

    This also adds a new CONSTANT_NameAndType_info + * structure. + * + * @param classInfo class_index + * @param name name_index + * of CONSTANT_NameAndType_info. + * @param type descriptor_index + * of CONSTANT_NameAndType_info. + * @return the index of the added entry. + */ + public int addFieldrefInfo(int classInfo, String name, String type) { + int nt = addNameAndTypeInfo(name, type); + return addFieldrefInfo(classInfo, nt); + } + + /** + * Adds a new CONSTANT_Fieldref_info structure. + * + * @param classInfo class_index + * @param nameAndTypeInfo name_and_type_index. + * @return the index of the added entry. + */ + public int addFieldrefInfo(int classInfo, int nameAndTypeInfo) { + return addItem(new FieldrefInfo(classInfo, nameAndTypeInfo)); + } + + /** + * Adds a new CONSTANT_Methodref_info structure. + * + *

    This also adds a new CONSTANT_NameAndType_info + * structure. + * + * @param classInfo class_index + * @param name name_index + * of CONSTANT_NameAndType_info. + * @param type descriptor_index + * of CONSTANT_NameAndType_info. + * @return the index of the added entry. + */ + public int addMethodrefInfo(int classInfo, String name, String type) { + int nt = addNameAndTypeInfo(name, type); + return addMethodrefInfo(classInfo, nt); + } + + /** + * Adds a new CONSTANT_Methodref_info structure. + * + * @param classInfo class_index + * @param nameAndTypeInfo name_and_type_index. + * @return the index of the added entry. + */ + public int addMethodrefInfo(int classInfo, int nameAndTypeInfo) { + return addItem(new MethodrefInfo(classInfo, nameAndTypeInfo)); + } + + /** + * Adds a new CONSTANT_InterfaceMethodref_info + * structure. + * + *

    This also adds a new CONSTANT_NameAndType_info + * structure. + * + * @param classInfo class_index + * @param name name_index + * of CONSTANT_NameAndType_info. + * @param type descriptor_index + * of CONSTANT_NameAndType_info. + * @return the index of the added entry. + */ + public int addInterfaceMethodrefInfo(int classInfo, String name, + String type) { + int nt = addNameAndTypeInfo(name, type); + return addInterfaceMethodrefInfo(classInfo, nt); + } + + /** + * Adds a new CONSTANT_InterfaceMethodref_info + * structure. + * + * @param classInfo class_index + * @param nameAndTypeInfo name_and_type_index. + * @return the index of the added entry. + */ + public int addInterfaceMethodrefInfo(int classInfo, + int nameAndTypeInfo) { + return addItem(new InterfaceMethodrefInfo(classInfo, + nameAndTypeInfo)); + } + + /** + * Adds a new CONSTANT_String_info + * structure. + * + *

    This also adds a new CONSTANT_Utf8_info + * structure. + * + * @return the index of the added entry. + */ + public int addStringInfo(String str) { + return addItem(new StringInfo(addUtf8Info(str))); + } + + /** + * Adds a new CONSTANT_Integer_info + * structure. + * + * @return the index of the added entry. + */ + public int addIntegerInfo(int i) { + return addItem(new IntegerInfo(i)); + } + + /** + * Adds a new CONSTANT_Float_info + * structure. + * + * @return the index of the added entry. + */ + public int addFloatInfo(float f) { + return addItem(new FloatInfo(f)); + } + + /** + * Adds a new CONSTANT_Long_info + * structure. + * + * @return the index of the added entry. + */ + public int addLongInfo(long l) { + int i = addItem(new LongInfo(l)); + addItem(new ConstInfoPadding()); + return i; + } + + /** + * Adds a new CONSTANT_Double_info + * structure. + * + * @return the index of the added entry. + */ + public int addDoubleInfo(double d) { + int i = addItem(new DoubleInfo(d)); + addItem(new ConstInfoPadding()); + return i; + } + + /** + * Adds a new CONSTANT_Utf8_info + * structure. + * + *

    If the given utf8 string has been already recorded in the + * table, then this method does not add a new entry to avoid adding + * a duplicated entry. + * Instead, it returns the index of the entry already recorded. + * + * @return the index of the added entry. + */ + public int addUtf8Info(String utf8) { + Utf8Info info = (Utf8Info)strings.get(utf8); + if (info != null) + return info.index; + else { + info = new Utf8Info(utf8, numOfItems); + strings.put(utf8, info); + return addItem(info); + } + } + + /** + * Get all the class names. + * + * @return a set of class names + */ + public Set getClassNames() + { + HashSet result = new HashSet(); + LongVector v = items; + int size = numOfItems; + for (int i = 1; i < size; ++i) { + String className = ((ConstInfo) v.elementAt(i)).getClassName(this); + if (className != null) + result.add(className); + } + return result; + } + + /** + * Replaces all occurrences of a class name. + * + * @param oldName the replaced name + * @param newName the substituted name. + */ + public void renameClass(String oldName, String newName) { + LongVector v = items; + int size = numOfItems; + for (int i = 1; i < size; ++i) + ((ConstInfo)v.elementAt(i)).renameClass(this, oldName, newName); + } + + /** + * Replaces all occurrences of class names. + * + * @param classnames specifies pairs of replaced and substituted + * name. + */ + public void renameClass(Map classnames) { + LongVector v = items; + int size = numOfItems; + for (int i = 1; i < size; ++i) + ((ConstInfo)v.elementAt(i)).renameClass(this, classnames); + } + + private void read(DataInputStream in) throws IOException { + int n = in.readUnsignedShort(); + + items = new LongVector(n); + numOfItems = 0; + addItem(null); // index 0 is reserved by the JVM. + + while (--n > 0) { // index 0 is reserved by JVM + int tag = readOne(in); + if ((tag == LongInfo.tag) || (tag == DoubleInfo.tag)) { + addItem(new ConstInfoPadding()); + --n; + } + } + + int i = 1; + while (true) { + ConstInfo info = (ConstInfo)items.elementAt(i++); + if (info == null) + break; + else + info.makeHashtable(this); + } + } + + private int readOne(DataInputStream in) throws IOException { + ConstInfo info; + int tag = in.readUnsignedByte(); + switch (tag) { + case Utf8Info.tag : // 1 + info = new Utf8Info(in, numOfItems); + strings.put(((Utf8Info)info).string, info); + break; + case IntegerInfo.tag : // 3 + info = new IntegerInfo(in); + break; + case FloatInfo.tag : // 4 + info = new FloatInfo(in); + break; + case LongInfo.tag : // 5 + info = new LongInfo(in); + break; + case DoubleInfo.tag : // 6 + info = new DoubleInfo(in); + break; + case ClassInfo.tag : // 7 + info = new ClassInfo(in, numOfItems); + // classes.put(, info); + break; + case StringInfo.tag : // 8 + info = new StringInfo(in); + break; + case FieldrefInfo.tag : // 9 + info = new FieldrefInfo(in); + break; + case MethodrefInfo.tag : // 10 + info = new MethodrefInfo(in); + break; + case InterfaceMethodrefInfo.tag : // 11 + info = new InterfaceMethodrefInfo(in); + break; + case NameAndTypeInfo.tag : // 12 + info = new NameAndTypeInfo(in); + break; + default : + throw new IOException("invalid constant type: " + tag); + } + + addItem(info); + return tag; + } + + /** + * Writes the contents of the constant pool table. + */ + public void write(DataOutputStream out) throws IOException { + out.writeShort(numOfItems); + LongVector v = items; + int size = numOfItems; + for (int i = 1; i < size; ++i) + ((ConstInfo)v.elementAt(i)).write(out); + } + + /** + * Prints the contents of the constant pool table. + */ + public void print() { + print(new PrintWriter(System.out, true)); + } + + /** + * Prints the contents of the constant pool table. + */ + public void print(PrintWriter out) { + int size = numOfItems; + for (int i = 1; i < size; ++i) { + out.print(i); + out.print(" "); + ((ConstInfo)items.elementAt(i)).print(out); + } + } +} + +abstract class ConstInfo { + public abstract int getTag(); + + public String getClassName(ConstPool cp) { return null; } + public void renameClass(ConstPool cp, String oldName, String newName) {} + public void renameClass(ConstPool cp, Map classnames) {} + public abstract int copy(ConstPool src, ConstPool dest, Map classnames); + // ** classnames is a mapping between JVM names. + + public abstract void write(DataOutputStream out) throws IOException; + public abstract void print(PrintWriter out); + + void makeHashtable(ConstPool cp) {} // called after read() finishes in ConstPool. + + public String toString() { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + PrintWriter out = new PrintWriter(bout); + print(out); + return bout.toString(); + } +} + +/* padding following DoubleInfo or LongInfo. + */ +class ConstInfoPadding extends ConstInfo { + public int getTag() { return 0; } + + public int copy(ConstPool src, ConstPool dest, Map map) { + return dest.addConstInfoPadding(); + } + + public void write(DataOutputStream out) throws IOException {} + + public void print(PrintWriter out) { + out.println("padding"); + } +} + +class ClassInfo extends ConstInfo { + static final int tag = 7; + int name; + int index; + + public ClassInfo(int className, int i) { + name = className; + index = i; + } + + public ClassInfo(DataInputStream in, int i) throws IOException { + name = in.readUnsignedShort(); + index = i; + } + + public int getTag() { return tag; } + + public String getClassName(ConstPool cp) { + return cp.getUtf8Info(name); + }; + + public void renameClass(ConstPool cp, String oldName, String newName) { + String nameStr = cp.getUtf8Info(name); + if (nameStr.equals(oldName)) + name = cp.addUtf8Info(newName); + else if (nameStr.charAt(0) == '[') { + String nameStr2 = Descriptor.rename(nameStr, oldName, newName); + if (nameStr != nameStr2) + name = cp.addUtf8Info(nameStr2); + } + } + + public void renameClass(ConstPool cp, Map map) { + String oldName = cp.getUtf8Info(name); + if (oldName.charAt(0) == '[') { + String newName = Descriptor.rename(oldName, map); + if (oldName != newName) + name = cp.addUtf8Info(newName); + } + else { + String newName = (String)map.get(oldName); + if (newName != null && !newName.equals(oldName)) + name = cp.addUtf8Info(newName); + } + } + + public int copy(ConstPool src, ConstPool dest, Map map) { + String classname = src.getUtf8Info(name); + if (map != null) { + String newname = (String)map.get(classname); + if (newname != null) + classname = newname; + } + + return dest.addClassInfo(classname); + } + + public void write(DataOutputStream out) throws IOException { + out.writeByte(tag); + out.writeShort(name); + } + + public void print(PrintWriter out) { + out.print("Class #"); + out.println(name); + } + + void makeHashtable(ConstPool cp) { + String name = Descriptor.toJavaName(getClassName(cp)); + cp.classes.put(name, this); + } +} + +class NameAndTypeInfo extends ConstInfo { + static final int tag = 12; + int memberName; + int typeDescriptor; + + public NameAndTypeInfo(int name, int type) { + memberName = name; + typeDescriptor = type; + } + + public NameAndTypeInfo(DataInputStream in) throws IOException { + memberName = in.readUnsignedShort(); + typeDescriptor = in.readUnsignedShort(); + } + + public int getTag() { return tag; } + + public void renameClass(ConstPool cp, String oldName, String newName) { + String type = cp.getUtf8Info(typeDescriptor); + String type2 = Descriptor.rename(type, oldName, newName); + if (type != type2) + typeDescriptor = cp.addUtf8Info(type2); + } + + public void renameClass(ConstPool cp, Map map) { + String type = cp.getUtf8Info(typeDescriptor); + String type2 = Descriptor.rename(type, map); + if (type != type2) + typeDescriptor = cp.addUtf8Info(type2); + } + + public int copy(ConstPool src, ConstPool dest, Map map) { + String mname = src.getUtf8Info(memberName); + String tdesc = src.getUtf8Info(typeDescriptor); + tdesc = Descriptor.rename(tdesc, map); + return dest.addNameAndTypeInfo(dest.addUtf8Info(mname), + dest.addUtf8Info(tdesc)); + } + + public void write(DataOutputStream out) throws IOException { + out.writeByte(tag); + out.writeShort(memberName); + out.writeShort(typeDescriptor); + } + + public void print(PrintWriter out) { + out.print("NameAndType #"); + out.print(memberName); + out.print(", type #"); + out.println(typeDescriptor); + } +} + +abstract class MemberrefInfo extends ConstInfo { + int classIndex; + int nameAndTypeIndex; + + public MemberrefInfo(int cindex, int ntindex) { + classIndex = cindex; + nameAndTypeIndex = ntindex; + } + + public MemberrefInfo(DataInputStream in) throws IOException { + classIndex = in.readUnsignedShort(); + nameAndTypeIndex = in.readUnsignedShort(); + } + + public int copy(ConstPool src, ConstPool dest, Map map) { + int classIndex2 = src.getItem(classIndex).copy(src, dest, map); + int ntIndex2 = src.getItem(nameAndTypeIndex).copy(src, dest, map); + return copy2(dest, classIndex2, ntIndex2); + } + + abstract protected int copy2(ConstPool dest, int cindex, int ntindex); + + public void write(DataOutputStream out) throws IOException { + out.writeByte(getTag()); + out.writeShort(classIndex); + out.writeShort(nameAndTypeIndex); + } + + public void print(PrintWriter out) { + out.print(getTagName() + " #"); + out.print(classIndex); + out.print(", name&type #"); + out.println(nameAndTypeIndex); + } + + public abstract String getTagName(); +} + +class FieldrefInfo extends MemberrefInfo { + static final int tag = 9; + + public FieldrefInfo(int cindex, int ntindex) { + super(cindex, ntindex); + } + + public FieldrefInfo(DataInputStream in) throws IOException { + super(in); + } + + public int getTag() { return tag; } + + public String getTagName() { return "Field"; } + + protected int copy2(ConstPool dest, int cindex, int ntindex) { + return dest.addFieldrefInfo(cindex, ntindex); + } +} + +class MethodrefInfo extends MemberrefInfo { + static final int tag = 10; + + public MethodrefInfo(int cindex, int ntindex) { + super(cindex, ntindex); + } + + public MethodrefInfo(DataInputStream in) throws IOException { + super(in); + } + + public int getTag() { return tag; } + + public String getTagName() { return "Method"; } + + protected int copy2(ConstPool dest, int cindex, int ntindex) { + return dest.addMethodrefInfo(cindex, ntindex); + } +} + +class InterfaceMethodrefInfo extends MemberrefInfo { + static final int tag = 11; + + public InterfaceMethodrefInfo(int cindex, int ntindex) { + super(cindex, ntindex); + } + + public InterfaceMethodrefInfo(DataInputStream in) throws IOException { + super(in); + } + + public int getTag() { return tag; } + + public String getTagName() { return "Interface"; } + + protected int copy2(ConstPool dest, int cindex, int ntindex) { + return dest.addInterfaceMethodrefInfo(cindex, ntindex); + } +} + +class StringInfo extends ConstInfo { + static final int tag = 8; + int string; + + public StringInfo(int str) { + string = str; + } + + public StringInfo(DataInputStream in) throws IOException { + string = in.readUnsignedShort(); + } + + public int getTag() { return tag; } + + public int copy(ConstPool src, ConstPool dest, Map map) { + return dest.addStringInfo(src.getUtf8Info(string)); + } + + public void write(DataOutputStream out) throws IOException { + out.writeByte(tag); + out.writeShort(string); + } + + public void print(PrintWriter out) { + out.print("String #"); + out.println(string); + } +} + +class IntegerInfo extends ConstInfo { + static final int tag = 3; + int value; + + public IntegerInfo(int i) { + value = i; + } + + public IntegerInfo(DataInputStream in) throws IOException { + value = in.readInt(); + } + + public int getTag() { return tag; } + + public int copy(ConstPool src, ConstPool dest, Map map) { + return dest.addIntegerInfo(value); + } + + public void write(DataOutputStream out) throws IOException { + out.writeByte(tag); + out.writeInt(value); + } + + public void print(PrintWriter out) { + out.print("Integer "); + out.println(value); + } +} + +class FloatInfo extends ConstInfo { + static final int tag = 4; + float value; + + public FloatInfo(float f) { + value = f; + } + + public FloatInfo(DataInputStream in) throws IOException { + value = in.readFloat(); + } + + public int getTag() { return tag; } + + public int copy(ConstPool src, ConstPool dest, Map map) { + return dest.addFloatInfo(value); + } + + public void write(DataOutputStream out) throws IOException { + out.writeByte(tag); + out.writeFloat(value); + } + + public void print(PrintWriter out) { + out.print("Float "); + out.println(value); + } +} + +class LongInfo extends ConstInfo { + static final int tag = 5; + long value; + + public LongInfo(long l) { + value = l; + } + + public LongInfo(DataInputStream in) throws IOException { + value = in.readLong(); + } + + public int getTag() { return tag; } + + public int copy(ConstPool src, ConstPool dest, Map map) { + return dest.addLongInfo(value); + } + + public void write(DataOutputStream out) throws IOException { + out.writeByte(tag); + out.writeLong(value); + } + + public void print(PrintWriter out) { + out.print("Long "); + out.println(value); + } +} + +class DoubleInfo extends ConstInfo { + static final int tag = 6; + double value; + + public DoubleInfo(double d) { + value = d; + } + + public DoubleInfo(DataInputStream in) throws IOException { + value = in.readDouble(); + } + + public int getTag() { return tag; } + + public int copy(ConstPool src, ConstPool dest, Map map) { + return dest.addDoubleInfo(value); + } + + public void write(DataOutputStream out) throws IOException { + out.writeByte(tag); + out.writeDouble(value); + } + + public void print(PrintWriter out) { + out.print("Double "); + out.println(value); + } +} + +class Utf8Info extends ConstInfo { + static final int tag = 1; + String string; + int index; + + public Utf8Info(String utf8, int i) { + string = utf8; + index = i; + } + + public Utf8Info(DataInputStream in, int i) throws IOException { + string = in.readUTF(); + index = i; + } + + public int getTag() { return tag; } + + public int copy(ConstPool src, ConstPool dest, Map map) { + return dest.addUtf8Info(string); + } + + public void write(DataOutputStream out) throws IOException { + out.writeByte(tag); + out.writeUTF(string); + } + + public void print(PrintWriter out) { + out.print("UTF8 \""); + out.print(string); + out.println("\""); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `v.elementAt(i)` could be null and is dereferenced at line 878. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ConstPool.renameClass(String,String) + +### Procedure Id: +javassist.bytecode.ConstPool.renameClass(java.lang.String,java.lang.String):void.842c388cf2f3a11ce7c8225cd2c6c4ef + +### File: +src/main/javassist/bytecode/ConstPool.java + +### Key: +ConstPool.java|renameClass|NULL_DEREFERENCE + +### Node Key: +4e2e9c3956b81da06fcd899ce03b4e5b + +### Hash: +32bc8d9bcf7c04c1c39f642344201ade + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3389/instruction.md b/inferredbugs-3389/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c5b3c89316d1158a15ede74187087526871ecc47 --- /dev/null +++ b/inferredbugs-3389/instruction.md @@ -0,0 +1,230 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** github-plugin +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.coravy.hudson.plugins.github; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import com.cloudbees.jenkins.GitHubRepositoryName; + +import org.junit.Test; + +/** + * Unit tests of {@link GitHubRepositoryName} + */ +public class GitHubRepositoryNameTest { + + @Test + public void gitAtUrlGitHub() { + GitHubRepositoryName repo = GitHubRepositoryName + .create("git@github.com:jenkinsci/jenkins.git"); + assertNotNull(repo); + assertEquals("jenkinsci", repo.userName); + assertEquals("jenkins", repo.repositoryName); + assertEquals("github.com", repo.host); + } + + @Test + public void gitAtUrlOtherHost() { + GitHubRepositoryName repo = GitHubRepositoryName + .create("git@gh.company.com:jenkinsci/jenkins.git"); + assertNotNull(repo); + assertEquals("jenkinsci", repo.userName); + assertEquals("jenkins", repo.repositoryName); + assertEquals("gh.company.com", repo.host); + } + + @Test + public void gitColonUrlGitHub() { + GitHubRepositoryName repo = GitHubRepositoryName + .create("git://github.com/jenkinsci/jenkins.git"); + assertNotNull(repo); + assertEquals("jenkinsci", repo.userName); + assertEquals("jenkins", repo.repositoryName); + assertEquals("github.com", repo.host); + } + + @Test + public void gitColonUrlOtherHost() { + GitHubRepositoryName repo = GitHubRepositoryName + .create("git://company.net/jenkinsci/jenkins.git"); + assertNotNull(repo); + assertEquals("jenkinsci", repo.userName); + assertEquals("jenkins", repo.repositoryName); + assertEquals("company.net", repo.host); + } + + @Test + public void httpsUrlGitHub() { + GitHubRepositoryName repo = GitHubRepositoryName + .create("https://user@github.com/jenkinsci/jenkins.git"); + assertNotNull(repo); + assertEquals("jenkinsci", repo.userName); + assertEquals("jenkins", repo.repositoryName); + assertEquals("github.com", repo.host); + } + + @Test + public void httpsUrlGitHubWithoutUser() { + //this is valid for anonymous usage + GitHubRepositoryName repo = GitHubRepositoryName + .create("https://github.com/jenkinsci/jenkins.git"); + assertNotNull(repo); + assertEquals("jenkinsci", repo.userName); + assertEquals("jenkins", repo.repositoryName); + assertEquals("github.com", repo.host); + } + + @Test + public void httpsUrlOtherHost() { + GitHubRepositoryName repo = GitHubRepositoryName + .create("https://employee@gh.company.com/jenkinsci/jenkins.git"); + assertNotNull(repo); + assertEquals("jenkinsci", repo.userName); + assertEquals("jenkins", repo.repositoryName); + assertEquals("gh.company.com", repo.host); + } + + @Test + public void gitAtUrlGitHubNoSuffix() { + GitHubRepositoryName repo = GitHubRepositoryName + .create("git@github.com:jenkinsci/jenkins"); + assertNotNull(repo); + assertEquals("jenkinsci", repo.userName); + assertEquals("jenkins", repo.repositoryName); + assertEquals("github.com", repo.host); + } + + @Test + public void gitAtUrlOtherHostNoSuffix() { + GitHubRepositoryName repo = GitHubRepositoryName + .create("git@gh.company.com:jenkinsci/jenkins"); + assertNotNull(repo); + assertEquals("jenkinsci", repo.userName); + assertEquals("jenkins", repo.repositoryName); + assertEquals("gh.company.com", repo.host); + } + + @Test + public void gitColonUrlGitHubNoSuffix() { + GitHubRepositoryName repo = GitHubRepositoryName + .create("git://github.com/jenkinsci/jenkins"); + assertNotNull(repo); + assertEquals("jenkinsci", repo.userName); + assertEquals("jenkins", repo.repositoryName); + assertEquals("github.com", repo.host); + } + + @Test + public void gitColonUrlOtherHostNoSuffix() { + GitHubRepositoryName repo = GitHubRepositoryName + .create("git://company.net/jenkinsci/jenkins"); + assertNotNull(repo); + assertEquals("jenkinsci", repo.userName); + assertEquals("jenkins", repo.repositoryName); + assertEquals("company.net", repo.host); + } + + @Test + public void httpsUrlGitHubNoSuffix() { + GitHubRepositoryName repo = GitHubRepositoryName + .create("https://user@github.com/jenkinsci/jenkins"); + assertNotNull(repo); + assertEquals("jenkinsci", repo.userName); + assertEquals("jenkins", repo.repositoryName); + assertEquals("github.com", repo.host); + } + + @Test + public void httpsUrlGitHubWithoutUserNoSuffix() { + //this is valid for anonymous usage + GitHubRepositoryName repo = GitHubRepositoryName + .create("https://github.com/jenkinsci/jenkins"); + assertNotNull(repo); + assertEquals("jenkinsci", repo.userName); + assertEquals("jenkins", repo.repositoryName); + assertEquals("github.com", repo.host); + } + + @Test + public void httpsUrlOtherHostNoSuffix() { + GitHubRepositoryName repo = GitHubRepositoryName + .create("https://employee@gh.company.com/jenkinsci/jenkins"); + assertNotNull(repo); + assertEquals("jenkinsci", repo.userName); + assertEquals("jenkins", repo.repositoryName); + assertEquals("gh.company.com", repo.host); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `repo` last assigned on line 99 could be null and is dereferenced at line 101. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GitHubRepositoryNameTest.gitAtUrlOtherHostNoSuffix() + +### Procedure Id: +com.coravy.hudson.plugins.github.GitHubRepositoryNameTest.gitAtUrlOtherHostNoSuffix():void.1b698a5aabeee711fd8daf9c289bbf24 + +### File: +src/test/java/com/coravy/hudson/plugins/github/GitHubRepositoryNameTest.java + +### Key: +GitHubRepositoryNameTest.java|gitAtUrlOtherHostNoSuffix|NULL_DEREFERENCE + +### Node Key: +85cff343258cecb5e4a32969738f5b12 + +### Hash: +0cea16ada9b3858898fb39561c22615f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3458/instruction.md b/inferredbugs-3458/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e886d92d3b9ad20ee0491a0dfe188c0615194023 --- /dev/null +++ b/inferredbugs-3458/instruction.md @@ -0,0 +1,2731 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-pool +**Bug ID:** 15 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.pool.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.TreeMap; +import java.util.TimerTask; + +import org.apache.commons.pool.BaseKeyedObjectPool; +import org.apache.commons.pool.KeyedObjectPool; +import org.apache.commons.pool.KeyedPoolableObjectFactory; +import org.apache.commons.pool.PoolUtils; + +/** + * A configurable KeyedObjectPool implementation. + *

    + * When coupled with the appropriate {@link KeyedPoolableObjectFactory}, + * GenericKeyedObjectPool provides robust pooling functionality for + * keyed objects. A GenericKeyedObjectPool can be viewed as a map + * of pools, keyed on the (unique) key values provided to the + * {@link #preparePool preparePool}, {@link #addObject addObject} or + * {@link #borrowObject borrowObject} methods. Each time a new key value is + * provided to one of these methods, a new pool is created under the given key + * to be managed by the containing GenericKeyedObjectPool. + *

    + *

    A GenericKeyedObjectPool provides a number of configurable + * parameters:

    + *
      + *
    • + * {@link #setMaxActive maxActive} controls the maximum number of objects + * (per key) that can allocated by the pool (checked out to client threads, + * or idle in the pool) at one time. When non-positive, there is no limit + * to the number of objects per key. When {@link #setMaxActive maxActive} is + * reached, the keyed pool is said to be exhausted. The default setting for + * this parameter is 8. + *
    • + *
    • + * {@link #setMaxTotal maxTotal} sets a global limit on the number of objects + * that can be in circulation (active or idle) within the combined set of + * pools. When non-positive, there is no limit to the total number of + * objects in circulation. When {@link #setMaxTotal maxTotal} is exceeded, + * all keyed pools are exhausted. When maxTotal is set to a + * positive value and {@link #borrowObject borrowObject} is invoked + * when at the limit with no idle instances available, an attempt is made to + * create room by clearing the oldest 15% of the elements from the keyed + * pools. The default setting for this parameter is -1 (no limit). + *
    • + *
    • + * {@link #setMaxIdle maxIdle} controls the maximum number of objects that can + * sit idle in the pool (per key) at any time. When negative, there + * is no limit to the number of objects that may be idle per key. The + * default setting for this parameter is 8. + *
    • + *
    • + * {@link #setWhenExhaustedAction whenExhaustedAction} specifies the + * behavior of the {@link #borrowObject borrowObject} method when a keyed + * pool is exhausted: + *
        + *
      • + * When {@link #setWhenExhaustedAction whenExhaustedAction} is + * {@link #WHEN_EXHAUSTED_FAIL}, {@link #borrowObject borrowObject} will throw + * a {@link NoSuchElementException} + *
      • + *
      • + * When {@link #setWhenExhaustedAction whenExhaustedAction} is + * {@link #WHEN_EXHAUSTED_GROW}, {@link #borrowObject borrowObject} will create a new + * object and return it (essentially making {@link #setMaxActive maxActive} + * meaningless.) + *
      • + *
      • + * When {@link #setWhenExhaustedAction whenExhaustedAction} + * is {@link #WHEN_EXHAUSTED_BLOCK}, {@link #borrowObject borrowObject} will block + * (invoke {@link Object#wait() wait} until a new or idle object is available. + * If a positive {@link #setMaxWait maxWait} + * value is supplied, the {@link #borrowObject borrowObject} will block for at + * most that many milliseconds, after which a {@link NoSuchElementException} + * will be thrown. If {@link #setMaxWait maxWait} is non-positive, + * the {@link #borrowObject borrowObject} method will block indefinitely. + *
      • + *
      + * The default whenExhaustedAction setting is + * {@link #WHEN_EXHAUSTED_BLOCK}. + *
    • + *
    • + * When {@link #setTestOnBorrow testOnBorrow} is set, the pool will + * attempt to validate each object before it is returned from the + * {@link #borrowObject borrowObject} method. (Using the provided factory's + * {@link KeyedPoolableObjectFactory#validateObject validateObject} method.) + * Objects that fail to validate will be dropped from the pool, and a + * different object will be borrowed. The default setting for this parameter + * is false. + *
    • + *
    • + * When {@link #setTestOnReturn testOnReturn} is set, the pool will + * attempt to validate each object before it is returned to the pool in the + * {@link #returnObject returnObject} method. (Using the provided factory's + * {@link KeyedPoolableObjectFactory#validateObject validateObject} + * method.) Objects that fail to validate will be dropped from the pool. + * The default setting for this parameter is false. + *
    • + *
    + *

    + * Optionally, one may configure the pool to examine and possibly evict objects + * as they sit idle in the pool and to ensure that a minimum number of idle + * objects is maintained for each key. This is performed by an + * "idle object eviction" thread, which runs asynchronously. Caution should be + * used when configuring this optional feature. Eviction runs require an + * exclusive synchronization lock on the pool, so if they run too frequently + * and / or incur excessive latency when creating, destroying or validating + * object instances, performance issues may result. The idle object eviction + * thread may be configured using the following attributes: + *

      + *
    • + * {@link #setTimeBetweenEvictionRunsMillis timeBetweenEvictionRunsMillis} + * indicates how long the eviction thread should sleep before "runs" of examining + * idle objects. When non-positive, no eviction thread will be launched. The + * default setting for this parameter is -1 (i.e., by default, idle object + * eviction is disabled). + *
    • + *
    • + * {@link #setMinEvictableIdleTimeMillis minEvictableIdleTimeMillis} + * specifies the minimum amount of time that an object may sit idle in the + * pool before it is eligible for eviction due to idle time. When + * non-positive, no object will be dropped from the pool due to idle time + * alone. This setting has no effect unless + * timeBetweenEvictionRunsMillis > 0. The default setting + * for this parameter is 30 minutes. + *
    • + *
    • + * {@link #setTestWhileIdle testWhileIdle} indicates whether or not idle + * objects should be validated using the factory's + * {@link KeyedPoolableObjectFactory#validateObject validateObject} method + * during idle object eviction runs. Objects that fail to validate will be + * dropped from the pool. This setting has no effect unless + * timeBetweenEvictionRunsMillis > 0. The default setting + * for this parameter is false. + *
    • + *
    • + * {@link #setMinIdle minIdle} sets a target value for the minimum number of + * idle objects (per key) that should always be available. If this parameter + * is set to a positive number and + * timeBetweenEvictionRunsMillis > 0, each time the idle object + * eviction thread runs, it will try to create enough idle instances so that + * there will be minIdle idle instances available under each + * key. This parameter is also used by {@link #preparePool preparePool} + * if true is provided as that method's + * populateImmediately parameter. The default setting for this + * parameter is 0. + *
    • + *
    + *

    + * The pools can be configured to behave as LIFO queues with respect to idle + * objects - always returning the most recently used object from the pool, + * or as FIFO queues, where borrowObject always returns the oldest object + * in the idle object pool. + *

      + *
    • + * {@link #setLifo Lifo} + * determines whether or not the pools return idle objects in + * last-in-first-out order. The default setting for this parameter is + * true. + *
    • + *
    + *

    + * GenericKeyedObjectPool is not usable without a {@link KeyedPoolableObjectFactory}. A + * non-null factory must be provided either as a constructor argument + * or via a call to {@link #setFactory setFactory} before the pool is used. + *

    + *

    + * Implementation note: To prevent possible deadlocks, care has been taken to + * ensure that no call to a factory method will occur within a synchronization + * block. See POOL-125 and DBCP-44 for more information. + *

    + * @see GenericObjectPool + * @author Rodney Waldhoff + * @author Dirk Verbeeck + * @author Sandy McArthur + * @version $Revision$ $Date$ + * @since Pool 1.0 + */ +public class GenericKeyedObjectPool extends BaseKeyedObjectPool implements KeyedObjectPool { + + //--- public constants ------------------------------------------- + + /** + * A "when exhausted action" type indicating that when the pool is + * exhausted (i.e., the maximum number of active objects has + * been reached), the {@link #borrowObject} + * method should fail, throwing a {@link NoSuchElementException}. + * @see #WHEN_EXHAUSTED_BLOCK + * @see #WHEN_EXHAUSTED_GROW + * @see #setWhenExhaustedAction + */ + public static final byte WHEN_EXHAUSTED_FAIL = 0; + + /** + * A "when exhausted action" type indicating that when the pool + * is exhausted (i.e., the maximum number + * of active objects has been reached), the {@link #borrowObject} + * method should block until a new object is available, or the + * {@link #getMaxWait maximum wait time} has been reached. + * @see #WHEN_EXHAUSTED_FAIL + * @see #WHEN_EXHAUSTED_GROW + * @see #setMaxWait + * @see #getMaxWait + * @see #setWhenExhaustedAction + */ + public static final byte WHEN_EXHAUSTED_BLOCK = 1; + + /** + * A "when exhausted action" type indicating that when the pool is + * exhausted (i.e., the maximum number + * of active objects has been reached), the {@link #borrowObject} + * method should simply create a new object anyway. + * @see #WHEN_EXHAUSTED_FAIL + * @see #WHEN_EXHAUSTED_GROW + * @see #setWhenExhaustedAction + */ + public static final byte WHEN_EXHAUSTED_GROW = 2; + + /** + * The default cap on the number of idle instances (per key) in the pool. + * @see #getMaxIdle + * @see #setMaxIdle + */ + public static final int DEFAULT_MAX_IDLE = 8; + + /** + * The default cap on the total number of active instances (per key) + * from the pool. + * @see #getMaxActive + * @see #setMaxActive + */ + public static final int DEFAULT_MAX_ACTIVE = 8; + + /** + * The default cap on the the overall maximum number of objects that can + * exist at one time. + * @see #getMaxTotal + * @see #setMaxTotal + */ + public static final int DEFAULT_MAX_TOTAL = -1; + + /** + * The default "when exhausted action" for the pool. + * @see #WHEN_EXHAUSTED_BLOCK + * @see #WHEN_EXHAUSTED_FAIL + * @see #WHEN_EXHAUSTED_GROW + * @see #setWhenExhaustedAction + */ + public static final byte DEFAULT_WHEN_EXHAUSTED_ACTION = WHEN_EXHAUSTED_BLOCK; + + /** + * The default maximum amount of time (in milliseconds) the + * {@link #borrowObject} method should block before throwing + * an exception when the pool is exhausted and the + * {@link #getWhenExhaustedAction "when exhausted" action} is + * {@link #WHEN_EXHAUSTED_BLOCK}. + * @see #getMaxWait + * @see #setMaxWait + */ + public static final long DEFAULT_MAX_WAIT = -1L; + + /** + * The default "test on borrow" value. + * @see #getTestOnBorrow + * @see #setTestOnBorrow + */ + public static final boolean DEFAULT_TEST_ON_BORROW = false; + + /** + * The default "test on return" value. + * @see #getTestOnReturn + * @see #setTestOnReturn + */ + public static final boolean DEFAULT_TEST_ON_RETURN = false; + + /** + * The default "test while idle" value. + * @see #getTestWhileIdle + * @see #setTestWhileIdle + * @see #getTimeBetweenEvictionRunsMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + public static final boolean DEFAULT_TEST_WHILE_IDLE = false; + + /** + * The default "time between eviction runs" value. + * @see #getTimeBetweenEvictionRunsMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + public static final long DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS = -1L; + + /** + * The default number of objects to examine per run in the + * idle object evictor. + * @see #getNumTestsPerEvictionRun + * @see #setNumTestsPerEvictionRun + * @see #getTimeBetweenEvictionRunsMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + public static final int DEFAULT_NUM_TESTS_PER_EVICTION_RUN = 3; + + /** + * The default value for {@link #getMinEvictableIdleTimeMillis}. + * @see #getMinEvictableIdleTimeMillis + * @see #setMinEvictableIdleTimeMillis + */ + public static final long DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS = 1000L * 60L * 30L; + + /** + * The default minimum level of idle objects in the pool. + * @since Pool 1.3 + * @see #setMinIdle + * @see #getMinIdle + */ + public static final int DEFAULT_MIN_IDLE = 0; + + /** + * The default LIFO status. True means that borrowObject returns the + * most recently used ("last in") idle object in a pool (if there are + * idle instances available). False means that pools behave as FIFO + * queues - objects are taken from idle object pools in the order that + * they are returned. + * @see #setLifo + */ + public static final boolean DEFAULT_LIFO = true; + + //--- constructors ----------------------------------------------- + + /** + * Create a new GenericKeyedObjectPool with no factory. + * + * @see #GenericKeyedObjectPool(KeyedPoolableObjectFactory) + * @see #setFactory(KeyedPoolableObjectFactory) + */ + public GenericKeyedObjectPool() { + this(null, DEFAULT_MAX_ACTIVE, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE, + DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, + DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy + * objects if not null + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory) { + this(factory, DEFAULT_MAX_ACTIVE, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE, + DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, + DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param config a non-null {@link GenericKeyedObjectPool.Config} describing the configuration + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, GenericKeyedObjectPool.Config config) { + this(factory, config.maxActive, config.whenExhaustedAction, config.maxWait, config.maxIdle, config.maxTotal, + config.minIdle, config.testOnBorrow, config.testOnReturn, config.timeBetweenEvictionRunsMillis, + config.numTestsPerEvictionRun, config.minEvictableIdleTimeMillis, config.testWhileIdle, config.lifo); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive}) + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive) { + this(factory,maxActive, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE, + DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, + DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive}) + * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait) { + this(factory, maxActive, whenExhaustedAction, maxWait, DEFAULT_MAX_IDLE, DEFAULT_TEST_ON_BORROW, + DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN, + DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) + * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) + * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} + * method (see {@link #setTestOnBorrow}) + * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} + * method (see {@link #setTestOnReturn}) + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait, boolean testOnBorrow, boolean testOnReturn) { + this(factory, maxActive, whenExhaustedAction, maxWait, DEFAULT_MAX_IDLE,testOnBorrow,testOnReturn, + DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN, + DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed from me at one time + * (see {@link #setMaxActive}) + * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) + * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait, int maxIdle) { + this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, + DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN, + DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed from me at one time + * (see {@link #setMaxActive}) + * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait}) + * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) + * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} + * method (see {@link #setTestOnBorrow}) + * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} + * method (see {@link #setTestOnReturn}) + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait, int maxIdle, boolean testOnBorrow, boolean testOnReturn) { + this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, testOnBorrow, testOnReturn, + DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN, + DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed from me at one time + * (see {@link #setMaxActive}) + * @param whenExhaustedAction the action to take when the pool is exhausted + * (see {@link #setWhenExhaustedAction}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) + * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) + * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} + * method (see {@link #setTestOnBorrow}) + * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} + * method (see {@link #setTestOnReturn}) + * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle + * objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis}) + * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction + * thread (if any) (see {@link #setNumTestsPerEvictionRun}) + * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before + * it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis}) + * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any + * (see {@link #setTestWhileIdle}) + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait, int maxIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis, + int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle) { + this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, GenericKeyedObjectPool.DEFAULT_MAX_TOTAL, + testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, numTestsPerEvictionRun, + minEvictableIdleTimeMillis, testWhileIdle); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed from me at one time + * (see {@link #setMaxActive}) + * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) + * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) + * @param maxTotal the maximum number of objects that can exists at one time (see {@link #setMaxTotal}) + * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} + * method (see {@link #setTestOnBorrow}) + * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} + * method (see {@link #setTestOnReturn}) + * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle + * objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis}) + * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction + * thread (if any) (see {@link #setNumTestsPerEvictionRun}) + * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool + * before it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis}) + * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any + * (see {@link #setTestWhileIdle}) + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait, int maxIdle, int maxTotal, boolean testOnBorrow, boolean testOnReturn, + long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, + boolean testWhileIdle) { + this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, maxTotal, + GenericKeyedObjectPool.DEFAULT_MIN_IDLE, testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, + numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed at one time (see {@link #setMaxActive}) + * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) + * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) + * @param maxTotal the maximum number of objects that can exists at one time (see {@link #setMaxTotal}) + * @param minIdle the minimum number of idle objects to have in the pool at any one time (see {@link #setMinIdle}) + * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} + * method (see {@link #setTestOnBorrow}) + * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} + * method (see {@link #setTestOnReturn}) + * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle + * objects + * for eviction (see {@link #setTimeBetweenEvictionRunsMillis}) + * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction + * thread (if any) (see {@link #setNumTestsPerEvictionRun}) + * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before + * it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis}) + * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any + * (see {@link #setTestWhileIdle}) + * @since Pool 1.3 + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait, int maxIdle, int maxTotal, int minIdle, boolean testOnBorrow, boolean testOnReturn, + long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, + boolean testWhileIdle) { + this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, maxTotal, minIdle, testOnBorrow, testOnReturn, + timeBetweenEvictionRunsMillis, numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle, + DEFAULT_LIFO); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed at one time + * (see {@link #setMaxActive}) + * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) + * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) + * @param maxTotal the maximum number of objects that can exists at one time (see {@link #setMaxTotal}) + * @param minIdle the minimum number of idle objects to have in the pool at any one time (see {@link #setMinIdle}) + * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} + * method (see {@link #setTestOnBorrow}) + * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} + * method (see {@link #setTestOnReturn}) + * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle + * objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis}) + * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction + * thread (if any) (see {@link #setNumTestsPerEvictionRun}) + * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before + * it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis}) + * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any + * (see {@link #setTestWhileIdle}) + * @param lifo whether or not the pools behave as LIFO (last in first out) queues (see {@link #setLifo}) + * @since Pool 1.4 + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait, int maxIdle, int maxTotal, int minIdle, boolean testOnBorrow, boolean testOnReturn, + long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, + boolean testWhileIdle, boolean lifo) { + _factory = factory; + _maxActive = maxActive; + _lifo = lifo; + switch (whenExhaustedAction) { + case WHEN_EXHAUSTED_BLOCK: + case WHEN_EXHAUSTED_FAIL: + case WHEN_EXHAUSTED_GROW: + _whenExhaustedAction = whenExhaustedAction; + break; + default: + throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized."); + } + _maxWait = maxWait; + _maxIdle = maxIdle; + _maxTotal = maxTotal; + _minIdle = minIdle; + _testOnBorrow = testOnBorrow; + _testOnReturn = testOnReturn; + _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; + _numTestsPerEvictionRun = numTestsPerEvictionRun; + _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; + _testWhileIdle = testWhileIdle; + + _poolMap = new HashMap(); + _poolList = new CursorableLinkedList(); + + startEvictor(_timeBetweenEvictionRunsMillis); + } + + //--- public methods --------------------------------------------- + + //--- configuration methods -------------------------------------- + + /** + * Returns the cap on the number of object instances allocated by the pool + * (checked out or idle), per key. + * A negative value indicates no limit. + * + * @return the cap on the number of active instances per key. + * @see #setMaxActive + */ + public synchronized int getMaxActive() { + return _maxActive; + } + + /** + * Sets the cap on the number of object instances managed by the pool per key. + * @param maxActive The cap on the number of object instances per key. + * Use a negative value for no limit. + * + * @see #getMaxActive + */ + public synchronized void setMaxActive(int maxActive) { + _maxActive = maxActive; + allocate(); + } + + /** + * Returns the overall maximum number of objects (across pools) that can + * exist at one time. A negative value indicates no limit. + * @return the maximum number of instances in circulation at one time. + * @see #setMaxTotal + */ + public synchronized int getMaxTotal() { + return _maxTotal; + } + + /** + * Sets the cap on the total number of instances from all pools combined. + * When maxTotal is set to a + * positive value and {@link #borrowObject borrowObject} is invoked + * when at the limit with no idle instances available, an attempt is made to + * create room by clearing the oldest 15% of the elements from the keyed + * pools. + * + * @param maxTotal The cap on the total number of instances across pools. + * Use a negative value for no limit. + * @see #getMaxTotal + */ + public synchronized void setMaxTotal(int maxTotal) { + _maxTotal = maxTotal; + allocate(); + } + + /** + * Returns the action to take when the {@link #borrowObject} method + * is invoked when the pool is exhausted (the maximum number + * of "active" objects has been reached). + * + * @return one of {@link #WHEN_EXHAUSTED_BLOCK}, + * {@link #WHEN_EXHAUSTED_FAIL} or {@link #WHEN_EXHAUSTED_GROW} + * @see #setWhenExhaustedAction + */ + public synchronized byte getWhenExhaustedAction() { + return _whenExhaustedAction; + } + + /** + * Sets the action to take when the {@link #borrowObject} method + * is invoked when the pool is exhausted (the maximum number + * of "active" objects has been reached). + * + * @param whenExhaustedAction the action code, which must be one of + * {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL}, + * or {@link #WHEN_EXHAUSTED_GROW} + * @see #getWhenExhaustedAction + */ + public synchronized void setWhenExhaustedAction(byte whenExhaustedAction) { + switch(whenExhaustedAction) { + case WHEN_EXHAUSTED_BLOCK: + case WHEN_EXHAUSTED_FAIL: + case WHEN_EXHAUSTED_GROW: + _whenExhaustedAction = whenExhaustedAction; + allocate(); + break; + default: + throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized."); + } + } + + + /** + * Returns the maximum amount of time (in milliseconds) the + * {@link #borrowObject} method should block before throwing + * an exception when the pool is exhausted and the + * {@link #setWhenExhaustedAction "when exhausted" action} is + * {@link #WHEN_EXHAUSTED_BLOCK}. + * + * When less than or equal to 0, the {@link #borrowObject} method + * may block indefinitely. + * + * @return the maximum number of milliseconds borrowObject will block. + * @see #setMaxWait + * @see #setWhenExhaustedAction + * @see #WHEN_EXHAUSTED_BLOCK + */ + public synchronized long getMaxWait() { + return _maxWait; + } + + /** + * Sets the maximum amount of time (in milliseconds) the + * {@link #borrowObject} method should block before throwing + * an exception when the pool is exhausted and the + * {@link #setWhenExhaustedAction "when exhausted" action} is + * {@link #WHEN_EXHAUSTED_BLOCK}. + * + * When less than or equal to 0, the {@link #borrowObject} method + * may block indefinitely. + * + * @param maxWait the maximum number of milliseconds borrowObject will block or negative for indefinitely. + * @see #getMaxWait + * @see #setWhenExhaustedAction + * @see #WHEN_EXHAUSTED_BLOCK + */ + public synchronized void setMaxWait(long maxWait) { + _maxWait = maxWait; + } + + /** + * Returns the cap on the number of "idle" instances per key. + * @return the maximum number of "idle" instances that can be held + * in a given keyed pool. + * @see #setMaxIdle + */ + public synchronized int getMaxIdle() { + return _maxIdle; + } + + /** + * Sets the cap on the number of "idle" instances in the pool. + * If maxIdle is set too low on heavily loaded systems it is possible you + * will see objects being destroyed and almost immediately new objects + * being created. This is a result of the active threads momentarily + * returning objects faster than they are requesting them them, causing the + * number of idle objects to rise above maxIdle. The best value for maxIdle + * for heavily loaded system will vary but the default is a good starting + * point. + * @param maxIdle the maximum number of "idle" instances that can be held + * in a given keyed pool. Use a negative value for no limit. + * @see #getMaxIdle + * @see #DEFAULT_MAX_IDLE + */ + public synchronized void setMaxIdle(int maxIdle) { + _maxIdle = maxIdle; + allocate(); + } + + /** + * Sets the minimum number of idle objects to maintain in each of the keyed + * pools. This setting has no effect unless + * timeBetweenEvictionRunsMillis > 0 and attempts to ensure + * that each pool has the required minimum number of instances are only + * made during idle object eviction runs. + * @param poolSize - The minimum size of the each keyed pool + * @since Pool 1.3 + * @see #getMinIdle + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized void setMinIdle(int poolSize) { + _minIdle = poolSize; + } + + /** + * Returns the minimum number of idle objects to maintain in each of the keyed + * pools. This setting has no effect unless + * timeBetweenEvictionRunsMillis > 0 and attempts to ensure + * that each pool has the required minimum number of instances are only + * made during idle object eviction runs. + * @return minimum size of the each keyed pool + * @since Pool 1.3 + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized int getMinIdle() { + return _minIdle; + } + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * before being returned by the {@link #borrowObject} + * method. If the object fails to validate, + * it will be dropped from the pool, and we will attempt + * to borrow another. + * + * @return true if objects are validated before being borrowed. + * @see #setTestOnBorrow + */ + public boolean getTestOnBorrow() { + return _testOnBorrow; + } + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * before being returned by the {@link #borrowObject} + * method. If the object fails to validate, + * it will be dropped from the pool, and we will attempt + * to borrow another. + * + * @param testOnBorrow whether object should be validated before being returned by borrowObject. + * @see #getTestOnBorrow + */ + public void setTestOnBorrow(boolean testOnBorrow) { + _testOnBorrow = testOnBorrow; + } + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * before being returned to the pool within the + * {@link #returnObject}. + * + * @return true when objects will be validated before being returned. + * @see #setTestOnReturn + */ + public boolean getTestOnReturn() { + return _testOnReturn; + } + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * before being returned to the pool within the + * {@link #returnObject}. + * + * @param testOnReturn true so objects will be validated before being returned. + * @see #getTestOnReturn + */ + public void setTestOnReturn(boolean testOnReturn) { + _testOnReturn = testOnReturn; + } + + /** + * Returns the number of milliseconds to sleep between runs of the + * idle object evictor thread. + * When non-positive, no idle object evictor thread will be + * run. + * + * @return milliseconds to sleep between evictor runs. + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized long getTimeBetweenEvictionRunsMillis() { + return _timeBetweenEvictionRunsMillis; + } + + /** + * Sets the number of milliseconds to sleep between runs of the + * idle object evictor thread. + * When non-positive, no idle object evictor thread will be + * run. + * + * @param timeBetweenEvictionRunsMillis milliseconds to sleep between evictor runs. + * @see #getTimeBetweenEvictionRunsMillis + */ + public synchronized void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) { + _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; + startEvictor(_timeBetweenEvictionRunsMillis); + } + + /** + * Returns the max number of objects to examine during each run of the + * idle object evictor thread (if any). + * + * @return number of objects to examine each eviction run. + * @see #setNumTestsPerEvictionRun + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized int getNumTestsPerEvictionRun() { + return _numTestsPerEvictionRun; + } + + /** + * Sets the max number of objects to examine during each run of the + * idle object evictor thread (if any). + *

    + * When a negative value is supplied, + * ceil({@link #getNumIdle()})/abs({@link #getNumTestsPerEvictionRun}) + * tests will be run. I.e., when the value is -n, roughly one nth of the + * idle objects will be tested per run. When the value is positive, the number of tests + * actually performed in each run will be the minimum of this value and the number of instances + * idle in the pools. + * + * @param numTestsPerEvictionRun number of objects to examine each eviction run. + * @see #setNumTestsPerEvictionRun + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) { + _numTestsPerEvictionRun = numTestsPerEvictionRun; + } + + /** + * Returns the minimum amount of time an object may sit idle in the pool + * before it is eligible for eviction by the idle object evictor + * (if any). + * + * @return minimum amount of time an object may sit idle in the pool before it is eligible for eviction. + * @see #setMinEvictableIdleTimeMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized long getMinEvictableIdleTimeMillis() { + return _minEvictableIdleTimeMillis; + } + + /** + * Sets the minimum amount of time an object may sit idle in the pool + * before it is eligible for eviction by the idle object evictor + * (if any). + * When non-positive, no objects will be evicted from the pool + * due to idle time alone. + * + * @param minEvictableIdleTimeMillis minimum amount of time an object may sit idle in the pool before + * it is eligible for eviction. + * @see #getMinEvictableIdleTimeMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { + _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; + } + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * by the idle object evictor (if any). If an object + * fails to validate, it will be dropped from the pool. + * + * @return true when objects are validated when borrowed. + * @see #setTestWhileIdle + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized boolean getTestWhileIdle() { + return _testWhileIdle; + } + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * by the idle object evictor (if any). If an object + * fails to validate, it will be dropped from the pool. + * + * @param testWhileIdle true so objects are validated when borrowed. + * @see #getTestWhileIdle + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized void setTestWhileIdle(boolean testWhileIdle) { + _testWhileIdle = testWhileIdle; + } + + /** + * Sets the configuration. + * @param conf the new configuration to use. + * @see GenericKeyedObjectPool.Config + */ + public synchronized void setConfig(GenericKeyedObjectPool.Config conf) { + setMaxIdle(conf.maxIdle); + setMaxActive(conf.maxActive); + setMaxTotal(conf.maxTotal); + setMinIdle(conf.minIdle); + setMaxWait(conf.maxWait); + setWhenExhaustedAction(conf.whenExhaustedAction); + setTestOnBorrow(conf.testOnBorrow); + setTestOnReturn(conf.testOnReturn); + setTestWhileIdle(conf.testWhileIdle); + setNumTestsPerEvictionRun(conf.numTestsPerEvictionRun); + setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis); + setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis); + } + + /** + * Whether or not the idle object pools act as LIFO queues. True means + * that borrowObject returns the most recently used ("last in") idle object + * in a pool (if there are idle instances available). False means that + * the pools behave as FIFO queues - objects are taken from idle object + * pools in the order that they are returned. + * + * @return true if the pools are configured to act as LIFO queues + * @since 1.4 + */ + public synchronized boolean getLifo() { + return _lifo; + } + + /** + * Sets the LIFO property of the pools. True means that borrowObject returns + * the most recently used ("last in") idle object in a pool (if there are + * idle instances available). False means that the pools behave as FIFO + * queues - objects are taken from idle object pools in the order that + * they are returned. + * + * @param lifo the new value for the lifo property + * @since 1.4 + */ + public synchronized void setLifo(boolean lifo) { + this._lifo = lifo; + } + + //-- ObjectPool methods ------------------------------------------ + + /** + *

    Borrows an object from the keyed pool associated with the given key.

    + * + *

    If there is an idle instance available in the pool associated with the given key, then + * either the most-recently returned (if {@link #getLifo() lifo} == true) or "oldest" (lifo == false) + * instance sitting idle in the pool will be activated and returned. If activation fails, or + * {@link #getTestOnBorrow() testOnBorrow} is set to true and validation fails, the instance is destroyed and the + * next available instance is examined. This continues until either a valid instance is returned or there + * are no more idle instances available.

    + * + *

    If there are no idle instances available in the pool associated with the given key, behavior + * depends on the {@link #getMaxActive() maxActive}, {@link #getMaxTotal() maxTotal}, and (if applicable) + * {@link #getWhenExhaustedAction() whenExhaustedAction} and {@link #getMaxWait() maxWait} properties. If the + * number of instances checked out from the pool under the given key is less than maxActive and + * the total number of instances in circulation (under all keys) is less than maxTotal, a new instance + * is created, activated and (if applicable) validated and returned to the caller.

    + * + *

    If the associated keyed pool is exhausted (no available idle instances and no capacity to create new ones), + * this method will either block ({@link #WHEN_EXHAUSTED_BLOCK}), throw a NoSuchElementException + * ({@link #WHEN_EXHAUSTED_FAIL}), or grow ({@link #WHEN_EXHAUSTED_GROW} - ignoring maxActive, maxTotal properties). + * The length of time that this method will block when whenExhaustedAction == WHEN_EXHAUSTED_BLOCK + * is determined by the {@link #getMaxWait() maxWait} property.

    + * + *

    When the pool is exhausted, multiple calling threads may be simultaneously blocked waiting for instances + * to become available. As of pool 1.5, a "fairness" algorithm has been implemented to ensure that threads receive + * available instances in request arrival order.

    + * + * @param key pool key + * @return object instance from the keyed pool + * @throws NoSuchElementException if a keyed object instance cannot be returned. + */ + public Object borrowObject(Object key) throws Exception { + long starttime = System.currentTimeMillis(); + Latch latch = new Latch(key); + byte whenExhaustedAction; + long maxWait; + synchronized (this) { + // Get local copy of current config. Can't sync when used later as + // it can result in a deadlock. Has the added advantage that config + // is consistent for entire method execution + whenExhaustedAction = _whenExhaustedAction; + maxWait = _maxWait; + + // Add this request to the queue + _allocationQueue.add(latch); + + // Work the allocation queue, allocating idle instances and + // instance creation permits in request arrival order + allocate(); + } + + for(;;) { + synchronized (this) { + assertOpen(); + } + // If no object was allocated + if (null == latch.getPair()) { + // Check to see if we were allowed to create one + if (latch.mayCreate()) { + // allow new object to be created + } else { + // the pool is exhausted + switch(whenExhaustedAction) { + case WHEN_EXHAUSTED_GROW: + // allow new object to be created + synchronized (this) { + // Make sure another thread didn't allocate us an object + // or permit a new object to be created + if (latch.getPair() == null && !latch.mayCreate()) { + _allocationQueue.remove(latch); + latch.getPool().incrementInternalProcessingCount(); + } + } + break; + case WHEN_EXHAUSTED_FAIL: + synchronized (this) { + // Make sure allocate hasn't already assigned an object + // in a different thread or permitted a new object to be created + if (latch.getPair() != null || latch.mayCreate()) { + break; + } + _allocationQueue.remove(latch); + } + throw new NoSuchElementException("Pool exhausted"); + case WHEN_EXHAUSTED_BLOCK: + try { + synchronized (latch) { + // Before we wait, make sure another thread didn't allocate us an object + // or permit a new object to be created + if (latch.getPair() == null && !latch.mayCreate()) { + if (maxWait <= 0) { + latch.wait(); + } else { + // this code may be executed again after a notify then continue cycle + // so, need to calculate the amount of time to wait + final long elapsed = (System.currentTimeMillis() - starttime); + final long waitTime = maxWait - elapsed; + if (waitTime > 0) + { + latch.wait(waitTime); + } + } + } else { + break; + } + } + } catch(InterruptedException e) { + synchronized (this) { + // Make sure allocate hasn't already assigned an object + // in a different thread or permitted a new object to be created + if (latch.getPair() == null && !latch.mayCreate()) { + _allocationQueue.remove(latch); + } else { + break; + } + } + Thread.currentThread().interrupt(); + throw e; + } + if (maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) { + synchronized (this) { + // Make sure allocate hasn't already assigned an object + // in a different thread or permitted a new object to be created + if (latch.getPair() == null && !latch.mayCreate()) { + _allocationQueue.remove(latch); + } else { + break; + } + } + throw new NoSuchElementException("Timeout waiting for idle object"); + } else { + continue; // keep looping + } + default: + throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + + " not recognized."); + } + } + } + + boolean newlyCreated = false; + if (null == latch.getPair()) { + try { + Object obj = _factory.makeObject(key); + latch.setPair(new ObjectTimestampPair(obj)); + newlyCreated = true; + } finally { + if (!newlyCreated) { + // object cannot be created + synchronized (this) { + latch.getPool().decrementInternalProcessingCount(); + // No need to reset latch - about to throw exception + allocate(); + } + } + } + } + + // activate & validate the object + try { + _factory.activateObject(key, latch.getPair().value); + if (_testOnBorrow && !_factory.validateObject(key, latch.getPair().value)) { + throw new Exception("ValidateObject failed"); + } + synchronized (this) { + latch.getPool().decrementInternalProcessingCount(); + latch.getPool().incrementActiveCount(); + } + return latch.getPair().value; + } catch (Throwable e) { + PoolUtils.checkRethrow(e); + // object cannot be activated or is invalid + try { + _factory.destroyObject(key, latch.getPair().value); + } catch (Throwable e2) { + PoolUtils.checkRethrow(e2); + // cannot destroy broken object + } + synchronized (this) { + latch.getPool().decrementInternalProcessingCount(); + if (!newlyCreated) { + latch.reset(); + _allocationQueue.add(0, latch); + } + allocate(); + } + if (newlyCreated) { + throw new NoSuchElementException( + "Could not create a validated object, cause: " + + e.getMessage()); + } + else { + continue; // keep looping + } + } + } + } + + /** + * Allocate available instances to latches in the allocation queue. Then + * set _mayCreate to true for as many additional latches remaining in queue + * as _maxActive allows for each key. + */ + private void allocate() { + boolean clearOldest = false; + + synchronized (this) { + if (isClosed()) return; + + Iterator allocationQueueIter = _allocationQueue.iterator(); + + while (allocationQueueIter.hasNext()) { + // First use any objects in the pool to clear the queue + Latch latch = (Latch) allocationQueueIter.next(); + ObjectQueue pool = (ObjectQueue)(_poolMap.get(latch.getkey())); + if (null == pool) { + pool = new ObjectQueue(); + _poolMap.put(latch.getkey(), pool); + _poolList.add(latch.getkey()); + } + latch.setPool(pool); + if (!pool.queue.isEmpty()) { + allocationQueueIter.remove(); + latch.setPair( + (ObjectTimestampPair) pool.queue.removeFirst()); + pool.incrementInternalProcessingCount(); + _totalIdle--; + synchronized (latch) { + latch.notify(); + } + // Next item in queue + continue; + } + + // If there is a totalMaxActive and we are at the limit then + // we have to make room + if ((_maxTotal > 0) && + (_totalActive + _totalIdle + _totalInternalProcessing >= _maxTotal)) { + clearOldest = true; + break; + } + + // Second utilise any spare capacity to create new objects + if ((_maxActive < 0 || pool.activeCount + pool.internalProcessingCount < _maxActive) && + (_maxTotal < 0 || _totalActive + _totalIdle + _totalInternalProcessing < _maxTotal)) { + // allow new object to be created + allocationQueueIter.remove(); + latch.setMayCreate(true); + pool.incrementInternalProcessingCount(); + synchronized (latch) { + latch.notify(); + } + // Next item in queue + continue; + } + + // If there is no per-key limit and we reach this point we + // must have allocated all the objects we possibly can and there + // is no point looking at the rest of the allocation queue + if (_maxActive < 0) { + break; + } + } + } + + if (clearOldest) { + /* Clear oldest calls factory methods so it must be called from + * outside the sync block. + * It also needs to be outside the sync block as it calls + * allocate(). If called inside the sync block, the call to + * allocate() would be able to enter the sync block (since the + * thread already has the lock) which may have unexpected, + * unpleasant results. + */ + clearOldest(); + } + } + + /** + * Clears any objects sitting idle in the pool by removing them from the + * idle instance pool and then invoking the configured + * {@link KeyedPoolableObjectFactory#destroyObject(Object, Object)} method on + * each idle instance. + * + *

    Implementation notes: + *

    • This method does not destroy or effect in any way instances that are + * checked out when it is invoked.
    • + *
    • Invoking this method does not prevent objects being + * returned to the idle instance pool, even during its execution. It locks + * the pool only during instance removal. Additional instances may be returned + * while removed items are being destroyed.

    + */ + public void clear() { + Map toDestroy = new HashMap(); + synchronized (this) { + for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) { + Object key = it.next(); + ObjectQueue pool = (ObjectQueue)_poolMap.get(key); + // Copy objects to new list so pool.queue can be cleared inside + // the sync + List objects = new ArrayList(); + objects.addAll(pool.queue); + toDestroy.put(key, objects); + it.remove(); + _poolList.remove(key); + _totalIdle = _totalIdle - pool.queue.size(); + _totalInternalProcessing = + _totalInternalProcessing + pool.queue.size(); + pool.queue.clear(); + } + } + destroy(toDestroy, _factory); + } + + /** + * Clears oldest 15% of objects in pool. The method sorts the + * objects into a TreeMap and then iterates the first 15% for removal. + * + * @since Pool 1.3 + */ + public void clearOldest() { + // Map of objects to destroy my key + final Map toDestroy = new HashMap(); + + // build sorted map of idle objects + final Map map = new TreeMap(); + synchronized (this) { + for (Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext();) { + final Object key = keyiter.next(); + final CursorableLinkedList list = ((ObjectQueue)_poolMap.get(key)).queue; + for (Iterator it = list.iterator(); it.hasNext();) { + // each item into the map uses the objectimestamppair object + // as the key. It then gets sorted based on the timstamp field + // each value in the map is the parent list it belongs in. + map.put(it.next(), key); + } + } + + // Now iterate created map and kill the first 15% plus one to account for zero + Set setPairKeys = map.entrySet(); + int itemsToRemove = ((int) (map.size() * 0.15)) + 1; + + Iterator iter = setPairKeys.iterator(); + while (iter.hasNext() && itemsToRemove > 0) { + Map.Entry entry = (Map.Entry) iter.next(); + // kind of backwards on naming. In the map, each key is the objecttimestamppair + // because it has the ordering with the timestamp value. Each value that the + // key references is the key of the list it belongs to. + Object key = entry.getValue(); + ObjectTimestampPair pairTimeStamp = (ObjectTimestampPair) entry.getKey(); + final CursorableLinkedList list = + ((ObjectQueue)(_poolMap.get(key))).queue; + list.remove(pairTimeStamp); + + if (toDestroy.containsKey(key)) { + ((List)toDestroy.get(key)).add(pairTimeStamp); + } else { + List listForKey = new ArrayList(); + listForKey.add(pairTimeStamp); + toDestroy.put(key, listForKey); + } + // if that was the last object for that key, drop that pool + if (list.isEmpty()) { + _poolMap.remove(key); + _poolList.remove(key); + } + _totalIdle--; + _totalInternalProcessing++; + itemsToRemove--; + } + + } + destroy(toDestroy, _factory); + } + + /** + * Clears the specified pool, removing all pooled instances corresponding to the given key. + * + * @param key the key to clear + */ + public void clear(Object key) { + Map toDestroy = new HashMap(); + + final ObjectQueue pool; + synchronized (this) { + pool = (ObjectQueue)(_poolMap.remove(key)); + if (pool == null) { + return; + } else { + _poolList.remove(key); + } + // Copy objects to new list so pool.queue can be cleared inside + // the sync + List objects = new ArrayList(); + objects.addAll(pool.queue); + toDestroy.put(key, objects); + _totalIdle = _totalIdle - pool.queue.size(); + _totalInternalProcessing = + _totalInternalProcessing + pool.queue.size(); + pool.queue.clear(); + } + destroy(toDestroy, _factory); + } + + /** + * Assuming Map>, destroy all + * ObjectTimestampPair.value using the supplied factory. + * + * @param m Map containing keyed pools to clear + * @param factory KeyedPoolableObjectFactory used to destroy the objects + */ + private void destroy(Map m, KeyedPoolableObjectFactory factory) { + for (Iterator keys = m.keySet().iterator(); keys.hasNext();) { + Object key = keys.next(); + Collection c = (Collection) m.get(key); + for (Iterator it = c.iterator(); it.hasNext();) { + try { + factory.destroyObject( + key,((ObjectTimestampPair)(it.next())).value); + } catch(Exception e) { + // ignore error, keep destroying the rest + } finally { + synchronized(this) { + _totalInternalProcessing--; + allocate(); + } + } + } + + } + } + + /** + * Returns the total number of instances current borrowed from this pool but not yet returned. + * + * @return the total number of instances currently borrowed from this pool + */ + public synchronized int getNumActive() { + return _totalActive; + } + + /** + * Returns the total number of instances currently idle in this pool. + * + * @return the total number of instances currently idle in this pool + */ + public synchronized int getNumIdle() { + return _totalIdle; + } + + /** + * Returns the number of instances currently borrowed from but not yet returned + * to the pool corresponding to the given key. + * + * @param key the key to query + * @return the number of instances corresponding to the given key currently borrowed in this pool + */ + public synchronized int getNumActive(Object key) { + final ObjectQueue pool = (ObjectQueue)(_poolMap.get(key)); + return pool != null ? pool.activeCount : 0; + } + + /** + * Returns the number of instances corresponding to the given key currently idle in this pool. + * + * @param key the key to query + * @return the number of instances corresponding to the given key currently idle in this pool + */ + public synchronized int getNumIdle(Object key) { + final ObjectQueue pool = (ObjectQueue)(_poolMap.get(key)); + return pool != null ? pool.queue.size() : 0; + } + + /** + *

    Returns an object to a keyed pool.

    + * + *

    For the pool to function correctly, the object instance must have been borrowed + * from the pool (under the same key) and not yet returned. Repeated returnObject calls on + * the same object/key pair (with no borrowObject calls in between) will result in multiple + * references to the object in the idle instance pool.

    + * + *

    If {@link #getMaxIdle() maxIdle} is set to a positive value and the number of idle instances under the given + * key has reached this value, the returning instance is destroyed.

    + * + *

    If {@link #getTestOnReturn() testOnReturn} == true, the returning instance is validated before being returned + * to the idle instance pool under the given key. In this case, if validation fails, the instance is destroyed.

    + * + * @param key pool key + * @param obj instance to return to the keyed pool + * @throws Exception + */ + public void returnObject(Object key, Object obj) throws Exception { + try { + addObjectToPool(key, obj, true); + } catch (Exception e) { + if (_factory != null) { + try { + _factory.destroyObject(key, obj); + } catch (Exception e2) { + // swallowed + } + // TODO: Correctness here depends on control in addObjectToPool. + // These two methods should be refactored, removing the + // "behavior flag", decrementNumActive, from addObjectToPool. + ObjectQueue pool = (ObjectQueue) (_poolMap.get(key)); + if (pool != null) { + synchronized(this) { + pool.decrementActiveCount(); + allocate(); + } + } + } + } + } + + /** + *

    Adds an object to the keyed pool.

    + * + *

    Validates the object if testOnReturn == true and passivates it before returning it to the pool. + * if validation or passivation fails, or maxIdle is set and there is no room in the pool, the instance + * is destroyed.

    + * + *

    Calls {@link #allocate()} on successful completion

    + * + * @param key pool key + * @param obj instance to add to the keyed pool + * @param decrementNumActive whether or not to decrement the active count associated with the keyed pool + * @throws Exception + */ + private void addObjectToPool(Object key, Object obj, + boolean decrementNumActive) throws Exception { + + // if we need to validate this object, do so + boolean success = true; // whether or not this object passed validation + if (_testOnReturn && !_factory.validateObject(key, obj)) { + success = false; + } else { + _factory.passivateObject(key, obj); + } + + boolean shouldDestroy = !success; + ObjectQueue pool; + + // Add instance to pool if there is room and it has passed validation + // (if testOnreturn is set) + synchronized (this) { + // grab the pool (list) of objects associated with the given key + pool = (ObjectQueue) (_poolMap.get(key)); + // if it doesn't exist, create it + if (null == pool) { + pool = new ObjectQueue(); + _poolMap.put(key, pool); + _poolList.add(key); + } + if (isClosed()) { + shouldDestroy = true; + } else { + // if there's no space in the pool, flag the object for destruction + // else if we passivated successfully, return it to the pool + if (_maxIdle >= 0 && (pool.queue.size() >= _maxIdle)) { + shouldDestroy = true; + } else if (success) { + // borrowObject always takes the first element from the queue, + // so for LIFO, push on top, FIFO add to end + if (_lifo) { + pool.queue.addFirst(new ObjectTimestampPair(obj)); + } else { + pool.queue.addLast(new ObjectTimestampPair(obj)); + } + _totalIdle++; + if (decrementNumActive) { + pool.decrementActiveCount(); + } + allocate(); + } + } + } + + // Destroy the instance if necessary + if (shouldDestroy) { + try { + _factory.destroyObject(key, obj); + } catch(Exception e) { + // ignored? + } + // Decrement active count *after* destroy if applicable + if (decrementNumActive) { + synchronized(this) { + pool.decrementActiveCount(); + allocate(); + } + } + } + } + + /** + *

    Invalidates the object instance associated with the given key. Decrements the active count + * associated with the given keyed pool and destroys the instance.

    + * + * @param key pool key + * @param obj instance to invalidate + * @throws Exception if an exception occurs destroying the object + */ + public void invalidateObject(Object key, Object obj) throws Exception { + try { + _factory.destroyObject(key, obj); + } finally { + synchronized (this) { + ObjectQueue pool = (ObjectQueue) (_poolMap.get(key)); + if (null == pool) { + pool = new ObjectQueue(); + _poolMap.put(key, pool); + _poolList.add(key); + } + pool.decrementActiveCount(); + allocate(); // _totalActive has changed + } + } + } + + /** + * Create an object using the {@link KeyedPoolableObjectFactory#makeObject factory}, + * passivate it, and then place it in the idle object pool. + * addObject is useful for "pre-loading" a pool with idle objects. + * + * @param key the key a new instance should be added to + * @throws Exception when {@link KeyedPoolableObjectFactory#makeObject} fails. + * @throws IllegalStateException when no {@link #setFactory factory} has been set or after {@link #close} has been + * called on this pool. + */ + public void addObject(Object key) throws Exception { + assertOpen(); + if (_factory == null) { + throw new IllegalStateException("Cannot add objects without a factory."); + } + Object obj = _factory.makeObject(key); + try { + assertOpen(); + addObjectToPool(key, obj, false); + } catch (IllegalStateException ex) { // Pool closed + try { + _factory.destroyObject(key, obj); + } catch (Exception ex2) { + // swallow + } + throw ex; + } + } + + /** + * Registers a key for pool control. + * + * If populateImmediately is true and + * minIdle > 0, the pool under the given key will be + * populated immediately with minIdle idle instances. + * + * @param key - The key to register for pool control. + * @param populateImmediately - If this is true, the pool + * will be populated immediately. + * @since Pool 1.3 + */ + public synchronized void preparePool(Object key, boolean populateImmediately) { + ObjectQueue pool = (ObjectQueue)(_poolMap.get(key)); + if (null == pool) { + pool = new ObjectQueue(); + _poolMap.put(key,pool); + _poolList.add(key); + } + + if (populateImmediately) { + try { + // Create the pooled objects + ensureMinIdle(key); + } + catch (Exception e) { + //Do nothing + } + } + } + + /** + *

    Closes the keyed object pool. Once the pool is closed, {@link #borrowObject(Object)} + * will fail with IllegalStateException, but {@link #returnObject(Object, Object)} and + * {@link #invalidateObject(Object, Object)} will continue to work, with returned objects + * destroyed on return.

    + * + *

    Destroys idle instances in the pool by invoking {@link #clear()}.

    + * + * @throws Exception + */ + public void close() throws Exception { + super.close(); + synchronized (this) { + clear(); + if (null != _evictionCursor) { + _evictionCursor.close(); + _evictionCursor = null; + } + if (null != _evictionKeyCursor) { + _evictionKeyCursor.close(); + _evictionKeyCursor = null; + } + startEvictor(-1L); + } + } + + /** + *

    Sets the keyed poolable object factory associated with this pool.

    + * + *

    If this method is called when objects are checked out of any of the keyed pools, + * an IllegalStateException is thrown. Calling this method also has the side effect of + * destroying any idle instances in existing keyed pools, using the original factory.

    + * + * @param factory KeyedPoolableObjectFactory to use when creating keyed object pool instances + * @throws IllegalStateException if there are active (checked out) instances associated with this keyed object pool + * @deprecated to be removed in version 2.0 + */ + public void setFactory(KeyedPoolableObjectFactory factory) throws IllegalStateException { + Map toDestroy = new HashMap(); + final KeyedPoolableObjectFactory oldFactory = _factory; + synchronized (this) { + assertOpen(); + if (0 < getNumActive()) { + throw new IllegalStateException("Objects are already active"); + } else { + for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) { + Object key = it.next(); + ObjectQueue pool = (ObjectQueue)_poolMap.get(key); + if (pool != null) { + // Copy objects to new list so pool.queue can be cleared + // inside the sync + List objects = new ArrayList(); + objects.addAll(pool.queue); + toDestroy.put(key, objects); + it.remove(); + _poolList.remove(key); + _totalIdle = _totalIdle - pool.queue.size(); + _totalInternalProcessing = + _totalInternalProcessing + pool.queue.size(); + pool.queue.clear(); + } + } + _factory = factory; + } + } + destroy(toDestroy, oldFactory); + } + + /** + *

    Perform numTests idle object eviction tests, evicting + * examined objects that meet the criteria for eviction. If + * testWhileIdle is true, examined objects are validated + * when visited (and removed if invalid); otherwise only objects that + * have been idle for more than minEvicableIdletimeMillis + * are removed.

    + * + *

    Successive activations of this method examine objects in keyed pools + * in sequence, cycling through the keys and examining objects in + * oldest-to-youngest order within the keyed pools.

    + * + * @throws Exception when there is a problem evicting idle objects. + */ + public void evict() throws Exception { + Object key = null; + boolean testWhileIdle; + long minEvictableIdleTimeMillis; + + synchronized (this) { + // Get local copy of current config. Can't sync when used later as + // it can result in a deadlock. Has the added advantage that config + // is consistent for entire method execution + testWhileIdle = _testWhileIdle; + minEvictableIdleTimeMillis = _minEvictableIdleTimeMillis; + + // Initialize key to last key value + if (_evictionKeyCursor != null && + _evictionKeyCursor._lastReturned != null) { + key = _evictionKeyCursor._lastReturned.value(); + } + } + + for (int i=0, m=getNumTests(); i 0) && + (System.currentTimeMillis() - pair.tstamp > + minEvictableIdleTimeMillis)) { + removeObject=true; + } + if (testWhileIdle && removeObject == false) { + boolean active = false; + try { + _factory.activateObject(key,pair.value); + active = true; + } catch(Exception e) { + removeObject=true; + } + if (active) { + if (!_factory.validateObject(key,pair.value)) { + removeObject=true; + } else { + try { + _factory.passivateObject(key,pair.value); + } catch(Exception e) { + removeObject=true; + } + } + } + } + + if (removeObject) { + try { + _factory.destroyObject(key, pair.value); + } catch(Exception e) { + // ignored + } finally { + // Do not remove the key from the _poolList or _poolmap, + // even if the list stored in the _poolMap for this key is + // empty when minIdle > 0. + // + // Otherwise if it was the last object for that key, + // drop that pool + if (_minIdle == 0) { + synchronized (this) { + ObjectQueue objectQueue = + (ObjectQueue)_poolMap.get(key); + if (objectQueue != null && + objectQueue.queue.isEmpty()) { + _poolMap.remove(key); + _poolList.remove(key); + } + } + } + } + } + synchronized (this) { + if (!removeObject) { + _evictionCursor.add(pair); + _totalIdle++; + if (_lifo) { + // Skip over the element we just added back + _evictionCursor.previous(); + } + } + _totalInternalProcessing--; + } + } + } + + /** + * Resets the eviction key cursor and closes any + * associated eviction object cursor + */ + private void resetEvictionKeyCursor() { + if (_evictionKeyCursor != null) { + _evictionKeyCursor.close(); + } + _evictionKeyCursor = _poolList.cursor(); + if (null != _evictionCursor) { + _evictionCursor.close(); + _evictionCursor = null; + } + } + + /** + * Resets the eviction object cursor for the given key + * + * @param key eviction key + */ + private void resetEvictionObjectCursor(Object key) { + if (_evictionCursor != null) { + _evictionCursor.close(); + } + if (_poolMap == null) { + return; + } + ObjectQueue pool = (ObjectQueue) (_poolMap.get(key)); + if (pool != null) { + CursorableLinkedList queue = pool.queue; + _evictionCursor = queue.cursor(_lifo ? queue.size() : 0); + } + } + + /** + * Iterates through all the known keys and creates any necessary objects to maintain + * the minimum level of pooled objects. + * @see #getMinIdle + * @see #setMinIdle + * @throws Exception If there was an error whilst creating the pooled objects. + */ + private void ensureMinIdle() throws Exception { + //Check if should sustain the pool + if (_minIdle > 0) { + Object[] keysCopy; + synchronized(this) { + // Get the current set of keys + keysCopy = _poolMap.keySet().toArray(); + } + + // Loop through all elements in _poolList + // Find out the total number of max active and max idle for that class + // If the number is less than the minIdle, do creation loop to boost numbers + for (int i=0; i < keysCopy.length; i++) { + //Get the next key to process + ensureMinIdle(keysCopy[i]); + } + } + } + + /** + * Re-creates any needed objects to maintain the minimum levels of + * pooled objects for the specified key. + * + * This method uses {@link #calculateDeficit} to calculate the number + * of objects to be created. {@link #calculateDeficit} can be overridden to + * provide a different method of calculating the number of objects to be + * created. + * @param key The key to process + * @throws Exception If there was an error whilst creating the pooled objects + */ + private void ensureMinIdle(Object key) throws Exception { + // Calculate current pool objects + ObjectQueue pool; + synchronized(this) { + pool = (ObjectQueue)(_poolMap.get(key)); + } + if (pool == null) { + return; + } + + // this method isn't synchronized so the + // calculateDeficit is done at the beginning + // as a loop limit and a second time inside the loop + // to stop when another thread already returned the + // needed objects + int objectDeficit = calculateDeficit(pool, false); + + for (int i = 0; i < objectDeficit && calculateDeficit(pool, true) > 0; i++) { + try { + addObject(key); + } finally { + synchronized (this) { + pool.decrementInternalProcessingCount(); + allocate(); + } + } + } + } + + //--- non-public methods ---------------------------------------- + + /** + * Start the eviction thread or service, or when + * delay is non-positive, stop it + * if it is already running. + * + * @param delay milliseconds between evictor runs. + */ + protected synchronized void startEvictor(long delay) { + if (null != _evictor) { + EvictionTimer.cancel(_evictor); + _evictor = null; + } + if (delay > 0) { + _evictor = new Evictor(); + EvictionTimer.schedule(_evictor, delay, delay); + } + } + + /** + * Returns pool info including {@link #getNumActive()}, {@link #getNumIdle()} + * and currently defined keys. + * + * @return string containing debug information + */ + synchronized String debugInfo() { + StringBuffer buf = new StringBuffer(); + buf.append("Active: ").append(getNumActive()).append("\n"); + buf.append("Idle: ").append(getNumIdle()).append("\n"); + Iterator it = _poolMap.keySet().iterator(); + while (it.hasNext()) { + Object key = it.next(); + buf.append("\t").append(key).append(" ").append(_poolMap.get(key)).append("\n"); + } + return buf.toString(); + } + + /** + * Returns the number of tests to be performed in an Evictor run, + * based on the current values of _numTestsPerEvictionRun + * and _totalIdle. + * + * @see #setNumTestsPerEvictionRun + * @return the number of tests for the Evictor to run + */ + private synchronized int getNumTests() { + if (_numTestsPerEvictionRun >= 0) { + return Math.min(_numTestsPerEvictionRun, _totalIdle); + } else { + return(int)(Math.ceil(_totalIdle/Math.abs((double)_numTestsPerEvictionRun))); + } + } + + /** + * This returns the number of objects to create during the pool + * sustain cycle. This will ensure that the minimum number of idle + * instances is maintained without going past the maxActive value. + * + * @param pool the ObjectPool to calculate the deficit for + * @param incrementInternal - Should the count of objects currently under + * some form of internal processing be + * incremented? + * @return The number of objects to be created + */ + private synchronized int calculateDeficit(ObjectQueue pool, + boolean incrementInternal) { + int objectDefecit = 0; + + //Calculate no of objects needed to be created, in order to have + //the number of pooled objects < maxActive(); + objectDefecit = getMinIdle() - pool.queue.size(); + if (getMaxActive() > 0) { + int growLimit = Math.max(0, getMaxActive() - pool.activeCount - pool.queue.size() - pool.internalProcessingCount); + objectDefecit = Math.min(objectDefecit, growLimit); + } + + // Take the maxTotal limit into account + if (getMaxTotal() > 0) { + int growLimit = Math.max(0, getMaxTotal() - getNumActive() - getNumIdle() - _totalInternalProcessing); + objectDefecit = Math.min(objectDefecit, growLimit); + } + + if (incrementInternal && objectDefecit > 0) { + pool.incrementInternalProcessingCount(); + } + return objectDefecit; + } + + //--- inner classes ---------------------------------------------- + + /** + * A "struct" that keeps additional information about the actual queue of pooled objects. + */ + private class ObjectQueue { + /** Number of instances checked out to clients from this queue */ + private int activeCount = 0; + + /** Idle instance queue */ + private final CursorableLinkedList queue = new CursorableLinkedList(); + + /** Number of instances in process of being created */ + private int internalProcessingCount = 0; + + /** Increment the active count for this queue */ + void incrementActiveCount() { + synchronized (GenericKeyedObjectPool.this) { + _totalActive++; + } + activeCount++; + } + + /** Decrement the active count for this queue */ + void decrementActiveCount() { + synchronized (GenericKeyedObjectPool.this) { + _totalActive--; + } + if (activeCount > 0) { + activeCount--; + } + } + + /** Record the fact that one more instance is queued for creation */ + void incrementInternalProcessingCount() { + synchronized (GenericKeyedObjectPool.this) { + _totalInternalProcessing++; + } + internalProcessingCount++; + } + + /** Decrement the number of instances in process of being created */ + void decrementInternalProcessingCount() { + synchronized (GenericKeyedObjectPool.this) { + _totalInternalProcessing--; + } + internalProcessingCount--; + } + } + + /** + * A simple "struct" encapsulating an object instance and a timestamp. + * + * Implements Comparable, objects are sorted from old to new. + * + * This is also used by {@link GenericObjectPool}. + */ + static class ObjectTimestampPair implements Comparable { + //CHECKSTYLE: stop VisibilityModifier + /** + * Object instance + * @deprecated this field will be made private and final in version 2.0 + */ + Object value; + + /** + * timestamp + * @deprecated this field will be made private and final in version 2.0 + */ + long tstamp; + //CHECKSTYLE: resume VisibilityModifier + + /** + * Create a new ObjectTimestampPair using the given object and the current system time. + * @param val object instance + */ + ObjectTimestampPair(Object val) { + this(val, System.currentTimeMillis()); + } + + /** + * Create a new ObjectTimeStampPair using the given object and timestamp value. + * @param val object instance + * @param time long representation of timestamp + */ + ObjectTimestampPair(Object val, long time) { + value = val; + tstamp = time; + } + + /** + * Returns a string representation. + * + * @return String representing this ObjectTimestampPair + */ + public String toString() { + return value + ";" + tstamp; + } + + /** + * Compares this to another object by casting the argument to an + * ObjectTimestampPair. + * + * @param obj object to cmpare + * @return result of comparison + */ + public int compareTo(Object obj) { + return compareTo((ObjectTimestampPair) obj); + } + + /** + * Compares this to another ObjectTimestampPair, using the timestamp as basis for comparison. + * Implementation is consistent with equals. + * + * @param other object to compare + * @return result of comparison + */ + public int compareTo(ObjectTimestampPair other) { + final long tstampdiff = this.tstamp - other.tstamp; + if (tstampdiff == 0) { + // make sure the natural ordering is consistent with equals + // see java.lang.Comparable Javadocs + return System.identityHashCode(this) - System.identityHashCode(other); + } else { + // handle int overflow + return (int)Math.min(Math.max(tstampdiff, Integer.MIN_VALUE), Integer.MAX_VALUE); + } + } + } + + /** + * The idle object evictor {@link TimerTask}. + * @see GenericKeyedObjectPool#setTimeBetweenEvictionRunsMillis + */ + private class Evictor extends TimerTask { + /** + * Run pool maintenance. Evict objects qualifying for eviction and then + * invoke {@link GenericKeyedObjectPool#ensureMinIdle()}. + */ + public void run() { + //Evict from the pool + try { + evict(); + } catch(Exception e) { + // ignored + } catch(OutOfMemoryError oome) { + // Log problem but give evictor thread a chance to continue in + // case error is recoverable + oome.printStackTrace(System.err); + } + //Re-create idle instances. + try { + ensureMinIdle(); + } catch (Exception e) { + // ignored + } + } + } + + /** + * A simple "struct" encapsulating the + * configuration information for a GenericKeyedObjectPool. + * @see GenericKeyedObjectPool#GenericKeyedObjectPool(KeyedPoolableObjectFactory,GenericKeyedObjectPool.Config) + * @see GenericKeyedObjectPool#setConfig + */ + public static class Config { + //CHECKSTYLE: stop VisibilityModifier + /** + * @see GenericKeyedObjectPool#setMaxIdle + */ + public int maxIdle = GenericKeyedObjectPool.DEFAULT_MAX_IDLE; + /** + * @see GenericKeyedObjectPool#setMaxActive + */ + public int maxActive = GenericKeyedObjectPool.DEFAULT_MAX_ACTIVE; + /** + * @see GenericKeyedObjectPool#setMaxTotal + */ + public int maxTotal = GenericKeyedObjectPool.DEFAULT_MAX_TOTAL; + /** + * @see GenericKeyedObjectPool#setMinIdle + */ + public int minIdle = GenericKeyedObjectPool.DEFAULT_MIN_IDLE; + /** + * @see GenericKeyedObjectPool#setMaxWait + */ + public long maxWait = GenericKeyedObjectPool.DEFAULT_MAX_WAIT; + /** + * @see GenericKeyedObjectPool#setWhenExhaustedAction + */ + public byte whenExhaustedAction = GenericKeyedObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION; + /** + * @see GenericKeyedObjectPool#setTestOnBorrow + */ + public boolean testOnBorrow = GenericKeyedObjectPool.DEFAULT_TEST_ON_BORROW; + /** + * @see GenericKeyedObjectPool#setTestOnReturn + */ + public boolean testOnReturn = GenericKeyedObjectPool.DEFAULT_TEST_ON_RETURN; + /** + * @see GenericKeyedObjectPool#setTestWhileIdle + */ + public boolean testWhileIdle = GenericKeyedObjectPool.DEFAULT_TEST_WHILE_IDLE; + /** + * @see GenericKeyedObjectPool#setTimeBetweenEvictionRunsMillis + */ + public long timeBetweenEvictionRunsMillis = GenericKeyedObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS; + /** + * @see GenericKeyedObjectPool#setNumTestsPerEvictionRun + */ + public int numTestsPerEvictionRun = GenericKeyedObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN; + /** + * @see GenericKeyedObjectPool#setMinEvictableIdleTimeMillis + */ + public long minEvictableIdleTimeMillis = GenericKeyedObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS; + /** + * @see GenericKeyedObjectPool#setLifo + */ + public boolean lifo = GenericKeyedObjectPool.DEFAULT_LIFO; + //CHECKSTYLE: resume VisibilityModifier + } + + /** + * Latch used to control allocation order of objects to threads to ensure + * fairness. That is, for each key, objects are allocated to threads in the order + * that threads request objects. + * + * @since 1.5 + */ + private static final class Latch { + + /** key of associated pool */ + private final Object _key; + + /** keyed pool associated with this latch */ + private ObjectQueue _pool; + + /** holds an ObjectTimestampPair when this latch has been allocated an instance */ + private ObjectTimestampPair _pair; + + /** indicates that this latch can create an instance */ + private boolean _mayCreate = false; + + /** + * Create a latch with the given key + * @param key key of the pool associated with this latch + */ + private Latch(Object key) { + _key = key; + } + + /** + * Retuns the key of the associated pool + * @return associated pool key + */ + private synchronized Object getkey() { + return _key; + } + + /** + * Returns the pool associated with this latch + * @return pool + */ + private synchronized ObjectQueue getPool() { + return _pool; + } + + /** + * Sets the pool associated with this latch + * @param pool the pool + */ + private synchronized void setPool(ObjectQueue pool) { + _pool = pool; + } + + /** + * Gets the ObjectTimestampPair allocated to this latch. + * Returns null if this latch does not have an instance allocated to it. + * @return the associated ObjectTimestampPair + */ + private synchronized ObjectTimestampPair getPair() { + return _pair; + } + + /** + * Allocate an ObjectTimestampPair to this latch. + * @param pair ObjectTimestampPair on this latch + */ + private synchronized void setPair(ObjectTimestampPair pair) { + _pair = pair; + } + + /** + * Whether or not this latch can create an instance + * @return true if this latch has an instance creation permit + */ + private synchronized boolean mayCreate() { + return _mayCreate; + } + + /** + * Sets the mayCreate property + * + * @param mayCreate true means this latch can create an instance + */ + private synchronized void setMayCreate(boolean mayCreate) { + _mayCreate = mayCreate; + } + + /** + * Reset the latch data. Used when an allocation fails and the latch + * needs to be re-added to the queue. + */ + private synchronized void reset() { + _pair = null; + _mayCreate = false; + } + } + + //--- protected attributes --------------------------------------- + + /** + * The cap on the number of idle instances in the pool. + * @see #setMaxIdle + * @see #getMaxIdle + */ + private int _maxIdle = DEFAULT_MAX_IDLE; + + /** + * The minimum no of idle objects to keep in the pool. + * @see #setMinIdle + * @see #getMinIdle + */ + private int _minIdle = DEFAULT_MIN_IDLE; + + /** + * The cap on the number of active instances from the pool. + * @see #setMaxActive + * @see #getMaxActive + */ + private int _maxActive = DEFAULT_MAX_ACTIVE; + + /** + * The cap on the total number of instances from the pool if non-positive. + * @see #setMaxTotal + * @see #getMaxTotal + */ + private int _maxTotal = DEFAULT_MAX_TOTAL; + + /** + * The maximum amount of time (in millis) the + * {@link #borrowObject} method should block before throwing + * an exception when the pool is exhausted and the + * {@link #getWhenExhaustedAction "when exhausted" action} is + * {@link #WHEN_EXHAUSTED_BLOCK}. + * + * When less than or equal to 0, the {@link #borrowObject} method + * may block indefinitely. + * + * @see #setMaxWait + * @see #getMaxWait + * @see #WHEN_EXHAUSTED_BLOCK + * @see #setWhenExhaustedAction + * @see #getWhenExhaustedAction + */ + private long _maxWait = DEFAULT_MAX_WAIT; + + /** + * The action to take when the {@link #borrowObject} method + * is invoked when the pool is exhausted (the maximum number + * of "active" objects has been reached). + * + * @see #WHEN_EXHAUSTED_BLOCK + * @see #WHEN_EXHAUSTED_FAIL + * @see #WHEN_EXHAUSTED_GROW + * @see #DEFAULT_WHEN_EXHAUSTED_ACTION + * @see #setWhenExhaustedAction + * @see #getWhenExhaustedAction + */ + private byte _whenExhaustedAction = DEFAULT_WHEN_EXHAUSTED_ACTION; + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * before being returned by the {@link #borrowObject} + * method. If the object fails to validate, + * it will be dropped from the pool, and we will attempt + * to borrow another. + * + * @see #setTestOnBorrow + * @see #getTestOnBorrow + */ + private volatile boolean _testOnBorrow = DEFAULT_TEST_ON_BORROW; + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * before being returned to the pool within the + * {@link #returnObject}. + * + * @see #getTestOnReturn + * @see #setTestOnReturn + */ + private volatile boolean _testOnReturn = DEFAULT_TEST_ON_RETURN; + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * by the idle object evictor (if any). If an object + * fails to validate, it will be dropped from the pool. + * + * @see #setTestWhileIdle + * @see #getTestWhileIdle + * @see #getTimeBetweenEvictionRunsMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + private boolean _testWhileIdle = DEFAULT_TEST_WHILE_IDLE; + + /** + * The number of milliseconds to sleep between runs of the + * idle object evictor thread. + * When non-positive, no idle object evictor thread will be + * run. + * + * @see #setTimeBetweenEvictionRunsMillis + * @see #getTimeBetweenEvictionRunsMillis + */ + private long _timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS; + + /** + * The number of objects to examine during each run of the + * idle object evictor thread (if any). + *

    + * When a negative value is supplied, ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun}) + * tests will be run. I.e., when the value is -n, roughly one nth of the + * idle objects will be tested per run. + * + * @see #setNumTestsPerEvictionRun + * @see #getNumTestsPerEvictionRun + * @see #getTimeBetweenEvictionRunsMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + private int _numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN; + + /** + * The minimum amount of time an object may sit idle in the pool + * before it is eligible for eviction by the idle object evictor + * (if any). + * When non-positive, no objects will be evicted from the pool + * due to idle time alone. + * + * @see #setMinEvictableIdleTimeMillis + * @see #getMinEvictableIdleTimeMillis + * @see #getTimeBetweenEvictionRunsMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + private long _minEvictableIdleTimeMillis = DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS; + + /** My hash of pools (ObjectQueue). */ + private Map _poolMap = null; + + /** The total number of active instances. */ + private int _totalActive = 0; + + /** The total number of idle instances. */ + private int _totalIdle = 0; + + /** + * The number of objects subject to some form of internal processing + * (usually creation or destruction) that should be included in the total + * number of objects but are neither active nor idle. + */ + private int _totalInternalProcessing = 0; + + /** My {@link KeyedPoolableObjectFactory}. */ + private KeyedPoolableObjectFactory _factory = null; + + /** + * My idle object eviction {@link TimerTask}, if any. + */ + private Evictor _evictor = null; + + /** + * A cursorable list of my pools. + * @see GenericKeyedObjectPool.Evictor#run + */ + private CursorableLinkedList _poolList = null; + + /** Eviction cursor (over instances within-key) */ + private CursorableLinkedList.Cursor _evictionCursor = null; + + /** Eviction cursor (over keys) */ + private CursorableLinkedList.Cursor _evictionKeyCursor = null; + + /** Whether or not the pools behave as LIFO queues (last in first out) */ + private boolean _lifo = DEFAULT_LIFO; + + /** + * Used to track the order in which threads call {@link #borrowObject()} so + * that objects can be allocated in the order in which the threads requested + * them. + */ + private LinkedList _allocationQueue = new LinkedList(); + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `c` last assigned on line 1460 could be null and is dereferenced at line 1461. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GenericKeyedObjectPool.destroy(HashMap,KeyedPoolableObjectFactory) + +### Procedure Id: +org.apache.commons.pool.impl.GenericKeyedObjectPool.destroy(java.util.HashMap,org.apache.commons.poo.3be3356d16be1344737f2da421518b32 + +### File: +src/java/org/apache/commons/pool/impl/GenericKeyedObjectPool.java + +### Key: +GenericKeyedObjectPool.java|destroy|NULL_DEREFERENCE + +### Node Key: +75a3105ef036e14d28c2a0df35d92164 + +### Hash: +34317ede13d252569ec24529129b74aa + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3460/instruction.md b/inferredbugs-3460/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..408386b6cd163a65a13a20e6dfeefd3c7d176828 --- /dev/null +++ b/inferredbugs-3460/instruction.md @@ -0,0 +1,2720 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-pool +**Bug ID:** 12 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.pool.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.TreeMap; +import java.util.TimerTask; + +import org.apache.commons.pool.BaseKeyedObjectPool; +import org.apache.commons.pool.KeyedObjectPool; +import org.apache.commons.pool.KeyedPoolableObjectFactory; +import org.apache.commons.pool.PoolUtils; + +/** + * A configurable KeyedObjectPool implementation. + *

    + * When coupled with the appropriate {@link KeyedPoolableObjectFactory}, + * GenericKeyedObjectPool provides robust pooling functionality for + * keyed objects. A GenericKeyedObjectPool can be viewed as a map + * of pools, keyed on the (unique) key values provided to the + * {@link #preparePool preparePool}, {@link #addObject addObject} or + * {@link #borrowObject borrowObject} methods. Each time a new key value is + * provided to one of these methods, a new pool is created under the given key + * to be managed by the containing GenericKeyedObjectPool. + *

    + *

    A GenericKeyedObjectPool provides a number of configurable + * parameters:

    + *
      + *
    • + * {@link #setMaxActive maxActive} controls the maximum number of objects + * (per key) that can allocated by the pool (checked out to client threads, + * or idle in the pool) at one time. When non-positive, there is no limit + * to the number of objects per key. When {@link #setMaxActive maxActive} is + * reached, the keyed pool is said to be exhausted. The default setting for + * this parameter is 8. + *
    • + *
    • + * {@link #setMaxTotal maxTotal} sets a global limit on the number of objects + * that can be in circulation (active or idle) within the combined set of + * pools. When non-positive, there is no limit to the total number of + * objects in circulation. When {@link #setMaxTotal maxTotal} is exceeded, + * all keyed pools are exhausted. When maxTotal is set to a + * positive value and {@link #borrowObject borrowObject} is invoked + * when at the limit with no idle instances available, an attempt is made to + * create room by clearing the oldest 15% of the elements from the keyed + * pools. The default setting for this parameter is -1 (no limit). + *
    • + *
    • + * {@link #setMaxIdle maxIdle} controls the maximum number of objects that can + * sit idle in the pool (per key) at any time. When negative, there + * is no limit to the number of objects that may be idle per key. The + * default setting for this parameter is 8. + *
    • + *
    • + * {@link #setWhenExhaustedAction whenExhaustedAction} specifies the + * behavior of the {@link #borrowObject borrowObject} method when a keyed + * pool is exhausted: + *
        + *
      • + * When {@link #setWhenExhaustedAction whenExhaustedAction} is + * {@link #WHEN_EXHAUSTED_FAIL}, {@link #borrowObject borrowObject} will throw + * a {@link NoSuchElementException} + *
      • + *
      • + * When {@link #setWhenExhaustedAction whenExhaustedAction} is + * {@link #WHEN_EXHAUSTED_GROW}, {@link #borrowObject borrowObject} will create a new + * object and return it (essentially making {@link #setMaxActive maxActive} + * meaningless.) + *
      • + *
      • + * When {@link #setWhenExhaustedAction whenExhaustedAction} + * is {@link #WHEN_EXHAUSTED_BLOCK}, {@link #borrowObject borrowObject} will block + * (invoke {@link Object#wait() wait} until a new or idle object is available. + * If a positive {@link #setMaxWait maxWait} + * value is supplied, the {@link #borrowObject borrowObject} will block for at + * most that many milliseconds, after which a {@link NoSuchElementException} + * will be thrown. If {@link #setMaxWait maxWait} is non-positive, + * the {@link #borrowObject borrowObject} method will block indefinitely. + *
      • + *
      + * The default whenExhaustedAction setting is + * {@link #WHEN_EXHAUSTED_BLOCK}. + *
    • + *
    • + * When {@link #setTestOnBorrow testOnBorrow} is set, the pool will + * attempt to validate each object before it is returned from the + * {@link #borrowObject borrowObject} method. (Using the provided factory's + * {@link KeyedPoolableObjectFactory#validateObject validateObject} method.) + * Objects that fail to validate will be dropped from the pool, and a + * different object will be borrowed. The default setting for this parameter + * is false. + *
    • + *
    • + * When {@link #setTestOnReturn testOnReturn} is set, the pool will + * attempt to validate each object before it is returned to the pool in the + * {@link #returnObject returnObject} method. (Using the provided factory's + * {@link KeyedPoolableObjectFactory#validateObject validateObject} + * method.) Objects that fail to validate will be dropped from the pool. + * The default setting for this parameter is false. + *
    • + *
    + *

    + * Optionally, one may configure the pool to examine and possibly evict objects + * as they sit idle in the pool and to ensure that a minimum number of idle + * objects is maintained for each key. This is performed by an + * "idle object eviction" thread, which runs asynchronously. Caution should be + * used when configuring this optional feature. Eviction runs require an + * exclusive synchronization lock on the pool, so if they run too frequently + * and / or incur excessive latency when creating, destroying or validating + * object instances, performance issues may result. The idle object eviction + * thread may be configured using the following attributes: + *

      + *
    • + * {@link #setTimeBetweenEvictionRunsMillis timeBetweenEvictionRunsMillis} + * indicates how long the eviction thread should sleep before "runs" of examining + * idle objects. When non-positive, no eviction thread will be launched. The + * default setting for this parameter is -1 (i.e., by default, idle object + * eviction is disabled). + *
    • + *
    • + * {@link #setMinEvictableIdleTimeMillis minEvictableIdleTimeMillis} + * specifies the minimum amount of time that an object may sit idle in the + * pool before it is eligible for eviction due to idle time. When + * non-positive, no object will be dropped from the pool due to idle time + * alone. This setting has no effect unless + * timeBetweenEvictionRunsMillis > 0. The default setting + * for this parameter is 30 minutes. + *
    • + *
    • + * {@link #setTestWhileIdle testWhileIdle} indicates whether or not idle + * objects should be validated using the factory's + * {@link KeyedPoolableObjectFactory#validateObject validateObject} method + * during idle object eviction runs. Objects that fail to validate will be + * dropped from the pool. This setting has no effect unless + * timeBetweenEvictionRunsMillis > 0. The default setting + * for this parameter is false. + *
    • + *
    • + * {@link #setMinIdle minIdle} sets a target value for the minimum number of + * idle objects (per key) that should always be available. If this parameter + * is set to a positive number and + * timeBetweenEvictionRunsMillis > 0, each time the idle object + * eviction thread runs, it will try to create enough idle instances so that + * there will be minIdle idle instances available under each + * key. This parameter is also used by {@link #preparePool preparePool} + * if true is provided as that method's + * populateImmediately parameter. The default setting for this + * parameter is 0. + *
    • + *
    + *

    + * The pools can be configured to behave as LIFO queues with respect to idle + * objects - always returning the most recently used object from the pool, + * or as FIFO queues, where borrowObject always returns the oldest object + * in the idle object pool. + *

      + *
    • + * {@link #setLifo Lifo} + * determines whether or not the pools return idle objects in + * last-in-first-out order. The default setting for this parameter is + * true. + *
    • + *
    + *

    + * GenericKeyedObjectPool is not usable without a {@link KeyedPoolableObjectFactory}. A + * non-null factory must be provided either as a constructor argument + * or via a call to {@link #setFactory setFactory} before the pool is used. + *

    + *

    + * Implementation note: To prevent possible deadlocks, care has been taken to + * ensure that no call to a factory method will occur within a synchronization + * block. See POOL-125 and DBCP-44 for more information. + *

    + * @see GenericObjectPool + * @author Rodney Waldhoff + * @author Dirk Verbeeck + * @author Sandy McArthur + * @version $Revision$ $Date$ + * @since Pool 1.0 + */ +public class GenericKeyedObjectPool extends BaseKeyedObjectPool implements KeyedObjectPool { + + //--- public constants ------------------------------------------- + + /** + * A "when exhausted action" type indicating that when the pool is + * exhausted (i.e., the maximum number of active objects has + * been reached), the {@link #borrowObject} + * method should fail, throwing a {@link NoSuchElementException}. + * @see #WHEN_EXHAUSTED_BLOCK + * @see #WHEN_EXHAUSTED_GROW + * @see #setWhenExhaustedAction + */ + public static final byte WHEN_EXHAUSTED_FAIL = 0; + + /** + * A "when exhausted action" type indicating that when the pool + * is exhausted (i.e., the maximum number + * of active objects has been reached), the {@link #borrowObject} + * method should block until a new object is available, or the + * {@link #getMaxWait maximum wait time} has been reached. + * @see #WHEN_EXHAUSTED_FAIL + * @see #WHEN_EXHAUSTED_GROW + * @see #setMaxWait + * @see #getMaxWait + * @see #setWhenExhaustedAction + */ + public static final byte WHEN_EXHAUSTED_BLOCK = 1; + + /** + * A "when exhausted action" type indicating that when the pool is + * exhausted (i.e., the maximum number + * of active objects has been reached), the {@link #borrowObject} + * method should simply create a new object anyway. + * @see #WHEN_EXHAUSTED_FAIL + * @see #WHEN_EXHAUSTED_GROW + * @see #setWhenExhaustedAction + */ + public static final byte WHEN_EXHAUSTED_GROW = 2; + + /** + * The default cap on the number of idle instances (per key) in the pool. + * @see #getMaxIdle + * @see #setMaxIdle + */ + public static final int DEFAULT_MAX_IDLE = 8; + + /** + * The default cap on the total number of active instances (per key) + * from the pool. + * @see #getMaxActive + * @see #setMaxActive + */ + public static final int DEFAULT_MAX_ACTIVE = 8; + + /** + * The default cap on the the overall maximum number of objects that can + * exist at one time. + * @see #getMaxTotal + * @see #setMaxTotal + */ + public static final int DEFAULT_MAX_TOTAL = -1; + + /** + * The default "when exhausted action" for the pool. + * @see #WHEN_EXHAUSTED_BLOCK + * @see #WHEN_EXHAUSTED_FAIL + * @see #WHEN_EXHAUSTED_GROW + * @see #setWhenExhaustedAction + */ + public static final byte DEFAULT_WHEN_EXHAUSTED_ACTION = WHEN_EXHAUSTED_BLOCK; + + /** + * The default maximum amount of time (in milliseconds) the + * {@link #borrowObject} method should block before throwing + * an exception when the pool is exhausted and the + * {@link #getWhenExhaustedAction "when exhausted" action} is + * {@link #WHEN_EXHAUSTED_BLOCK}. + * @see #getMaxWait + * @see #setMaxWait + */ + public static final long DEFAULT_MAX_WAIT = -1L; + + /** + * The default "test on borrow" value. + * @see #getTestOnBorrow + * @see #setTestOnBorrow + */ + public static final boolean DEFAULT_TEST_ON_BORROW = false; + + /** + * The default "test on return" value. + * @see #getTestOnReturn + * @see #setTestOnReturn + */ + public static final boolean DEFAULT_TEST_ON_RETURN = false; + + /** + * The default "test while idle" value. + * @see #getTestWhileIdle + * @see #setTestWhileIdle + * @see #getTimeBetweenEvictionRunsMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + public static final boolean DEFAULT_TEST_WHILE_IDLE = false; + + /** + * The default "time between eviction runs" value. + * @see #getTimeBetweenEvictionRunsMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + public static final long DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS = -1L; + + /** + * The default number of objects to examine per run in the + * idle object evictor. + * @see #getNumTestsPerEvictionRun + * @see #setNumTestsPerEvictionRun + * @see #getTimeBetweenEvictionRunsMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + public static final int DEFAULT_NUM_TESTS_PER_EVICTION_RUN = 3; + + /** + * The default value for {@link #getMinEvictableIdleTimeMillis}. + * @see #getMinEvictableIdleTimeMillis + * @see #setMinEvictableIdleTimeMillis + */ + public static final long DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS = 1000L * 60L * 30L; + + /** + * The default minimum level of idle objects in the pool. + * @since Pool 1.3 + * @see #setMinIdle + * @see #getMinIdle + */ + public static final int DEFAULT_MIN_IDLE = 0; + + /** + * The default LIFO status. True means that borrowObject returns the + * most recently used ("last in") idle object in a pool (if there are + * idle instances available). False means that pools behave as FIFO + * queues - objects are taken from idle object pools in the order that + * they are returned. + * @see #setLifo + */ + public static final boolean DEFAULT_LIFO = true; + + //--- constructors ----------------------------------------------- + + /** + * Create a new GenericKeyedObjectPool with no factory. + * + * @see #GenericKeyedObjectPool(KeyedPoolableObjectFactory) + * @see #setFactory(KeyedPoolableObjectFactory) + */ + public GenericKeyedObjectPool() { + this(null, DEFAULT_MAX_ACTIVE, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE, + DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, + DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy + * objects if not null + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory) { + this(factory, DEFAULT_MAX_ACTIVE, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE, + DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, + DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param config a non-null {@link GenericKeyedObjectPool.Config} describing the configuration + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, GenericKeyedObjectPool.Config config) { + this(factory, config.maxActive, config.whenExhaustedAction, config.maxWait, config.maxIdle, config.maxTotal, + config.minIdle, config.testOnBorrow, config.testOnReturn, config.timeBetweenEvictionRunsMillis, + config.numTestsPerEvictionRun, config.minEvictableIdleTimeMillis, config.testWhileIdle, config.lifo); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive}) + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive) { + this(factory,maxActive, DEFAULT_WHEN_EXHAUSTED_ACTION, DEFAULT_MAX_WAIT, DEFAULT_MAX_IDLE, + DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, + DEFAULT_NUM_TESTS_PER_EVICTION_RUN, DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive}) + * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait) { + this(factory, maxActive, whenExhaustedAction, maxWait, DEFAULT_MAX_IDLE, DEFAULT_TEST_ON_BORROW, + DEFAULT_TEST_ON_RETURN, DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN, + DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) + * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) + * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} + * method (see {@link #setTestOnBorrow}) + * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} + * method (see {@link #setTestOnReturn}) + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait, boolean testOnBorrow, boolean testOnReturn) { + this(factory, maxActive, whenExhaustedAction, maxWait, DEFAULT_MAX_IDLE,testOnBorrow,testOnReturn, + DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN, + DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed from me at one time + * (see {@link #setMaxActive}) + * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) + * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait, int maxIdle) { + this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, DEFAULT_TEST_ON_BORROW, DEFAULT_TEST_ON_RETURN, + DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN, + DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed from me at one time + * (see {@link #setMaxActive}) + * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait}) + * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) + * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} + * method (see {@link #setTestOnBorrow}) + * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} + * method (see {@link #setTestOnReturn}) + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait, int maxIdle, boolean testOnBorrow, boolean testOnReturn) { + this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, testOnBorrow, testOnReturn, + DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, DEFAULT_NUM_TESTS_PER_EVICTION_RUN, + DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, DEFAULT_TEST_WHILE_IDLE); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed from me at one time + * (see {@link #setMaxActive}) + * @param whenExhaustedAction the action to take when the pool is exhausted + * (see {@link #setWhenExhaustedAction}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) + * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) + * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} + * method (see {@link #setTestOnBorrow}) + * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} + * method (see {@link #setTestOnReturn}) + * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle + * objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis}) + * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction + * thread (if any) (see {@link #setNumTestsPerEvictionRun}) + * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before + * it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis}) + * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any + * (see {@link #setTestWhileIdle}) + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait, int maxIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis, + int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle) { + this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, GenericKeyedObjectPool.DEFAULT_MAX_TOTAL, + testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, numTestsPerEvictionRun, + minEvictableIdleTimeMillis, testWhileIdle); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed from me at one time + * (see {@link #setMaxActive}) + * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) + * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) + * @param maxTotal the maximum number of objects that can exists at one time (see {@link #setMaxTotal}) + * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} + * method (see {@link #setTestOnBorrow}) + * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} + * method (see {@link #setTestOnReturn}) + * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle + * objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis}) + * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction + * thread (if any) (see {@link #setNumTestsPerEvictionRun}) + * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool + * before it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis}) + * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any + * (see {@link #setTestWhileIdle}) + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait, int maxIdle, int maxTotal, boolean testOnBorrow, boolean testOnReturn, + long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, + boolean testWhileIdle) { + this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, maxTotal, + GenericKeyedObjectPool.DEFAULT_MIN_IDLE, testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, + numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed at one time (see {@link #setMaxActive}) + * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) + * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) + * @param maxTotal the maximum number of objects that can exists at one time (see {@link #setMaxTotal}) + * @param minIdle the minimum number of idle objects to have in the pool at any one time (see {@link #setMinIdle}) + * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} + * method (see {@link #setTestOnBorrow}) + * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} + * method (see {@link #setTestOnReturn}) + * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle + * objects + * for eviction (see {@link #setTimeBetweenEvictionRunsMillis}) + * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction + * thread (if any) (see {@link #setNumTestsPerEvictionRun}) + * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before + * it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis}) + * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any + * (see {@link #setTestWhileIdle}) + * @since Pool 1.3 + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait, int maxIdle, int maxTotal, int minIdle, boolean testOnBorrow, boolean testOnReturn, + long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, + boolean testWhileIdle) { + this(factory, maxActive, whenExhaustedAction, maxWait, maxIdle, maxTotal, minIdle, testOnBorrow, testOnReturn, + timeBetweenEvictionRunsMillis, numTestsPerEvictionRun, minEvictableIdleTimeMillis, testWhileIdle, + DEFAULT_LIFO); + } + + /** + * Create a new GenericKeyedObjectPool using the specified values. + * @param factory the KeyedPoolableObjectFactory to use to create, validate, and destroy objects + * if not null + * @param maxActive the maximum number of objects that can be borrowed at one time + * (see {@link #setMaxActive}) + * @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction}) + * @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted and + * whenExhaustedAction is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait}) + * @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle}) + * @param maxTotal the maximum number of objects that can exists at one time (see {@link #setMaxTotal}) + * @param minIdle the minimum number of idle objects to have in the pool at any one time (see {@link #setMinIdle}) + * @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} + * method (see {@link #setTestOnBorrow}) + * @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} + * method (see {@link #setTestOnReturn}) + * @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle + * objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis}) + * @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction + * thread (if any) (see {@link #setNumTestsPerEvictionRun}) + * @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before + * it is eligible for eviction (see {@link #setMinEvictableIdleTimeMillis}) + * @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any + * (see {@link #setTestWhileIdle}) + * @param lifo whether or not the pools behave as LIFO (last in first out) queues (see {@link #setLifo}) + * @since Pool 1.4 + */ + public GenericKeyedObjectPool(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, + long maxWait, int maxIdle, int maxTotal, int minIdle, boolean testOnBorrow, boolean testOnReturn, + long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, + boolean testWhileIdle, boolean lifo) { + _factory = factory; + _maxActive = maxActive; + _lifo = lifo; + switch (whenExhaustedAction) { + case WHEN_EXHAUSTED_BLOCK: + case WHEN_EXHAUSTED_FAIL: + case WHEN_EXHAUSTED_GROW: + _whenExhaustedAction = whenExhaustedAction; + break; + default: + throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized."); + } + _maxWait = maxWait; + _maxIdle = maxIdle; + _maxTotal = maxTotal; + _minIdle = minIdle; + _testOnBorrow = testOnBorrow; + _testOnReturn = testOnReturn; + _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; + _numTestsPerEvictionRun = numTestsPerEvictionRun; + _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; + _testWhileIdle = testWhileIdle; + + _poolMap = new HashMap(); + _poolList = new CursorableLinkedList(); + + startEvictor(_timeBetweenEvictionRunsMillis); + } + + //--- public methods --------------------------------------------- + + //--- configuration methods -------------------------------------- + + /** + * Returns the cap on the number of object instances allocated by the pool + * (checked out or idle), per key. + * A negative value indicates no limit. + * + * @return the cap on the number of active instances per key. + * @see #setMaxActive + */ + public synchronized int getMaxActive() { + return _maxActive; + } + + /** + * Sets the cap on the number of object instances managed by the pool per key. + * @param maxActive The cap on the number of object instances per key. + * Use a negative value for no limit. + * + * @see #getMaxActive + */ + public synchronized void setMaxActive(int maxActive) { + _maxActive = maxActive; + allocate(); + } + + /** + * Returns the overall maximum number of objects (across pools) that can + * exist at one time. A negative value indicates no limit. + * @return the maximum number of instances in circulation at one time. + * @see #setMaxTotal + */ + public synchronized int getMaxTotal() { + return _maxTotal; + } + + /** + * Sets the cap on the total number of instances from all pools combined. + * When maxTotal is set to a + * positive value and {@link #borrowObject borrowObject} is invoked + * when at the limit with no idle instances available, an attempt is made to + * create room by clearing the oldest 15% of the elements from the keyed + * pools. + * + * @param maxTotal The cap on the total number of instances across pools. + * Use a negative value for no limit. + * @see #getMaxTotal + */ + public synchronized void setMaxTotal(int maxTotal) { + _maxTotal = maxTotal; + allocate(); + } + + /** + * Returns the action to take when the {@link #borrowObject} method + * is invoked when the pool is exhausted (the maximum number + * of "active" objects has been reached). + * + * @return one of {@link #WHEN_EXHAUSTED_BLOCK}, + * {@link #WHEN_EXHAUSTED_FAIL} or {@link #WHEN_EXHAUSTED_GROW} + * @see #setWhenExhaustedAction + */ + public synchronized byte getWhenExhaustedAction() { + return _whenExhaustedAction; + } + + /** + * Sets the action to take when the {@link #borrowObject} method + * is invoked when the pool is exhausted (the maximum number + * of "active" objects has been reached). + * + * @param whenExhaustedAction the action code, which must be one of + * {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL}, + * or {@link #WHEN_EXHAUSTED_GROW} + * @see #getWhenExhaustedAction + */ + public synchronized void setWhenExhaustedAction(byte whenExhaustedAction) { + switch(whenExhaustedAction) { + case WHEN_EXHAUSTED_BLOCK: + case WHEN_EXHAUSTED_FAIL: + case WHEN_EXHAUSTED_GROW: + _whenExhaustedAction = whenExhaustedAction; + allocate(); + break; + default: + throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized."); + } + } + + + /** + * Returns the maximum amount of time (in milliseconds) the + * {@link #borrowObject} method should block before throwing + * an exception when the pool is exhausted and the + * {@link #setWhenExhaustedAction "when exhausted" action} is + * {@link #WHEN_EXHAUSTED_BLOCK}. + * + * When less than or equal to 0, the {@link #borrowObject} method + * may block indefinitely. + * + * @return the maximum number of milliseconds borrowObject will block. + * @see #setMaxWait + * @see #setWhenExhaustedAction + * @see #WHEN_EXHAUSTED_BLOCK + */ + public synchronized long getMaxWait() { + return _maxWait; + } + + /** + * Sets the maximum amount of time (in milliseconds) the + * {@link #borrowObject} method should block before throwing + * an exception when the pool is exhausted and the + * {@link #setWhenExhaustedAction "when exhausted" action} is + * {@link #WHEN_EXHAUSTED_BLOCK}. + * + * When less than or equal to 0, the {@link #borrowObject} method + * may block indefinitely. + * + * @param maxWait the maximum number of milliseconds borrowObject will block or negative for indefinitely. + * @see #getMaxWait + * @see #setWhenExhaustedAction + * @see #WHEN_EXHAUSTED_BLOCK + */ + public synchronized void setMaxWait(long maxWait) { + _maxWait = maxWait; + } + + /** + * Returns the cap on the number of "idle" instances per key. + * @return the maximum number of "idle" instances that can be held + * in a given keyed pool. + * @see #setMaxIdle + */ + public synchronized int getMaxIdle() { + return _maxIdle; + } + + /** + * Sets the cap on the number of "idle" instances in the pool. + * If maxIdle is set too low on heavily loaded systems it is possible you + * will see objects being destroyed and almost immediately new objects + * being created. This is a result of the active threads momentarily + * returning objects faster than they are requesting them them, causing the + * number of idle objects to rise above maxIdle. The best value for maxIdle + * for heavily loaded system will vary but the default is a good starting + * point. + * @param maxIdle the maximum number of "idle" instances that can be held + * in a given keyed pool. Use a negative value for no limit. + * @see #getMaxIdle + * @see #DEFAULT_MAX_IDLE + */ + public synchronized void setMaxIdle(int maxIdle) { + _maxIdle = maxIdle; + allocate(); + } + + /** + * Sets the minimum number of idle objects to maintain in each of the keyed + * pools. This setting has no effect unless + * timeBetweenEvictionRunsMillis > 0 and attempts to ensure + * that each pool has the required minimum number of instances are only + * made during idle object eviction runs. + * @param poolSize - The minimum size of the each keyed pool + * @since Pool 1.3 + * @see #getMinIdle + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized void setMinIdle(int poolSize) { + _minIdle = poolSize; + } + + /** + * Returns the minimum number of idle objects to maintain in each of the keyed + * pools. This setting has no effect unless + * timeBetweenEvictionRunsMillis > 0 and attempts to ensure + * that each pool has the required minimum number of instances are only + * made during idle object eviction runs. + * @return minimum size of the each keyed pool + * @since Pool 1.3 + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized int getMinIdle() { + return _minIdle; + } + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * before being returned by the {@link #borrowObject} + * method. If the object fails to validate, + * it will be dropped from the pool, and we will attempt + * to borrow another. + * + * @return true if objects are validated before being borrowed. + * @see #setTestOnBorrow + */ + public boolean getTestOnBorrow() { + return _testOnBorrow; + } + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * before being returned by the {@link #borrowObject} + * method. If the object fails to validate, + * it will be dropped from the pool, and we will attempt + * to borrow another. + * + * @param testOnBorrow whether object should be validated before being returned by borrowObject. + * @see #getTestOnBorrow + */ + public void setTestOnBorrow(boolean testOnBorrow) { + _testOnBorrow = testOnBorrow; + } + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * before being returned to the pool within the + * {@link #returnObject}. + * + * @return true when objects will be validated before being returned. + * @see #setTestOnReturn + */ + public boolean getTestOnReturn() { + return _testOnReturn; + } + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * before being returned to the pool within the + * {@link #returnObject}. + * + * @param testOnReturn true so objects will be validated before being returned. + * @see #getTestOnReturn + */ + public void setTestOnReturn(boolean testOnReturn) { + _testOnReturn = testOnReturn; + } + + /** + * Returns the number of milliseconds to sleep between runs of the + * idle object evictor thread. + * When non-positive, no idle object evictor thread will be + * run. + * + * @return milliseconds to sleep between evictor runs. + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized long getTimeBetweenEvictionRunsMillis() { + return _timeBetweenEvictionRunsMillis; + } + + /** + * Sets the number of milliseconds to sleep between runs of the + * idle object evictor thread. + * When non-positive, no idle object evictor thread will be + * run. + * + * @param timeBetweenEvictionRunsMillis milliseconds to sleep between evictor runs. + * @see #getTimeBetweenEvictionRunsMillis + */ + public synchronized void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) { + _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; + startEvictor(_timeBetweenEvictionRunsMillis); + } + + /** + * Returns the max number of objects to examine during each run of the + * idle object evictor thread (if any). + * + * @return number of objects to examine each eviction run. + * @see #setNumTestsPerEvictionRun + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized int getNumTestsPerEvictionRun() { + return _numTestsPerEvictionRun; + } + + /** + * Sets the max number of objects to examine during each run of the + * idle object evictor thread (if any). + *

    + * When a negative value is supplied, + * ceil({@link #getNumIdle()})/abs({@link #getNumTestsPerEvictionRun}) + * tests will be run. I.e., when the value is -n, roughly one nth of the + * idle objects will be tested per run. When the value is positive, the number of tests + * actually performed in each run will be the minimum of this value and the number of instances + * idle in the pools. + * + * @param numTestsPerEvictionRun number of objects to examine each eviction run. + * @see #setNumTestsPerEvictionRun + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) { + _numTestsPerEvictionRun = numTestsPerEvictionRun; + } + + /** + * Returns the minimum amount of time an object may sit idle in the pool + * before it is eligible for eviction by the idle object evictor + * (if any). + * + * @return minimum amount of time an object may sit idle in the pool before it is eligible for eviction. + * @see #setMinEvictableIdleTimeMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized long getMinEvictableIdleTimeMillis() { + return _minEvictableIdleTimeMillis; + } + + /** + * Sets the minimum amount of time an object may sit idle in the pool + * before it is eligible for eviction by the idle object evictor + * (if any). + * When non-positive, no objects will be evicted from the pool + * due to idle time alone. + * + * @param minEvictableIdleTimeMillis minimum amount of time an object may sit idle in the pool before + * it is eligible for eviction. + * @see #getMinEvictableIdleTimeMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { + _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; + } + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * by the idle object evictor (if any). If an object + * fails to validate, it will be dropped from the pool. + * + * @return true when objects are validated when borrowed. + * @see #setTestWhileIdle + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized boolean getTestWhileIdle() { + return _testWhileIdle; + } + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * by the idle object evictor (if any). If an object + * fails to validate, it will be dropped from the pool. + * + * @param testWhileIdle true so objects are validated when borrowed. + * @see #getTestWhileIdle + * @see #setTimeBetweenEvictionRunsMillis + */ + public synchronized void setTestWhileIdle(boolean testWhileIdle) { + _testWhileIdle = testWhileIdle; + } + + /** + * Sets the configuration. + * @param conf the new configuration to use. + * @see GenericKeyedObjectPool.Config + */ + public synchronized void setConfig(GenericKeyedObjectPool.Config conf) { + setMaxIdle(conf.maxIdle); + setMaxActive(conf.maxActive); + setMaxTotal(conf.maxTotal); + setMinIdle(conf.minIdle); + setMaxWait(conf.maxWait); + setWhenExhaustedAction(conf.whenExhaustedAction); + setTestOnBorrow(conf.testOnBorrow); + setTestOnReturn(conf.testOnReturn); + setTestWhileIdle(conf.testWhileIdle); + setNumTestsPerEvictionRun(conf.numTestsPerEvictionRun); + setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis); + setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis); + } + + /** + * Whether or not the idle object pools act as LIFO queues. True means + * that borrowObject returns the most recently used ("last in") idle object + * in a pool (if there are idle instances available). False means that + * the pools behave as FIFO queues - objects are taken from idle object + * pools in the order that they are returned. + * + * @return true if the pools are configured to act as LIFO queues + * @since 1.4 + */ + public synchronized boolean getLifo() { + return _lifo; + } + + /** + * Sets the LIFO property of the pools. True means that borrowObject returns + * the most recently used ("last in") idle object in a pool (if there are + * idle instances available). False means that the pools behave as FIFO + * queues - objects are taken from idle object pools in the order that + * they are returned. + * + * @param lifo the new value for the lifo property + * @since 1.4 + */ + public synchronized void setLifo(boolean lifo) { + this._lifo = lifo; + } + + //-- ObjectPool methods ------------------------------------------ + + /** + *

    Borrows an object from the keyed pool associated with the given key.

    + * + *

    If there is an idle instance available in the pool associated with the given key, then + * either the most-recently returned (if {@link #getLifo() lifo} == true) or "oldest" (lifo == false) + * instance sitting idle in the pool will be activated and returned. If activation fails, or + * {@link #getTestOnBorrow() testOnBorrow} is set to true and validation fails, the instance is destroyed and the + * next available instance is examined. This continues until either a valid instance is returned or there + * are no more idle instances available.

    + * + *

    If there are no idle instances available in the pool associated with the given key, behavior + * depends on the {@link #getMaxActive() maxActive}, {@link #getMaxTotal() maxTotal}, and (if applicable) + * {@link #getWhenExhaustedAction() whenExhaustedAction} and {@link #getMaxWait() maxWait} properties. If the + * number of instances checked out from the pool under the given key is less than maxActive and + * the total number of instances in circulation (under all keys) is less than maxTotal, a new instance + * is created, activated and (if applicable) validated and returned to the caller.

    + * + *

    If the associated keyed pool is exhausted (no available idle instances and no capacity to create new ones), + * this method will either block ({@link #WHEN_EXHAUSTED_BLOCK}), throw a NoSuchElementException + * ({@link #WHEN_EXHAUSTED_FAIL}), or grow ({@link #WHEN_EXHAUSTED_GROW} - ignoring maxActive, maxTotal properties). + * The length of time that this method will block when whenExhaustedAction == WHEN_EXHAUSTED_BLOCK + * is determined by the {@link #getMaxWait() maxWait} property.

    + * + *

    When the pool is exhausted, multiple calling threads may be simultaneously blocked waiting for instances + * to become available. As of pool 1.5, a "fairness" algorithm has been implemented to ensure that threads receive + * available instances in request arrival order.

    + * + * @param key pool key + * @return object instance from the keyed pool + * @throws NoSuchElementException if a keyed object instance cannot be returned. + */ + public Object borrowObject(Object key) throws Exception { + long starttime = System.currentTimeMillis(); + Latch latch = new Latch(key); + byte whenExhaustedAction; + long maxWait; + synchronized (this) { + // Get local copy of current config. Can't sync when used later as + // it can result in a deadlock. Has the added advantage that config + // is consistent for entire method execution + whenExhaustedAction = _whenExhaustedAction; + maxWait = _maxWait; + + // Add this request to the queue + _allocationQueue.add(latch); + + // Work the allocation queue, allocating idle instances and + // instance creation permits in request arrival order + allocate(); + } + + for(;;) { + synchronized (this) { + assertOpen(); + } + // If no object was allocated + if (null == latch.getPair()) { + // Check to see if we were allowed to create one + if (latch.mayCreate()) { + // allow new object to be created + } else { + // the pool is exhausted + switch(whenExhaustedAction) { + case WHEN_EXHAUSTED_GROW: + // allow new object to be created + synchronized (this) { + // Make sure another thread didn't allocate us an object + // or permit a new object to be created + if (latch.getPair() == null && !latch.mayCreate()) { + _allocationQueue.remove(latch); + latch.getPool().incrementInternalProcessingCount(); + } + } + break; + case WHEN_EXHAUSTED_FAIL: + synchronized (this) { + // Make sure allocate hasn't already assigned an object + // in a different thread or permitted a new object to be created + if (latch.getPair() != null || latch.mayCreate()) { + break; + } + _allocationQueue.remove(latch); + } + throw new NoSuchElementException("Pool exhausted"); + case WHEN_EXHAUSTED_BLOCK: + try { + synchronized (latch) { + // Before we wait, make sure another thread didn't allocate us an object + // or permit a new object to be created + if (latch.getPair() == null && !latch.mayCreate()) { + if (maxWait <= 0) { + latch.wait(); + } else { + // this code may be executed again after a notify then continue cycle + // so, need to calculate the amount of time to wait + final long elapsed = (System.currentTimeMillis() - starttime); + final long waitTime = maxWait - elapsed; + if (waitTime > 0) + { + latch.wait(waitTime); + } + } + } else { + break; + } + } + } catch(InterruptedException e) { + synchronized (this) { + // Make sure allocate hasn't already assigned an object + // in a different thread or permitted a new object to be created + if (latch.getPair() == null && !latch.mayCreate()) { + _allocationQueue.remove(latch); + } else { + break; + } + } + Thread.currentThread().interrupt(); + throw e; + } + if (maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) { + synchronized (this) { + // Make sure allocate hasn't already assigned an object + // in a different thread or permitted a new object to be created + if (latch.getPair() == null && !latch.mayCreate()) { + _allocationQueue.remove(latch); + } else { + break; + } + } + throw new NoSuchElementException("Timeout waiting for idle object"); + } else { + continue; // keep looping + } + default: + throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + + " not recognized."); + } + } + } + + boolean newlyCreated = false; + if (null == latch.getPair()) { + try { + Object obj = _factory.makeObject(key); + latch.setPair(new ObjectTimestampPair(obj)); + newlyCreated = true; + } finally { + if (!newlyCreated) { + // object cannot be created + synchronized (this) { + latch.getPool().decrementInternalProcessingCount(); + // No need to reset latch - about to throw exception + allocate(); + } + } + } + } + + // activate & validate the object + try { + _factory.activateObject(key, latch.getPair().value); + if (_testOnBorrow && !_factory.validateObject(key, latch.getPair().value)) { + throw new Exception("ValidateObject failed"); + } + synchronized (this) { + latch.getPool().decrementInternalProcessingCount(); + latch.getPool().incrementActiveCount(); + } + return latch.getPair().value; + } catch (Throwable e) { + PoolUtils.checkRethrow(e); + // object cannot be activated or is invalid + try { + _factory.destroyObject(key, latch.getPair().value); + } catch (Throwable e2) { + PoolUtils.checkRethrow(e2); + // cannot destroy broken object + } + synchronized (this) { + latch.getPool().decrementInternalProcessingCount(); + if (!newlyCreated) { + latch.reset(); + _allocationQueue.add(0, latch); + } + allocate(); + } + if (newlyCreated) { + throw new NoSuchElementException( + "Could not create a validated object, cause: " + + e.getMessage()); + } + else { + continue; // keep looping + } + } + } + } + + /** + * Allocate available instances to latches in the allocation queue. Then + * set _mayCreate to true for as many additional latches remaining in queue + * as _maxActive allows for each key. + */ + private void allocate() { + boolean clearOldest = false; + + synchronized (this) { + if (isClosed()) return; + + Iterator allocationQueueIter = _allocationQueue.iterator(); + + while (allocationQueueIter.hasNext()) { + // First use any objects in the pool to clear the queue + Latch latch = (Latch) allocationQueueIter.next(); + ObjectQueue pool = (ObjectQueue)(_poolMap.get(latch.getkey())); + if (null == pool) { + pool = new ObjectQueue(); + _poolMap.put(latch.getkey(), pool); + _poolList.add(latch.getkey()); + } + latch.setPool(pool); + if (!pool.queue.isEmpty()) { + allocationQueueIter.remove(); + latch.setPair( + (ObjectTimestampPair) pool.queue.removeFirst()); + pool.incrementInternalProcessingCount(); + _totalIdle--; + synchronized (latch) { + latch.notify(); + } + // Next item in queue + continue; + } + + // If there is a totalMaxActive and we are at the limit then + // we have to make room + if ((_maxTotal > 0) && + (_totalActive + _totalIdle + _totalInternalProcessing >= _maxTotal)) { + clearOldest = true; + break; + } + + // Second utilise any spare capacity to create new objects + if ((_maxActive < 0 || pool.activeCount + pool.internalProcessingCount < _maxActive) && + (_maxTotal < 0 || _totalActive + _totalIdle + _totalInternalProcessing < _maxTotal)) { + // allow new object to be created + allocationQueueIter.remove(); + latch.setMayCreate(true); + pool.incrementInternalProcessingCount(); + synchronized (latch) { + latch.notify(); + } + // Next item in queue + continue; + } + + // If there is no per-key limit and we reach this point we + // must have allocated all the objects we possibly can and there + // is no point looking at the rest of the allocation queue + if (_maxActive < 0) { + break; + } + } + } + + if (clearOldest) { + /* Clear oldest calls factory methods so it must be called from + * outside the sync block. + * It also needs to be outside the sync block as it calls + * allocate(). If called inside the sync block, the call to + * allocate() would be able to enter the sync block (since the + * thread already has the lock) which may have unexpected, + * unpleasant results. + */ + clearOldest(); + } + } + + /** + * Clears any objects sitting idle in the pool by removing them from the + * idle instance pool and then invoking the configured + * {@link KeyedPoolableObjectFactory#destroyObject(Object, Object)} method on + * each idle instance. + * + *

    Implementation notes: + *

    • This method does not destroy or effect in any way instances that are + * checked out when it is invoked.
    • + *
    • Invoking this method does not prevent objects being + * returned to the idle instance pool, even during its execution. It locks + * the pool only during instance removal. Additional instances may be returned + * while removed items are being destroyed.

    + */ + public void clear() { + Map toDestroy = new HashMap(); + synchronized (this) { + for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) { + Object key = it.next(); + ObjectQueue pool = (ObjectQueue)_poolMap.get(key); + // Copy objects to new list so pool.queue can be cleared inside + // the sync + List objects = new ArrayList(); + objects.addAll(pool.queue); + toDestroy.put(key, objects); + it.remove(); + _poolList.remove(key); + _totalIdle = _totalIdle - pool.queue.size(); + _totalInternalProcessing = + _totalInternalProcessing + pool.queue.size(); + pool.queue.clear(); + } + } + destroy(toDestroy); + } + + /** + * Clears oldest 15% of objects in pool. The method sorts the + * objects into a TreeMap and then iterates the first 15% for removal. + * + * @since Pool 1.3 + */ + public void clearOldest() { + // Map of objects to destroy my key + final Map toDestroy = new HashMap(); + + // build sorted map of idle objects + final Map map = new TreeMap(); + synchronized (this) { + for (Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext();) { + final Object key = keyiter.next(); + final CursorableLinkedList list = ((ObjectQueue)_poolMap.get(key)).queue; + for (Iterator it = list.iterator(); it.hasNext();) { + // each item into the map uses the objectimestamppair object + // as the key. It then gets sorted based on the timstamp field + // each value in the map is the parent list it belongs in. + map.put(it.next(), key); + } + } + + // Now iterate created map and kill the first 15% plus one to account for zero + Set setPairKeys = map.entrySet(); + int itemsToRemove = ((int) (map.size() * 0.15)) + 1; + + Iterator iter = setPairKeys.iterator(); + while (iter.hasNext() && itemsToRemove > 0) { + Map.Entry entry = (Map.Entry) iter.next(); + // kind of backwards on naming. In the map, each key is the objecttimestamppair + // because it has the ordering with the timestamp value. Each value that the + // key references is the key of the list it belongs to. + Object key = entry.getValue(); + ObjectTimestampPair pairTimeStamp = (ObjectTimestampPair) entry.getKey(); + final CursorableLinkedList list = + ((ObjectQueue)(_poolMap.get(key))).queue; + list.remove(pairTimeStamp); + + if (toDestroy.containsKey(key)) { + ((List)toDestroy.get(key)).add(pairTimeStamp); + } else { + List listForKey = new ArrayList(); + listForKey.add(pairTimeStamp); + toDestroy.put(key, listForKey); + } + // if that was the last object for that key, drop that pool + if (list.isEmpty()) { + _poolMap.remove(key); + _poolList.remove(key); + } + _totalIdle--; + _totalInternalProcessing++; + itemsToRemove--; + } + + } + destroy(toDestroy); + } + + /** + * Clears the specified pool, removing all pooled instances corresponding to the given key. + * + * @param key the key to clear + */ + public void clear(Object key) { + Map toDestroy = new HashMap(); + + final ObjectQueue pool; + synchronized (this) { + pool = (ObjectQueue)(_poolMap.remove(key)); + if (pool == null) { + return; + } else { + _poolList.remove(key); + } + // Copy objects to new list so pool.queue can be cleared inside + // the sync + List objects = new ArrayList(); + objects.addAll(pool.queue); + toDestroy.put(key, objects); + _totalIdle = _totalIdle - pool.queue.size(); + _totalInternalProcessing = + _totalInternalProcessing + pool.queue.size(); + pool.queue.clear(); + } + destroy(toDestroy); + } + + /** + * Assuming Map>, destroy all + * ObjectTimestampPair.value + * + * @param m Map containing keyed pools to clear + */ + private void destroy(Map m) { + for (Iterator keys = m.keySet().iterator(); keys.hasNext();) { + Object key = keys.next(); + Collection c = (Collection) m.get(key); + for (Iterator it = c.iterator(); it.hasNext();) { + try { + _factory.destroyObject( + key,((ObjectTimestampPair)(it.next())).value); + } catch(Exception e) { + // ignore error, keep destroying the rest + } finally { + synchronized(this) { + _totalInternalProcessing--; + allocate(); + } + } + } + + } + } + + /** + * Returns the total number of instances current borrowed from this pool but not yet returned. + * + * @return the total number of instances currently borrowed from this pool + */ + public synchronized int getNumActive() { + return _totalActive; + } + + /** + * Returns the total number of instances currently idle in this pool. + * + * @return the total number of instances currently idle in this pool + */ + public synchronized int getNumIdle() { + return _totalIdle; + } + + /** + * Returns the number of instances currently borrowed from but not yet returned + * to the pool corresponding to the given key. + * + * @param key the key to query + * @return the number of instances corresponding to the given key currently borrowed in this pool + */ + public synchronized int getNumActive(Object key) { + final ObjectQueue pool = (ObjectQueue)(_poolMap.get(key)); + return pool != null ? pool.activeCount : 0; + } + + /** + * Returns the number of instances corresponding to the given key currently idle in this pool. + * + * @param key the key to query + * @return the number of instances corresponding to the given key currently idle in this pool + */ + public synchronized int getNumIdle(Object key) { + final ObjectQueue pool = (ObjectQueue)(_poolMap.get(key)); + return pool != null ? pool.queue.size() : 0; + } + + /** + *

    Returns an object to a keyed pool.

    + * + *

    For the pool to function correctly, the object instance must have been borrowed + * from the pool (under the same key) and not yet returned. Repeated returnObject calls on + * the same object/key pair (with no borrowObject calls in between) will result in multiple + * references to the object in the idle instance pool.

    + * + *

    If {@link #getMaxIdle() maxIdle} is set to a positive value and the number of idle instances under the given + * key has reached this value, the returning instance is destroyed.

    + * + *

    If {@link #getTestOnReturn() testOnReturn} == true, the returning instance is validated before being returned + * to the idle instance pool under the given key. In this case, if validation fails, the instance is destroyed.

    + * + * @param key pool key + * @param obj instance to return to the keyed pool + * @throws Exception + */ + public void returnObject(Object key, Object obj) throws Exception { + try { + addObjectToPool(key, obj, true); + } catch (Exception e) { + if (_factory != null) { + try { + _factory.destroyObject(key, obj); + } catch (Exception e2) { + // swallowed + } + // TODO: Correctness here depends on control in addObjectToPool. + // These two methods should be refactored, removing the + // "behavior flag", decrementNumActive, from addObjectToPool. + ObjectQueue pool = (ObjectQueue) (_poolMap.get(key)); + if (pool != null) { + synchronized(this) { + pool.decrementActiveCount(); + allocate(); + } + } + } + } + } + + /** + *

    Adds an object to the keyed pool.

    + * + *

    Validates the object if testOnReturn == true and passivates it before returning it to the pool. + * if validation or passivation fails, or maxIdle is set and there is no room in the pool, the instance + * is destroyed.

    + * + *

    Calls {@link #allocate()} on successful completion

    + * + * @param key pool key + * @param obj instance to add to the keyed pool + * @param decrementNumActive whether or not to decrement the active count associated with the keyed pool + * @throws Exception + */ + private void addObjectToPool(Object key, Object obj, + boolean decrementNumActive) throws Exception { + + // if we need to validate this object, do so + boolean success = true; // whether or not this object passed validation + if (_testOnReturn && !_factory.validateObject(key, obj)) { + success = false; + } else { + _factory.passivateObject(key, obj); + } + + boolean shouldDestroy = !success; + ObjectQueue pool; + + // Add instance to pool if there is room and it has passed validation + // (if testOnreturn is set) + synchronized (this) { + // grab the pool (list) of objects associated with the given key + pool = (ObjectQueue) (_poolMap.get(key)); + // if it doesn't exist, create it + if (null == pool) { + pool = new ObjectQueue(); + _poolMap.put(key, pool); + _poolList.add(key); + } + if (isClosed()) { + shouldDestroy = true; + } else { + // if there's no space in the pool, flag the object for destruction + // else if we passivated successfully, return it to the pool + if (_maxIdle >= 0 && (pool.queue.size() >= _maxIdle)) { + shouldDestroy = true; + } else if (success) { + // borrowObject always takes the first element from the queue, + // so for LIFO, push on top, FIFO add to end + if (_lifo) { + pool.queue.addFirst(new ObjectTimestampPair(obj)); + } else { + pool.queue.addLast(new ObjectTimestampPair(obj)); + } + _totalIdle++; + if (decrementNumActive) { + pool.decrementActiveCount(); + } + allocate(); + } + } + } + + // Destroy the instance if necessary + if (shouldDestroy) { + try { + _factory.destroyObject(key, obj); + } catch(Exception e) { + // ignored? + } + // Decrement active count *after* destroy if applicable + if (decrementNumActive) { + synchronized(this) { + pool.decrementActiveCount(); + allocate(); + } + } + } + } + + /** + *

    Invalidates the object instance associated with the given key. Decrements the active count + * associated with the given keyed pool and destroys the instance.

    + * + * @param key pool key + * @param obj instance to invalidate + * @throws Exception if an exception occurs destroying the object + */ + public void invalidateObject(Object key, Object obj) throws Exception { + try { + _factory.destroyObject(key, obj); + } finally { + synchronized (this) { + ObjectQueue pool = (ObjectQueue) (_poolMap.get(key)); + if (null == pool) { + pool = new ObjectQueue(); + _poolMap.put(key, pool); + _poolList.add(key); + } + pool.decrementActiveCount(); + allocate(); // _totalActive has changed + } + } + } + + /** + * Create an object using the {@link KeyedPoolableObjectFactory#makeObject factory}, + * passivate it, and then place it in the idle object pool. + * addObject is useful for "pre-loading" a pool with idle objects. + * + * @param key the key a new instance should be added to + * @throws Exception when {@link KeyedPoolableObjectFactory#makeObject} fails. + * @throws IllegalStateException when no {@link #setFactory factory} has been set or after {@link #close} has been + * called on this pool. + */ + public void addObject(Object key) throws Exception { + assertOpen(); + if (_factory == null) { + throw new IllegalStateException("Cannot add objects without a factory."); + } + Object obj = _factory.makeObject(key); + try { + assertOpen(); + addObjectToPool(key, obj, false); + } catch (IllegalStateException ex) { // Pool closed + try { + _factory.destroyObject(key, obj); + } catch (Exception ex2) { + // swallow + } + throw ex; + } + } + + /** + * Registers a key for pool control. + * + * If populateImmediately is true and + * minIdle > 0, the pool under the given key will be + * populated immediately with minIdle idle instances. + * + * @param key - The key to register for pool control. + * @param populateImmediately - If this is true, the pool + * will be populated immediately. + * @since Pool 1.3 + */ + public synchronized void preparePool(Object key, boolean populateImmediately) { + ObjectQueue pool = (ObjectQueue)(_poolMap.get(key)); + if (null == pool) { + pool = new ObjectQueue(); + _poolMap.put(key,pool); + _poolList.add(key); + } + + if (populateImmediately) { + try { + // Create the pooled objects + ensureMinIdle(key); + } + catch (Exception e) { + //Do nothing + } + } + } + + /** + *

    Closes the keyed object pool. Once the pool is closed, {@link #borrowObject(Object)} + * will fail with IllegalStateException, but {@link #returnObject(Object, Object)} and + * {@link #invalidateObject(Object, Object)} will continue to work, with returned objects + * destroyed on return.

    + * + *

    Destroys idle instances in the pool by invoking {@link #clear()}.

    + * + * @throws Exception + */ + public void close() throws Exception { + super.close(); + synchronized (this) { + clear(); + if (null != _evictionCursor) { + _evictionCursor.close(); + _evictionCursor = null; + } + if (null != _evictionKeyCursor) { + _evictionKeyCursor.close(); + _evictionKeyCursor = null; + } + startEvictor(-1L); + } + } + + /** + *

    Sets the keyed poolable object factory associated with this pool.

    + * + *

    If this method is called when objects are checked out of any of the keyed pools, + * an IllegalStateException is thrown. Calling this method also has the side effect of + * destroying any idle instances in existing keyed pools.

    + * + * @param factory KeyedPoolableObjectFactory to use when creating keyed object pool instances + * @throws IllegalStateException if there are active (checked out) instances associated with this keyed object pool + */ + public void setFactory(KeyedPoolableObjectFactory factory) throws IllegalStateException { + Map toDestroy = new HashMap(); + synchronized (this) { + assertOpen(); + if (0 < getNumActive()) { + throw new IllegalStateException("Objects are already active"); + } else { + for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) { + Object key = it.next(); + ObjectQueue pool = (ObjectQueue)_poolMap.get(key); + if (pool != null) { + // Copy objects to new list so pool.queue can be cleared + // inside the sync + List objects = new ArrayList(); + objects.addAll(pool.queue); + toDestroy.put(key, objects); + it.remove(); + _poolList.remove(key); + _totalIdle = _totalIdle - pool.queue.size(); + _totalInternalProcessing = + _totalInternalProcessing + pool.queue.size(); + pool.queue.clear(); + } + } + _factory = factory; + } + } + destroy(toDestroy); + } + + /** + *

    Perform numTests idle object eviction tests, evicting + * examined objects that meet the criteria for eviction. If + * testWhileIdle is true, examined objects are validated + * when visited (and removed if invalid); otherwise only objects that + * have been idle for more than minEvicableIdletimeMillis + * are removed.

    + * + *

    Successive activations of this method examine objects in keyed pools + * in sequence, cycling through the keys and examining objects in + * oldest-to-youngest order within the keyed pools.

    + * + * @throws Exception when there is a problem evicting idle objects. + */ + public void evict() throws Exception { + Object key = null; + boolean testWhileIdle; + long minEvictableIdleTimeMillis; + + synchronized (this) { + // Get local copy of current config. Can't sync when used later as + // it can result in a deadlock. Has the added advantage that config + // is consistent for entire method execution + testWhileIdle = _testWhileIdle; + minEvictableIdleTimeMillis = _minEvictableIdleTimeMillis; + + // Initialize key to last key value + if (_evictionKeyCursor != null && + _evictionKeyCursor._lastReturned != null) { + key = _evictionKeyCursor._lastReturned.value(); + } + } + + for (int i=0, m=getNumTests(); i 0) && + (System.currentTimeMillis() - pair.tstamp > + minEvictableIdleTimeMillis)) { + removeObject=true; + } + if (testWhileIdle && removeObject == false) { + boolean active = false; + try { + _factory.activateObject(key,pair.value); + active = true; + } catch(Exception e) { + removeObject=true; + } + if (active) { + if (!_factory.validateObject(key,pair.value)) { + removeObject=true; + } else { + try { + _factory.passivateObject(key,pair.value); + } catch(Exception e) { + removeObject=true; + } + } + } + } + + if (removeObject) { + try { + _factory.destroyObject(key, pair.value); + } catch(Exception e) { + // ignored + } finally { + // Do not remove the key from the _poolList or _poolmap, + // even if the list stored in the _poolMap for this key is + // empty when minIdle > 0. + // + // Otherwise if it was the last object for that key, + // drop that pool + if (_minIdle == 0) { + synchronized (this) { + ObjectQueue objectQueue = + (ObjectQueue)_poolMap.get(key); + if (objectQueue != null && + objectQueue.queue.isEmpty()) { + _poolMap.remove(key); + _poolList.remove(key); + } + } + } + } + } + synchronized (this) { + if (!removeObject) { + _evictionCursor.add(pair); + _totalIdle++; + if (_lifo) { + // Skip over the element we just added back + _evictionCursor.previous(); + } + } + _totalInternalProcessing--; + } + } + } + + /** + * Resets the eviction key cursor and closes any + * associated eviction object cursor + */ + private void resetEvictionKeyCursor() { + if (_evictionKeyCursor != null) { + _evictionKeyCursor.close(); + } + _evictionKeyCursor = _poolList.cursor(); + if (null != _evictionCursor) { + _evictionCursor.close(); + _evictionCursor = null; + } + } + + /** + * Resets the eviction object cursor for the given key + * + * @param key eviction key + */ + private void resetEvictionObjectCursor(Object key) { + if (_evictionCursor != null) { + _evictionCursor.close(); + } + if (_poolMap == null) { + return; + } + ObjectQueue pool = (ObjectQueue) (_poolMap.get(key)); + if (pool != null) { + CursorableLinkedList queue = pool.queue; + _evictionCursor = queue.cursor(_lifo ? queue.size() : 0); + } + } + + /** + * Iterates through all the known keys and creates any necessary objects to maintain + * the minimum level of pooled objects. + * @see #getMinIdle + * @see #setMinIdle + * @throws Exception If there was an error whilst creating the pooled objects. + */ + private void ensureMinIdle() throws Exception { + //Check if should sustain the pool + if (_minIdle > 0) { + Object[] keysCopy; + synchronized(this) { + // Get the current set of keys + keysCopy = _poolMap.keySet().toArray(); + } + + // Loop through all elements in _poolList + // Find out the total number of max active and max idle for that class + // If the number is less than the minIdle, do creation loop to boost numbers + for (int i=0; i < keysCopy.length; i++) { + //Get the next key to process + ensureMinIdle(keysCopy[i]); + } + } + } + + /** + * Re-creates any needed objects to maintain the minimum levels of + * pooled objects for the specified key. + * + * This method uses {@link #calculateDeficit} to calculate the number + * of objects to be created. {@link #calculateDeficit} can be overridden to + * provide a different method of calculating the number of objects to be + * created. + * @param key The key to process + * @throws Exception If there was an error whilst creating the pooled objects + */ + private void ensureMinIdle(Object key) throws Exception { + // Calculate current pool objects + ObjectQueue pool; + synchronized(this) { + pool = (ObjectQueue)(_poolMap.get(key)); + } + if (pool == null) { + return; + } + + // this method isn't synchronized so the + // calculateDeficit is done at the beginning + // as a loop limit and a second time inside the loop + // to stop when another thread already returned the + // needed objects + int objectDeficit = calculateDeficit(pool, false); + + for (int i = 0; i < objectDeficit && calculateDeficit(pool, true) > 0; i++) { + try { + addObject(key); + } finally { + synchronized (this) { + pool.decrementInternalProcessingCount(); + allocate(); + } + } + } + } + + //--- non-public methods ---------------------------------------- + + /** + * Start the eviction thread or service, or when + * delay is non-positive, stop it + * if it is already running. + * + * @param delay milliseconds between evictor runs. + */ + protected synchronized void startEvictor(long delay) { + if (null != _evictor) { + EvictionTimer.cancel(_evictor); + _evictor = null; + } + if (delay > 0) { + _evictor = new Evictor(); + EvictionTimer.schedule(_evictor, delay, delay); + } + } + + /** + * Returns pool info including {@link #getNumActive()}, {@link #getNumIdle()} + * and currently defined keys. + * + * @return string containing debug information + */ + synchronized String debugInfo() { + StringBuffer buf = new StringBuffer(); + buf.append("Active: ").append(getNumActive()).append("\n"); + buf.append("Idle: ").append(getNumIdle()).append("\n"); + Iterator it = _poolMap.keySet().iterator(); + while (it.hasNext()) { + Object key = it.next(); + buf.append("\t").append(key).append(" ").append(_poolMap.get(key)).append("\n"); + } + return buf.toString(); + } + + /** + * Returns the number of tests to be performed in an Evictor run, + * based on the current values of _numTestsPerEvictionRun + * and _totalIdle. + * + * @see #setNumTestsPerEvictionRun + * @return the number of tests for the Evictor to run + */ + private synchronized int getNumTests() { + if (_numTestsPerEvictionRun >= 0) { + return Math.min(_numTestsPerEvictionRun, _totalIdle); + } else { + return(int)(Math.ceil(_totalIdle/Math.abs((double)_numTestsPerEvictionRun))); + } + } + + /** + * This returns the number of objects to create during the pool + * sustain cycle. This will ensure that the minimum number of idle + * instances is maintained without going past the maxActive value. + * + * @param pool the ObjectPool to calculate the deficit for + * @param incrementInternal - Should the count of objects currently under + * some form of internal processing be + * incremented? + * @return The number of objects to be created + */ + private synchronized int calculateDeficit(ObjectQueue pool, + boolean incrementInternal) { + int objectDefecit = 0; + + //Calculate no of objects needed to be created, in order to have + //the number of pooled objects < maxActive(); + objectDefecit = getMinIdle() - pool.queue.size(); + if (getMaxActive() > 0) { + int growLimit = Math.max(0, getMaxActive() - pool.activeCount - pool.queue.size() - pool.internalProcessingCount); + objectDefecit = Math.min(objectDefecit, growLimit); + } + + // Take the maxTotal limit into account + if (getMaxTotal() > 0) { + int growLimit = Math.max(0, getMaxTotal() - getNumActive() - getNumIdle() - _totalInternalProcessing); + objectDefecit = Math.min(objectDefecit, growLimit); + } + + if (incrementInternal && objectDefecit > 0) { + pool.incrementInternalProcessingCount(); + } + return objectDefecit; + } + + //--- inner classes ---------------------------------------------- + + /** + * A "struct" that keeps additional information about the actual queue of pooled objects. + */ + private class ObjectQueue { + /** Number of instances checked out to clients from this queue */ + private int activeCount = 0; + + /** Idle instance queue */ + private final CursorableLinkedList queue = new CursorableLinkedList(); + + /** Number of instances in process of being created */ + private int internalProcessingCount = 0; + + /** Increment the active count for this queue */ + void incrementActiveCount() { + synchronized (GenericKeyedObjectPool.this) { + _totalActive++; + } + activeCount++; + } + + /** Decrement the active count for this queue */ + void decrementActiveCount() { + synchronized (GenericKeyedObjectPool.this) { + _totalActive--; + } + if (activeCount > 0) { + activeCount--; + } + } + + /** Record the fact that one more instance is queued for creation */ + void incrementInternalProcessingCount() { + synchronized (GenericKeyedObjectPool.this) { + _totalInternalProcessing++; + } + internalProcessingCount++; + } + + /** Decrement the number of instances in process of being created */ + void decrementInternalProcessingCount() { + synchronized (GenericKeyedObjectPool.this) { + _totalInternalProcessing--; + } + internalProcessingCount--; + } + } + + /** + * A simple "struct" encapsulating an object instance and a timestamp. + * + * Implements Comparable, objects are sorted from old to new. + * + * This is also used by {@link GenericObjectPool}. + */ + static class ObjectTimestampPair implements Comparable { + + /** Object instance */ + Object value; + + /** timestamp */ + long tstamp; + + /** + * Create a new ObjectTimestampPair using the given object and the current system time. + * @param val object instance + */ + ObjectTimestampPair(Object val) { + this(val, System.currentTimeMillis()); + } + + /** + * Create a new ObjectTimeStampPair using the given object and timestamp value. + * @param val object instance + * @param time long representation of timestamp + */ + ObjectTimestampPair(Object val, long time) { + value = val; + tstamp = time; + } + + /** + * Returns a string representation. + * + * @return String representing this ObjectTimestampPair + */ + public String toString() { + return value + ";" + tstamp; + } + + /** + * Compares this to another object by casting the argument to an + * ObjectTimestampPair. + * + * @param obj object to cmpare + * @return result of comparison + */ + public int compareTo(Object obj) { + return compareTo((ObjectTimestampPair) obj); + } + + /** + * Compares this to another ObjectTimestampPair, using the timestamp as basis for comparison. + * Implementation is consistent with equals. + * + * @param other object to compare + * @return result of comparison + */ + public int compareTo(ObjectTimestampPair other) { + final long tstampdiff = this.tstamp - other.tstamp; + if (tstampdiff == 0) { + // make sure the natural ordering is consistent with equals + // see java.lang.Comparable Javadocs + return System.identityHashCode(this) - System.identityHashCode(other); + } else { + // handle int overflow + return (int)Math.min(Math.max(tstampdiff, Integer.MIN_VALUE), Integer.MAX_VALUE); + } + } + } + + /** + * The idle object evictor {@link TimerTask}. + * @see GenericKeyedObjectPool#setTimeBetweenEvictionRunsMillis + */ + private class Evictor extends TimerTask { + /** + * Run pool maintenance. Evict objects qualifying for eviction and then + * invoke {@link GenericKeyedObjectPool#ensureMinIdle()}. + */ + public void run() { + //Evict from the pool + try { + evict(); + } catch(Exception e) { + // ignored + } catch(OutOfMemoryError oome) { + // Log problem but give evictor thread a chance to continue in + // case error is recoverable + oome.printStackTrace(System.err); + } + //Re-create idle instances. + try { + ensureMinIdle(); + } catch (Exception e) { + // ignored + } + } + } + + /** + * A simple "struct" encapsulating the + * configuration information for a GenericKeyedObjectPool. + * @see GenericKeyedObjectPool#GenericKeyedObjectPool(KeyedPoolableObjectFactory,GenericKeyedObjectPool.Config) + * @see GenericKeyedObjectPool#setConfig + */ + public static class Config { + /** + * @see GenericKeyedObjectPool#setMaxIdle + */ + public int maxIdle = GenericKeyedObjectPool.DEFAULT_MAX_IDLE; + /** + * @see GenericKeyedObjectPool#setMaxActive + */ + public int maxActive = GenericKeyedObjectPool.DEFAULT_MAX_ACTIVE; + /** + * @see GenericKeyedObjectPool#setMaxTotal + */ + public int maxTotal = GenericKeyedObjectPool.DEFAULT_MAX_TOTAL; + /** + * @see GenericKeyedObjectPool#setMinIdle + */ + public int minIdle = GenericKeyedObjectPool.DEFAULT_MIN_IDLE; + /** + * @see GenericKeyedObjectPool#setMaxWait + */ + public long maxWait = GenericKeyedObjectPool.DEFAULT_MAX_WAIT; + /** + * @see GenericKeyedObjectPool#setWhenExhaustedAction + */ + public byte whenExhaustedAction = GenericKeyedObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION; + /** + * @see GenericKeyedObjectPool#setTestOnBorrow + */ + public boolean testOnBorrow = GenericKeyedObjectPool.DEFAULT_TEST_ON_BORROW; + /** + * @see GenericKeyedObjectPool#setTestOnReturn + */ + public boolean testOnReturn = GenericKeyedObjectPool.DEFAULT_TEST_ON_RETURN; + /** + * @see GenericKeyedObjectPool#setTestWhileIdle + */ + public boolean testWhileIdle = GenericKeyedObjectPool.DEFAULT_TEST_WHILE_IDLE; + /** + * @see GenericKeyedObjectPool#setTimeBetweenEvictionRunsMillis + */ + public long timeBetweenEvictionRunsMillis = GenericKeyedObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS; + /** + * @see GenericKeyedObjectPool#setNumTestsPerEvictionRun + */ + public int numTestsPerEvictionRun = GenericKeyedObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN; + /** + * @see GenericKeyedObjectPool#setMinEvictableIdleTimeMillis + */ + public long minEvictableIdleTimeMillis = GenericKeyedObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS; + /** + * @see GenericKeyedObjectPool#setLifo + */ + public boolean lifo = GenericKeyedObjectPool.DEFAULT_LIFO; + } + + /** + * Latch used to control allocation order of objects to threads to ensure + * fairness. That is, for each key, objects are allocated to threads in the order + * that threads request objects. + * + * @since 1.5 + */ + private static final class Latch { + + /** key of associated pool */ + private final Object _key; + + /** keyed pool associated with this latch */ + private ObjectQueue _pool; + + /** holds an ObjectTimestampPair when this latch has been allocated an instance */ + private ObjectTimestampPair _pair; + + /** indicates that this latch can create an instance */ + private boolean _mayCreate = false; + + /** + * Create a latch with the given key + * @param key key of the pool associated with this latch + */ + private Latch(Object key) { + _key = key; + } + + /** + * Retuns the key of the associated pool + * @return associated pool key + */ + private synchronized Object getkey() { + return _key; + } + + /** + * Returns the pool associated with this latch + * @return pool + */ + private synchronized ObjectQueue getPool() { + return _pool; + } + + /** + * Sets the pool associated with this latch + * @param pool the pool + */ + private synchronized void setPool(ObjectQueue pool) { + _pool = pool; + } + + /** + * Gets the ObjectTimestampPair allocated to this latch. + * Returns null if this latch does not have an instance allocated to it. + * @return the associated ObjectTimestampPair + */ + private synchronized ObjectTimestampPair getPair() { + return _pair; + } + + /** + * Allocate an ObjectTimestampPair to this latch. + * @param pair ObjectTimestampPair on this latch + */ + private synchronized void setPair(ObjectTimestampPair pair) { + _pair = pair; + } + + /** + * Whether or not this latch can create an instance + * @return true if this latch has an instance creation permit + */ + private synchronized boolean mayCreate() { + return _mayCreate; + } + + /** + * Sets the mayCreate property + * + * @param mayCreate true means this latch can create an instance + */ + private synchronized void setMayCreate(boolean mayCreate) { + _mayCreate = mayCreate; + } + + /** + * Reset the latch data. Used when an allocation fails and the latch + * needs to be re-added to the queue. + */ + private synchronized void reset() { + _pair = null; + _mayCreate = false; + } + } + + //--- protected attributes --------------------------------------- + + /** + * The cap on the number of idle instances in the pool. + * @see #setMaxIdle + * @see #getMaxIdle + */ + private int _maxIdle = DEFAULT_MAX_IDLE; + + /** + * The minimum no of idle objects to keep in the pool. + * @see #setMinIdle + * @see #getMinIdle + */ + private int _minIdle = DEFAULT_MIN_IDLE; + + /** + * The cap on the number of active instances from the pool. + * @see #setMaxActive + * @see #getMaxActive + */ + private int _maxActive = DEFAULT_MAX_ACTIVE; + + /** + * The cap on the total number of instances from the pool if non-positive. + * @see #setMaxTotal + * @see #getMaxTotal + */ + private int _maxTotal = DEFAULT_MAX_TOTAL; + + /** + * The maximum amount of time (in millis) the + * {@link #borrowObject} method should block before throwing + * an exception when the pool is exhausted and the + * {@link #getWhenExhaustedAction "when exhausted" action} is + * {@link #WHEN_EXHAUSTED_BLOCK}. + * + * When less than or equal to 0, the {@link #borrowObject} method + * may block indefinitely. + * + * @see #setMaxWait + * @see #getMaxWait + * @see #WHEN_EXHAUSTED_BLOCK + * @see #setWhenExhaustedAction + * @see #getWhenExhaustedAction + */ + private long _maxWait = DEFAULT_MAX_WAIT; + + /** + * The action to take when the {@link #borrowObject} method + * is invoked when the pool is exhausted (the maximum number + * of "active" objects has been reached). + * + * @see #WHEN_EXHAUSTED_BLOCK + * @see #WHEN_EXHAUSTED_FAIL + * @see #WHEN_EXHAUSTED_GROW + * @see #DEFAULT_WHEN_EXHAUSTED_ACTION + * @see #setWhenExhaustedAction + * @see #getWhenExhaustedAction + */ + private byte _whenExhaustedAction = DEFAULT_WHEN_EXHAUSTED_ACTION; + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * before being returned by the {@link #borrowObject} + * method. If the object fails to validate, + * it will be dropped from the pool, and we will attempt + * to borrow another. + * + * @see #setTestOnBorrow + * @see #getTestOnBorrow + */ + private volatile boolean _testOnBorrow = DEFAULT_TEST_ON_BORROW; + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * before being returned to the pool within the + * {@link #returnObject}. + * + * @see #getTestOnReturn + * @see #setTestOnReturn + */ + private volatile boolean _testOnReturn = DEFAULT_TEST_ON_RETURN; + + /** + * When true, objects will be + * {@link org.apache.commons.pool.PoolableObjectFactory#validateObject validated} + * by the idle object evictor (if any). If an object + * fails to validate, it will be dropped from the pool. + * + * @see #setTestWhileIdle + * @see #getTestWhileIdle + * @see #getTimeBetweenEvictionRunsMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + private boolean _testWhileIdle = DEFAULT_TEST_WHILE_IDLE; + + /** + * The number of milliseconds to sleep between runs of the + * idle object evictor thread. + * When non-positive, no idle object evictor thread will be + * run. + * + * @see #setTimeBetweenEvictionRunsMillis + * @see #getTimeBetweenEvictionRunsMillis + */ + private long _timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS; + + /** + * The number of objects to examine during each run of the + * idle object evictor thread (if any). + *

    + * When a negative value is supplied, ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun}) + * tests will be run. I.e., when the value is -n, roughly one nth of the + * idle objects will be tested per run. + * + * @see #setNumTestsPerEvictionRun + * @see #getNumTestsPerEvictionRun + * @see #getTimeBetweenEvictionRunsMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + private int _numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN; + + /** + * The minimum amount of time an object may sit idle in the pool + * before it is eligible for eviction by the idle object evictor + * (if any). + * When non-positive, no objects will be evicted from the pool + * due to idle time alone. + * + * @see #setMinEvictableIdleTimeMillis + * @see #getMinEvictableIdleTimeMillis + * @see #getTimeBetweenEvictionRunsMillis + * @see #setTimeBetweenEvictionRunsMillis + */ + private long _minEvictableIdleTimeMillis = DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS; + + /** My hash of pools (ObjectQueue). */ + private Map _poolMap = null; + + /** The total number of active instances. */ + private int _totalActive = 0; + + /** The total number of idle instances. */ + private int _totalIdle = 0; + + /** + * The number of objects subject to some form of internal processing + * (usually creation or destruction) that should be included in the total + * number of objects but are neither active nor idle. + */ + private int _totalInternalProcessing = 0; + + /** My {@link KeyedPoolableObjectFactory}. */ + private KeyedPoolableObjectFactory _factory = null; + + /** + * My idle object eviction {@link TimerTask}, if any. + */ + private Evictor _evictor = null; + + /** + * A cursorable list of my pools. + * @see GenericKeyedObjectPool.Evictor#run + */ + private CursorableLinkedList _poolList = null; + + /** Eviction cursor (over instances within-key) */ + private CursorableLinkedList.Cursor _evictionCursor = null; + + /** Eviction cursor (over keys) */ + private CursorableLinkedList.Cursor _evictionKeyCursor = null; + + /** Whether or not the pools behave as LIFO queues (last in first out) */ + private boolean _lifo = DEFAULT_LIFO; + + /** + * Used to track the order in which threads call {@link #borrowObject()} so + * that objects can be allocated in the order in which the threads requested + * them. + */ + private LinkedList _allocationQueue = new LinkedList(); + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.commons.pool.impl.GenericKeyedObjectPool.setFactory` indirectly reads without synchronization from `this.org.apache.commons.pool.impl.GenericKeyedObjectPool._factory`. Potentially races with write in method `GenericKeyedObjectPool.setFactory(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GenericKeyedObjectPool.setFactory(KeyedPoolableObjectFactory) + +### Procedure Id: +org.apache.commons.pool.impl.GenericKeyedObjectPool.setFactory(org.apache.commons.pool.KeyedPoolable.b452c2da76947368af8bd6f1d52e640b + +### File: +src/java/org/apache/commons/pool/impl/GenericKeyedObjectPool.java + +### Key: +GenericKeyedObjectPool.java|setFactory|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +b35c37720b61d01147d7e16a15d22450 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3467/instruction.md b/inferredbugs-3467/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..497a605120bb66aa7365a9d86a78e6eeb5e3c88c --- /dev/null +++ b/inferredbugs-3467/instruction.md @@ -0,0 +1,1293 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** Sundial +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright 2001-2009 Terracotta, Inc. + * Copyright 2014 Xeiam, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ +package org.quartz; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import org.quartz.builders.SimpleScheduleBuilder; +import org.quartz.builders.TriggerBuilder; +import org.quartz.classloading.CascadingClassLoadHelper; +import org.quartz.core.Calendar; +import org.quartz.core.JobExecutionContext; +import org.quartz.core.QuartzSchedulerResources; +import org.quartz.core.QuartzSchedulerThread; +import org.quartz.core.Scheduler; +import org.quartz.core.SchedulerSignaler; +import org.quartz.core.SchedulerSignalerImpl; +import org.quartz.exceptions.JobExecutionException; +import org.quartz.exceptions.JobPersistenceException; +import org.quartz.exceptions.ObjectAlreadyExistsException; +import org.quartz.exceptions.SchedulerException; +import org.quartz.jobs.InterruptableJob; +import org.quartz.jobs.Job; +import org.quartz.jobs.JobDataMap; +import org.quartz.jobs.JobDetail; +import org.quartz.jobs.JobFactory; +import org.quartz.jobs.SimpleJobFactory; +import org.quartz.listeners.JobListener; +import org.quartz.listeners.ListenerManager; +import org.quartz.listeners.ListenerManagerImpl; +import org.quartz.listeners.SchedulerListener; +import org.quartz.listeners.SchedulerListenerSupport; +import org.quartz.listeners.TriggerListener; +import org.quartz.plugins.SchedulerPlugin; +import org.quartz.triggers.OperableTrigger; +import org.quartz.triggers.Trigger; +import org.quartz.triggers.Trigger.CompletedExecutionInstruction; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + *

    + * This is the heart of Quartz, an indirect implementation of the {@link org.quartz.core.Scheduler} interface, containing methods to + * schedule {@link org.quartz.jobs.Job}s, register {@link org.quartz.listeners.JobListener} instances, etc. + *

    + * + * @see org.quartz.core.Scheduler + * @see org.quartz.core.QuartzSchedulerThread + * @see org.quartz.core.JobStore + * @see org.quartz.core.ThreadPool + * @author James House + */ +public class QuartzScheduler implements Scheduler { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Data members. + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private final QuartzSchedulerResources quartzSchedulerResources; + + private final QuartzSchedulerThread quartzSchedulerThread; + + private ThreadGroup threadGroup; + + private final ListenerManager listenerManager = new ListenerManagerImpl(); + + private final HashMap internalJobListeners = new HashMap(10); + + private final HashMap internalTriggerListeners = new HashMap(10); + + private final ArrayList internalSchedulerListeners = new ArrayList(10); + + private JobFactory jobFactory = new SimpleJobFactory(); + + private ExecutingJobsManager jobMgr = null; + + private ErrorLogger errLogger = null; + + private final SchedulerSignaler signaler; + + private final Random random = new Random(); + + private final ArrayList holdToPreventGC = new ArrayList(5); + + private boolean signalOnSchedulingChange = true; + + private volatile boolean closed = false; + + private volatile boolean shuttingDown = false; + + private Date initialStart = null; + + CascadingClassLoadHelper cascadingClassLoadHelper = new CascadingClassLoadHelper(); + + private final Logger logger = LoggerFactory.getLogger(QuartzScheduler.class); + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Constructors. + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

    + * Create a QuartzScheduler with the given configuration properties. + *

    + * + * @see QuartzSchedulerResources + */ + public QuartzScheduler(QuartzSchedulerResources quartzSchedulerResources) throws SchedulerException { + + this.quartzSchedulerResources = quartzSchedulerResources; + if (quartzSchedulerResources.getJobStore() instanceof JobListener) { + addInternalJobListener((JobListener) quartzSchedulerResources.getJobStore()); + } + + this.quartzSchedulerThread = new QuartzSchedulerThread(this, quartzSchedulerResources); + + jobMgr = new ExecutingJobsManager(); + addInternalJobListener(jobMgr); + errLogger = new ErrorLogger(); + addInternalSchedulerListener(errLogger); + + signaler = new SchedulerSignalerImpl(this, this.quartzSchedulerThread); + + cascadingClassLoadHelper.initialize(); + } + + public void initialize() throws SchedulerException { + + this.quartzSchedulerThread.start(); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Interface. + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public SchedulerSignaler getSchedulerSignaler() { + + return signaler; + } + + /** + *

    + * Returns the name of the thread group for Quartz's main threads. + *

    + */ + public ThreadGroup getSchedulerThreadGroup() { + + if (threadGroup == null) { + threadGroup = new ThreadGroup("QuartzScheduler"); + if (quartzSchedulerResources.getMakeSchedulerThreadDaemon()) { + threadGroup.setDaemon(true); + } + } + + return threadGroup; + } + + public boolean isSignalOnSchedulingChange() { + + return signalOnSchedulingChange; + } + + public void setSignalOnSchedulingChange(boolean signalOnSchedulingChange) { + + this.signalOnSchedulingChange = signalOnSchedulingChange; + } + + // ///////////////////////////////////////////////////////////////////////// + // / + // / Scheduler State Management Methods + // / + // ///////////////////////////////////////////////////////////////////////// + + /** + *

    + * Starts the QuartzScheduler's threads that fire {@link org.quartz.triggers.Trigger}s. + *

    + *

    + * All {@link org.quartz.triggers.Trigger}s that have misfired will be passed to the appropriate TriggerListener(s). + *

    + */ + @Override + public void start() throws SchedulerException { + + if (shuttingDown || closed) { + throw new SchedulerException("The Scheduler cannot be restarted after shutdown() has been called."); + } + + if (initialStart == null) { + initialStart = new Date(); + quartzSchedulerResources.getJobStore().schedulerStarted(); + startPlugins(); + } + + this.quartzSchedulerThread.togglePause(false); + + logger.info("Scheduler started."); + + notifySchedulerListenersStarted(); + } + + @Override + public void startDelayed(final int seconds) throws SchedulerException { + + Thread t = new Thread(new Runnable() { + + @Override + public void run() { + + try { + Thread.sleep(seconds * 1000L); + } catch (InterruptedException ignore) { + } + try { + start(); + } catch (SchedulerException se) { + logger.error("Unable to start secheduler after startup delay.", se); + } + } + }); + t.start(); + } + + /** + *

    + * Temporarily halts the QuartzScheduler's firing of {@link org.quartz.triggers.Trigger}s. + *

    + *

    + * The scheduler is not destroyed, and can be re-started at any time. + *

    + */ + @Override + public void standby() { + + this.quartzSchedulerThread.togglePause(true); + logger.info("Scheduler paused."); + notifySchedulerListenersInStandbyMode(); + } + + /** + *

    + * Reports whether the Scheduler is paused. + *

    + */ + @Override + public boolean isInStandbyMode() { + + return this.quartzSchedulerThread.isPaused(); + } + + public Class getJobStoreClass() { + + return quartzSchedulerResources.getJobStore().getClass(); + } + + public Class getThreadPoolClass() { + + return quartzSchedulerResources.getThreadPool().getClass(); + } + + public int getThreadPoolSize() { + + return quartzSchedulerResources.getThreadPool().getPoolSize(); + } + + /** + *

    + * Halts the QuartzScheduler's firing of {@link org.quartz.triggers.Trigger}s, and cleans up all resources associated with + * the QuartzScheduler. + *

    + *

    + * The scheduler cannot be re-started. + *

    + * + * @param waitForJobsToComplete if true the scheduler will not allow this method to return until all currently executing jobs have + * completed. + */ + @Override + public void shutdown(boolean waitForJobsToComplete) { + + if (shuttingDown || closed) { + return; + } + + shuttingDown = true; + + logger.info("Scheduler shutting down..."); + + standby(); + + this.quartzSchedulerThread.halt(); + + notifySchedulerListenersShuttingdown(); + + if ((quartzSchedulerResources.isInterruptJobsOnShutdown() && !waitForJobsToComplete) + || (quartzSchedulerResources.isInterruptJobsOnShutdownWithWait() && waitForJobsToComplete)) { + List jobs = getCurrentlyExecutingJobs(); + for (JobExecutionContext job : jobs) { + if (job.getJobInstance() instanceof InterruptableJob) { + try { + ((InterruptableJob) job.getJobInstance()).interrupt(); + } catch (Throwable e) { + // do nothing, this was just a courtesy effort + logger.warn("Encountered error when interrupting job {} during shutdown: {}", job.getJobDetail().getName(), e); + } + } + } + } + + quartzSchedulerResources.getThreadPool().shutdown(waitForJobsToComplete); + + if (waitForJobsToComplete) { + while (jobMgr.getNumJobsCurrentlyExecuting() > 0) { + try { + Thread.sleep(100); + } catch (Exception ignore) { + } + } + } + + // Scheduler thread may have be waiting for the fire time of an acquired + // trigger and need time to release the trigger once halted, so make sure + // the thread is dead before continuing to shutdown the job store. + try { + this.quartzSchedulerThread.join(); + } catch (InterruptedException ignore) { + } + + closed = true; + + shutdownPlugins(); + + notifySchedulerListenersShutdown(); + + holdToPreventGC.clear(); + + logger.info("Scheduler shutdown complete."); + } + + /** + *

    + * Reports whether the Scheduler has been shutdown. + *

    + */ + @Override + public boolean isShutdown() { + + return closed; + } + + public boolean isShuttingDown() { + + return shuttingDown; + } + + @Override + public boolean isStarted() { + + return !shuttingDown && !closed && !isInStandbyMode() && initialStart != null; + } + + private void validateState() throws SchedulerException { + + if (isShutdown()) { + throw new SchedulerException("The Scheduler has been shutdown."); + } + + // other conditions to check (?) + } + + /** + *

    + * Return a list of JobExecutionContext objects that represent all currently executing Jobs in this Scheduler instance. + *

    + *

    + * This method is not cluster aware. That is, it will only return Jobs currently executing in this Scheduler instance, not across the entire + * cluster. + *

    + *

    + * Note that the list returned is an 'instantaneous' snap-shot, and that as soon as it's returned, the true list of executing jobs may be different. + *

    + */ + @Override + public List getCurrentlyExecutingJobs() { + + return jobMgr.getExecutingJobs(); + } + + // ///////////////////////////////////////////////////////////////////////// + // / + // / Scheduling-related Methods + // / + // ///////////////////////////////////////////////////////////////////////// + + /** + *

    + * Add the {@link org.quartz.jobs.Job} identified by the given {@link org.quartz.jobs.JobDetail} to the Scheduler, and + * associate the given {@link org.quartz.triggers.Trigger} with it. + *

    + *

    + * If the given Trigger does not reference any Job, then it will be set to reference the Job passed with it into this method. + *

    + * + * @throws SchedulerException if the Job or Trigger cannot be added to the Scheduler, or there is an internal Scheduler error. + */ + @Override + public Date scheduleJob(JobDetail jobDetail, OperableTrigger trigger) throws SchedulerException { + + validateState(); + + if (jobDetail == null) { + throw new SchedulerException("JobDetail cannot be null"); + } + + if (trigger == null) { + throw new SchedulerException("Trigger cannot be null"); + } + + if (jobDetail.getName() == null) { + throw new SchedulerException("Job's key cannot be null"); + } + + if (jobDetail.getJobClass() == null) { + throw new SchedulerException("Job's class cannot be null"); + } + + OperableTrigger trig = trigger; + + if (trigger.getJobName() == null) { + trig.setJobName(jobDetail.getName()); + } else if (!trigger.getJobName().equals(jobDetail.getName())) { + throw new SchedulerException("Trigger does not reference given job!"); + } + + trig.validate(); + + Calendar cal = null; + if (trigger.getCalendarName() != null) { + cal = quartzSchedulerResources.getJobStore().retrieveCalendar(trigger.getCalendarName()); + } + Date ft = trig.computeFirstFireTime(cal); + + if (ft == null) { + throw new SchedulerException("Based on configured schedule, the given trigger will never fire."); + } + + quartzSchedulerResources.getJobStore().storeJobAndTrigger(jobDetail, trig); + notifySchedulerListenersJobAdded(jobDetail); + notifySchedulerThread(trigger.getNextFireTime().getTime()); + notifySchedulerListenersScheduled(trigger); + + return ft; + } + + /** + *

    + * Schedule the given {@link org.quartz.triggers.Trigger} with the Job identified by the Trigger's settings. + *

    + * + * @throws SchedulerException if the indicated Job does not exist, or the Trigger cannot be added to the Scheduler, or there is an internal + * Scheduler error. + */ + + @Override + public Date scheduleJob(OperableTrigger trigger) throws SchedulerException { + + validateState(); + + if (trigger == null) { + throw new SchedulerException("Trigger cannot be null"); + } + + OperableTrigger trig = trigger; + + trig.validate(); + + Calendar cal = null; + if (trigger.getCalendarName() != null) { + cal = quartzSchedulerResources.getJobStore().retrieveCalendar(trigger.getCalendarName()); + if (cal == null) { + throw new SchedulerException("Calendar not found: " + trigger.getCalendarName()); + } + } + Date ft = trig.computeFirstFireTime(cal); + + if (ft == null) { + throw new SchedulerException("Based on configured schedule, the given trigger will never fire."); + } + + quartzSchedulerResources.getJobStore().storeTrigger(trig, false); + notifySchedulerThread(trigger.getNextFireTime().getTime()); + notifySchedulerListenersScheduled(trigger); + + return ft; + } + + /** + *

    + * Add the given Job to the Scheduler - with no associated Trigger. The Job will be 'dormant' until it is + * scheduled with a Trigger, or Scheduler.triggerJob() is called for it. + *

    + */ + @Override + public void addJob(JobDetail jobDetail) throws SchedulerException { + + validateState(); + + quartzSchedulerResources.getJobStore().storeJob(jobDetail, true); + notifySchedulerThread(0L); + notifySchedulerListenersJobAdded(jobDetail); + } + + @Override + public void deleteJob(String jobKey) throws SchedulerException { + + validateState(); + + List triggers = getTriggersOfJob(jobKey); + for (Trigger trigger : triggers) { + unscheduleJob(trigger.getName()); + } + boolean result = quartzSchedulerResources.getJobStore().removeJob(jobKey); + if (result) { + notifySchedulerThread(0L); + notifySchedulerListenersJobDeleted(jobKey); + } + } + + @Override + public void unscheduleJob(String triggerKey) throws SchedulerException { + + validateState(); + + if (quartzSchedulerResources.getJobStore().removeTrigger(triggerKey)) { + notifySchedulerThread(0L); + notifySchedulerListenersUnscheduled(triggerKey); + } + } + + @Override + public Date rescheduleJob(String triggerKey, OperableTrigger newTrigger) throws SchedulerException { + + validateState(); + + if (triggerKey == null) { + throw new IllegalArgumentException("triggerKey cannot be null"); + } + if (newTrigger == null) { + throw new IllegalArgumentException("newTrigger cannot be null"); + } + + OperableTrigger trig = newTrigger; + Trigger oldTrigger = getTrigger(triggerKey); + if (oldTrigger == null) { + return null; + } else { + trig.setJobName(oldTrigger.getJobName()); + } + trig.validate(); + + Calendar cal = null; + if (newTrigger.getCalendarName() != null) { + cal = quartzSchedulerResources.getJobStore().retrieveCalendar(newTrigger.getCalendarName()); + } + Date ft = trig.computeFirstFireTime(cal); + + if (ft == null) { + throw new SchedulerException("Based on configured schedule, the given trigger will never fire."); + } + + if (quartzSchedulerResources.getJobStore().replaceTrigger(triggerKey, trig)) { + notifySchedulerThread(newTrigger.getNextFireTime().getTime()); + notifySchedulerListenersUnscheduled(triggerKey); + notifySchedulerListenersScheduled(newTrigger); + } else { + return null; + } + + return ft; + + } + + private String newTriggerId() { + + long r = random.nextLong(); + if (r < 0) { + r = -r; + } + return "MT_" + Long.toString(r, 30 + (int) (System.currentTimeMillis() % 7)); + } + + /** + *

    + * Trigger the identified {@link org.quartz.jobs.Job} (execute it now) - with a non-volatile trigger. + *

    + */ + @Override + public void triggerJob(String jobKey, JobDataMap data) throws SchedulerException { + + validateState(); + + OperableTrigger operableTrigger = TriggerBuilder.newTriggerBuilder().withIdentity(jobKey + "-trigger").forJob(jobKey) + .withTriggerImplementation(SimpleScheduleBuilder.simpleScheduleBuilderBuilder().build()).startAt(new Date()).build(); + + // TODO what does this accomplish??? Seems to sets it's next fire time internally + operableTrigger.computeFirstFireTime(null); + + if (data != null) { + operableTrigger.setJobDataMap(data); + } + + boolean collision = true; + while (collision) { + try { + quartzSchedulerResources.getJobStore().storeTrigger(operableTrigger, false); + collision = false; + } catch (ObjectAlreadyExistsException oaee) { + operableTrigger.setName(newTriggerId()); + } + } + + notifySchedulerThread(operableTrigger.getNextFireTime().getTime()); + notifySchedulerListenersScheduled(operableTrigger); + } + + /** + *

    + * Get all {@link Trigger} s that are associated with the identified {@link org.quartz.jobs.JobDetail}. + *

    + */ + + @Override + public List getTriggersOfJob(String jobKey) throws SchedulerException { + + validateState(); + + return quartzSchedulerResources.getJobStore().getTriggersForJob(jobKey); + } + + /** + *

    + * Get the {@link JobDetail} for the Job instance with the given name and group. + *

    + */ + @Override + public JobDetail getJobDetail(String jobKey) throws SchedulerException { + + validateState(); + + return quartzSchedulerResources.getJobStore().retrieveJob(jobKey); + } + + /** + *

    + * Get the {@link Trigger} instance with the given name and group. + *

    + */ + + @Override + public Trigger getTrigger(String triggerKey) throws SchedulerException { + + validateState(); + + return quartzSchedulerResources.getJobStore().retrieveTrigger(triggerKey); + } + + /** + * Clears (deletes!) all scheduling data - all {@link Job}s, {@link Trigger}s {@link Calendar}s. + * + * @throws SchedulerException + */ + + @Override + public ListenerManager getListenerManager() { + + return listenerManager; + } + + /** + *

    + * Add the given {@link org.quartz.listeners.JobListener} to the Scheduler's internal list. + *

    + */ + private void addInternalJobListener(JobListener jobListener) { + + if (jobListener.getName() == null || jobListener.getName().length() == 0) { + throw new IllegalArgumentException("JobListener name cannot be empty."); + } + + synchronized (internalJobListeners) { + internalJobListeners.put(jobListener.getName(), jobListener); + } + } + + /** + *

    + * Get a List containing all of the {@link org.quartz.listeners.JobListener}s in the Scheduler's internal list. + *

    + */ + public List getInternalJobListeners() { + + synchronized (internalJobListeners) { + return java.util.Collections.unmodifiableList(new LinkedList(internalJobListeners.values())); + } + } + + /** + *

    + * Get a list containing all of the {@link org.quartz.listeners.TriggerListener}s in the Scheduler's internal list. + *

    + */ + public List getInternalTriggerListeners() { + + synchronized (internalTriggerListeners) { + return java.util.Collections.unmodifiableList(new LinkedList(internalTriggerListeners.values())); + } + } + + /** + *

    + * Register the given {@link SchedulerListener} with the Scheduler's list of internal listeners. + *

    + */ + public void addInternalSchedulerListener(SchedulerListener schedulerListener) { + + synchronized (internalSchedulerListeners) { + internalSchedulerListeners.add(schedulerListener); + } + } + + /** + *

    + * Remove the given {@link SchedulerListener} from the Scheduler's list of internal listeners. + *

    + * + * @return true if the identified listener was found in the list, and removed. + */ + public boolean removeInternalSchedulerListener(SchedulerListener schedulerListener) { + + synchronized (internalSchedulerListeners) { + return internalSchedulerListeners.remove(schedulerListener); + } + } + + /** + *

    + * Get a List containing all of the internal {@link SchedulerListener}s registered with the Scheduler. + *

    + */ + public List getInternalSchedulerListeners() { + + synchronized (internalSchedulerListeners) { + return java.util.Collections.unmodifiableList(new ArrayList(internalSchedulerListeners)); + } + } + + public void notifyJobStoreJobComplete(OperableTrigger trigger, JobDetail detail, CompletedExecutionInstruction instCode) + throws JobPersistenceException { + + quartzSchedulerResources.getJobStore().triggeredJobComplete(trigger, detail, instCode); + } + + public void notifyJobStoreJobVetoed(OperableTrigger trigger, JobDetail detail, CompletedExecutionInstruction instCode) + throws JobPersistenceException { + + quartzSchedulerResources.getJobStore().triggeredJobComplete(trigger, detail, instCode); + } + + private void notifySchedulerThread(long candidateNewNextFireTime) { + + if (isSignalOnSchedulingChange()) { + signaler.signalSchedulingChange(candidateNewNextFireTime); + } + } + + private List buildTriggerListenerList() throws SchedulerException { + + List allListeners = new LinkedList(); + allListeners.addAll(getListenerManager().getTriggerListeners()); + allListeners.addAll(getInternalTriggerListeners()); + + return allListeners; + } + + private List buildJobListenerList() throws SchedulerException { + + List allListeners = new LinkedList(); + allListeners.addAll(getListenerManager().getJobListeners()); + allListeners.addAll(getInternalJobListeners()); + + return allListeners; + } + + private List buildSchedulerListenerList() { + + List allListeners = new LinkedList(); + allListeners.addAll(getListenerManager().getSchedulerListeners()); + allListeners.addAll(getInternalSchedulerListeners()); + + return allListeners; + } + + public boolean notifyTriggerListenersFired(JobExecutionContext jec) throws SchedulerException { + + boolean vetoedExecution = false; + + // build a list of all trigger listeners that are to be notified... + List triggerListeners = buildTriggerListenerList(); + + // notify all trigger listeners in the list + for (TriggerListener tl : triggerListeners) { + try { + tl.triggerFired(jec.getTrigger(), jec); + + if (tl.vetoJobExecution(jec.getTrigger(), jec)) { + vetoedExecution = true; + } + } catch (Exception e) { + SchedulerException se = new SchedulerException("TriggerListener '" + tl.getName() + "' threw exception: " + e.getMessage(), e); + throw se; + } + } + + return vetoedExecution; + } + + public void notifyTriggerListenersMisfired(Trigger trigger) throws SchedulerException { + + // build a list of all trigger listeners that are to be notified... + List triggerListeners = buildTriggerListenerList(); + + // notify all trigger listeners in the list + for (TriggerListener tl : triggerListeners) { + try { + tl.triggerMisfired(trigger); + } catch (Exception e) { + SchedulerException se = new SchedulerException("TriggerListener '" + tl.getName() + "' threw exception: " + e.getMessage(), e); + throw se; + } + } + } + + public void notifyTriggerListenersComplete(JobExecutionContext jec, CompletedExecutionInstruction instCode) throws SchedulerException { + + // build a list of all trigger listeners that are to be notified... + List triggerListeners = buildTriggerListenerList(); + + // notify all trigger listeners in the list + for (TriggerListener tl : triggerListeners) { + try { + tl.triggerComplete(jec.getTrigger(), jec, instCode); + } catch (Exception e) { + SchedulerException se = new SchedulerException("TriggerListener '" + tl.getName() + "' threw exception: " + e.getMessage(), e); + throw se; + } + } + } + + public void notifyJobListenersToBeExecuted(JobExecutionContext jec) throws SchedulerException { + + // build a list of all job listeners that are to be notified... + List jobListeners = buildJobListenerList(); + + // notify all job listeners + for (JobListener jl : jobListeners) { + try { + jl.jobToBeExecuted(jec); + } catch (Exception e) { + SchedulerException se = new SchedulerException("JobListener '" + jl.getName() + "' threw exception: " + e.getMessage(), e); + throw se; + } + } + } + + public void notifyJobListenersWasVetoed(JobExecutionContext jec) throws SchedulerException { + + // build a list of all job listeners that are to be notified... + List jobListeners = buildJobListenerList(); + + // notify all job listeners + for (JobListener jl : jobListeners) { + try { + jl.jobExecutionVetoed(jec); + } catch (Exception e) { + SchedulerException se = new SchedulerException("JobListener '" + jl.getName() + "' threw exception: " + e.getMessage(), e); + throw se; + } + } + } + + public void notifyJobListenersWasExecuted(JobExecutionContext jec, JobExecutionException je) throws SchedulerException { + + // build a list of all job listeners that are to be notified... + List jobListeners = buildJobListenerList(); + + // notify all job listeners + for (JobListener jl : jobListeners) { + try { + jl.jobWasExecuted(jec, je); + } catch (Exception e) { + SchedulerException se = new SchedulerException("JobListener '" + jl.getName() + "' threw exception: " + e.getMessage(), e); + throw se; + } + } + } + + public void notifySchedulerListenersError(String msg, SchedulerException se) { + + // build a list of all scheduler listeners that are to be notified... + List schedListeners = buildSchedulerListenerList(); + + // notify all scheduler listeners + for (SchedulerListener sl : schedListeners) { + try { + sl.schedulerError(msg, se); + } catch (Exception e) { + logger.error("Error while notifying SchedulerListener of error: ", e); + logger.error(" Original error (for notification) was: " + msg, se); + } + } + } + + private void notifySchedulerListenersScheduled(Trigger trigger) { + + // build a list of all scheduler listeners that are to be notified... + List schedListeners = buildSchedulerListenerList(); + + // notify all scheduler listeners + for (SchedulerListener sl : schedListeners) { + try { + sl.jobScheduled(trigger); + } catch (Exception e) { + logger.error("Error while notifying SchedulerListener of scheduled job." + " Triger=" + trigger.getName(), e); + } + } + } + + private void notifySchedulerListenersUnscheduled(String triggerKey) { + + // build a list of all scheduler listeners that are to be notified... + List schedListeners = buildSchedulerListenerList(); + + // notify all scheduler listeners + for (SchedulerListener sl : schedListeners) { + try { + if (triggerKey == null) { + sl.schedulingDataCleared(); + } else { + sl.jobUnscheduled(triggerKey); + } + } catch (Exception e) { + logger.error("Error while notifying SchedulerListener of unscheduled job." + " Triger=" + (triggerKey == null ? "ALL DATA" : triggerKey), e); + } + } + } + + public void notifySchedulerListenersFinalized(Trigger trigger) { + + // build a list of all scheduler listeners that are to be notified... + List schedListeners = buildSchedulerListenerList(); + + // notify all scheduler listeners + for (SchedulerListener sl : schedListeners) { + try { + sl.triggerFinalized(trigger); + } catch (Exception e) { + logger.error("Error while notifying SchedulerListener of finalized trigger." + " Triger=" + trigger.getName(), e); + } + } + } + + private void notifySchedulerListenersInStandbyMode() { + + // build a list of all scheduler listeners that are to be notified... + List schedListeners = buildSchedulerListenerList(); + + // notify all scheduler listeners + for (SchedulerListener sl : schedListeners) { + try { + sl.schedulerInStandbyMode(); + } catch (Exception e) { + logger.error("Error while notifying SchedulerListener of inStandByMode.", e); + } + } + } + + private void notifySchedulerListenersStarted() { + + // build a list of all scheduler listeners that are to be notified... + List schedListeners = buildSchedulerListenerList(); + + // notify all scheduler listeners + for (SchedulerListener sl : schedListeners) { + try { + sl.schedulerStarted(); + } catch (Exception e) { + logger.error("Error while notifying SchedulerListener of startup.", e); + } + } + } + + private void notifySchedulerListenersShutdown() { + + // build a list of all scheduler listeners that are to be notified... + List schedListeners = buildSchedulerListenerList(); + + // notify all scheduler listeners + for (SchedulerListener sl : schedListeners) { + try { + sl.schedulerShutdown(); + } catch (Exception e) { + logger.error("Error while notifying SchedulerListener of shutdown.", e); + } + } + } + + private void notifySchedulerListenersShuttingdown() { + + // build a list of all scheduler listeners that are to be notified... + List schedListeners = buildSchedulerListenerList(); + + // notify all scheduler listeners + for (SchedulerListener sl : schedListeners) { + try { + sl.schedulerShuttingdown(); + } catch (Exception e) { + logger.error("Error while notifying SchedulerListener of shutdown.", e); + } + } + } + + private void notifySchedulerListenersJobAdded(JobDetail jobDetail) { + + // build a list of all scheduler listeners that are to be notified... + List schedListeners = buildSchedulerListenerList(); + + // notify all scheduler listeners + for (SchedulerListener sl : schedListeners) { + try { + sl.jobAdded(jobDetail); + } catch (Exception e) { + logger.error("Error while notifying SchedulerListener of JobAdded.", e); + } + } + } + + public void notifySchedulerListenersJobDeleted(String jobKey) { + + // build a list of all scheduler listeners that are to be notified... + List schedListeners = buildSchedulerListenerList(); + + // notify all scheduler listeners + for (SchedulerListener sl : schedListeners) { + try { + sl.jobDeleted(jobKey); + } catch (Exception e) { + logger.error("Error while notifying SchedulerListener of JobAdded.", e); + } + } + } + + public JobFactory getJobFactory() { + + return jobFactory; + } + + private void shutdownPlugins() { + + java.util.Iterator itr = quartzSchedulerResources.getSchedulerPlugins().iterator(); + while (itr.hasNext()) { + SchedulerPlugin plugin = (SchedulerPlugin) itr.next(); + plugin.shutdown(); + } + } + + private void startPlugins() { + + java.util.Iterator itr = quartzSchedulerResources.getSchedulerPlugins().iterator(); + while (itr.hasNext()) { + SchedulerPlugin plugin = (SchedulerPlugin) itr.next(); + plugin.start(); + } + } + + @Override + public CascadingClassLoadHelper getCascadingClassLoadHelper() { + return this.cascadingClassLoadHelper; + } + + /** + *

    + * Get the names of all the {@link org.quartz.jobs.Job}s in the matching groups. + *

    + */ + + @Override + public Set getJobKeys() throws SchedulerException { + + validateState(); + + return quartzSchedulerResources.getJobStore().getJobKeys(); + } + +} + +// /////////////////////////////////////////////////////////////////////////// +// +// ErrorLogger - Scheduler Listener Class +// +// /////////////////////////////////////////////////////////////////////////// + +class ErrorLogger extends SchedulerListenerSupport { + + private final Logger logger = LoggerFactory.getLogger(ErrorLogger.class); + + /** + * Constructor + */ + ErrorLogger() { + + } + + @Override + public void schedulerError(String msg, SchedulerException cause) { + + logger.error(msg, cause); + } + +} + +// /////////////////////////////////////////////////////////////////////////// +// +// ExecutingJobsManager - Job Listener Class +// +// /////////////////////////////////////////////////////////////////////////// + +class ExecutingJobsManager implements JobListener { + + private HashMap executingJobs = new HashMap(); + + private AtomicInteger numJobsFired = new AtomicInteger(0); + + ExecutingJobsManager() { + + } + + @Override + public String getName() { + + return getClass().getName(); + } + + public int getNumJobsCurrentlyExecuting() { + + synchronized (executingJobs) { + return executingJobs.size(); + } + } + + @Override + public void jobToBeExecuted(JobExecutionContext context) { + + numJobsFired.incrementAndGet(); + + synchronized (executingJobs) { + executingJobs.put(((OperableTrigger) context.getTrigger()).getFireInstanceId(), context); + } + } + + @Override + public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) { + + synchronized (executingJobs) { + executingJobs.remove(((OperableTrigger) context.getTrigger()).getFireInstanceId()); + } + } + + public int getNumJobsFired() { + + return numJobsFired.get(); + } + + public List getExecutingJobs() { + + synchronized (executingJobs) { + return java.util.Collections.unmodifiableList(new ArrayList(executingJobs.values())); + } + } + + @Override + public void jobExecutionVetoed(JobExecutionContext context) { + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `operableTrigger.getNextFireTime()` could be null and is dereferenced at line 646. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void QuartzScheduler.triggerJob(String,JobDataMap) + +### Procedure Id: +org.quartz.QuartzScheduler.triggerJob(java.lang.String,org.quartz.jobs.JobDataMap):void.17559b29973a15de37967a49549624d2 + +### File: +src/main/java/org/quartz/QuartzScheduler.java + +### Key: +QuartzScheduler.java|triggerJob|NULL_DEREFERENCE + +### Node Key: +20a35cb35a7b0d8f02a62e464233ebb8 + +### Hash: +cd40a83fe3ddf32fa1a27988cc6354dc + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3469/instruction.md b/inferredbugs-3469/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eab6196d5ccb88d05d502a8579a61c2a1ba1fb99 --- /dev/null +++ b/inferredbugs-3469/instruction.md @@ -0,0 +1,171 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** seyren +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.seyren.core.service.notification; + +import static java.lang.String.*; + +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.net.Socket; +import java.util.Arrays; +import java.util.List; + +import javax.inject.Inject; +import javax.inject.Named; + +import org.slf4j.LoggerFactory; + +import com.google.common.io.Closeables; +import com.seyren.core.domain.Alert; +import com.seyren.core.domain.AlertType; +import com.seyren.core.domain.Check; +import com.seyren.core.domain.Subscription; +import com.seyren.core.domain.SubscriptionType; +import com.seyren.core.exception.NotificationFailedException; +import com.seyren.core.util.config.SeyrenConfig; + +@Named +public class IrcCatNotificationService implements NotificationService { + + private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(IrcCatNotificationService.class); + + private final SeyrenConfig seyrenConfig; + + @Inject + public IrcCatNotificationService(SeyrenConfig seyrenConfig) { + this.seyrenConfig = seyrenConfig; + } + + @Override + public void sendNotification(Check check, Subscription subscription, List alerts) throws NotificationFailedException { + List channels = Arrays.asList(subscription.getTarget().split(",")); + try { + for (String channel : channels) { + String message = createMessage(check); + sendMessage(seyrenConfig.getIrcCatHost(), seyrenConfig.getIrcCatPort(), message, channel); + } + } catch (IOException ioe) { + throw new NotificationFailedException("Could not send message", ioe); + } + } + + private String createMessage(Check check) { + String checkUrl = seyrenConfig.getBaseUrl() + "/#/checks/" + check.getId(); + + if (check.getState() == AlertType.ERROR) { + return format("%%RED[CRIT]%%NORMAL %s | Please check %s.", check.getName(), checkUrl); + } + if (check.getState() == AlertType.WARN) { + return format("%%YELLOW[WARN]%%NORMAL %s | Please check %s.", check.getName(), checkUrl); + } + if (check.getState() == AlertType.OK) { + return format("%%GREEN[OK]%%NORMAL %s | %s", check.getName(), checkUrl); + } + + LOGGER.info("Unmanaged check state [%s] for check [%s]", check.getState(), check.getName()); + return ""; + } + + private void sendMessage(String ircCatHost, int ircCatPort, String message, String channel) throws IOException { + Socket socket = new Socket(ircCatHost, ircCatPort); + Writer out = new OutputStreamWriter(socket.getOutputStream()); + try { + out.write(format("%s %s\n", channel, message)); + out.flush(); + } catch (IOException e) { + Closeables.closeQuietly(out); + socket.close(); + } + } + + @Override + public boolean canHandle(SubscriptionType subscriptionType) { + return subscriptionType == SubscriptionType.IRCCAT; + } + +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.net.Socket` acquired to `socket` by call to `new()` at line 82 is not released after line 91. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void IrcCatNotificationService.sendMessage(String,int,String,String) + +### Procedure Id: +com.seyren.core.service.notification.IrcCatNotificationService.sendMessage(java.lang.String,int,java.cc6abd50aa7643e3566eed2b3e7a252d + +### File: +seyren-core/src/main/java/com/seyren/core/service/notification/IrcCatNotificationService.java + +### Key: +IrcCatNotificationService.java|sendMessage|RESOURCE_LEAK + +### Node Key: +4b85ce29b197b846c1d2f9bceaeca227 + +### Hash: +c88b9635e46e6c36a1e8d3165a0a4b4b + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3493/instruction.md b/inferredbugs-3493/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6938284dc31861200579db88e70e5442091c6712 --- /dev/null +++ b/inferredbugs-3493/instruction.md @@ -0,0 +1,171 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** unipop +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.tinkerpop.gremlin.elastic.elastic; + + +import com.tinkerpop.gremlin.elastic.elasticservice.DefaultSchemaProvider; +import com.tinkerpop.gremlin.elastic.elasticservice.ElasticService; +import com.tinkerpop.gremlin.elastic.structure.ElasticGraph; +import com.tinkerpop.gremlin.elastic.elasticservice.TimingAccessor; +import com.tinkerpop.gremlin.process.T; +import com.tinkerpop.gremlin.process.graph.GraphTraversal; +import com.tinkerpop.gremlin.process.graph.step.filter.GroovyHasNotTest; +import com.tinkerpop.gremlin.process.graph.step.filter.GroovyHasTest; +import com.tinkerpop.gremlin.structure.*; +import org.apache.commons.configuration.BaseConfiguration; +import org.junit.Test; + +import java.io.IOException; +import java.util.Iterator; + +public class PerformanceTests { + + TimingAccessor sw = new TimingAccessor(); + + + @Test + public void hasNot() throws IOException { + BaseConfiguration config = new BaseConfiguration(); + config.addProperty(Graph.GRAPH, ElasticGraph.class.getName()); + config.addProperty("elasticsearch.cluster.name", "test2"); + String indexName = "graph2"; + config.addProperty("elasticsearch.index.name", indexName.toLowerCase()); + config.addProperty("elasticsearch.local", true); + config.addProperty("elasticsearch.refresh", true); + config.addProperty("elasticsearch.client", "NODE"); + ElasticGraph graph = new ElasticGraph(config); + ((DefaultSchemaProvider)graph.elasticService.schemaProvider).clearAllData(); + Vertex vertex = graph.addVertex(T.label, "test_doc", T.id, "1", "name", "eliran", "age", 24); + Vertex vertex1 = graph.addVertex(T.label, "test_doc", T.id, "2", "name", "ran"); + Vertex vertex2 = graph.addVertex(T.label, "test_doc", T.id, "3", "name", "chiko"); + Vertex vertex3 = graph.addVertex(T.label, "test_doc", T.id, "4", "name", "medico"); + vertex2.addEdge("heardof",vertex,T.id,"111"); + vertex.addEdge("knows",vertex1); + vertex.addEdge("heardof",vertex3); + //graph.V("1").outE("heardof").next(); + //vertex1.addEdge("knows",vertex); + Element knows = graph.E("111").has(T.label, "heardof").next(); + + Object out = graph.V("1").out().next(); + Object in = graph.V("1").in().next(); + int i=1; + + } + + @Test + public void profile() throws IOException { + BaseConfiguration config = new BaseConfiguration(); + config.addProperty(Graph.GRAPH, ElasticGraph.class.getName()); + config.addProperty("elasticsearch.cluster.name", "test"); + config.addProperty("elasticsearch.index.name", "graph"); + config.addProperty("elasticsearch.refresh", true); + config.addProperty("elasticsearch.client", ElasticService.ClientType.NODE.toString()); + + startWatch("graph initalization"); + ElasticGraph graph = new ElasticGraph(config); + stopWatch("graph initalization"); + + startWatch("add vertices"); + int count = 10000; + for(int i = 0; i < count; i++) + graph.addVertex(); + stopWatch("add vertices"); + + startWatch("vertex iterator"); + Iterator vertexIterator = graph.iterators().vertexIterator(); + stopWatch("vertex iterator"); + + startWatch("add edges"); + vertexIterator.forEachRemaining(v -> v.addEdge("bla", v)); + stopWatch("add edges"); + + startWatch("edge iterator"); + Iterator edgeIterator = graph.iterators().edgeIterator(); + stopWatch("edge iterator"); + + sw.print(); + System.out.println("-----"); + graph.elasticService.collectData(); + graph.close(); + } + + private void stopWatch(String s) { + sw.timer(s).stop(); + } + + private void startWatch(String s) { + sw.timer(s).start(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.tinkerpop.gremlin.elastic.structure.ElasticGraph` acquired to `graph` by call to `new()` at line 34 is not released after line 48. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PerformanceTests.hasNot() + +### Procedure Id: +com.tinkerpop.gremlin.elastic.elastic.PerformanceTests.hasNot():void.3bd0884315f13a3ac01c7f22267b9d2d + +### File: +src/test/java/com/tinkerpop/gremlin/elastic/elastic/PerformanceTests.java + +### Key: +PerformanceTests.java|hasNot|RESOURCE_LEAK + +### Node Key: +80def7de1b9b2eab43000521da4f4111 + +### Hash: +154ac571bec6a8f97774cc1f9019d0a5 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3494/instruction.md b/inferredbugs-3494/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f92feb1c71df325b7ac4f4fe22f3a1053b60fcc0 --- /dev/null +++ b/inferredbugs-3494/instruction.md @@ -0,0 +1,157 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** SpringCloud +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.springboot.cloud.gateway.filter; + +import com.springboot.cloud.auth.client.service.IAuthService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * 请求url权限校验 + */ +@Configuration +@ComponentScan(basePackages = "com.springboot.cloud.auth.client") +@Slf4j +public class AccessGatewayFilter implements GlobalFilter { + + private final static String X_CLIENT_TOKEN_USER = "x-client-token-user"; + private final static String X_CLIENT_TOKEN = "x-client-token"; + private static final String BEARER = "Bearer"; + /** + * 由authentication-client模块提供签权的feign客户端 + */ + @Autowired + private IAuthService authService; + + /** + * 1.首先网关检查token是否有效,无效直接返回401,不调用签权服务 + * 2.调用签权服务器看是否对该请求有权限,有权限进入下一个filter,没有权限返回401 + * + * @param exchange + * @param chain + * @return + */ + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + ServerHttpRequest request = exchange.getRequest(); + String authentication = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION); + String method = request.getMethodValue(); + String url = request.getPath().value(); + log.debug("url:{},method:{},headers:{}", url, method, request.getHeaders()); + //不需要网关签权的url + if (authService.ignoreAuthentication(url)) { + return chain.filter(exchange); + } + // 如果请求未携带token信息, 直接跳出 + if (StringUtils.isBlank(authentication) || !authentication.startsWith(BEARER)) { + log.debug("url:{},method:{},headers:{}, 请求未携带token信息", url, method, request.getHeaders()); + return unauthorized(exchange); + } + //调用签权服务看用户是否有权限,若有权限进入下一个filter + if (authService.hasPermission(authentication, url, method)) { + ServerHttpRequest.Builder builder = request.mutate(); + //TODO 转发的请求都加上服务间认证token + builder.header(X_CLIENT_TOKEN, "TODO zhoutaoo添加服务间简单认证"); + //将jwt token中的用户信息传给服务 + builder.header(X_CLIENT_TOKEN_USER, authService.getJwt(authentication).getClaims()); + return chain.filter(exchange.mutate().request(builder.build()).build()); + } + return unauthorized(exchange); + } + + /** + * 网关拒绝,返回401 + * + * @param + */ + private Mono unauthorized(ServerWebExchange serverWebExchange) { + serverWebExchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); + DataBuffer buffer = serverWebExchange.getResponse() + .bufferFactory().wrap(HttpStatus.UNAUTHORIZED.getReasonPhrase().getBytes()); + return serverWebExchange.getResponse().writeWith(Flux.just(buffer)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `authentication` last assigned on line 47 at line 56. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Mono AccessGatewayFilter.filter(ServerWebExchange,GatewayFilterChain) + +### Procedure Id: +com.springboot.cloud.gateway.filter.AccessGatewayFilter.filter(org.springframework.web.server.Server.07151e1d64d2e609f6627da1651c9918 + +### File: +gateway/gateway-web/src/main/java/com/springboot/cloud/gateway/filter/AccessGatewayFilter.java + +### Key: +AccessGatewayFilter.java|filter|NULL_DEREFERENCE + +### Node Key: +0d5a2f2639f34d56cc8af6d106187976 + +### Hash: +6b1a122d1beadb92889d722cc136c5f7 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3512/instruction.md b/inferredbugs-3512/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3638d9fa8abf87a366452cfaa322d9c673a42299 --- /dev/null +++ b/inferredbugs-3512/instruction.md @@ -0,0 +1,1230 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helios +**Bug ID:** 29 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2014 Spotify AB. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.spotify.helios.system; + +import com.google.common.base.Charsets; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Range; +import com.google.common.io.Files; +import com.google.common.util.concurrent.FutureFallback; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.Service; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.spotify.docker.client.ContainerNotFoundException; +import com.spotify.docker.client.DefaultDockerClient; +import com.spotify.docker.client.DockerCertificates; +import com.spotify.docker.client.DockerClient; +import com.spotify.docker.client.DockerException; +import com.spotify.docker.client.DockerHost; +import com.spotify.docker.client.DockerRequestException; +import com.spotify.docker.client.ImageNotFoundException; +import com.spotify.docker.client.LogMessage; +import com.spotify.docker.client.LogReader; +import com.spotify.docker.client.messages.Container; +import com.spotify.docker.client.messages.ContainerConfig; +import com.spotify.docker.client.messages.ContainerCreation; +import com.spotify.docker.client.messages.ContainerInfo; +import com.spotify.docker.client.messages.HostConfig; +import com.spotify.docker.client.messages.PortBinding; +import com.spotify.helios.Polling; +import com.spotify.helios.TemporaryPorts; +import com.spotify.helios.TemporaryPorts.AllocatedPort; +import com.spotify.helios.ZooKeeperTestManager; +import com.spotify.helios.ZooKeeperTestingServerManager; +import com.spotify.helios.agent.AgentMain; +import com.spotify.helios.cli.CliMain; +import com.spotify.helios.cli.command.JobCreateCommand; +import com.spotify.helios.client.HeliosClient; +import com.spotify.helios.common.Json; +import com.spotify.helios.common.descriptors.Deployment; +import com.spotify.helios.common.descriptors.DeploymentGroupStatus; +import com.spotify.helios.common.descriptors.HostStatus; +import com.spotify.helios.common.descriptors.Job; +import com.spotify.helios.common.descriptors.Job.Builder; +import com.spotify.helios.common.descriptors.JobId; +import com.spotify.helios.common.descriptors.JobStatus; +import com.spotify.helios.common.descriptors.PortMapping; +import com.spotify.helios.common.descriptors.ServiceEndpoint; +import com.spotify.helios.common.descriptors.ServicePorts; +import com.spotify.helios.common.descriptors.TaskStatus; +import com.spotify.helios.common.descriptors.ThrottleState; +import com.spotify.helios.common.protocol.DeploymentGroupStatusResponse; +import com.spotify.helios.master.MasterMain; +import com.spotify.helios.servicescommon.ZooKeeperAclProviders; +import com.spotify.helios.servicescommon.coordination.CuratorClientFactory; +import com.spotify.helios.servicescommon.coordination.Paths; +import com.sun.jersey.api.client.ClientResponse; + +import org.apache.curator.framework.CuratorFramework; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.jetbrains.annotations.NotNull; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.rules.ExpectedException; +import org.junit.rules.TemporaryFolder; +import org.junit.rules.TestRule; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.bridge.SLF4JBridgeHandler; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.net.Socket; +import java.net.URI; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static com.google.common.base.CharMatcher.WHITESPACE; +import static com.google.common.base.Charsets.UTF_8; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Strings.isNullOrEmpty; +import static com.google.common.collect.Iterables.concat; +import static com.google.common.collect.Lists.newArrayList; +import static com.spotify.helios.common.descriptors.Job.EMPTY_ENV; +import static com.spotify.helios.common.descriptors.Job.EMPTY_EXPIRES; +import static com.spotify.helios.common.descriptors.Job.EMPTY_GRACE_PERIOD; +import static com.spotify.helios.common.descriptors.Job.EMPTY_HOSTNAME; +import static com.spotify.helios.common.descriptors.Job.EMPTY_PORTS; +import static com.spotify.helios.common.descriptors.Job.EMPTY_REGISTRATION; +import static com.spotify.helios.common.descriptors.Job.EMPTY_VOLUMES; +import static java.lang.Integer.toHexString; +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; +import static java.util.concurrent.TimeUnit.MINUTES; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public abstract class SystemTestBase { + + private static final Logger log = LoggerFactory.getLogger(SystemTestBase.class); + + public static final int WAIT_TIMEOUT_SECONDS = 40; + public static final int LONG_WAIT_SECONDS = 400; + + public static final String BUSYBOX = "busybox:latest"; + public static final String BUSYBOX_WITH_DIGEST = + "busybox@sha256:16a2a52884c2a9481ed267c2d46483eac7693b813a63132368ab098a71303f8a"; + public static final String NGINX = "rohan/nginx-alpine:latest"; + public static final String UHTTPD = "fnichol/docker-uhttpd:latest"; + public static final String ALPINE = "onescience/alpine:latest"; + public static final String MEMCACHED = "rohan/memcached-mini:latest"; + public static final List IDLE_COMMAND = asList( + "sh", "-c", "trap 'exit 0' SIGINT SIGTERM; while :; do sleep 1; done"); + + public final String testTag = "test_" + randomHexString(); + public final String testJobName = "job_" + testTag; + public final String testJobVersion = "v" + randomHexString(); + public final String testJobNameAndVersion = testJobName + ":" + testJobVersion; + + public static final DockerHost DOCKER_HOST = DockerHost.fromEnv(); + + public static final String TEST_USER = "test-user"; + public static final String TEST_HOST = "test-host"; + public static final String TEST_MASTER = "test-master"; + + private static final String MASTER_USER = "helios-master"; + private static final String MASTER_PASSWORD = "master-password"; + private static final String AGENT_USER = "helios-agent"; + private static final String AGENT_PASSWORD = "agent-password"; + private static final String MASTER_DIGEST = + ZooKeeperAclProviders.digest(MASTER_USER, MASTER_PASSWORD); + private static final String AGENT_DIGEST = ZooKeeperAclProviders.digest( + AGENT_USER, AGENT_PASSWORD); + + @Rule public final TemporaryPorts temporaryPorts = TemporaryPorts.create(); + + @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @Rule public final ExpectedException exception = ExpectedException.none(); + @Rule public final TestRule watcher = new LoggingTestWatcher(); + + private int masterPort; + private int masterAdminPort; + private String masterEndpoint; + private String masterAdminEndpoint; + private Range dockerPortRange; + + private final List services = newArrayList(); + private final List clients = Lists.newArrayList(); + + private Path agentStateDirs; + private Path masterStateDirs; + + private ZooKeeperTestManager zk; + protected static String zooKeeperNamespace = null; + protected final String zkClusterId = String.valueOf(ThreadLocalRandom.current().nextInt(10000)); + + /** An HttpClient that can be used for sending arbitrary HTTP requests */ + protected CloseableHttpClient httpClient; + + @BeforeClass + public static void staticSetup() { + SLF4JBridgeHandler.removeHandlersForRootLogger(); + SLF4JBridgeHandler.install(); + } + + @Before + public void baseSetup() throws Exception { + System.setProperty("user.name", TEST_USER); + masterPort = temporaryPorts.localPort("helios master"); + masterAdminPort = temporaryPorts.localPort("helios master admin"); + + masterEndpoint = "http://localhost:" + masterPort(); + masterAdminEndpoint = "http://localhost:" + masterAdminPort(); + + zk = zooKeeperTestManager(); + listThreads(); + zk.ensure("/config"); + zk.ensure("/status"); + agentStateDirs = temporaryFolder.newFolder("helios-agents").toPath(); + masterStateDirs = temporaryFolder.newFolder("helios-masters").toPath(); + + // TODO (mbrown): not 100% sure what a minimal client is but it sounds good + httpClient = HttpClients.createMinimal(); + } + + @Before + public void dockerSetup() throws Exception { + final String portRange = System.getenv("DOCKER_PORT_RANGE"); + + final AllocatedPort allocatedPort; + final int probePort; + if (portRange != null) { + final String[] parts = portRange.split(":", 2); + dockerPortRange = Range.closedOpen(Integer.valueOf(parts[0]), + Integer.valueOf(parts[1])); + allocatedPort = Polling.await(LONG_WAIT_SECONDS, SECONDS, new Callable() { + @Override + public AllocatedPort call() throws Exception { + final int port = ThreadLocalRandom.current().nextInt(dockerPortRange.lowerEndpoint(), + dockerPortRange.upperEndpoint()); + return temporaryPorts.tryAcquire("docker-probe", port); + } + }); + probePort = allocatedPort.port(); + } else { + dockerPortRange = temporaryPorts.localPortRange("docker", 10); + probePort = dockerPortRange().lowerEndpoint(); + allocatedPort = null; + } + + try { + assertDockerReachable(probePort); + } finally { + if (allocatedPort != null) { + allocatedPort.release(); + } + } + } + + protected DockerClient getNewDockerClient() throws Exception { + if (isNullOrEmpty(DOCKER_HOST.dockerCertPath())) { + return new DefaultDockerClient(DOCKER_HOST.uri()); + } else { + final Path dockerCertPath = java.nio.file.Paths.get(DOCKER_HOST.dockerCertPath()); + return new DefaultDockerClient(DOCKER_HOST.uri(), new DockerCertificates(dockerCertPath)); + } + } + + private void assertDockerReachable(final int probePort) throws Exception { + try (final DockerClient docker = getNewDockerClient()) { + // Pull our base images + try { + docker.inspectImage(BUSYBOX); + } catch (ImageNotFoundException e) { + docker.pull(BUSYBOX); + } + + try { + docker.inspectImage(ALPINE); + } catch (ImageNotFoundException e) { + docker.pull(ALPINE); + } + + // Start a container with an exposed port + final HostConfig hostConfig = HostConfig.builder() + .portBindings(ImmutableMap.of("4711/tcp", + singletonList(PortBinding.of("0.0.0.0", probePort)))) + .build(); + final ContainerConfig config = ContainerConfig.builder() + .image(BUSYBOX) + .cmd("nc", "-p", "4711", "-lle", "cat") + .exposedPorts(ImmutableSet.of("4711/tcp")) + .hostConfig(hostConfig) + .build(); + final ContainerCreation creation = docker.createContainer(config, testTag + "-probe"); + final String containerId = creation.id(); + docker.startContainer(containerId); + + // Wait for container to come up + Polling.await(5, SECONDS, new Callable() { + @Override + public Object call() throws Exception { + final ContainerInfo info = docker.inspectContainer(containerId); + return info.state().running() ? true : null; + } + }); + + log.info("Verifying that docker containers are reachable"); + try { + Polling.awaitUnchecked(5, SECONDS, new Callable() { + @Override + public Object call() throws Exception { + log.info("Probing: {}:{}", DOCKER_HOST.address(), probePort); + try (final Socket ignored = new Socket(DOCKER_HOST.address(), probePort)) { + return true; + } catch (IOException e) { + return false; + } + } + }); + } catch (TimeoutException e) { + fail("Please ensure that DOCKER_HOST is set to an address that where containers can " + + "be reached. If docker is running in a local VM, DOCKER_HOST must be set to the " + + "address of that VM. If docker can only be reached on a limited port range, " + + "set the environment variable DOCKER_PORT_RANGE=start:end"); + } + + docker.killContainer(containerId); + } + } + + protected ZooKeeperTestManager zooKeeperTestManager() { + return new ZooKeeperTestingServerManager(zooKeeperNamespace); + } + + @After + public void baseTeardown() throws Exception { + for (final HeliosClient client : clients) { + client.close(); + } + clients.clear(); + + for (Service service : services) { + try { + service.stopAsync(); + } catch (Exception e) { + log.error("Uncaught exception", e); + } + } + for (Service service : services) { + try { + service.awaitTerminated(); + } catch (Exception e) { + log.error("Service failed", e); + } + } + services.clear(); + + // Clean up docker + try (final DockerClient dockerClient = getNewDockerClient()) { + final List containers = dockerClient.listContainers(); + for (final Container container : containers) { + for (final String name : container.names()) { + if (name.contains(testTag)) { + try { + dockerClient.killContainer(container.id()); + } catch (DockerException e) { + e.printStackTrace(); + } + break; + } + } + } + } catch (Exception e) { + log.error("Docker client exception", e); + } + + if (zk != null) { + zk.close(); + } + + listThreads(); + } + + private void listThreads() { + final Set threads = Thread.getAllStackTraces().keySet(); + final Map sorted = Maps.newTreeMap(); + for (final Thread t : threads) { + final ThreadGroup tg = t.getThreadGroup(); + if (t.isAlive() && (tg == null || !tg.getName().equals("system"))) { + sorted.put(t.getName(), t); + } + } + log.info("= THREADS " + Strings.repeat("=", 70)); + for (final Thread t : sorted.values()) { + final ThreadGroup tg = t.getThreadGroup(); + log.info("{}: \"{}\" ({}{})", t.getId(), t.getName(), + (tg == null ? "" : tg.getName() + " "), + (t.isDaemon() ? "daemon" : "")); + } + log.info(Strings.repeat("=", 80)); + } + + protected TemporaryPorts temporaryPorts() { + return temporaryPorts; + } + + protected ZooKeeperTestManager zk() { + return zk; + } + + protected String masterEndpoint() { + return masterEndpoint; + } + + protected String masterAdminEndpoint() { + return masterAdminEndpoint; + } + + protected String masterName() throws InterruptedException, ExecutionException { + return TEST_MASTER; + } + + protected HeliosClient defaultClient() { + return client(TEST_USER, masterEndpoint()); + } + + protected HeliosClient client(final String user, final String endpoint) { + final HeliosClient client = HeliosClient.newBuilder() + .setUser(user) + .setEndpoints(singletonList(URI.create(endpoint))) + .build(); + clients.add(client); + return client; + } + + protected int masterPort() { + return masterPort; + } + + protected int masterAdminPort() { + return masterAdminPort; + } + + public Range dockerPortRange() { + return dockerPortRange; + } + + protected String testHost() throws InterruptedException, ExecutionException { + return TEST_HOST; + } + + protected List setupDefaultMaster(String... args) throws Exception { + return setupDefaultMaster(0, args); + } + + protected List setupDefaultMaster(final int offset, String... args) throws Exception { + // TODO (dano): Move this bootstrapping to something reusable + final CuratorFramework curator = zk.curator(); + curator.newNamespaceAwareEnsurePath(Paths.configHosts()).ensure(curator.getZookeeperClient()); + curator.newNamespaceAwareEnsurePath(Paths.configJobs()).ensure(curator.getZookeeperClient()); + curator.newNamespaceAwareEnsurePath(Paths.configJobRefs()).ensure(curator.getZookeeperClient()); + curator.newNamespaceAwareEnsurePath(Paths.statusHosts()).ensure(curator.getZookeeperClient()); + curator.newNamespaceAwareEnsurePath(Paths.statusMasters()).ensure(curator.getZookeeperClient()); + curator.newNamespaceAwareEnsurePath(Paths.historyJobs()).ensure(curator.getZookeeperClient()); + curator.newNamespaceAwareEnsurePath(Paths.configId(zkClusterId)) + .ensure(curator.getZookeeperClient()); + + final List argsList = Lists.newArrayList( + "-vvvv", + "--no-log-setup", + "--http", "http://0.0.0.0:" + (masterPort() + offset), + "--admin=" + (masterAdminPort() + offset), + "--domain", "", + "--zk", zk.connectString(), + "--zk-enable-acls", + "--zk-acl-agent-user", AGENT_USER, + "--zk-acl-agent-digest", AGENT_DIGEST, + "--zk-acl-master-user", MASTER_USER, + "--zk-acl-master-password", MASTER_PASSWORD + ); + + final String name; + if (asList(args).contains("--name")) { + name = args[asList(args).indexOf("--name") + 1]; + } else { + name = TEST_MASTER + offset; + argsList.addAll(asList("--name", TEST_MASTER)); + } + + final String stateDir = masterStateDirs.resolve(name).toString(); + argsList.addAll(asList("--state-dir", stateDir)); + + argsList.addAll(asList(args)); + + return argsList; + } + + protected MasterMain startDefaultMaster(String... args) throws Exception { + return startDefaultMaster(0, args); + } + + protected MasterMain startDefaultMaster(Map environmentVariables, String... args) + throws Exception { + return startDefaultMaster(0, environmentVariables, args); + } + + protected MasterMain startDefaultMaster(final int offset, String... args) throws Exception { + return startDefaultMaster(offset, ImmutableMap.of(), args); + } + + protected MasterMain startDefaultMaster(final int offset, + final Map environmentVariables, + final String... args) throws Exception { + final List argsList = setupDefaultMaster(offset, args); + + if (argsList == null) { + return null; + } + + final MasterMain master = + startMaster(environmentVariables, argsList.toArray(new String[argsList.size()])); + + waitForMasterToBeFullyUp(); + + return master; + } + + protected Map startDefaultMasters(final int numMasters, String... args) + throws Exception { + final Map masters = Maps.newHashMap(); + + for (int i = 0; i < numMasters; i++) { + final String name = TEST_MASTER + i; + final List argsList = Lists.newArrayList(args); + argsList.addAll(asList("--name", name)); + masters.put(name, startDefaultMaster(i, argsList.toArray(new String[argsList.size()]))); + } + + return masters; + } + + protected void waitForMasterToBeFullyUp() throws Exception { + log.debug("waitForMasterToBeFullyUp: beginning wait loop"); + Polling.await(WAIT_TIMEOUT_SECONDS, SECONDS, new Callable() { + @Override + public Object call() { + try { + // While MasterService will start listening for http requests on the main and admin ports + // as soon as it is started (without waiting for ZK to be available), the Healthcheck + // registered for Zookeeper connectivity will cause the HealthcheckServlet to not return + // 200 OK until ZK is connected to (and even better, until *everything* is healthy). + final HttpGet request = new HttpGet(masterAdminEndpoint + "/healthcheck"); + + try (CloseableHttpResponse response = httpClient.execute(request)) { + final int status = response.getStatusLine().getStatusCode(); + log.debug("waitForMasterToBeFullyUp: healthcheck endpoint returned {}", status); + return status == HttpStatus.SC_OK; + } + } catch (Exception e) { + return null; + } + } + }); + } + + protected void startDefaultMasterDontWaitForZK(final CuratorClientFactory curatorClientFactory, + String... args) throws Exception { + List argsList = setupDefaultMaster(args); + + if (argsList == null) { + return; + } + + startMaster(curatorClientFactory, argsList.toArray(new String[argsList.size()])); + } + + protected AgentMain startDefaultAgent(final String host, final String... args) + throws Exception { + final String stateDir = agentStateDirs.resolve(host).toString(); + final List argsList = Lists.newArrayList( + "-vvvv", + "--no-log-setup", + "--no-http", + "--name", host, + "--docker=" + DOCKER_HOST, + "--zk", zk.connectString(), + "--zk-session-timeout", "100", + "--zk-connection-timeout", "100", + "--zk-enable-acls", + "--zk-acl-master-user", MASTER_USER, + "--zk-acl-master-digest", MASTER_DIGEST, + "--zk-acl-agent-user", AGENT_USER, + "--zk-acl-agent-password", AGENT_PASSWORD, + "--state-dir", stateDir, + "--domain", "", + "--port-range=" + + dockerPortRange.lowerEndpoint() + ":" + + dockerPortRange.upperEndpoint() + ); + argsList.addAll(asList(args)); + return startAgent(argsList.toArray(new String[argsList.size()])); + } + + protected MasterMain startMaster(final Map environmentVariables, + final String... args) throws Exception { + final MasterMain main = new MasterMain(environmentVariables, args); + main.startAsync().awaitRunning(); + services.add(main); + return main; + } + + MasterMain startMaster(final CuratorClientFactory curatorClientFactory, + final String... args) throws Exception { + final MasterMain main = new MasterMain(curatorClientFactory, args); + main.startAsync().awaitRunning(); + services.add(main); + return main; + } + + protected AgentMain startAgent(final String... args) throws Exception { + final AgentMain main = new AgentMain(args); + main.startAsync().awaitRunning(); + services.add(main); + return main; + } + + protected JobId createJob(final String name, + final String version, + final String image, + final List command) throws Exception { + return createJob(name, version, image, command, EMPTY_ENV, EMPTY_PORTS, EMPTY_REGISTRATION); + } + + protected JobId createJob(final String name, + final String version, + final String image, + final List command, + final Date expires) throws Exception { + return createJob(name, version, image, EMPTY_HOSTNAME, command, EMPTY_ENV, EMPTY_PORTS, + EMPTY_REGISTRATION, EMPTY_GRACE_PERIOD, EMPTY_VOLUMES, expires); + } + + protected JobId createJob(final String name, + final String version, + final String image, + final List command, + final ImmutableMap env) + throws Exception { + return createJob(name, version, image, command, env, EMPTY_PORTS, EMPTY_REGISTRATION); + } + + protected JobId createJob(final String name, + final String version, + final String image, + final List command, + final Map env, + final Map ports) throws Exception { + return createJob(name, version, image, command, env, ports, EMPTY_REGISTRATION); + } + + protected JobId createJob(final String name, + final String version, + final String image, + final List command, + final Map env, + final Map ports, + final Map registration) + throws Exception { + return createJob(name, version, image, command, env, ports, registration, EMPTY_GRACE_PERIOD, + EMPTY_VOLUMES); + } + + protected JobId createJob(final String name, + final String version, + final String image, + final List command, + final Map env, + final Map ports, + final Map registration, + final Integer gracePeriod, + final Map volumes) throws Exception { + return createJob(name, version, image, EMPTY_HOSTNAME, command, env, ports, registration, + gracePeriod, volumes, EMPTY_EXPIRES); + } + + protected JobId createJob(final String name, + final String version, + final String image, + final String hostname, + final List command, + final Map env, + final Map ports, + final Map registration, + final Integer gracePeriod, + final Map volumes, + final Date expires) throws Exception { + return createJob(Job.newBuilder() + .setName(name) + .setVersion(version) + .setImage(image) + .setHostname(hostname) + .setCommand(command) + .setEnv(env) + .setPorts(ports) + .setRegistration(registration) + .setGracePeriod(gracePeriod) + .setVolumes(volumes) + .setExpires(expires) + .build()); + } + + protected JobId createJob(final Job job) throws Exception { + final String createOutput = createJobRawOutput(job); + final String jobId = WHITESPACE.trimFrom(createOutput); + + return JobId.fromString(jobId); + } + + protected String createJobRawOutput(final Job job) throws Exception { + final String name = job.getId().getName(); + checkArgument(name.contains(testTag), "Job name must contain testTag to enable cleanup"); + + final String serializedConfig = Json.asNormalizedString(job); + final File configFile = temporaryFolder.newFile(); + Files.write(serializedConfig, configFile, Charsets.UTF_8); + + final List args = ImmutableList.of("-q", "-f", configFile.getAbsolutePath()); + return cli("create", args); + } + + protected void deployJob(final JobId jobId, final String host) throws Exception { + deployJob(jobId, host, null); + } + + protected void deployJob(final JobId jobId, final String host, final String token) + throws Exception { + final List deployArgs = Lists.newArrayList(jobId.toString(), host); + + if (token != null) { + deployArgs.addAll(ImmutableList.of("--token", token)); + } + + final String deployOutput = cli("deploy", deployArgs); + assertThat(deployOutput, containsString(host + ": done")); + + final String output = cli("status", "--host", host, "--json"); + final Map statuses = + Json.readUnchecked(output, new TypeReference>() { + }); + assertTrue(statuses.keySet().contains(jobId)); + } + + protected void undeployJob(final JobId jobId, final String host) throws Exception { + final String undeployOutput = cli("undeploy", jobId.toString(), host); + assertThat(undeployOutput, containsString(host + ": done")); + + final String output = cli("status", "--host", host, "--json"); + final Map statuses = + Json.readUnchecked(output, new TypeReference>() { + }); + final JobStatus status = statuses.get(jobId); + assertTrue(status == null || status.getDeployments().get(host) == null); + } + + protected String startJob(final JobId jobId, final String host) throws Exception { + return cli("start", jobId.toString(), host); + } + + protected String stopJob(final JobId jobId, final String host) throws Exception { + return cli("stop", jobId.toString(), host); + } + + protected String deregisterHost(final String host) throws Exception { + return cli("deregister", host, "--yes"); + } + + protected String cli(final String command, final Object... args) + throws Exception { + return cli(command, flatten(args)); + } + + protected String cli(final String command, final String... args) + throws Exception { + return cli(command, asList(args)); + } + + protected String cli(final String command, final List args) + throws Exception { + final List commands = asList(command, "-z", masterEndpoint(), "--no-log-setup"); + final List allArgs = newArrayList(concat(commands, args)); + return main(allArgs).toString(); + } + + protected T cliJson(final Class klass, final String command, final String... args) + throws Exception { + return cliJson(klass, command, asList(args)); + } + + protected T cliJson(final Class klass, final String command, final List args) + throws Exception { + final List args0 = newArrayList("--json"); + args0.addAll(args); + return Json.read(cli(command, args0), klass); + } + + protected ByteArrayOutputStream main(final String... args) throws Exception { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + final ByteArrayOutputStream err = new ByteArrayOutputStream(); + final CliMain main = new CliMain(new PrintStream(out), new PrintStream(err), args); + main.run(); + return out; + } + + protected ByteArrayOutputStream main(final Collection args) throws Exception { + return main(args.toArray(new String[args.size()])); + } + + protected void awaitHostRegistered(final String name, final long timeout, final TimeUnit timeUnit) + throws Exception { + Polling.await(timeout, timeUnit, new Callable() { + @Override + public Object call() throws Exception { + final String output = cli("hosts", "-q"); + return output.contains(name) ? true : null; + } + }); + } + + protected HostStatus awaitHostStatus(final String name, final HostStatus.Status status, + final int timeout, final TimeUnit timeUnit) + throws Exception { + return Polling.await(timeout, timeUnit, new Callable() { + @Override + public HostStatus call() throws Exception { + final String output = cli("hosts", name, "--json"); + final Map statuses; + try { + statuses = Json.read(output, new TypeReference>() {}); + } catch (IOException e) { + return null; + } + final HostStatus hostStatus = statuses.get(name); + if (hostStatus == null) { + return null; + } + return (hostStatus.getStatus() == status) ? hostStatus : null; + } + }); + } + + protected TaskStatus awaitJobState(final HeliosClient client, final String host, + final JobId jobId, + final TaskStatus.State state, final int timeout, + final TimeUnit timeunit) throws Exception { + return Polling.await(timeout, timeunit, new Callable() { + @Override + public TaskStatus call() throws Exception { + final HostStatus hostStatus = getOrNull(client.hostStatus(host)); + if (hostStatus == null) { + return null; + } + final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId); + return (taskStatus != null && taskStatus.getState() == state) ? taskStatus + : null; + } + }); + } + + protected TaskStatus awaitJobThrottle(final HeliosClient client, final String host, + final JobId jobId, + final ThrottleState throttled, final int timeout, + final TimeUnit timeunit) throws Exception { + return Polling.await(timeout, timeunit, new Callable() { + @Override + public TaskStatus call() throws Exception { + final HostStatus hostStatus = getOrNull(client.hostStatus(host)); + if (hostStatus == null) { + return null; + } + final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId); + return (taskStatus != null && taskStatus.getThrottled() == throttled) ? taskStatus : null; + } + }); + } + + protected void awaitHostRegistered(final HeliosClient client, final String host, + final int timeout, + final TimeUnit timeUnit) throws Exception { + Polling.await(timeout, timeUnit, new Callable() { + @Override + public HostStatus call() throws Exception { + return getOrNull(client.hostStatus(host)); + } + }); + } + + protected HostStatus awaitHostStatus(final HeliosClient client, final String host, + final HostStatus.Status status, + final int timeout, + final TimeUnit timeUnit) throws Exception { + return Polling.await(timeout, timeUnit, new Callable() { + @Override + public HostStatus call() throws Exception { + final HostStatus hostStatus = getOrNull(client.hostStatus(host)); + if (hostStatus == null) { + return null; + } + return (hostStatus.getStatus() == status) ? hostStatus : null; + } + }); + } + + protected HostStatus awaitHostStatusWithLabels(final HeliosClient client, final String host, + final HostStatus.Status status, + final int timeout, + final TimeUnit timeUnit) throws Exception { + return Polling.await(timeout, timeUnit, new Callable() { + @Override + public HostStatus call() throws Exception { + final HostStatus hostStatus = getOrNull(client.hostStatus(host)); + if (hostStatus == null || hostStatus.getLabels().size() == 0) { + return null; + } + return (hostStatus.getStatus() == status) ? hostStatus : null; + } + }); + } + + protected HostStatus awaitHostStatusWithHostInfo(final HeliosClient client, final String host, + final HostStatus.Status status, + final int timeout, + final TimeUnit timeUnit) throws Exception { + return Polling.await(timeout, timeUnit, new Callable() { + @Override + public HostStatus call() throws Exception { + final HostStatus hostStatus = getOrNull(client.hostStatus(host)); + if (hostStatus == null || hostStatus.getHostInfo() == null) { + return null; + } + return (hostStatus.getStatus() == status) ? hostStatus : null; + } + }); + } + + protected TaskStatus awaitTaskState(final JobId jobId, final String host, + final TaskStatus.State state) throws Exception { + return Polling.await(LONG_WAIT_SECONDS, SECONDS, new Callable() { + @Override + public TaskStatus call() throws Exception { + final String output = cli("status", "--json", "--job", jobId.toString()); + final Map statusMap; + try { + statusMap = Json.read(output, new TypeReference>() {}); + } catch (IOException e) { + return null; + } + final JobStatus status = statusMap.get(jobId); + if (status == null) { + return null; + } + final TaskStatus taskStatus = status.getTaskStatuses().get(host); + if (taskStatus == null) { + return null; + } + if (taskStatus.getState() != state) { + return null; + } + return taskStatus; + } + }); + } + + protected void awaitTaskGone(final HeliosClient client, final String host, final JobId jobId, + final long timeout, final TimeUnit timeunit) throws Exception { + Polling.await(timeout, timeunit, new Callable() { + @Override + public Boolean call() throws Exception { + final HostStatus hostStatus = getOrNull(client.hostStatus(host)); + final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId); + final Deployment deployment = hostStatus.getJobs().get(jobId); + return taskStatus == null && deployment == null ? true : null; + } + }); + } + + protected DeploymentGroupStatus awaitDeploymentGroupStatus( + final HeliosClient client, + final String name, + final DeploymentGroupStatus.State state) + throws Exception { + return Polling.await(LONG_WAIT_SECONDS, SECONDS, new Callable() { + @Override + public DeploymentGroupStatus call() throws Exception { + final DeploymentGroupStatusResponse response = getOrNull( + client.deploymentGroupStatus(name)); + + if (response != null) { + final DeploymentGroupStatus status = response.getDeploymentGroupStatus(); + if (status.getState().equals(state)) { + return status; + } else if (status.getState().equals(DeploymentGroupStatus.State.FAILED)) { + assertEquals(state, status.getState()); + } + } + + return null; + } + }); + } + + protected T getOrNull(final ListenableFuture future) + throws ExecutionException, InterruptedException { + return Futures.withFallback(future, new FutureFallback() { + @Override + public ListenableFuture create(@NotNull final Throwable t) throws Exception { + return Futures.immediateFuture(null); + } + }).get(); + } + + protected String readLogFully(final ClientResponse logs) throws IOException { + final LogReader logReader = new LogReader(logs.getEntityInputStream()); + StringBuilder stringBuilder = new StringBuilder(); + LogMessage logMessage; + while ((logMessage = logReader.nextMessage()) != null) { + stringBuilder.append(UTF_8.decode(logMessage.content())); + } + logReader.close(); + return stringBuilder.toString(); + } + + protected static void removeContainer(final DockerClient dockerClient, final String containerId) + throws Exception { + // Work around docker sometimes failing to remove a container directly after killing it + Polling.await(1, MINUTES, new Callable() { + @Override + public Object call() throws Exception { + try { + dockerClient.killContainer(containerId); + } catch (DockerRequestException e) { + if (e.message().contains("is not running")) { + // Container already isn't running. So we continue. + } else { + throw e; + } + } + + try { + dockerClient.removeContainer(containerId); + return true; + } catch (ContainerNotFoundException e) { + // We're done here + return true; + } catch (DockerException e) { + if ((e instanceof DockerRequestException) && + ((DockerRequestException) e).message().contains( + "Driver btrfs failed to remove root filesystem")) { + // Workaround btrfs issue where removing containers throws an exception, + // but succeeds anyway. + return true; + } else { + return null; + } + } + } + }); + } + + protected List listContainers(final DockerClient dockerClient, final String needle) + throws DockerException, InterruptedException { + final List containers = dockerClient.listContainers(); + final List matches = Lists.newArrayList(); + for (final Container container : containers) { + if (container.names() != null) { + for (final String name : container.names()) { + if (name.contains(needle)) { + matches.add(container); + break; + } + } + } + } + return matches; + } + + protected List flatten(final Object... values) { + final Iterable valuesList = asList(values); + return flatten(valuesList); + } + + protected List flatten(final Iterable values) { + final List list = new ArrayList<>(); + for (Object value : values) { + if (value instanceof Iterable) { + list.addAll(flatten((Iterable) value)); + } else if (value.getClass() == String[].class) { + list.addAll(asList((String[]) value)); + } else if (value instanceof String) { + list.add((String) value); + } else { + throw new IllegalArgumentException(); + } + } + return list; + } + + protected void assertJobsEqual(final Map expected, final Map actual) { + assertEquals(expected.size(), actual.size()); + for (final Map.Entry entry : actual.entrySet()) { + assertJobEquals(expected.get(entry.getKey()), entry.getValue()); + } + } + + protected void assertJobEquals(final Job expected, final Job actual) { + final Builder expectedBuilder = expected.toBuilder(); + + // hack to make sure that any environment variables that were folded into the created job + // because of environment variables set at runtime on the test-running-agent are removed + // from the actual when we assert the equality below + final Builder actualBuilder = actual.toBuilder(); + final Map metadata = Maps.newHashMap(actual.getMetadata()); + for (Map.Entry entry : JobCreateCommand.DEFAULT_METADATA_ENVVARS.entrySet()) { + final String envVar = entry.getKey(); + final String metadataKey = entry.getValue(); + final String envValue = System.getenv(envVar); + if (envValue != null + && actual.getMetadata().containsKey(metadataKey) + && actual.getMetadata().get(metadataKey).equals(envValue)) { + metadata.remove(metadataKey); + } + } + actualBuilder.setMetadata(metadata); + + // Remove created timestamp set by master + actualBuilder.setCreated(null); + + // copy the hash + expectedBuilder.setHash(actualBuilder.build().getId().getHash()); + + assertEquals(expectedBuilder.build(), actualBuilder.build()); + } + + protected static String randomHexString() { + return toHexString(ThreadLocalRandom.current().nextInt()); + } + + protected void resetAgentStateDir() throws IOException { + agentStateDirs = temporaryFolder.newFolder(UUID.randomUUID().toString()).toPath(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.curator.test.TestingServer` acquired by call to `ZooKeeperTestingServerManager(...)` at line 337 is not released after line 337. +**Note**: potential exception at line 337 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +ZooKeeperTestManager SystemTestBase.zooKeeperTestManager() + +### Procedure Id: +com.spotify.helios.system.SystemTestBase.zooKeeperTestManager():com.spotify.helios.ZooKeeperTestMana.7ccd02df5621155dd63c4142399debe5 + +### File: +helios-system-tests/src/main/java/com/spotify/helios/system/SystemTestBase.java + +### Key: +SystemTestBase.java|zooKeeperTestManager|RESOURCE_LEAK + +### Node Key: +059f2744cc2584f5360423ee802f205e + +### Hash: +2bedc75c6a609aa641eb4926aa9a6ba9 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3513/instruction.md b/inferredbugs-3513/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c604f406a303962cf2ca175fc129ed9b809581b5 --- /dev/null +++ b/inferredbugs-3513/instruction.md @@ -0,0 +1,254 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helios +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2014 Spotify AB. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.spotify.helios.cli; + +import com.google.common.base.Function; +import com.google.common.base.Strings; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Ordering; +import com.google.common.util.concurrent.ListenableFuture; + +import com.spotify.helios.client.Endpoints; +import com.spotify.helios.client.HeliosClient; +import com.spotify.helios.common.descriptors.Deployment; +import com.spotify.helios.common.descriptors.HostSelector; +import com.spotify.helios.common.protocol.SetGoalResponse; + +import net.sourceforge.argparse4j.inf.Argument; +import net.sourceforge.argparse4j.inf.Namespace; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintStream; +import java.net.URI; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; + +import static java.lang.String.format; + +public class Utils { + + public static Map allAsMap(final Map> map) + throws ExecutionException, InterruptedException { + final Map result = Maps.newHashMap(); + for (Map.Entry> e : map.entrySet()) { + result.put(e.getKey(), e.getValue().get()); + } + return result; + } + + public static HeliosClient getClient(final Target target, final PrintStream err, + final String username, final Namespace options) { + + List endpoints = Collections.emptyList(); + try { + endpoints = target.getEndpointSupplier().get(); + } catch (Exception ignore) { + // TODO (dano): Nasty. Refactor target to propagate resolution failure in a checked manner. + } + if (endpoints.size() == 0) { + err.println("Failed to resolve helios master in " + target); + return null; + } + + return HeliosClient.newBuilder() + .setEndpointSupplier(Endpoints.of(target.getEndpointSupplier())) + .setSslHostnameVerification(!options.getBoolean("insecure")) + .setUser(username) + .build(); + } + + public static boolean userConfirmed(final PrintStream out, final BufferedReader stdin) + throws IOException { + out.printf("Do you want to continue? [y/N]%n"); + + final String line = stdin.readLine().trim(); + + if (line.length() < 1) { + return false; + } + final char c = line.charAt(0); + + if (c != 'Y' && c != 'y') { + return false; + } + + return true; + } + + public static Map argToStringMap(final Namespace namespace, final Argument arg) { + final List> args = namespace.getList(arg.getDest()); + final Map map = Maps.newHashMap(); + if (args != null) { + for (final List group : args) { + for (final String s : group) { + final String[] parts = s.split("=", 2); + if (parts.length != 2) { + throw new IllegalArgumentException("Bad " + arg.textualName() + " value: " + s); + } + map.put(parts[0], parts[1]); + } + } + } + return map; + } + + public static , V> void printMap(final PrintStream out, final String name, + final Function transform, + final Map values) { + out.print(name); + boolean first = true; + for (final K key : Ordering.natural().sortedCopy(values.keySet())) { + if (!first) { + out.print(Strings.repeat(" ", name.length())); + } + final V value = values.get(key); + out.printf("%s=%s%n", key, transform.apply(value)); + first = false; + } + if (first) { + out.println(); + } + } + + public static List parseHostSelectors(final Namespace namespace, + final Argument arg) { + final List> args = namespace.getList(arg.getDest()); + final List ret = Lists.newArrayList(); + if (args != null) { + for (final List group : args) { + for (final String s : group) { + final HostSelector hostSelector = HostSelector.parse(s); + if (hostSelector == null) { + throw new IllegalArgumentException(format("Bad host selector expression: '%s'", s)); + } + ret.add(hostSelector); + } + } + } + return ret; + } + + // shared between JobStartCommand and JobStopCommand + public static int setGoalOnHosts(final HeliosClient client, final PrintStream out, + final boolean json, final List hosts, + final Deployment deployment, final String token) + throws InterruptedException, ExecutionException { + int code = 0; + + for (final String host : hosts) { + if (!json) { + out.printf("%s: ", host); + } + final SetGoalResponse result = client.setGoal(deployment, host, token).get(); + if (result.getStatus() == SetGoalResponse.Status.OK) { + if (json) { + out.printf(result.toJsonString()); + } else { + out.printf("done%n"); + } + } else { + if (json) { + out.printf(result.toJsonString()); + } else { + out.printf("failed: %s%n", result); + } + code = 1; + } + } + + return code; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +CHECKERS_PRINTF_ARGS + +### Qualifier: +Format string must be string literal. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int Utils.setGoalOnHosts(HeliosClient,PrintStream,boolean,List,Deployment,String) + +### Procedure Id: +com.spotify.helios.cli.Utils.setGoalOnHosts(com.spotify.helios.client.HeliosClient,java.io.PrintStre.dd3906532cee2669e40343dd76bf63dc + +### File: +helios-tools/src/main/java/com/spotify/helios/cli/Utils.java + +### Key: +Utils.java|setGoalOnHosts|CHECKERS_PRINTF_ARGS + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +db0973079ad3eb416da3129fb367ab59 + +### Bug Type Hum: +Checkers Printf Args + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3514/instruction.md b/inferredbugs-3514/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef6f1e064baa228769c1ffc0d2c66819609dc318 --- /dev/null +++ b/inferredbugs-3514/instruction.md @@ -0,0 +1,1084 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helios +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2014 Spotify AB. + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.spotify.helios.system; + +import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Range; +import com.google.common.util.concurrent.FutureFallback; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.Service; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.spotify.docker.client.ContainerNotFoundException; +import com.spotify.docker.client.DefaultDockerClient; +import com.spotify.docker.client.DockerClient; +import com.spotify.docker.client.DockerException; +import com.spotify.docker.client.DockerRequestException; +import com.spotify.docker.client.ImageNotFoundException; +import com.spotify.docker.client.LogMessage; +import com.spotify.docker.client.LogReader; +import com.spotify.docker.client.messages.Container; +import com.spotify.docker.client.messages.ContainerConfig; +import com.spotify.docker.client.messages.ContainerCreation; +import com.spotify.docker.client.messages.ContainerInfo; +import com.spotify.docker.client.messages.HostConfig; +import com.spotify.docker.client.messages.PortBinding; +import com.spotify.helios.Polling; +import com.spotify.helios.TemporaryPorts; +import com.spotify.helios.ZooKeeperStandaloneServerManager; +import com.spotify.helios.ZooKeeperTestManager; +import com.spotify.helios.agent.AgentMain; +import com.spotify.helios.cli.CliMain; +import com.spotify.helios.client.HeliosClient; +import com.spotify.helios.common.Json; +import com.spotify.helios.common.descriptors.Deployment; +import com.spotify.helios.common.descriptors.HostStatus; +import com.spotify.helios.common.descriptors.Job; +import com.spotify.helios.common.descriptors.JobId; +import com.spotify.helios.common.descriptors.JobStatus; +import com.spotify.helios.common.descriptors.PortMapping; +import com.spotify.helios.common.descriptors.ServiceEndpoint; +import com.spotify.helios.common.descriptors.ServicePorts; +import com.spotify.helios.common.descriptors.TaskStatus; +import com.spotify.helios.common.descriptors.ThrottleState; +import com.spotify.helios.common.protocol.JobDeleteResponse; +import com.spotify.helios.common.protocol.JobUndeployResponse; +import com.spotify.helios.master.MasterMain; +import com.spotify.helios.servicescommon.DockerHost; +import com.spotify.helios.servicescommon.coordination.CuratorClientFactory; +import com.spotify.helios.servicescommon.coordination.Paths; +import com.sun.jersey.api.client.ClientResponse; + +import org.apache.curator.framework.CuratorFramework; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.rules.ExpectedException; +import org.junit.rules.TemporaryFolder; +import org.junit.rules.TestRule; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.bridge.SLF4JBridgeHandler; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.net.Socket; +import java.net.URI; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static com.google.common.base.CharMatcher.WHITESPACE; +import static com.google.common.base.Charsets.UTF_8; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.concat; +import static com.google.common.collect.Lists.newArrayList; +import static com.spotify.helios.TemporaryPorts.AllocatedPort; +import static com.spotify.helios.common.descriptors.Goal.UNDEPLOY; +import static com.spotify.helios.common.descriptors.Job.EMPTY_ENV; +import static com.spotify.helios.common.descriptors.Job.EMPTY_EXPIRES; +import static com.spotify.helios.common.descriptors.Job.EMPTY_PORTS; +import static com.spotify.helios.common.descriptors.Job.EMPTY_REGISTRATION; +import static com.spotify.helios.common.descriptors.Job.EMPTY_VOLUMES; +import static java.lang.Integer.toHexString; +import static java.lang.String.format; +import static java.util.Arrays.asList; +import static java.util.concurrent.TimeUnit.MINUTES; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public abstract class SystemTestBase { + + private static final Logger log = LoggerFactory.getLogger(SystemTestBase.class); + + public static final int WAIT_TIMEOUT_SECONDS = 40; + public static final int LONG_WAIT_MINUTES = 10; + public static final int INTERNAL_PORT = 4444; + + public static final String BUSYBOX = "busybox"; + public static final List IDLE_COMMAND = asList("sh", "-c", "while :; do sleep 1; done"); + + public final String testTag = "test_" + toHexString(ThreadLocalRandom.current().nextInt()); + public final String testJobName = "job_" + testTag; + public final String testJobVersion = "v" + toHexString(ThreadLocalRandom.current().nextInt()); + + public static final DockerHost DOCKER_HOST = DockerHost.fromEnv(); + + public static final String TEST_USER = "test-user"; + public static final String TEST_HOST = "test-host"; + public static final String TEST_MASTER = "test-master"; + + @Rule public final TemporaryPorts temporaryPorts = TemporaryPorts.create(); + + @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @Rule public final ExpectedException exception = ExpectedException.none(); + @Rule public final TestRule watcher = new LoggingTestWatcher(); + + private int masterPort; + private int masterAdminPort; + private String masterEndpoint; + private boolean integrationMode; + private Range dockerPortRange; + + private final List services = newArrayList(); + private final List clients = Lists.newArrayList(); + + private String testHost; + private Path agentStateDirs; + private String masterName; + + private ZooKeeperTestManager zk; + + @BeforeClass + public static void staticSetup() { + SLF4JBridgeHandler.removeHandlersForRootLogger(); + SLF4JBridgeHandler.install(); + } + + @Before + public void baseSetup() throws Exception { + masterPort = temporaryPorts.localPort("helios master"); + masterAdminPort = temporaryPorts.localPort("helios master admin"); + + String className = getClass().getName(); + if (className.endsWith("ITCase")) { + masterEndpoint = checkNotNull(System.getenv("HELIOS_ENDPOINT"), + "For integration tests, HELIOS_ENDPOINT *must* be set"); + integrationMode = true; + } else if (className.endsWith("Test")) { + integrationMode = false; + masterEndpoint = "http://localhost:" + masterPort(); + // unit test + } else { + throw new RuntimeException("testClass neither ends in Test or ITCase"); + } + + zk = zooKeeperTestManager(); + listThreads(); + zk.ensure("/config"); + zk.ensure("/status"); + agentStateDirs = temporaryFolder.newFolder("helios-agents").toPath(); + } + + @Before + public void dockerSetup() throws Exception { + final String portRange = System.getenv("DOCKER_PORT_RANGE"); + + final AllocatedPort allocatedPort; + final int probePort; + if (portRange != null) { + final String[] parts = portRange.split(":", 2); + dockerPortRange = Range.closedOpen(Integer.valueOf(parts[0]), + Integer.valueOf(parts[1])); + allocatedPort = Polling.await(LONG_WAIT_MINUTES, MINUTES, new Callable() { + @Override + public AllocatedPort call() throws Exception { + final int port = ThreadLocalRandom.current().nextInt(dockerPortRange.lowerEndpoint(), + dockerPortRange.upperEndpoint()); + return temporaryPorts.tryAcquire("docker-probe", port); + } + }); + probePort = allocatedPort.port(); + } else { + dockerPortRange = temporaryPorts.localPortRange("docker", 10); + probePort = dockerPortRange().lowerEndpoint(); + allocatedPort = null; + } + + try { + assertDockerReachable(probePort); + } finally { + if (allocatedPort != null) { + allocatedPort.release(); + } + } + } + + private void assertDockerReachable(final int probePort) throws Exception { + final DockerClient docker = new DefaultDockerClient(DOCKER_HOST.uri()); + + try { + docker.inspectImage(BUSYBOX); + } catch (ImageNotFoundException e) { + docker.pull(BUSYBOX); + } + + final ContainerConfig config = ContainerConfig.builder() + .image(BUSYBOX) + .cmd("nc", "-p", "4711", "-lle", "cat") + .exposedPorts(ImmutableSet.of("4711/tcp")) + .build(); + final HostConfig hostConfig = HostConfig.builder() + .portBindings(ImmutableMap.of("4711/tcp", + asList(PortBinding.of("0.0.0.0", probePort)))) + .build(); + final ContainerCreation creation = docker.createContainer(config, testTag + "-probe"); + final String containerId = creation.id(); + docker.startContainer(containerId, hostConfig); + + // Wait for container to come up + Polling.await(5, SECONDS, new Callable() { + @Override + public Object call() throws Exception { + final ContainerInfo info = docker.inspectContainer(containerId); + return info.state().running() ? true : null; + } + }); + + log.info("Verifying that docker containers are reachable"); + try { + Polling.awaitUnchecked(5, SECONDS, new Callable() { + @Override + public Object call() throws Exception { + log.info("Probing: {}:{}", DOCKER_HOST.address(), probePort); + try (final Socket ignored = new Socket(DOCKER_HOST.address(), probePort)) { + return true; + } catch (IOException e) { + return false; + } + } + }); + } catch (TimeoutException e) { + fail("Please ensure that DOCKER_HOST is set to an address that where containers can " + + "be reached. If docker is running in a local VM, DOCKER_HOST must be set to the " + + "address of that VM. If docker can only be reached on a limited port range, " + + "set the environment variable DOCKER_PORT_RANGE=start:end"); + } + + docker.killContainer(containerId); + } + + protected ZooKeeperTestManager zooKeeperTestManager() { + return new ZooKeeperStandaloneServerManager(); + } + + @After + public void baseTeardown() throws Exception { + tearDownJobs(); + for (final HeliosClient client : clients) { + client.close(); + } + clients.clear(); + + for (Service service : services) { + try { + service.stopAsync(); + } catch (Exception e) { + log.error("Uncaught exception", e); + } + } + for (Service service : services) { + try { + service.awaitTerminated(); + } catch (Exception e) { + log.error("Service failed", e); + } + } + services.clear(); + + // Clean up docker + try { + final DockerClient dockerClient = new DefaultDockerClient(DOCKER_HOST.uri()); + final List containers = dockerClient.listContainers(); + for (final Container container : containers) { + for (final String name : container.names()) { + if (name.contains(testTag)) { + try { + dockerClient.killContainer(container.id()); + } catch (DockerException e) { + e.printStackTrace(); + } + break; + } + } + } + } catch (Exception e) { + log.error("Docker client exception", e); + } + + if (zk != null) { + zk.close(); + } + + listThreads(); + } + + private void listThreads() { + final Set threads = Thread.getAllStackTraces().keySet(); + final Map sorted = Maps.newTreeMap(); + for (final Thread t : threads) { + final ThreadGroup tg = t.getThreadGroup(); + if (t.isAlive() && (tg == null || !tg.getName().equals("system"))) { + sorted.put(t.getName(), t); + } + } + log.info("= THREADS " + Strings.repeat("=", 70)); + for (final Thread t : sorted.values()) { + final ThreadGroup tg = t.getThreadGroup(); + log.info("{}: \"{}\" ({}{})", t.getId(), t.getName(), + (tg == null ? "" : tg.getName() + " "), + (t.isDaemon() ? "daemon" : "")); + } + log.info(Strings.repeat("=", 80)); + } + + protected void tearDownJobs() throws InterruptedException, ExecutionException { + if (!isIntegration()) { + return; + } + + if (System.getenv("ITCASE_PRESERVE_JOBS") != null) { + return; + } + + final List> undeploys = Lists.newArrayList(); + final HeliosClient c = defaultClient(); + final Map jobs = c.jobs().get(); + for (JobId jobId : jobs.keySet()) { + if (!jobId.toString().startsWith(testTag)) { + continue; + } + final JobStatus st = c.jobStatus(jobId).get(); + final Set hosts = st.getDeployments().keySet(); + for (String host : hosts) { + log.info("Undeploying job " + jobId); + undeploys.add(c.undeploy(jobId, host)); + } + } + Futures.allAsList(undeploys); + + final List> deletes = Lists.newArrayList(); + for (JobId jobId : jobs.keySet()) { + if (!jobId.toString().startsWith(testTag)) { + continue; + } + log.info("Deleting job " + jobId); + deletes.add(c.deleteJob(jobId)); + } + Futures.allAsList(deletes); + } + + protected boolean isIntegration() { + return integrationMode; + } + + protected TemporaryPorts temporaryPorts() { + return temporaryPorts; + } + + protected ZooKeeperTestManager zk() { + return zk; + } + + protected String masterEndpoint() { + return masterEndpoint; + } + + protected String masterName() throws InterruptedException, ExecutionException { + if (integrationMode) { + if (masterName == null) { + masterName = defaultClient().listMasters().get().get(0); + } + return masterName; + } else { + return "test-master"; + } + } + + protected HeliosClient defaultClient() { + return client(TEST_USER, masterEndpoint()); + } + + protected HeliosClient client(final String user, final String endpoint) { + final HeliosClient client = HeliosClient.newBuilder() + .setUser(user) + .setEndpoints(asList(URI.create(endpoint))) + .build(); + clients.add(client); + return client; + } + + protected int masterPort() { + return masterPort; + } + + protected int masterAdminPort() { + return masterAdminPort; + } + + public Range dockerPortRange() { + return dockerPortRange; + } + + protected String testHost() throws InterruptedException, ExecutionException { + if (integrationMode) { + if (testHost == null) { + final List hosts = defaultClient().listHosts().get(); + testHost = hosts.get(new SecureRandom().nextInt(hosts.size())); + } + return testHost; + } else { + return TEST_HOST; + } + } + + protected List setupDefaultMaster(String... args) throws Exception { + if (isIntegration()) { + checkArgument(args.length == 0, + "cannot start default master in integration test with arguments passed"); + return null; + } + + // TODO (dano): Move this bootstrapping to something reusable + final CuratorFramework curator = zk.curator(); + curator.newNamespaceAwareEnsurePath(Paths.configHosts()).ensure(curator.getZookeeperClient()); + curator.newNamespaceAwareEnsurePath(Paths.configJobs()).ensure(curator.getZookeeperClient()); + curator.newNamespaceAwareEnsurePath(Paths.configJobRefs()).ensure(curator.getZookeeperClient()); + curator.newNamespaceAwareEnsurePath(Paths.statusHosts()).ensure(curator.getZookeeperClient()); + curator.newNamespaceAwareEnsurePath(Paths.statusMasters()).ensure(curator.getZookeeperClient()); + curator.newNamespaceAwareEnsurePath(Paths.historyJobs()).ensure(curator.getZookeeperClient()); + + final List argsList = Lists.newArrayList("-vvvv", + "--no-log-setup", + "--http", masterEndpoint(), + "--admin=" + masterAdminPort(), + "--name", TEST_MASTER, + "--domain", "", + "--zk", zk.connectString()); + argsList.addAll(asList(args)); + + return argsList; + } + + protected void startDefaultMaster(String... args) throws Exception { + final List argsList = setupDefaultMaster(args); + + if (argsList == null) { + return; + } + + startMaster(argsList.toArray(new String[argsList.size()])); + waitForMasterToConnectToZK(); + } + + protected void waitForMasterToConnectToZK() throws Exception { + Polling.await(WAIT_TIMEOUT_SECONDS, SECONDS, new Callable() { + @Override + public Object call() { + try { + final List masters = defaultClient().listMasters().get(); + return masters != null; + } catch (Exception e) { + return null; + } + } + }); + } + + protected void startDefaultMasterDontWaitForZK(final CuratorClientFactory curatorClientFactory, + String... args) throws Exception { + List argsList = setupDefaultMaster(args); + + if (argsList == null) { + return; + } + + startMaster(curatorClientFactory, argsList.toArray(new String[argsList.size()])); + } + + protected AgentMain startDefaultAgent(final String host, final String... args) + throws Exception { + if (isIntegration()) { + checkArgument(args.length == 0, + "cannot start default agent in integration test with arguments passed"); + return null; + } + + final String stateDir = agentStateDirs.resolve(host).toString(); + final List argsList = Lists.newArrayList("-vvvv", + "--no-log-setup", + "--no-http", + "--name", host, + "--docker=" + DOCKER_HOST, + "--zk", zk.connectString(), + "--zk-session-timeout", "100", + "--zk-connection-timeout", "100", + "--state-dir", stateDir, + "--domain", "", + "--port-range=" + + dockerPortRange.lowerEndpoint() + ":" + + dockerPortRange.upperEndpoint() + ); + argsList.addAll(asList(args)); + return startAgent(argsList.toArray(new String[argsList.size()])); + } + + protected MasterMain startMaster(final String... args) throws Exception { + final MasterMain main = new MasterMain(args); + main.startAsync().awaitRunning(); + services.add(main); + return main; + } + + MasterMain startMaster(final CuratorClientFactory curatorClientFactory, + final String... args) throws Exception { + final MasterMain main = new MasterMain(curatorClientFactory, args); + main.startAsync().awaitRunning(); + services.add(main); + return main; + } + + protected AgentMain startAgent(final String... args) throws Exception { + final AgentMain main = new AgentMain(args); + main.startAsync().awaitRunning(); + services.add(main); + return main; + } + + protected JobId createJob(final String name, + final String version, + final String image, + final List command) throws Exception { + return createJob(name, version, image, command, EMPTY_ENV, EMPTY_PORTS, EMPTY_REGISTRATION); + } + + protected JobId createJob(final String name, + final String version, + final String image, + final List command, + final Date expires) throws Exception { + return createJob(name, version, image, command, EMPTY_ENV, EMPTY_PORTS, EMPTY_REGISTRATION, + EMPTY_VOLUMES, expires); + } + + protected JobId createJob(final String name, + final String version, + final String image, + final List command, + final ImmutableMap env) + throws Exception { + return createJob(name, version, image, command, env, EMPTY_PORTS, EMPTY_REGISTRATION); + } + + protected JobId createJob(final String name, + final String version, + final String image, + final List command, + final Map env, + final Map ports) throws Exception { + return createJob(name, version, image, command, env, ports, EMPTY_REGISTRATION); + } + + protected JobId createJob(final String name, + final String version, + final String image, + final List command, + final Map env, + final Map ports, + final Map registration) + throws Exception { + return createJob(name, version, image, command, env, ports, registration, EMPTY_VOLUMES); + } + + protected JobId createJob(final String name, + final String version, + final String image, + final List command, + final Map env, + final Map ports, + final Map registration, + final Map volumes) throws Exception { + return createJob(name, version, image, command, env, ports, registration, volumes, + EMPTY_EXPIRES); + } + + protected JobId createJob(final String name, + final String version, + final String image, + final List command, + final Map env, + final Map ports, + final Map registration, + final Map volumes, + final Date expires) throws Exception { + return createJob(Job.newBuilder() + .setName(name) + .setVersion(version) + .setImage(image) + .setCommand(command) + .setEnv(env) + .setPorts(ports) + .setRegistration(registration) + .setVolumes(volumes) + .setExpires(expires) + .build()); + } + + protected JobId createJob(final Job job) throws Exception { + final String name = job.getId().getName(); + final String version = job.getId().getVersion(); + checkArgument(name.contains(testTag), "Job name must contain testTag to enable cleanup"); + + final List args = Lists.newArrayList("-q", name + ':' + version, job.getImage()); + + for (Map.Entry entry : job.getEnv().entrySet()) { + args.add("--env=" + entry.getKey() + "=" + entry.getValue()); + } + + for (final Map.Entry entry : job.getPorts().entrySet()) { + args.add("--port"); + String value = "" + entry.getValue().getInternalPort(); + if (entry.getValue().getExternalPort() != null) { + value += ":" + entry.getValue().getExternalPort(); + } + if (entry.getValue().getProtocol() != null) { + value += "/" + entry.getValue().getProtocol(); + } + args.add(entry.getKey() + "=" + value); + } + + for (final Map.Entry entry : job.getRegistration().entrySet()) { + final ServiceEndpoint r = entry.getKey(); + for (String portName : entry.getValue().getPorts().keySet()) { + args.add("--register=" + ((r.getProtocol() == null) + ? format("%s=%s", r.getName(), portName) + : format("%s/%s=%s", r.getName(), r.getProtocol(), portName))); + } + } + + for (Map.Entry entry : job.getVolumes().entrySet()) { + if (Strings.isNullOrEmpty(entry.getKey())) { + // Data volume + args.add("--volume=" + entry.getKey()); + } else { + // Bind mount + args.add("--volume=" + entry.getValue() + ":" + entry.getKey()); + } + } + + if (job.getExpires() != null) { + args.add("--expires=" + ISO8601Utils.format(job.getExpires())); + } + + args.add("--"); + args.addAll(job.getCommand()); + + final String createOutput = cli("create", args); + final String jobId = WHITESPACE.trimFrom(createOutput); + + final String listOutput = cli("jobs", "-q"); + assertThat(listOutput, containsString(jobId)); + return JobId.fromString(jobId); + } + + protected void deployJob(final JobId jobId, final String host) + throws Exception { + final String deployOutput = cli("deploy", jobId.toString(), host); + assertThat(deployOutput, containsString(host + ": done")); + + final String output = cli("status", "--host", host, "--json"); + final Map statuses = + Json.readUnchecked(output, new TypeReference>() {}); + assertTrue(statuses.keySet().contains(jobId)); + } + + protected void undeployJob(final JobId jobId, final String host) throws Exception { + final String undeployOutput = cli("undeploy", jobId.toString(), host); + assertThat(undeployOutput, containsString(host + ": done")); + + final String output = cli("status", "--host", host, "--json"); + final Map statuses = + Json.readUnchecked(output, new TypeReference>() {}); + final JobStatus status = statuses.get(jobId); + assertTrue(status == null || + status.getDeployments().get(host) == null || + status.getDeployments().get(host).getGoal() == UNDEPLOY); + } + + protected String startJob(final JobId jobId, final String host) throws Exception { + return cli("start", jobId.toString(), host); + } + + protected String stopJob(final JobId jobId, final String host) throws Exception { + return cli("stop", jobId.toString(), host); + } + + protected String deregisterHost(final String host) throws Exception { + return cli("deregister", host, "--force"); + } + + protected String cli(final String command, final Object... args) + throws Exception { + return cli(command, flatten(args)); + } + + protected String cli(final String command, final String... args) + throws Exception { + return cli(command, asList(args)); + } + + protected String cli(final String command, final List args) + throws Exception { + final List commands = asList(command, "-z", masterEndpoint(), "--no-log-setup"); + final List allArgs = newArrayList(concat(commands, args)); + return main(allArgs).toString(); + } + + protected ByteArrayOutputStream main(final String... args) throws Exception { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + final ByteArrayOutputStream err = new ByteArrayOutputStream(); + final CliMain main = new CliMain(new PrintStream(out), new PrintStream(err), args); + main.run(); + return out; + } + + protected ByteArrayOutputStream main(final Collection args) throws Exception { + return main(args.toArray(new String[args.size()])); + } + + protected void awaitHostRegistered(final String name, final long timeout, final TimeUnit timeUnit) + throws Exception { + Polling.await(timeout, timeUnit, new Callable() { + @Override + public Object call() throws Exception { + final String output = cli("hosts", "-q"); + return output.contains(name) ? true : null; + } + }); + } + + protected HostStatus awaitHostStatus(final String name, final HostStatus.Status status, + final int timeout, final TimeUnit timeUnit) + throws Exception { + return Polling.await(timeout, timeUnit, new Callable() { + @Override + public HostStatus call() throws Exception { + final String output = cli("hosts", name, "--json"); + final Map statuses; + try { + statuses = Json.read(output, new TypeReference>() {}); + } catch (IOException e) { + return null; + } + final HostStatus hostStatus = statuses.get(name); + if (hostStatus == null) { + return null; + } + return (hostStatus.getStatus() == status) ? hostStatus : null; + } + }); + } + + protected TaskStatus awaitJobState(final HeliosClient client, final String host, + final JobId jobId, + final TaskStatus.State state, final int timeout, + final TimeUnit timeunit) throws Exception { + return Polling.await(timeout, timeunit, new Callable() { + @Override + public TaskStatus call() throws Exception { + final HostStatus hostStatus = getOrNull(client.hostStatus(host)); + if (hostStatus == null) { + return null; + } + final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId); + return (taskStatus != null && taskStatus.getState() == state) ? taskStatus + : null; + } + }); + } + + protected TaskStatus awaitJobThrottle(final HeliosClient client, final String host, + final JobId jobId, + final ThrottleState throttled, final int timeout, + final TimeUnit timeunit) throws Exception { + return Polling.await(timeout, timeunit, new Callable() { + @Override + public TaskStatus call() throws Exception { + final HostStatus hostStatus = getOrNull(client.hostStatus(host)); + if (hostStatus == null) { + return null; + } + final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId); + return (taskStatus != null && taskStatus.getThrottled() == throttled) ? taskStatus : null; + } + }); + } + + protected void awaitHostRegistered(final HeliosClient client, final String host, + final int timeout, + final TimeUnit timeUnit) throws Exception { + Polling.await(timeout, timeUnit, new Callable() { + @Override + public HostStatus call() throws Exception { + return getOrNull(client.hostStatus(host)); + } + }); + } + + protected HostStatus awaitHostStatus(final HeliosClient client, final String host, + final HostStatus.Status status, + final int timeout, + final TimeUnit timeUnit) throws Exception { + return Polling.await(timeout, timeUnit, new Callable() { + @Override + public HostStatus call() throws Exception { + final HostStatus hostStatus = getOrNull(client.hostStatus(host)); + if (hostStatus == null) { + return null; + } + return (hostStatus.getStatus() == status) ? hostStatus : null; + } + }); + } + + protected TaskStatus awaitTaskState(final JobId jobId, final String host, + final TaskStatus.State state) throws Exception { + long timeout = LONG_WAIT_MINUTES; + TimeUnit timeUnit = MINUTES; + return Polling.await(timeout, timeUnit, new Callable() { + @Override + public TaskStatus call() throws Exception { + final String output = cli("status", "--json", "--job", jobId.toString()); + final Map statusMap; + try { + statusMap = Json.read(output, new TypeReference>() {}); + } catch (IOException e) { + return null; + } + final JobStatus status = statusMap.get(jobId); + if (status == null) { + return null; + } + final TaskStatus taskStatus = status.getTaskStatuses().get(host); + if (taskStatus == null) { + return null; + } + if (taskStatus.getState() != state) { + return null; + } + return taskStatus; + } + }); + } + + protected void awaitTaskGone(final HeliosClient client, final String host, final JobId jobId, + final long timeout, final TimeUnit timeunit) throws Exception { + Polling.await(timeout, timeunit, new Callable() { + @Override + public Boolean call() throws Exception { + final HostStatus hostStatus = getOrNull(client.hostStatus(host)); + final TaskStatus taskStatus = hostStatus.getStatuses().get(jobId); + final Deployment deployment = hostStatus.getJobs().get(jobId); + return taskStatus == null && deployment == null ? true : null; + } + }); + } + + protected T getOrNull(final ListenableFuture future) + throws ExecutionException, InterruptedException { + return Futures.withFallback(future, new FutureFallback() { + @Override + public ListenableFuture create(final Throwable t) throws Exception { + return Futures.immediateFuture(null); + } + }).get(); + } + + protected String readLogFully(final ClientResponse logs) throws IOException { + final LogReader logReader = new LogReader(logs.getEntityInputStream()); + StringBuilder stringBuilder = new StringBuilder(); + LogMessage logMessage; + while ((logMessage = logReader.nextMessage()) != null) { + stringBuilder.append(UTF_8.decode(logMessage.content())); + } + logReader.close(); + return stringBuilder.toString(); + } + + protected static void removeContainer(final DockerClient dockerClient, final String containerId) + throws Exception { + // Work around docker sometimes failing to remove a container directly after killing it + Polling.await(1, MINUTES, new Callable() { + @Override + public Object call() throws Exception { + try { + dockerClient.killContainer(containerId); + dockerClient.removeContainer(containerId); + return true; + } catch (ContainerNotFoundException e) { + // We're done here + return true; + } catch (DockerException e) { + if ((e instanceof DockerRequestException) && + ((DockerRequestException) e).message().contains( + "Driver btrfs failed to remove root filesystem")) { + // Workaround btrfs issue where removing containers throws an exception, + // but succeeds anyway. + return true; + } else { + return null; + } + } + } + }); + try { + // This should fail with an exception if the container still exists + dockerClient.inspectContainer(containerId); + fail(); + } catch (DockerException ignore) { + } + } + + protected List listContainers(final DockerClient dockerClient, final String needle) + throws DockerException, InterruptedException { + final List containers = dockerClient.listContainers(); + final List matches = Lists.newArrayList(); + for (final Container container : containers) { + if (container.names() != null) { + for (final String name : container.names()) { + if (name.contains(needle)) { + matches.add(container); + break; + } + } + } + } + return matches; + } + + protected List flatten(final Object... values) { + final Iterable valuesList = asList(values); + return flatten(valuesList); + } + + protected List flatten(final Iterable values) { + final List list = new ArrayList<>(); + for (Object value : values) { + if (value instanceof Iterable) { + list.addAll(flatten((Iterable) value)); + } else if (value.getClass() == String[].class) { + list.addAll(asList((String[]) value)); + } else if (value instanceof String) { + list.add((String) value); + } else { + throw new IllegalArgumentException(); + } + } + return list; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.spotify.docker.client.DefaultDockerClient` acquired by call to `new()` at line 322 is not released after line 341. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SystemTestBase.baseTeardown() + +### Procedure Id: +com.spotify.helios.system.SystemTestBase.baseTeardown():void.133e9fcd4ccddb4c8c340aac28606fe0 + +### File: +helios-system-tests/src/main/java/com/spotify/helios/system/SystemTestBase.java + +### Key: +SystemTestBase.java|baseTeardown|RESOURCE_LEAK + +### Node Key: +f7047c406cabcf9dfda157fe072d71ae + +### Hash: +2766ba3258e03210425e881aa436820d + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3522/instruction.md b/inferredbugs-3522/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2a9fae17ec3e702277b6b5a4f3b88d9160b587df --- /dev/null +++ b/inferredbugs-3522/instruction.md @@ -0,0 +1,198 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helios +**Bug ID:** 21 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2014 Spotify AB. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.spotify.helios.cli.command; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; + +import com.spotify.helios.client.HeliosClient; +import com.spotify.helios.common.descriptors.Deployment; +import com.spotify.helios.common.descriptors.JobId; +import com.spotify.helios.common.protocol.JobDeployResponse; + +import net.sourceforge.argparse4j.inf.Argument; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; + +import java.io.BufferedReader; +import java.io.PrintStream; +import java.util.List; +import java.util.concurrent.ExecutionException; + +import static com.spotify.helios.common.descriptors.Goal.START; +import static com.spotify.helios.common.descriptors.Goal.STOP; +import static net.sourceforge.argparse4j.impl.Arguments.storeTrue; + +public class JobDeployCommand extends WildcardJobCommand { + + private final Argument hostsArg; + private final Argument tokenArg; + private final Argument noStartArg; + private final Argument watchArg; + private final Argument intervalArg; + + public JobDeployCommand(final Subparser parser) { + super(parser); + + parser.help("deploy a job to hosts"); + + hostsArg = parser.addArgument("hosts") + .nargs("+") + .help("The hosts to deploy the job on."); + + tokenArg = parser.addArgument("--token") + .nargs("?") + .setDefault("") + .help("Insecure access token"); + + noStartArg = parser.addArgument("--no-start") + .action(storeTrue()) + .help("Deploy job without starting it."); + + watchArg = parser.addArgument("--watch") + .action(storeTrue()) + .help("Watch the newly deployed job (like running job watch right after)"); + + intervalArg = parser.addArgument("--interval") + .setDefault(1) + .help("if --watch is specified, the polling interval, default 1 second"); + } + + @Override + protected int runWithJobId(final Namespace options, final HeliosClient client, + final PrintStream out, final boolean json, final JobId jobId, + final BufferedReader stdin) + throws ExecutionException, InterruptedException { + final List hosts = options.getList(hostsArg.getDest()); + final Deployment job = Deployment.of(jobId, + options.getBoolean(noStartArg.getDest()) ? STOP : START); + + if (!json) { + out.printf("Deploying %s on %s%n", job, hosts); + } + + int code = 0; + + final HostResolver resolver = HostResolver.create(client); + + final List resolvedHosts = Lists.newArrayList(); + for (final String candidateHost : hosts) { + final String host = resolver.resolveName(candidateHost); + resolvedHosts.add(host); + if (!json) { + out.printf("%s: ", host); + } + final String token = options.getString(tokenArg.getDest()); + final JobDeployResponse result = client.deploy(job, host, token).get(); + if (result.getStatus() == JobDeployResponse.Status.OK) { + if (!json) { + out.printf("done%n"); + } else { + out.printf(result.toJsonString()); + } + } else { + if (!json) { + out.printf("failed: %s%n", result); + } else { + out.printf(result.toJsonString()); + } + code = 1; + } + } + + if (code == 0 && options.getBoolean(watchArg.getDest())) { + JobWatchCommand.watchJobsOnHosts(out, true, resolvedHosts, ImmutableList.of(jobId), + options.getInt(intervalArg.getDest()), client); + } + return code; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +CHECKERS_PRINTF_ARGS + +### Qualifier: +Format string must be string literal. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int JobDeployCommand.runWithJobId(Namespace,HeliosClient,PrintStream,boolean,JobId,BufferedReader) + +### Procedure Id: +com.spotify.helios.cli.command.JobDeployCommand.runWithJobId(net.sourceforge.argparse4j.inf.Namespac.6e5535246c1ff403694d6b6865b49e00 + +### File: +helios-tools/src/main/java/com/spotify/helios/cli/command/JobDeployCommand.java + +### Key: +JobDeployCommand.java|runWithJobId|CHECKERS_PRINTF_ARGS + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +af2f3e9525e46d1843b40940065204ea + +### Bug Type Hum: +Checkers Printf Args + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3523/instruction.md b/inferredbugs-3523/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..65198911e165f9bff3d125b452d336daa534d4ae --- /dev/null +++ b/inferredbugs-3523/instruction.md @@ -0,0 +1,198 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helios +**Bug ID:** 31 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2014 Spotify AB. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.spotify.helios.servicescommon; + +import com.google.common.collect.ImmutableList; + +import com.spotify.helios.ZooKeeperTestingServerManager; +import com.spotify.helios.common.descriptors.JobId; +import com.spotify.helios.servicescommon.coordination.DefaultZooKeeperClient; +import com.spotify.helios.servicescommon.coordination.Paths; +import com.spotify.helios.servicescommon.coordination.ZooKeeperClient; +import com.spotify.helios.servicescommon.coordination.ZooKeeperOperation; + +import org.apache.zookeeper.data.Stat; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static com.google.common.base.Charsets.UTF_8; +import static org.hamcrest.Matchers.contains; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.mockito.Matchers.anyListOf; +import static org.mockito.Mockito.verify; + +@RunWith(MockitoJUnitRunner.class) +public class ZooKeeperRegistrarServiceUtilTest { + + private static final String HOSTNAME = "host"; + private static final String ID = UUID.randomUUID().toString(); + private static final JobId JOB_ID1 = + JobId.newBuilder().setName("job1").setVersion("0.1.0").build(); + private static final JobId JOB_ID2 = + JobId.newBuilder().setName("job2").setVersion("0.2.0").build(); + private static final List JOB_IDS = ImmutableList.of(JOB_ID1, JOB_ID2); + private static final String JOB_STRING1 = JOB_ID1.toString(); + private static final String JOB_STRING2 = JOB_ID2.toString(); + private static final List JOB_STRINGS = ImmutableList.of(JOB_STRING1, JOB_STRING2); + + @Mock ZooKeeperClient zkClient; + + @Test + public void testRegisterHost() throws Exception { + final String idPath = Paths.configHostId(HOSTNAME); + ZooKeeperRegistrarUtil.registerHost(zkClient, idPath, HOSTNAME, ID); + verify(zkClient).ensurePath(Paths.configHost(HOSTNAME)); + verify(zkClient).ensurePath(Paths.configHostJobs(HOSTNAME)); + verify(zkClient).ensurePath(Paths.configHostPorts(HOSTNAME)); + verify(zkClient).ensurePath(Paths.statusHost(HOSTNAME)); + verify(zkClient).ensurePath(Paths.statusHostJobs(HOSTNAME)); + verify(zkClient).createAndSetData(idPath, ID.getBytes(UTF_8)); + } + + @Test + public void testDeregisterHost() throws Exception { + ZooKeeperRegistrarUtil.deregisterHost(zkClient, HOSTNAME); + verify(zkClient).transaction(anyListOf(ZooKeeperOperation.class)); + } + + // Verify that the re-registering: + // * does not change the /config/hosts/ subtree, except the host-id. + // * deletes everything under /status/hosts/ subtree. + @Test + public void testReRegisterHost() throws Exception { + ZooKeeperTestingServerManager testingServerManager = null; + try { + testingServerManager = new ZooKeeperTestingServerManager(); + testingServerManager.awaitUp(5, TimeUnit.SECONDS); + + final ZooKeeperClient zkClient = new DefaultZooKeeperClient( + testingServerManager.curatorWithSuperAuth()); + + // Register the host & add some fake data to its status & config dirs + final String idPath = Paths.configHostId(HOSTNAME); + ZooKeeperRegistrarUtil.registerHost(zkClient, idPath, HOSTNAME, ID); + zkClient.ensurePath(Paths.statusHostJob(HOSTNAME, JOB_ID1)); + zkClient.ensurePath(Paths.configHostJob(HOSTNAME, JOB_ID1)); + final Stat jobConfigStat = zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1)); + + // ... and then re-register it + final String newId = UUID.randomUUID().toString(); + ZooKeeperRegistrarUtil.reRegisterHost(zkClient, HOSTNAME, newId); + + // Verify that the host-id was updated + assertEquals(newId, new String(zkClient.getData(idPath))); + + // Verify that /status/hosts//jobs exists and is EMPTY + assertNotNull(zkClient.exists(Paths.statusHostJobs(HOSTNAME))); + assertThat(zkClient.listRecursive(Paths.statusHostJobs(HOSTNAME)), + contains(Paths.statusHostJobs(HOSTNAME))); + // Verify that re-registering didn't change the nodes in /config/hosts//jobs + assertEquals( + jobConfigStat, + zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1)) + ); + } finally { + if (testingServerManager != null) { + testingServerManager.close(); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.curator.test.TestingServer` acquired by call to `ZooKeeperTestingServerManager()` at line 88 is not released after line 88. +**Note**: potential exception at line 88 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ZooKeeperRegistrarServiceUtilTest.testReRegisterHost() + +### Procedure Id: +com.spotify.helios.servicescommon.ZooKeeperRegistrarServiceUtilTest.testReRegisterHost():void.3bf8e8c7756c290996e8ea79f81eda49 + +### File: +helios-services/src/test/java/com/spotify/helios/servicescommon/ZooKeeperRegistrarServiceUtilTest.java + +### Key: +ZooKeeperRegistrarServiceUtilTest.java|testReRegisterHost|RESOURCE_LEAK + +### Node Key: +557488ea6c00b9cd0110e65bfe07a3d7 + +### Hash: +548b839110b3d7be51dfb68c995f79b5 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3524/instruction.md b/inferredbugs-3524/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..932fb5418b63826d389de103432bb58f1d16b11f --- /dev/null +++ b/inferredbugs-3524/instruction.md @@ -0,0 +1,507 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helios +**Bug ID:** 30 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2014 Spotify AB. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.spotify.helios.servicescommon.coordination; + +import com.google.common.collect.ImmutableList; + +import com.fasterxml.jackson.databind.JavaType; + +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.api.transaction.CuratorTransactionFinal; +import org.apache.curator.framework.api.transaction.CuratorTransactionResult; +import org.apache.curator.framework.listen.Listenable; +import org.apache.curator.framework.recipes.nodes.PersistentEphemeralNode; +import org.apache.curator.framework.state.ConnectionState; +import org.apache.curator.framework.state.ConnectionStateListener; +import org.apache.curator.utils.EnsurePath; +import org.apache.curator.utils.ZKPaths; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.ZKUtil; +import org.apache.zookeeper.ZooKeeper; +import org.apache.zookeeper.data.ACL; +import org.apache.zookeeper.data.Stat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import static com.google.common.base.Strings.emptyToNull; +import static com.google.common.base.Strings.isNullOrEmpty; +import static com.google.common.base.Throwables.propagate; +import static com.google.common.base.Throwables.propagateIfInstanceOf; +import static com.google.common.collect.Lists.reverse; +import static java.util.Arrays.asList; +import static java.util.Collections.emptyList; + +public class DefaultZooKeeperClient implements ZooKeeperClient { + + private static final Logger log = LoggerFactory.getLogger(DefaultZooKeeperClient.class); + + private final CuratorFramework client; + private final String clusterId; + private final AtomicBoolean clusterIdExists; + private final Watcher watcher; + private final ConnectionStateListener connectionStateListener; + + public DefaultZooKeeperClient(final CuratorFramework client) { + this(client, null); + } + + public DefaultZooKeeperClient(final CuratorFramework client, final String clusterId) { + this.client = client; + this.clusterId = clusterId; + + if (clusterId == null) { + this.clusterIdExists = null; + this.watcher = null; + this.connectionStateListener = null; + return; + } + + this.clusterIdExists = new AtomicBoolean(false); + + this.watcher = new Watcher() { + @Override + public void process(WatchedEvent event) { + log.info("DefaultZooKeeperClient processing WatchedEvent - {}", event); + checkClusterIdExists(clusterId, "watcher"); + } + }; + + connectionStateListener = new ConnectionStateListener() { + @Override + public void stateChanged(CuratorFramework client, ConnectionState newState) { + log.info("DefaultZooKeeperClient connection state change - {}", newState); + if (newState == ConnectionState.RECONNECTED) { + checkClusterIdExists(clusterId, "connectionStateListener"); + } + } + }; + } + + @Override + public CuratorFramework getCuratorFramework() { + return client; + } + + @Override + /** {@inheritDoc} */ + public void ensurePath(final String path) throws KeeperException { + assertClusterIdFlagTrue(); + ensurePath(path, false); + } + + @Override + /** {@inheritDoc} */ + public void ensurePath(final String path, final boolean excludingLast) throws KeeperException { + assertClusterIdFlagTrue(); + EnsurePath ensurePath = client.newNamespaceAwareEnsurePath(path); + if (excludingLast) { + ensurePath = ensurePath.excludingLast(); + } + try { + ensurePath.ensure(client.getZookeeperClient()); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public byte[] getData(final String path) throws KeeperException { + assertClusterIdFlagTrue(); + try { + return client.getData().forPath(path); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public Node getNode(final String path) throws KeeperException { + assertClusterIdFlagTrue(); + final Stat stat = new Stat(); + try { + byte[] bytes = client.getData().storingStatIn(stat).forPath(path); + return new Node(path, bytes, stat); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public Stat exists(final String path) throws KeeperException { + return stat(path); + } + + @Override + public void start() { + client.start(); + if (clusterId != null) { + client.getConnectionStateListenable().addListener(connectionStateListener); + checkClusterIdExists(clusterId, "start"); + } + } + + @Override + public void close() { + if (clusterId != null) { + client.getConnectionStateListenable().removeListener(connectionStateListener); + } + client.close(); + } + + @Override + public PersistentEphemeralNode persistentEphemeralNode(final String path, + final PersistentEphemeralNode.Mode mode, + final byte[] data) { + assertClusterIdFlagTrue(); + return new PersistentEphemeralNode(client, mode, path, data); + } + + @Override + public Listenable getConnectionStateListenable() { + return client.getConnectionStateListenable(); + } + + @Override + public ZooKeeper.States getState() throws KeeperException { + assertClusterIdFlagTrue(); + try { + return client.getZookeeperClient().getZooKeeper().getState(); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public List getChildren(final String path) throws KeeperException { + assertClusterIdFlagTrue(); + try { + return client.getChildren().forPath(path); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public void deleteRecursive(final String path) throws KeeperException { + assertClusterIdFlagTrue(); + try { + final List nodes = listRecursive(path); + if (nodes.isEmpty()) { + return; + } + final CuratorTransactionFinal t = client.inTransaction().check().forPath(path).and(); + for (final String node : reverse(nodes)) { + t.delete().forPath(node).and(); + } + t.commit(); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public List listRecursive(final String path) throws KeeperException { + assertClusterIdFlagTrue(); + + // namespace the path since we're using zookeeper directly + final String namespace = emptyToNull(client.getNamespace()); + final String namespacedPath = ZKPaths.fixForNamespace(namespace, path); + + try { + final List paths = ZKUtil.listSubTreeBFS( + client.getZookeeperClient().getZooKeeper(), namespacedPath); + + if (isNullOrEmpty(namespace)) { + return paths; + } else { + // hide the namespace in the paths returned from zookeeper + final ImmutableList.Builder builder = ImmutableList.builder(); + for (final String p : paths) { + final String fixed; + if (p.startsWith("/" + namespace)) { + fixed = (p.length() > namespace.length() + 1) + ? p.substring(namespace.length() + 1) + : "/"; + } else { + fixed = p; + } + + builder.add(fixed); + } + + return builder.build(); + } + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public void delete(final String path) throws KeeperException { + assertClusterIdFlagTrue(); + try { + client.delete().forPath(path); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public void delete(final String path, final int version) throws KeeperException { + assertClusterIdFlagTrue(); + + final String namespace = emptyToNull(client.getNamespace()); + final String namespacedPath = ZKPaths.fixForNamespace(namespace, path); + try { + client.getZookeeperClient().getZooKeeper().delete(namespacedPath, version); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public void createAndSetData(final String path, final byte[] data) throws KeeperException { + assertClusterIdFlagTrue(); + try { + client.create().forPath(path, data); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public void create(final String path) throws KeeperException { + assertClusterIdFlagTrue(); + try { + client.create().forPath(path); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public void createWithMode(final String path, final CreateMode mode) throws KeeperException { + assertClusterIdFlagTrue(); + try { + client.create().withMode(mode).forPath(path); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public void setData(final String path, final byte[] data) throws KeeperException { + assertClusterIdFlagTrue(); + try { + client.setData().forPath(path, data); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public Stat stat(final String path) throws KeeperException { + assertClusterIdFlagTrue(); + try { + return client.checkExists().forPath(path); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public PersistentPathChildrenCache pathChildrenCache(final String path, + final Path snapshotFile, + final JavaType valueType) + throws IOException, InterruptedException { + return new PersistentPathChildrenCache(client, path, clusterId, snapshotFile, valueType); + } + + @Override + public Collection transaction(final List operations) + throws KeeperException { + assertClusterIdFlagTrue(); + log.debug("transaction: {}", operations); + + if (operations.isEmpty()) { + return emptyList(); + } + + // Assemble transaction + final CuratorTransactionFinal transaction = (CuratorTransactionFinal) client.inTransaction(); + for (final ZooKeeperOperation operation : operations) { + try { + operation.register(transaction); + } catch (final Exception e) { + throw propagate(e); + } + } + + // Commit + try { + return transaction.commit(); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public Collection transaction(final ZooKeeperOperation... operations) + throws KeeperException { + return transaction(asList(operations)); + } + + @Override + public void setAcl(final String path, final List aclList) throws KeeperException { + assertClusterIdFlagTrue(); + try { + client.setACL().withACL(aclList).forPath(path); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + @Override + public List getAcl(final String path) throws KeeperException { + assertClusterIdFlagTrue(); + try { + return client.getACL().forPath(path); + } catch (Exception e) { + propagateIfInstanceOf(e, KeeperException.class); + throw propagate(e); + } + } + + private void assertClusterIdFlagTrue() { + if (clusterId != null && !clusterIdExists.get()) { + throw new IllegalStateException("ZooKeeper cluster ID does not exist"); + } + } + + private void checkClusterIdExists(final String id, final String checker) { + try { + final Stat stat = client.checkExists().usingWatcher(watcher).forPath(Paths.configId(id)); + final boolean exists = stat != null; + clusterIdExists.set(exists); + log.info("Cluster ID {} {} when checked by {}", id, exists ? "exists" : "does not exist", + checker); + } catch (Exception e) { + clusterIdExists.set(false); + log.error("Exception while checking ZooKeeper cluster ID {}", clusterId, e); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `namespace` last assigned on line 237 at line 252. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List DefaultZooKeeperClient.listRecursive(String) + +### Procedure Id: +com.spotify.helios.servicescommon.coordination.DefaultZooKeeperClient.listRecursive(java.lang.String.33796d928bd10e3cc5989cbcf31c81e4 + +### File: +helios-services/src/main/java/com/spotify/helios/servicescommon/coordination/DefaultZooKeeperClient.java + +### Key: +DefaultZooKeeperClient.java|listRecursive|NULL_DEREFERENCE + +### Node Key: +00c1f65e387d55c612515ace03b6e05b + +### Hash: +0500384d7120f799907a2d5bc033ab9f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3525/instruction.md b/inferredbugs-3525/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..426068360ee9d5a00bc77975ab534e3c24f0e2ec --- /dev/null +++ b/inferredbugs-3525/instruction.md @@ -0,0 +1,228 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helios +**Bug ID:** 24 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2014 Spotify AB. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.spotify.helios.cli.command; + +import com.google.common.collect.ImmutableList; + +import com.spotify.helios.cli.Utils; +import com.spotify.helios.client.HeliosClient; +import com.spotify.helios.common.descriptors.JobId; +import com.spotify.helios.common.descriptors.JobStatus; +import com.spotify.helios.common.protocol.JobUndeployResponse; + +import net.sourceforge.argparse4j.inf.Argument; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintStream; +import java.util.List; +import java.util.concurrent.ExecutionException; + +import static net.sourceforge.argparse4j.impl.Arguments.storeTrue; + +public class JobUndeployCommand extends WildcardJobCommand { + + private static final Logger log = LoggerFactory.getLogger(JobUndeployCommand.class); + + private final Argument hostsArg; + private final Argument tokenArg; + private final Argument allArg; + private final Argument yesArg; + private final Argument forceArg; + + public JobUndeployCommand(final Subparser parser) { + super(parser); + + parser.help("undeploy a job from hosts"); + + hostsArg = parser.addArgument("hosts") + .nargs("*") + .help("The hosts to undeploy the job from."); + + tokenArg = parser.addArgument("--token") + .nargs("?") + .setDefault("") + .help("Insecure access token"); + + allArg = parser.addArgument("-a", "--all") + .action(storeTrue()) + .help("Undeploy from all currently deployed hosts."); + + yesArg = parser.addArgument("--yes") + .action(storeTrue()) + .help("Automatically answer 'yes' to the interactive prompt."); + + // TODO (dxia) Deprecated, remove at a later date + forceArg = parser.addArgument("--force") + .action(storeTrue()) + .help("Automatically answer 'yes' to the interactive prompt."); + } + + @Override + protected int runWithJobId(final Namespace options, final HeliosClient client, + final PrintStream out, final boolean json, final JobId jobId, + final BufferedReader stdin) + throws ExecutionException, InterruptedException, IOException { + + final boolean all = options.getBoolean(allArg.getDest()); + final boolean yes = options.getBoolean(yesArg.getDest()); + final boolean force = options.getBoolean(forceArg.getDest()); + final List hosts; + + if (force) { + log.warn("If you are using '--force' to skip the interactive prompt, " + + "note that we have deprecated it. Please use '--yes'."); + } + + if (all) { + final JobStatus status = client.jobStatus(jobId).get(); + hosts = ImmutableList.copyOf(status.getDeployments().keySet()); + if (hosts.isEmpty()) { + out.printf("%s is not currently deployed on any hosts.", jobId); + return 0; + } + + if (!yes && !force) { + out.printf("This will undeploy %s from %s%n", jobId, hosts); + final boolean confirmed = Utils.userConfirmed(out, stdin); + if (!confirmed) { + return 1; + } + } + } else { + hosts = options.getList(hostsArg.getDest()); + if (hosts.isEmpty()) { + out.println("Please either specify a list of hosts or use the -a/--all flag."); + return 1; + } + } + + if (!json) { + out.printf("Undeploying %s from %s%n", jobId, hosts); + } + + int code = 0; + final HostResolver resolver = HostResolver.create(client); + + for (final String candidateHost : hosts) { + final String host = resolver.resolveName(candidateHost); + + if (!json) { + out.printf("%s: ", host); + } + + final String token = options.getString(tokenArg.getDest()); + final JobUndeployResponse response = client.undeploy(jobId, host, token).get(); + if (response.getStatus() == JobUndeployResponse.Status.OK) { + if (!json) { + out.println("done"); + } else { + out.printf(response.toJsonString()); + } + } else { + if (!json) { + out.println("failed: " + response); + } else { + out.printf(response.toJsonString()); + } + code = -1; + } + } + + return code; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +CHECKERS_PRINTF_ARGS + +### Qualifier: +Format string must be string literal. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int JobUndeployCommand.runWithJobId(Namespace,HeliosClient,PrintStream,boolean,JobId,BufferedReader) + +### Procedure Id: +com.spotify.helios.cli.command.JobUndeployCommand.runWithJobId(net.sourceforge.argparse4j.inf.Namesp.2acf00262d33b09575d55f02df9bf88e + +### File: +helios-tools/src/main/java/com/spotify/helios/cli/command/JobUndeployCommand.java + +### Key: +JobUndeployCommand.java|runWithJobId|CHECKERS_PRINTF_ARGS + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +aa1bef4b408e61e9368e535a07df40f8 + +### Bug Type Hum: +Checkers Printf Args + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3541/instruction.md b/inferredbugs-3541/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..58267551a23c2caaa1f907b9fed5bc5eee5948c9 --- /dev/null +++ b/inferredbugs-3541/instruction.md @@ -0,0 +1,768 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** kiftd-source +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package kohgylw.kiftd.server.service.impl; + +import kohgylw.kiftd.server.service.*; + +import org.springframework.stereotype.*; +import kohgylw.kiftd.server.mapper.*; +import javax.annotation.*; +import kohgylw.kiftd.server.enumeration.*; +import kohgylw.kiftd.server.model.*; +import kohgylw.kiftd.server.pojo.CheckUploadFilesRespons; +import kohgylw.kiftd.server.pojo.UploadKeyCertificate; + +import org.springframework.web.multipart.*; + +import javax.servlet.http.*; +import java.io.*; +import java.nio.charset.Charset; + +import kohgylw.kiftd.server.util.*; +import java.util.*; + +import com.google.gson.*; +import com.google.gson.reflect.TypeToken; + +/** + * + *

    文件服务功能实现类

    + *

    + * 该类负责对文件相关的服务进行实现操作,例如下载和上传等,各方法功能详见接口定义。 + *

    + * + * @author 青阳龙野(kohgylw) + * @version 1.0 + * @see kohgylw.kiftd.server.service.FileService + */ +@Service +public class FileServiceImpl extends RangeFileStreamWriter implements FileService { + private static final String ERROR_PARAMETER = "errorParameter";// 参数错误标识 + private static final String NO_AUTHORIZED = "noAuthorized";// 权限错误标识 + private static final String UPLOADSUCCESS = "uploadsuccess";// 上传成功标识 + private static final String UPLOADERROR = "uploaderror";// 上传失败标识 + + private static Map keyEffecMap = new HashMap<>();// 上传次数凭证表,用于记录用次数有限但时间不限的上传凭证 + + @Resource + private NodeMapper fm; + @Resource + private FolderMapper flm; + @Resource + private LogUtil lu; + @Resource + private Gson gson; + @Resource + private FileBlockUtil fbu; + @Resource + private FolderUtil fu; + + private static final String CONTENT_TYPE = "application/octet-stream"; + + // 检查上传文件列表的实现 + public String checkUploadFile(final HttpServletRequest request, final HttpServletResponse response) { + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + final String folderId = request.getParameter("folderId"); + final String nameList = request.getParameter("namelist"); + // 先行权限检查 + if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { + return NO_AUTHORIZED; + } + // 获得上传文件名列表 + final List namelistObj = gson.fromJson(nameList, new TypeToken>() { + }.getType()); + final List pereFileNameList = new ArrayList<>(); + // 查找目标目录下是否存在与待上传文件同名的文件(或文件夹),如果有,记录在上方的列表中 + for (final String fileName : namelistObj) { + if (folderId == null || folderId.length() <= 0 || fileName == null || fileName.length() <= 0) { + return ERROR_PARAMETER; + } + final List files = this.fm.queryByParentFolderId(folderId); + if (files.stream().parallel().anyMatch((n) -> n.getFileName() + .equals(new String(fileName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"))))) { + pereFileNameList.add(fileName); + } + } + // 为客户端分发一个凭证,该凭证可使用本次声明要上传的次数,但不限时长。 + String key = UUID.randomUUID().toString(); + synchronized (keyEffecMap) { + keyEffecMap.put(key, new UploadKeyCertificate(namelistObj.size(), account)); + } + // 装订检查结果 + CheckUploadFilesRespons cufr = new CheckUploadFilesRespons(); + cufr.setUploadKey(key);// 分配一个凭证 + // 如果存在同名文件,则写入同名文件的列表;否则,直接允许上传 + if (pereFileNameList.size() > 0) { + cufr.setCheckResult("hasExistsNames"); + cufr.setPereFileNameList(pereFileNameList); + } else { + cufr.setCheckResult("permitUpload"); + cufr.setPereFileNameList(new ArrayList()); + } + return gson.toJson(cufr);// 以JSON格式写回该结果 + } + + // 执行上传操作,接收文件并存入文件节点 + public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, + final MultipartFile file) { + String account = (String) request.getSession().getAttribute("ACCOUNT"); + final String folderId = request.getParameter("folderId"); + final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), + Charset.forName("UTF-8")); + String fileName = originalFileName; + final String repeType = request.getParameter("repeType"); + // 再次检查上传文件名与目标目录ID + if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { + return UPLOADERROR; + } + // 检查上传凭证,如果有则允许上传,否则丢弃该资源。该凭证用完后立即销毁。 + String uploadKey = request.getParameter("uploadKey"); + if (uploadKey != null) { + synchronized (keyEffecMap) { + UploadKeyCertificate c = keyEffecMap.get(uploadKey); + if (c != null && c.isEffective()) {// 比对凭证有效性 + c.checked();// 使用一次 + account = c.getAccount(); + if (!c.isEffective()) { + keyEffecMap.remove(uploadKey);// 用完后销毁这个凭证 + } + } else { + return UPLOADERROR; + } + } + } else { + return UPLOADERROR; + } + // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 + final List files = this.fm.queryByParentFolderId(folderId); + if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { + // 针对存在同名文件的操作 + if (repeType != null) { + switch (repeType) { + // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) + case "skip": + return UPLOADSUCCESS; + // 覆盖则找到已存在文件节点的File并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息) + case "cover": + // 其中覆盖操作同时要求用户必须具备删除权限 + if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { + return UPLOADERROR; + } + for (Node f : files) { + if (f.getFileName().equals(originalFileName)) { + File file2 = fbu.getFileFromBlocks(f); + try { + file.transferTo(file2); + f.setFileSize(fbu.getFileSize(file)); + f.setFileCreationDate(ServerTimeUtil.accurateToDay()); + if (account != null) { + f.setFileCreator(account); + } else { + f.setFileCreator("\u533f\u540d\u7528\u6237"); + } + if (fm.update(f) > 0) { + this.lu.writeUploadFileEvent(f, account); + return UPLOADSUCCESS; + } else { + return UPLOADERROR; + } + } catch (Exception e) { + // TODO 自动生成的 catch 块 + return UPLOADERROR; + } + } + } + return UPLOADERROR; + // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 + case "both": + // 设置新文件名为标号形式 + fileName = FileNodeUtil.getNewNodeName(originalFileName, files); + break; + default: + // 其他声明,容错,暂无效果 + return UPLOADERROR; + } + } else { + // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 + return UPLOADERROR; + } + } + // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 + final String path = this.fbu.saveToFileBlocks(file); + if (path.equals("ERROR")) { + return UPLOADERROR; + } + final String fsize = this.fbu.getFileSize(file); + final Node f2 = new Node(); + f2.setFileId(UUID.randomUUID().toString()); + if (account != null) { + f2.setFileCreator(account); + } else { + f2.setFileCreator("\u533f\u540d\u7528\u6237"); + } + f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); + f2.setFileName(fileName); + f2.setFileParentFolder(folderId); + f2.setFilePath(path); + f2.setFileSize(fsize); + int i = 0; + // 尽可能避免UUID重复的情况发生,重试10次 + while (true) { + try { + if (this.fm.insert(f2) > 0) { + this.lu.writeUploadFileEvent(f2, account); + return UPLOADSUCCESS; + } + break; + } catch (Exception e) { + f2.setFileId(UUID.randomUUID().toString()); + i++; + } + if (i >= 10) { + break; + } + } + return UPLOADERROR; + } + + // 删除单个文件,该功能与删除多个文件重复,计划合并二者 + public String deleteFile(final HttpServletRequest request) { + // 接收参数并接续要删除的文件 + final String fileId = request.getParameter("fileId"); + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { + return NO_AUTHORIZED; + } + if (fileId == null || fileId.length() <= 0) { + return ERROR_PARAMETER; + } + // 确认要删除的文件存在 + final Node file = this.fm.queryById(fileId); + if (file == null) { + return ERROR_PARAMETER; + } + // 从文件块删除 + if (!this.fbu.deleteFromFileBlocks(file)) { + return "cannotDeleteFile"; + } + // 从节点删除 + if (this.fm.deleteById(fileId) > 0) { + this.lu.writeDeleteFileEvent(request, file); + return "deleteFileSuccess"; + } + return "cannotDeleteFile"; + } + + // 普通下载:下载单个文件 + public void doDownloadFile(final HttpServletRequest request, final HttpServletResponse response) { + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + // 权限检查 + if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) { + // 找到要下载的文件节点 + final String fileId = request.getParameter("fileId"); + if (fileId != null) { + final Node f = this.fm.queryById(fileId); + if (f != null) { + // 执行写出 + final File fo = this.fbu.getFileFromBlocks(f); + writeRangeFileStream(request, response, fo, f.getFileName(), CONTENT_TYPE); + // 日志记录(仅针对一次下载) + if (request.getHeader("Range") == null) { + this.lu.writeDownloadFileEvent(request, f); + } + return; + } + } + } + try { + //  处理无法下载的资源 + response.sendError(404); + } catch (IOException e) { + // TODO 自动生成的 catch 块 + + } + } + + // 重命名文件 + public String doRenameFile(final HttpServletRequest request) { + final String fileId = request.getParameter("fileId"); + final String newFileName = request.getParameter("newFileName"); + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + // 权限检查 + if (!ConfigureReader.instance().authorized(account, AccountAuth.RENAME_FILE_OR_FOLDER)) { + return NO_AUTHORIZED; + } + // 参数检查 + if (fileId == null || fileId.length() <= 0 || newFileName == null || newFileName.length() <= 0) { + return ERROR_PARAMETER; + } + if (!TextFormateUtil.instance().matcherFileName(newFileName) || newFileName.indexOf(".") == 0) { + return ERROR_PARAMETER; + } + final Node file = this.fm.queryById(fileId); + if (file == null) { + return ERROR_PARAMETER; + } + if (!file.getFileName().equals(newFileName)) { + // 不允许重名 + if (fm.queryBySomeFolder(fileId).parallelStream().anyMatch((e) -> e.getFileName().equals(newFileName))) { + return "nameOccupied"; + } + // 更新文件名 + final Map map = new HashMap(); + map.put("fileId", fileId); + map.put("newFileName", newFileName); + if (this.fm.updateFileNameById(map) == 0) { + // 并写入日志 + return "cannotRenameFile"; + } + } + this.lu.writeRenameFileEvent(request, file, newFileName); + return "renameFileSuccess"; + } + + // 删除所有选中文件和文件夹 + public String deleteCheckedFiles(final HttpServletRequest request) { + final String strIdList = request.getParameter("strIdList"); + final String strFidList = request.getParameter("strFidList"); + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + // 权限检查 + if (ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { + try { + // 得到要删除的文件ID列表 + final List idList = gson.fromJson(strIdList, new TypeToken>() { + }.getType()); + // 对每个要删除的文件节点进行确认并删除 + for (final String fileId : idList) { + if (fileId == null || fileId.length() <= 0) { + return ERROR_PARAMETER; + } + final Node file = this.fm.queryById(fileId); + if (file == null) { + return "deleteFileSuccess"; + } + // 删除文件块 + if (!this.fbu.deleteFromFileBlocks(file)) { + return "cannotDeleteFile"; + } + // 删除文件节点 + if (this.fm.deleteById(fileId) <= 0) { + return "cannotDeleteFile"; + } + // 日志记录 + this.lu.writeDeleteFileEvent(request, file); + } + // 删完选中的文件,再去删文件夹 + final List fidList = gson.fromJson(strFidList, new TypeToken>() { + }.getType()); + for (String fid : fidList) { + Folder folder = flm.queryById(fid); + final List l = this.fu.getParentList(fid); + if (fu.deleteAllChildFolder(fid) <= 0) { + return "cannotDeleteFile"; + } else { + this.lu.writeDeleteFolderEvent(request, folder, l); + } + } + return "deleteFileSuccess"; + } catch (Exception e) { + return ERROR_PARAMETER; + } + } + return NO_AUTHORIZED; + } + + // 打包下载功能:前置——压缩要打包下载的文件 + public String downloadCheckedFiles(final HttpServletRequest request) { + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + // 权限检查 + if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) { + final String strIdList = request.getParameter("strIdList"); + final String strFidList = request.getParameter("strFidList"); + try { + // 获得要打包下载的文件ID + final List idList = gson.fromJson(strIdList, new TypeToken>() { + }.getType()); + final List fidList = gson.fromJson(strFidList, new TypeToken>() { + }.getType()); + // 创建ZIP压缩包并将全部文件压缩 + if (idList.size() > 0 || fidList.size() > 0) { + final String zipname = this.fbu.createZip(idList, fidList, account); + this.lu.writeDownloadCheckedFileEvent(request, idList); + // 返回生成的压缩包路径 + return zipname; + } + } catch (Exception ex) { + } + } + return "ERROR"; + } + + // 打包下载功能:执行——下载压缩好的文件 + public void downloadCheckedFilesZip(final HttpServletRequest request, final HttpServletResponse response) + throws Exception { + final String zipname = request.getParameter("zipId"); + if (zipname != null && !zipname.equals("ERROR")) { + final String tfPath = ConfigureReader.instance().getTemporaryfilePath(); + final File zip = new File(tfPath, zipname); + String fname = "kiftd_" + ServerTimeUtil.accurateToDay() + "_\u6253\u5305\u4e0b\u8f7d.zip"; + if (zip.exists()) { + writeRangeFileStream(request, response, zip, fname, CONTENT_TYPE); + zip.delete(); + } + } + } + + public String getPackTime(final HttpServletRequest request) { + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) { + final String strIdList = request.getParameter("strIdList"); + final String strFidList = request.getParameter("strFidList"); + try { + final List idList = gson.fromJson(strIdList, new TypeToken>() { + }.getType()); + final List fidList = gson.fromJson(strFidList, new TypeToken>() { + }.getType()); + for (String fid : fidList) { + countFolderFilesId(account, fid, fidList); + } + long packTime = 0L; + for (final String fid : idList) { + final Node n = this.fm.queryById(fid); + final File f = new File(ConfigureReader.instance().getFileBlockPath(), n.getFilePath()); + if (f.exists()) { + packTime += f.length() / 25000000L; + } + } + if (packTime < 4L) { + return "\u9a6c\u4e0a\u5b8c\u6210"; + } + if (packTime >= 4L && packTime < 10L) { + return "\u5927\u7ea610\u79d2"; + } + if (packTime >= 10L && packTime < 35L) { + return "\u4e0d\u5230\u534a\u5206\u949f"; + } + if (packTime >= 35L && packTime < 65L) { + return "\u5927\u7ea61\u5206\u949f"; + } + if (packTime >= 65L) { + return "\u8d85\u8fc7" + packTime / 60L + + "\u5206\u949f\uff0c\u8017\u65f6\u8f83\u957f\uff0c\u5efa\u8bae\u76f4\u63a5\u4e0b\u8f7d"; + } + } catch (Exception ex) { + } + } + return "0"; + } + + // 用于迭代获得全部文件夹内的文件ID(方便预测耗时) + private void countFolderFilesId(String account, String fid, List idList) { + Folder f = flm.queryById(fid); + if (ConfigureReader.instance().accessFolder(f, account)) { + idList.addAll(Arrays.asList( + fm.queryByParentFolderId(fid).parallelStream().map((e) -> e.getFileId()).toArray(String[]::new))); + List cFolders = flm.queryByParentId(fid); + for (Folder cFolder : cFolders) { + countFolderFilesId(account, cFolder.getFolderId(), idList); + } + } + } + + @Override + public String doMoveFiles(HttpServletRequest request) { + // TODO 自动生成的方法存根 + final String strIdList = request.getParameter("strIdList"); + final String strFidList = request.getParameter("strFidList"); + final String strOptMap = request.getParameter("strOptMap"); + final String locationpath = request.getParameter("locationpath"); + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + if (ConfigureReader.instance().authorized(account, AccountAuth.MOVE_FILES)) { + try { + final List idList = gson.fromJson(strIdList, new TypeToken>() { + }.getType()); + final Map optMap = gson.fromJson(strOptMap, new TypeToken>() { + }.getType()); + for (final String id : idList) { + if (id == null || id.length() <= 0) { + return ERROR_PARAMETER; + } + final Node node = this.fm.queryById(id); + if (node == null) { + return ERROR_PARAMETER; + } + if (node.getFileParentFolder().equals(locationpath)) { + break; + } + if (fm.queryByParentFolderId(locationpath).parallelStream() + .anyMatch((e) -> e.getFileName().equals(node.getFileName()))) { + if (optMap.get(id) == null) { + return ERROR_PARAMETER; + } + switch (optMap.get(id)) { + case "cover": + if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { + return NO_AUTHORIZED; + } + Node n = fm.queryByParentFolderId(locationpath).parallelStream() + .filter((e) -> e.getFileName().equals(node.getFileName())).findFirst().get(); + if (fm.deleteById(n.getFileId()) > 0) { + Map map = new HashMap<>(); + map.put("fileId", node.getFileId()); + map.put("locationpath", locationpath); + if (this.fm.moveById(map) <= 0) { + return "cannotMoveFiles"; + } + } else { + return "cannotMoveFiles"; + } + this.lu.writeMoveFileEvent(request, node); + break; + case "both": + node.setFileName(FileNodeUtil.getNewNodeName(node.getFileName(), + fm.queryByParentFolderId(locationpath))); + if (fm.update(node) <= 0) { + return "cannotMoveFiles"; + } + Map map = new HashMap<>(); + map.put("fileId", node.getFileId()); + map.put("locationpath", locationpath); + if (this.fm.moveById(map) <= 0) { + return "cannotMoveFiles"; + } + this.lu.writeMoveFileEvent(request, node); + break; + case "skip": + break; + default: + return ERROR_PARAMETER; + } + } else { + Map map = new HashMap<>(); + map.put("fileId", node.getFileId()); + map.put("locationpath", locationpath); + if (this.fm.moveById(map) <= 0) { + return "cannotMoveFiles"; + } + this.lu.writeMoveFileEvent(request, node); + } + } + final List fidList = gson.fromJson(strFidList, new TypeToken>() { + }.getType()); + for (final String fid : fidList) { + if (fid == null || fid.length() <= 0) { + return ERROR_PARAMETER; + } + final Folder folder = this.flm.queryById(fid); + if (folder == null) { + return ERROR_PARAMETER; + } + if (folder.getFolderParent().equals(locationpath)) { + break; + } + if (fid.equals(locationpath) || fu.getParentList(locationpath).parallelStream() + .anyMatch((e) -> e.getFolderId().equals(folder.getFolderId()))) { + return ERROR_PARAMETER; + } + if (flm.queryByParentId(locationpath).parallelStream() + .anyMatch((e) -> e.getFolderName().equals(folder.getFolderName()))) { + if (optMap.get(fid) == null) { + return ERROR_PARAMETER; + } + switch (optMap.get(fid)) { + case "cover": + if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { + return NO_AUTHORIZED; + } + Folder f = flm.queryByParentId(locationpath).parallelStream() + .filter((e) -> e.getFolderName().equals(folder.getFolderName())).findFirst().get(); + Map map = new HashMap<>(); + map.put("folderId", folder.getFolderId()); + map.put("locationpath", locationpath); + if (this.flm.moveById(map) > 0) { + if (fu.deleteAllChildFolder(f.getFolderId()) > 0) { + this.lu.writeMoveFileEvent(request, folder); + break; + } + } + return "cannotMoveFiles"; + case "both": + Map map3 = new HashMap<>(); + map3.put("folderId", folder.getFolderId()); + map3.put("locationpath", locationpath); + if (this.flm.moveById(map3) > 0) { + Map map2 = new HashMap(); + map2.put("folderId", folder.getFolderId()); + map2.put("newName", FileNodeUtil.getNewFolderName(folder.getFolderName(), + flm.queryByParentId(locationpath))); + if (flm.updateFolderNameById(map2) <= 0) { + return "cannotMoveFiles"; + } + this.lu.writeMoveFileEvent(request, folder); + break; + } + this.lu.writeMoveFileEvent(request, folder); + break; + case "skip": + break; + default: + return ERROR_PARAMETER; + } + } else { + Map map = new HashMap<>(); + map.put("folderId", folder.getFolderId()); + map.put("locationpath", locationpath); + if (this.flm.moveById(map) > 0) { + this.lu.writeMoveFileEvent(request, folder); + } else { + return "cannotMoveFiles"; + } + } + } + return "moveFilesSuccess"; + } catch (Exception e) { + return ERROR_PARAMETER; + } + } + return NO_AUTHORIZED; + } + + @Override + public String confirmMoveFiles(HttpServletRequest request) { + // TODO 自动生成的方法存根 + final String strIdList = request.getParameter("strIdList"); + final String strFidList = request.getParameter("strFidList"); + final String locationpath = request.getParameter("locationpath"); + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + if (ConfigureReader.instance().authorized(account, AccountAuth.MOVE_FILES)) { + try { + final List idList = gson.fromJson(strIdList, new TypeToken>() { + }.getType()); + final List fidList = gson.fromJson(strFidList, new TypeToken>() { + }.getType()); + List repeNodes = new ArrayList<>(); + List repeFolders = new ArrayList<>(); + for (final String fileId : idList) { + if (fileId == null || fileId.length() <= 0) { + return ERROR_PARAMETER; + } + final Node node = this.fm.queryById(fileId); + if (node == null) { + return ERROR_PARAMETER; + } + if (node.getFileParentFolder().equals(locationpath)) { + break; + } + if (fm.queryByParentFolderId(locationpath).parallelStream() + .anyMatch((e) -> e.getFileName().equals(node.getFileName()))) { + repeNodes.add(node); + } + } + for (final String folderId : fidList) { + if (folderId == null || folderId.length() <= 0) { + return ERROR_PARAMETER; + } + final Folder folder = this.flm.queryById(folderId); + if (folder == null) { + return ERROR_PARAMETER; + } + if (folder.getFolderParent().equals(locationpath)) { + break; + } + if (folderId.equals(locationpath) || fu.getParentList(locationpath).parallelStream() + .anyMatch((e) -> e.getFolderId().equals(folder.getFolderId()))) { + return "CANT_MOVE_TO_INSIDE:" + folder.getFolderName(); + } + if (flm.queryByParentId(locationpath).parallelStream() + .anyMatch((e) -> e.getFolderName().equals(folder.getFolderName()))) { + repeFolders.add(folder); + } + } + if (repeNodes.size() > 0 || repeFolders.size() > 0) { + Map> repeMap = new HashMap<>(); + repeMap.put("repeFolders", repeFolders); + repeMap.put("repeNodes", repeNodes); + return "duplicationFileName:" + gson.toJson(repeMap); + } + return "confirmMoveFiles"; + } catch (Exception e) { + return ERROR_PARAMETER; + } + } + return NO_AUTHORIZED; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `kohgylw.kiftd.server.service.impl.FileServiceImpl.doUploadFile` indirectly reads without synchronization from `util.ConfigureReader.kohgylw.kiftd.server.util.ConfigureReader.accountPropertiesUpdateDaemonThread`. Potentially races with write in method `FileServiceImpl.getPackTime(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String FileServiceImpl.doUploadFile(HttpServletRequest,HttpServletResponse,MultipartFile) + +### Procedure Id: +kohgylw.kiftd.server.service.impl.FileServiceImpl.doUploadFile(javax.servlet.http.HttpServletRequest.84e15f0447d8c2b714da5b9089993650 + +### File: +src/main/java/kohgylw/kiftd/server/service/impl/FileServiceImpl.java + +### Key: +FileServiceImpl.java|doUploadFile|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +fbe4e1aaa03f35ce1236057536de0fd5 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3546/instruction.md b/inferredbugs-3546/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c0c5db91372938117d97c30804587f7654d32ab1 --- /dev/null +++ b/inferredbugs-3546/instruction.md @@ -0,0 +1,798 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** kiftd-source +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package kohgylw.kiftd.util.file_system_manager; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.Charset; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +import kohgylw.kiftd.printer.Printer; +import kohgylw.kiftd.server.model.Node; +import kohgylw.kiftd.server.util.ConfigureReader; +import kohgylw.kiftd.server.util.FileNodeUtil; +import kohgylw.kiftd.server.util.ServerTimeUtil; +import kohgylw.kiftd.util.file_system_manager.pojo.Folder; +import kohgylw.kiftd.util.file_system_manager.pojo.FolderView; + +/** + * + *

    kiftd文件系统管理器

    + *

    + * 该管理器用于提供本地文件系统相关操作(例如文件的导入导出)。为确保操作安全,其中的所有方法在同一时刻应只有一个被调用。 + * 该类被设计为单例模式,请使用静态方法getInstance()获取其唯一实例。当您第一次获取它时,该工具将加载资源并开启数据库链接 + * (可能会有一定的耗时)。 + * 每次使用前都请手动调用kohgylw.kiftd.server.util.FileNodeUtil.initNodeTableToDataBase()方法以确保节点链接最新。 + *

    + * + * @author 青阳龙野(kohgylw) + * @version 1.0 + */ +public class FileSystemManager { + + public static final String BOTH = "BOTH"; + public static final String COVER = "COVER"; + private static FileSystemManager fsm;// 唯一实例 + private static final int BUFFER_SIZE = 4096;// 缓存大小,单位为Byte(B) + + /** + * 正在进行的操作进度,请只读勿改 + */ + public static int per; + /** + * 正在进行的操作提示,请只读勿改 + */ + public static String message; + + // 用于中途取消操作的标识 + private boolean gono; + + // 缓存各式各样的、基本的查询语句,功能见名称 + private PreparedStatement selectFolderById; + private PreparedStatement selectNodeById; + private PreparedStatement selectNodeByFolderId; + private PreparedStatement selectFoldersByParentFolderId; + private PreparedStatement insertNode; + private PreparedStatement insertFolder; + private PreparedStatement deleteNodeById; + private PreparedStatement deleteFolderById; + private PreparedStatement updateNodeById; + private PreparedStatement updateFolderById; + + // 加载资源 + private FileSystemManager() { + Connection c = FileNodeUtil.getNodeDBConnection(); + try { + selectFolderById = c.prepareStatement("SELECT * FROM FOLDER WHERE folder_id = ?"); + selectNodeById = c.prepareStatement("SELECT * FROM FILE WHERE file_id = ?"); + selectNodeByFolderId = c.prepareStatement("SELECT * FROM FILE WHERE file_parent_folder = ?"); + selectFoldersByParentFolderId = c.prepareStatement("SELECT * FROM FOLDER WHERE folder_parent = ?"); + insertNode = c.prepareStatement("INSERT INTO FILE VALUES(?,?,?,?,?,?,?)"); + insertFolder = c.prepareStatement("INSERT INTO FOLDER VALUES(?,?,?,?,?,?)"); + deleteNodeById = c.prepareStatement("DELETE FROM FILE WHERE file_id = ?"); + deleteFolderById = c.prepareStatement("DELETE FROM FOLDER WHERE folder_id = ?"); + updateNodeById = c.prepareStatement( + "UPDATE FILE SET file_name = ? , file_size = ? , file_parent_folder = ? , file_creation_date = ? , file_creator = ? , file_path = ? WHERE file_id = ?"); + updateFolderById = c.prepareStatement( + "UPDATE FOLDER SET folder_name= ? , folder_creation_date = ? , folder_creator = ? , folder_parent = ? , folder_constraint = ? WHERE folder_id = ?"); + } catch (SQLException e) { + Printer.instance.print("错误:出现未知错误,文件系统解析失败,无法浏览文件。"); + } + } + + /** + * + *

    获取文件管理器唯一实例

    + *

    + * 请通过该方法获取其唯一实例并使用,首次获取时可能会耗时并加载资源。注意,请务必确保在每次使用前均已重新执行初始化节点操作。 + *

    + * + * @author 青阳龙野(kohgylw) + * @return kohgylw.kiftd.util.file_system_manager.FileSystemManager 唯一实例 + */ + public static FileSystemManager getInstance() { + if (fsm == null) { + fsm = new FileSystemManager(); + } + return fsm; + } + + /** + * + *

    根据ID获得指定文件夹视图

    + *

    + * 由文件系统得到ID代表的文件视图。 + *

    + * + * @see kohgylw.kiftd.util.file_system_manager.pojo.FolderView + * @author 青阳龙野(kohgylw) + * @param folderId + * java.lang.String 文件夹ID + * @return kohgylw.kiftd.util.file_system_manager.pojo.FolderView 指定的文件夹视图 + * @throws SQLException + * 获取失败 + */ + public FolderView getFolderView(String folderId) throws SQLException { + FolderView fv = new FolderView(); + fv.setCurrent(selectFolderById(folderId)); + fv.setFiles(selectNodesByFolderId(folderId)); + fv.setFolders(getFoldersByParentId(folderId)); + return fv; + } + + /** + * + *

    删除指定文件和文件夹

    + *

    + * 该方法将直接删除指定文件夹和文件,该操作无法恢复。鉴于操作较为耗时,该操作将在一个新线程中进行。操作时,您可以根据“per”属性来实时获取该操作的进度。 + *

    + * + * @author 青阳龙野(kohgylw) + * @param foldersId + * java.lang.String[] 要删除的文件夹ID + * @param filesId + * java.lang.String[] 要删除的文件ID + * @return boolean 删除结果 + * @throws SQLException + */ + public boolean delete(String[] foldersId, String[] filesId) throws SQLException { + gono = true; + for (int i = 0; i < filesId.length && gono; i++) { + deleteFile(filesId[i]); + } + for (int i = 0; i < foldersId.length && gono; i++) { + deleteFolder(foldersId[i]); + } + return gono; + } + + /** + * + *

    将文件系统内的文件或文件夹导出至指定位置

    + *

    + * 将文件夹ID和文件ID指向的内容导出至指定路径,并规定如果存在该文件时应进行何种处理。鉴于操作较为耗时,该操作将在一个新线程中进行。操作时,您可以根据“per”属性来实时获取该操作的进度。 + *

    + * + * @author 青阳龙野(kohgylw) + * @param foldersId + * java.lang.String[] 要导出的文件夹ID + * @param filesId + * java.lang.String[] 要导出的文件ID + * @param path + * java.io.File 要导出的目标路径,必须是个文件夹 + * @param type + * java.lang.String 导出操作类型:“COVER”覆盖或“BOTH”保留两者,其他情况默认为“COVER” + * @return boolean 是否全部导出成功 + * @throws Exception + */ + public boolean exportTo(String[] foldersId, String[] nodesId, File path, String type) throws Exception { + gono = true; + for (int i = 0; i < nodesId.length && gono; i++) { + exportNode(nodesId[i], path, type); + } + for (int i = 0; i < foldersId.length && gono; i++) { + exportFolder(foldersId[i], path, type); + } + return gono; + } + + /** + * + *

    检查文件系统中指定路径下是否存在某些名称的文件或文件夹

    + *

    + * 该方法被设计为导入功能的前置,您应该在用户导入前先进行本检查以确定是否应该让用户选择导入方式。 + * 如果返回值为0则可以直接导入,否则应选择覆盖或是保留两者或是取消。注意:该方法会阻塞线程。 + *

    + * + * @author 青阳龙野(kohgylw) + * @param files + * java.io.File[] 要检查的文件对象 + * @param folderId + * java.lang.String 要检查的目标文件夹ID + * @return int 存在同名文件(或文件夹)的数量,当被检查的路径下不存在同名文件(或文件夹)时返回0 + * @throws SQLException + */ + public int hasExistsFilesOrFolders(File[] files, String folderId) throws SQLException { + int result = 0; + List folders = getFoldersByParentId(folderId); + List nodes = selectNodesByFolderId(folderId); + for (File f : files) { + if (f.isDirectory() && folders.parallelStream().anyMatch((e) -> e.getFolderName() + .equals(new String(f.getName().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"))))) { + result++; + } else if (nodes.parallelStream().anyMatch((e) -> e.getFileName() + .equals(new String(f.getName().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"))))) { + result++; + } + } + return result; + } + + /** + * + *

    检查指定路径下是否存在与文件系统中同名的文件或文件夹

    + *

    + * 该方法被设计为导出功能的前置,您应该在用户导出前先进行本检查以确定是否应该让用户选择导出方式。 + * 如果返回值为0则可以直接导出,否则应选择覆盖或是保留两者或是取消。注意:该方法会阻塞线程。 + *

    + * + * @author 青阳龙野(kohgylw) + * @param foldersId + * java.lang.String[] 要导出的文件夹ID + * @param filesId + * java.lang.String[] 要导出的文件ID + * @param java.io.File + * path 要检查的目标路径 + * @return int 存在同名文件(或文件夹)的数量,当被检查的路径下不存在同名文件(或文件夹)时返回0 + * @throws SQLException + */ + public int hasExistsFilesOrFolders(String[] foldersId, String[] filesId, File path) throws Exception { + if (path.isDirectory()) { + int c = 0; + List folders = new ArrayList<>(); + List nodes = new ArrayList<>(); + for (String fid : foldersId) { + folders.add(selectFolderById(fid)); + } + for (String nid : filesId) { + nodes.add(selectNodeById(nid)); + } + for (File f : path.listFiles()) { + if (f.isDirectory() && folders.parallelStream().anyMatch((e) -> e.getFolderName().equals( + new String(f.getName().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"))))) { + c++; + } else if (nodes.parallelStream().anyMatch((e) -> e.getFileName().equals( + new String(f.getName().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"))))) { + c++; + } + } + return c; + } else { + throw new IllegalArgumentException(); + } + } + + /** + * + *

    将本地文件导入至文件系统中

    + *

    + * 将指定文件导入至文件系统,其中文件夹会自动创建,可以规定如何处理已存在的文件。鉴于操作较为耗时,该操作将在一个新线程中进行。操作时,您可以根据“per”属性来实时获取该操作的进度。 + *

    + * + * @author 青阳龙野(kohgylw) + * @param files + * java.io.File[] 要导入的文件对象 + * @param folderId + * java.lang.String 目标文件夹ID + * @param type + * java.lang.String 导入操作类型:“COVER”覆盖或“BOTH”保留两者,其他情况默认为“COVER” + * @return boolean 是否全部导入成功 + * @throws Exception + */ + public boolean importFrom(File[] files, String folderId, String type) throws Exception { + gono = true; + for (int i = 0; i < files.length && gono; i++) { + if (files[i].isDirectory()) { + importFolderInto(files[i], folderId, type); + } else { + importFileInto(files[i], folderId, type); + } + } + return gono; + } + + /** + * + *

    获取指定文件夹内的所有子文件夹

    + *

    + * 该功能用于提供浏览文件夹功能,您可以通过迭代调用本方法来获取文件系统内的全部文件夹,注意:该操作会阻塞线程。 + *

    + * + * @author 青阳龙野(kohgylw) + * @param folderId + * java.lang.String 需要查询的父文件夹ID + * @return java.util.List 文件夹对象列表,如果没有结果则长度为0 + * @throws SQLException + * 查询失败 + */ + public List getFoldersByParentId(String folderId) throws SQLException { + selectFoldersByParentFolderId.setString(1, folderId); + ResultSet r = selectFoldersByParentFolderId.executeQuery(); + List folders = new ArrayList<>(); + while (r.next()) { + folders.add(resultSetAccessFolder(r)); + } + return folders; + } + + // 根据ID查询文件夹对象,无符合对象则返回null + private Folder selectFolderById(String folderId) throws SQLException { + selectFolderById.setString(1, folderId); + ResultSet r = selectFolderById.executeQuery(); + if (r.next()) { + return resultSetAccessFolder(r); + } + return null; + } + + // 根据ID查询文件节点对象,无符合对象则返回null + private Node selectNodeById(String nodeId) throws SQLException { + selectNodeById.setString(1, nodeId); + ResultSet r = selectNodeById.executeQuery(); + if (r.next()) { + return resultSetAccessNode(r); + } + return null; + } + + // 查询指定文件夹内的所有文件节点,如无符合则返回空List + private List selectNodesByFolderId(String folderId) throws SQLException { + List nodes = new ArrayList<>(); + selectNodeByFolderId.setString(1, folderId); + ResultSet r = selectNodeByFolderId.executeQuery(); + while (r.next()) { + nodes.add(resultSetAccessNode(r)); + } + return nodes; + } + + // 插入一个新的文件节点并返回插入结果,0失败,1成功 + private int insertNode(Node n) throws SQLException { + insertNode.setString(1, n.getFileId()); + insertNode.setString(2, n.getFileName()); + insertNode.setString(3, n.getFileSize()); + insertNode.setString(4, n.getFileParentFolder()); + insertNode.setString(5, n.getFileCreationDate()); + insertNode.setString(6, n.getFileCreator()); + insertNode.setString(7, n.getFilePath()); + insertNode.execute(); + return insertNode.getUpdateCount(); + } + + // 插入一个新的文件夹节点,返回值同上 + private int insertFolder(Folder f) throws SQLException { + insertFolder.setString(1, f.getFolderId()); + insertFolder.setString(2, f.getFolderName()); + insertFolder.setString(3, f.getFolderCreationDate()); + insertFolder.setString(4, f.getFolderCreator()); + insertFolder.setString(5, f.getFolderParent()); + insertFolder.setInt(6, f.getFolderConstraint()); + insertFolder.execute(); + return insertFolder.getUpdateCount(); + } + + // 将SQL结果集封装为Node对象 + private Node resultSetAccessNode(ResultSet r) throws SQLException { + Node node = new Node(); + node.setFileId(r.getString("file_id")); + node.setFileName(r.getString("file_name")); + node.setFileSize(r.getString("file_size")); + node.setFileParentFolder(r.getString("file_parent_folder")); + node.setFileCreationDate(r.getString("file_creation_date")); + node.setFileCreator(r.getString("file_creator")); + node.setFilePath(r.getString("file_path")); + return node; + } + + // 将SQL结果集封装为Folder对象 + private Folder resultSetAccessFolder(ResultSet r) throws SQLException { + Folder folder = new Folder(); + folder.setFolderId(r.getString("folder_id")); + folder.setFolderName(r.getString("folder_name")); + folder.setFolderParent(r.getString("folder_parent")); + folder.setFolderCreationDate(r.getString("folder_creation_date")); + folder.setFolderCreator(r.getString("folder_creator")); + folder.setFolderConstraint(r.getInt("folder_constraint")); + return folder; + } + + // 将一个本地文件导入到文件系统中,注意,导入的必须是文件而不是文件夹 + private void importFileInto(File f, String folderId, String type) throws Exception { + if (f.isFile()) { + String name = new String(f.getName().getBytes("UTF-8"), "UTF-8"); + String newName = name; + per = 0; + message = "正在导入文件:" + name; + List nodes = selectNodesByFolderId(folderId); + Node node = null; + File target; + long size = f.length(); + String fileBlocks = ConfigureReader.instance().getFileBlockPath(); + if (nodes.parallelStream().anyMatch((e) -> e.getFileName().equals(name))) { + switch (type) { + case COVER: + // 覆盖 + node = nodes.parallelStream().filter((e) -> e.getFileName().equals(f.getName())).findFirst().get(); + node.setFileCreationDate(ServerTimeUtil.accurateToDay()); + node.setFileCreator("SYS_IN"); + int mb = (int) (size / 1024L / 1024L); + node.setFileSize(mb + ""); + if (updateNode(node) == 0) { + throw new SQLException(); + } + break; + case BOTH: + // 保留两者(计数命名) + newName = FileNodeUtil.getNewNodeName(name, nodes); + break; + default: + per = 100; + return; + } + } + // 处理文件节点,有则用,没有则创建一个 + if (node == null) { + node = new Node(); + node.setFileName(newName); + node.setFileId(UUID.randomUUID().toString()); + node.setFileParentFolder(folderId); + String id = UUID.randomUUID().toString().replace("-", ""); + String path = "file_" + id + ".block"; + node.setFilePath(path); + target = new File(fileBlocks, path); + target.createNewFile(); + node.setFileCreationDate(ServerTimeUtil.accurateToDay()); + node.setFileCreator("SYS_IN"); + int mb = (int) (size / 1024L / 1024L); + node.setFileSize(mb + ""); + if (insertNode(node) == 0) { + throw new SQLException(); + } + } else { + target = new File(fileBlocks, node.getFilePath()); + } + FileOutputStream fileOutputStream = new FileOutputStream(target); + FileInputStream fileInputStream = new FileInputStream(f); + FileChannel out = fileOutputStream.getChannel(); + FileChannel in = fileInputStream.getChannel(); + ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); + int length = 0; + long finishLength = 0; + while ((length = in.read(buffer)) != -1 && gono) { + buffer.flip(); + out.write(buffer); + buffer.clear(); + finishLength += length; + per = (int) (((double) finishLength / (double) size) * 100); + } + in.close(); + out.close(); + fileInputStream.close(); + fileOutputStream.close(); + return; + } + throw new IllegalArgumentException(); + } + + // 将一个本地文件夹导入至文件系统,必须是文件夹而不是文件。它会自动将其中的文件和文件夹也一并导入。 + private void importFolderInto(File f, String folderId, String type) throws Exception { + if (f.isDirectory()) { + String name = new String(f.getName().getBytes("UTF-8"), "UTF-8"); + String newName = name; + per = 0; + message = "正在导入文件夹:" + name; + Folder parent = selectFolderById(folderId); + List folders = getFoldersByParentId(folderId); + Folder folder = null; + if (folders.parallelStream().anyMatch((e) -> e.getFolderName().equals(name))) { + switch (type) { + case COVER: + folder = folders.parallelStream().filter((e) -> e.getFolderName().equals(name)).findFirst().get(); + break; + case BOTH: + newName = FileNodeUtil.getNewFolderName(name, folders); + break; + default: + + return; + } + } + per = 50; + if (folder == null) { + folder = new Folder(); + String nFolderId = UUID.randomUUID().toString(); + folder.setFolderId(nFolderId); + folder.setFolderName(newName); + folder.setFolderConstraint(parent.getFolderConstraint()); + folder.setFolderParent(folderId); + folder.setFolderCreator("SYS_IN"); + folder.setFolderCreationDate(ServerTimeUtil.accurateToDay()); + if (insertFolder(folder) == 0) { + throw new SQLException(); + } + } else { + folder.setFolderCreationDate(ServerTimeUtil.accurateToDay()); + if (updateFolder(folder) == 0) { + throw new SQLException(); + } + } + per = 100; + File[] childs = f.listFiles(); + for (int i = 0; i < childs.length && gono; i++) { + if (childs[i].isDirectory()) { + importFolderInto(childs[i], folder.getFolderId(), type); + } else { + importFileInto(childs[i], folder.getFolderId(), type); + } + } + // 迭代执行直至将全部文件夹及文件导入完毕为止 + } else { + throw new IllegalArgumentException(); + } + } + + // 删除一个文件节点 + private int deleteNodeById(String nodeId) throws SQLException { + deleteNodeById.setString(1, nodeId); + deleteNodeById.execute(); + return deleteNodeById.getUpdateCount(); + } + + // 删除一个文件夹 + private int deleteFolderById(String folderId) throws SQLException { + deleteFolderById.setString(1, folderId); + deleteFolderById.execute(); + return deleteFolderById.getUpdateCount(); + } + + // 修改节点 + private int updateNode(Node n) throws SQLException { + updateNodeById.setString(1, n.getFileName()); + updateNodeById.setString(2, n.getFileSize()); + updateNodeById.setString(3, n.getFileParentFolder()); + updateNodeById.setString(4, n.getFileCreationDate()); + updateNodeById.setString(5, n.getFileCreator()); + updateNodeById.setString(6, n.getFilePath()); + updateNodeById.setString(7, n.getFileId()); + updateNodeById.execute(); + return updateNodeById.getUpdateCount(); + } + + // 修改文件夹 + private int updateFolder(Folder f) throws SQLException { + updateFolderById.setString(1, f.getFolderName()); + updateFolderById.setString(2, f.getFolderCreationDate()); + updateFolderById.setString(3, f.getFolderCreator()); + updateFolderById.setString(4, f.getFolderParent()); + updateFolderById.setInt(5, f.getFolderConstraint()); + updateFolderById.setString(6, f.getFolderId()); + updateFolderById.execute(); + return updateFolderById.getUpdateCount(); + } + + // 删除一个文件夹 + private void deleteFolder(String folderId) throws SQLException { + Folder f = selectFolderById(folderId); + List nodes = selectNodesByFolderId(folderId); + int size = nodes.size(); + // 删除该文件夹内的所有文件 + for (int i = 0; i < size && gono; i++) { + deleteFile(nodes.get(i).getFileId()); + } + List folders = getFoldersByParentId(folderId); + size = folders.size(); + // 迭代删除该文件夹内的所有文件夹 + for (int i = 0; i < size && gono; i++) { + deleteFolder(folders.get(i).getFolderId()); + } + per = 50; + message = "正在删除文件夹:" + f.getFolderName(); + // 删除自己的数据 + if (deleteFolderById(folderId) > 0) { + per = 100; + return; + } + throw new SQLException(); + } + + // 删除一个文件 + private void deleteFile(String nodeId) throws SQLException { + Node n = selectNodeById(nodeId); + per = 50; + message = "正在删除文件:" + n.getFileName(); + if (n != null) { + // 删除文件节点对应的数据块 + if (new File(ConfigureReader.instance().getFileBlockPath(), n.getFilePath()).delete()) { + per = 80; + // 删除节点信息 + if (deleteNodeById(nodeId) > 0) { + per = 100; + return; + } + } + } + throw new SQLException(); + } + + // 导出一个文件节点 + private void exportNode(String nodeId, File path, String type) throws Exception { + Node node = selectNodeById(nodeId); + File target = null; + if (node != null && path != null && path.isDirectory()) { + per = 0; + message = "正在导出文件:" + node.getFileName(); + if (Arrays.stream(path.listFiles()).parallel().filter((e) -> e.isFile()) + .anyMatch((f) -> new String(f.getName().getBytes()).equals(node.getFileName()))) { + switch (type) { + case BOTH: + target = Arrays.stream(path.listFiles()).parallel().filter((e) -> e.isFile()) + .filter((e) -> new String(e.getName().getBytes()).equals(node.getFileName())).findFirst() + .get(); + break; + case COVER: + target = new File(path, new String(FileNodeUtil.getNewNodeName(node, path).getBytes())); + target.createNewFile(); + break; + default: + return; + } + } + if (target == null) { + target = new File(path, new String(node.getFileName().getBytes())); + target.createNewFile(); + } + File block = new File(ConfigureReader.instance().getFileBlockPath(), node.getFilePath()); + long size = block.length(); + FileInputStream in = new FileInputStream(block); + FileOutputStream out = new FileOutputStream(target); + FileChannel fci = in.getChannel(); + FileChannel fco = out.getChannel(); + ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); + int length = 0; + long finishLength = 0; + while ((length = fci.read(buffer)) != -1 && gono) { + buffer.flip(); + fco.write(buffer); + buffer.clear(); + finishLength += length; + per = (int) (((double) finishLength / (double) size) * 100); + } + fci.close(); + fco.close(); + in.close(); + out.close(); + return; + } + throw new IllegalArgumentException(); + } + + // 导出一个文件夹 + private void exportFolder(String folderId, File path, String type) throws Exception { + Folder folder = selectFolderById(folderId); + File target = null; + per = 0; + message = "正在导出文件夹:" + folder.getFolderName(); + if (folder != null && path != null && path.isDirectory()) { + if (Arrays.stream(path.listFiles()).parallel().filter((e) -> e.isDirectory()) + .anyMatch((f) -> new String(f.getName().getBytes()).equals(folder.getFolderName()))) { + switch (type) { + case COVER: + target = Arrays.stream(path.listFiles()).parallel().filter((e) -> e.isDirectory()) + .filter((e) -> new String(e.getName().getBytes()).equals(folder.getFolderName())) + .findFirst().get(); + break; + case BOTH: + target = new File(path, new String(FileNodeUtil.getNewFolderName(folder, path).getBytes())); + target.mkdir(); + break; + + default: + return; + } + } + if (target == null) { + target = new File(path, new String(folder.getFolderName().getBytes())); + target.mkdir(); + } + per = 100; + List nodes = selectNodesByFolderId(folderId); + List folders = getFoldersByParentId(folderId); + int size = 0; + int i = 0; + for (i = 0, size = nodes.size(); i < size && gono; i++) { + exportNode(nodes.get(i).getFileId(), target, type); + } + for (i = 0, size = folders.size(); i < size && gono; i++) { + exportFolder(folders.get(i).getFolderId(), target, type); + } + return; + } + throw new IllegalArgumentException(); + } + + /** + * + *

    立即终止当前操作

    + *

    + * 这是一个不安全的终止操作,可能会导致文件损坏,但不会污染文件节点系统。 + *

    + * + * @author 青阳龙野(kohgylw) + */ + public void cannel() { + message = "正在终止,请稍候..."; + gono = false; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `f` last assigned on line 573 could be null and is dereferenced at line 587. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void FileSystemManager.deleteFolder(String) + +### Procedure Id: +kohgylw.kiftd.util.file_system_manager.FileSystemManager.deleteFolder(java.lang.String):void.2119afff25314addddc4acb54f5185b4 + +### File: +src/main/java/kohgylw/kiftd/util/file_system_manager/FileSystemManager.java + +### Key: +FileSystemManager.java|deleteFolder|NULL_DEREFERENCE + +### Node Key: +3677875e6aead27ee1320f16c80d8b0f + +### Hash: +2960702a860d5d278bd56d5a489b9b6f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3548/instruction.md b/inferredbugs-3548/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..384b38c121f7338c946fa59e03dd3ac34fb2342b --- /dev/null +++ b/inferredbugs-3548/instruction.md @@ -0,0 +1,1025 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** kiftd-source +**Bug ID:** 17 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package kohgylw.kiftd.server.service.impl; + +import kohgylw.kiftd.server.service.*; + +import org.springframework.stereotype.*; +import kohgylw.kiftd.server.mapper.*; +import javax.annotation.*; +import kohgylw.kiftd.server.enumeration.*; +import kohgylw.kiftd.server.model.*; +import kohgylw.kiftd.server.pojo.CheckImportFolderRespons; +import kohgylw.kiftd.server.pojo.CheckUploadFilesRespons; + +import org.springframework.web.multipart.*; + +import javax.servlet.http.*; +import java.io.*; +import java.nio.charset.Charset; + +import kohgylw.kiftd.server.util.*; +import java.util.*; + +import com.google.gson.*; +import com.google.gson.reflect.TypeToken; + +/** + * + *

    文件服务功能实现类

    + *

    + * 该类负责对文件相关的服务进行实现操作,例如下载和上传等,各方法功能详见接口定义。 + *

    + * + * @author 青阳龙野(kohgylw) + * @version 1.0 + * @see kohgylw.kiftd.server.service.FileService + */ +@Service +public class FileServiceImpl extends RangeFileStreamWriter implements FileService { + private static final String ERROR_PARAMETER = "errorParameter";// 参数错误标识 + private static final String NO_AUTHORIZED = "noAuthorized";// 权限错误标识 + private static final String UPLOADSUCCESS = "uploadsuccess";// 上传成功标识 + private static final String UPLOADERROR = "uploaderror";// 上传失败标识 + + private static Set pathsKeys;//文件夹上传安全锁,避免同时对同文件夹重复导入 + + @Resource + private NodeMapper fm; + @Resource + private FolderMapper flm; + @Resource + private LogUtil lu; + @Resource + private Gson gson; + @Resource + private FileBlockUtil fbu; + @Resource + private FolderUtil fu; + + private static final String CONTENT_TYPE = "application/octet-stream"; + + { + pathsKeys = new HashSet<>(); + } + + // 检查上传文件列表的实现 + public String checkUploadFile(final HttpServletRequest request, final HttpServletResponse response) { + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + final String folderId = request.getParameter("folderId"); + final String nameList = request.getParameter("namelist"); + final String maxUploadFileSize = request.getParameter("maxSize"); + final String maxUploadFileIndex = request.getParameter("maxFileIndex"); + // 目标文件夹合法性检查 + if (folderId == null || folderId.length() == 0) { + return ERROR_PARAMETER; + } + Folder folder = flm.queryById(folderId); + if (folder == null) { + return ERROR_PARAMETER; + } + // 权限检查 + if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) + || !ConfigureReader.instance().accessFolder(folder, account)) { + return NO_AUTHORIZED; + } + // 获得上传文件名列表 + final List namelistObj = gson.fromJson(nameList, new TypeToken>() { + }.getType()); + // 准备一个检查结果对象 + CheckUploadFilesRespons cufr = new CheckUploadFilesRespons(); + // 开始文件上传体积限制检查 + try { + // 获取最大文件体积(以Byte为单位) + long mufs = Long.parseLong(maxUploadFileSize); + // 获取最大文件的名称 + String mfname = namelistObj.get(Integer.parseInt(maxUploadFileIndex)); + long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); + if (pMaxUploadSize >= 0) { + if (mufs > pMaxUploadSize) { + cufr.setCheckResult("fileTooLarge"); + cufr.setMaxUploadFileSize(formatMaxUploadFileSize(pMaxUploadSize)); + cufr.setOverSizeFile(mfname); + return gson.toJson(cufr); + } + } + } catch (Exception e) { + return ERROR_PARAMETER; + } + // 开始文件命名冲突检查 + final List pereFileNameList = new ArrayList<>(); + // 查找目标目录下是否存在与待上传文件同名的文件(或文件夹),如果有,记录在上方的列表中 + for (final String fileName : namelistObj) { + if (folderId == null || folderId.length() <= 0 || fileName == null || fileName.length() <= 0) { + return ERROR_PARAMETER; + } + final List files = this.fm.queryByParentFolderId(folderId); + if (files.stream().parallel().anyMatch((n) -> n.getFileName() + .equals(new String(fileName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"))))) { + pereFileNameList.add(fileName); + } + } + // 如果存在同名文件,则写入同名文件的列表;否则,直接允许上传 + if (pereFileNameList.size() > 0) { + cufr.setCheckResult("hasExistsNames"); + cufr.setPereFileNameList(pereFileNameList); + } else { + cufr.setCheckResult("permitUpload"); + cufr.setPereFileNameList(new ArrayList()); + } + return gson.toJson(cufr);// 以JSON格式写回该结果 + } + + // 格式化存储体积,便于返回上传文件体积的检查提示信息 + private String formatMaxUploadFileSize(long size) { + double result = (double) size; + String unit = "B"; + if (size <= 0) { + return "设置无效,请联系管理员"; + } + if (size >= 1024 && size < 1048576) { + result = (double) size / 1024; + unit = "KB"; + } else if (size >= 1048576 && size < 1073741824) { + result = (double) size / 1048576; + unit = "MB"; + } else if (size >= 1073741824) { + result = (double) size / 1073741824; + unit = "GB"; + } + return String.format("%.1f", result) + " " + unit; + } + + // 执行上传操作,接收文件并存入文件节点 + public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, + final MultipartFile file) { + String account = (String) request.getSession().getAttribute("ACCOUNT"); + final String folderId = request.getParameter("folderId"); + final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), + Charset.forName("UTF-8")); + String fileName = originalFileName; + final String repeType = request.getParameter("repeType"); + // 再次检查上传文件名与目标目录ID + if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { + return UPLOADERROR; + } + Folder folder = flm.queryById(folderId); + if (folder == null) { + return UPLOADERROR; + } + // 检查上传权限 + if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) + || !ConfigureReader.instance().accessFolder(folder, account)) { + return UPLOADERROR; + } + // 检查上传文件体积是否超限 + long mufs = ConfigureReader.instance().getUploadFileSize(account); + if (mufs >= 0 && file.getSize() > mufs) { + return UPLOADERROR; + } + // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 + final List files = this.fm.queryByParentFolderId(folderId); + if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { + // 针对存在同名文件的操作 + if (repeType != null) { + switch (repeType) { + // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) + case "skip": + return UPLOADSUCCESS; + // 覆盖则找到已存在文件节点的File并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息) + case "cover": + // 其中覆盖操作同时要求用户必须具备删除权限 + if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { + return UPLOADERROR; + } + for (Node f : files) { + if (f.getFileName().equals(originalFileName)) { + File file2 = fbu.getFileFromBlocks(f); + try { + file.transferTo(file2); + f.setFileSize(fbu.getFileSize(file)); + f.setFileCreationDate(ServerTimeUtil.accurateToDay()); + if (account != null) { + f.setFileCreator(account); + } else { + f.setFileCreator("\u533f\u540d\u7528\u6237"); + } + if (fm.update(f) > 0) { + this.lu.writeUploadFileEvent(f, account); + return UPLOADSUCCESS; + } else { + return UPLOADERROR; + } + } catch (Exception e) { + return UPLOADERROR; + } + } + } + return UPLOADERROR; + // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 + case "both": + // 设置新文件名为标号形式 + fileName = FileNodeUtil.getNewNodeName(originalFileName, files); + break; + default: + // 其他声明,容错,暂无效果 + return UPLOADERROR; + } + } else { + // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 + return UPLOADERROR; + } + } + // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 + final String path = this.fbu.saveToFileBlocks(file); + if (path.equals("ERROR")) { + return UPLOADERROR; + } + final String fsize = this.fbu.getFileSize(file); + final Node f2 = new Node(); + f2.setFileId(UUID.randomUUID().toString()); + if (account != null) { + f2.setFileCreator(account); + } else { + f2.setFileCreator("\u533f\u540d\u7528\u6237"); + } + f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); + f2.setFileName(fileName); + f2.setFileParentFolder(folderId); + f2.setFilePath(path); + f2.setFileSize(fsize); + int i = 0; + // 尽可能避免UUID重复的情况发生,重试10次 + while (true) { + try { + if (this.fm.insert(f2) > 0) { + this.lu.writeUploadFileEvent(f2, account); + return UPLOADSUCCESS; + } + break; + } catch (Exception e) { + f2.setFileId(UUID.randomUUID().toString()); + i++; + } + if (i >= 10) { + break; + } + } + return UPLOADERROR; + } + + // 删除单个文件,该功能与删除多个文件重复,计划合并二者 + public String deleteFile(final HttpServletRequest request) { + // 接收参数并接续要删除的文件 + final String fileId = request.getParameter("fileId"); + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { + return NO_AUTHORIZED; + } + if (fileId == null || fileId.length() <= 0) { + return ERROR_PARAMETER; + } + // 确认要删除的文件存在 + final Node file = this.fm.queryById(fileId); + if (file == null) { + return ERROR_PARAMETER; + } + // 从文件块删除 + if (!this.fbu.deleteFromFileBlocks(file)) { + return "cannotDeleteFile"; + } + // 从节点删除 + if (this.fm.deleteById(fileId) > 0) { + this.lu.writeDeleteFileEvent(request, file); + return "deleteFileSuccess"; + } + return "cannotDeleteFile"; + } + + // 普通下载:下载单个文件 + public void doDownloadFile(final HttpServletRequest request, final HttpServletResponse response) { + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + // 权限检查 + if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) { + // 找到要下载的文件节点 + final String fileId = request.getParameter("fileId"); + if (fileId != null) { + final Node f = this.fm.queryById(fileId); + if (f != null) { + // 执行写出 + final File fo = this.fbu.getFileFromBlocks(f); + if (fo != null) { + writeRangeFileStream(request, response, fo, f.getFileName(), CONTENT_TYPE); + // 日志记录(仅针对一次下载) + if (request.getHeader("Range") == null) { + this.lu.writeDownloadFileEvent(request, f); + } + return; + } + } + } + } + try { + //  处理无法下载的资源 + response.sendError(404); + } catch (IOException e) { + } + } + + // 重命名文件 + public String doRenameFile(final HttpServletRequest request) { + final String fileId = request.getParameter("fileId"); + final String newFileName = request.getParameter("newFileName"); + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + // 权限检查 + if (!ConfigureReader.instance().authorized(account, AccountAuth.RENAME_FILE_OR_FOLDER)) { + return NO_AUTHORIZED; + } + // 参数检查 + if (fileId == null || fileId.length() <= 0 || newFileName == null || newFileName.length() <= 0) { + return ERROR_PARAMETER; + } + if (!TextFormateUtil.instance().matcherFileName(newFileName) || newFileName.indexOf(".") == 0) { + return ERROR_PARAMETER; + } + final Node file = this.fm.queryById(fileId); + if (file == null) { + return ERROR_PARAMETER; + } + if (!file.getFileName().equals(newFileName)) { + // 不允许重名 + if (fm.queryBySomeFolder(fileId).parallelStream().anyMatch((e) -> e.getFileName().equals(newFileName))) { + return "nameOccupied"; + } + // 更新文件名 + final Map map = new HashMap(); + map.put("fileId", fileId); + map.put("newFileName", newFileName); + if (this.fm.updateFileNameById(map) == 0) { + // 并写入日志 + return "cannotRenameFile"; + } + } + this.lu.writeRenameFileEvent(request, file, newFileName); + return "renameFileSuccess"; + } + + // 删除所有选中文件和文件夹 + public String deleteCheckedFiles(final HttpServletRequest request) { + final String strIdList = request.getParameter("strIdList"); + final String strFidList = request.getParameter("strFidList"); + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + // 权限检查 + if (ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { + try { + // 得到要删除的文件ID列表 + final List idList = gson.fromJson(strIdList, new TypeToken>() { + }.getType()); + // 对每个要删除的文件节点进行确认并删除 + for (final String fileId : idList) { + if (fileId == null || fileId.length() <= 0) { + return ERROR_PARAMETER; + } + final Node file = this.fm.queryById(fileId); + if (file == null) { + return "deleteFileSuccess"; + } + // 删除文件块 + if (!this.fbu.deleteFromFileBlocks(file)) { + return "cannotDeleteFile"; + } + // 删除文件节点 + if (this.fm.deleteById(fileId) <= 0) { + return "cannotDeleteFile"; + } + // 日志记录 + this.lu.writeDeleteFileEvent(request, file); + } + // 删完选中的文件,再去删文件夹 + final List fidList = gson.fromJson(strFidList, new TypeToken>() { + }.getType()); + for (String fid : fidList) { + Folder folder = flm.queryById(fid); + final List l = this.fu.getParentList(fid); + if (fu.deleteAllChildFolder(fid) <= 0) { + return "cannotDeleteFile"; + } else { + this.lu.writeDeleteFolderEvent(request, folder, l); + } + } + return "deleteFileSuccess"; + } catch (Exception e) { + return ERROR_PARAMETER; + } + } + return NO_AUTHORIZED; + } + + // 打包下载功能:前置——压缩要打包下载的文件 + public String downloadCheckedFiles(final HttpServletRequest request) { + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + // 权限检查 + if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) { + final String strIdList = request.getParameter("strIdList"); + final String strFidList = request.getParameter("strFidList"); + try { + // 获得要打包下载的文件ID + final List idList = gson.fromJson(strIdList, new TypeToken>() { + }.getType()); + final List fidList = gson.fromJson(strFidList, new TypeToken>() { + }.getType()); + // 创建ZIP压缩包并将全部文件压缩 + if (idList.size() > 0 || fidList.size() > 0) { + final String zipname = this.fbu.createZip(idList, fidList, account); + this.lu.writeDownloadCheckedFileEvent(request, idList); + // 返回生成的压缩包路径 + return zipname; + } + } catch (Exception ex) { + } + } + return "ERROR"; + } + + // 打包下载功能:执行——下载压缩好的文件 + public void downloadCheckedFilesZip(final HttpServletRequest request, final HttpServletResponse response) + throws Exception { + final String zipname = request.getParameter("zipId"); + if (zipname != null && !zipname.equals("ERROR")) { + final String tfPath = ConfigureReader.instance().getTemporaryfilePath(); + final File zip = new File(tfPath, zipname); + String fname = "kiftd_" + ServerTimeUtil.accurateToDay() + "_\u6253\u5305\u4e0b\u8f7d.zip"; + if (zip.exists()) { + writeRangeFileStream(request, response, zip, fname, CONTENT_TYPE); + zip.delete(); + } + } + } + + public String getPackTime(final HttpServletRequest request) { + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) { + final String strIdList = request.getParameter("strIdList"); + final String strFidList = request.getParameter("strFidList"); + try { + final List idList = gson.fromJson(strIdList, new TypeToken>() { + }.getType()); + final List fidList = gson.fromJson(strFidList, new TypeToken>() { + }.getType()); + for (String fid : fidList) { + countFolderFilesId(account, fid, fidList); + } + long packTime = 0L; + for (final String fid : idList) { + final Node n = this.fm.queryById(fid); + final File f = fbu.getFileFromBlocks(n); + if (f != null && f.exists()) { + packTime += f.length() / 25000000L; + } + } + if (packTime < 4L) { + return "\u9a6c\u4e0a\u5b8c\u6210"; + } + if (packTime >= 4L && packTime < 10L) { + return "\u5927\u7ea610\u79d2"; + } + if (packTime >= 10L && packTime < 35L) { + return "\u4e0d\u5230\u534a\u5206\u949f"; + } + if (packTime >= 35L && packTime < 65L) { + return "\u5927\u7ea61\u5206\u949f"; + } + if (packTime >= 65L) { + return "\u8d85\u8fc7" + packTime / 60L + + "\u5206\u949f\uff0c\u8017\u65f6\u8f83\u957f\uff0c\u5efa\u8bae\u76f4\u63a5\u4e0b\u8f7d"; + } + } catch (Exception ex) { + } + } + return "0"; + } + + // 用于迭代获得全部文件夹内的文件ID(方便预测耗时) + private void countFolderFilesId(String account, String fid, List idList) { + Folder f = flm.queryById(fid); + if (ConfigureReader.instance().accessFolder(f, account)) { + idList.addAll(Arrays.asList( + fm.queryByParentFolderId(fid).parallelStream().map((e) -> e.getFileId()).toArray(String[]::new))); + List cFolders = flm.queryByParentId(fid); + for (Folder cFolder : cFolders) { + countFolderFilesId(account, cFolder.getFolderId(), idList); + } + } + } + + @Override + public String doMoveFiles(HttpServletRequest request) { + final String strIdList = request.getParameter("strIdList"); + final String strFidList = request.getParameter("strFidList"); + final String strOptMap = request.getParameter("strOptMap"); + final String locationpath = request.getParameter("locationpath"); + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + if (ConfigureReader.instance().authorized(account, AccountAuth.MOVE_FILES)) { + try { + final List idList = gson.fromJson(strIdList, new TypeToken>() { + }.getType()); + final Map optMap = gson.fromJson(strOptMap, new TypeToken>() { + }.getType()); + for (final String id : idList) { + if (id == null || id.length() <= 0) { + return ERROR_PARAMETER; + } + final Node node = this.fm.queryById(id); + if (node == null) { + return ERROR_PARAMETER; + } + if (node.getFileParentFolder().equals(locationpath)) { + break; + } + if (fm.queryByParentFolderId(locationpath).parallelStream() + .anyMatch((e) -> e.getFileName().equals(node.getFileName()))) { + if (optMap.get(id) == null) { + return ERROR_PARAMETER; + } + switch (optMap.get(id)) { + case "cover": + if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { + return NO_AUTHORIZED; + } + Node n = fm.queryByParentFolderId(locationpath).parallelStream() + .filter((e) -> e.getFileName().equals(node.getFileName())).findFirst().get(); + if (fm.deleteById(n.getFileId()) > 0) { + Map map = new HashMap<>(); + map.put("fileId", node.getFileId()); + map.put("locationpath", locationpath); + if (this.fm.moveById(map) <= 0) { + return "cannotMoveFiles"; + } + } else { + return "cannotMoveFiles"; + } + this.lu.writeMoveFileEvent(request, node); + break; + case "both": + node.setFileName(FileNodeUtil.getNewNodeName(node.getFileName(), + fm.queryByParentFolderId(locationpath))); + if (fm.update(node) <= 0) { + return "cannotMoveFiles"; + } + Map map = new HashMap<>(); + map.put("fileId", node.getFileId()); + map.put("locationpath", locationpath); + if (this.fm.moveById(map) <= 0) { + return "cannotMoveFiles"; + } + this.lu.writeMoveFileEvent(request, node); + break; + case "skip": + break; + default: + return ERROR_PARAMETER; + } + } else { + Map map = new HashMap<>(); + map.put("fileId", node.getFileId()); + map.put("locationpath", locationpath); + if (this.fm.moveById(map) <= 0) { + return "cannotMoveFiles"; + } + this.lu.writeMoveFileEvent(request, node); + } + } + final List fidList = gson.fromJson(strFidList, new TypeToken>() { + }.getType()); + for (final String fid : fidList) { + if (fid == null || fid.length() <= 0) { + return ERROR_PARAMETER; + } + final Folder folder = this.flm.queryById(fid); + if (folder == null) { + return ERROR_PARAMETER; + } + if (folder.getFolderParent().equals(locationpath)) { + break; + } + if (fid.equals(locationpath) || fu.getParentList(locationpath).parallelStream() + .anyMatch((e) -> e.getFolderId().equals(folder.getFolderId()))) { + return ERROR_PARAMETER; + } + if (flm.queryByParentId(locationpath).parallelStream() + .anyMatch((e) -> e.getFolderName().equals(folder.getFolderName()))) { + if (optMap.get(fid) == null) { + return ERROR_PARAMETER; + } + switch (optMap.get(fid)) { + case "cover": + if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { + return NO_AUTHORIZED; + } + Folder f = flm.queryByParentId(locationpath).parallelStream() + .filter((e) -> e.getFolderName().equals(folder.getFolderName())).findFirst().get(); + Map map = new HashMap<>(); + map.put("folderId", folder.getFolderId()); + map.put("locationpath", locationpath); + if (this.flm.moveById(map) > 0) { + if (fu.deleteAllChildFolder(f.getFolderId()) > 0) { + this.lu.writeMoveFileEvent(request, folder); + break; + } + } + return "cannotMoveFiles"; + case "both": + Map map3 = new HashMap<>(); + map3.put("folderId", folder.getFolderId()); + map3.put("locationpath", locationpath); + if (this.flm.moveById(map3) > 0) { + Map map2 = new HashMap(); + map2.put("folderId", folder.getFolderId()); + map2.put("newName", FileNodeUtil.getNewFolderName(folder.getFolderName(), + flm.queryByParentId(locationpath))); + if (flm.updateFolderNameById(map2) <= 0) { + return "cannotMoveFiles"; + } + this.lu.writeMoveFileEvent(request, folder); + break; + } + this.lu.writeMoveFileEvent(request, folder); + break; + case "skip": + break; + default: + return ERROR_PARAMETER; + } + } else { + Map map = new HashMap<>(); + map.put("folderId", folder.getFolderId()); + map.put("locationpath", locationpath); + if (this.flm.moveById(map) > 0) { + this.lu.writeMoveFileEvent(request, folder); + } else { + return "cannotMoveFiles"; + } + } + } + return "moveFilesSuccess"; + } catch (Exception e) { + return ERROR_PARAMETER; + } + } + return NO_AUTHORIZED; + } + + @Override + public String confirmMoveFiles(HttpServletRequest request) { + final String strIdList = request.getParameter("strIdList"); + final String strFidList = request.getParameter("strFidList"); + final String locationpath = request.getParameter("locationpath"); + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + if (ConfigureReader.instance().authorized(account, AccountAuth.MOVE_FILES)) { + try { + final List idList = gson.fromJson(strIdList, new TypeToken>() { + }.getType()); + final List fidList = gson.fromJson(strFidList, new TypeToken>() { + }.getType()); + List repeNodes = new ArrayList<>(); + List repeFolders = new ArrayList<>(); + for (final String fileId : idList) { + if (fileId == null || fileId.length() <= 0) { + return ERROR_PARAMETER; + } + final Node node = this.fm.queryById(fileId); + if (node == null) { + return ERROR_PARAMETER; + } + if (node.getFileParentFolder().equals(locationpath)) { + break; + } + if (fm.queryByParentFolderId(locationpath).parallelStream() + .anyMatch((e) -> e.getFileName().equals(node.getFileName()))) { + repeNodes.add(node); + } + } + for (final String folderId : fidList) { + if (folderId == null || folderId.length() <= 0) { + return ERROR_PARAMETER; + } + final Folder folder = this.flm.queryById(folderId); + if (folder == null) { + return ERROR_PARAMETER; + } + if (folder.getFolderParent().equals(locationpath)) { + break; + } + if (folderId.equals(locationpath) || fu.getParentList(locationpath).parallelStream() + .anyMatch((e) -> e.getFolderId().equals(folder.getFolderId()))) { + return "CANT_MOVE_TO_INSIDE:" + folder.getFolderName(); + } + if (flm.queryByParentId(locationpath).parallelStream() + .anyMatch((e) -> e.getFolderName().equals(folder.getFolderName()))) { + repeFolders.add(folder); + } + } + if (repeNodes.size() > 0 || repeFolders.size() > 0) { + Map> repeMap = new HashMap<>(); + repeMap.put("repeFolders", repeFolders); + repeMap.put("repeNodes", repeNodes); + return "duplicationFileName:" + gson.toJson(repeMap); + } + return "confirmMoveFiles"; + } catch (Exception e) { + return ERROR_PARAMETER; + } + } + return NO_AUTHORIZED; + } + + @Override + public String checkImportFolder(HttpServletRequest request) { + final String account = (String) request.getSession().getAttribute("ACCOUNT"); + final String folderId = request.getParameter("folderId"); + final String folderName = request.getParameter("folderName"); + final String maxUploadFileSize = request.getParameter("maxSize"); + CheckImportFolderRespons cifr = new CheckImportFolderRespons(); + // 先行权限检查 + if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { + cifr.setResult(NO_AUTHORIZED); + return gson.toJson(cifr); + } + // 开始文件上传体积限制检查 + try { + // 获取最大文件体积(以Byte为单位) + long mufs = Long.parseLong(maxUploadFileSize); + long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); + if (pMaxUploadSize >= 0) { + if (mufs > pMaxUploadSize) { + cifr.setResult("fileOverSize"); + cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); + return gson.toJson(cifr); + } + } + } catch (Exception e) { + cifr.setResult(ERROR_PARAMETER); + return gson.toJson(cifr); + } + // 开始文件夹命名冲突检查,若无重名则允许上传。 + final List folders = flm.queryByParentId(folderId); + try { + Folder testfolder = folders.stream().parallel() + .filter((n) -> n.getFolderName().equals( + new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) + .findAny().get(); + // 若有重名,则判定该用户是否具备删除权限,这是能够覆盖的第一步 + if (ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { + // 接下来判断其是否具备冲突文件夹的访问权限,这是能够覆盖的第二步 + if (ConfigureReader.instance().accessFolder(testfolder, account)) { + cifr.setResult("coverOrBoth"); + return gson.toJson(cifr); + } + } + // 如果上述条件不满足,则只能允许保留两者 + cifr.setResult("onlyBoth"); + return gson.toJson(cifr); + } catch (NoSuchElementException e) { + // 通过所有检查,允许上传 + cifr.setResult("permitUpload"); + return gson.toJson(cifr); + } + } + + @Override + public String doImportFolder(HttpServletRequest request, MultipartFile file) { + String account = (String) request.getSession().getAttribute("ACCOUNT"); + String folderId = request.getParameter("folderId"); + final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), + Charset.forName("UTF-8")); + final String folderConstraint = request.getParameter("folderConstraint"); + // 再次检查上传文件名与目标目录ID + if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { + return UPLOADERROR; + } + Folder folder = flm.queryById(folderId); + if (folder == null) { + return UPLOADERROR; + } + // 检查上传权限 + if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) + || !ConfigureReader.instance().accessFolder(folder, account)) { + return UPLOADERROR; + } + // 检查上传文件体积是否超限 + long mufs = ConfigureReader.instance().getUploadFileSize(account); + if (mufs >= 0 && file.getSize() > mufs) { + return UPLOADERROR; + } + // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) + String[] paths = getParentPath(originalFileName); + //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 + String pathskey = Arrays.toString(paths); + synchronized (pathsKeys) { + if(pathsKeys.contains(pathskey)) { + return UPLOADERROR; + }else { + pathsKeys.add(pathskey); + } + } + String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); + synchronized (pathsKeys) { + pathsKeys.remove(pathskey); + } + return result; + } + + /** + * + *

    解析相对路径字符串

    + *

    + * 根据相对路径获得文件夹的层级名称,并以数组的形式返回。若无层级则返回空数组,若层级名称为空字符串则忽略。 + *

    + *

    + * 示例1:输入"aaa/bbb/ccc.c",返回["aaa","bbb"]。 + *

    + *

    + * 示例2:输入"bbb.c",返回[]。 + *

    + *

    + * 示例3:输入"aaa//bbb/ccc.c",返回["aaa","bbb"]。 + *

    + * + * @author 青阳龙野(kohgylw) + * @param path + * java.lang.String 原路径字符串 + * @return java.lang.String[] 解析出的目录层级 + */ + private String[] getParentPath(String path) { + if (path != null) { + String[] paths = path.split("/"); + List result = new ArrayList(); + for (int i = 0; i < paths.length - 1; i++) { + if (paths[i].length() > 0) { + result.add(paths[i]); + } + } + return result.toArray(new String[0]); + } + return new String[0]; + } + + /** + * + *

    解析相对路径中的文件名

    + *

    + * 从相对路径中获得文件名,若解析失败则返回null。 + *

    + * + * @author 青阳龙野(kohgylw) + * @param java.lang.String + * 需要解析的相对路径 + * @return java.lang.String 文件名 + */ + private String getFileNameFormPath(String path) { + if (path != null) { + String[] paths = path.split("/"); + if (paths.length > 0) { + return paths[paths.length - 1]; + } + } + return null; + } + + private String protectImportFolder(String[] paths,String folderId,String account,String folderConstraint,String originalFileName,MultipartFile file) { + for (String pName : paths) { + try { + Folder target = flm.queryByParentId(folderId).parallelStream() + .filter((e) -> e.getFolderName().equals(pName)).findAny().get(); + if (ConfigureReader.instance().accessFolder(target, account)) { + folderId = target.getFolderId();// 向下迭代直至将父路径全部迭代完毕并找到最终路径 + } else { + return UPLOADERROR; + } + } catch (NoSuchElementException e) { + Folder newFolder = fu.createNewFolder(flm.queryById(folderId), account, pName, folderConstraint); + if (newFolder != null) { + folderId = newFolder.getFolderId(); + } else { + return UPLOADERROR; + } + } + } + String fileName = getFileNameFormPath(originalFileName); + // 检查是否存在同名文件。存在则直接失败(确保上传的文件夹内容的原始性) + final List files = this.fm.queryByParentFolderId(folderId); + if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(fileName))) { + return UPLOADERROR; + } + // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 + final String path = this.fbu.saveToFileBlocks(file); + if (path.equals("ERROR")) { + return UPLOADERROR; + } + final String fsize = this.fbu.getFileSize(file); + final Node f2 = new Node(); + f2.setFileId(UUID.randomUUID().toString()); + if (account != null) { + f2.setFileCreator(account); + } else { + f2.setFileCreator("\u533f\u540d\u7528\u6237"); + } + f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); + f2.setFileName(fileName); + f2.setFileParentFolder(folderId); + f2.setFilePath(path); + f2.setFileSize(fsize); + int i = 0; + // 尽可能避免UUID重复的情况发生,重试10次 + while (true) { + try { + if (this.fm.insert(f2) > 0) { + this.lu.writeUploadFileEvent(f2, account); + return UPLOADSUCCESS; + } + break; + } catch (Exception e) { + f2.setFileId(UUID.randomUUID().toString()); + i++; + } + if (i >= 10) { + break; + } + } + return UPLOADERROR; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `kohgylw.kiftd.server.service.impl.FileServiceImpl.checkImportFolder` indirectly reads without synchronization from `util.ConfigureReader.kohgylw.kiftd.server.util.ConfigureReader.accountPropertiesUpdateDaemonThread`. Potentially races with write in method `FileServiceImpl.doImportFolder(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String FileServiceImpl.checkImportFolder(HttpServletRequest) + +### Procedure Id: +kohgylw.kiftd.server.service.impl.FileServiceImpl.checkImportFolder(javax.servlet.http.HttpServletRe.2b17d060b1347c4be79e2d5f399644ad + +### File: +src/main/java/kohgylw/kiftd/server/service/impl/FileServiceImpl.java + +### Key: +FileServiceImpl.java|checkImportFolder|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +b95e37b6a0f377f75d6dec34f3c05d37 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3570/instruction.md b/inferredbugs-3570/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5b55fba8d92df1e9fe2959e067f3ee882fe2dee6 --- /dev/null +++ b/inferredbugs-3570/instruction.md @@ -0,0 +1,237 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-compress +**Bug ID:** 35 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.commons.compress.archivers; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; + +import org.apache.commons.compress.AbstractTestCase; +import org.apache.commons.compress.archivers.ar.ArArchiveEntry; +import org.apache.commons.compress.utils.IOUtils; + +public final class ArTestCase extends AbstractTestCase { + + public void testArArchiveCreation() throws Exception { + final File output = new File(dir, "bla.ar"); + + final File file1 = getFile("test1.xml"); + final File file2 = getFile("test2.xml"); + + final OutputStream out = new FileOutputStream(output); + final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out); + os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length())); + IOUtils.copy(new FileInputStream(file1), os); + os.closeArchiveEntry(); + + os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length())); + IOUtils.copy(new FileInputStream(file2), os); + os.closeArchiveEntry(); + + os.close(); + } + + public void testArUnarchive() throws Exception { + final File output = new File(dir, "bla.ar"); + { + final File file1 = getFile("test1.xml"); + final File file2 = getFile("test2.xml"); + + final OutputStream out = new FileOutputStream(output); + final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out); + os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length())); + IOUtils.copy(new FileInputStream(file1), os); + os.closeArchiveEntry(); + + os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length())); + IOUtils.copy(new FileInputStream(file2), os); + os.closeArchiveEntry(); + os.close(); + out.close(); + } + + // UnArArchive Operation + final File input = output; + final InputStream is = new FileInputStream(input); + final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is)); + final ArArchiveEntry entry = (ArArchiveEntry)in.getNextEntry(); + + File target = new File(dir, entry.getName()); + final OutputStream out = new FileOutputStream(target); + + IOUtils.copy(in, out); + + out.close(); + in.close(); + is.close(); + } + + public void testArDelete() throws Exception { + final File output = new File(dir, "bla.ar"); + + { + // create + final File file1 = getFile("test1.xml"); + final File file2 = getFile("test2.xml"); + + final OutputStream out = new FileOutputStream(output); + final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out); + os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length())); + IOUtils.copy(new FileInputStream(file1), os); + os.closeArchiveEntry(); + + os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length())); + IOUtils.copy(new FileInputStream(file2), os); + os.closeArchiveEntry(); + os.close(); + out.close(); + } + + final File output2 = new File(dir, "bla2.ar"); + + { + // remove all but one file + final InputStream is = new FileInputStream(output); + final OutputStream os = new FileOutputStream(output2); + final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os); + final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is)); + while(true) { + final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry(); + if (entry == null) { + break; + } + + if ("test1.xml".equals(entry.getName())) { + aos.putArchiveEntry(entry); + IOUtils.copy(ais, aos); + } else { + IOUtils.copy(ais, new ByteArrayOutputStream()); + } + + } + ais.close(); + aos.close(); + is.close(); + os.close(); + } + + + long sum = 0; + + { + final InputStream is = new FileInputStream(output2); + final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is)); + while(true) { + final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry(); + if (entry == null) { + break; + } + + IOUtils.copy(ais, new ByteArrayOutputStream()); + + sum += entry.getLength(); + } + ais.close(); + is.close(); + } + + assertEquals(76, sum); + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired by call to `FileInputStream(...)` at line 114 is not released after line 160. +**Note**: potential exception at line 116 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ArTestCase.testArDelete() + +### Procedure Id: +org.apache.commons.compress.archivers.ArTestCase.testArDelete():void.ab8e6380df3726e01d37ca4a329c1238 + +### File: +src/test/java/org/apache/commons/compress/archivers/ArTestCase.java + +### Key: +ArTestCase.java|testArDelete|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +0b88ba76550d1cbd289abd36ae20f9f3 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3577/instruction.md b/inferredbugs-3577/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..47b1e006c586712b39a26273d44b48d358c9ea3c --- /dev/null +++ b/inferredbugs-3577/instruction.md @@ -0,0 +1,150 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-compress +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.commons.compress; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; + +import junit.framework.TestCase; + +import org.apache.commons.compress.archivers.ArchiveInputStream; +import org.apache.commons.compress.archivers.ArchiveStreamFactory; +import org.apache.commons.compress.archivers.ar.ArArchiveInputStream; +import org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream; +import org.apache.commons.compress.archivers.jar.JarArchiveInputStream; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; + +public final class DetectArchiverTestCase extends AbstractTestCase { + public void testDetection() throws Exception { + final ArchiveStreamFactory factory = new ArchiveStreamFactory(); + + final ArchiveInputStream ar = factory.createArchiveInputStream( + new BufferedInputStream(new FileInputStream( + new File(getClass().getClassLoader().getResource("bla.ar").getFile())))); + assertNotNull(ar); + assertTrue(ar instanceof ArArchiveInputStream); + + final ArchiveInputStream tar = factory.createArchiveInputStream( + new BufferedInputStream(new FileInputStream( + new File(getClass().getClassLoader().getResource("bla.tar").getFile())))); + assertNotNull(tar); + assertTrue(tar instanceof TarArchiveInputStream); + + final ArchiveInputStream zip = factory.createArchiveInputStream( + new BufferedInputStream(new FileInputStream( + new File(getClass().getClassLoader().getResource("bla.zip").getFile())))); + assertNotNull(zip); + assertTrue(zip instanceof ZipArchiveInputStream); + + final ArchiveInputStream jar = factory.createArchiveInputStream( + new BufferedInputStream(new FileInputStream( + new File(getClass().getClassLoader().getResource("bla.jar").getFile())))); + assertNotNull(jar); + assertTrue(jar instanceof JarArchiveInputStream); + + final ArchiveInputStream cpio = factory.createArchiveInputStream( + new BufferedInputStream(new FileInputStream( + new File(getClass().getClassLoader().getResource("bla.cpio").getFile())))); + assertNotNull(cpio); + assertTrue(cpio instanceof CpioArchiveInputStream); + + // final ArchiveInputStream tgz = factory.createArchiveInputStream( + // new BufferedInputStream(new FileInputStream( + // new File(getClass().getClassLoader().getResource("bla.tgz").getFile())))); + // assertTrue(tgz instanceof TarArchiveInputStream); + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.BufferedInputStream` acquired by call to `new()` at line 59 is not released after line 57. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DetectArchiverTestCase.testDetection() + +### Procedure Id: +org.apache.commons.compress.DetectArchiverTestCase.testDetection():void.d3e5087426409bb03ad13e1ef41ce1e8 + +### File: +src/test/java/org/apache/commons/compress/DetectArchiverTestCase.java + +### Key: +DetectArchiverTestCase.java|testDetection|RESOURCE_LEAK + +### Node Key: +bc72aa43eb53391fb347c8113b6d8d95 + +### Hash: +4fc3662b0d2bc05ce58008e47de4be51 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3579/instruction.md b/inferredbugs-3579/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..50c385d3bdacf96666871ef8f0dd182c6a5be7e0 --- /dev/null +++ b/inferredbugs-3579/instruction.md @@ -0,0 +1,181 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-compress +**Bug ID:** 29 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.commons.compress.archivers; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.compress.AbstractTestCase; +import org.apache.commons.compress.archivers.cpio.CpioArchiveEntry; +import org.apache.commons.compress.utils.IOUtils; + +public final class CpioTestCase extends AbstractTestCase { + + public void testCpioArchiveCreation() throws Exception { + final File output = new File(dir, "bla.cpio"); + + final File file1 = getFile("test1.xml"); + final File file2 = getFile("test2.xml"); + + final OutputStream out = new FileOutputStream(output); + final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); + os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length())); + IOUtils.copy(new FileInputStream(file1), os); + os.closeArchiveEntry(); + + os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length())); + IOUtils.copy(new FileInputStream(file2), os); + os.closeArchiveEntry(); + + os.close(); + out.close(); + } + + public void testCpioUnarchive() throws Exception { + final File output = new File(dir, "bla.cpio"); + { + final File file1 = getFile("test1.xml"); + final File file2 = getFile("test2.xml"); + + final OutputStream out = new FileOutputStream(output); + final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); + os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length())); + IOUtils.copy(new FileInputStream(file1), os); + os.closeArchiveEntry(); + + os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length())); + IOUtils.copy(new FileInputStream(file2), os); + os.closeArchiveEntry(); + + os.close(); + out.close(); + } + + // Unarchive Operation + final File input = output; + final InputStream is = new FileInputStream(input); + final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is); + + + Map result = new HashMap(); + ArchiveEntry entry = null; + while ((entry = in.getNextEntry()) != null) { + File target = new File(dir, entry.getName()); + final OutputStream out = new FileOutputStream(target); + IOUtils.copy(in, out); + out.close(); + result.put(entry.getName(), target); + } + in.close(); + is.close(); + + int lineSepLength = System.getProperty("line.separator").length(); + + File t = (File)result.get("test1.xml"); + assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); + assertEquals("length of " + t.getAbsolutePath(), + 72 + 4 * lineSepLength, t.length()); + + t = (File)result.get("test2.xml"); + assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists()); + assertEquals("length of " + t.getAbsolutePath(), + 73 + 5 * lineSepLength, t.length()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired by call to `FileInputStream(...)` at line 64 is not released after line 64. +**Note**: potential exception at line 64 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CpioTestCase.testCpioUnarchive() + +### Procedure Id: +org.apache.commons.compress.archivers.CpioTestCase.testCpioUnarchive():void.b2b24f778833775bf1442c00648bd251 + +### File: +src/test/java/org/apache/commons/compress/archivers/CpioTestCase.java + +### Key: +CpioTestCase.java|testCpioUnarchive|RESOURCE_LEAK + +### Node Key: +7ab2347659f4532683b9d067eea566ee + +### Hash: +7b0243bb890081d8e83c3dbf08b72ed8 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3583/instruction.md b/inferredbugs-3583/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..18e93453ab719b105dcc20325459f73f493ed0bf --- /dev/null +++ b/inferredbugs-3583/instruction.md @@ -0,0 +1,125 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-compress +**Bug ID:** 28 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.commons.compress.compressors; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; + +import org.apache.commons.compress.AbstractTestCase; +import org.apache.commons.compress.utils.IOUtils; + +public final class GZipTestCase extends AbstractTestCase { + + public void testGzipCreation() throws Exception { + final File input = getFile("test1.xml"); + final File output = new File(dir, "test1.xml.gz"); + final OutputStream out = new FileOutputStream(output); + final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("gz", out); + IOUtils.copy(new FileInputStream(input), cos); + cos.close(); + } + + public void testGzipUnarchive() throws Exception { + final File input = getFile("bla.tgz"); + final File output = new File(dir, "bla.tar"); + final InputStream is = new FileInputStream(input); + final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("gz", is); + IOUtils.copy(in, new FileOutputStream(output)); + in.close(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileOutputStream` acquired by call to `FileOutputStream(...)` at line 46 is not released after line 46. +**Note**: potential exception at line 46 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GZipTestCase.testGzipUnarchive() + +### Procedure Id: +org.apache.commons.compress.compressors.GZipTestCase.testGzipUnarchive():void.f7a582a72d12129bba293169378d7681 + +### File: +src/test/java/org/apache/commons/compress/compressors/GZipTestCase.java + +### Key: +GZipTestCase.java|testGzipUnarchive|RESOURCE_LEAK + +### Node Key: +7ab2347659f4532683b9d067eea566ee + +### Hash: +cfee2b6e272ccc68452e8f1fbfb83097 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3584/instruction.md b/inferredbugs-3584/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fe8282085a75b322d7bed8c7d5fdea43782c9bff --- /dev/null +++ b/inferredbugs-3584/instruction.md @@ -0,0 +1,160 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-compress +**Bug ID:** 17 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.commons.compress.archivers; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; + +import org.apache.commons.compress.AbstractTestCase; +import org.apache.commons.compress.archivers.cpio.CpioArchiveEntry; +import org.apache.commons.compress.utils.IOUtils; + +public final class CpioTestCase extends AbstractTestCase { + + public void testCpioArchiveCreation() throws Exception { + final File output = new File(dir, "bla.cpio"); + + final File file1 = getFile("test1.xml"); + final File file2 = getFile("test2.xml"); + + final OutputStream out = new FileOutputStream(output); + final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); + os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length())); + IOUtils.copy(new FileInputStream(file1), os); + os.closeArchiveEntry(); + + os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length())); + IOUtils.copy(new FileInputStream(file2), os); + os.closeArchiveEntry(); + + os.close(); + } + + public void testCpioUnarchive() throws Exception { + final File output = new File(dir, "bla.cpio"); + { + final File file1 = getFile("test1.xml"); + final File file2 = getFile("test2.xml"); + + final OutputStream out = new FileOutputStream(output); + final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out); + os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length())); + IOUtils.copy(new FileInputStream(file1), os); + os.closeArchiveEntry(); + + os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length())); + IOUtils.copy(new FileInputStream(file2), os); + os.closeArchiveEntry(); + os.close(); + } + + // Unarchive Operation + final File input = output; + final InputStream is = new FileInputStream(input); + final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is); + final CpioArchiveEntry entry = (CpioArchiveEntry)in.getNextEntry(); + + File target = new File(dir, entry.getName()); + final OutputStream out = new FileOutputStream(target); + + IOUtils.copy(in, out); + + out.close(); + in.close(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.compress.archivers.ar.ArArchiveOutputStream` acquired by call to `createArchiveOutputStream(...)` at line 59 is not released after line 83. +**Note**: potential exception at line 60 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CpioTestCase.testCpioUnarchive() + +### Procedure Id: +org.apache.commons.compress.archivers.CpioTestCase.testCpioUnarchive():void.b2b24f778833775bf1442c00648bd251 + +### File: +src/test/java/org/apache/commons/compress/archivers/CpioTestCase.java + +### Key: +CpioTestCase.java|testCpioUnarchive|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +363c9e9ef73989a825d625fa9153305e + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3652/instruction.md b/inferredbugs-3652/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5f41b5af9640a752e5b19cf98b75f0a7fa19ff28 --- /dev/null +++ b/inferredbugs-3652/instruction.md @@ -0,0 +1,676 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fabric8-maven-plugin +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2016 Red Hat, Inc. + * + * Red Hat licenses this file to you under the Apache License, version + * 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. + */ +package io.fabric8.maven.plugin; + + +import com.fasterxml.jackson.core.JsonProcessingException; +import io.fabric8.kubernetes.api.Controller; +import io.fabric8.kubernetes.api.KubernetesHelper; +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.KubernetesResource; +import io.fabric8.kubernetes.api.model.ObjectReference; +import io.fabric8.kubernetes.api.model.Pod; +import io.fabric8.kubernetes.api.model.ReplicationController; +import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.ServicePort; +import io.fabric8.kubernetes.api.model.ServiceSpec; +import io.fabric8.kubernetes.api.model.extensions.HTTPIngressPath; +import io.fabric8.kubernetes.api.model.extensions.HTTPIngressPathBuilder; +import io.fabric8.kubernetes.api.model.extensions.HTTPIngressRuleValue; +import io.fabric8.kubernetes.api.model.extensions.Ingress; +import io.fabric8.kubernetes.api.model.extensions.IngressBackend; +import io.fabric8.kubernetes.api.model.extensions.IngressBuilder; +import io.fabric8.kubernetes.api.model.extensions.IngressList; +import io.fabric8.kubernetes.api.model.extensions.IngressRule; +import io.fabric8.kubernetes.api.model.extensions.IngressSpec; +import io.fabric8.kubernetes.client.*; +import io.fabric8.kubernetes.internal.HasMetadataComparator; +import io.fabric8.openshift.api.model.Route; +import io.fabric8.openshift.api.model.RouteList; +import io.fabric8.openshift.api.model.RouteSpec; +import io.fabric8.openshift.api.model.Template; +import io.fabric8.openshift.client.OpenShiftClient; +import io.fabric8.utils.Files; +import io.fabric8.utils.Strings; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.apache.maven.project.MavenProject; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Properties; +import java.util.Set; +import java.util.TreeSet; + +import static io.fabric8.kubernetes.api.KubernetesHelper.DEFAULT_NAMESPACE; +import static io.fabric8.kubernetes.api.KubernetesHelper.createIntOrString; + +/** + * Applies the Kubernetes UYAML to a namespace in a kubernetes environment + */ +@Mojo(name = "deploy", requiresDependencyResolution = ResolutionScope.RUNTIME, defaultPhase = LifecyclePhase.INSTALL) +public class DeployMojo extends AbstractFabric8Mojo { + + /** + * The domain added to the service ID when creating OpenShift routes + */ + @Parameter(property = "fabric8.domain") + protected String routeDomain; + + /** + * Should we fail the build if an apply fails? + */ + @Parameter(property = "fabric8.deploy.failOnError", defaultValue = "true") + protected boolean failOnError; + /** + * Should we update resources by deleting them first and then creating them again? + */ + @Parameter(property = "fabric8.recreate", defaultValue = "false") + protected boolean recreate; + /** + * The generated kubernetes YAML file + */ + @Parameter(property = "fabric8.manifest", defaultValue = "${basedir}/target/classes/kubernetes.yml") + private File kubernetesManifest; + + /** + * Should we create new kubernetes resources? + */ + @Parameter(property = "fabric8.deploy.create", defaultValue = "true") + private boolean createNewResources; + + /** + * Should we use rolling upgrades to apply changes? + */ + @Parameter(property = "fabric8.rolling", defaultValue = "false") + private boolean rollingUpgrades; + + /** + * Should we fail if there is no kubernetes json + */ + @Parameter(property = "fabric8.deploy.failOnNoKubernetesJson", defaultValue = "false") + private boolean failOnNoKubernetesJson; + + /** + * In services only mode we only process services so that those can be recursively created/updated first + * before creating/updating any pods and replication controllers + */ + @Parameter(property = "fabric8.deploy.servicesOnly", defaultValue = "false") + private boolean servicesOnly; + + /** + * Do we want to ignore services. This is particularly useful when in recreate mode + * to let you easily recreate all the ReplicationControllers and Pods but leave any service + * definitions alone to avoid changing the portalIP addresses and breaking existing pods using + * the service. + */ + @Parameter(property = "fabric8.deploy.ignoreServices", defaultValue = "false") + private boolean ignoreServices; + + /** + * Process templates locally in Java so that we can apply OpenShift templates on any Kubernetes environment + */ + @Parameter(property = "fabric8.deploy.processTemplatesLocally", defaultValue = "false") + private boolean processTemplatesLocally; + + /** + * Should we delete all the pods if we update a Replication Controller + */ + @Parameter(property = "fabric8.deploy.deletePods", defaultValue = "true") + private boolean deletePodsOnReplicationControllerUpdate; + + /** + * Do we want to ignore OAuthClients which are already running?. OAuthClients are shared across namespaces + * so we should not try to update or create/delete global oauth clients + */ + @Parameter(property = "fabric8.deploy.ignoreRunningOAuthClients", defaultValue = "true") + private boolean ignoreRunningOAuthClients; + + /** + * Should we create external Ingress/Routes for any LoadBalancer services which don't already have them. + */ + @Parameter(property = "fabric8.deploy.createExternalUrls", defaultValue = "true") + private boolean createExternalUrls; + + /** + * The folder we should store any temporary json files or results + */ + @Parameter(property = "fabric8.deploy.jsonLogDir", defaultValue = "${basedir}/target/fabric8/applyJson") + private File jsonLogDir; + + /** + * Namespace under which to operate + */ + @Parameter(property = "fabric8.namespace") + private String namespace; + + // Kubernetes cliend + private KubernetesClient kubernetes; + + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + File manifest = kubernetesManifest; + if (!Files.isFile(manifest)) { + if (failOnNoKubernetesJson) { + throw new MojoFailureException("No such generated kubernetes YAML file: " + manifest); + } else { + getLog().warn("No such generated kubernetes YAML file: " + manifest + " for this project so ignoring"); + return; + } + } + KubernetesClient kubernetes = createKubernetesClient(); + + if (kubernetes.getMasterUrl() == null || Strings.isNullOrBlank(kubernetes.getMasterUrl().toString())) { + throw new MojoFailureException("Cannot find Kubernetes master URL"); + } + getLog().info("Using kubernetes at: " + kubernetes.getMasterUrl() + " in namespace " + getNamespace() + " Kubernetes manifest: " + manifest); + + try { + Controller controller = createController(); + controller.setAllowCreate(createNewResources); + controller.setServicesOnlyMode(servicesOnly); + controller.setIgnoreServiceMode(ignoreServices); + controller.setLogJsonDir(jsonLogDir); + controller.setBasedir(getRootProjectFolder()); + controller.setIgnoreRunningOAuthClients(ignoreRunningOAuthClients); + controller.setProcessTemplatesLocally(processTemplatesLocally); + controller.setDeletePodsOnReplicationControllerUpdate(deletePodsOnReplicationControllerUpdate); + controller.setRollingUpgrade(rollingUpgrades); + controller.setRollingUpgradePreserveScale(isRollingUpgradePreserveScale()); + + boolean openShift = KubernetesHelper.isOpenShift(kubernetes); + if (openShift) { + getLog().info("OpenShift platform detected"); + } else { + disableOpenShiftFeatures(controller); + } + + + String fileName = manifest.getName(); + Object dto = KubernetesHelper.loadYaml(manifest, KubernetesResource.class); + if (dto == null) { + throw new MojoFailureException("Cannot load kubernetes YAML: " + manifest); + } + + // lets check we have created the namespace + String namespace = getNamespace(); + controller.applyNamespace(namespace); + controller.setNamespace(namespace); + + if (dto instanceof Template) { + Template template = (Template) dto; + dto = applyTemplates(template, kubernetes, controller, fileName); + } + + Set resources = new LinkedHashSet<>(); + + Set entities = new TreeSet<>(new HasMetadataComparator()); + for (KubernetesResource resource : resources) { + entities.addAll(KubernetesHelper.toItemList(resource)); + } + + entities.addAll(KubernetesHelper.toItemList(dto)); + + if (createExternalUrls) { + if (controller.getOpenShiftClientOrNull() != null) { + createRoutes(controller, entities); + } else { + createIngress(controller, kubernetes, entities); + } + } + + // Apply all items + for (HasMetadata entity : entities) { + if (entity instanceof Pod) { + Pod pod = (Pod) entity; + controller.applyPod(pod, fileName); + } else if (entity instanceof Service) { + Service service = (Service) entity; + controller.applyService(service, fileName); + } else if (entity instanceof ReplicationController) { + ReplicationController replicationController = (ReplicationController) entity; + controller.applyReplicationController(replicationController, fileName); + } else if (entity != null) { + controller.apply(entity, fileName); + } + } + } catch (Exception e) { + throw new MojoExecutionException(e.getMessage(), e); + } + } + + public static Route createRouteForService(String routeDomainPostfix, String namespace, Service service, Log log) { + Route route = null; + String id = KubernetesHelper.getName(service); + if (Strings.isNotBlank(id) && shouldCreateExternalURLForService(log, service, id)) { + route = new Route(); + String routeId = id; + KubernetesHelper.setName(route, namespace, routeId); + RouteSpec routeSpec = new RouteSpec(); + ObjectReference objectRef = new ObjectReference(); + objectRef.setName(id); + objectRef.setNamespace(namespace); + routeSpec.setTo(objectRef); + if (!Strings.isNullOrBlank(routeDomainPostfix)) { + String host = Strings.stripSuffix(Strings.stripSuffix(id, "-service"), "."); + routeSpec.setHost(host + "." + Strings.stripPrefix(routeDomainPostfix, ".")); + } else { + routeSpec.setHost(""); + } + route.setSpec(routeSpec); + String json; + try { + json = KubernetesHelper.toJson(route); + } catch (JsonProcessingException e) { + json = e.getMessage() + ". object: " + route; + } + log.debug("Created route: " + json); + } + return route; + } + + public static Ingress createIngressForService(String routeDomainPostfix, String namespace, Service service, Log log) { + Ingress ingress = null; + String serviceName = KubernetesHelper.getName(service); + ServiceSpec serviceSpec = service.getSpec(); + if (serviceSpec != null && Strings.isNotBlank(serviceName) && + shouldCreateExternalURLForService(log, service, serviceName)) { + String ingressId = serviceName; + String host = ""; + if (Strings.isNotBlank(routeDomainPostfix)) { + host = serviceName + "-" + namespace + "." + Strings.stripPrefix(routeDomainPostfix, "."); + } + List paths = new ArrayList<>(); + List ports = serviceSpec.getPorts(); + if (ports != null) { + for (ServicePort port : ports) { + Integer portNumber = port.getPort(); + if (portNumber != null) { + HTTPIngressPath path = new HTTPIngressPathBuilder().withNewBackend(). + withServiceName(serviceName).withServicePort(createIntOrString(portNumber.intValue())). + endBackend().build(); + paths.add(path); + } + } + } + if (paths.isEmpty()) { + return ingress; + } + ingress = new IngressBuilder(). + withNewMetadata().withName(ingressId).withNamespace(namespace).endMetadata(). + withNewSpec(). + addNewRule(). + withHost(host). + withNewHttp(). + withPaths(paths). + endHttp(). + endRule(). + endSpec().build(); + + String json; + try { + json = KubernetesHelper.toJson(ingress); + } catch (JsonProcessingException e) { + json = e.getMessage() + ". object: " + ingress; + } + log.debug("Created ingress: " + json); + } + return ingress; + } + + /** + * Should we try to create an external URL for the given service? + *

    + * By default lets ignore the kubernetes services and any service which does not expose ports 80 and 443 + * + * @return true if we should create an OpenShift Route for this service. + */ + protected static boolean shouldCreateExternalURLForService(Log log, Service service, String id) { + if ("kubernetes".equals(id) || "kubernetes-ro".equals(id)) { + return false; + } + Set ports = KubernetesHelper.getPorts(service); + log.debug("Service " + id + " has ports: " + ports); + if (ports.size() == 1) { + String type = null; + ServiceSpec spec = service.getSpec(); + if (spec != null) { + type = spec.getType(); + if (Objects.equals(type, "LoadBalancer")) { + return true; + } + } + log.info("Not generating route for service " + id + " type is not LoadBalancer: " + type); + return false; + } else { + log.info("Not generating route for service " + id + " as only single port services are supported. Has ports: " + ports); + return false; + } + } + + public boolean isRollingUpgrades() { + return rollingUpgrades; + } + + public boolean isRollingUpgradePreserveScale() { + return false; + } + + public MavenProject getProject() { + return project; + } + + /** + * Lets disable OpenShift-only features if we are not running on OpenShift + */ + protected void disableOpenShiftFeatures(Controller controller) { + // TODO we could check if the Templates service is running and if so we could still support templates? + this.processTemplatesLocally = true; + controller.setSupportOAuthClients(false); + controller.setProcessTemplatesLocally(true); + } + + protected Object applyTemplates(Template template, KubernetesClient kubernetes, Controller controller, String fileName) throws Exception { + KubernetesHelper.setNamespace(template, getNamespace()); + overrideTemplateParameters(template); + return controller.applyTemplate(template, fileName); + } + + /** + * Before applying the given template lets allow template parameters to be overridden via the maven + * properties - or optionally - via the command line if in interactive mode. + */ + protected void overrideTemplateParameters(Template template) { + List parameters = template.getParameters(); + MavenProject project = getProject(); + if (parameters != null && project != null) { + Properties properties = getProjectAndFabric8Properties(project); + boolean missingProperty = false; + for (io.fabric8.openshift.api.model.Parameter parameter : parameters) { + String parameterName = parameter.getName(); + String name = "fabric8.apply." + parameterName; + String propertyValue = properties.getProperty(name); + if (propertyValue != null) { + getLog().info("Overriding template parameter " + name + " with value: " + propertyValue); + parameter.setValue(propertyValue); + } else { + missingProperty = true; + getLog().info("No property defined for template parameter: " + name); + } + } + if (missingProperty) { + getLog().debug("Current properties " + new TreeSet<>(properties.keySet())); + } + } + } + + protected Properties getProjectAndFabric8Properties(MavenProject project) { + Properties properties = project.getProperties(); + properties.putAll(project.getProperties()); + // let system properties override so we can read from the command line + properties.putAll(System.getProperties()); + return properties; + } + + protected void createRoutes(Controller controller, Collection collection) { + String routeDomainPostfix = this.routeDomain; + Log log = getLog(); + String namespace = getNamespace(); + // lets get the routes first to see if we should bother + try { + OpenShiftClient openshiftClient = controller.getOpenShiftClientOrNull(); + if (openshiftClient == null) { + return; + } + RouteList routes = openshiftClient.routes().inNamespace(namespace).list(); + if (routes != null) { + routes.getItems(); + } + } catch (Exception e) { + log.warn("Cannot load OpenShift Routes; maybe not connected to an OpenShift platform? " + e, e); + return; + } + List routes = new ArrayList<>(); + for (Object object : collection) { + if (object instanceof Service) { + Service service = (Service) object; + Route route = createRouteForService(routeDomainPostfix, namespace, service, log); + if (route != null) { + routes.add(route); + } + } + } + collection.addAll(routes); + } + + protected void createIngress(Controller controller, KubernetesClient kubernetesClient, Collection collection) { + String routeDomainPostfix = this.routeDomain; + Log log = getLog(); + String namespace = getNamespace(); + List ingressList = null; + // lets get the routes first to see if we should bother + try { + IngressList ingresses = kubernetesClient.extensions().ingresses().inNamespace(namespace).list(); + if (ingresses != null) { + ingressList = ingresses.getItems(); + } + } catch (Exception e) { + log.warn("Cannot load Ingress instances. Must be an older version of Kubernetes? Error: " + e, e); + return; + } + List ingresses = new ArrayList<>(); + for (Object object : collection) { + if (object instanceof Service) { + Service service = (Service) object; + if (!serviceHasIngressRule(ingressList, service)) { + Ingress ingress = createIngressForService(routeDomainPostfix, namespace, service, log); + if (ingress != null) { + ingresses.add(ingress); + log.info("Created ingress for " + namespace + ":" + KubernetesHelper.getName(service)); + } else { + log.debug("No ingress required for " + namespace + ":" + KubernetesHelper.getName(service)); + } + } else { + log.info("Already has ingress for service " + namespace + ":" + KubernetesHelper.getName(service)); + } + } + } + collection.addAll(ingresses); + + } + + /** + * Returns true if there is an existing ingress rule for the given service + */ + private boolean serviceHasIngressRule(List ingresses, Service service) { + String serviceName = KubernetesHelper.getName(service); + for (Ingress ingress : ingresses) { + IngressSpec spec = ingress.getSpec(); + if (spec != null) { + List rules = spec.getRules(); + if (rules != null) { + for (IngressRule rule : rules) { + HTTPIngressRuleValue http = rule.getHttp(); + if (http != null) { + List paths = http.getPaths(); + if (paths != null) { + for (HTTPIngressPath path : paths) { + IngressBackend backend = path.getBackend(); + if (backend != null) { + if (Objects.equals(serviceName, backend.getServiceName())) { + return true; + } + } + } + } + } + + } + } + } + } + return false; + } + + private KubernetesClient createKubernetesClient() { + Config config = new ConfigBuilder().withNamespace(getNamespace()).build(); + return new DefaultKubernetesClient(config); + } + + protected Controller createController() { + Controller controller = new Controller(createKubernetesClient()); + controller.setThrowExceptionOnError(failOnError); + controller.setRecreateMode(recreate); + getLog().debug("Using recreate mode: " + recreate); + return controller; + } + + protected synchronized String getNamespace() { + if (Strings.isNullOrBlank(namespace)) { + namespace = KubernetesHelper.defaultNamespace(); + } + if (Strings.isNullOrBlank(namespace)) { + namespace = DEFAULT_NAMESPACE; + } + return namespace; + } + + public String getRouteDomain() { + return routeDomain; + } + + public boolean isFailOnError() { + return failOnError; + } + + public boolean isRecreate() { + return recreate; + } + + /** + * Returns the root project folder + */ + protected File getRootProjectFolder() { + File answer = null; + MavenProject project = getProject(); + while (project != null) { + File basedir = project.getBasedir(); + if (basedir != null) { + answer = basedir; + } + project = project.getParent(); + } + return answer; + } + + /** + * Returns the root project folder + */ + protected MavenProject getRootProject() { + MavenProject project = getProject(); + while (project != null) { + MavenProject parent = project.getParent(); + if (parent == null) { + break; + } + project = parent; + } + return project; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `io.fabric8.kubernetes.client.DefaultKubernetesClient` acquired by call to `createKubernetesClient()` at line 183 is not released after line 185. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DeployMojo.execute() + +### Procedure Id: +io.fabric8.maven.plugin.DeployMojo.execute():void.93710971e888b6594f8476c7be13dc0c + +### File: +plugin/src/main/java/io/fabric8/maven/plugin/DeployMojo.java + +### Key: +DeployMojo.java|execute|RESOURCE_LEAK + +### Node Key: +0e6c776ba1024631142d3bb7d683a3b3 + +### Hash: +679f4259274e6ca782f92e9bc14b7cd9 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3655/instruction.md b/inferredbugs-3655/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6411b176c4900153ac608bc8141c9d797586dc59 --- /dev/null +++ b/inferredbugs-3655/instruction.md @@ -0,0 +1,177 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fabric8-maven-plugin +**Bug ID:** 26 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright 2016 Red Hat, Inc. + * + * Red Hat licenses this file to you under the Apache License, version + * 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. + */ +package io.fabric8.maven.generator.javaexec; + +import java.io.File; +import java.io.FilenameFilter; +import java.io.IOException; +import java.util.jar.Attributes; +import java.util.jar.JarFile; +import java.util.jar.Manifest; + +import org.apache.maven.plugin.MojoExecutionException; + +/** + * Class for finding out the fat jar of a directory and provide + * some insights into the fat jar + * @author roland + * @since 10/11/16 + */ +public class FatJarDetector { + + private File directory; + private Result result; + + FatJarDetector(String dir) { + this.directory = new File(dir); + } + + Result scan() throws MojoExecutionException { + // Scanning is lazy ... + if (result == null) { + if (!directory.exists()) { + // No directory to check found so we return null here ... + return null; + } + String[] jarOrWars = directory.list((dir, name) -> name.endsWith(".war") || name.endsWith(".jar")); + if (jarOrWars == null || jarOrWars.length == 0) { + return null; + } + long maxSize = 0; + for (String jarOrWar : jarOrWars) { + File archiveFile = new File(directory, jarOrWar); + try { + JarFile archive = new JarFile(archiveFile); + Manifest mf = archive.getManifest(); + Attributes mainAttributes = mf.getMainAttributes(); + if (mainAttributes != null) { + String mainClass = mainAttributes.getValue("Main-Class"); + if (mainClass != null) { + long size = archiveFile.length(); + // Take the largest jar / war file found + if (size > maxSize) { + maxSize = size; + result = new Result(archiveFile, mainClass, mainAttributes); + } + } + } + } catch (IOException e) { + throw new MojoExecutionException("Cannot examine file " + archiveFile + " for the manifest"); + } + } + } + return result; + } + + public class Result { + + private final File archiveFile; + private final String mainClass; + private final Attributes attributes; + + public Result(File archiveFile, String mainClass, Attributes attributes) { + this.archiveFile = archiveFile; + this.mainClass = mainClass; + this.attributes = attributes; + } + + public File getArchiveFile() { + return archiveFile; + } + + public String getMainClass() { + return mainClass; + } + + public String getManifestEntry(String key) { + return attributes.getValue(key); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.util.jar.JarFile` acquired to `archive` by call to `JarFile(...)` at line 57 is not released after line 58. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +FatJarDetector$Result FatJarDetector.scan() + +### Procedure Id: +io.fabric8.maven.generator.javaexec.FatJarDetector.scan():io.fabric8.maven.generator.javaexec.FatJar.efec5dfd784370cf98e58d3d1c81195c + +### File: +generator/java-exec/src/main/java/io/fabric8/maven/generator/javaexec/FatJarDetector.java + +### Key: +FatJarDetector.java|scan|RESOURCE_LEAK + +### Node Key: +c9deda297ca620e1c62c0c1ea8763701 + +### Hash: +89f6a4b35d732f374bbc64038caa7bfa + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3699/instruction.md b/inferredbugs-3699/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..10017d5f1e8b9693736f8c2e6488f979541fcaff --- /dev/null +++ b/inferredbugs-3699/instruction.md @@ -0,0 +1,153 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** migrations +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright 2010-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.ibatis.migration.operations; + +import java.io.PrintStream; +import java.math.BigDecimal; +import java.util.List; + +import org.apache.ibatis.migration.Change; +import org.apache.ibatis.migration.ConnectionProvider; +import org.apache.ibatis.migration.MigrationException; +import org.apache.ibatis.migration.MigrationLoader; +import org.apache.ibatis.migration.hook.MigrationHook; +import org.apache.ibatis.migration.options.DatabaseOperationOption; + +public final class VersionOperation extends DatabaseOperation { + private BigDecimal version; + + public VersionOperation(BigDecimal version) { + super(); + this.version = version; + if (version == null) { + throw new IllegalArgumentException("The version must be null."); + } + } + + public VersionOperation operate(ConnectionProvider connectionProvider, MigrationLoader migrationsLoader, + DatabaseOperationOption option, PrintStream printStream) { + return operate(connectionProvider, migrationsLoader, option, printStream, null, null); + } + + public VersionOperation operate(ConnectionProvider connectionProvider, MigrationLoader migrationsLoader, + DatabaseOperationOption option, PrintStream printStream, MigrationHook upHook, MigrationHook downHook) { + if (option == null) { + option = new DatabaseOperationOption(); + } + ensureVersionExists(migrationsLoader); + Change change = getLastAppliedChange(connectionProvider, option); + if (change == null || version.compareTo(change.getId()) > 0) { + println(printStream, "Upgrading to: " + version); + UpOperation up = new UpOperation(1); + while (!version.equals(change.getId())) { + up.operate(connectionProvider, migrationsLoader, option, printStream, upHook); + change = getLastAppliedChange(connectionProvider, option); + } + } else if (version.compareTo(change.getId()) < 0) { + println(printStream, "Downgrading to: " + version); + DownOperation down = new DownOperation(1); + while (!version.equals(change.getId())) { + down.operate(connectionProvider, migrationsLoader, option, printStream, downHook); + change = getLastAppliedChange(connectionProvider, option); + } + } else { + println(printStream, "Already at version: " + version); + } + println(printStream); + return this; + } + + private void ensureVersionExists(MigrationLoader migrationsLoader) { + List migrations = migrationsLoader.getMigrations(); + if (!migrations.contains(new Change(version))) { + throw new MigrationException("A migration for the specified version number does not exist."); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `change` last assigned on line 64 could be null and is dereferenced at line 62. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +VersionOperation VersionOperation.operate(ConnectionProvider,MigrationLoader,DatabaseOperationOption,PrintStream,MigrationHook,MigrationHook) + +### Procedure Id: +org.apache.ibatis.migration.operations.VersionOperation.operate(org.apache.ibatis.migration.Connecti.523f7eff28834757afe8515df9b73164 + +### File: +src/main/java/org/apache/ibatis/migration/operations/VersionOperation.java + +### Key: +VersionOperation.java|operate|NULL_DEREFERENCE + +### Node Key: +a8e5ea4c3fb7e7356fb4a16694fe8325 + +### Hash: +be69b28fae634e697b820a4a6ab8efc6 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3710/instruction.md b/inferredbugs-3710/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..13ddf87ba73d2cbee9333b2f275647a3ae7ad156 --- /dev/null +++ b/inferredbugs-3710/instruction.md @@ -0,0 +1,184 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** springside4 +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/******************************************************************************* + * Copyright (c) 2005, 2014 springside.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + *******************************************************************************/ +package org.springside.modules.metrics.reporter; + +import java.io.PrintStream; +import java.util.Date; +import java.util.Map; +import java.util.Map.Entry; + +import org.springside.modules.metrics.Counter; +import org.springside.modules.metrics.CounterMetric; +import org.springside.modules.metrics.Gauge; +import org.springside.modules.metrics.Histogram; +import org.springside.modules.metrics.HistogramMetric; +import org.springside.modules.metrics.Timer; +import org.springside.modules.metrics.TimerMetric; + +public class ConsoleReporter implements Reporter { + + private static final int CONSOLE_WIDTH = 80; + private PrintStream output = System.out; + + @Override + public void report(Map gauges, Map counters, Map histograms, + Map timers) { + + printWithBanner(new Date().toString(), '='); + output.println(); + + if (!gauges.isEmpty()) { + printWithBanner("-- Gaugues", '-'); + for (Map.Entry entry : gauges.entrySet()) { + output.println(entry.getKey()); + printGauge(entry.getValue()); + } + output.println(); + } + + if (!counters.isEmpty()) { + printWithBanner("-- Counters", '-'); + for (Map.Entry entry : counters.entrySet()) { + output.println(entry.getKey()); + printCounter(entry.getValue().snapshot); + } + output.println(); + } + + if (!histograms.isEmpty()) { + printWithBanner("-- Histograms", '-'); + for (Map.Entry entry : histograms.entrySet()) { + output.println(entry.getKey()); + printHistogram(entry.getValue().snapshot); + } + output.println(); + } + + if (!timers.isEmpty()) { + printWithBanner("-- Timers", '-'); + for (Map.Entry entry : timers.entrySet()) { + output.println(entry.getKey()); + printTimer(entry.getValue().snapshot); + } + output.println(); + } + } + + private void printWithBanner(String s, char c) { + output.print(s); + output.print(' '); + for (int i = 0; i < (CONSOLE_WIDTH - s.length() - 1); i++) { + output.print(c); + } + output.println(); + } + + private void printGauge(Gauge gauge) { + output.printf(" value = %s%n", gauge.snapshot); + } + + private void printCounter(CounterMetric counter) { + output.printf(" last count = %d%n", counter.lastCount); + output.printf(" total count = %d%n", counter.totalCount); + output.printf(" last rate = %2.2f/s%n", counter.lastRate); + output.printf(" mean rate = %2.2f/s%n", counter.meanRate); + } + + private void printHistogram(HistogramMetric histogram) { + output.printf(" min = %d%n", histogram.min); + output.printf(" max = %d%n", histogram.max); + output.printf(" mean = %2.2f%n", histogram.mean); + for (Entry pct : histogram.pcts.entrySet()) { + output.printf(" %2.2f%% <= %d %n", pct.getKey(), pct.getValue()); + } + } + + private void printTimer(TimerMetric timer) { + output.printf(" count = %d%n", timer.counterMetric.totalCount); + output.printf(" last rate = %2.2f/s%n", timer.counterMetric.lastRate); + output.printf(" mean rate = %2.2f/s%n", timer.counterMetric.meanRate); + output.printf(" min = %d ms%n", timer.histogramMetric.min); + output.printf(" max = %d ms%n", timer.histogramMetric.max); + output.printf(" mean = %2.2f ms%n", timer.histogramMetric.mean); + for (Entry pct : timer.histogramMetric.pcts.entrySet()) { + output.printf(" %2.2f%% <= %d ms%n", pct.getKey(), pct.getValue()); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +CHECKERS_PRINTF_ARGS + +### Qualifier: +printf(...) at line 87: parameter 2 is expected to be of type java.lang.Double but java.lang.Long was given. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ConsoleReporter.printCounter(CounterMetric) + +### Procedure Id: +org.springside.modules.metrics.reporter.ConsoleReporter.printCounter(org.springside.modules.metrics..c6505633e0e61017b294d5368dab4100 + +### File: +modules/metrics/src/main/java/org/springside/modules/metrics/reporter/ConsoleReporter.java + +### Key: +ConsoleReporter.java|printCounter|CHECKERS_PRINTF_ARGS + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +b546f62f0851749fecf25d8120f896ff + +### Bug Type Hum: +Checkers Printf Args + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3711/instruction.md b/inferredbugs-3711/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..57c2507a8847272b8db21b2ab5fef9e1651151cb --- /dev/null +++ b/inferredbugs-3711/instruction.md @@ -0,0 +1,184 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** springside4 +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/******************************************************************************* + * Copyright (c) 2005, 2014 springside.github.io + * + * Licensed under the Apache License, Version 2.0 (the "License"); + *******************************************************************************/ +package org.springside.modules.metrics.reporter; + +import java.io.PrintStream; +import java.util.Date; +import java.util.Map; +import java.util.Map.Entry; + +import org.springside.modules.metrics.Counter; +import org.springside.modules.metrics.CounterMetric; +import org.springside.modules.metrics.Gauge; +import org.springside.modules.metrics.Histogram; +import org.springside.modules.metrics.HistogramMetric; +import org.springside.modules.metrics.Timer; +import org.springside.modules.metrics.TimerMetric; + +public class ConsoleReporter implements Reporter { + + private static final int CONSOLE_WIDTH = 80; + private PrintStream output = System.out; + + @Override + public void report(Map gauges, Map counters, Map histograms, + Map timers) { + + printWithBanner(new Date().toString(), '='); + output.println(); + + if (!gauges.isEmpty()) { + printWithBanner("-- Gaugues", '-'); + for (Map.Entry entry : gauges.entrySet()) { + output.println(entry.getKey()); + printGauge(entry.getValue()); + } + output.println(); + } + + if (!counters.isEmpty()) { + printWithBanner("-- Counters", '-'); + for (Map.Entry entry : counters.entrySet()) { + output.println(entry.getKey()); + printCounter(entry.getValue().snapshot); + } + output.println(); + } + + if (!histograms.isEmpty()) { + printWithBanner("-- Histograms", '-'); + for (Map.Entry entry : histograms.entrySet()) { + output.println(entry.getKey()); + printHistogram(entry.getValue().snapshot); + } + output.println(); + } + + if (!timers.isEmpty()) { + printWithBanner("-- Timers", '-'); + for (Map.Entry entry : timers.entrySet()) { + output.println(entry.getKey()); + printTimer(entry.getValue().snapshot); + } + output.println(); + } + } + + private void printWithBanner(String s, char c) { + output.print(s); + output.print(' '); + for (int i = 0; i < (CONSOLE_WIDTH - s.length() - 1); i++) { + output.print(c); + } + output.println(); + } + + private void printGauge(Gauge gauge) { + output.printf(" value = %s%n", gauge.snapshot); + } + + private void printCounter(CounterMetric counter) { + output.printf(" last count = %d%n", counter.lastCount); + output.printf(" total count = %d%n", counter.totalCount); + output.printf(" last rate = %2.2f/s%n", counter.lastRate); + output.printf(" mean rate = %2.2f/s%n", counter.meanRate); + } + + private void printHistogram(HistogramMetric histogram) { + output.printf(" min = %d%n", histogram.min); + output.printf(" max = %d%n", histogram.max); + output.printf(" mean = %2.2f%n", histogram.mean); + for (Entry pct : histogram.pcts.entrySet()) { + output.printf(" %2.2f%% <= %d %n", pct.getKey(), pct.getValue()); + } + } + + private void printTimer(TimerMetric timer) { + output.printf(" count = %d%n", timer.counterMetric.totalCount); + output.printf(" last rate = %2.2f/s%n", timer.counterMetric.lastRate); + output.printf(" mean rate = %2.2f/s%n", timer.counterMetric.meanRate); + output.printf(" min = %d ms%n", timer.histogramMetric.min); + output.printf(" max = %d ms%n", timer.histogramMetric.max); + output.printf(" mean = %2.2f ms%n", timer.histogramMetric.mean); + for (Entry pct : timer.histogramMetric.pcts.entrySet()) { + output.printf(" %2.2f%% <= %d ms%n", pct.getKey(), pct.getValue()); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +CHECKERS_PRINTF_ARGS + +### Qualifier: +printf(...) at line 86: parameter 2 is expected to be of type java.lang.Double but java.lang.Long was given. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ConsoleReporter.printCounter(CounterMetric) + +### Procedure Id: +org.springside.modules.metrics.reporter.ConsoleReporter.printCounter(org.springside.modules.metrics..c6505633e0e61017b294d5368dab4100 + +### File: +modules/metrics/src/main/java/org/springside/modules/metrics/reporter/ConsoleReporter.java + +### Key: +ConsoleReporter.java|printCounter|CHECKERS_PRINTF_ARGS + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +b546f62f0851749fecf25d8120f896ff + +### Bug Type Hum: +Checkers Printf Args + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3716/instruction.md b/inferredbugs-3716/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..37e68e966552c61abaca8a1c4d4aa64e4fce41cb --- /dev/null +++ b/inferredbugs-3716/instruction.md @@ -0,0 +1,161 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** springside4 +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.springside.modules.metrics.report; + +import java.io.PrintStream; +import java.util.Date; +import java.util.Map; +import java.util.Map.Entry; + +import org.springside.modules.metrics.CounterMetric; +import org.springside.modules.metrics.ExecutionMetric; +import org.springside.modules.metrics.HistogramMetric; + +public class ConsoleReporter implements Reporter { + + private static final int CONSOLE_WIDTH = 80; + private PrintStream output = System.out; + + @Override + public void report(Map counters, Map histograms, + Map executions) { + + printWithBanner(new Date().toString(), '='); + output.println(); + + if (!counters.isEmpty()) { + printWithBanner("-- Counters", '-'); + for (Map.Entry entry : counters.entrySet()) { + output.println(entry.getKey()); + printCounter(entry.getValue()); + } + output.println(); + } + + if (!histograms.isEmpty()) { + printWithBanner("-- Histograms", '-'); + for (Map.Entry entry : histograms.entrySet()) { + output.println(entry.getKey()); + printHistogram(entry.getValue()); + } + output.println(); + } + + if (!executions.isEmpty()) { + printWithBanner("-- Executions", '-'); + for (Map.Entry entry : executions.entrySet()) { + output.println(entry.getKey()); + printExecution(entry.getValue()); + } + output.println(); + } + } + + private void printWithBanner(String s, char c) { + output.print(s); + output.print(' '); + for (int i = 0; i < (CONSOLE_WIDTH - s.length() - 1); i++) { + output.print(c); + } + output.println(); + } + + private void printCounter(CounterMetric counter) { + output.printf(" count = %d%n", counter.count); + output.printf(" last rate = %2.2f/s%n", counter.lastRate); + output.printf(" mean rate = %2.2f/s%n", counter.meanRate); + } + + private void printHistogram(HistogramMetric histogram) { + output.printf(" min = %d%n", histogram.min); + output.printf(" max = %d%n", histogram.max); + output.printf(" mean = %2.2f%n", histogram.mean); + for (Entry pct : histogram.pcts.entrySet()) { + output.printf(" %2.2f%% <= %d %n", pct.getKey() * 100, pct.getValue()); + } + } + + private void printExecution(ExecutionMetric execution) { + output.printf(" count = %d%n", execution.counter.count); + output.printf(" last rate = %2.2f/s%n", execution.counter.lastRate); + output.printf(" mean rate = %2.2f/s%n", execution.counter.meanRate); + output.printf(" min = %d ms%n", execution.histogram.min); + output.printf(" max = %d ms%n", execution.histogram.max); + output.printf(" mean = %2.2f ms%n", execution.histogram.mean); + for (Entry pct : execution.histogram.pcts.entrySet()) { + output.printf(" %2.2f%% <= %d ms%n", pct.getKey() * 100, pct.getValue()); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +CHECKERS_PRINTF_ARGS + +### Qualifier: +printf(...) at line 84: parameter 3 is expected to be of type java.lang.Integer but java.lang.Object was given. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ConsoleReporter.printExecution(ExecutionMetric) + +### Procedure Id: +org.springside.modules.metrics.report.ConsoleReporter.printExecution(org.springside.modules.metrics..d63ba897b364ece77c83559b0ff51738 + +### File: +modules/metrics/src/main/java/org/springside/modules/metrics/report/ConsoleReporter.java + +### Key: +ConsoleReporter.java|printExecution|CHECKERS_PRINTF_ARGS + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +61bba1e83d92f3a7d83a17ae19cea2e3 + +### Bug Type Hum: +Checkers Printf Args + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3717/instruction.md b/inferredbugs-3717/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e6627a6bdad17d39d88183549814379007eede0a --- /dev/null +++ b/inferredbugs-3717/instruction.md @@ -0,0 +1,229 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** springside4 +**Bug ID:** 12 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.springside.modules.utils.concurrent; + +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; +import java.lang.management.ThreadMXBean; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 由程序触发的ThreadDump,打印到日志中. + * + * 因为ThreadDump本身会造成JVM停顿,所以加上了开关和最少间隔时间的选项(默认不限制) + * + * 因为ThreadInfo的toString()最多只会打印8层的StackTrace,所以加上了最大打印层数的选项.(默认为8) + * + * @author calvin + */ +public class ThreadDumpper { + + private static final int DEFAULT_MAX_STACK_LEVEL = 8; + + private static Logger logger = LoggerFactory.getLogger(ThreadDumpper.class); + + private boolean enable = true; // 快速关闭该功能 + private long leastIntervalMills = 0; // 每次打印ThreadDump的最小时间间隔,单位为毫秒 + private int maxStackLevel = DEFAULT_MAX_STACK_LEVEL; // 打印StackTrace的最大深度 + + private ThreadMXBean threadMBean = ManagementFactory.getThreadMXBean(); + private volatile Long lastThreadDumpTime = 0L; + + public ThreadDumpper() { + } + + public ThreadDumpper(long leastIntervalMills, int maxStackLevel) { + this.leastIntervalMills = leastIntervalMills; + this.maxStackLevel = maxStackLevel; + } + + /** + * 符合条件则打印线程栈. + */ + public void threadDumpIfNeed() { + threadDumpIfNeed(null); + } + + /** + * 符合条件则打印线程栈. + * + * @param reasonMsg 发生ThreadDump的原因 + */ + public void threadDumpIfNeed(String reasonMsg) { + if (!enable) { + return; + } + + synchronized (this) { + if (System.currentTimeMillis() - lastThreadDumpTime < leastIntervalMills) { + return; + } else { + lastThreadDumpTime = System.currentTimeMillis(); + } + } + + logger.info("Thread dump by ThreadDumpper" + reasonMsg != null ? (" for " + reasonMsg) : ""); + + // 参数均为false, 避免输出lockedMonitors和lockedSynchronizers导致的JVM缓慢 + ThreadInfo[] threadInfos = threadMBean.dumpAllThreads(false, false); + + StringBuilder b = new StringBuilder(8192); + b.append('['); + for (int i = 0; i < threadInfos.length; i++) { + b.append(dumpThreadInfo(threadInfos[i])).append(", "); + } + + // 两条日志间的时间间隔,是VM被thread dump堵塞的时间. + logger.info(b.toString()); + } + + /** + * 打印全部的stack,重新实现threadInfo的toString()函数,因为默认最多只打印8层的stack. 同时,不再打印lockedMonitors和lockedSynchronizers. + */ + private String dumpThreadInfo(ThreadInfo threadInfo) { + StringBuilder sb = new StringBuilder(512); + sb.append("\"").append(threadInfo.getThreadName()).append("\" Id=").append(threadInfo.getThreadId()).append(' ') + .append(threadInfo.getThreadState()); + if (threadInfo.getLockName() != null) { + sb.append(" on ").append(threadInfo.getLockName()); + } + if (threadInfo.getLockOwnerName() != null) { + sb.append(" owned by \"").append(threadInfo.getLockOwnerName()).append("\" Id=") + .append(threadInfo.getLockOwnerId()); + } + if (threadInfo.isSuspended()) { + sb.append(" (suspended)"); + } + if (threadInfo.isInNative()) { + sb.append(" (in native)"); + } + sb.append('\n'); + int i = 0; + StackTraceElement[] stackTrace = threadInfo.getStackTrace(); + for (; i < Math.min(maxStackLevel, stackTrace.length); i++) { + StackTraceElement ste = stackTrace[i]; + sb.append("\tat ").append(ste.toString()).append('\n'); + if (i == 0 && threadInfo.getLockInfo() != null) { + Thread.State ts = threadInfo.getThreadState(); + switch (ts) { + case BLOCKED: + sb.append("\t- blocked on ").append(threadInfo.getLockInfo()).append('\n'); + break; + case WAITING: + sb.append("\t- waiting on ").append(threadInfo.getLockInfo()).append('\n'); + break; + case TIMED_WAITING: + sb.append("\t- time waiting on ").append(threadInfo.getLockInfo()).append('\n'); + break; + default: + } + } + + } + if (i < stackTrace.length) { + sb.append("\t...").append('\n'); + } + + sb.append('\n'); + return sb.toString(); + } + + /** + * 快速关闭打印 + */ + public void setEnable(boolean enable) { + this.enable = enable; + } + + /** + * 打印ThreadDump的最小时间间隔,单位为秒,默认为0不限制. + */ + public void setLeastInterval(int leastIntervalSeconds) { + synchronized (this) { + this.leastIntervalMills = TimeUnit.SECONDS.toMillis(leastIntervalSeconds); + } + } + + /** + * 打印StackTrace的最大深度, 默认为8 + */ + public void setMaxStackLevel(int maxStackLevel) { + this.maxStackLevel = maxStackLevel; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.springside.modules.utils.concurrent.ThreadDumpper.threadDumpIfNeed` indirectly reads without synchronization from `this.org.springside.modules.utils.concurrent.ThreadDumpper.maxStackLevel`. Potentially races with write in method `ThreadDumpper.setMaxStackLevel(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ThreadDumpper.threadDumpIfNeed(String) + +### Procedure Id: +org.springside.modules.utils.concurrent.ThreadDumpper.threadDumpIfNeed(java.lang.String):void.cb6cbb835fe28783ae5e5de2f0a8467d + +### File: +modules/utils/src/main/java/org/springside/modules/utils/concurrent/ThreadDumpper.java + +### Key: +ThreadDumpper.java|threadDumpIfNeed|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +6989afcf963e4d5623e32d15346d5729 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3719/instruction.md b/inferredbugs-3719/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c52d90dca7e433bcc3f18f623652626f8e3ea308 --- /dev/null +++ b/inferredbugs-3719/instruction.md @@ -0,0 +1,289 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** springside4 +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.springside.modules.utils.net; + +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.ServerSocket; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.util.Enumeration; +import java.util.Map; +import java.util.Random; + +import javax.net.ServerSocketFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springside.modules.utils.base.SystemPropertiesUtil; +import org.springside.modules.utils.collection.MapUtil; + +import com.google.common.annotations.Beta; + +/** + * 关于网络的工具类. + * + * 1. 获取Local Address + * + * 2. 查找空闲端口 + * + * @author calvin + * + */ +@Beta +public abstract class NetUtil { + + private static Logger logger = LoggerFactory.getLogger(NetUtil.class); + + public static final int PORT_RANGE_MIN = 1024; + + public static final int PORT_RANGE_MAX = 65535; + + private static final Random random = new Random(); + + private static InetAddress localAddress; + private static String localHost; + + static { + initLocalAddress(); + } + + public static InetAddress getLocalAddress() { + return localAddress; + } + + public static String getLocalHost() { + return localHost; + } + + /** + * 测试端口是否空闲可用, from Spring SocketUtils + */ + public static boolean isPortAvailable(int port) { + try { + ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, 1, + InetAddress.getByName("localhost")); + serverSocket.close(); + return true; + } catch (Exception ex) { + return false; + } + } + + /** + * 从1024到65535, 随机找一个空闲端口 from Spring SocketUtils + */ + public static int findRandomAvailablePort() { + return findRandomAvailablePort(PORT_RANGE_MIN, PORT_RANGE_MAX); + } + + /** + * 在范围里随机找一个空闲端口,from Spring SocketUtils. + * + * @throws IllegalStateException 最多尝试(maxPort-minPort)次,如无空闲端口,抛出此异常. + */ + public static int findRandomAvailablePort(int minPort, int maxPort) { + int portRange = maxPort - minPort; + int candidatePort; + int searchCounter = 0; + + do { + if (++searchCounter > portRange) { + throw new IllegalStateException( + String.format("Could not find an available tcp port in the range [%d, %d] after %d attempts", + minPort, maxPort, searchCounter)); + } + candidatePort = minPort + random.nextInt(portRange + 1); + } while (!isPortAvailable(candidatePort)); + + return candidatePort; + } + + /** + * 从某个端口开始,递增直到65535,找一个空闲端口. + * + * @throws IllegalStateException 范围内如无空闲端口,抛出此异常 + */ + public static int findAvailablePortFrom(int minPort) { + for (int port = minPort; port < PORT_RANGE_MAX; port++) { + if (isPortAvailable(port)) { + return port; + } + } + + throw new IllegalStateException( + String.format("Could not find an available tcp port in the range [%d, %d]", minPort, PORT_RANGE_MAX)); + } + + /** + * 初始化本地地址 + */ + private static void initLocalAddress() { + NetworkInterface nic = null; + // 根据命令行执行hostname获得本机hostname, 与/etc/hosts 中该hostname的第一条ip配置,获得ip地址 + try { + localAddress = InetAddress.getLocalHost(); + nic = NetworkInterface.getByInetAddress(localAddress); + } catch (Exception ignored) { + // NOSONAR + } + + // 如果结果为空,或是一个loopback地址(127.0.0.1), 或是ipv6地址,再遍历网卡尝试获取 + if (localAddress == null || nic == null || localAddress.isLoopbackAddress() + || localAddress instanceof Inet6Address) { + InetAddress lookedUpAddr = findLocalAddressViaNetworkInterface(); + // 仍然不符合要求,只好使用127.0.0.1 + try { + localAddress = lookedUpAddr != null ? lookedUpAddr : InetAddress.getByName("127.0.0.1"); + } catch (UnknownHostException ignored) { + // NOSONAR + } + } + + localHost = IPUtil.toString(localAddress); + + logger.info("localhost is {}", localHost); + } + + /** + * 根据preferNamePrefix 与 defaultNicList的配置网卡,找出合适的网卡 + */ + private static InetAddress findLocalAddressViaNetworkInterface() { + // 如果hostname +/etc/hosts 得到的是127.0.0.1, 则首选这块网卡 + String preferNamePrefix = SystemPropertiesUtil.getString("localhost.prefer.nic.prefix", + "LOCALHOST_PREFER_NIC_PREFIX", "bond0."); + // 如果hostname +/etc/hosts 得到的是127.0.0.1, 和首选网卡都不符合要求,则按顺序遍历下面的网卡 + String defaultNicList = SystemPropertiesUtil.getString("localhost.default.nic.list", "LOCALHOST_DEFAULT_NIC_LIST", + "bond0,eth0,em0,br0"); + + InetAddress resultAddress = null; + Map candidateInterfaces = MapUtil.newHashMap(); + + // 遍历所有网卡,找出所有可用网卡,尝试找出符合prefer前缀的网卡 + try { + for (Enumeration allInterfaces = NetworkInterface.getNetworkInterfaces(); allInterfaces + .hasMoreElements();) { + NetworkInterface nic = allInterfaces.nextElement(); + // 检查网卡可用并支持广播 + try { + if (!nic.isUp() || !nic.supportsMulticast()) { + continue; + } + } catch (SocketException e) { + continue; + } + + // 检查是否符合prefer前缀 + String name = nic.getName(); + if (name.startsWith(preferNamePrefix)) { + // 检查有否非ipv6 非127.0.0.1的inetaddress + resultAddress = findAvailableInetAddress(nic); + if (resultAddress != null) { + return resultAddress; + } + } else { + // 不是Prefer前缀,先放入可选列表 + candidateInterfaces.put(name, nic); + } + } + + for (String nifName : defaultNicList.split(",")) { + NetworkInterface nic = candidateInterfaces.get(nifName); + resultAddress = findAvailableInetAddress(nic); + if (resultAddress != null) { + return resultAddress; + } + } + } catch (SocketException e) { + return null; + } + return null; + + } + + /** + * 检查有否非ipv6,非127.0.0.1的inetaddress + */ + private static InetAddress findAvailableInetAddress(NetworkInterface nic) { + for (Enumeration indetAddresses = nic.getInetAddresses(); indetAddresses.hasMoreElements();) { + InetAddress inetAddress = indetAddresses.nextElement(); + if (!(inetAddress instanceof Inet6Address) && !inetAddress.isLoopbackAddress()) { + return inetAddress; + } + } + return null; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `nic` last assigned on line 190 could be null and is dereferenced by call to `findAvailableInetAddress(...)` at line 191. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +InetAddress NetUtil.findLocalAddressViaNetworkInterface() + +### Procedure Id: +org.springside.modules.utils.net.NetUtil.findLocalAddressViaNetworkInterface():java.net.InetAddress.a7384c207779b49d42777c7c0ed01ef5 + +### File: +modules/utils/src/main/java/org/springside/modules/utils/net/NetUtil.java + +### Key: +NetUtil.java|findLocalAddressViaNetworkInterface|NULL_DEREFERENCE + +### Node Key: +3145047bf331c62774be7c2cdae1b437 + +### Hash: +5ff6f613486df9ad8a4ad2513897ad0f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3721/instruction.md b/inferredbugs-3721/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..46c979bf43c5b11773576e1b8471b5d51eb2a026 --- /dev/null +++ b/inferredbugs-3721/instruction.md @@ -0,0 +1,190 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** vaadin4spring +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2015 The original authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.vaadin.spring.navigator.internal; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.ObjectFactory; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.config.Scope; +import org.springframework.util.Assert; + + +/** + * Implementation of Spring's {@link org.springframework.beans.factory.config.Scope} that binds the views + * and dependent beans to the visibility of the view, i.e. the scope is activated when a user navigates + * into a view and destroyed when the user navigates out of the view. + * Registered by default as the scope "{@value #VAADIN_VIEW_SCOPE_NAME}". + * + * @author Petter Holmström (petter@vaadin.com) + * @see org.vaadin.spring.navigator.annotation.VaadinViewScope + */ +public class VaadinViewScope implements Scope, BeanFactoryPostProcessor { + + private static final Logger LOGGER = LoggerFactory.getLogger(VaadinViewScope.class); + + public static final String VAADIN_VIEW_SCOPE_NAME = "vaadin-view"; + + private static ViewCacheRetrievalStrategy viewCacheRetrievalStrategy = new BeanFactoryContextViewCacheRetrievalStrategy(); + + private ConfigurableListableBeanFactory beanFactory; + + /** + * Sets the {@link org.vaadin.spring.navigator.internal.ViewCacheRetrievalStrategy} to use. + */ + public static synchronized void setViewCacheRetrievalStrategy(ViewCacheRetrievalStrategy viewCacheRetrievalStrategy) { + if (viewCacheRetrievalStrategy == null) { + viewCacheRetrievalStrategy = new BeanFactoryContextViewCacheRetrievalStrategy(); + } + VaadinViewScope.viewCacheRetrievalStrategy = viewCacheRetrievalStrategy; + } + + /** + * Returns the {@link org.vaadin.spring.navigator.internal.ViewCacheRetrievalStrategy} to use. + * By default, {@link org.vaadin.spring.navigator.internal.VaadinViewScope.BeanFactoryContextViewCacheRetrievalStrategy} is used. + */ + public static synchronized ViewCacheRetrievalStrategy getViewCacheRetrievalStrategy() { + return viewCacheRetrievalStrategy; + } + + @Override + public Object get(String name, ObjectFactory objectFactory) { + return getViewCache().getCurrentViewBeanStore().get(name, objectFactory); + } + + @Override + public Object remove(String name) { + return getViewCache().getCurrentViewBeanStore().remove(name); + } + + @Override + public void registerDestructionCallback(String name, Runnable callback) { + getViewCache().getCurrentViewBeanStore().registerDestructionCallback(name, callback); + } + + @Override + public Object resolveContextualObject(String key) { + return null; + } + + @Override + public String getConversationId() { + return getViewCache().getCurrentConversationId(); + } + + private ViewCache getViewCache() { + Assert.notNull(beanFactory, "beanFactory has not been set yet"); + return viewCacheRetrievalStrategy.getViewCache(beanFactory); + } + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + this.beanFactory = beanFactory; + LOGGER.debug("Registering Vaadin View scope with bean factory [{}]", beanFactory); + beanFactory.registerScope(VAADIN_VIEW_SCOPE_NAME, this); + } + + /** + * Implementation of {@link org.vaadin.spring.navigator.internal.ViewCacheRetrievalStrategy} that + * fetches the {@link org.vaadin.spring.navigator.internal.ViewCache} instance from the provided + * bean factory. + */ + public static class BeanFactoryContextViewCacheRetrievalStrategy implements ViewCacheRetrievalStrategy { + + @Override + public ViewCache getViewCache(BeanFactory beanFactory) { + return beanFactory.getBean(ViewCache.class); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.vaadin.spring.navigator.internal.VaadinViewScope.getConversationId` indirectly reads without synchronization from `internal.VaadinViewScope.org.vaadin.spring.navigator.internal.VaadinViewScope.viewCacheRetrievalStrategy`. Potentially races with write in method `VaadinViewScope.setViewCacheRetrievalStrategy(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String VaadinViewScope.getConversationId() + +### Procedure Id: +org.vaadin.spring.navigator.internal.VaadinViewScope.getConversationId():java.lang.String.859e1c234cf6f6fa2aa8828d71963206 + +### File: +spring-vaadin/src/main/java/org/vaadin/spring/navigator/internal/VaadinViewScope.java + +### Key: +VaadinViewScope.java|getConversationId|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +03b3803e1caaf79557a9165780673e3a + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3726/instruction.md b/inferredbugs-3726/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5172cf7a3df44f3c13837d13aa943a64f1f53769 --- /dev/null +++ b/inferredbugs-3726/instruction.md @@ -0,0 +1,668 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** J2V8 +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/******************************************************************************* + * Copyright (c) 2014 EclipseSource and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * EclipseSource - initial API and implementation + ******************************************************************************/ +package com.eclipsesource.v8.utils; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import com.eclipsesource.v8.V8; +import com.eclipsesource.v8.V8Array; +import com.eclipsesource.v8.V8Object; +import com.eclipsesource.v8.V8TypedArray; +import com.eclipsesource.v8.V8Value; +import com.eclipsesource.v8.utils.typedarrays.Float32Array; +import com.eclipsesource.v8.utils.typedarrays.Float64Array; +import com.eclipsesource.v8.utils.typedarrays.Int16Array; +import com.eclipsesource.v8.utils.typedarrays.Int32Array; +import com.eclipsesource.v8.utils.typedarrays.Int8Array; +import com.eclipsesource.v8.utils.typedarrays.UInt16Array; +import com.eclipsesource.v8.utils.typedarrays.UInt32Array; +import com.eclipsesource.v8.utils.typedarrays.UInt8Array; +import com.eclipsesource.v8.utils.typedarrays.UInt8ClampedArray; + +/** + * A set of static helper methods to convert V8Objects / V8Arrays to + * java.util Maps and Lists and back again. These conversions + * perform a deep copy. + */ +public class V8ObjectUtils { + + private static final Object IGNORE = new Object(); + + /** + * Creates a Map from a V8Object using a deep copy. All elements + * in the V8Object are released after they are accessed. However, the root + * object itself is not released. + * + * @param object The root of the V8Object graph. + * + * @return A map representing a deep copy of the V8Object rooted at 'object'. + */ + public static Map toMap(final V8Object object) { + V8Map cache = new V8Map(); + try { + return toMap(object, cache); + } finally { + cache.release(); + } + } + + /** + * Creates a List from a V8Array using a deep copy. All elements + * in the V8Array are released after they are accessed. However, the root + * array itself is not released. + * + * @param array The root of the V8Array graph. + * + * @return A list representing a deep copy of the V8Array rooted at 'array'. + */ + public static List toList(final V8Array array) { + V8Map cache = new V8Map(); + try { + return toList(array, cache); + } finally { + cache.release(); + } + } + + /** + * Populates a Java array from a V8Array. The type of the array must be specified. + * Currently, only INTEGER, DOUBLE, BOOLEAN and STRING are supported. + * The V8Array must only contain elements of type 'arrayType'. The result + * can be optionally passed in as a parameter. + * + * This method will use J2V8's bulk array copy making it faster than iterating over + * all the elements in the array. + * + * @param array The V8Array to convert to a Java Array. + * @param arrayType The type of the V8Array to convert. + * @param result The array to use as the result. If null, a new array will be created. + * + * @return A Java array representing a V8Array. + */ + public static Object getTypedArray(final V8Array array, final int arrayType, final Object result) { + int length = array.length(); + if (arrayType == V8Value.INTEGER) { + int[] intArray = (int[]) result; + if ((intArray == null) || (intArray.length < length)) { + intArray = new int[length]; + } + array.getIntegers(0, length, intArray); + return intArray; + } else if (arrayType == V8Value.DOUBLE) { + double[] doubleArray = (double[]) result; + if ((doubleArray == null) || (doubleArray.length < length)) { + doubleArray = new double[length]; + } + array.getDoubles(0, length, doubleArray); + return doubleArray; + } else if (arrayType == V8Value.BOOLEAN) { + boolean[] booleanArray = (boolean[]) result; + if ((booleanArray == null) || (booleanArray.length < length)) { + booleanArray = new boolean[length]; + } + array.getBooleans(0, length, booleanArray); + return booleanArray; + } else if (arrayType == V8Value.STRING) { + String[] stringArray = (String[]) result; + if ((stringArray == null) || (stringArray.length < length)) { + stringArray = new String[length]; + } + array.getStrings(0, length, stringArray); + return stringArray; + } else if (arrayType == V8Value.BYTE) { + byte[] byteArray = (byte[]) result; + if ((byteArray == null) || (byteArray.length < length)) { + byteArray = new byte[length]; + } + array.getBytes(0, length, byteArray); + return byteArray; + } + throw new RuntimeException("Unsupported bulk load type: " + arrayType); + } + + /** + * Creates a Java array from a V8Array. The type of the Array must be specified. + * Currently, only INTEGER, DOUBLE, BOOLEAN and STRING are supported. + * The V8Array must only contain elements of type 'arrayType'. + * + * This method will use J2V8's bulk array copy making it faster than iterating over + * all the elements in the array. + * + * @param array The V8Array to convert to a Java Array. + * @param arrayType The type of the V8Array to convert. + * + * @return A Java array representing a V8Array. + */ + public static Object getTypedArray(final V8Array array, final int arrayType) { + int length = array.length(); + if (arrayType == V8Value.INTEGER) { + return array.getIntegers(0, length); + } else if (arrayType == V8Value.DOUBLE) { + return array.getDoubles(0, length); + } else if (arrayType == V8Value.BOOLEAN) { + return array.getBooleans(0, length); + } else if (arrayType == V8Value.STRING) { + return array.getStrings(0, length); + } + throw new RuntimeException("Unsupported bulk load type: " + arrayType); + } + + /** + * Creates a V8Object from a java.util.Map. This is a deep copy, so if the map + * contains other maps (or lists) they will also be converted. + * + * @param v8 The runtime on which to create the result. + * @param map The map to convert to a V8Object. + * + * @return A V8Object representing the map. + */ + public static V8Object toV8Object(final V8 v8, final Map map) { + Map cache = new Hashtable(); + try { + return toV8Object(v8, map, cache).twin(); + } finally { + for (V8Object v8Object : cache.values()) { + v8Object.release(); + } + } + } + + /** + * Creates a V8Array from a java.util.List. This is a deep copy, so if the list + * contains other lists (or maps) they will also be converted. + * + * @param v8 The runtime on which to create the result. + * @param list The list to convert to a V8Array. + * + * @return A V8Array representing the list. + */ + public static V8Array toV8Array(final V8 v8, final List list) { + Map cache = new Hashtable(); + try { + return toV8Array(v8, list, cache).twin(); + } finally { + for (V8Object v8Object : cache.values()) { + v8Object.release(); + } + } + } + + /** + * Returns an object usable with a V8 Runtime which represents + * the parameter 'value'. If 'value' is an Integer, Boolean, Double + * or String, then 'value' is simply returned as these are directly + * usable on V8. If 'value' is a map / list, then it's converted to + * a V8Object / V8Array first. + * + * If the result is a V8Value, it must be released. + * + * @param v8 The runtime on which to create V8Values. + * @param value The value to convert to an object usable with V8 + * + * @return An object which can be used directly with a V8 runtime. + */ + public static Object getV8Result(final V8 v8, final Object value) { + if (value == null) { + return null; + } + Map cache = new Hashtable(); + try { + Object result = getV8Result(v8, value, cache); + if (result instanceof V8Object) { + return ((V8Object) result).twin(); + } + return result; + } finally { + for (V8Object v8Object : cache.values()) { + v8Object.release(); + } + } + } + + /** + * Pushes a Java Object to a V8Array by first converting it to a V8Value if needed. + * If the value is a boxed primitive, then the primitive will be pushed. If the object + * is a Map / List then a deep copy will be performed, converting the object to a + * V8Object / V8Array first. + * + * @param v8 The runtime on which to create any needed V8Values. + * @param array The array to push the elements to. + * @param value The value to push to the array. + */ + public static void pushValue(final V8 v8, final V8Array array, final Object value) { + Map cache = new Hashtable(); + try { + pushValue(v8, array, value, cache); + } finally { + for (V8Object v8Object : cache.values()) { + v8Object.release(); + } + } + } + + /** + * Gets a Java Object representing the value at the given index in the V8Array. + * If the value is a primitive (int, boolean or double) then a boxed instance + * is returned. If the value is a String, then a String is returned. If + * the value is a V8Object or V8Array, then a Map or List is returned. + * + * @param array The array on which to lookup the value. The array is not + * released. + * @param index The index whose element to lookup. + * + * @return A Java Object representing the value at a given index. + */ + public static Object getValue(final V8Array array, final int index) { + V8Map cache = new V8Map(); + try { + return getValue(array, index, cache); + } finally { + cache.release(); + } + } + + /** + * Gets a Java Object representing the value with the given key in the V8Object. + * If the value is a primitive (int, boolean or double) then a boxed instance + * is returned. If the value is a String, then a String is returned. If + * the value is a V8Object or V8Array, then a Map or List is returned. + * + * @param object The object on which to lookup the value. The object is not + * released. + * @param key The key to use to lookup the value. + * + * @return A Java Object representing the value at a given key. + */ + public static Object getValue(final V8Object object, final String key) { + V8Map cache = new V8Map(); + try { + return getValue(object, key, cache); + } finally { + cache.release(); + } + } + + @SuppressWarnings("unchecked") + private static Map toMap(final V8Object object, final V8Map cache) { + if (object == null) { + return Collections.emptyMap(); + } + if (cache.containsKey(object)) { + return (Map) cache.get(object); + } + Map result = new V8PropertyMap(); + cache.put(object, result); + String[] keys = object.getKeys(); + for (String key : keys) { + Object value = getValue(object, key, cache); + if (value != IGNORE) { + result.put(key, value); + } + } + return result; + } + + @SuppressWarnings("unchecked") + private static List toList(final V8Array array, final V8Map cache) { + if (array == null) { + return Collections.emptyList(); + } + if (cache.containsKey(array)) { + return (List) cache.get(array); + } + List result = new ArrayList(); + cache.put(array, result); + for (int i = 0; i < array.length(); i++) { + Object value = getValue(array, i, cache); + if (value != IGNORE) { + result.add(getValue(array, i, cache)); + } + } + return result; + } + + private static V8Object toV8Object(final V8 v8, final Map map, final Map cache) { + if (cache.containsKey(map)) { + return cache.get(map); + } + V8Object result = new V8Object(v8); + cache.put(map, result); + try { + for (Entry entry : map.entrySet()) { + setValue(v8, result, entry.getKey(), entry.getValue(), cache); + } + } catch (IllegalStateException e) { + result.release(); + throw e; + } + return result; + } + + private static V8Array toV8Array(final V8 v8, final List list, final Map cache) { + if (cache.containsKey(new ListWrapper(list))) { + return (V8Array) cache.get(new ListWrapper(list)); + } + V8Array result = new V8Array(v8); + cache.put(new ListWrapper(list), result); + try { + for (int i = 0; i < list.size(); i++) { + Object value = list.get(i); + pushValue(v8, result, value, cache); + } + } catch (IllegalStateException e) { + result.release(); + throw e; + } + + return result; + } + + @SuppressWarnings("unchecked") + private static Object getV8Result(final V8 v8, final Object value, final Map cache) { + if (cache.containsKey(value)) { + return cache.get(value); + } + if (value instanceof Map) { + return toV8Object(v8, (Map) value, cache); + } else if (value instanceof List) { + return toV8Array(v8, (List) value, cache); + } + return value; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static void pushValue(final V8 v8, final V8Array result, final Object value, final Map cache) { + if (value == null) { + result.pushUndefined(); + } else if (value instanceof Integer) { + result.push((Integer) value); + } else if (value instanceof Long) { + result.push(new Double((Long) value)); + } else if (value instanceof Double) { + result.push((Double) value); + } else if (value instanceof Float) { + result.push((Float) value); + } else if (value instanceof String) { + result.push((String) value); + } else if (value instanceof Boolean) { + result.push((Boolean) value); + } else if (value instanceof V8Object) { + result.push((V8Object) value); + } else if (value instanceof Map) { + V8Object object = toV8Object(v8, (Map) value, cache); + result.push(object); + } else if (value instanceof List) { + V8Array array = toV8Array(v8, (List) value, cache); + result.push(array); + } else { + throw new IllegalStateException("Unsupported Object of type: " + value.getClass()); + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static void setValue(final V8 v8, final V8Object result, final String key, final Object value, final Map cache) { + if (value == null) { + result.addUndefined(key); + } else if (value instanceof Integer) { + result.add(key, (Integer) value); + } else if (value instanceof Long) { + result.add(key, (int) (long) (Long) value); + } else if (value instanceof Double) { + result.add(key, (Double) value); + } else if (value instanceof Float) { + result.add(key, (Float) value); + } else if (value instanceof String) { + result.add(key, (String) value); + } else if (value instanceof Boolean) { + result.add(key, (Boolean) value); + } else if (value instanceof V8Object) { + result.add(key, (V8Object) value); + } else if (value instanceof Map) { + V8Object object = toV8Object(v8, (Map) value, cache); + result.add(key, object); + } else if (value instanceof List) { + V8Array array = toV8Array(v8, (List) value, cache); + result.add(key, array); + } else { + throw new IllegalStateException("Unsupported Object of type: " + value.getClass()); + } + } + + private static Object getValue(final V8Array array, final int index, final V8Map cache) { + int valueType = array.getType(index); + switch (valueType) { + case V8Value.INTEGER: + return array.getInteger(index); + case V8Value.DOUBLE: + return array.getDouble(index); + case V8Value.BOOLEAN: + return array.getBoolean(index); + case V8Value.STRING: + return array.getString(index); + case V8Value.V8_FUNCTION: + return IGNORE; + case V8Value.V8_TYPED_ARRAY: + V8Array typedArray = array.getArray(index); + try { + return toByteBuffer(typedArray); + } finally { + if (typedArray instanceof V8Array) { + typedArray.release(); + } + } + case V8Value.V8_ARRAY: + V8Array arrayValue = array.getArray(index); + try { + return toList(arrayValue, cache); + } finally { + if (arrayValue instanceof V8Array) { + arrayValue.release(); + } + } + case V8Value.V8_OBJECT: + V8Object objectValue = array.getObject(index); + try { + return toMap(objectValue, cache); + } finally { + if (objectValue instanceof V8Object) { + objectValue.release(); + } + } + case V8Value.NULL: + return null; + case V8Value.UNDEFINED: + return V8.getUndefined(); + default: + throw new IllegalStateException("Cannot find type for index: " + index); + } + } + + private static Object toByteBuffer(final V8Array typedArray) { + int arrayType = typedArray.getType(); + ByteBuffer buffer = ((V8TypedArray) typedArray).getByteBuffer(); + switch (arrayType) { + case V8Value.INT_8_ARRAY: + return new Int8Array(buffer); + case V8Value.UNSIGNED_INT_8_ARRAY: + return new UInt8Array(buffer); + case V8Value.UNSIGNED_INT_8_CLAMPED_ARRAY: + return new UInt8ClampedArray(buffer); + case V8Value.INT_16_ARRAY: + return new Int16Array(buffer); + case V8Value.UNSIGNED_INT_16_ARRAY: + return new UInt16Array(buffer); + case V8Value.INT_32_ARRAY: + return new Int32Array(buffer); + case V8Value.UNSIGNED_INT_32_ARRAY: + return new UInt32Array(buffer); + case V8Value.FLOAT_32_ARRAY: + return new Float32Array(buffer); + case V8Value.FLOAT_64_ARRAY: + return new Float64Array(buffer); + default: + throw new IllegalStateException("Known Typed Array type: " + V8Value.getStringRepresentaion(arrayType)); + } + } + + private static Object getValue(final V8Object object, final String key, final V8Map cache) { + int valueType = object.getType(key); + switch (valueType) { + case V8Value.INTEGER: + return object.getInteger(key); + case V8Value.DOUBLE: + return object.getDouble(key); + case V8Value.BOOLEAN: + return object.getBoolean(key); + case V8Value.STRING: + return object.getString(key); + case V8Value.V8_FUNCTION: + return IGNORE; + case V8Value.V8_TYPED_ARRAY: + V8Array typedArray = object.getArray(key); + try { + return toByteBuffer(typedArray); + } finally { + if (typedArray instanceof V8Array) { + typedArray.release(); + } + } + case V8Value.V8_ARRAY: + V8Array array = object.getArray(key); + try { + return toList(array, cache); + } finally { + if (array instanceof V8Array) { + array.release(); + } + } + case V8Value.V8_OBJECT: + V8Object child = object.getObject(key); + try { + return toMap(child, cache); + } finally { + if (child instanceof V8Object) { + child.release(); + } + } + case V8Value.NULL: + return null; + case V8Value.UNDEFINED: + return V8.getUndefined(); + default: + throw new IllegalStateException("Cannot find type for key: " + key); + } + } + + private V8ObjectUtils() { + + } + + static class ListWrapper { + private List list; + + public ListWrapper(final List list) { + this.list = list; + } + + @Override + public boolean equals(final Object obj) { + if (obj instanceof ListWrapper) { + return ((ListWrapper) obj).list == list; + } + return false; + } + + @Override + public int hashCode() { + return System.identityHashCode(list); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `array` last assigned on line 544 could be null and is dereferenced by call to `toList(...)` at line 546. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object V8ObjectUtils.getValue(V8Object,String,V8Map) + +### Procedure Id: +com.eclipsesource.v8.utils.V8ObjectUtils.getValue(com.eclipsesource.v8.V8Object,java.lang.String,com.c49b774ac7722ebf6fe869b45639e1d2 + +### File: +src/main/java/com/eclipsesource/v8/utils/V8ObjectUtils.java + +### Key: +V8ObjectUtils.java|getValue|NULL_DEREFERENCE + +### Node Key: +dc3f80da49eedd3dac507ee1d2b00097 + +### Hash: +8815c4c34be3173a446c78fb4b5227d6 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3728/instruction.md b/inferredbugs-3728/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b5903df213839ddae7d37b00f67cdb47f02a905a --- /dev/null +++ b/inferredbugs-3728/instruction.md @@ -0,0 +1,627 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** J2V8 +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/******************************************************************************* + * Copyright (c) 2014 EclipseSource and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * EclipseSource - initial API and implementation + ******************************************************************************/ +package com.eclipsesource.v8.utils; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import com.eclipsesource.v8.V8; +import com.eclipsesource.v8.V8Array; +import com.eclipsesource.v8.V8Object; +import com.eclipsesource.v8.V8TypedArray; +import com.eclipsesource.v8.V8Value; + +/** + * A set of static helper methods to convert V8Objects / V8Arrays to + * java.util Maps and Lists and back again. These conversions + * perform a deep copy. + */ +public class V8ObjectUtils { + + private static final Object IGNORE = new Object(); + + /** + * Creates a Map from a V8Object using a deep copy. All elements + * in the V8Object are released after they are accessed. However, the root + * object itself is not released. + * + * @param object The root of the V8Object graph. + * + * @return A map representing a deep copy of the V8Object rooted at 'object'. + */ + public static Map toMap(final V8Object object) { + V8Map cache = new V8Map(); + try { + return toMap(object, cache); + } finally { + cache.release(); + } + } + + /** + * Creates a List from a V8Array using a deep copy. All elements + * in the V8Array are released after they are accessed. However, the root + * array itself is not released. + * + * @param array The root of the V8Array graph. + * + * @return A list representing a deep copy of the V8Array rooted at 'array'. + */ + public static List toList(final V8Array array) { + V8Map cache = new V8Map(); + try { + return toList(array, cache); + } finally { + cache.release(); + } + } + + /** + * Populates a Java array from a V8Array. The type of the array must be specified. + * Currently, only INTEGER, DOUBLE, BOOLEAN and STRING are supported. + * The V8Array must only contain elements of type 'arrayType'. The result + * can be optionally passed in as a parameter. + * + * This method will use J2V8's bulk array copy making it faster than iterating over + * all the elements in the array. + * + * @param array The V8Array to convert to a Java Array. + * @param arrayType The type of the V8Array to convert. + * @param result The array to use as the result. If null, a new array will be created. + * + * @return A Java array representing a V8Array. + */ + public static Object getTypedArray(final V8Array array, final int arrayType, final Object result) { + int length = array.length(); + if (arrayType == V8Value.INTEGER) { + int[] intArray = (int[]) result; + if ((intArray == null) || (intArray.length < length)) { + intArray = new int[length]; + } + array.getIntegers(0, length, intArray); + return intArray; + } else if (arrayType == V8Value.DOUBLE) { + double[] doubleArray = (double[]) result; + if ((doubleArray == null) || (doubleArray.length < length)) { + doubleArray = new double[length]; + } + array.getDoubles(0, length, doubleArray); + return doubleArray; + } else if (arrayType == V8Value.BOOLEAN) { + boolean[] booleanArray = (boolean[]) result; + if ((booleanArray == null) || (booleanArray.length < length)) { + booleanArray = new boolean[length]; + } + array.getBooleans(0, length, booleanArray); + return booleanArray; + } else if (arrayType == V8Value.STRING) { + String[] stringArray = (String[]) result; + if ((stringArray == null) || (stringArray.length < length)) { + stringArray = new String[length]; + } + array.getStrings(0, length, stringArray); + return stringArray; + } else if (arrayType == V8Value.BYTE) { + byte[] byteArray = (byte[]) result; + if ((byteArray == null) || (byteArray.length < length)) { + byteArray = new byte[length]; + } + array.getBytes(0, length, byteArray); + return byteArray; + } + throw new RuntimeException("Unsupported bulk load type: " + arrayType); + } + + /** + * Creates a Java array from a V8Array. The type of the Array must be specified. + * Currently, only INTEGER, DOUBLE, BOOLEAN and STRING are supported. + * The V8Array must only contain elements of type 'arrayType'. + * + * This method will use J2V8's bulk array copy making it faster than iterating over + * all the elements in the array. + * + * @param array The V8Array to convert to a Java Array. + * @param arrayType The type of the V8Array to convert. + * + * @return A Java array representing a V8Array. + */ + public static Object getTypedArray(final V8Array array, final int arrayType) { + int length = array.length(); + if (arrayType == V8Value.INTEGER) { + return array.getIntegers(0, length); + } else if (arrayType == V8Value.DOUBLE) { + return array.getDoubles(0, length); + } else if (arrayType == V8Value.BOOLEAN) { + return array.getBooleans(0, length); + } else if (arrayType == V8Value.STRING) { + return array.getStrings(0, length); + } + throw new RuntimeException("Unsupported bulk load type: " + arrayType); + } + + /** + * Creates a V8Object from a java.util.Map. This is a deep copy, so if the map + * contains other maps (or lists) they will also be converted. + * + * @param v8 The runtime on which to create the result. + * @param map The map to convert to a V8Object. + * + * @return A V8Object representing the map. + */ + public static V8Object toV8Object(final V8 v8, final Map map) { + Map cache = new Hashtable(); + try { + return toV8Object(v8, map, cache).twin(); + } finally { + for (V8Object v8Object : cache.values()) { + v8Object.release(); + } + } + } + + /** + * Creates a V8Array from a java.util.List. This is a deep copy, so if the list + * contains other lists (or maps) they will also be converted. + * + * @param v8 The runtime on which to create the result. + * @param list The list to convert to a V8Array. + * + * @return A V8Array representing the list. + */ + public static V8Array toV8Array(final V8 v8, final List list) { + Map cache = new Hashtable(); + try { + return toV8Array(v8, list, cache).twin(); + } finally { + for (V8Object v8Object : cache.values()) { + v8Object.release(); + } + } + } + + /** + * Returns an object usable with a V8 Runtime which represents + * the parameter 'value'. If 'value' is an Integer, Boolean, Double + * or String, then 'value' is simply returned as these are directly + * usable on V8. If 'value' is a map / list, then it's converted to + * a V8Object / V8Array first. + * + * If the result is a V8Value, it must be released. + * + * @param v8 The runtime on which to create V8Values. + * @param value The value to convert to an object usable with V8 + * + * @return An object which can be used directly with a V8 runtime. + */ + public static Object getV8Result(final V8 v8, final Object value) { + if (value == null) { + return null; + } + Map cache = new Hashtable(); + try { + Object result = getV8Result(v8, value, cache); + if (result instanceof V8Object) { + return ((V8Object) result).twin(); + } + return result; + } finally { + for (V8Object v8Object : cache.values()) { + v8Object.release(); + } + } + } + + /** + * Pushes a Java Object to a V8Array by first converting it to a V8Value if needed. + * If the value is a boxed primitive, then the primitive will be pushed. If the object + * is a Map / List then a deep copy will be performed, converting the object to a + * V8Object / V8Array first. + * + * @param v8 The runtime on which to create any needed V8Values. + * @param array The array to push the elements to. + * @param value The value to push to the array. + */ + public static void pushValue(final V8 v8, final V8Array array, final Object value) { + Map cache = new Hashtable(); + try { + pushValue(v8, array, value, cache); + } finally { + for (V8Object v8Object : cache.values()) { + v8Object.release(); + } + } + } + + /** + * Gets a Java Object representing the value at the given index in the V8Array. + * If the value is a primitive (int, boolean or double) then a boxed instance + * is returned. If the value is a String, then a String is returned. If + * the value is a V8Object or V8Array, then a Map or List is returned. + * + * @param array The array on which to lookup the value. The array is not + * released. + * @param index The index whose element to lookup. + * + * @return A Java Object representing the value at a given index. + */ + public static Object getValue(final V8Array array, final int index) { + V8Map cache = new V8Map(); + try { + return getValue(array, index, cache); + } finally { + cache.release(); + } + } + + /** + * Gets a Java Object representing the value with the given key in the V8Object. + * If the value is a primitive (int, boolean or double) then a boxed instance + * is returned. If the value is a String, then a String is returned. If + * the value is a V8Object or V8Array, then a Map or List is returned. + * + * @param object The object on which to lookup the value. The object is not + * released. + * @param key The key to use to lookup the value. + * + * @return A Java Object representing the value at a given key. + */ + public static Object getValue(final V8Object object, final String key) { + V8Map cache = new V8Map(); + try { + return getValue(object, key, cache); + } finally { + cache.release(); + } + } + + @SuppressWarnings("unchecked") + private static Map toMap(final V8Object object, final V8Map cache) { + if (object == null) { + return Collections.emptyMap(); + } + if (cache.containsKey(object)) { + return (Map) cache.get(object); + } + Map result = new V8PropertyMap(); + cache.put(object, result); + String[] keys = object.getKeys(); + for (String key : keys) { + Object value = getValue(object, key, cache); + if (value != IGNORE) { + result.put(key, value); + } + } + return result; + } + + @SuppressWarnings("unchecked") + private static List toList(final V8Array array, final V8Map cache) { + if (array == null) { + return Collections.emptyList(); + } + if (cache.containsKey(array)) { + return (List) cache.get(array); + } + List result = new ArrayList(); + cache.put(array, result); + for (int i = 0; i < array.length(); i++) { + Object value = getValue(array, i, cache); + if (value != IGNORE) { + result.add(getValue(array, i, cache)); + } + } + return result; + } + + private static V8Object toV8Object(final V8 v8, final Map map, final Map cache) { + if (cache.containsKey(map)) { + return cache.get(map); + } + V8Object result = new V8Object(v8); + cache.put(map, result); + try { + for (Entry entry : map.entrySet()) { + setValue(v8, result, entry.getKey(), entry.getValue(), cache); + } + } catch (IllegalStateException e) { + result.release(); + throw e; + } + return result; + } + + private static V8Array toV8Array(final V8 v8, final List list, final Map cache) { + if (cache.containsKey(new ListWrapper(list))) { + return (V8Array) cache.get(new ListWrapper(list)); + } + V8Array result = new V8Array(v8); + cache.put(new ListWrapper(list), result); + try { + for (int i = 0; i < list.size(); i++) { + Object value = list.get(i); + pushValue(v8, result, value, cache); + } + } catch (IllegalStateException e) { + result.release(); + throw e; + } + + return result; + } + + @SuppressWarnings("unchecked") + private static Object getV8Result(final V8 v8, final Object value, final Map cache) { + if (cache.containsKey(value)) { + return cache.get(value); + } + if (value instanceof Map) { + return toV8Object(v8, (Map) value, cache); + } else if (value instanceof List) { + return toV8Array(v8, (List) value, cache); + } + return value; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static void pushValue(final V8 v8, final V8Array result, final Object value, final Map cache) { + if (value == null) { + result.pushUndefined(); + } else if (value instanceof Integer) { + result.push((Integer) value); + } else if (value instanceof Long) { + result.push(new Double((Long) value)); + } else if (value instanceof Double) { + result.push((Double) value); + } else if (value instanceof Float) { + result.push((Float) value); + } else if (value instanceof String) { + result.push((String) value); + } else if (value instanceof Boolean) { + result.push((Boolean) value); + } else if (value instanceof Map) { + V8Object object = toV8Object(v8, (Map) value, cache); + result.push(object); + } else if (value instanceof List) { + V8Array array = toV8Array(v8, (List) value, cache); + result.push(array); + } else { + throw new IllegalStateException("Unsupported Object of type: " + value.getClass()); + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static void setValue(final V8 v8, final V8Object result, final String key, final Object value, final Map cache) { + if (value == null) { + result.addUndefined(key); + } else if (value instanceof Integer) { + result.add(key, (Integer) value); + } else if (value instanceof Long) { + result.add(key, (int) (long) (Long) value); + } else if (value instanceof Double) { + result.add(key, (Double) value); + } else if (value instanceof Float) { + result.add(key, (Float) value); + } else if (value instanceof String) { + result.add(key, (String) value); + } else if (value instanceof Boolean) { + result.add(key, (Boolean) value); + } else if (value instanceof Map) { + V8Object object = toV8Object(v8, (Map) value, cache); + result.add(key, object); + } else if (value instanceof List) { + V8Array array = toV8Array(v8, (List) value, cache); + result.add(key, array); + } else { + throw new IllegalStateException("Unsupported Object of type: " + value.getClass()); + } + } + + private static Object getValue(final V8Array array, final int index, final V8Map cache) { + int valueType = array.getType(index); + switch (valueType) { + case V8Value.INTEGER: + return array.getInteger(index); + case V8Value.DOUBLE: + return array.getDouble(index); + case V8Value.BOOLEAN: + return array.getBoolean(index); + case V8Value.STRING: + return array.getString(index); + case V8Value.V8_FUNCTION: + return IGNORE; + case V8Value.V8_TYPED_ARRAY: + V8Array typedArray = array.getArray(index); + try { + return ((V8TypedArray) typedArray).getByteBuffer(); + } finally { + if (typedArray instanceof V8Array) { + typedArray.release(); + } + } + case V8Value.V8_ARRAY: + V8Array arrayValue = array.getArray(index); + try { + return toList(arrayValue, cache); + } finally { + if (arrayValue instanceof V8Array) { + arrayValue.release(); + } + } + case V8Value.V8_OBJECT: + V8Object objectValue = array.getObject(index); + try { + return toMap(objectValue, cache); + } finally { + if (objectValue instanceof V8Object) { + objectValue.release(); + } + } + case V8Value.NULL: + return null; + case V8Value.UNDEFINED: + return V8.getUndefined(); + default: + throw new IllegalStateException("Cannot find type for index: " + index); + } + } + + private static Object getValue(final V8Object object, final String key, final V8Map cache) { + int valueType = object.getType(key); + switch (valueType) { + case V8Value.INTEGER: + return object.getInteger(key); + case V8Value.DOUBLE: + return object.getDouble(key); + case V8Value.BOOLEAN: + return object.getBoolean(key); + case V8Value.STRING: + return object.getString(key); + case V8Value.V8_FUNCTION: + return IGNORE; + case V8Value.V8_TYPED_ARRAY: + V8Array typedArray = object.getArray(key); + try { + return ((V8TypedArray) typedArray).getByteBuffer(); + } finally { + if (typedArray instanceof V8Array) { + typedArray.release(); + } + } + case V8Value.V8_ARRAY: + V8Array array = object.getArray(key); + try { + return toList(array, cache); + } finally { + if (array instanceof V8Array) { + array.release(); + } + } + case V8Value.V8_OBJECT: + V8Object child = object.getObject(key); + try { + return toMap(child, cache); + } finally { + if (child instanceof V8Object) { + child.release(); + } + } + case V8Value.NULL: + return null; + case V8Value.UNDEFINED: + return V8.getUndefined(); + default: + throw new IllegalStateException("Cannot find type for key: " + key); + } + } + + private V8ObjectUtils() { + + } + + static class ListWrapper { + private List list; + + public ListWrapper(final List list) { + this.list = list; + } + + @Override + public boolean equals(final Object obj) { + if (obj instanceof ListWrapper) { + return ((ListWrapper) obj).list == list; + } + return false; + } + + @Override + public int hashCode() { + return System.identityHashCode(list); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `typedArray` last assigned on line 445 could be null and is dereferenced at line 447. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object V8ObjectUtils.getValue(V8Array,int,V8Map) + +### Procedure Id: +com.eclipsesource.v8.utils.V8ObjectUtils.getValue(com.eclipsesource.v8.V8Array,int,com.eclipsesource.fd046dbbae538a3eee439603b812e919 + +### File: +src/main/java/com/eclipsesource/v8/utils/V8ObjectUtils.java + +### Key: +V8ObjectUtils.java|getValue|NULL_DEREFERENCE + +### Node Key: +8144698381ce182e42fba72006da536b + +### Hash: +abe3bc8679608e8b453482368bf4aa3b + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3729/instruction.md b/inferredbugs-3729/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..635251a415ac7a9864d73ca36bdab080b5b3149f --- /dev/null +++ b/inferredbugs-3729/instruction.md @@ -0,0 +1,1423 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** J2V8 +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/******************************************************************************* + * Copyright (c) 2014 EclipseSource and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * EclipseSource - initial API and implementation + ******************************************************************************/ +package com.eclipsesource.v8; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.eclipsesource.v8.utils.V8Executor; +import com.eclipsesource.v8.utils.V8Map; + +/** + * An isolated V8Runtime. All JavaScript execution must exist + * on a single runtime, and data is not shared between runtimes. + * A runtime must be created and released when finished. + * + * All access to a runtime must come from the same thread, unless + * the thread explicitly gives up control using the V8Locker. + * + * A public static factory method can be used to create the runtime. + * + * V8 runtime = V8.createV8Runtime(); + * + */ +public class V8 extends V8Object { + + private static Object lock = new Object(); + private volatile static int runtimeCounter = 0; + private static Runnable debugHandler = null; + private static Thread debugThread = null; + private static String v8Flags = null; + private static boolean initialized = false; + + private final V8Locker locker; + private int methodReferenceCounter = 0; + private boolean debugEnabled = false; + private long objectReferences = 0; + private long v8RuntimePtr = 0; + private List resources = null; + private V8Map executors = null; + private boolean forceTerminateExecutors = false; + private Map functions = new HashMap(); + + private static boolean nativeLibraryLoaded = false; + private static Error nativeLoadError = null; + private static Exception nativeLoadException = null; + private static V8Value undefined = new V8Object.Undefined(); + private static Object invalid = new Object(); + + private class MethodDescriptor { + Object object; + Method method; + JavaCallback callback; + JavaVoidCallback voidCallback; + boolean includeReceiver; + } + + private synchronized static void load(final String tmpDirectory) { + try { + LibraryLoader.loadLibrary(tmpDirectory); + nativeLibraryLoaded = true; + } catch (Error e) { + nativeLoadError = e; + } catch (Exception e) { + nativeLoadException = e; + } + } + + /** + * Determines if the native libraries are loaded. + * + * @return Returns true if the native libraries are loaded, + * false otherwise. + */ + public static boolean isLoaded() { + return nativeLibraryLoaded; + } + + /** + * Sets the V8 flags on the platform. All runtimes will be created + * with the same flags. Flags must be set before the runtime is + * created. + * + * @param flags The flags to set on V8 + */ + public static void setFlags(final String flags) { + v8Flags = flags; + initialized = false; + } + + /** + * Creates a new V8Runtime and loads the required + * native libraries if they are not already loaded. + * The current thread is given the lock to this runtime. + * + * @return A new isolated V8 Runtime. + */ + public static V8 createV8Runtime() { + return createV8Runtime(null, null); + } + + /** + * Creates a new V8Runtime and loads the required native libraries if they + * are not already loaded. An alias is also set for the global scope. For example, + * 'window' can be set as the global scope name. + * + * The current thread is given the lock to this runtime. + * + * @param globalAlias The name to associate with the global scope. + * + * @return A new isolated V8 Runtime. + */ + public static V8 createV8Runtime(final String globalAlias) { + return createV8Runtime(globalAlias, null); + } + + /** + * Creates a new V8Runtime and loads the required native libraries if they + * are not already loaded. An alias is also set for the global scope. For example, + * 'window' can be set as the global scope name. + * + * The current thread is given the lock to this runtime. + * + * @param globalAlias The name to associate with the global scope. + * @param tempDirectory The name of the directory to extract the native + * libraries too. + * + * @return A new isolated V8 Runtime. + */ + public static V8 createV8Runtime(final String globalAlias, final String tempDirectory) { + if (!nativeLibraryLoaded) { + synchronized (lock) { + if (!nativeLibraryLoaded) { + load(tempDirectory); + } + } + } + checkNativeLibraryLoaded(); + if (!initialized) { + _setFlags(v8Flags); + initialized = true; + } + if (debugThread == null) { + debugThread = Thread.currentThread(); + } + V8 runtime = new V8(globalAlias); + synchronized (lock) { + runtimeCounter++; + } + return runtime; + } + + private static void checkNativeLibraryLoaded() { + if (!nativeLibraryLoaded) { + if (nativeLoadError != null) { + throw new IllegalStateException("J2V8 native library not loaded.", nativeLoadError); + } else if (nativeLoadException != null) { + throw new IllegalStateException("J2V8 native library not loaded.", nativeLoadException); + } else { + throw new IllegalStateException("J2V8 native library not loaded."); + } + } + } + + protected V8() { + this(null); + } + + protected V8(final String globalAlias) { + super(null); + released = false; + locker = new V8Locker(); + checkThread(); + v8RuntimePtr = _createIsolate(globalAlias); + objectHandle = _getGlobalObject(v8RuntimePtr); + } + + /** + * Returns an UNDEFINED constant. + * + * @return The UNDEFINED constant value. + */ + public static V8Value getUndefined() { + return undefined; + } + + /** + * Enables debug support for this runtime. + * + * @param port The port to listen for debug connections. + * @param waitForConnection True if the runtime should wait on the first + * instruction for the debugger to connect. + * + * @return true if debug support was successfully enabled, false otherwise + * + * @deprecated NOTE: This is not API and likely to change + */ + @Deprecated + public boolean enableDebugSupport(final int port, final boolean waitForConnection) { + V8.checkDebugThread(); + debugEnabled = enableDebugSupport(getV8RuntimePtr(), port, waitForConnection); + return debugEnabled; + } + + /** + * Enables debug support for this runtime and does not pause for a connection. + * + * @param port The port to listen for debug connections. + * + * @return true if debug support was successfully enabled, false otherwise + * + * @deprecated NOTE: This is not API and likely to change + */ + @Deprecated + public boolean enableDebugSupport(final int port) { + V8.checkDebugThread(); + debugEnabled = enableDebugSupport(getV8RuntimePtr(), port, false); + return debugEnabled; + } + + /** + * Processes all outstanding debug messages for this runtime. + * + * @deprecated + */ + @Deprecated + public static void processDebugMessages(final V8 runtime) { + runtime.checkThread(); + runtime._processDebugMessages(runtime.getV8RuntimePtr()); + } + + /** + * Disables debug support for this runtime. + * + * @deprecated + */ + @Deprecated + public void disableDebugSupport() { + V8.checkDebugThread(); + disableDebugSupport(getV8RuntimePtr()); + debugEnabled = false; + } + + /** + * Registers a callback that will be invoked whenever a debug message + * is received. This can be used so the main thread can call + * processDebugMessages to handle the messages. + * + * @param handler The debug handler to invoke when a debug message + * is received. + * + * @deprecated + */ + @Deprecated + public static void registerDebugHandler(final Runnable handler) { + debugHandler = handler; + } + + /** + * Returns the number of active runtimes. + * + * @return The number of active runtimes. + */ + public static int getActiveRuntimes() { + return runtimeCounter; + } + + protected long getV8RuntimePtr() { + return v8RuntimePtr; + } + + /* + * (non-Javadoc) + * @see com.eclipsesource.v8.V8Value#release() + */ + @Override + public void release() { + release(true); + } + + /** + * Terminates any JavaScript executing on this runtime. Once + * the runtime is released, any executors that were spawned + * will also be force terminated. + */ + public void terminateExecution() { + forceTerminateExecutors = true; + terminateExecution(v8RuntimePtr); + } + + /** + * Release native resources associated with this runtime. Once + * released, a runtime cannot be reused. + * + * @param reportMemoryLeaks True if memory leaks should be + * reported by throwing an IllegalStateException if any + * objects were not released. + */ + public void release(final boolean reportMemoryLeaks) { + if (isReleased()) { + return; + } + checkThread(); + if (debugEnabled) { + disableDebugSupport(); + } + releaseResources(); + shutdownExecutors(forceTerminateExecutors); + if (executors != null) { + executors.clear(); + } + synchronized (lock) { + runtimeCounter--; + } + _releaseRuntime(v8RuntimePtr); + v8RuntimePtr = 0L; + released = true; + if (reportMemoryLeaks && (objectReferences > 0)) { + throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime"); + } + } + + private void releaseResources() { + if (resources != null) { + for (Releasable releasable : resources) { + releasable.release(); + } + resources.clear(); + resources = null; + } + } + + /** + * Registers an executor with this runtime. An executor is another + * runtime with its own thread. By registering an executor, it can be + * terminated when this runtime is released. + * + * @param key The key to associate the executor with. + * @param executor The executor itself. + */ + public void registerV8Executor(final V8Object key, final V8Executor executor) { + checkThread(); + if (executors == null) { + executors = new V8Map(); + } + executors.put(key, executor); + } + + /** + * Removes the executor from this runtime. The executor is + * *NOT* shutdown, simply removed from the list of known + * executors. + * + * @param key The key the executor was associated with. + * @return The executor or null if it does not exist. + */ + public V8Executor removeExecutor(final V8Object key) { + checkThread(); + if (executors == null) { + return null; + } + return executors.remove(key); + } + + /** + * Returns the executor associated with the given key. + * + * @param key The key the executor was associated with. + * @return The executor or null if it does not exist. + */ + public V8Executor getExecutor(final V8Object key) { + checkThread(); + if (executors == null) { + return null; + } + return executors.get(key); + } + + /** + * Shutdown all executors associated with this runtime. + * If force terminate is specified, it will forcefully terminate + * the executors, otherwise it will simply signal that they + * should terminate. + * + * @param forceTerminate Specify if the executors should be + * forcefully terminated, or simply notified to shutdown when ready. + */ + public void shutdownExecutors(final boolean forceTerminate) { + checkThread(); + if (executors == null) { + return; + } + for (V8Executor executor : executors.values()) { + if (forceTerminate) { + executor.forceTermination(); + } else { + executor.shutdown(); + } + } + } + + /** + * Registers a resource with this runtime. All registered + * resources will be released before the runtime is released. + * + * @param resource The resource to register. + */ + public void registerResource(final Releasable resource) { + checkThread(); + if (resources == null) { + resources = new ArrayList(); + } + resources.add(resource); + } + + /** + * Executes a JS Script on this runtime and returns the result as an integer. + * If the result is not an integer, then a V8ResultUndefinedException is thrown. + * + * @param script The script to execute. + * + * @return The result of the script as an integer, or V8ResultUndefinedException if + * the result is not an integer. + */ + public int executeIntegerScript(final String script) { + return executeIntegerScript(script, null, 0); + } + + /** + * Executes a JS Script on this runtime and returns the result as an integer. + * If the result is not an integer, then a V8ResultUndefinedException is thrown. + * + * @param script The script to execute. + * @param scriptName The name of the script + * @param lineNumber The line number that is considered to be the first line of + * the script. Typically 0, but could be set to another value for excepton purposes. + * + * @return The result of the script as an integer, or V8ResultUndefinedException if + * the result is not an integer. + */ + public int executeIntegerScript(final String script, final String scriptName, final int lineNumber) { + checkThread(); + checkScript(script); + return executeIntegerScript(v8RuntimePtr, script, scriptName, lineNumber); + } + + protected void createTwin(final V8Value value, final V8Value twin) { + checkThread(); + createTwin(v8RuntimePtr, value.getHandle(), twin.getHandle()); + } + + /** + * Executes a JS Script on this runtime and returns the result as a double. + * If the result is not a double, then a V8ResultUndefinedException is thrown. + * + * @param script The script to execute. + * + * @return The result of the script as a double, or V8ResultUndefinedException if + * the result is not a double. + */ + public double executeDoubleScript(final String script) { + return executeDoubleScript(script, null, 0); + } + + /** + * Executes a JS Script on this runtime and returns the result as a double. + * If the result is not a double, then a V8ResultUndefinedException is thrown. + * + * @param script The script to execute. + * @param scriptName The name of the script + * @param lineNumber The line number that is considered to be the first line of + * the script. Typically 0, but could be set to another value for exception stack trace purposes. + * + * @return The result of the script as a double, or V8ResultUndefinedException if + * the result is not a double. + */ + public double executeDoubleScript(final String script, final String scriptName, final int lineNumber) { + checkThread(); + checkScript(script); + return executeDoubleScript(v8RuntimePtr, script, scriptName, lineNumber); + } + + /** + * Executes a JS Script on this runtime and returns the result as a String. + * If the result is not a String, then a V8ResultUndefinedException is thrown. + * + * @param script The script to execute. + * + * @return The result of the script as a String, or V8ResultUndefinedException if + * the result is not a String. + */ + public String executeStringScript(final String script) { + return executeStringScript(script, null, 0); + } + + /** + * Executes a JS Script on this runtime and returns the result as a String. + * If the result is not a String, then a V8ResultUndefinedException is thrown. + * + * @param script The script to execute. + * @param scriptName The name of the script + * @param lineNumber The line number that is considered to be the first line of + * the script. Typically 0, but could be set to another value for exception stack trace purposes. + * + * @return The result of the script as a String, or V8ResultUndefinedException if + * the result is not a String. + */ + public String executeStringScript(final String script, final String scriptName, final int lineNumber) { + checkThread(); + checkScript(script); + return executeStringScript(v8RuntimePtr, script, scriptName, lineNumber); + } + + /** + * Executes a JS Script on this runtime and returns the result as a boolean. + * If the result is not a boolean, then a V8ResultUndefinedException is thrown. + * + * @param script The script to execute. + * + * @return The result of the script as a boolean, or V8ResultUndefinedException if + * the result is not a boolean. + */ + public boolean executeBooleanScript(final String script) { + return executeBooleanScript(script, null, 0); + } + + /** + * Executes a JS Script on this runtime and returns the result as a boolean. + * If the result is not a boolean, then a V8ResultUndefinedException is thrown. + * + * @param script The script to execute. + * @param scriptName The name of the script + * @param lineNumber The line number that is considered to be the first line of + * the script. Typically 0, but could be set to another value for exception stack trace purposes. + * + * @return The result of the script as a boolean, or V8ResultUndefinedException if + * the result is not a boolean. + */ + public boolean executeBooleanScript(final String script, final String scriptName, final int lineNumber) { + checkThread(); + checkScript(script); + return executeBooleanScript(v8RuntimePtr, script, scriptName, lineNumber); + } + + /** + * Executes a JS Script on this runtime and returns the result as a V8Array. + * If the result is not a V8Array, then a V8ResultUndefinedException is thrown. + * + * @param script The script to execute. + * + * @return The result of the script as a V8Array, or V8ResultUndefinedException if + * the result is not a V8Array. + */ + public V8Array executeArrayScript(final String script) { + return this.executeArrayScript(script, null, 0); + } + + /** + * Executes a JS Script on this runtime and returns the result as a V8Array. + * If the result is not a V8Array, then a V8ResultUndefinedException is thrown. + * + * @param script The script to execute. + * @param scriptName The name of the script + * @param lineNumber The line number that is considered to be the first line of + * the script. Typically 0, but could be set to another value for exception stack trace purposes. + * + * @return The result of the script as a V8Array, or V8ResultUndefinedException if + * the result is not a V8Array. + */ + public V8Array executeArrayScript(final String script, final String scriptName, final int lineNumber) { + checkThread(); + Object result = this.executeScript(script, null, 0); + if (result instanceof V8Array) { + return (V8Array) result; + } + throw new V8ResultUndefined(); + } + + /** + * Executes a JS Script on this runtime and returns the result as a Java Object. + * Primitives will be boxed. + * + * @param script The script to execute. + * + * @return The result of the script as a Java Object. + */ + public Object executeScript(final String script) { + return executeScript(script, null, 0); + } + + /** + * Executes a JS Script on this runtime and returns the result as a Java Object. + * Primitives will be boxed. + * + * @param script The script to execute. + * @param scriptName The name of the script + * @param lineNumber The line number that is considered to be the first line of + * the script. Typically 0, but could be set to another value for exception stack trace purposes. + * + * @return The result of the script as a Java Object. + */ + public Object executeScript(final String script, final String scriptName, final int lineNumber) { + checkThread(); + checkScript(script); + return executeScript(getV8RuntimePtr(), UNKNOWN, script, scriptName, lineNumber); + } + + /** + * Executes a JS Script on this runtime and returns the result as a V8Object. + * If the result is not a V8Object, then a V8ResultUndefinedException is thrown. + * + * @param script The script to execute. + * + * @return The result of the script as a V8Object, or V8ResultUndefinedException if + * the result is not a V8Object. + */ + public V8Object executeObjectScript(final String script) { + return this.executeObjectScript(script, null, 0); + } + + /** + * Executes a JS Script on this runtime and returns the result as a V8Object. + * If the result is not a V8Object, then a V8ResultUndefinedException is thrown. + * + * @param script The script to execute. + * @param scriptName The name of the script + * @param lineNumber The line number that is considered to be the first line of + * the script. Typically 0, but could be set to another value for exception stack trace purposes. + * + * @return The result of the script as a V8Object, or V8ResultUndefinedException if + * the result is not a V8Object. + */ + public V8Object executeObjectScript(final String script, final String scriptName, final int lineNumber) { + checkThread(); + Object result = this.executeScript(script, null, 0); + if (result instanceof V8Object) { + return (V8Object) result; + } + throw new V8ResultUndefined(); + } + + /** + * Executes a JS Script on this runtime. + * + * @param script The script to execute. + */ + public void executeVoidScript(final String script) { + this.executeVoidScript(script, null, 0); + } + + /** + * Executes a JS Script on this runtime. + * + * @param script The script to execute. + * @param scriptName The name of the script + * @param lineNumber The line number that is considered to be the first line of + * the script. Typically 0, but could be set to another value for exception stack trace purposes. + */ + public void executeVoidScript(final String script, final String scriptName, final int lineNumber) { + checkThread(); + checkScript(script); + executeVoidScript(v8RuntimePtr, script, scriptName, lineNumber); + } + + /** + * Returns the locker associated with this runtime. The locker allows + * threads to give up control of the runtime and other threads to acquire + * control. + * + * @return The locker associated with this runtime. + */ + public V8Locker getLocker() { + return locker; + } + + /** + * Returns the unique build ID of the native library. + */ + public long getBuildID() { + return _getBuildID(); + } + + void checkThread() { + locker.checkThread(); + if (isReleased()) { + throw new Error("Runtime disposed error."); + } + } + + static void checkDebugThread() { + if ((debugThread != null) && (debugThread != Thread.currentThread())) { + throw new Error("Invalid V8 thread access."); + } + } + + static void checkScript(final String script) { + if (script == null) { + throw new NullPointerException("Script is null"); + } + } + + void registerCallback(final Object object, final Method method, final long objectHandle, final String jsFunctionName, final boolean includeReceiver) { + MethodDescriptor methodDescriptor = new MethodDescriptor(); + methodDescriptor.object = object; + methodDescriptor.method = method; + methodDescriptor.includeReceiver = includeReceiver; + int methodID = methodReferenceCounter++; + getFunctionRegistry().put(methodID, methodDescriptor); + registerJavaMethod(getV8RuntimePtr(), objectHandle, jsFunctionName, methodID, isVoidMethod(method)); + } + + void registerVoidCallback(final JavaVoidCallback callback, final long objectHandle, final String jsFunctionName) { + MethodDescriptor methodDescriptor = new MethodDescriptor(); + methodDescriptor.voidCallback = callback; + int methodID = methodReferenceCounter++; + getFunctionRegistry().put(methodID, methodDescriptor); + registerJavaMethod(getV8RuntimePtr(), objectHandle, jsFunctionName, methodID, true); + } + + void registerCallback(final JavaCallback callback, final long objectHandle, final String jsFunctionName) { + MethodDescriptor methodDescriptor = new MethodDescriptor(); + methodDescriptor.callback = callback; + int methodID = methodReferenceCounter++; + getFunctionRegistry().put(methodID, methodDescriptor); + registerJavaMethod(getV8RuntimePtr(), objectHandle, jsFunctionName, methodID, false); + } + + private boolean isVoidMethod(final Method method) { + Class returnType = method.getReturnType(); + if (returnType.equals(Void.TYPE)) { + return true; + } + return false; + } + + private Object getDefaultValue(final Class type) { + if (type.equals(V8Object.class)) { + return new V8Object.Undefined(); + } else if (type.equals(V8Array.class)) { + return new V8Array.Undefined(); + } + return invalid; + } + + protected Object callObjectJavaMethod(final int methodID, final V8Object receiver, final V8Array parameters) throws Throwable { + MethodDescriptor methodDescriptor = getFunctionRegistry().get(methodID); + if (methodDescriptor.callback != null) { + return checkResult(methodDescriptor.callback.invoke(receiver, parameters)); + } + boolean hasVarArgs = methodDescriptor.method.isVarArgs(); + Object[] args = getArgs(receiver, methodDescriptor, parameters, hasVarArgs); + checkArgs(args); + try { + Object result = methodDescriptor.method.invoke(methodDescriptor.object, args); + return checkResult(result); + } catch (InvocationTargetException e) { + throw e.getTargetException(); + } catch (IllegalAccessException e) { + throw e; + } catch (IllegalArgumentException e) { + throw e; + } finally { + releaseArguments(args, hasVarArgs); + } + + } + + private Object checkResult(final Object result) { + if (result == null) { + return result; + } + if (result instanceof Float) { + return ((Float) result).doubleValue(); + } + if ((result instanceof Integer) || (result instanceof Double) || (result instanceof Boolean) + || (result instanceof String)) { + return result; + } + if (result instanceof V8Value) { + if (((V8Value) result).isReleased()) { + throw new V8RuntimeException("V8Value already released."); + } + return result; + } + throw new V8RuntimeException("Unknown return type: " + result.getClass()); + } + + protected void callVoidJavaMethod(final int methodID, final V8Object receiver, final V8Array parameters) throws Throwable { + MethodDescriptor methodDescriptor = getFunctionRegistry().get(methodID); + if (methodDescriptor.voidCallback != null) { + methodDescriptor.voidCallback.invoke(receiver, parameters); + return; + } + boolean hasVarArgs = methodDescriptor.method.isVarArgs(); + Object[] args = getArgs(receiver, methodDescriptor, parameters, hasVarArgs); + checkArgs(args); + try { + methodDescriptor.method.invoke(methodDescriptor.object, args); + } catch (InvocationTargetException e) { + throw e.getTargetException(); + } catch (IllegalAccessException e) { + throw e; + } catch (IllegalArgumentException e) { + throw e; + } finally { + releaseArguments(args, hasVarArgs); + } + } + + private void checkArgs(final Object[] args) { + for (Object argument : args) { + if (argument == invalid) { + throw new IllegalArgumentException("argument type mismatch"); + } + } + } + + private void releaseArguments(final Object[] args, final boolean hasVarArgs) { + if (hasVarArgs && ((args.length > 0) && (args[args.length - 1] instanceof Object[]))) { + Object[] varArgs = (Object[]) args[args.length - 1]; + for (Object object : varArgs) { + if (object instanceof V8Object) { + ((V8Value) object).release(); + } + } + } + for (Object arg : args) { + if (arg instanceof V8Object) { + ((V8Value) arg).release(); + } + } + } + + private Object[] getArgs(final V8Object receiver, final MethodDescriptor methodDescriptor, final V8Array parameters, final boolean hasVarArgs) { + int numberOfParameters = methodDescriptor.method.getParameterTypes().length; + int varArgIndex = hasVarArgs ? numberOfParameters - 1 : numberOfParameters; + Object[] args = setDefaultValues(new Object[numberOfParameters], methodDescriptor.method.getParameterTypes(), receiver, methodDescriptor.includeReceiver); + List varArgs = new ArrayList(); + populateParamters(parameters, varArgIndex, args, varArgs, methodDescriptor.includeReceiver); + if (hasVarArgs) { + Object varArgContainer = getVarArgContainer(methodDescriptor.method.getParameterTypes(), varArgs.size()); + System.arraycopy(varArgs.toArray(), 0, varArgContainer, 0, varArgs.size()); + args[varArgIndex] = varArgContainer; + } + return args; + } + + private Object getVarArgContainer(final Class[] parameterTypes, final int size) { + Class clazz = parameterTypes[parameterTypes.length - 1]; + if (clazz.isArray()) { + clazz = clazz.getComponentType(); + } + Object result = java.lang.reflect.Array.newInstance(clazz, size); + return result; + } + + private void populateParamters(final V8Array parameters, final int varArgIndex, final Object[] args, final List varArgs, final boolean includeReceiver) { + int start = 0; + if (includeReceiver) { + start = 1; + } + for (int i = start; i < (parameters.length() + start); i++) { + if (i >= varArgIndex) { + varArgs.add(getArrayItem(parameters, i - start)); + } else { + args[i] = getArrayItem(parameters, i - start); + } + } + } + + private Object[] setDefaultValues(final Object[] parameters, final Class[] parameterTypes, final V8Object receiver, final boolean includeReceiver) { + int start = 0; + if (includeReceiver) { + start = 1; + parameters[0] = receiver; + } + for (int i = start; i < parameters.length; i++) { + parameters[i] = getDefaultValue(parameterTypes[i]); + } + return parameters; + } + + private Object getArrayItem(final V8Array array, final int index) { + try { + int type = array.getType(index); + switch (type) { + case INTEGER: + return array.getInteger(index); + case DOUBLE: + return array.getDouble(index); + case BOOLEAN: + return array.getBoolean(index); + case STRING: + return array.getString(index); + case V8_ARRAY: + return array.getArray(index); + case V8_OBJECT: + return array.getObject(index); + case V8_FUNCTION: + return array.getObject(index); + case UNDEFINED: + return V8.getUndefined(); + } + } catch (V8ResultUndefined e) { + // do nothing + } + return null; + } + + protected static void debugMessageReceived() { + if (debugHandler != null) { + debugHandler.run(); + } + } + + private Map getFunctionRegistry() { + if (functions == null) { + functions = new HashMap(); + } + return functions; + } + + protected long initNewV8Object(final long v8RuntimePtr) { + return _initNewV8Object(v8RuntimePtr); + } + + protected void createTwin(final long v8RuntimePtr, final long objectHandle, final long twinHandle) { + _createTwin(v8RuntimePtr, objectHandle, twinHandle); + } + + protected int executeIntegerScript(final long v8RuntimePtr, final String script, final String scriptName, final int lineNumber) { + return _executeIntegerScript(v8RuntimePtr, script, scriptName, lineNumber); + } + + protected double executeDoubleScript(final long v8RuntimePtr, final String script, final String scriptName, final int lineNumber) { + return _executeDoubleScript(v8RuntimePtr, script, scriptName, lineNumber); + } + + protected String executeStringScript(final long v8RuntimePtr, final String script, final String scriptName, final int lineNumber) { + return _executeStringScript(v8RuntimePtr, script, scriptName, lineNumber); + } + + protected boolean executeBooleanScript(final long v8RuntimePtr, final String script, final String scriptName, final int lineNumber) { + return _executeBooleanScript(v8RuntimePtr, script, scriptName, lineNumber); + } + + protected Object executeScript(final long v8RuntimePtr, final int expectedType, final String script, final String scriptName, final int lineNumber) { + return _executeScript(v8RuntimePtr, expectedType, script, scriptName, lineNumber); + } + + protected void executeVoidScript(final long v8RuntimePtr, final String script, final String scriptName, final int lineNumber) { + _executeVoidScript(v8RuntimePtr, script, scriptName, lineNumber); + } + + protected void release(final long v8RuntimePtr, final long objectHandle) { + _release(v8RuntimePtr, objectHandle); + } + + protected boolean contains(final long v8RuntimePtr, final long objectHandle, final String key) { + return _contains(v8RuntimePtr, objectHandle, key); + } + + protected String[] getKeys(final long v8RuntimePtr, final long objectHandle) { + return _getKeys(v8RuntimePtr, objectHandle); + } + + protected int getInteger(final long v8RuntimePtr, final long objectHandle, final String key) { + return _getInteger(v8RuntimePtr, objectHandle, key); + } + + protected boolean getBoolean(final long v8RuntimePtr, final long objectHandle, final String key) { + return _getBoolean(v8RuntimePtr, objectHandle, key); + } + + protected double getDouble(final long v8RuntimePtr, final long objectHandle, final String key) { + return _getDouble(v8RuntimePtr, objectHandle, key); + } + + protected String getString(final long v8RuntimePtr, final long objectHandle, final String key) { + return _getString(v8RuntimePtr, objectHandle, key); + } + + protected Object get(final long v8RuntimePtr, final int expectedType, final long objectHandle, final String key) { + return _get(v8RuntimePtr, expectedType, objectHandle, key); + } + + protected int executeIntegerFunction(final long v8RuntimePtr, final long objectHandle, final String name, final long parametersHandle) { + return _executeIntegerFunction(v8RuntimePtr, objectHandle, name, parametersHandle); + } + + protected double executeDoubleFunction(final long v8RuntimePtr, final long objectHandle, final String name, final long parametersHandle) { + return _executeDoubleFunction(v8RuntimePtr, objectHandle, name, parametersHandle); + } + + protected String executeStringFunction(final long v8RuntimePtr, final long handle, final String name, final long parametersHandle) { + return _executeStringFunction(v8RuntimePtr, handle, name, parametersHandle); + } + + protected boolean executeBooleanFunction(final long v8RuntimePtr, final long handle, final String name, final long parametersHandle) { + return _executeBooleanFunction(v8RuntimePtr, handle, name, parametersHandle); + } + + protected Object executeFunction(final long v8RuntimePtr, final int expectedType, final long objectHandle, final String name, final long parametersHandle) { + return _executeFunction(v8RuntimePtr, expectedType, objectHandle, name, parametersHandle); + } + + protected Object executeFunction(final long v8RuntimePtr, final long receiverHandle, final long functionHandle, final long parametersHandle) { + return _executeFunction(v8RuntimePtr, receiverHandle, functionHandle, parametersHandle); + } + + protected void executeVoidFunction(final long v8RuntimePtr, final long objectHandle, final String name, final long parametersHandle) { + _executeVoidFunction(v8RuntimePtr, objectHandle, name, parametersHandle); + } + + protected boolean equals(final long v8RuntimePtr, final long objectHandle, final long that) { + return _equals(v8RuntimePtr, objectHandle, that); + } + + protected boolean strictEquals(final long v8RuntimePtr, final long objectHandle, final long that) { + return _strictEquals(v8RuntimePtr, objectHandle, that); + } + + protected boolean sameValue(final long v8RuntimePtr, final long objectHandle, final long that) { + return _sameValue(v8RuntimePtr, objectHandle, that); + } + + protected int identityHash(final long v8RuntimePtr, final long objectHandle) { + return _identityHash(v8RuntimePtr, objectHandle); + } + + protected void add(final long v8RuntimePtr, final long objectHandle, final String key, final int value) { + _add(v8RuntimePtr, objectHandle, key, value); + } + + protected void addObject(final long v8RuntimePtr, final long objectHandle, final String key, final long value) { + _addObject(v8RuntimePtr, objectHandle, key, value); + } + + protected void add(final long v8RuntimePtr, final long objectHandle, final String key, final boolean value) { + _add(v8RuntimePtr, objectHandle, key, value); + } + + protected void add(final long v8RuntimePtr, final long objectHandle, final String key, final double value) { + _add(v8RuntimePtr, objectHandle, key, value); + } + + protected void add(final long v8RuntimePtr, final long objectHandle, final String key, final String value) { + _add(v8RuntimePtr, objectHandle, key, value); + } + + protected void addUndefined(final long v8RuntimePtr, final long objectHandle, final String key) { + _addUndefined(v8RuntimePtr, objectHandle, key); + } + + protected void addNull(final long v8RuntimePtr, final long objectHandle, final String key) { + _addNull(v8RuntimePtr, objectHandle, key); + } + + protected void registerJavaMethod(final long v8RuntimePtr, final long objectHandle, final String functionName, final int methodID, final boolean voidMethod) { + _registerJavaMethod(v8RuntimePtr, objectHandle, functionName, methodID, voidMethod); + } + + protected long initNewV8Array(final long v8RuntimePtr) { + return _initNewV8Array(v8RuntimePtr); + } + + protected int arrayGetSize(final long v8RuntimePtr, final long arrayHandle) { + return _arrayGetSize(v8RuntimePtr, arrayHandle); + } + + protected int arrayGetInteger(final long v8RuntimePtr, final long arrayHandle, final int index) { + return _arrayGetInteger(v8RuntimePtr, arrayHandle, index); + } + + protected boolean arrayGetBoolean(final long v8RuntimePtr, final long arrayHandle, final int index) { + return _arrayGetBoolean(v8RuntimePtr, arrayHandle, index); + } + + protected double arrayGetDouble(final long v8RuntimePtr, final long arrayHandle, final int index) { + return _arrayGetDouble(v8RuntimePtr, arrayHandle, index); + } + + protected String arrayGetString(final long v8RuntimePtr, final long arrayHandle, final int index) { + return _arrayGetString(v8RuntimePtr, arrayHandle, index); + } + + protected Object arrayGet(final long v8RuntimePtr, final int expectedType, final long arrayHandle, final int index) { + return _arrayGet(v8RuntimePtr, expectedType, arrayHandle, index); + } + + protected void addArrayIntItem(final long v8RuntimePtr, final long arrayHandle, final int value) { + _addArrayIntItem(v8RuntimePtr, arrayHandle, value); + } + + protected void addArrayBooleanItem(final long v8RuntimePtr, final long arrayHandle, final boolean value) { + _addArrayBooleanItem(v8RuntimePtr, arrayHandle, value); + } + + protected void addArrayDoubleItem(final long v8RuntimePtr, final long arrayHandle, final double value) { + _addArrayDoubleItem(v8RuntimePtr, arrayHandle, value); + } + + protected void addArrayStringItem(final long v8RuntimePtr, final long arrayHandle, final String value) { + _addArrayStringItem(v8RuntimePtr, arrayHandle, value); + } + + protected void addArrayObjectItem(final long v8RuntimePtr, final long arrayHandle, final long value) { + _addArrayObjectItem(v8RuntimePtr, arrayHandle, value); + } + + protected void addArrayUndefinedItem(final long v8RuntimePtr, final long arrayHandle) { + _addArrayUndefinedItem(v8RuntimePtr, arrayHandle); + } + + protected void addArrayNullItem(final long v8RuntimePtr, final long arrayHandle) { + _addArrayNullItem(v8RuntimePtr, arrayHandle); + } + + protected int getType(final long v8RuntimePtr, final long objectHandle, final String key) { + return _getType(v8RuntimePtr, objectHandle, key); + } + + protected int getType(final long v8RuntimePtr, final long objectHandle, final int index) { + return _getType(v8RuntimePtr, objectHandle, index); + } + + protected int getArrayType(final long v8RuntimePtr, final long objectHandle) { + return _getArrayType(v8RuntimePtr, objectHandle); + } + + protected int getType(final long v8RuntimePtr, final long objectHandle, final int index, final int length) { + return _getType(v8RuntimePtr, objectHandle, index, length); + } + + protected void setPrototype(final long v8RuntimePtr, final long objectHandle, final long prototypeHandle) { + _setPrototype(v8RuntimePtr, objectHandle, prototypeHandle); + } + + protected boolean enableDebugSupport(final long v8RuntimePtr, final int port, final boolean waitForConnection) { + return _enableDebugSupport(v8RuntimePtr, port, waitForConnection); + } + + protected void disableDebugSupport(final long v8RuntimePtr) { + _disableDebugSupport(v8RuntimePtr); + } + + protected void processDebugMessages(final long v8RuntimePtr) { + _processDebugMessages(v8RuntimePtr); + } + + protected int[] arrayGetIntegers(final long v8RuntimePtr, final long objectHandle, final int index, final int length) { + return _arrayGetIntegers(v8RuntimePtr, objectHandle, index, length); + } + + protected double[] arrayGetDoubles(final long v8RuntimePtr, final long objectHandle, final int index, final int length) { + return _arrayGetDoubles(v8RuntimePtr, objectHandle, index, length); + } + + protected boolean[] arrayGetBooleans(final long v8RuntimePtr, final long objectHandle, final int index, final int length) { + return _arrayGetBooleans(v8RuntimePtr, objectHandle, index, length); + } + + protected String[] arrayGetStrings(final long v8RuntimePtr, final long objectHandle, final int index, final int length) { + return _arrayGetStrings(v8RuntimePtr, objectHandle, index, length); + } + + protected int arrayGetIntegers(final long v8RuntimePtr, final long objectHandle, final int index, final int length, final int[] resultArray) { + return _arrayGetIntegers(v8RuntimePtr, objectHandle, index, length, resultArray); + } + + protected int arrayGetDoubles(final long v8RuntimePtr, final long objectHandle, final int index, final int length, final double[] resultArray) { + return _arrayGetDoubles(v8RuntimePtr, objectHandle, index, length, resultArray); + } + + protected int arrayGetBooleans(final long v8RuntimePtr, final long objectHandle, final int index, final int length, final boolean[] resultArray) { + return _arrayGetBooleans(v8RuntimePtr, objectHandle, index, length, resultArray); + } + + protected int arrayGetStrings(final long v8RuntimePtr, final long objectHandle, final int index, final int length, final String[] resultArray) { + return _arrayGetStrings(v8RuntimePtr, objectHandle, index, length, resultArray); + } + + protected void terminateExecution(final long v8RuntimePtr) { + _terminateExecution(v8RuntimePtr); + } + + private native long _initNewV8Object(long v8RuntimePtr); + + private native void _createTwin(long v8RuntimePtr, long objectHandle, long twinHandle); + + private native void _releaseRuntime(long v8RuntimePtr); + + private native long _createIsolate(String globalAlias); + + private native int _executeIntegerScript(long v8RuntimePtr, final String script, final String scriptName, final int lineNumber); + + private native double _executeDoubleScript(long v8RuntimePtr, final String script, final String scriptName, final int lineNumber); + + private native String _executeStringScript(long v8RuntimePtr, final String script, final String scriptName, final int lineNumber); + + private native boolean _executeBooleanScript(long v8RuntimePtr, final String script, final String scriptName, final int lineNumber); + + private native Object _executeScript(long v8RuntimePtr, int expectedType, String script, String scriptName, int lineNumber); + + private native void _executeVoidScript(long v8RuntimePtr, String script, String scriptName, int lineNumber); + + private native void _release(long v8RuntimePtr, long objectHandle); + + private native boolean _contains(long v8RuntimePtr, long objectHandle, final String key); + + private native String[] _getKeys(long v8RuntimePtr, long objectHandle); + + private native int _getInteger(long v8RuntimePtr, long objectHandle, final String key); + + private native boolean _getBoolean(long v8RuntimePtr, long objectHandle, final String key); + + private native double _getDouble(long v8RuntimePtr, long objectHandle, final String key); + + private native String _getString(long v8RuntimePtr, long objectHandle, final String key); + + private native Object _get(long v8RuntimePtr, int expectedType, long objectHandle, final String key); + + private native int _executeIntegerFunction(long v8RuntimePtr, long objectHandle, String name, long parametersHandle); + + private native double _executeDoubleFunction(long v8RuntimePtr, long objectHandle, String name, long parametersHandle); + + private native String _executeStringFunction(long v8RuntimePtr2, long handle, String name, long parametersHandle); + + private native boolean _executeBooleanFunction(long v8RuntimePtr2, long handle, String name, long parametersHandle); + + private native Object _executeFunction(long v8RuntimePtr, int expectedType, long objectHandle, String name, long parametersHandle); + + private native Object _executeFunction(long v8RuntimePtr, long receiverHandle, long functionHandle, long parametersHandle); + + private native void _executeVoidFunction(long v8RuntimePtr, long objectHandle, final String name, final long parametersHandle); + + private native boolean _equals(long v8RuntimePtr, long objectHandle, long that); + + private native boolean _strictEquals(long v8RuntimePtr, long objectHandle, long that); + + private native boolean _sameValue(long v8RuntimePtr, long objectHandle, long that); + + private native int _identityHash(long v8RuntimePtr, long objectHandle); + + private native void _add(long v8RuntimePtr, long objectHandle, final String key, final int value); + + private native void _addObject(long v8RuntimePtr, long objectHandle, final String key, final long value); + + private native void _add(long v8RuntimePtr, long objectHandle, final String key, final boolean value); + + private native void _add(long v8RuntimePtr, long objectHandle, final String key, final double value); + + private native void _add(long v8RuntimePtr, long objectHandle, final String key, final String value); + + private native void _addUndefined(long v8RuntimePtr, long objectHandle, final String key); + + private native void _addNull(long v8RuntimePtr, long objectHandle, final String key); + + private native void _registerJavaMethod(long v8RuntimePtr, long objectHandle, final String functionName, final int methodID, final boolean voidMethod); + + private native long _initNewV8Array(long v8RuntimePtr); + + private native int _arrayGetSize(long v8RuntimePtr, long arrayHandle); + + private native int _arrayGetInteger(long v8RuntimePtr, long arrayHandle, int index); + + private native boolean _arrayGetBoolean(long v8RuntimePtr, long arrayHandle, int index); + + private native double _arrayGetDouble(long v8RuntimePtr, long arrayHandle, int index); + + private native String _arrayGetString(long v8RuntimePtr, long arrayHandle, int index); + + private native Object _arrayGet(long v8RuntimePtr, int expectedType, long arrayHandle, int index); + + private native void _addArrayIntItem(long v8RuntimePtr, long arrayHandle, int value); + + private native void _addArrayBooleanItem(long v8RuntimePtr, long arrayHandle, boolean value); + + private native void _addArrayDoubleItem(long v8RuntimePtr, long arrayHandle, double value); + + private native void _addArrayStringItem(long v8RuntimePtr, long arrayHandle, String value); + + private native void _addArrayObjectItem(long v8RuntimePtr, long arrayHandle, long value); + + private native void _addArrayUndefinedItem(long v8RuntimePtr, long arrayHandle); + + private native void _addArrayNullItem(long v8RuntimePtr, long arrayHandle); + + private native int _getType(long v8RuntimePtr, long objectHandle, final String key); + + private native int _getType(long v8RuntimePtr, long objectHandle, final int index); + + private native int _getArrayType(long v8RuntimePtr, long objectHandle); + + private native void _setPrototype(long v8RuntimePtr, long objectHandle, long prototypeHandle); + + private native int _getType(long v8RuntimePtr, long objectHandle, final int index, final int length); + + private native boolean _enableDebugSupport(long v8RuntimePtr, int port, boolean waitForConnection); + + private native void _disableDebugSupport(long v8RuntimePtr); + + private native void _processDebugMessages(long v8RuntimePtr); + + private native double[] _arrayGetDoubles(final long v8RuntimePtr, final long objectHandle, final int index, final int length); + + private native int[] _arrayGetIntegers(final long v8RuntimePtr, final long objectHandle, final int index, final int length); + + private native boolean[] _arrayGetBooleans(final long v8RuntimePtr, final long objectHandle, final int index, final int length); + + private native String[] _arrayGetStrings(final long v8RuntimePtr, final long objectHandle, final int index, final int length); + + private native int _arrayGetIntegers(final long v8RuntimePtr, final long objectHandle, final int index, final int length, int[] resultArray); + + private native int _arrayGetDoubles(final long v8RuntimePtr, final long objectHandle, final int index, final int length, double[] resultArray); + + private native int _arrayGetBooleans(final long v8RuntimePtr, final long objectHandle, final int index, final int length, boolean[] resultArray); + + private native int _arrayGetStrings(final long v8RuntimePtr, final long objectHandle, final int index, final int length, String[] resultArray); + + private static native void _setFlags(String v8flags); + + private native void _terminateExecution(final long v8RuntimePtr); + + private native long _getGlobalObject(final long v8RuntimePtr); + + private native long _getBuildID(); + + void addObjRef() { + objectReferences++; + } + + void releaseObjRef() { + objectReferences--; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.eclipsesource.v8.V8.release` indirectly reads without synchronization from `v8.V8.com.eclipsesource.v8.V8.debugThread`. Potentially races with write in method `V8.createV8Runtime(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void V8.release(boolean) + +### Procedure Id: +com.eclipsesource.v8.V8.release(boolean):void.650229571c63d62abea645d7076fb33c + +### File: +src/main/java/com/eclipsesource/v8/V8.java + +### Key: +V8.java|release|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +805455233c66744fe8534fa0b96b135f + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3742/instruction.md b/inferredbugs-3742/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..621222f028007a9f8b766cf2d719345cd607768f --- /dev/null +++ b/inferredbugs-3742/instruction.md @@ -0,0 +1,242 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** Oak +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.oath.oak; + +import org.junit.Test; + +import java.nio.ByteBuffer; +import java.util.Iterator; +import java.util.Map; + +import static junit.framework.TestCase.assertEquals; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.fail; + +public class UnsafeUtilsTest { + + + @Test + public void testUnsafeCopy() { + + IntHolder minKey = new IntHolder(0, new int[0]); + + OakMapBuilder builder = + new OakMapBuilder( + new UnsafeTestComparator(),new UnsafeTestSerializer(),new UnsafeTestSerializer()) + .setMinKey(minKey) + ; + + OakMap oak = builder.build(); + + IntHolder key1 = new IntHolder(5, new int[]{1, 2, 3, 4, 5}); + IntHolder value1 = new IntHolder(5, new int[]{1, 2, 3, 4, 5}); + + IntHolder key2 = new IntHolder(6, new int[]{10, 20, 30, 40, 50, 60}); + IntHolder value2 = new IntHolder(6, new int[]{10, 20, 30, 40, 50, 60}); + + oak.put(key1, value1); + oak.put(key2, value2); + + + IntHolder resValue1 = oak.get(key1); + assertEquals(value1.size, resValue1.size); + + for (int i = 0; i < value1.size; ++i) { + assertEquals(value1.array[i], resValue1.array[i]); + } + IntHolder resValue2 = oak.get(key2); + assertEquals(value2.size, resValue2.size); + for (int i = 0; i < value2.size; ++i) { + assertEquals(value2.array[i], resValue2.array[i]); + } + + Iterator> iter = oak.zc().entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = iter.next(); + int size = entry.getKey().getInt(0); + int[] dstArrayValue = new int[size]; + int[] dstArrayKey = new int[size]; + entry.getKey().unsafeCopyBufferToIntArray(Integer.BYTES, dstArrayKey, size); + entry.getValue().unsafeCopyBufferToIntArray(Integer.BYTES, dstArrayValue, size); + if (size == 5) { + //value1 + assertArrayEquals(value1.array, dstArrayKey); + assertArrayEquals(value1.array, dstArrayValue); + } else if (size == 6) { + //value2 + assertArrayEquals(value2.array, dstArrayKey); + assertArrayEquals(value2.array, dstArrayValue); + } else { + fail(); + } + } + + } + + + private static class IntHolder { + + private final int size; + private final int[] array; + + private IntHolder(int size, int[] array) { + this.size = size; + this.array = array; + } + + public int getSize() { + return size; + } + + public int[] getArray() { + return array; + } + } + + public static class UnsafeTestSerializer implements OakSerializer { + + @Override + public void serialize(IntHolder object, ByteBuffer targetBuffer) { + targetBuffer.putInt(targetBuffer.position(), object.size); + UnsafeUtils.unsafeCopyIntArrayToBuffer(object.array, targetBuffer, + targetBuffer.position() + Integer.BYTES, object.size); + } + + @Override + public IntHolder deserialize(ByteBuffer byteBuffer) { + int size = byteBuffer.getInt(byteBuffer.position()); + int[] array = new int[size]; + UnsafeUtils.unsafeCopyBufferToIntArray(byteBuffer, byteBuffer.position() + Integer.BYTES, array, size); + return new IntHolder(size, array); + } + + @Override + public int calculateSize(IntHolder object) { + return object.size * Integer.BYTES + Integer.BYTES; + } + } + + public static class UnsafeTestComparator implements OakComparator { + + + @Override + public int compareKeys(IntHolder key1, IntHolder key2) { + int pos = 0; + while (pos < key1.size && pos < key2.size) { + if (key1.array[pos] != key2.array[pos]) { + return key1.array[pos] - key2.array[pos]; + } + pos++; + } + return key1.size - key2.size; + } + + @Override + public int compareSerializedKeys(ByteBuffer serializedKey1, ByteBuffer serializedKey2) { + return compareKeys(new UnsafeTestSerializer().deserialize(serializedKey1), + new UnsafeTestSerializer().deserialize(serializedKey2)); + } + + @Override + public int compareKeyAndSerializedKey(IntHolder key, ByteBuffer serializedKey) { + return compareKeys(key, new UnsafeTestSerializer().deserialize(serializedKey)); + } + } + + @Test + public void testIntsToLong(){ + int i1 = 1, i2 = 2; + long combine = UnsafeUtils.intsToLong(i1, i2); + int[] res = UnsafeUtils.longToInts(combine); + assertEquals(i1, res[0]); + assertEquals(i2, res[1]); + i2 = -2; + combine = UnsafeUtils.intsToLong(i1, i2); + res = UnsafeUtils.longToInts(combine); + assertEquals(i1, res[0]); + assertEquals(i2, res[1]); + i1 = -1; + combine = UnsafeUtils.intsToLong(i1, i2); + res = UnsafeUtils.longToInts(combine); + assertEquals(i1, res[0]); + assertEquals(i2, res[1]); + i2 = 2; + combine = UnsafeUtils.intsToLong(i1, i2); + res = UnsafeUtils.longToInts(combine); + assertEquals(i1, res[0]); + assertEquals(i2, res[1]); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `resValue1` last assigned on line 39 could be null and is dereferenced at line 40. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void UnsafeUtilsTest.testUnsafeCopy() + +### Procedure Id: +com.oath.oak.UnsafeUtilsTest.testUnsafeCopy():void.8d711d2a2e7c3fdf157cab938c03fef3 + +### File: +core/src/test/java/com/oath/oak/UnsafeUtilsTest.java + +### Key: +UnsafeUtilsTest.java|testUnsafeCopy|NULL_DEREFERENCE + +### Node Key: +2797f3577e9ca5ddb3a75a7ee4ea135f + +### Hash: +03cb40fbcc95783b67a405c95c7b3520 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3745/instruction.md b/inferredbugs-3745/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5b43b540a00d794e49d2a67943a597c7f8f38bb6 --- /dev/null +++ b/inferredbugs-3745/instruction.md @@ -0,0 +1,197 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** Oak +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2018 Oath Inc. + * Licensed under the terms of the Apache 2.0 license. + * Please see LICENSE file in the project root for terms. + */ + +package com.oath.oak.NativeAllocator; + +import java.util.concurrent.ConcurrentLinkedQueue; + +/* + * The singleton Pool to pre-allocate and reuse blocks of off-heap memory. The singleton has lazy + * initialization so the big memory is allocated only on demand when first Oak is used. + * However it makes creation of the first Oak slower. This initialization is thread safe, thus + * multiple concurrent Oak creations will result only in the one Pool. + * */ +class BlocksPool implements BlocksProvider { + + private static BlocksPool instance = null; + private final ConcurrentLinkedQueue blocks = new ConcurrentLinkedQueue<>(); + + // TODO change BLOCK_SIZE and NUMBER_OF_BLOCKS to be pre-configurable + private static int BLOCK_SIZE = 256 * 1024 * 1024; // currently 200MB, the one block size + // Number of memory blocks to be pre-allocated (currently gives us 2GB). When it is not enough, + // another half such amount of memory (1GB) will be allocated at once. + private final static int NUMBER_OF_BLOCKS = 10; + private final static int EXCESS_POOL_RATIO = 3; + + // not thread safe, private constructor; should be called only once + private BlocksPool() { + prealloc(NUMBER_OF_BLOCKS); + } + + /** + * Initializes the instance of BlocksPool if not yet initialized, otherwise returns + * the single instance of the singleton. Thread safe. + */ + static BlocksPool getInstance() { + if (instance == null) { + synchronized (BlocksPool.class) { // can be easily changed to lock-free + if (instance == null) { + instance = new BlocksPool(); + } + } + } + return instance; + } + + static void setBlockSize(int blockSize) { + BLOCK_SIZE = blockSize; + synchronized (BlocksPool.class) { // can be easily changed to lock-free + instance = new BlocksPool(); + } + } + + @Override + public int blockSize() { + return BLOCK_SIZE; + } + + /** + * Returns a single Block from within the Pool, enlarges the Pool if needed + * Thread-safe + */ + public Block getBlock() { + Block b = null; + while (b == null) { + boolean noMoreBlocks = blocks.isEmpty(); + if (!noMoreBlocks) { + b = blocks.poll(); + } + + if (noMoreBlocks || b == null) { + synchronized (BlocksPool.class) { // can be easily changed to lock-free + if (blocks.isEmpty()) { + prealloc(NUMBER_OF_BLOCKS / 2); + } + } + } + } + return b; + } + + /** + * Returns a single Block to the Pool, decreases the Pool if needed + * Assumes block is not used by any concurrent thread, otherwise thread-safe + */ + public void returnBlock(Block b) { + b.reset(); + blocks.add(b); + if (blocks.size() > EXCESS_POOL_RATIO * NUMBER_OF_BLOCKS) { // too many unused blocks + synchronized (BlocksPool.class) { // can be easily changed to lock-free + for (int i = 0; i < NUMBER_OF_BLOCKS; i++) { + this.blocks.poll().clean(); + } + } + } + } + + /** + * Should be called when the entire Pool is not used anymore. Releases the memory only of the + * blocks returned back to the pool. + * However this object is GCed when the entire process dies, but thus all the memory is released + * anyway... + */ + void close() { + while (!blocks.isEmpty()) { + blocks.poll().clean(); + } + } + + private void prealloc(int numOfBlocks) { + // pre-allocation loop + for (int i = 0; i < numOfBlocks; i++) { + this.blocks.add(new Block(BlocksPool.BLOCK_SIZE)); + } + } + + // used only for testing + int numOfRemainingBlocks() { + return blocks.size(); + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.oath.oak.NativeAllocator.BlocksPool.blockSize` reads without synchronization from `NativeAllocator.BlocksPool.com.oath.oak.NativeAllocator.BlocksPool.BLOCK_SIZE`. Potentially races with write in method `BlocksPool.setBlockSize(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int BlocksPool.blockSize() + +### Procedure Id: +com.oath.oak.NativeAllocator.BlocksPool.blockSize():int.81a9bcb2d3549bb4513bc02fa095d397 + +### File: +core/src/main/java/com/oath/oak/NativeAllocator/BlocksPool.java + +### Key: +BlocksPool.java|blockSize|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +fbb13260ba54bd55619df7a4ba67e5c7 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3773/instruction.md b/inferredbugs-3773/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c172994e38e89f67edc570684f5c36848755180e --- /dev/null +++ b/inferredbugs-3773/instruction.md @@ -0,0 +1,793 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ojAlgo +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 1997-2017 Optimatika (www.optimatika.se) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.ojalgo.matrix.decomposition; + +import static org.ojalgo.constant.PrimitiveMath.*; +import static org.ojalgo.function.PrimitiveFunction.*; + +import java.math.BigDecimal; + +import org.ojalgo.RecoverableCondition; +import org.ojalgo.access.Access2D; +import org.ojalgo.access.Access2D.Collectable; +import org.ojalgo.access.Structure2D; +import org.ojalgo.array.Array1D; +import org.ojalgo.array.Primitive64Array; +import org.ojalgo.constant.PrimitiveMath; +import org.ojalgo.function.BinaryFunction; +import org.ojalgo.function.PrimitiveFunction; +import org.ojalgo.matrix.decomposition.function.ExchangeColumns; +import org.ojalgo.matrix.decomposition.function.NegateColumn; +import org.ojalgo.matrix.decomposition.function.RotateRight; +import org.ojalgo.matrix.store.BigDenseStore; +import org.ojalgo.matrix.store.ComplexDenseStore; +import org.ojalgo.matrix.store.MatrixStore; +import org.ojalgo.matrix.store.PhysicalStore; +import org.ojalgo.matrix.store.PrimitiveDenseStore; +import org.ojalgo.netio.BasicLogger; +import org.ojalgo.scalar.ComplexNumber; +import org.ojalgo.scalar.Scalar; + +abstract class SingularValueDecomposition> extends GenericDecomposition implements SingularValue { + + static final class Big extends SingularValueDecomposition { + + Big() { + super(BigDenseStore.FACTORY, new BidiagonalDecomposition.Big()); + } + + } + + static final class Complex extends SingularValueDecomposition { + + Complex() { + super(ComplexDenseStore.FACTORY, new BidiagonalDecomposition.Complex()); + } + + } + + static final class Primitive extends SingularValueDecomposition { + + Primitive() { + super(PrimitiveDenseStore.FACTORY, new BidiagonalDecomposition.Primitive()); + } + + } + + private static void doCase1(final double[] s, final double[] e, final int p, final int k, final RotateRight q2RotR) { + + double f = e[p - 2]; + e[p - 2] = ZERO; + + double tmp, cos, sin; + + for (int j = p - 2; j > k; j--) { + + tmp = HYPOT.invoke(s[j], f); + cos = s[j] / tmp; + sin = f / tmp; + s[j] = tmp; + + q2RotR.rotateRight(p - 1, j, cos, sin); + + tmp = e[j - 1]; + f = -sin * tmp; + e[j - 1] = cos * tmp; + } + + tmp = HYPOT.invoke(s[k], f); + cos = s[k] / tmp; + sin = f / tmp; + s[k] = tmp; + + q2RotR.rotateRight(p - 1, k, cos, sin); + } + + private static void doCase2(final double[] s, final double[] e, final int p, final int k, final RotateRight mtrxQ1) { + + double f = e[k - 1]; + e[k - 1] = ZERO; + + double tmp, cos, sin; + + for (int j = k; j < p; j++) { + + tmp = HYPOT.invoke(s[j], f); + cos = s[j] / tmp; + sin = f / tmp; + s[j] = tmp; + + mtrxQ1.rotateRight(k - 1, j, cos, sin); + + tmp = e[j]; + f = -sin * tmp; + e[j] = cos * tmp; + } + } + + private static void doCase3(final double[] s, final double[] e, final int p, final int k, final RotateRight q1RotR, final RotateRight q2RotR) { + + // Calculate the shift. + final double scale = MAX.invoke(MAX.invoke(MAX.invoke(MAX.invoke(ABS.invoke(s[p - 1]), ABS.invoke(s[p - 2])), ABS.invoke(e[p - 2])), ABS.invoke(s[k])), + ABS.invoke(e[k])); + + final double s_p1 = s[p - 1] / scale; + final double s_p2 = s[p - 2] / scale; + final double e_p2 = e[p - 2] / scale; + + final double s_k = s[k] / scale; + final double e_k = e[k] / scale; + + final double b = (((s_p2 + s_p1) * (s_p2 - s_p1)) + (e_p2 * e_p2)) / TWO; + final double c = (s_p1 * e_p2) * (s_p1 * e_p2); + + double shift = ZERO; + if ((Double.compare(b, ZERO) != 0) || (Double.compare(c, ZERO) != 0)) { + shift = SQRT.invoke((b * b) + c); + if (b < ZERO) { + shift = -shift; + } + shift = c / (b + shift); + } + + double f = ((s_k + s_p1) * (s_k - s_p1)) + shift; + double g = s_k * e_k; + + double tmp, cos, sin; + + // Chase zeros. + for (int j = k; j < (p - 1); j++) { + + tmp = HYPOT.invoke(f, g); + cos = f / tmp; + sin = g / tmp; + + if (j != k) { + e[j - 1] = tmp; + } + + f = (cos * s[j]) + (sin * e[j]); + e[j] = (cos * e[j]) - (sin * s[j]); + g = sin * s[j + 1]; + s[j + 1] = cos * s[j + 1]; + + q2RotR.rotateRight(j + 1, j, cos, sin); + + tmp = HYPOT.invoke(f, g); + cos = f / tmp; + sin = g / tmp; + s[j] = tmp; + + f = (cos * e[j]) + (sin * s[j + 1]); + s[j + 1] = (-sin * e[j]) + (cos * s[j + 1]); + g = sin * e[j + 1]; + e[j + 1] = cos * e[j + 1]; + + q1RotR.rotateRight(j + 1, j, cos, sin); + } + + e[p - 2] = f; + } + + private static void doCase4(final double[] s, final int k, final NegateColumn q2NegCol, final ExchangeColumns q1XchgCols, + final ExchangeColumns q2XchgCols) { + + // Make the singular values positive. + if (s[k] <= ZERO) { + s[k] = s[k] < ZERO ? -s[k] : ZERO; + q2NegCol.negateColumn(k); + } + + final int size = s.length; + double tmp; + + // Order the singular values. + for (int iter = k, next = iter + 1; (next < size) && (s[iter] < s[next]); iter++, next++) { + + tmp = s[iter]; + s[iter] = s[next]; + s[next] = tmp; + + q1XchgCols.exchangeColumns(iter, next); + q2XchgCols.exchangeColumns(iter, next); + } + } + + static void toDiagonal(final double[] s, final double[] e, final RotateRight q1RotR, final RotateRight q2RotR, final ExchangeColumns q1XchgCols, + final ExchangeColumns q2XchgCols, final NegateColumn q2NegCol) { + + int p = s.length; + while (p > 0) { + int k, kase; + + // This section of the program inspects for negligible elements in the s and e arrays. + // On completion the variables kase and k are set as follows: + // + // kase = 1 if s[p] and e[k-1] are negligible and k

    deflate negligible s[p] + // kase = 2 if s[k] is negligible and k

    split at negligible s[k] + // kase = 3 if e[k-1] is negligible, k perform QR-step + // kase = 4 if e[p-1] is negligible => convergence + + for (k = p - 2; k >= -1; k--) { + if (k == -1) { + break; + } + if (ABS.invoke(e[k]) <= (TINY + (MACHINE_EPSILON * (ABS.invoke(s[k]) + ABS.invoke(s[k + 1]))))) { + e[k] = ZERO; + break; + } + } + if (k == (p - 2)) { + kase = 4; + } else { + int ks; + for (ks = p - 1; ks >= k; ks--) { + if (ks == k) { + break; + } + final double t = (ks != p ? ABS.invoke(e[ks]) : ZERO) + (ks != (k + 1) ? ABS.invoke(e[ks - 1]) : ZERO); + if (ABS.invoke(s[ks]) <= (TINY + (MACHINE_EPSILON * t))) { + s[ks] = ZERO; + break; + } + } + if (ks == k) { + kase = 3; + } else if (ks == (p - 1)) { + kase = 1; + } else { + kase = 2; + k = ks; + } + } + k++; + + switch (kase) { // Perform the task indicated by kase. + + // s[p] and e[k-1] are negligible and k

    myBidiagonal; + + private transient MatrixStore myD = null; + private boolean myFullSize = false; + private final Structure2D myInputStructure = new Structure2D() { + + public long countColumns() { + return myTransposed ? myBidiagonal.getRowDim() : myBidiagonal.getColDim(); + } + + public long countRows() { + return myTransposed ? myBidiagonal.getColDim() : myBidiagonal.getRowDim(); + } + }; + private transient MatrixStore myInverse = null; + private transient MatrixStore myQ1 = null; + private transient MatrixStore myQ2 = null; + private transient Array1D mySingularValues = null; + private boolean myTransposed = false; + private boolean myValuesOnly = false; + private double[] s = null; + @SuppressWarnings("unused") + private SingularValueDecomposition(final DecompositionStore.Factory> factory) { + this(factory, null); + } + + protected SingularValueDecomposition(final DecompositionStore.Factory> factory, + final BidiagonalDecomposition bidiagonal) { + + super(factory); + + myBidiagonal = bidiagonal; + } + + public boolean computeValuesOnly(final Access2D.Collectable> matrix) { + return this.compute(matrix, true, false); + } + + public boolean decompose(final Access2D.Collectable> matrix) { + return this.compute(matrix, false, this.isFullSize()); + } + + public double getCondition() { + + final Array1D tmpSingularValues = this.getSingularValues(); + + return tmpSingularValues.doubleValue(0) / tmpSingularValues.doubleValue(tmpSingularValues.length - 1); + } + + public MatrixStore getD() { + + if (this.isComputed() && (myD == null)) { + myD = this.makeD(); + } + + return myD; + } + + public double getFrobeniusNorm() { + + double retVal = PrimitiveMath.ZERO; + + final Array1D tmpSingularValues = this.getSingularValues(); + double tmpVal; + + for (int i = tmpSingularValues.size() - 1; i >= 0; i--) { + tmpVal = tmpSingularValues.doubleValue(i); + retVal += tmpVal * tmpVal; + } + + return PrimitiveFunction.SQRT.invoke(retVal); + } + + public MatrixStore getInverse() { + return this.getInverse(this.preallocate(myInputStructure)); + } + + public MatrixStore getInverse(final PhysicalStore preallocated) { + + if (myInverse == null) { + + final MatrixStore tmpQ1 = this.getQ1(); + final Array1D tmpSingulars = this.getSingularValues(); + final MatrixStore tmpQ2 = this.getQ2(); + + final int rank = this.getRank(); + + final PhysicalStore tmpMtrx = tmpQ2.logical().limits(-1, rank).copy(); + + final Scalar.Factory tmpScalar = this.scalar(); + final BinaryFunction tmpDivide = this.function().divide(); + + for (int j = 0; j < rank; j++) { + tmpMtrx.modifyColumn(0L, j, tmpDivide.second(tmpScalar.cast(tmpSingulars.doubleValue(j)))); + } + + preallocated.fillByMultiplying(tmpMtrx, tmpQ1.logical().limits(-1, rank).conjugate().get()); + myInverse = preallocated; + } + + return myInverse; + } + + public double getKyFanNorm(final int k) { + + final Array1D tmpSingularValues = this.getSingularValues(); + + double retVal = PrimitiveMath.ZERO; + + for (int i = Math.min(tmpSingularValues.size(), k) - 1; i >= 0; i--) { + retVal += tmpSingularValues.doubleValue(i); + } + + return retVal; + } + + public double getOperatorNorm() { + return this.getSingularValues().doubleValue(0); + } + + public MatrixStore getQ1() { + + if (!myValuesOnly && this.isComputed() && (myQ1 == null)) { + + if (myTransposed) { + myQ1 = this.makeQ2(); + } else { + myQ1 = this.makeQ1(); + } + } + + return myQ1; + } + + public MatrixStore getQ2() { + + if (!myValuesOnly && this.isComputed() && (myQ2 == null)) { + if (myTransposed) { + myQ2 = this.makeQ1(); + } else { + myQ2 = this.makeQ2(); + } + } + + return myQ2; + } + + public int getRank() { + + final Array1D tmpSingularValues = this.getSingularValues(); + int retVal = tmpSingularValues.size(); + + // Tolerance based on min-dim but should be max-dim + final double tmpTolerance = retVal * (tmpSingularValues.doubleValue(0) * PrimitiveMath.MACHINE_EPSILON); + + for (int i = retVal - 1; i >= 0; i--) { + if (tmpSingularValues.doubleValue(i) <= tmpTolerance) { + retVal--; + } else { + return retVal; + } + } + + return retVal; + } + + public Array1D getSingularValues() { + + if ((mySingularValues == null) && this.isComputed()) { + mySingularValues = this.makeSingularValues(); + } + + return mySingularValues; + } + + public MatrixStore getSolution(final Collectable> rhs) { + return this.getInverse().multiply(this.collect(rhs)); + } + + public MatrixStore getSolution(final Collectable> rhs, final PhysicalStore preallocated) { + preallocated.fillByMultiplying(this.getInverse(), this.collect(rhs)); + return preallocated; + } + + public double getTraceNorm() { + return this.getKyFanNorm(this.getSingularValues().size()); + } + + public MatrixStore invert(final Access2D original) throws RecoverableCondition { + + this.decompose(this.wrap(original)); + + if (this.isSolvable()) { + return this.getInverse(); + } else { + throw RecoverableCondition.newMatrixNotInvertible(); + } + } + + public MatrixStore invert(final Access2D original, final PhysicalStore preallocated) throws RecoverableCondition { + + this.decompose(this.wrap(original)); + + if (this.isSolvable()) { + return this.getInverse(preallocated); + } else { + throw RecoverableCondition.newMatrixNotInvertible(); + } + } + + public boolean isFullRank() { + return this.getRank() == myBidiagonal.getMinDim(); + } + + public boolean isFullSize() { + return myFullSize; + } + + public boolean isOrdered() { + return true; + } + + public PhysicalStore preallocate(final Structure2D template) { + return this.allocate(template.countColumns(), template.countRows()); + } + + public PhysicalStore preallocate(final Structure2D templateBody, final Structure2D templateRHS) { + return this.allocate(templateRHS.countRows(), templateRHS.countColumns()); + } + + @Override + public void reset() { + + super.reset(); + + myBidiagonal.reset(); + + myD = null; + myQ1 = null; + myQ2 = null; + mySingularValues = null; + + myInverse = null; + + myValuesOnly = false; + myTransposed = false; + } + + public void setFullSize(final boolean fullSize) { + myFullSize = fullSize; + } + + public MatrixStore solve(final Access2D body, final Access2D rhs) throws RecoverableCondition { + + this.decompose(this.wrap(body)); + + if (this.isSolvable()) { + return this.getSolution(this.wrap(rhs)); + } else { + throw RecoverableCondition.newEquationSystemNotSolvable(); + } + } + + public MatrixStore solve(final Access2D body, final Access2D rhs, final PhysicalStore preallocated) throws RecoverableCondition { + + this.decompose(this.wrap(body)); + + if (this.isSolvable()) { + return this.getSolution(this.wrap(rhs), preallocated); + } else { + throw RecoverableCondition.newEquationSystemNotSolvable(); + } + } + + private MatrixStore getInverseOldVersion(final DecompositionStore preallocated) { + + if (myInverse == null) { + + final MatrixStore tmpQ1 = this.getQ1(); + final Array1D tmpSingulars = this.getSingularValues(); + final MatrixStore tmpQ2 = this.getQ2(); + + final int tmpRowDim = (int) tmpSingulars.count(); + final int tmpColDim = (int) tmpQ1.countRows(); + final PhysicalStore tmpMtrx = this.makeZero(tmpRowDim, tmpColDim); + + double tmpValue; + final int rank = this.getRank(); + for (int i = 0; i < rank; i++) { + tmpValue = tmpSingulars.doubleValue(i); + for (int j = 0; j < tmpColDim; j++) { + tmpMtrx.set(i, j, tmpQ1.toScalar(j, i).conjugate().divide(tmpValue).getNumber()); + } + } + + preallocated.fillByMultiplying(tmpQ2, tmpMtrx); + myInverse = preallocated; + } + + return myInverse; + } + + @Override + protected boolean checkSolvability() { + return this.isComputed(); + } + + protected boolean compute(final Access2D.Collectable> matrix, final boolean valuesOnly, final boolean fullSize) { + + this.reset(); + + if (matrix.countRows() >= matrix.countColumns()) { + myTransposed = false; + } else { + myTransposed = true; + } + + myValuesOnly = valuesOnly; + + boolean computeOK = false; + + try { + + computeOK = this.doCompute(myTransposed ? this.collect(matrix).conjugate() : matrix, valuesOnly, fullSize); + + } catch (final Exception xcptn) { + + BasicLogger.error(xcptn.toString()); + + this.reset(); + + computeOK = false; + } + + return this.computed(computeOK); + } + + protected boolean computeBidiagonal(final Access2D.Collectable> matrix, final boolean fullSize) { + myBidiagonal.setFullSize(fullSize); + return myBidiagonal.decompose(matrix); + } + + protected boolean doCompute(final Access2D.Collectable> matrix, final boolean valuesOnly, final boolean fullSize) { + + this.computeBidiagonal(matrix, fullSize); + + final DiagonalArray1D tmpBidiagonal = this.getBidiagonal(); + + final DecompositionStore tmpQ1 = valuesOnly ? null : this.getBidiagonalQ1(); + final DecompositionStore tmpQ2 = valuesOnly ? null : this.getBidiagonalQ2(); + + final int size = tmpBidiagonal.getDimension(); + + if ((s == null) || (s.length != size)) { + s = new double[size]; + e = new double[size]; + } + + tmpBidiagonal.mainDiagonal.supplyTo(s); + tmpBidiagonal.superdiagonal.supplyTo(e); + + final RotateRight q1RotR = tmpQ1 != null ? tmpQ1 : RotateRight.NULL; + final RotateRight q2RotR = tmpQ2 != null ? tmpQ2 : RotateRight.NULL; + final ExchangeColumns q1XchgCols = tmpQ1 != null ? tmpQ1 : ExchangeColumns.NULL; + final ExchangeColumns q2XchgCols = tmpQ2 != null ? tmpQ2 : ExchangeColumns.NULL; + final NegateColumn q2NegCol = tmpQ1 != null ? tmpQ2 : NegateColumn.NULL; + + SingularValueDecomposition.toDiagonal(s, e, q1RotR, q2RotR, q1XchgCols, q2XchgCols, q2NegCol); + + return this.computed(true); + } + + protected DiagonalArray1D getBidiagonal() { + return myBidiagonal.getDiagonal(); + } + + protected DecompositionStore getBidiagonalQ1() { + return (DecompositionStore) myBidiagonal.getQ1(); + } + + protected DecompositionStore getBidiagonalQ2() { + return (DecompositionStore) myBidiagonal.getQ2(); + } + + @Override + protected double getDimensionalEpsilon() { + return myBidiagonal.getMaxDim() * PrimitiveMath.MACHINE_EPSILON; + } + + protected boolean isTransposed() { + return myTransposed; + } + + protected MatrixStore makeD() { + return this.wrap(new DiagonalArray1D<>(this.getSingularValues(), null, null, ZERO)).get(); + } + + protected MatrixStore makeQ1() { + return this.getBidiagonalQ1(); + } + + protected MatrixStore makeQ2() { + return this.getBidiagonalQ2(); + } + + protected Array1D makeSingularValues() { + return Array1D.PRIMITIVE64.wrap(Primitive64Array.wrap(s)); + } + + void setD(final MatrixStore someD) { + myD = someD; + } + + void setSingularValues(final Array1D singularValues) { + mySingularValues = singularValues; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `tmpSingularValues` last assigned on line 451 could be null and is dereferenced at line 452. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int SingularValueDecomposition.getRank() + +### Procedure Id: +org.ojalgo.matrix.decomposition.SingularValueDecomposition.getRank():int.e02683fe8443a98e046d5e25f2a908c8 + +### File: +src/org/ojalgo/matrix/decomposition/SingularValueDecomposition.java + +### Key: +SingularValueDecomposition.java|getRank|NULL_DEREFERENCE + +### Node Key: +42f56fda1ad408e362508b93a175bb0c + +### Hash: +61d69d64f82f8d29dc41a63e0eed1e7f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3780/instruction.md b/inferredbugs-3780/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7953f0e8ac00925df27f940062e7ed52370a6810 --- /dev/null +++ b/inferredbugs-3780/instruction.md @@ -0,0 +1,1011 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ojAlgo +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 1997-2017 Optimatika (www.optimatika.se) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.ojalgo.optimisation.convex; + +import static org.ojalgo.constant.PrimitiveMath.*; +import static org.ojalgo.function.PrimitiveFunction.*; + +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import org.ojalgo.ProgrammingError; +import org.ojalgo.access.Access1D; +import org.ojalgo.access.Access2D.Collectable; +import org.ojalgo.access.IntIndex; +import org.ojalgo.access.IntRowColumn; +import org.ojalgo.array.Array1D; +import org.ojalgo.function.BinaryFunction; +import org.ojalgo.function.PrimitiveFunction; +import org.ojalgo.function.UnaryFunction; +import org.ojalgo.matrix.MatrixUtils; +import org.ojalgo.matrix.PrimitiveMatrix; +import org.ojalgo.matrix.decomposition.Cholesky; +import org.ojalgo.matrix.decomposition.Eigenvalue; +import org.ojalgo.matrix.decomposition.LU; +import org.ojalgo.matrix.store.MatrixStore; +import org.ojalgo.matrix.store.PhysicalStore; +import org.ojalgo.matrix.store.PrimitiveDenseStore; +import org.ojalgo.matrix.store.SparseStore; +import org.ojalgo.optimisation.Expression; +import org.ojalgo.optimisation.ExpressionsBasedModel; +import org.ojalgo.optimisation.GenericSolver; +import org.ojalgo.optimisation.Optimisation; +import org.ojalgo.optimisation.Variable; +import org.ojalgo.scalar.ComplexNumber; +import org.ojalgo.type.context.NumberContext; + +/** + * ConvexSolver solves optimisation problems of the form: + *

    + * min 1/2 [X]T[Q][X] - [C]T[X]
    + * when [AE][X] == [BE]
    + * and [AI][X] <= [BI] + *

    + *

    + * The matrix [Q] is assumed to be symmetric (it must be made that way) and positive (semi)definite: + *

    + *
      + *
    • If [Q] is positive semidefinite, then the objective function is convex: In this case the quadratic + * program has a global minimizer if there exists some feasible vector [X] (satisfying the constraints) and if + * the objective function is bounded below on the feasible region.
    • + *
    • If [Q] is positive definite and the problem has a feasible solution, then the global minimizer is + * unique.
    • + *
    + *

    + * The general recommendation is to construct optimisation problems using {@linkplain ExpressionsBasedModel} + * and not worry about solver details. If you do want to instantiate a convex solver directly use the + * {@linkplain ConvexSolver.Builder} class. It will return an appropriate subclass for you. + *

    + *

    + * When the KKT matrix is nonsingular, there is a unique optimal primal-dual pair (x,l). If the KKT matrix is + * singular, but the KKT system is still solvable, any solution yields an optimal pair (x,l). If the KKT + * system is not solvable, the quadratic optimization problem is unbounded below or infeasible. + *

    + * + * @author apete + */ +public abstract class ConvexSolver extends GenericSolver { + + public static final class Builder extends GenericSolver.Builder { + + private static final NumberContext NC = NumberContext.getGeneral(12); + + private MatrixStore myAE = null; + private SparseStore myAI = null; + private MatrixStore myBE = null; + private MatrixStore myBI = null; + private MatrixStore myC = null; + private MatrixStore myQ = null; + + public Builder() { + super(); + } + + public Builder(final MatrixStore C) { + + super(); + + this.objective(C); + } + + public Builder(final MatrixStore Q, final MatrixStore C) { + + super(); + + this.objective(Q, C); + } + + protected Builder(final ConvexSolver.Builder matrices) { + + super(); + + if (matrices.hasEqualityConstraints()) { + this.equalities(matrices.getAE(), matrices.getBE()); + } + + if (matrices.hasObjective()) { + if (matrices.getQ() != null) { + this.objective(matrices.getQ(), matrices.getC()); + } else { + this.objective(matrices.getC()); + } + } + + if (matrices.hasInequalityConstraints()) { + this.inequalities(matrices.getAI(), matrices.getBI()); + } + } + + Builder(final MatrixStore[] matrices) { + + super(); + + if ((matrices.length >= 2) && (matrices[0] != null) && (matrices[1] != null)) { + this.equalities(matrices[0], matrices[1]); + } + + if (matrices.length >= 4) { + if (matrices[2] != null) { + this.objective(matrices[2], matrices[3]); + } else if (matrices[3] != null) { + this.objective(matrices[3]); + } + } + + if ((matrices.length >= 6) && (matrices[4] != null) && (matrices[5] != null)) { + this.inequalities(matrices[4], matrices[5]); + } + } + + @Override + public int countConstraints() { + return this.countEqualityConstraints() + this.countInequalityConstraints(); + } + + public int countEqualityConstraints() { + return (int) ((this.getAE() != null) ? this.getAE().countRows() : 0); + } + + public int countInequalityConstraints() { + return (int) ((this.getAI() != null) ? this.getAI().countRows() : 0); + } + + @Override + public int countVariables() { + + int retVal = -1; + + if (this.getAE() != null) { + retVal = (int) this.getAE().countColumns(); + } else if (this.getAI() != null) { + retVal = (int) this.getAI().countColumns(); + } else if (this.getQ() != null) { + retVal = (int) this.getQ().countRows(); + } else if (this.getC() != null) { + retVal = (int) this.getC().countRows(); + } else { + throw new ProgrammingError("Cannot deduce the number of variables!"); + } + + return retVal; + } + + public ConvexSolver.Builder equalities(final MatrixStore AE, final MatrixStore BE) { + + if ((AE == null) || (BE == null) || (AE.countRows() != BE.countRows())) { + throw new IllegalArgumentException(); + } + + myAE = AE; + myBE = BE; + + return this; + } + + /** + * [AE][X] == [BE] + */ + public MatrixStore getAE() { + return myAE; + } + + /** + * [AI][X] <= [BI] + */ + public MatrixStore getAI() { + return myAI; + } + + /** + * [AE][X] == [BE] + */ + public MatrixStore getBE() { + return myBE; + } + + /** + * [AI][X] <= [BI] + */ + public MatrixStore getBI() { + return myBI; + } + + /** + * Linear objective: [C] + */ + public MatrixStore getC() { + return myC; + } + + /** + * Quadratic objective: [Q] + */ + public MatrixStore getQ() { + return myQ; + } + + public boolean hasEqualityConstraints() { + return (myAE != null) && (myAE.countRows() > 0); + } + + public boolean hasInequalityConstraints() { + return (myAI != null) && (myAI.countRows() > 0); + } + + public boolean hasObjective() { + return (myQ != null) || (myC != null); + } + + public ConvexSolver.Builder inequalities(final MatrixStore AI, final MatrixStore BI) { + + if ((AI == null) || (BI == null) || (AI.countRows() != BI.countRows())) { + throw new IllegalArgumentException(); + } + + if (AI instanceof SparseStore) { + + myAI = (SparseStore) AI; + + } else { + + myAI = SparseStore.PRIMITIVE.make(AI.countRows(), AI.countColumns()); + + double value; + for (int j = 0; j < AI.countColumns(); j++) { + for (int i = 0; i < AI.countRows(); i++) { + value = AI.doubleValue(i, j); + if (!NC.isZero(value)) { + myAI.set(i, j, value); + } + } + } + } + + myBI = BI; + + return this; + } + + public Builder objective(final MatrixStore C) { + + if (C == null) { + throw new IllegalArgumentException(); + } + + myC = C; + + return this; + } + + public Builder objective(final MatrixStore Q, final MatrixStore C) { + + if (Q == null) { + throw new IllegalArgumentException(); + } + + myQ = Q; + + final MatrixStore tmpC = C != null ? C : MatrixStore.PRIMITIVE.makeZero((int) Q.countRows(), 1).get(); + + myC = tmpC; + + return this; + } + + public void reset() { + myAE = null; + myAI = null; + myBE = null; + myBI = null; + myC = null; + myQ = null; + } + + @Override + public String toString() { + + final String simpleName = this.getClass().getSimpleName(); + + final StringBuilder retVal = new StringBuilder("<" + simpleName + ">"); + + retVal.append("\n[AE] = " + (myAE != null ? PrimitiveMatrix.FACTORY.copy(this.getAE()) : "?")); + + retVal.append("\n[BE] = " + (myBE != null ? PrimitiveMatrix.FACTORY.copy(this.getBE()) : "?")); + + retVal.append("\n[Q] = " + (myQ != null ? PrimitiveMatrix.FACTORY.copy(this.getQ()) : "?")); + + retVal.append("\n[C] = " + (myC != null ? PrimitiveMatrix.FACTORY.copy(this.getC()) : "?")); + + retVal.append("\n[AI] = " + (myAI != null ? PrimitiveMatrix.FACTORY.copy(this.getAI()) : "?")); + + retVal.append("\n[BI] = " + (myBI != null ? PrimitiveMatrix.FACTORY.copy(this.getBI()) : "?")); + + retVal.append("\n"); + + return retVal.toString(); + } + + public void validate() { + + if (this.hasEqualityConstraints()) { + + if (this.getAE() == null) { + throw new ProgrammingError("AE cannot be null!"); + } else if (this.getAE().countColumns() != this.countVariables()) { + throw new ProgrammingError("AE has the wrong number of columns!"); + } else if (this.getAE().countRows() != this.getBE().countRows()) { + throw new ProgrammingError("AE and BE do not have the same number of rows!"); + } else if (this.getBE().countColumns() != 1) { + throw new ProgrammingError("BE must have precisely one column!"); + } + + } else { + + myAE = null; + myBE = null; + } + + if (this.hasObjective()) { + + if ((this.getQ() != null) && ((this.getQ().countRows() != this.countVariables()) || (this.getQ().countColumns() != this.countVariables()))) { + throw new ProgrammingError("Q has the wrong number of rows and/or columns!"); + } + + if (((this.getC() != null) && (this.getC().countRows() != this.countVariables())) || (this.getC().countColumns() != 1)) { + throw new ProgrammingError("C has the wrong number of rows and/or columns!"); + } + + } else { + + myQ = null; + myC = null; + } + + if (this.hasInequalityConstraints()) { + + if (this.getAI() == null) { + throw new ProgrammingError("AI cannot be null!"); + } else if (this.getAI().countColumns() != this.countVariables()) { + throw new ProgrammingError("AI has the wrong number of columns!"); + } else if (this.getAI().countRows() != this.getBI().countRows()) { + throw new ProgrammingError("AI and BI do not have the same number of rows!"); + } else if (this.getBI().countColumns() != 1) { + throw new ProgrammingError("BI must have precisely one column!"); + } + + } else { + + myAI = null; + myBI = null; + } + } + + @Override + protected ConvexSolver doBuild(final Optimisation.Options options) { + + this.validate(); + + if (this.hasInequalityConstraints()) { + if (this.hasEqualityConstraints()) { + return new IterativeMixedASS(this, options); + } else { + return new IterativePureASS(this, options); + } + } else if (this.hasEqualityConstraints()) { + return new QPESolver(this, options); + } else { + return new UnconstrainedSolver(this, options); + } + } + + } + + public static final class ModelIntegration extends ExpressionsBasedModel.Integration { + + public ConvexSolver build(final ExpressionsBasedModel model) { + + final ConvexSolver.Builder tmpBuilder = ConvexSolver.getBuilder(); + + ConvexSolver.copy(model, tmpBuilder); + + return tmpBuilder.build(model.options); + } + + public boolean isCapable(final ExpressionsBasedModel model) { + return !model.isAnyVariableInteger() && model.isAnyExpressionQuadratic(); + } + + } + + public static void copy(final ExpressionsBasedModel sourceModel, final ConvexSolver.Builder destinationBuilder) { + + destinationBuilder.reset(); + + final List tmpFreeVariables = sourceModel.getFreeVariables(); + final Set tmpFixedVariables = sourceModel.getFixedVariables(); + final int tmpFreeVarDim = tmpFreeVariables.size(); + + // final Array1D tmpCurrentSolution = Array1D.PRIMITIVE.makeZero(tmpFreeVarDim); + // for (int i = 0; i < tmpFreeVariables.size(); i++) { + // final BigDecimal tmpValue = tmpFreeVariables.get(i).getValue(); + // if (tmpValue != null) { + // tmpCurrentSolution.set(i, tmpValue.doubleValue()); + // } + // } + // final Optimisation.Result tmpKickStarter = new Optimisation.Result(Optimisation.State.UNEXPLORED, Double.NaN, tmpCurrentSolution); + + // AE & BE + + final List tmpEqExpr = sourceModel.constraints() + .filter((final Expression c) -> c.isEqualityConstraint() && !c.isAnyQuadraticFactorNonZero()).collect(Collectors.toList()); + final int tmpEqExprDim = tmpEqExpr.size(); + + if (tmpEqExprDim > 0) { + + final SparseStore tmpAE = SparseStore.PRIMITIVE.make(tmpEqExprDim, tmpFreeVarDim); + final PhysicalStore tmpBE = PrimitiveDenseStore.FACTORY.makeZero(tmpEqExprDim, 1); + + for (int i = 0; i < tmpEqExprDim; i++) { + + final Expression tmpExpression = tmpEqExpr.get(i).compensate(tmpFixedVariables); + + for (final IntIndex tmpKey : tmpExpression.getLinearKeySet()) { + final int tmpIndex = sourceModel.indexOfFreeVariable(tmpKey.index); + if (tmpIndex >= 0) { + tmpAE.set(i, tmpIndex, tmpExpression.getAdjustedLinearFactor(tmpKey)); + } + } + tmpBE.set(i, 0, tmpExpression.getAdjustedUpperLimit()); + } + + destinationBuilder.equalities(tmpAE, tmpBE); + } + + // Q & C + + final Expression tmpObjExpr = sourceModel.objective().compensate(tmpFixedVariables); + + PhysicalStore tmpQ = null; + if (tmpObjExpr.isAnyQuadraticFactorNonZero()) { + tmpQ = PrimitiveDenseStore.FACTORY.makeZero(tmpFreeVarDim, tmpFreeVarDim); + + final BinaryFunction tmpBaseFunc = sourceModel.isMaximisation() ? SUBTRACT : ADD; + UnaryFunction tmpModifier; + for (final IntRowColumn tmpKey : tmpObjExpr.getQuadraticKeySet()) { + final int tmpRow = sourceModel.indexOfFreeVariable(tmpKey.row); + final int tmpColumn = sourceModel.indexOfFreeVariable(tmpKey.column); + if ((tmpRow >= 0) && (tmpColumn >= 0)) { + tmpModifier = tmpBaseFunc.second(tmpObjExpr.getAdjustedQuadraticFactor(tmpKey)); + tmpQ.modifyOne(tmpRow, tmpColumn, tmpModifier); + tmpQ.modifyOne(tmpColumn, tmpRow, tmpModifier); + } + } + } + + PhysicalStore tmpC = null; + if (tmpObjExpr.isAnyLinearFactorNonZero()) { + tmpC = PrimitiveDenseStore.FACTORY.makeZero(tmpFreeVarDim, 1); + if (sourceModel.isMinimisation()) { + for (final IntIndex tmpKey : tmpObjExpr.getLinearKeySet()) { + final int tmpIndex = sourceModel.indexOfFreeVariable(tmpKey.index); + if (tmpIndex >= 0) { + tmpC.set(tmpIndex, 0, -tmpObjExpr.getAdjustedLinearFactor(tmpKey)); + } + } + } else { + for (final IntIndex tmpKey : tmpObjExpr.getLinearKeySet()) { + final int tmpIndex = sourceModel.indexOfFreeVariable(tmpKey.index); + if (tmpIndex >= 0) { + tmpC.set(tmpIndex, 0, tmpObjExpr.getAdjustedLinearFactor(tmpKey)); + } + } + } + } + + destinationBuilder.objective(tmpQ, tmpC); + + // AI & BI + + final List tmpUpExpr = sourceModel.constraints() + .filter((final Expression c2) -> c2.isUpperConstraint() && !c2.isAnyQuadraticFactorNonZero()).collect(Collectors.toList()); + final int tmpUpExprDim = tmpUpExpr.size(); + final List tmpUpVar = sourceModel.bounds().filter((final Variable c4) -> c4.isUpperConstraint()).collect(Collectors.toList()); + final int tmpUpVarDim = tmpUpVar.size(); + + final List tmpLoExpr = sourceModel.constraints() + .filter((final Expression c1) -> c1.isLowerConstraint() && !c1.isAnyQuadraticFactorNonZero()).collect(Collectors.toList()); + final int tmpLoExprDim = tmpLoExpr.size(); + final List tmpLoVar = sourceModel.bounds().filter((final Variable c3) -> c3.isLowerConstraint()).collect(Collectors.toList()); + final int tmpLoVarDim = tmpLoVar.size(); + + if ((tmpUpExprDim + tmpUpVarDim + tmpLoExprDim + tmpLoVarDim) > 0) { + + final SparseStore tmpAI = SparseStore.PRIMITIVE.make(tmpUpExprDim + tmpUpVarDim + tmpLoExprDim + tmpLoVarDim, tmpFreeVarDim); + final PhysicalStore tmpBI = PrimitiveDenseStore.FACTORY.makeZero(tmpUpExprDim + tmpUpVarDim + tmpLoExprDim + tmpLoVarDim, 1); + + if (tmpUpExprDim > 0) { + for (int i = 0; i < tmpUpExprDim; i++) { + final Expression tmpExpression = tmpUpExpr.get(i).compensate(tmpFixedVariables); + for (final IntIndex tmpKey : tmpExpression.getLinearKeySet()) { + final int tmpIndex = sourceModel.indexOfFreeVariable(tmpKey.index); + if (tmpIndex >= 0) { + tmpAI.set(i, tmpIndex, tmpExpression.getAdjustedLinearFactor(tmpKey)); + } + } + tmpBI.set(i, 0, tmpExpression.getAdjustedUpperLimit()); + } + } + + if (tmpUpVarDim > 0) { + for (int i = 0; i < tmpUpVarDim; i++) { + final Variable tmpVariable = tmpUpVar.get(i); + tmpAI.set(tmpUpExprDim + i, sourceModel.indexOfFreeVariable(tmpVariable), tmpVariable.getAdjustmentFactor()); + tmpBI.set(tmpUpExprDim + i, 0, tmpVariable.getAdjustedUpperLimit()); + } + } + + if (tmpLoExprDim > 0) { + for (int i = 0; i < tmpLoExprDim; i++) { + final Expression tmpExpression = tmpLoExpr.get(i).compensate(tmpFixedVariables); + for (final IntIndex tmpKey : tmpExpression.getLinearKeySet()) { + final int tmpIndex = sourceModel.indexOfFreeVariable(tmpKey.index); + if (tmpIndex >= 0) { + tmpAI.set(tmpUpExprDim + tmpUpVarDim + i, tmpIndex, -tmpExpression.getAdjustedLinearFactor(tmpKey)); + } + } + tmpBI.set(tmpUpExprDim + tmpUpVarDim + i, 0, -tmpExpression.getAdjustedLowerLimit()); + } + } + + if (tmpLoVarDim > 0) { + for (int i = 0; i < tmpLoVarDim; i++) { + final Variable tmpVariable = tmpLoVar.get(i); + tmpAI.set(tmpUpExprDim + tmpUpVarDim + tmpLoExprDim + i, sourceModel.indexOfFreeVariable(tmpVariable), -tmpVariable.getAdjustmentFactor()); + tmpBI.set(tmpUpExprDim + tmpUpVarDim + tmpLoExprDim + i, 0, -tmpVariable.getAdjustedLowerLimit()); + } + } + + destinationBuilder.inequalities(tmpAI, tmpBI); + } + } + + public static Builder getBuilder() { + return new Builder(); + } + + public static Builder getBuilder(final MatrixStore Q, final MatrixStore C) { + return ConvexSolver.getBuilder().objective(Q, C); + } + + private final ConvexSolver.Builder myMatrices; + + private final LU mySolverGeneral; + + private final Cholesky mySolverQ; + + private PrimitiveDenseStore myX = null; + + @SuppressWarnings("unused") + private ConvexSolver(final Options solverOptions) { + this(null, solverOptions); + } + + protected ConvexSolver(final ConvexSolver.Builder matrices, final Optimisation.Options solverOptions) { + + super(solverOptions); + + myMatrices = matrices; + + final MatrixStore tmpQ = this.getQ(); + + mySolverQ = Cholesky.make(tmpQ); + mySolverGeneral = LU.make(tmpQ); + } + + public void dispose() { + + super.dispose(); + + myMatrices.reset(); + } + + public final Optimisation.Result solve(final Optimisation.Result kickStarter) { + + boolean tmpContinue = true; + + if (options.validate) { + tmpContinue = this.validate(); + } + + if (tmpContinue) { + tmpContinue = this.initialise(kickStarter); + } + + if (tmpContinue) { + + this.resetIterationsCount(); + + do { + + this.performIteration(); + + this.incrementIterationsCount(); + + } while (!this.getState().isFailure() && this.needsAnotherIteration() && this.isIterationAllowed()); + } + + return this.buildResult(); + } + + @Override + public String toString() { + return myMatrices.toString(); + } + + protected boolean computeGeneral(final Collectable> matrix) { + return mySolverGeneral.compute(matrix); + } + + protected boolean computeQ(final Collectable> matrix) { + return mySolverQ.compute(matrix); + } + + protected int countEqualityConstraints() { + return myMatrices.countEqualityConstraints(); + } + + protected int countInequalityConstraints() { + return myMatrices.countInequalityConstraints(); + } + + protected int countVariables() { + return myMatrices.countVariables(); + } + + @Override + protected double evaluateFunction(final Access1D solution) { + + final MatrixStore tmpX = this.getX(); + + return tmpX.transpose().multiply(this.getQ().multiply(tmpX)).multiply(0.5).subtract(tmpX.transpose().multiply(this.getC())).doubleValue(0L); + } + + @Override + protected MatrixStore extractSolution() { + + return this.getX().copy(); + + } + + protected void fillX(final Access1D solution) { + final int tmpLimit = this.countVariables(); + for (int i = 0; i < tmpLimit; i++) { + this.setX(i, solution.doubleValue(i)); + } + } + + protected void fillX(final double value) { + final int tmpLimit = this.countVariables(); + for (int i = 0; i < tmpLimit; i++) { + this.setX(i, value); + } + } + + protected MatrixStore getAE() { + return myMatrices.getAE(); + } + + protected MatrixStore getAEX() { + + MatrixStore retVal = null; + + final MatrixStore tmpAE = this.getAE(); + final PhysicalStore tmpX = this.getX(); + + if ((tmpAE != null) && (tmpX != null)) { + retVal = tmpAE.multiply(tmpX); + } + return retVal; + } + + protected MatrixStore getAI() { + return myMatrices.getAI(); + } + + protected MatrixStore getAIX(final int[] selector) { + + final MatrixStore tmpAI = this.getAI(); + final PhysicalStore tmpX = this.getX(); + + if ((tmpAI != null) && (tmpX != null)) { + return tmpAI.logical().row(selector).get().multiply(tmpX); + } else { + return null; + } + } + + protected MatrixStore getBE() { + return myMatrices.getBE(); + } + + protected MatrixStore getBI() { + return myMatrices.getBI(); + } + + protected MatrixStore getBI(final int[] selector) { + return myMatrices.getBI().logical().row(selector).get(); + } + + protected MatrixStore getC() { + return myMatrices.getC(); + } + + protected abstract MatrixStore getIterationKKT(); + + protected abstract MatrixStore getIterationRHS(); + + protected MatrixStore getQ() { + return myMatrices.getQ(); + } + + protected int getRankGeneral() { + return mySolverGeneral.getRank(); + } + + protected PhysicalStore getSE() { + + PhysicalStore retVal = null; + + final MatrixStore mtrxAE = this.getAE(); + final MatrixStore mtrxBE = this.getBE(); + final PhysicalStore mtrxX = this.getX(); + + if ((mtrxAE != null) && (mtrxBE != null)) { + + retVal = mtrxBE.copy(); + + retVal.modifyMatching(PrimitiveFunction.SUBTRACT, mtrxAE.multiply(mtrxX)); + } + + return retVal; + } + + protected PhysicalStore getSI() { + + PhysicalStore retVal = null; + + final MatrixStore mtrxAI = this.getAI(); + final MatrixStore mtrxBI = this.getBI(); + final PhysicalStore mtrxX = this.getX(); + + if ((mtrxAI != null) && (mtrxBI != null)) { + + retVal = mtrxBI.copy(); + + retVal.modifyMatching(PrimitiveFunction.SUBTRACT, mtrxAI.multiply(mtrxX)); + } + + return retVal; + } + + protected MatrixStore getSI(final int... selector) { + + PhysicalStore retVal = null; + + final MatrixStore mtrxAI = this.getAI(); + final MatrixStore mtrxBI = this.getBI(); + final PhysicalStore mtrxX = this.getX(); + + if ((mtrxAI != null) && (mtrxBI != null)) { + + final MatrixStore selectedAI = mtrxAI.logical().row(selector).get(); + final MatrixStore selectedBI = mtrxBI.logical().row(selector).get(); + + retVal = selectedBI.copy(); + + retVal.modifyMatching(PrimitiveFunction.SUBTRACT, selectedAI.multiply(mtrxX)); + } + + return retVal; + } + + protected MatrixStore getSolutionGeneral(final Collectable> rhs) { + return mySolverGeneral.getSolution(rhs); + } + + protected MatrixStore getSolutionGeneral(final Collectable> rhs, final PhysicalStore preallocated) { + return mySolverGeneral.getSolution(rhs, preallocated); + } + + protected MatrixStore getSolutionQ(final Collectable> rhs) { + return mySolverQ.getSolution(rhs); + } + + protected MatrixStore getSolutionQ(final Collectable> rhs, final PhysicalStore preallocated) { + return mySolverQ.getSolution(rhs, preallocated); + } + + /** + * Solution / Variables: [X] + */ + protected PhysicalStore getX() { + if (myX == null) { + myX = PrimitiveDenseStore.FACTORY.makeZero(this.countVariables(), 1); + } + return myX; + } + + protected boolean hasEqualityConstraints() { + return myMatrices.hasEqualityConstraints(); + } + + protected boolean hasInequalityConstraints() { + return myMatrices.hasInequalityConstraints(); + } + + protected boolean hasObjective() { + return myMatrices.hasObjective(); + } + + protected boolean isSolvableGeneral() { + return mySolverGeneral.isSolvable(); + } + + protected boolean isSolvableQ() { + return mySolverQ.isSolvable(); + } + + protected boolean isX() { + return myX != null; + } + + abstract protected void performIteration(); + + protected void resetX() { + if (myX != null) { + myX.fillAll(ZERO); + } + } + + protected void setX(final int index, final double value) { + this.getX().set(index, 0, value); + } + + @Override + protected boolean validate() { + + final MatrixStore tmpQ = this.getQ(); + final MatrixStore tmpC = this.getC(); + + if ((tmpQ == null) || (tmpC == null)) { + throw new IllegalArgumentException("Neither Q nor C may be null!"); + } + + if (!MatrixUtils.isHermitian(tmpQ)) { + if (this.isDebug()) { + this.debug("Q not symmetric!", tmpQ); + } + throw new IllegalArgumentException("Q must be symmetric!"); + } + + if (!mySolverQ.isSPD()) { + // Not symmetric positive definite. Check if at least positive semidefinite. + + final Eigenvalue tmpEvD = Eigenvalue.PRIMITIVE.make(true); + + tmpEvD.computeValuesOnly(tmpQ); + + final Array1D tmpEigenvalues = tmpEvD.getEigenvalues(); + + tmpEvD.reset(); + + for (final ComplexNumber tmpValue : tmpEigenvalues) { + if ((tmpValue.doubleValue() < ZERO) || !tmpValue.isReal()) { + if (this.isDebug()) { + this.debug("Q not positive semidefinite!"); + this.debug("The eigenvalues are: {}", tmpEigenvalues); + } + throw new IllegalArgumentException("Q must be positive semidefinite!"); + } + } + } + + this.setState(State.VALID); + return true; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getQ()` could be null and is dereferenced at line 690. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +double ConvexSolver.evaluateFunction(Access1D) + +### Procedure Id: +org.ojalgo.optimisation.convex.ConvexSolver.evaluateFunction(org.ojalgo.access.Access1D):double.808e67877eae2f57d2065de69f6fc1eb + +### File: +src/org/ojalgo/optimisation/convex/ConvexSolver.java + +### Key: +ConvexSolver.java|evaluateFunction|NULL_DEREFERENCE + +### Node Key: +e3c557d7766c6aa2f820227d95f6c155 + +### Hash: +b3219713a9c96e455914c39ddfc4155b + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3787/instruction.md b/inferredbugs-3787/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eafc70e8bb453fe9709412c3d4b8d94911d41a31 --- /dev/null +++ b/inferredbugs-3787/instruction.md @@ -0,0 +1,426 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ojAlgo +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.ojalgo.array; + +import java.util.AbstractSet; +import java.util.Comparator; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.SortedMap; + +import org.ojalgo.ProgrammingError; +import org.ojalgo.access.Access1D; +import org.ojalgo.access.Mutate1D; +import org.ojalgo.array.DenseArray.Factory; +import org.ojalgo.array.SparseArray.NonzeroView; +import org.ojalgo.constant.PrimitiveMath; +import org.ojalgo.function.BinaryFunction; +import org.ojalgo.type.context.NumberContext; + +public final class LongToNumberMap implements SortedMap, Access1D, Mutate1D.Mixable { + + public static final class MapFactory extends StrategyBuilder, MapFactory> { + + MapFactory(final Factory denseFactory) { + super(denseFactory); + } + + @Override + public LongToNumberMap make() { + return new LongToNumberMap<>(this.getStrategy()); + } + + } + + public static MapFactory factory(final DenseArray.Factory denseFactory) { + return new MapFactory<>(denseFactory); + } + + private final SparseArray myStorage; + private final DenseCapacityStrategy myStrategy; + + LongToNumberMap(final DenseCapacityStrategy strategy) { + + super(); + + myStrategy = strategy; + + myStorage = new SparseArray<>(Long.MAX_VALUE, strategy); + } + + /** + * The current capacity of the underlying data structure. The capacity is always greater than or equal to + * the current number of entries in the map. When you add entries to the map the capacity may have to + * grow. + */ + public long capacity() { + return myStorage.capacity(); + } + + public void clear() { + myStorage.reset(); + } + + public Comparator comparator() { + return null; + } + + public boolean containsKey(final long key) { + return myStorage.index(key) >= 0; + } + + public boolean containsKey(final Object key) { + if (key instanceof Number) { + return this.containsKey(((Number) key).longValue()); + } else { + return false; + } + } + + public boolean containsValue(final double value) { + for (final NonzeroView tmpView : myStorage.nonzeros()) { + // if (tmpView.doubleValue() == value) { + if (NumberContext.compare(tmpView.doubleValue(), value) == 0) { + return true; + } + } + return false; + } + + public boolean containsValue(final Object value) { + for (final NonzeroView tmpView : myStorage.nonzeros()) { + if (value.equals(tmpView.getNumber())) { + return true; + } + } + return false; + } + + public long count() { + return myStorage.getActualLength(); + } + + public double doubleValue(final long key) { + final int tmpIndex = myStorage.index(key); + if (tmpIndex >= 0) { + return myStorage.doubleValueInternally(tmpIndex); + } else { + return PrimitiveMath.NaN; + } + } + + public Set> entrySet() { + return new AbstractSet>() { + + @Override + public Iterator> iterator() { + return new Iterator>() { + + NonzeroView tmpNonzeros = myStorage.nonzeros(); + + public boolean hasNext() { + return tmpNonzeros.hasNext(); + } + + public Map.Entry next() { + + tmpNonzeros.next(); + + return new Map.Entry() { + + public Long getKey() { + return tmpNonzeros.index(); + } + + public N getValue() { + return tmpNonzeros.getNumber(); + } + + public N setValue(final N value) { + ProgrammingError.throwForUnsupportedOptionalOperation(); + return null; + } + + }; + } + + }; + } + + @Override + public int size() { + return myStorage.getActualLength(); + } + }; + } + + public Long firstKey() { + return myStorage.firstIndex(); + } + + public N get(final long key) { + final int tmpIndex = myStorage.index(key); + if (tmpIndex >= 0) { + return myStorage.getInternally(tmpIndex); + } else { + return null; + } + } + + public N get(final Object key) { + return key instanceof Number ? this.get(((Number) key).longValue()) : null; + } + + public LongToNumberMap headMap(final long toKey) { + return this.subMap(myStorage.firstIndex(), toKey); + } + + public LongToNumberMap headMap(final Long toKey) { + return this.headMap(toKey.longValue()); + } + + public boolean isEmpty() { + return myStorage.getActualLength() == 0; + } + + public Set keySet() { + return new AbstractSet() { + + @Override + public Iterator iterator() { + return myStorage.indices().iterator(); + } + + @Override + public int size() { + return myStorage.getActualLength(); + } + + }; + } + + public Long lastKey() { + return myStorage.lastIndex(); + } + + public double mix(final long key, final BinaryFunction mixer, final double addend) { + ProgrammingError.throwIfNull(mixer); + synchronized (myStorage) { + final int tmpIndex = myStorage.index(key); + final double oldValue = tmpIndex >= 0 ? myStorage.doubleValueInternally(tmpIndex) : PrimitiveMath.NaN; + final double newValue = tmpIndex >= 0 ? mixer.invoke(oldValue, addend) : addend; + myStorage.doSet(key, tmpIndex, newValue, true); + return newValue; + } + } + + public N mix(final long key, final BinaryFunction mixer, final N addend) { + ProgrammingError.throwIfNull(mixer); + synchronized (myStorage) { + final int tmpIndex = myStorage.index(key); + final N oldValue = tmpIndex >= 0 ? myStorage.getInternally(tmpIndex) : null; + final N newValue = tmpIndex >= 0 ? mixer.invoke(oldValue, addend) : addend; + myStorage.doSet(key, tmpIndex, newValue, true); + return newValue; + } + } + + public double put(final long key, final double value) { + final int tmpIndex = myStorage.index(key); + final double tmpOldValue = tmpIndex >= 0 ? myStorage.doubleValueInternally(tmpIndex) : PrimitiveMath.NaN; + myStorage.doSet(key, tmpIndex, value, true); + return tmpOldValue; + } + + public N put(final long key, final N value) { + final int tmpIndex = myStorage.index(key); + final N tmpOldValue = tmpIndex >= 0 ? myStorage.getInternally(tmpIndex) : null; + myStorage.doSet(key, tmpIndex, value, true); + return tmpOldValue; + } + + public N put(final Long key, final N value) { + return this.put(key.longValue(), value); + } + + public void putAll(final LongToNumberMap m) { + if (myStorage.isPrimitive()) { + for (final NonzeroView tmpView : m.getStorage().nonzeros()) { + myStorage.set(tmpView.index(), tmpView.doubleValue()); + } + } else { + for (final NonzeroView tmpView : m.getStorage().nonzeros()) { + myStorage.set(tmpView.index(), tmpView.getNumber()); + } + } + } + + public void putAll(final Map m) { + for (final java.util.Map.Entry tmpEntry : m.entrySet()) { + myStorage.set(tmpEntry.getKey(), tmpEntry.getValue()); + } + } + + public N remove(final long key) { + final N tmpOldVal = myStorage.get(key); + myStorage.set(key, 0.0); + return tmpOldVal; + } + + public N remove(final Object key) { + if (key instanceof Number) { + return this.remove(((Number) key).longValue()); + } else { + return null; + } + } + + public int size() { + return myStorage.getActualLength(); + } + + public LongToNumberMap subMap(final long fromKey, final long toKey) { + + final LongToNumberMap retVal = new LongToNumberMap<>(myStrategy); + + long tmpKey; + for (final NonzeroView tmpView : myStorage.nonzeros()) { + tmpKey = tmpView.index(); + if ((fromKey <= tmpKey) && (tmpKey < toKey)) { + final N tmpValue = tmpView.getNumber(); + retVal.put(tmpKey, tmpValue); + } + } + + return retVal; + } + + public LongToNumberMap subMap(final Long fromKey, final Long toKey) { + return this.subMap(fromKey.longValue(), toKey.longValue()); + } + + public LongToNumberMap tailMap(final long fromKey) { + return this.subMap(fromKey, myStorage.lastIndex() + 1L); + } + + public LongToNumberMap tailMap(final Long fromKey) { + return this.tailMap(fromKey.longValue()); + } + + @Override + public String toString() { + + NonzeroView nz = myStorage.nonzeros(); + + if (!nz.hasNext()) { + return "{}"; + } + + StringBuilder builder = new StringBuilder(); + builder.append('{'); + for (;;) { + NonzeroView entry = nz.next(); + long key = entry.index(); + N value = entry.getNumber(); + builder.append(key); + builder.append('='); + builder.append(value); + if (!nz.hasNext()) { + return builder.append('}').toString(); + } + builder.append(',').append(' '); + } + } + + public NumberList values() { + return new NumberList<>(myStorage.getValues(), myStrategy, myStorage.getActualLength()); + } + + /** + * Should return the same elements/values as first calling {@link #subMap(Long, Long)} and then + * {@link #values()} but this method does not create any copies. Any change in the underlying data + * structure (this map) will corrupt this method's output. + */ + public Access1D values(final long fromKey, final long toKey) { + return myStorage.getValues(fromKey, toKey); + } + + SparseArray getStorage() { + return myStorage; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.ojalgo.array.LongToNumberMap.remove` indirectly writes to field `this.org.ojalgo.array.LongToNumberMap.myStorage.org.ojalgo.array.SparseArray.myValues` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Number LongToNumberMap.remove(long) + +### Procedure Id: +org.ojalgo.array.LongToNumberMap.remove(long):java.lang.Number.27b34bbd8e48a08c7d589d3fb8418f0b + +### File: +src/org/ojalgo/array/LongToNumberMap.java + +### Key: +LongToNumberMap.java|remove|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +393d710a959e2f6eec42f0fd2380fb8f + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3789/instruction.md b/inferredbugs-3789/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3e513302f391dec4da6001d7db7d104bb8eda060 --- /dev/null +++ b/inferredbugs-3789/instruction.md @@ -0,0 +1,188 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ojAlgo +**Bug ID:** 14 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +import org.ojalgo.TestUtils; +import org.ojalgo.array.Array1D; +import org.ojalgo.array.Primitive32Array; +import org.ojalgo.function.PrimitiveFunction; +import org.ojalgo.function.aggregator.Aggregator; +import org.ojalgo.matrix.MatrixUtils; +import org.ojalgo.matrix.decomposition.Eigenvalue; +import org.ojalgo.matrix.store.MatrixStore; +import org.ojalgo.matrix.store.PhysicalStore; +import org.ojalgo.matrix.store.PrimitiveDenseStore; +import org.ojalgo.random.SampleSet; +import org.ojalgo.random.Uniform; +import org.ojalgo.scalar.ComplexNumber; + +/* + * Copyright 1997-2018 Optimatika + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +public class CodeSnippets { + + public static void main(final String[] args) { + + final Array1D doubles = Array1D.factory(Primitive32Array.FACTORY).makeFilled(10, new Uniform()); + System.out.println(doubles.toString()); + + final Array1D rollingMedian = Array1D.PRIMITIVE32.makeZero(doubles.size()); + + rollingMedian.set(0, doubles.get(0)); + System.out.printf("%1$s -> %1$s\n", doubles.get(0)); + + final Array1D someSamples2 = doubles.subList(0, 2); + final double mean2 = SampleSet.wrap(someSamples2).getMean(); + rollingMedian.set(1, mean2); + System.out.printf("%s -> %s\n", someSamples2.toString(), mean2); + + for (int i = 2; i < doubles.length; i++) { + final Array1D someSamples = doubles.subList(i - 2, i + 1); + final double mean = SampleSet.wrap(someSamples).getMean(); + rollingMedian.set(i, mean); + System.out.printf("%s -> %s\n", someSamples.toString(), mean2); + } + + System.out.println(rollingMedian.toString()); + + for (int i = 0; i < doubles.length; i++) { + final int first = Math.max(0, i - 2); + final int limit = i + 1; + final double mean = doubles.aggregateRange(first, limit, Aggregator.AVERAGE); + rollingMedian.set(i, mean); + } + + System.out.println(rollingMedian.toString()); + + final SampleSet samples = SampleSet.make(); + for (int i = 0; i < doubles.length; i++) { + final int first = Math.max(0, i - 2); + final int limit = i + 1; + samples.swap(doubles.sliceRange(first, limit)); + final double mean = samples.getMean(); + rollingMedian.set(i, mean); + } + + System.out.println(rollingMedian.toString()); + + final PrimitiveDenseStore org = MatrixUtils.makeSPD(10); + + final Eigenvalue evd = Eigenvalue.PRIMITIVE.make(true); + evd.decompose(org); + + final MatrixStore expSquared = org.multiply(org); + + final MatrixStore v = evd.getV(); + final MatrixStore d = evd.getD().logical().diagonal(false).get(); + final Array1D values = evd.getEigenvalues(); + + final MatrixStore ident = v.multiply(v.conjugate()); + + final MatrixStore actSquared = v.multiply(d).multiply(d).multiply(v.conjugate()); + + TestUtils.assertEquals(expSquared, actSquared); + + final PhysicalStore copied = v.copy(); + copied.loopRow(0, (r, c) -> copied.modifyColumn(c, PrimitiveFunction.MULTIPLY.second(values.doubleValue(c) * values.doubleValue(c)))); + final MatrixStore actSquared2 = copied.multiply(v.conjugate()); + + TestUtils.assertEquals(expSquared, actSquared2); + + final MatrixStore matrix = null; + + matrix.logical().limits(3, 3).offsets(1, 1).get(); + + matrix.logical().offsets(1, 1).get(); + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `matrix` last assigned on line 106 could be null and is dereferenced at line 108. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CodeSnippets.main(java.lang.String[]) + +### Procedure Id: +CodeSnippets.main(java.lang.String[]):void.dc6015cddebe782bd2b531d66245b2e8 + +### File: +test/CodeSnippets.java + +### Key: +CodeSnippets.java|main|NULL_DEREFERENCE + +### Node Key: +eae2ee1cdadb82e549c2a1b7c9bd0e3a + +### Hash: +2e95d7ab1771dd590dee9722ff4db6ee + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3800/instruction.md b/inferredbugs-3800/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..31f110ea3144b84fe91585046108b0b35938984a --- /dev/null +++ b/inferredbugs-3800/instruction.md @@ -0,0 +1,226 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** acs-aem-commons +**Bug ID:** 15 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * #%L + * ACS AEM Commons Bundle + * %% + * Copyright (C) 2013 Adobe + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ +package com.adobe.acs.commons.forms.helpers.impl; + +import com.adobe.acs.commons.forms.Form; +import com.adobe.acs.commons.forms.helpers.FormHelper; +import com.adobe.acs.commons.forms.helpers.PostRedirectGetWithCookiesFormHelper; +import com.adobe.acs.commons.util.CookieUtil; +import com.day.cq.wcm.api.Page; +import org.apache.commons.lang.StringUtils; +import org.apache.felix.scr.annotations.Component; +import org.apache.felix.scr.annotations.Property; +import org.apache.felix.scr.annotations.Service; +import org.apache.sling.api.SlingHttpServletRequest; +import org.apache.sling.api.SlingHttpServletResponse; +import org.apache.sling.api.resource.Resource; +import org.apache.sling.commons.json.JSONException; +import org.osgi.framework.Constants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.http.Cookie; +import java.io.IOException; + +/** + * ACS AEM Commons - Forms - POST-Redirect-GET-With-Cookies Form Helper + * + */ +@Component(inherit = true) +@Property(label = "Service Ranking", + name = Constants.SERVICE_RANKING, + intValue = FormHelper.SERVICE_RANKING_POST_REDIRECT_WITH_COOKIES_GET) +@Service(value = { FormHelper.class, PostRedirectGetWithCookiesFormHelper.class }) +public class PostRedirectGetWithCookiesFormHelperImpl extends PostRedirectGetFormHelperImpl implements PostRedirectGetWithCookiesFormHelper { + private static final Logger log = LoggerFactory.getLogger(PostRedirectGetWithCookiesFormHelperImpl.class); + + public static final int COOKIE_MAX_AGE = 10 * 60; + public static final String ROOT_COOKIE_PATH = "/"; + + @Override + public final void sendRedirect(Form form, String path, String formSelector, SlingHttpServletResponse response) + throws IOException, JSONException { + final String url = this.getRedirectPath(form, path, formSelector); + addFlashCookie(response, form); + response.sendRedirect(url); + } + + @Override + public final void sendRedirect(Form form, Page page, String formSelector, SlingHttpServletResponse response) + throws IOException, JSONException { + final String url = this.getRedirectPath(form, page, formSelector); + addFlashCookie(response, form); + response.sendRedirect(url); + } + + @Override + public final void sendRedirect(Form form, Resource resource, String formSelector, + SlingHttpServletResponse response) throws IOException, JSONException { + final String url = this.getRedirectPath(form, resource, formSelector); + addFlashCookie(response, form); + response.sendRedirect(url); + } + + @Override + protected final boolean doHandleGet(final String formName, final SlingHttpServletRequest request) { + //noinspection SimplifiableIfStatement + if (StringUtils.equalsIgnoreCase("GET", request.getMethod())) { + return (CookieUtil.getCookie(request, this.getGetLookupKey(formName)) != null); + } else { + return false; + } + } + + @Override + protected String getRawFormData(final String formName, final SlingHttpServletRequest request, + final SlingHttpServletResponse response) { + final String cookieName = getGetLookupKey(formName); + final Cookie cookie = CookieUtil.getCookie(request, cookieName); + + if (response != null && cookie != null) { + CookieUtil.dropCookies(request, response, ROOT_COOKIE_PATH, cookieName); + } else { + log.warn("SlingHttpServletResponse required for removing cookie. Please use formHelper.getForm({}, slingRequest, slingResponse);", formName); + } + // Get the QP lookup for this form + return this.decode(cookie.getValue()); + } + + @Override + protected final String getRedirectPath(final Form form, final String path, final String formSelector) throws + JSONException { + String redirectPath = path; + redirectPath += this.getSuffix(); + if (StringUtils.isNotBlank(formSelector)) { + redirectPath += "/" + formSelector; + } + return redirectPath; + } + + /** + * Encodes URL data, escaping characters such as "+" and "=" + * + * @param unencoded + * @return + */ + @Override + protected final String encode(String unencoded) { + return StringUtils.isBlank(unencoded) ? "" : org.apache.sling.commons.json.http.Cookie.escape(unencoded); + } + + /** + * Decodes URL data. + * + * @param encoded + * @return + */ + @Override + protected final String decode(String encoded) { + return StringUtils.isBlank(encoded) ? "" : org.apache.sling.commons.json.http.Cookie.unescape(encoded); + } + + /** + * Adds a cookie containing the serialised contents of the form to a cookie named after the GET lookup key + * @param response + * @param form + * @throws JSONException + */ + protected void addFlashCookie(SlingHttpServletResponse response, Form form) throws JSONException { + final String name = this.getGetLookupKey(form.getName()); + final String value = getQueryParameterValue(form); + final Cookie cookie = new Cookie(name, value); + cookie.setMaxAge(COOKIE_MAX_AGE); + CookieUtil.addCookie(cookie, response); + } + +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `cookie` last assigned on line 95 could be null and is dereferenced at line 103. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String PostRedirectGetWithCookiesFormHelperImpl.getRawFormData(String,SlingHttpServletRequest,SlingHttpServletResponse) + +### Procedure Id: +com.adobe.acs.commons.forms.helpers.impl.PostRedirectGetWithCookiesFormHelperImpl.getRawFormData(jav.ec2a4a6b4fd9a8a9301eb307821e724a + +### File: +bundle/src/main/java/com/adobe/acs/commons/forms/helpers/impl/PostRedirectGetWithCookiesFormHelperImpl.java + +### Key: +PostRedirectGetWithCookiesFormHelperImpl.java|getRawFormData|NULL_DEREFERENCE + +### Node Key: +d53599b03e0a784f08ab07e6981b8b5b + +### Hash: +d0a737dffb984cfe8daa104a28f65d64 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3807/instruction.md b/inferredbugs-3807/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c5068f17edb511abd7a3dbb7141a490529a374a5 --- /dev/null +++ b/inferredbugs-3807/instruction.md @@ -0,0 +1,223 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bistoury +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2019 Qunar, 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 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, see . + */ + +package qunar.tc.bistoury.agent.task.agentInfo; + +import com.google.common.base.Splitter; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.google.common.util.concurrent.ListeningScheduledExecutorService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import qunar.tc.bistoury.clientside.common.meta.MetaStore; +import qunar.tc.bistoury.clientside.common.meta.MetaStores; +import qunar.tc.bistoury.commands.arthas.telnet.Telnet; +import qunar.tc.bistoury.commands.arthas.telnet.TelnetStore; +import qunar.tc.bistoury.commands.arthas.telnet.UrlEncodedTelnetStore; +import qunar.tc.bistoury.common.JacksonSerializer; +import qunar.tc.bistoury.common.URLCoder; +import qunar.tc.bistoury.common.VersionUtil; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static qunar.tc.bistoury.common.BistouryConstants.REQ_AGENT_INFO; + +/** + * @author: leix.xie + * @date: 2019/2/25 17:51 + * @describe: + */ +public class TaskRunner implements Runnable { + private static final Logger logger = LoggerFactory.getLogger(TaskRunner.class); + + private static final MetaStore META_STORE = MetaStores.getMetaStore(); + + private static final TelnetStore TELNET_STORE = UrlEncodedTelnetStore.getInstance(); + + private static final String MIN_VERSION = "1.2.8"; + + private static final String command = REQ_AGENT_INFO; + + private static final String AGENT_PUSH_INTERVAL_MIN = "agent.push.interval.min"; + private static final int DEFAULT_AGENT_INFO_PUSH_INTERVAL_MINUTES = 1; + + private static final String PUSH_PROPERTIES_LIMIT = "push.properties.limit"; + + private static final Splitter PUSH_LIMIT_SPLITTER = Splitter.on("|").trimResults().omitEmptyStrings(); + + private ListeningScheduledExecutorService executor; + + TaskRunner(ListeningScheduledExecutorService executor) { + this.executor = executor; + } + + @Override + public void run() { + Telnet telnet = tryGetTelnet(); + if (telnet != null) { + try { + Map info = META_STORE.getAgentInfo(); + push(filterInfo(info), telnet); + } finally { + telnet.close(); + } + } + executor.schedule(this, getAgentInfoPushIntervalMinutes() * 20, TimeUnit.SECONDS); + } + + private Map filterInfo(Map info) { + + HashMap newInfo = Maps.newHashMap(info); + + String limit = newInfo.get(PUSH_PROPERTIES_LIMIT); + if (Strings.isNullOrEmpty(limit)) { + newInfo.remove(PUSH_PROPERTIES_LIMIT); + return ImmutableMap.copyOf(newInfo); + } + List limitList = PUSH_LIMIT_SPLITTER.splitToList(limit); + if (limitList.size() == 0) { + newInfo.remove(PUSH_PROPERTIES_LIMIT); + return ImmutableMap.copyOf(newInfo); + } + + ImmutableMap.Builder builder = ImmutableMap.builder(); + for (String key : limitList) { + builder.put(key, newInfo.get(key)); + } + return builder.build(); + } + + private int getAgentInfoPushIntervalMinutes() { + return META_STORE.getIntProperty(AGENT_PUSH_INTERVAL_MIN, DEFAULT_AGENT_INFO_PUSH_INTERVAL_MINUTES); + } + + private void push(Map agentInfo, Telnet telnet) { + try { + if (!legalVersion(telnet.getVersion())) { + return; + } + + if (agentInfo != null) { + logger.debug("push agent info: {}", agentInfo); + String newCommand = TaskRunner.command + " " + URLCoder.encode(JacksonSerializer.serialize(agentInfo)); + telnet.write(newCommand); + //如果不read,一定概率会出现push失败 + while (telnet.read() != null) { + // continue + } + } + + } catch (Exception e) { + logger.error("push agent info error", e); + } + } + + private Telnet tryGetTelnet() { + try { + return TELNET_STORE.tryGetTelnet(); + } catch (Exception e) { + logger.error("try get telnet fail", e); + return null; + } + } + + private boolean legalVersion(final String version) { + try { + return VersionUtil.greaterEqualThanVersion(version, MIN_VERSION); + } catch (Exception e) { + return false; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +CHECKERS_IMMUTABLE_CAST + +### Qualifier: +Method filterInfo(...) returns class com.google.common.collect.ImmutableMap but the return type is class java.util.Map. Make sure that users of this method do not try to modify the collection. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Map TaskRunner.filterInfo(Map) + +### Procedure Id: +qunar.tc.bistoury.agent.task.agentInfo.TaskRunner.filterInfo(java.util.Map):java.util.Map.7a4883c3cf1a99454561332f0b301134 + +### File: +bistoury-agent-task/src/main/java/qunar/tc/bistoury/agent/task/agentInfo/TaskRunner.java + +### Key: +TaskRunner.java|filterInfo|CHECKERS_IMMUTABLE_CAST + +### Node Key: +969e665cd3cad5968c8bdb29c3bc324b + +### Hash: +70c1a324a04f621b7d0ce17d4243fa4a + +### Bug Type Hum: +Checkers Immutable Cast + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3831/instruction.md b/inferredbugs-3831/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ff1a065f796ed826ad64ba53542ac58195811b29 --- /dev/null +++ b/inferredbugs-3831/instruction.md @@ -0,0 +1,917 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ohc +**Bug ID:** 67 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.caffinitas.ohc.tables; + +import java.util.List; +import java.util.concurrent.locks.ReentrantLock; + +import org.caffinitas.ohc.OHCacheBuilder; +import org.caffinitas.ohc.histo.EstimatedHistogram; + +final class OffHeapMap +{ + // maximum hash table size + private static final int MAX_TABLE_SIZE = 1 << 30; + + // TODO think of exchanging this "poor man's" open-address table to a real open-address table. + // Need to add "tombstone" for removed entries. + // Need to add "max probe length. + + private final int entriesPerBucket; + private long size; + private Table table; + + private long threshold; + private final float loadFactor; + + private long lruCompactions; + private long hitCount; + private long missCount; + private long putAddCount; + private long putReplaceCount; + private long removeCount; + + private long rehashes; + private long evictedEntries; + + private long freeCapacity; + + private final ReentrantLock lock = new ReentrantLock(); + + private final boolean throwOOME; + + OffHeapMap(OHCacheBuilder builder, long freeCapacity) + { + this.freeCapacity = freeCapacity; + + this.throwOOME = builder.isThrowOOME(); + + int hts = builder.getHashTableSize(); + if (hts <= 0) + hts = 8192; + if (hts < 256) + hts = 256; + int bl = builder.getBucketLength(); + if (bl <= 0) + bl = 8; + int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); + entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); + table = Table.create(buckets, entriesPerBucket, throwOOME); + if (table == null) + throw new RuntimeException("unable to allocate off-heap memory for segment"); + + float lf = builder.getLoadFactor(); + if (lf <= .0d) + lf = .75f; + if (lf >= 1d) + throw new IllegalArgumentException("load factor must not be greater that 1"); + this.loadFactor = lf; + threshold = (long) ((double) table.size() * loadFactor); + } + + void release() + { + lock.lock(); + try + { + table.release(); + table = null; + } + finally + { + lock.unlock(); + } + } + + long size() + { + return size; + } + + long hitCount() + { + return hitCount; + } + + long missCount() + { + return missCount; + } + + long putAddCount() + { + return putAddCount; + } + + long putReplaceCount() + { + return putReplaceCount; + } + + long removeCount() + { + return removeCount; + } + + void resetStatistics() + { + rehashes = 0L; + evictedEntries = 0L; + hitCount = 0L; + missCount = 0L; + putAddCount = 0L; + putReplaceCount = 0L; + removeCount = 0L; + lruCompactions = 0L; + } + + long rehashes() + { + return rehashes; + } + + long freeCapacity() + { + return freeCapacity; + } + + void updateFreeCapacity(long diff) + { + lock.lock(); + try + { + freeCapacity += diff; + } + finally + { + lock.unlock(); + } + } + + long evictedEntries() + { + return evictedEntries; + } + + long lruCompactions() + { + return lruCompactions; + } + + long getEntry(KeyBuffer key, boolean reference, boolean updateLRU) + { + lock.lock(); + try + { + long ptr = table.bucketOffset(key.hash()); + long hashEntryAdr; + for (int idx = 0; idx < entriesPerBucket; idx++, ptr += Util.BUCKET_ENTRY_LEN) + { + hashEntryAdr = table.getEntryAdr(ptr); + if (hashEntryAdr == 0L) + break; + if (table.getHash(ptr) != key.hash() || notSameKey(key, hashEntryAdr)) + continue; + + // return existing entry + + if (updateLRU) + touch(hashEntryAdr); + + if (reference) + HashEntries.reference(hashEntryAdr); + + hitCount++; + return hashEntryAdr; + } + + // not found + missCount++; + return 0L; + } + finally + { + lock.unlock(); + } + } + + boolean putEntry(long newHashEntryAdr, long hash, long keyLen, long bytes, boolean ifAbsent, long oldValueAdr, long oldValueLen) + { + long removeHashEntryAdr = 0L; + LongArrayList derefList = null; + lock.lock(); + try + { + long hashEntryAdr; + long ptr = table.bucketOffset(hash); + for (int idx = 0; idx < entriesPerBucket; idx++, ptr += Util.BUCKET_ENTRY_LEN) + { + if ((hashEntryAdr = table.getEntryAdr(ptr)) == 0L) + break; + + if (table.getHash(ptr) != hash) + continue; + + // fetch allocLen here - same CPU cache line needed by key compare + long allocLen = HashEntries.getAllocLen(hashEntryAdr); + if (notSameKey(newHashEntryAdr, keyLen, hashEntryAdr)) + continue; + + // replace existing entry + + if (ifAbsent) + return false; + + if (oldValueAdr != 0L) + { + // code for replace() operation + if (HashEntries.getValueLen(hashEntryAdr) != oldValueLen + || !HashEntries.compare(hashEntryAdr, Util.ENTRY_OFF_DATA + Util.roundUpTo8(keyLen), oldValueAdr, 0L, oldValueLen)) + return false; + } + + freeCapacity += allocLen; + table.removeFromTableWithOff(hashEntryAdr, ptr, idx); + + removeHashEntryAdr = hashEntryAdr; + + break; + } + + if (freeCapacity < bytes) + { + derefList = new LongArrayList(); + do + { + long eldestEntryAdr = table.removeEldest(); + if (eldestEntryAdr == 0L) + { + if (removeHashEntryAdr != 0L) + size--; + return false; + } + + freeCapacity += HashEntries.getAllocLen(eldestEntryAdr); + + size--; + evictedEntries++; + derefList.add(eldestEntryAdr); + } while (freeCapacity < bytes); + } + + if (removeHashEntryAdr == 0L) + { + if (size >= threshold) + rehash(); + + size++; + } + + if (!add(newHashEntryAdr, hash)) + return false; + + freeCapacity -= bytes; + + if (removeHashEntryAdr == 0L) + putAddCount++; + else + putReplaceCount++; + + return true; + } + finally + { + lock.unlock(); + if (removeHashEntryAdr != 0L) + HashEntries.dereference(removeHashEntryAdr); + if (derefList != null) + for (int i = 0; i < derefList.size(); i++) + HashEntries.dereference(derefList.getLong(i)); + } + } + + void clear() + { + lock.lock(); + try + { + size = 0L; + + long freed = 0L; + long hashEntryAdr; + for (int p = 0; p < table.size(); p++) + { + long ptr = table.bucketOffset(p); + for (int idx = 0; idx < entriesPerBucket; idx++, ptr += Util.BUCKET_ENTRY_LEN) + { + if ((hashEntryAdr = table.getEntryAdr(ptr)) == 0L) + break; + + freed += HashEntries.getAllocLen(hashEntryAdr); + HashEntries.dereference(hashEntryAdr); + } + } + + table.clear(); + + freeCapacity += freed; + } + finally + { + lock.unlock(); + } + } + + void removeEntry(long removeHashEntryAdr) + { + lock.lock(); + try + { + long hash = HashEntries.getHash(removeHashEntryAdr); + long hashEntryAdr; + long ptr = table.bucketOffset(hash); + for (int idx = 0; idx < entriesPerBucket; idx++, ptr += Util.BUCKET_ENTRY_LEN) + { + if ((hashEntryAdr = table.getEntryAdr(ptr)) == 0L) + break; + + if (hashEntryAdr != removeHashEntryAdr) + continue; + + // remove existing entry + + removeInternal(hashEntryAdr, ptr, idx); + + return; + } + removeHashEntryAdr = 0L; + } + finally + { + lock.unlock(); + if (removeHashEntryAdr != 0L) + HashEntries.dereference(removeHashEntryAdr); + } + } + + void removeEntry(KeyBuffer key) + { + long removeHashEntryAdr = 0L; + lock.lock(); + try + { + long hashEntryAdr; + long ptr = table.bucketOffset(key.hash()); + for (int idx = 0; idx < entriesPerBucket; idx++, ptr += Util.BUCKET_ENTRY_LEN) + { + if ((hashEntryAdr = table.getEntryAdr(ptr)) == 0L) + break; + + if (table.getHash(ptr) != key.hash() || notSameKey(key, hashEntryAdr)) + continue; + + // remove existing entry + + removeHashEntryAdr = hashEntryAdr; + removeInternal(hashEntryAdr, ptr, idx); + + return; + } + } + finally + { + lock.unlock(); + if (removeHashEntryAdr != 0L) + HashEntries.dereference(removeHashEntryAdr); + } + } + + private void removeInternal(long hashEntryAdr, long off, int idx) + { + table.removeFromTableWithOff(hashEntryAdr, off, idx); + + freeCapacity += HashEntries.getAllocLen(hashEntryAdr); + + size--; + removeCount++; + } + + private static boolean notSameKey(KeyBuffer key, long hashEntryAdr) + { + long serKeyLen = HashEntries.getKeyLen(hashEntryAdr); + return serKeyLen != key.size() + || !HashEntries.compareKey(hashEntryAdr, key, serKeyLen); + } + + private static boolean notSameKey(long newHashEntryAdr, long newKeyLen, long hashEntryAdr) + { + long serKeyLen = HashEntries.getKeyLen(hashEntryAdr); + return serKeyLen != newKeyLen + || !HashEntries.compare(hashEntryAdr, Util.ENTRY_OFF_DATA, newHashEntryAdr, Util.ENTRY_OFF_DATA, serKeyLen); + } + + private void rehash() + { + Table tab = table; + int tableSize = tab.size(); + if (tableSize > MAX_TABLE_SIZE) + { + // already at max hash table size + return; + } + + Table newTable = Table.create(tableSize * 2, entriesPerBucket, throwOOME); + if (newTable == null) + return; + + for (int part = 0; part < tableSize; part++) + { + long hashEntryAdr; + long ptr = table.bucketOffset(part); + for (int idx = 0; idx < entriesPerBucket; idx++, ptr += Util.BUCKET_ENTRY_LEN) + { + if ((hashEntryAdr = table.getEntryAdr(ptr)) == 0L) + break; + + if (!newTable.addToTable(table.getHash(ptr), hashEntryAdr)) + // this should never occur - so don't care about expensive free() + HashEntries.dereference(hashEntryAdr); + } + } + newTable.copyLRU(table); + + threshold = (long) ((float) newTable.size() * loadFactor); + table.release(); + table = newTable; + rehashes++; + } + + long[] hotN(int n) + { + lock.lock(); + try + { + long[] r = new long[n]; + table.fillHotN(r, n); + for (long hashEntryAdr : r) + if (hashEntryAdr != 0L) + HashEntries.reference(hashEntryAdr); + return r; + } + finally + { + lock.unlock(); + } + } + + float loadFactor() + { + return loadFactor; + } + + int hashTableSize() + { + return table.size(); + } + + void updateBucketHistogram(EstimatedHistogram hist) + { + lock.lock(); + try + { + table.updateBucketHistogram(hist); + } + finally + { + lock.unlock(); + } + } + + void getEntryAddresses(int mapSegmentIndex, int nSegments, List hashEntryAdrs) + { + lock.lock(); + try + { + for (; nSegments-- > 0 && mapSegmentIndex < table.size(); mapSegmentIndex++) + { + long hashEntryAdr; + long ptr = table.bucketOffset(mapSegmentIndex); + for (int idx = 0; idx < entriesPerBucket; idx++, ptr += Util.BUCKET_ENTRY_LEN) + { + if ((hashEntryAdr = table.getEntryAdr(ptr)) == 0L) + break; + hashEntryAdrs.add(hashEntryAdr); + HashEntries.reference(hashEntryAdr); + } + } + } + finally + { + lock.unlock(); + } + } + + static final class Table + { + /* + * Holds an off-heap structure with two tables: the bucket-entry-table and the LRU-table. + * The bucket-entry-table starts at 'address'. + * The LRU-table starts at 'address + lruOffset'. + * + * Layout of the bucket-entry-table: + * +----------------+------------+----------------+------------+----- + * | hash-entry-adr | hash-value | hash-entry-adr | hash-value | ... + * +----------------+------------+----------------+------------+----- + * For each bucket the table holds as many entries as specified by 'entriesPerBucket'. + * + * Layout of the LRU-table: + * +----------------+----------------+----- + * | hash-entry-adr | hash-entry-adr | ... + * +----------------+----------------+----- + * The field 'lruWriteTarget' defines at which index in the LRU-table the next recently hash-entry-address goes. + * The field 'lruEldestIndex' defines the index of the eldest entry in the LRU-table. + * If there's no more room in the LRU-table ('lruWriteTarget == size()'), the whole LRU table is compacted. + * For fast access into the LRU-table, the hash-entry itself tracks the index of the hash-entry in the LRU-table. + */ + + final int mask; + final long address; + private final int entriesPerBucket; + private boolean released; + + private final long lruOffset; + + private int lruWriteTarget; + private int lruEldestIndex; + + static Table create(int hashTableSize, int entriesPerBucket, boolean throwOOME) + { + int msz = (int) Util.BUCKET_ENTRY_LEN * hashTableSize * entriesPerBucket; + + msz += hashTableSize * Util.POINTER_LEN; + + long address = Uns.allocate(msz, throwOOME); + return address != 0L ? new Table(address, hashTableSize, entriesPerBucket) : null; + } + + private Table(long address, int hashTableSize, int entriesPerBucket) + { + this.address = address; + this.mask = hashTableSize - 1; + this.entriesPerBucket = entriesPerBucket; + + this.lruOffset = Util.BUCKET_ENTRY_LEN * hashTableSize * entriesPerBucket; + this.lruWriteTarget = 0; + + clear(); + } + + // + + void removeFromTableWithOff(long hashEntryAdr, long off, int idx) + { + for (; idx < entriesPerBucket; idx++, off += Util.BUCKET_ENTRY_LEN) + { + if (idx < entriesPerBucket - 1) + { + long adr = getEntryAdr(off + Util.BUCKET_ENTRY_LEN); + long h = getHash(off + Util.BUCKET_ENTRY_LEN); + setEntryAdr(off, adr); + setHash(off, h); + if (adr == 0L) + break; + } + else + setEntryAdr(off, 0L); + } + removeFromLRU(hashEntryAdr); + } + + long removeEldest() + { + int i = lruEldestIndex; + long off = lruOffset(i); + for (; i < lruWriteTarget; i++, off += Util.POINTER_LEN) + { + long hashEntryAdr = Uns.getAndPutLong(address, off, 0L); + if (hashEntryAdr != 0L) + { + lruEldestIndex = i + 1; + + off = bucketOffset(HashEntries.getHash(hashEntryAdr)); + boolean st = false; + for (i = 0; i < entriesPerBucket; i++, off += Util.BUCKET_ENTRY_LEN) + { + long adr; + if (!st) + { + adr = getEntryAdr(off); + if (adr == hashEntryAdr) + st = true; + else if (adr == 0L) + break; + else + continue; + } + + adr = getEntryAdr(off + Util.BUCKET_ENTRY_LEN); + long h = getHash(off + Util.BUCKET_ENTRY_LEN); + if (i < entriesPerBucket - 1) + { + setEntryAdr(off, adr); + setHash(off, h); + } + else + setEntryAdr(off, 0L); + if (adr == 0L) + break; + } + + return hashEntryAdr; + } + } + return 0; + } + + void fillHotN(long[] r, int n) + { + int c = 0; + long hashEntryAdr; + int i = lruWriteTarget - 1; + long off = lruOffset(i); + for (; i >= lruEldestIndex; i--, off -= Util.POINTER_LEN) + { + if ((hashEntryAdr = Uns.getLong(address, off)) != 0L) + { + r[c++] = hashEntryAdr; + if (c == n) + return; + } + } + } + + void copyLRU(Table srcTable) + { + lruEldestIndex = srcTable.lruEldestIndex; + lruWriteTarget = srcTable.lruWriteTarget; + Uns.copyMemory(srcTable.address, srcTable.lruOffset(0), address, lruOffset(0), lruWriteTarget * Util.POINTER_LEN); + } + + boolean addToLRU(long hashEntryAdr) + { + if (lruWriteTarget < size()) + { + // try to add to current-write-target + entryToLRU(hashEntryAdr, lruWriteTarget++); + return false; + } + + // LRU table compaction needed + + int id = 0; + long adr; + int is = lruEldestIndex; + long off = lruOffset(is); + for (; is < size(); is++, off += Util.POINTER_LEN) + if ((adr = Uns.getLong(address, off)) != 0L) + { + if (is != id) + entryToLRU(adr, id); + id++; + } + + // add hash-entry to LRU + entryToLRU(hashEntryAdr, id++); + + lruWriteTarget = id; + lruEldestIndex = 0; + + // clear remaining LRU table + Uns.setMemory(address, lruOffset(id), + (size() - id) * Util.POINTER_LEN, + (byte) 0); + + return true; + } + + private void entryToLRU(long hashEntryAdr, int id) + { + Uns.putLong(address, lruOffset(id), hashEntryAdr); + HashEntries.setLRUIndex(hashEntryAdr, id); + } + + void removeFromLRU(long hashEntryAdr) + { + int lruIndex = HashEntries.getLRUIndex(hashEntryAdr); + if (lruEldestIndex == lruIndex) + lruEldestIndex++; + if (lruIndex == lruWriteTarget - 1) + lruWriteTarget = lruIndex; + Uns.putLong(address, lruOffset(lruIndex), 0L); + } + + private long lruOffset(int i) + { + return lruOffset + i * Util.POINTER_LEN; + } + + // + + void clear() + { + // It's important to initialize the hash table memory. + // (uninitialized memory will cause problems - endless loops, JVM crashes, damaged data, etc) + Uns.setMemory(address, 0L, + Util.BUCKET_ENTRY_LEN * entriesPerBucket * size() + + Util.POINTER_LEN * size(), + (byte) 0); + } + + void release() + { + Uns.free(address); + released = true; + } + + protected void finalize() throws Throwable + { + if (!released) + Uns.free(address); + super.finalize(); + } + + boolean addToTable(long hash, long hashEntryAdr) + { + long off = bucketOffset(hash); + for (int i = 0; i < entriesPerBucket; i++, off += Util.BUCKET_ENTRY_LEN) + if (Uns.compareAndSwapLong(address, off, 0L, hashEntryAdr)) + { + setHash(off, hash); + return true; + } + return false; + } + + long bucketOffset(long hash) + { + return bucketIndexForHash(hash) * entriesPerBucket * Util.BUCKET_ENTRY_LEN; + } + + private int bucketIndexForHash(long hash) + { + return (int) (hash & mask); + } + + int size() + { + return mask + 1; + } + + void updateBucketHistogram(EstimatedHistogram h) + { + for (int p = 0; p < size(); p++) + h.add(bucketLength(p) + 1); + } + + private int bucketLength(long hash) + { + int len = 0; + long off = bucketOffset(hash); + for (int i = 0; i < entriesPerBucket; i++, off += Util.BUCKET_ENTRY_LEN) + if (getEntryAdr(off) != 0L) + len++; + else + break; + return len; + } + + long getEntryAdr(long entryOff) + { + return Uns.getLong(address, entryOff); + } + + private void setEntryAdr(long entryOff, long adr) + { + Uns.putLong(address, entryOff, adr); + } + + long getHash(long entryOff) + { + return Uns.getLong(address, entryOff + Util.BUCKET_OFF_HASH); + } + + private void setHash(long entryOff, long adr) + { + Uns.putLong(address, entryOff + Util.BUCKET_OFF_HASH, adr); + } + } + + private boolean add(long hashEntryAdr, long hash) + { + if (!table.addToTable(hash, hashEntryAdr)) + return false; + + addToLRU(hashEntryAdr); + return true; + } + + private void touch(long hashEntryAdr) + { + table.removeFromLRU(hashEntryAdr); + addToLRU(hashEntryAdr); + } + + private void addToLRU(long hashEntryAdr) + { + if (table.addToLRU(hashEntryAdr)) + lruCompactions++; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.caffinitas.ohc.tables.OffHeapMap.resetStatistics` writes to field `this.org.caffinitas.ohc.tables.OffHeapMap.putAddCount` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void OffHeapMap.resetStatistics() + +### Procedure Id: +org.caffinitas.ohc.tables.OffHeapMap.resetStatistics():void.7826fedb81df57e83b302e74c0f3aae0 + +### File: +ohc-core/src/main/java/org/caffinitas/ohc/tables/OffHeapMap.java + +### Key: +OffHeapMap.java|resetStatistics|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +b445dcefde44065d67ed2b22d1c572dd + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3838/instruction.md b/inferredbugs-3838/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f3fd13faa384b869a41d82b1e2fa3b0eefd0e84b --- /dev/null +++ b/inferredbugs-3838/instruction.md @@ -0,0 +1,650 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ohc +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.caffinitas.ohc; + +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; + +import org.caffinitas.ohc.histo.EstimatedHistogram; + +import static org.caffinitas.ohc.Util.BUCKET_ENTRY_LEN; +import static org.caffinitas.ohc.Util.ENTRY_OFF_DATA; +import static org.caffinitas.ohc.Util.roundUpTo8; + +final class OffHeapMap +{ + // maximum hash table size + private static final int MAX_TABLE_SIZE = 1 << 30; + + private long lruHead; + private long lruTail; + + private long size; + private Table table; + + private long hitCount; + private long missCount; + private long putAddCount; + private long putReplaceCount; + private long removeCount; + + private long threshold; + private final float loadFactor; + + private long rehashes; + private long evictedEntries; + + private final AtomicLong freeCapacity; + + OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) + { + this.freeCapacity = freeCapacity; + + int hts = builder.getHashTableSize(); + if (hts <= 0) + hts = 8192; + if (hts < 256) + hts = 256; + table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE)); + if (table == null) + throw new RuntimeException("unable to allocate off-heap memory for segment"); + + float lf = builder.getLoadFactor(); + if (lf <= .0d) + lf = .75f; + this.loadFactor = lf; + threshold = (long) ((double) table.size() * loadFactor); + } + + synchronized void release() + { + table.release(); + table = null; + } + + long size() + { + return size; + } + + long hitCount() + { + return hitCount; + } + + long missCount() + { + return missCount; + } + + long putAddCount() + { + return putAddCount; + } + + long putReplaceCount() + { + return putReplaceCount; + } + + long removeCount() + { + return removeCount; + } + + void resetStatistics() + { + rehashes = 0L; + evictedEntries = 0L; + hitCount = 0L; + missCount = 0L; + putAddCount = 0L; + putReplaceCount = 0L; + removeCount = 0L; + } + + long rehashes() + { + return rehashes; + } + + long evictedEntries() + { + return evictedEntries; + } + + synchronized long getEntry(KeyBuffer key, boolean reference) + { + for (long hashEntryAdr = table.getFirst(key.hash()); + hashEntryAdr != 0L; + hashEntryAdr = HashEntries.getNext(hashEntryAdr)) + { + if (notSameKey(key, hashEntryAdr)) + continue; + + // return existing entry + + touch(hashEntryAdr); + + if (reference) + HashEntries.reference(hashEntryAdr); + + hitCount++; + return hashEntryAdr; + } + + // not found + missCount++; + return 0L; + } + + synchronized boolean putEntry(long newHashEntryAdr, long hash, long keyLen, long bytes, boolean ifAbsent, long oldValueAdr, long oldValueLen) + { + long hashEntryAdr; + long prevEntryAdr = 0L; + for (hashEntryAdr = table.getFirst(hash); + hashEntryAdr != 0L; + prevEntryAdr = hashEntryAdr, hashEntryAdr = HashEntries.getNext(hashEntryAdr)) + { + if (notSameKey(newHashEntryAdr, hash, keyLen, hashEntryAdr)) + continue; + + // replace existing entry + + if (ifAbsent) + return false; + + if (oldValueAdr != 0L) + { + // code for replace() operation + long valueLen = HashEntries.getValueLen(hashEntryAdr); + if (valueLen != oldValueLen || !HashEntries.compare(hashEntryAdr, ENTRY_OFF_DATA + roundUpTo8(keyLen), oldValueAdr, 0L, oldValueLen)) + return false; + } + + removeAndDereference(hashEntryAdr, prevEntryAdr); + + break; + } + + while (freeCapacity.get() < bytes) + if (!removeOldest()) + { + if (hashEntryAdr != 0L) + size--; + return false; + } + + if (hashEntryAdr == 0L) + { + if (size >= threshold) + rehash(); + + size++; + } + + freeCapacity.addAndGet(-bytes); + + add(newHashEntryAdr, hash); + + if (hashEntryAdr == 0L) + putAddCount++; + else + putReplaceCount++; + + return true; + } + + synchronized void clear() + { + lruHead = lruTail = 0L; + size = 0L; + + long next; + for (int p = 0; p < table.size(); p++) + for (long hashEntryAdr = table.getFirst(p); + hashEntryAdr != 0L; + hashEntryAdr = next) + { + next = HashEntries.getNext(hashEntryAdr); + + dereference(hashEntryAdr); + } + + table.clear(); + } + + synchronized void removeEntry(long removeHashEntryAdr) + { + long hash = HashEntries.getHash(removeHashEntryAdr); + long prevEntryAdr = 0L; + for (long hashEntryAdr = table.getFirst(hash); + hashEntryAdr != 0L; + prevEntryAdr = hashEntryAdr, hashEntryAdr = HashEntries.getNext(hashEntryAdr)) + { + if (hashEntryAdr != removeHashEntryAdr) + continue; + + // remove existing entry + + removeAndDereference(hashEntryAdr, prevEntryAdr); + + size--; + removeCount++; + + return; + } + } + + synchronized void removeEntry(KeyBuffer key) + { + long prevEntryAdr = 0L; + for (long hashEntryAdr = table.getFirst(key.hash()); + hashEntryAdr != 0L; + prevEntryAdr = hashEntryAdr, hashEntryAdr = HashEntries.getNext(hashEntryAdr)) + { + if (notSameKey(key, hashEntryAdr)) + continue; + + // remove existing entry + + removeAndDereference(hashEntryAdr, prevEntryAdr); + + size--; + removeCount++; + + return; + } + } + + private static boolean notSameKey(KeyBuffer key, long hashEntryAdr) + { + if (HashEntries.getHash(hashEntryAdr) != key.hash()) return true; + + long serKeyLen = HashEntries.getKeyLen(hashEntryAdr); + return serKeyLen != key.size() + || !HashEntries.compareKey(hashEntryAdr, key, serKeyLen); + } + + private static boolean notSameKey(long newHashEntryAdr, long newHash, long newKeyLen, long hashEntryAdr) + { + if (HashEntries.getHash(hashEntryAdr) != newHash) return true; + + long serKeyLen = HashEntries.getKeyLen(hashEntryAdr); + return serKeyLen != newKeyLen + || !HashEntries.compare(hashEntryAdr, ENTRY_OFF_DATA, newHashEntryAdr, ENTRY_OFF_DATA, serKeyLen); + } + + private void rehash() + { + Table tab = table; + int tableSize = tab.size(); + if (tableSize > MAX_TABLE_SIZE) + { + // already at max hash table size - keep rehashTrigger field true + return; + } + + Table newTable = Table.create(tableSize * 2); + if (newTable == null) + return; + long next; + + for (int part = 0; part < tableSize; part++) + for (long hashEntryAdr = tab.getFirst(part); + hashEntryAdr != 0L; + hashEntryAdr = next) + { + next = HashEntries.getNext(hashEntryAdr); + + HashEntries.setNext(hashEntryAdr, 0L); + + newTable.addAsHead(HashEntries.getHash(hashEntryAdr), hashEntryAdr); + } + + threshold = (long) ((float) newTable.size() * loadFactor); + table = newTable; + rehashes++; + } + + synchronized long[] hotN(int n) + { + long[] r = new long[n]; + int i = 0; + for (long hashEntryAdr = lruHead; + hashEntryAdr != 0L && i < n; + hashEntryAdr = HashEntries.getLRUNext(hashEntryAdr)) + { + r[i++] = hashEntryAdr; + HashEntries.reference(hashEntryAdr); + } + return r; + } + + float loadFactor() + { + return loadFactor; + } + + int hashTableSize() + { + return table.size(); + } + + synchronized void updateBucketHistogram(EstimatedHistogram hist) + { + table.updateBucketHistogram(hist); + } + + synchronized void getEntryAddresses(int mapSegmentIndex, int nSegments, List hashEntryAdrs) + { + for (; nSegments-- > 0 && mapSegmentIndex < table.size(); mapSegmentIndex++) + for (long hashEntryAdr = table.getFirst(mapSegmentIndex); + hashEntryAdr != 0L; + hashEntryAdr = HashEntries.getNext(hashEntryAdr)) + { + hashEntryAdrs.add(hashEntryAdr); + HashEntries.reference(hashEntryAdr); + } + } + + static final class Table + { + final int mask; + final long address; + private boolean released; + + static Table create(int hashTableSize) + { + int msz = (int) BUCKET_ENTRY_LEN * hashTableSize; + long address = Uns.allocate(msz); + return address != 0L ? new Table(address, hashTableSize) : null; + } + + private Table(long address, int hashTableSize) + { + this.address = address; + this.mask = hashTableSize - 1; + clear(); + } + + void clear() + { + // It's important to initialize the hash table memory. + // (uninitialized memory will cause problems - endless loops, JVM crashes, damaged data, etc) + Uns.setMemory(address, 0L, BUCKET_ENTRY_LEN * size(), (byte) 0); + } + + void release() + { + Uns.free(address); + released = true; + } + + protected void finalize() throws Throwable + { + if (!released) + Uns.free(address); + super.finalize(); + } + + long getFirst(long hash) + { + return Uns.getLong(address, bucketOffset(hash)); + } + + void setFirst(long hash, long hashEntryAdr) + { + Uns.putLong(address, bucketOffset(hash), hashEntryAdr); + } + + private long bucketOffset(long hash) + { + return bucketIndexForHash(hash) * BUCKET_ENTRY_LEN; + } + + private int bucketIndexForHash(long hash) + { + return (int) (hash & mask); + } + + void removeLink(long hash, long hashEntryAdr, long prevEntryAdr) + { + long next = HashEntries.getNext(hashEntryAdr); + + long head = getFirst(hash); + if (head == hashEntryAdr) + { + setFirst(hash, next); + } + else if (prevEntryAdr != 0L) + { + if (prevEntryAdr == -1L) + { + for (long adr = head; + adr != 0L; + prevEntryAdr = adr, adr = HashEntries.getNext(adr)) + { + if (adr == hashEntryAdr) + break; + } + } + HashEntries.setNext(prevEntryAdr, next); + } + } + + void addAsHead(long hash, long hashEntryAdr) + { + long head = getFirst(hash); + HashEntries.setNext(hashEntryAdr, head); + setFirst(hash, hashEntryAdr); + } + + int size() + { + return mask + 1; + } + + void updateBucketHistogram(EstimatedHistogram h) + { + for (int i = 0; i < size(); i++) + { + int len = 0; + for (long adr = getFirst(i); adr != 0L; adr = HashEntries.getNext(adr)) + len++; + h.add(len + 1); + } + } + } + + // + // eviction/replacement/cleanup + // + + private void removeAndDereference(long hashEntryAdr, long prevEntryAdr) + { + long hash = HashEntries.getHash(hashEntryAdr); + + table.removeLink(hash, hashEntryAdr, prevEntryAdr); + + // LRU stuff + + long next = HashEntries.getLRUNext(hashEntryAdr); + long prev = HashEntries.getLRUPrev(hashEntryAdr); + + if (lruHead == hashEntryAdr) + lruHead = next; + if (lruTail == hashEntryAdr) + lruTail = prev; + + if (next != 0L) + HashEntries.setLRUPrev(next, prev); + if (prev != 0L) + HashEntries.setLRUNext(prev, next); + + dereference(hashEntryAdr); + } + + private void add(long hashEntryAdr, long hash) + { + table.addAsHead(hash, hashEntryAdr); + + // LRU stuff + + long h = lruHead; + HashEntries.setLRUNext(hashEntryAdr, h); + if (h != 0L) + HashEntries.setLRUPrev(h, hashEntryAdr); + HashEntries.setLRUPrev(hashEntryAdr, 0L); + lruHead = hashEntryAdr; + + if (lruTail == 0L) + lruTail = hashEntryAdr; + } + + private void touch(long hashEntryAdr) + { + long head = lruHead; + + if (head == hashEntryAdr) + // short-cut - entry already at LRU head + return; + + // LRU stuff + + long next = HashEntries.getAndSetLRUNext(hashEntryAdr, head); + long prev = HashEntries.getAndSetLRUPrev(hashEntryAdr, 0L); + + long tail = lruTail; + if (tail == hashEntryAdr) + lruTail = prev == 0L ? hashEntryAdr : prev; + else if (tail == 0L) + lruTail = hashEntryAdr; + + if (next != 0L) + HashEntries.setLRUPrev(next, prev); + if (prev != 0L) + HashEntries.setLRUNext(prev, next); + + // LRU stuff (basically an add to LRU linked list) + + if (head != 0L) + HashEntries.setLRUPrev(head, hashEntryAdr); + lruHead = hashEntryAdr; + } + + private boolean removeOldest() + { + long hashEntryAdr = lruTail; + if (hashEntryAdr == 0L) + return false; + + removeAndDereference(hashEntryAdr, -1L); + + size--; + + evictedEntries ++; + + return true; + } + + void dereference(long hashEntryAdr) + { + if (HashEntries.dereference(hashEntryAdr)) + { + long bytes = HashEntries.getAllocLen(hashEntryAdr); + + HashEntries.free(hashEntryAdr, bytes); + + freeCapacity.addAndGet(bytes); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.caffinitas.ohc.OffHeapMap.size` reads without synchronization from `this.org.caffinitas.ohc.OffHeapMap.size`. Potentially races with write in method `OffHeapMap.removeEntry(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +long OffHeapMap.size() + +### Procedure Id: +org.caffinitas.ohc.OffHeapMap.size():long.a6c6c340ed673a3b63045728e267d74f + +### File: +ohc-core/src/main/java/org/caffinitas/ohc/OffHeapMap.java + +### Key: +OffHeapMap.java|size|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +fc467db4b29ce18a98369a469ce8a41a + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3917/instruction.md b/inferredbugs-3917/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..89c1ba6c653d542cee36ed47c8a787d0eb9be90b --- /dev/null +++ b/inferredbugs-3917/instruction.md @@ -0,0 +1,184 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** pitest +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.pitest.mutationtest; + +import java.io.BufferedInputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.List; + +import org.pitest.Description; +import org.pitest.PitError; +import org.pitest.coverage.CoverageStatistics; +import org.pitest.coverage.execute.CoveragePipe; +import org.pitest.coverage.execute.CoverageResult; +import org.pitest.extension.TestUnit; +import org.pitest.functional.SideEffect1; +import org.pitest.util.Unchecked; + +public class CoverageReceiverThread extends Thread { + + private final SideEffect1 handler; + private final List tus; + private final int port; + + public CoverageReceiverThread(final int port, final List tus, + final SideEffect1 handler) { + this.setDaemon(true); + this.handler = handler; + this.tus = tus; + this.port = port; + } + + @Override + public void run() { + + ServerSocket socket = null; + try { + socket = new ServerSocket(this.port); + final Socket clientSocket = socket.accept(); + final BufferedInputStream bif = new BufferedInputStream( + clientSocket.getInputStream()); + final DataInputStream is = new DataInputStream(bif); + + Description d = null; + final CoverageStatistics cs = new CoverageStatistics(); + + byte control = is.readByte(); + while (control != CoveragePipe.DONE) { + switch (control) { + case CoveragePipe.CLAZZ: + + final int id = is.readInt(); + final String name = is.readUTF(); + + final int newId = cs.registerClass(name); + if (id != newId) { + throw new PitError("Coverage id out of sync"); + } + + break; + case CoveragePipe.LINE: + + final int classId = is.readInt(); + final int lineId = is.readInt(); + + cs.visitLine(classId, lineId); + + break; + case CoveragePipe.OUTCOME: + + final boolean isGreen = is.readBoolean(); + final long executionTime = is.readLong(); + final CoverageResult cr = new CoverageResult(d, executionTime, + isGreen, cs.getClassStatistics()); + + this.handler.apply(cr); + + cs.clearCoverageStats(); + + break; + case CoveragePipe.TEST_CHANGE: + + final int index = is.readInt(); + d = this.tus.get(index).getDescription(); + break; + case CoveragePipe.DONE: + + } + control = is.readByte(); + } + + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } finally { + if (socket != null) { + try { + socket.close(); + } catch (final IOException e) { + throw Unchecked.translateCheckedException(e); + } + } + } + + } + + public void waitToFinish() throws InterruptedException { + this.join(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.DataInputStream` acquired by call to `new()` at line 42 is not released after line 97. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CoverageReceiverThread.run() + +### Procedure Id: +org.pitest.mutationtest.CoverageReceiverThread.run():void.5b45e48704e56ec4010387f2bd295a50 + +### File: +pitest/src/main/java/org/pitest/mutationtest/CoverageReceiverThread.java + +### Key: +CoverageReceiverThread.java|run|RESOURCE_LEAK + +### Node Key: +e51514e1868709acbc6a21f9dc970738 + +### Hash: +98b384782c030bcd877773f09dfcf749 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3919/instruction.md b/inferredbugs-3919/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3fae46f248953906fcd5ac9cb359f520b755441a --- /dev/null +++ b/inferredbugs-3919/instruction.md @@ -0,0 +1,129 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** pitest +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.instrument; + +import java.io.File; +import java.util.regex.Pattern; + +import org.pitest.functional.Option; +import org.pitest.util.JavaAgent; + +public class JavaAgentJarFinder implements JavaAgent { + + private static final Pattern JAR_REGEX = Pattern + .compile(".*pitest-[\\w-\\.]*.jar"); + private final String location; + + public JavaAgentJarFinder() { + String pitJar = findPathToJarFileFromClasspath(); + if (pitJar == null) { + pitJar = "pitest-agent.jar"; + } + this.location = pitJar; + } + + private String findPathToJarFileFromClasspath() { + final String[] classPath = System.getProperty("java.class.path").split( + File.pathSeparator); + + for (final String root : classPath) { + if (JAR_REGEX.matcher(root).matches()) { + return root; + } + } + + return null; + } + + public Option getJarLocation() { + // TODO Auto-generated method stub + return Option.some(this.location); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getProperty("java.class.path")` could be null and is dereferenced at line 38. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String JavaAgentJarFinder.findPathToJarFileFromClasspath() + +### Procedure Id: +org.pitest.mutationtest.instrument.JavaAgentJarFinder.findPathToJarFileFromClasspath():java.lang.Str.4e9a4445f932c94d53b4b2c787711bb7 + +### File: +pitest/src/main/java/org/pitest/mutationtest/instrument/JavaAgentJarFinder.java + +### Key: +JavaAgentJarFinder.java|findPathToJarFileFromClasspath|NULL_DEREFERENCE + +### Node Key: +89940d97b858c9767a0f65c7a2f08fd5 + +### Hash: +6bbc5b53e200ed2bd3f69b79454309f4 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3926/instruction.md b/inferredbugs-3926/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..65a97258fcdb9e6a19289616e59929ce862340fb --- /dev/null +++ b/inferredbugs-3926/instruction.md @@ -0,0 +1,343 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** pitest +**Bug ID:** 12 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.mutationtest.report; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Reader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; + +import org.antlr.stringtemplate.StringTemplate; +import org.antlr.stringtemplate.StringTemplateGroup; +import org.pitest.Description; +import org.pitest.TestResult; +import org.pitest.classinfo.ClassInfo; +import org.pitest.extension.TestListener; +import org.pitest.functional.F; +import org.pitest.functional.F2; +import org.pitest.functional.FCollection; +import org.pitest.functional.Option; +import org.pitest.internal.IsolationUtils; +import org.pitest.mutationtest.CoverageDatabase; +import org.pitest.mutationtest.MutationResultList; +import org.pitest.mutationtest.instrument.MutationMetaData; +import org.pitest.mutationtest.instrument.UnRunnableMutationTestMetaData; +import org.pitest.util.FileUtil; + +public class MutationHtmlReportListener implements TestListener { + + private final MutatorScores mutatorScores = new MutatorScores(); + private final long startTime; + + private final Collection sourceRoots = new HashSet(); + private final File reportDir; + private final List summaryData = new ArrayList(); + private final List errors = new ArrayList(); + private final CoverageDatabase coverage; + + public MutationHtmlReportListener(final CoverageDatabase coverage, + final long startTime, final File reportDir, + final SourceLocator... locators) { + this.coverage = coverage; + this.reportDir = reportDir; + this.startTime = startTime; + this.sourceRoots.addAll(Arrays.asList(locators)); + } + + private void extractMetaData(final TestResult tr) { + final Option d = tr.getValue(MutationMetaData.class); + if (d.hasSome()) { + processMetaData(d.value()); + } else { + final Option unrunnable = tr + .getValue(UnRunnableMutationTestMetaData.class); + if (unrunnable.hasSome()) { + processUnruntest(unrunnable.value()); + } + } + } + + private void processUnruntest(final UnRunnableMutationTestMetaData unrunnable) { + this.errors.add(unrunnable.getReason()); + } + + private void processMetaData(final MutationMetaData value) { + + try { + this.mutatorScores.registerResults(value.getMutations()); + + final String css = FileUtil.readToString(IsolationUtils + .getContextClassLoader().getResourceAsStream( + "templates/mutation/style.css")); + + final int lineCoverage = calculateLineCoverage(value); + + final MutationTestSummaryData summaryData = new MutationTestSummaryData( + value.getMutatedClass(), value.getTestClasses(), + value.getPercentageMutationCoverage(), lineCoverage); + collectSummaryData(summaryData); + + final String fileName = summaryData.getFileName(); + + final BufferedWriter bf = new BufferedWriter(new FileWriter( + this.reportDir.getAbsolutePath() + File.separatorChar + fileName)); + + final StringTemplateGroup group = new StringTemplateGroup("mutation_test"); + final StringTemplate st = group + .getInstanceOf("templates/mutation/mutation_report"); + st.setAttribute("css", css); + st.setAttribute("summary", summaryData); + + st.setAttribute("tests", value.getTargettedTests()); + + st.setAttribute("mutators", value.getConfig().getMutatorNames()); + + final Collection sourceFiles = createAnnotatedSoureFiles(value); + + st.setAttribute("sourceFiles", sourceFiles); + st.setAttribute("mutatedClasses", value.getMutatedClass()); + + // st.setAttribute("groups", groups); + bf.write(st.toString()); + bf.close(); + + } catch (final IOException ex) { + ex.printStackTrace(); + } + } + + private int calculateLineCoverage(final MutationMetaData value) { + final long numberOfCoveredLines = this.coverage + .getNumberOfCoveredLines(value.getMutatedClass()); + + int lineCoverage = 0; + if (numberOfCoveredLines != 0) { + final long numberOfCodeLines = FCollection.fold(accumulateCodeLines(), 0, + this.coverage.getClassInfo(value.getMutatedClass())); + + lineCoverage = Math + .round(100f / numberOfCodeLines * numberOfCoveredLines); + + } + return lineCoverage; + } + + private F2 accumulateCodeLines() { + return new F2() { + + public Integer apply(final Integer a, final ClassInfo b) { + return a + b.getCodeLines().size(); + } + + }; + } + + private Collection createAnnotatedSoureFiles( + final MutationMetaData value) throws IOException { + final Collection sourceFiles = new ArrayList(); + for (final String each : value.getSourceFiles()) { + final MutationResultList mutationsForThisFile = value + .getResultsForSourceFile(each); + final List lines = createAnnotatedSourceCodeLines(each, + mutationsForThisFile, + this.coverage.getClassInfo(value.getClassesForSourceFile(each))); + + sourceFiles.add(new SourceFile(each, lines, mutationsForThisFile + .groupMutationsByLine())); + } + return sourceFiles; + } + + private void collectSummaryData(final MutationTestSummaryData summaryData) { + synchronized (this.summaryData) { + this.summaryData.add(summaryData); + } + + } + + private List createAnnotatedSourceCodeLines(final String sourceFile, + final MutationResultList mutationsForThisFile, + final Collection classes) throws IOException { + final Option reader = findSourceFile(classInfoToNames(classes), + sourceFile); + if (reader.hasSome()) { + final AnnotatedLineFactory alf = new AnnotatedLineFactory( + mutationsForThisFile, this.coverage, classes); + return alf.convert(reader.value()); + } + return Collections.emptyList(); + } + + private Collection classInfoToNames( + final Collection classes) { + return FCollection.map(classes, classInfoToName()); + } + + private F classInfoToName() { + return new F() { + + public String apply(final ClassInfo a) { + return a.getName(); + } + + }; + } + + private Option findSourceFile(final Collection classes, + final String fileName) { + for (final SourceLocator each : this.sourceRoots) { + final Option maybe = each.locate(classes, fileName); + if (maybe.hasSome()) { + return maybe; + } + } + return Option.none(); + } + + public void onTestError(final TestResult tr) { + extractMetaData(tr); + } + + public void onTestFailure(final TestResult tr) { + extractMetaData(tr); + } + + public void onTestSkipped(final TestResult tr) { + extractMetaData(tr); + } + + public void onTestStart(final Description d) { + + } + + public void onTestSuccess(final TestResult tr) { + extractMetaData(tr); + + } + + public void onRunEnd() { + try { + final long duration = (System.currentTimeMillis() - this.startTime) / 1000; + + final StringTemplateGroup group = new StringTemplateGroup("mutation_test"); + final StringTemplate st = group + .getInstanceOf("templates/mutation/mutation_index"); + final BufferedWriter bw = new BufferedWriter(new FileWriter( + this.reportDir.getAbsolutePath() + File.separatorChar + "index.html")); + st.setAttribute("summaryList", this.summaryData); + st.setAttribute("errors", this.errors); + st.setAttribute("numberOfMutations", + this.mutatorScores.getTotalMutations()); + st.setAttribute("numberOfDetectedMutations", + this.mutatorScores.getTotalDetectedMutations()); + st.setAttribute("duration", duration); + st.setAttribute("mutatorScores", this.mutatorScores); + bw.write(st.toString()); + bw.close(); + + } catch (final IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + public void onRunStart() { + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.BufferedWriter` acquired to `bw` by call to `new()` at line 245 is not released after line 257. +**Note**: potential exception at line 254 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MutationHtmlReportListener.onRunEnd() + +### Procedure Id: +org.pitest.mutationtest.report.MutationHtmlReportListener.onRunEnd():void.05b8d073e3594d530b1b40ddf142dcf2 + +### File: +pitest/src/main/java/org/pitest/mutationtest/report/MutationHtmlReportListener.java + +### Key: +MutationHtmlReportListener.java|onRunEnd|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +0ac1b553a28cd42d931e834830e902ca + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3928/instruction.md b/inferredbugs-3928/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5f34a9a99c244c8849f51ac2a4c26d03b081b869 --- /dev/null +++ b/inferredbugs-3928/instruction.md @@ -0,0 +1,185 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** pitest +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2010 Henry Coles + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and limitations under the License. + */ +package org.pitest.coverage.execute; + +import static org.pitest.util.Unchecked.translateCheckedException; + +import java.io.BufferedOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.Socket; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.pitest.boot.CodeCoverageStore; +import org.pitest.boot.HotSwapAgent; +import org.pitest.coverage.CoverageTransformer; +import org.pitest.extension.TestUnit; +import org.pitest.util.ExitCode; +import org.pitest.util.Log; +import org.pitest.util.SafeDataInputStream; + +public class CoverageSlave { + + private final static Logger LOG = Log.getLogger(); + + public static void main(final String[] args) { + + ExitCode exitCode = ExitCode.OK; + Socket s = null; + CoveragePipe invokeQueue = null; + try { + + final int port = Integer.valueOf(args[0]); + s = new Socket("localhost", port); + + final SafeDataInputStream dis = new SafeDataInputStream( + s.getInputStream()); + + final SlaveArguments paramsFromParent = dis.read(SlaveArguments.class); + + Log.setVerbose(paramsFromParent.isVerbose()); + + final DataOutputStream dos = new DataOutputStream( + new BufferedOutputStream(s.getOutputStream())); + + invokeQueue = new CoveragePipe(dos); + + CodeCoverageStore.init(invokeQueue); + + HotSwapAgent.addTransformer(new CoverageTransformer(paramsFromParent + .getFilter())); + + final List tus = getTestsFromParent(dis); + + LOG.info(tus.size() + " tests received"); + + final CoverageWorker worker = new CoverageWorker(invokeQueue, tus); + + worker.run(); + + } catch (final Throwable ex) { + LOG.log(Level.SEVERE, "Error calculating coverage. Process will exit.", + ex); + ex.printStackTrace(); + exitCode = ExitCode.UNKNOWN_ERROR; + } finally { + if (invokeQueue != null) { + invokeQueue.end(); + } + + try { + if (s != null) { + s.close(); + } + } catch (final IOException e) { + throw translateCheckedException(e); + } + } + + System.exit(exitCode.getCode()); + + } + + private static List getTestsFromParent(final SafeDataInputStream dis) + throws IOException { + final int count = dis.readInt(); + final List tus = new ArrayList(count); + for (int i = 0; i != count; i++) { + tus.add(dis.read(TestUnit.class)); + } + LOG.fine("Receiving " + count + " tests from parent"); + return tus; + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.net.Socket` acquired to `s` by call to `new()` at line 48 is not released after line 96. +**Note**: potential exception at line 82 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CoverageSlave.main(java.lang.String[]) + +### Procedure Id: +org.pitest.coverage.execute.CoverageSlave.main(java.lang.String[]):void.cdc89fdcbeb08542065832739b6242c6 + +### File: +pitest/src/main/java/org/pitest/coverage/execute/CoverageSlave.java + +### Key: +CoverageSlave.java|main|RESOURCE_LEAK + +### Node Key: +32e63f338c4828c4a71fa2361896ad9a + +### Hash: +ee3a99457cb8fe9b3ce671d798f5d244 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3942/instruction.md b/inferredbugs-3942/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2f786e7b0a1cbb33539dd0e879732066e2e42f54 --- /dev/null +++ b/inferredbugs-3942/instruction.md @@ -0,0 +1,449 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** kontraktor +**Bug ID:** 12 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nustaq.kontraktor.impl; + +import org.nustaq.kontraktor.*; +import io.jaq.mpsc.MpscConcurrentQueue; + +import java.lang.reflect.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Queue; +import java.util.concurrent.locks.LockSupport; + +/** + * Copyright (c) 2012, Ruediger Moeller. All rights reserved. + * + * 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., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + * + * Date: 03.01.14 + * Time: 22:19 + * To change this template use File | Settings | File Templates. + */ + +/** + * Implements the default dispatcher/scheduling of actors. + * For each actor created from "outside" (not from within another actor). A new DispatcherThread is created + * automatically. An actor created from within another actor inherits the dispatcher of the enclosing actor + * by default. + * Calls from actors sharing the same dispatcher are done directly (no queueing). Calls across actors in + * different dispatchers are put to the Channel of the receiving dispatcher. Note that cross-dispatcher calls + * are like 1000 times slower than inbound calls. + * + * Each dispatcher owns exactly one single thread. + * Note that dispatchers must be terminated if not needed any longer, as a thread is associated with them. + * + * For more sophisticated applications it might be appropriate to manually set up dispatchers (Actors.assignDispatcher()). + * The Actors.Channel method allows to specifiy a dedicated dispatcher on which to run the actor. This way it is possible + * to exactly balance and control the number of threads created and which thread operates a set of actors. + * + */ +public class DispatcherThread extends Thread { + + + public static final int PROFILE_INTERVAL = 255; + public static final int SCHEDULE_PER_PROFILE = 32; + Scheduler scheduler; + + /** + * defines the strategy applied when idling + */ + ArrayList queueList = new ArrayList<>(); + Queue queues[] = new Queue[0]; + Queue cbQueues[]= new Queue[0]; + + protected int instanceNum; + + protected boolean shutDown = false; + + public DispatcherThread(Scheduler scheduler) { + this.scheduler = scheduler; + } + + @Override + public String toString() { + return "DispatcherThread{" + + " name:"+getName()+ + '}'; + } + + public void addActor(Actor a) { + synchronized (queueList) { + queueList.add(a); + } + } + + public void removeActor(Actor a) { + synchronized (queueList) { + queueList.remove(a); + } + } + + public void run() { + int emptyCount = 0; + boolean isShutDown = false; + while( ! isShutDown ) { + + if ( pollQs() ) { + emptyCount = 0; + } + else { + emptyCount++; + scheduler.yield(emptyCount); + if (shutDown) // access volatile only when idle + isShutDown = true; + if ( scheduler.getBackoffStrategy().isSleeping(emptyCount) && System.currentTimeMillis()-created > 3000 ) { + if ( queueList.size() == 0 ) { + shutDown = true; + } else { + scheduler.tryStopThread(this); + } + } + } + } + scheduler.threadStopped(this); + for ( int i = 0; i < 100; i++ ) { + LockSupport.parkNanos(1000*1000*5); + if ( queueList.size() > 0 ) { + System.out.println("Severe: zombie dispatcher thread detected"); + run(); // for now keep things going .. + break; + } + } + System.out.println("thread died"); + } + + // if list of queues to schedule has changed, + // apply the change. needs to be done in thread + void applyQueueList() { + synchronized (queueList) { + Queue queues[] = new Queue[queueList.size()]; + Queue cbQueues[] = new Queue[queueList.size()]; + for (int i = 0; i < queues.length; i++) { + queues[i] = queueList.get(i).__mailbox; + cbQueues[i] = queueList.get(i).__cbQueue; + } + this.queues = queues; + this.cbQueues = cbQueues; + } + } + + // poll all queues in queue arr round robin + int count = 0; + protected CallEntry pollQueues(Queue[] cbQueues, Queue[] queueArr) { + if ( count >= queueArr.length ) { + // check for changed queueList each run FIXME: too often ! + count = 0; + if ( queueArr.length != queueList.size() ) { + applyQueueList(); + } + if ( queueArr.length == 0 ) { + return null; + } + } + CallEntry res = (CallEntry) cbQueues[count].poll(); + if ( res == null ) + res = (CallEntry) queueArr[count].poll(); + + count++; + return res; + } + + + // return true if msg was avaiable + int profileCounter = 0; + int schedCounter = 0; + int loadCounter=0; // counts load peaks in direct seq + int nextProfile = 511; + long created = System.currentTimeMillis(); + + public boolean pollQs() { + CallEntry poll = pollQueues(cbQueues, queues); // first callback queues + if (poll != null) { + try { + Actor.sender.set(poll.getTargetActor()); + Object invoke = null; + profileCounter++; + if ( profileCounter > nextProfile && queueList.size() > 1 && poll.getTarget() instanceof Actor ) { + profileCounter = 0; + invoke = profiledCall(poll); + } else { + invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); + } + if (poll.getFutureCB() != null) { + final Future futureCB = poll.getFutureCB(); // the future of caller side + final Promise invokeResult = (Promise) invoke; // the future returned sync from call + invokeResult.then( + new Callback() { + @Override + public void receiveResult(Object result, Object error) { + futureCB.receiveResult(result, error ); + } + } + ); + } + return true; + } catch ( Exception e) { + if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { + Actor actor = (Actor) poll.getTarget(); + actor.__stopped = true; + removeActor(actor); + applyQueueList(); + return true; + } + if (poll.getFutureCB() != null) + poll.getFutureCB().receiveResult(null, e); + if (e.getCause() != null) + e.getCause().printStackTrace(); + else + e.printStackTrace(); + } + } + return false; + } + + private Object profiledCall(CallEntry poll) throws IllegalAccessException, InvocationTargetException { + nextProfile = (int) (PROFILE_INTERVAL + Math.random() * 13); + schedCounter++; + + long nanos = System.nanoTime(); + Object invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); + nanos = System.nanoTime() - nanos; + ((Actor) poll.getTarget()).__nanos = (((Actor) poll.getTarget()).__nanos * 31 + nanos) / 32; + + if (schedCounter > SCHEDULE_PER_PROFILE) { + schedCounter = 0; + checkForSplit(); + } + return invoke; + } + + private void checkForSplit() { + int load = getLoad(); + if (load > 80 && queueList.size() > 1 && System.currentTimeMillis()-created > 1000 ) { + loadCounter++; + if (loadCounter > 2) { + loadCounter = 0; + scheduler.rebalance(this); + } + } + } + + // must be called in thread + public void splitTo( DispatcherThread newOne ) { + System.out.println("SPLIT " + scheduler.getMaxThreads()); + synchronized (queueList) { + long myTime = 0; + long otherTime = 0; + Collections.sort(queueList, new Comparator() { + @Override + public int compare(Actor o1, Actor o2) { + return (o1.__nanos - o2.__nanos) > 0 ? -1 : 1; + } + }); + for (int i = 0; i < queueList.size(); i++) { + Actor act = queueList.get(i); + long nan = act.__nanos; + if (otherTime < myTime) { + otherTime += nan; + } else { + myTime += nan; + } + } + //if ( 8*myTime > otherTime && 8*otherTime > myTime ) + // { + myTime = otherTime = 0; + for (int i = 0; i < queueList.size(); i++) { + Actor act = queueList.get(i); + long nan = act.__nanos; + if (otherTime < myTime) { + newOne.queueList.add(act); + queueList.remove(act); + i--; + otherTime += nan; + act.__currentDispatcher = newOne; + } else { + myTime += nan; + } + } + System.out.println("distributeion " + myTime + ":" + otherTime + " actors " + queues.length); + created = System.currentTimeMillis(); + applyQueueList(); + newOne.applyQueueList(); + } + } + + /** + * @return percentage of queue fill of max actor + */ + public int getLoad() { + int res = 0; + for (int i = 0; i < queues.length; i++) { + MpscConcurrentQueue queue = (MpscConcurrentQueue) queues[i]; + int load = queue.size() * 100 / queue.getCapacity(); + if ( load > res ) + res = load; + } + return res; + } + + /** + * @return profiling based load + */ + public long getLoadNanos() { + long res = 0; + for (int i = 0; i < queueList.size(); i++) { + Actor a = queueList.get(i); + res += a.__nanos; + } + return res; + } + + // FIXME: bad for concurrentlinkedq + public int getQSize() { + int res = 0; + for (int i = 0; i < queues.length; i++) { + Queue queue = queues[i]; + res+=queue.size(); + } + for (int i = 0; i < queues.length; i++) { + Queue queue = cbQueues[i]; + res+=queue.size(); + } + return res; + } + + /** + * @return true if DispatcherThread is not shut down + */ + public boolean isShutDown() { + return ! shutDown; + } + + /** + * terminate operation after emptying Q + */ + public void shutDown() { + shutDown=true; + } + + /** + * terminate operation immediately. Pending messages in Q are lost + */ + public void shutDownImmediate() { + throw new RuntimeException("unimplemented"); + } + + public boolean isEmpty() { + for (int i = 0; i < queues.length; i++) { + Queue queue = queues[i]; + if ( ! queue.isEmpty() ) + return false; + } + for (int i = 0; i < cbQueues.length; i++) { + Queue queue = cbQueues[i]; + if ( ! queue.isEmpty() ) + return false; + } + return true; + } + + /** + * blocking method, use for debugging only. + */ + public void waitEmpty(long nanos) { + while( ! isEmpty() ) + LockSupport.parkNanos(nanos); + } + + public Scheduler getScheduler() { + return scheduler; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.nustaq.kontraktor.impl.DispatcherThread.getQSize` reads without synchronization from `this.org.nustaq.kontraktor.impl.DispatcherThread.cbQueues`. Potentially races with write in method `DispatcherThread.splitTo(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int DispatcherThread.getQSize() + +### Procedure Id: +org.nustaq.kontraktor.impl.DispatcherThread.getQSize():int.adf45d0d22c24679e2cf058208efb981 + +### File: +src/main/java/org/nustaq/kontraktor/impl/DispatcherThread.java + +### Key: +DispatcherThread.java|getQSize|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +791501b153e3ba0906f4f83c78e8cbcf + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3943/instruction.md b/inferredbugs-3943/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..71126347dcd2dbdb9305070acbd970548d4f9208 --- /dev/null +++ b/inferredbugs-3943/instruction.md @@ -0,0 +1,420 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** kontraktor +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nustaq.kontraktor.impl; + +import org.nustaq.kontraktor.*; +import io.jaq.mpsc.MpscConcurrentQueue; + +import java.lang.reflect.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Queue; +import java.util.concurrent.locks.LockSupport; + +/** + * Copyright (c) 2012, Ruediger Moeller. All rights reserved. + * + * 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., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + * + * Date: 03.01.14 + * Time: 22:19 + * To change this template use File | Settings | File Templates. + */ + +/** + * Implements the default dispatcher/scheduling of actors. + * For each actor created from "outside" (not from within another actor). A new DispatcherThread is created + * automatically. An actor created from within another actor inherits the dispatcher of the enclosing actor + * by default. + * Calls from actors sharing the same dispatcher are done directly (no queueing). Calls across actors in + * different dispatchers are put to the Channel of the receiving dispatcher. Note that cross-dispatcher calls + * are like 1000 times slower than inbound calls. + * + * Each dispatcher owns exactly one single thread. + * Note that dispatchers must be terminated if not needed any longer, as a thread is associated with them. + * + * For more sophisticated applications it might be appropriate to manually set up dispatchers (Actors.assignDispatcher()). + * The Actors.Channel method allows to specifiy a dedicated dispatcher on which to run the actor. This way it is possible + * to exactly balance and control the number of threads created and which thread operates a set of actors. + * + */ +public class DispatcherThread extends Thread { + + + public static final int PROFILE_INTERVAL = 255; + public static final int SCHEDULE_PER_PROFILE = 10; + Scheduler scheduler; + + /** + * defines the strategy applied when idling + */ + ArrayList queueList = new ArrayList<>(); + Queue queues[] = new Queue[0]; + Queue cbQueues[]= new Queue[0]; + + protected int instanceNum; + + protected boolean shutDown = false; + + public DispatcherThread(Scheduler scheduler) { + this.scheduler = scheduler; + } + + @Override + public String toString() { + return "DispatcherThread{" + + " name:"+getName()+ + '}'; + } + + public void addActor(Actor a) { + synchronized (queueList) { + queueList.add(a); + } + } + + public void removeActor(Actor a) { + synchronized (queueList) { + queueList.remove(a); + } + } + + public void run() { + int emptyCount = 0; + boolean isShutDown = false; + while( ! isShutDown ) { + + if ( pollQs() ) { + emptyCount = 0; + } + else { + emptyCount++; + scheduler.yield(emptyCount); + if (shutDown) // access volatile only when idle + isShutDown = true; + } + } + scheduler.threadStopped(this); + } + + // if list of queues to schedule has changed, + // apply the change. needs to be done in thread + public void applyQueueList() { + synchronized (queueList) { + if ( queueList.size() == 0 ) + shutDown = true; + queues = new Queue[queueList.size()]; + cbQueues = new Queue[queueList.size()]; + for (int i = 0; i < queues.length; i++) { + queues[i] = queueList.get(i).__mailbox; + cbQueues[i] = queueList.get(i).__cbQueue; + } + } + } + + // poll all queues in queue arr round robin + int count = 0; + protected CallEntry pollQueues(Queue[] cbQueues, Queue[] queueArr) { + if ( count >= queueArr.length ) { + // check for changed queueList each run FIXME: too often ! + count = 0; + if ( queueArr.length != queueList.size() ) { + applyQueueList(); + } + if ( queueArr.length == 0 ) { + return null; + } + } + CallEntry res = (CallEntry) cbQueues[count].poll(); + if ( res == null ) + res = (CallEntry) queueArr[count].poll(); + + count++; + return res; + } + + + // return true if msg was avaiable + int profileCounter = 0; + int schedCounter = 0; + int loadCounter=0; // counts load peaks in direct seq + int nextProfile = 511; + long created = System.currentTimeMillis(); + + public boolean pollQs() { + CallEntry poll = pollQueues(cbQueues, queues); // first callback queues + if (poll != null) { + try { + Actor.sender.set(poll.getTargetActor()); + Object invoke = null; + profileCounter++; + if ( profileCounter > nextProfile && queueList.size() > 1 && poll.getTarget() instanceof Actor ) { + profileCounter = 0; + invoke = profiledCall(poll); + } else { + invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); + } + if (poll.getFutureCB() != null) { + final Future futureCB = poll.getFutureCB(); // the future of caller side + final Promise invokeResult = (Promise) invoke; // the future returned sync from call + invokeResult.then( + new Callback() { + @Override + public void receiveResult(Object result, Object error) { + futureCB.receiveResult(result, error ); + } + } + ); + } + return true; + } catch ( Exception e) { + if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { + removeActor((Actor) poll.getTarget()); + applyQueueList(); + return true; + } + if (poll.getFutureCB() != null) + poll.getFutureCB().receiveResult(null, e); + if (e.getCause() != null) + e.getCause().printStackTrace(); + else + e.printStackTrace(); + } + } + return false; + } + + private Object profiledCall(CallEntry poll) throws IllegalAccessException, InvocationTargetException { + nextProfile = (int) (PROFILE_INTERVAL + Math.random() * 13); + schedCounter++; + + long nanos = System.nanoTime(); + Object invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); + nanos = System.nanoTime() - nanos; + ((Actor) poll.getTarget()).__nanos = (((Actor) poll.getTarget()).__nanos * 7 + nanos) / 8; + + if (schedCounter > SCHEDULE_PER_PROFILE) { + schedCounter = 0; + checkForSplit(); + } + return invoke; + } + + private void checkForSplit() { + int load = getLoad(); + if (load > 80 && queueList.size() > 1 && System.currentTimeMillis()-created > 100 ) { + loadCounter++; + if (loadCounter > 2) { + loadCounter = 0; + doSplit(); + } + } + } + + private void doSplit() { + scheduler.rebalance(this); + } + + // must be called in thread + public void splitTo( DispatcherThread newOne ) { + System.out.println("SPLIT " + scheduler.getMaxThreads()); + synchronized (queueList) { + long myTime = 0; + long otherTime = 0; + Collections.sort(queueList, new Comparator() { + @Override + public int compare(Actor o1, Actor o2) { + return (o1.__nanos - o2.__nanos) > 0 ? -1 : 1; + } + }); + for (int i = 0; i < queueList.size(); i++) { + Actor act = queueList.get(i); + long nan = act.__nanos; + if (otherTime < myTime) { + otherTime += nan; + } else { + myTime += nan; + } + } + //if ( 8*myTime > otherTime && 8*otherTime > myTime ) + // { + myTime = otherTime = 0; + for (int i = 0; i < queueList.size(); i++) { + Actor act = queueList.get(i); + long nan = act.__nanos; + if (otherTime < myTime) { + newOne.queueList.add(act); + queueList.remove(act); + i--; + otherTime += nan; + act.__currentDispatcher = newOne; + } else { + myTime += nan; + } + } + System.out.println("distributeion " + myTime + ":" + otherTime + " actors " + queues.length); + created = System.currentTimeMillis(); + applyQueueList(); + newOne.applyQueueList(); + } + } + + public int getLoad() { + int res = 0; + for (int i = 0; i < queues.length; i++) { + MpscConcurrentQueue queue = (MpscConcurrentQueue) queues[i]; + int load = queue.size() * 100 / queue.getCapacity(); + if ( load > res ) + res = load; + } + return res; + } + + // FIXME: bad for concurrentlinkedq + public int getQSize() { + int res = 0; + for (int i = 0; i < queues.length; i++) { + Queue queue = queues[i]; + res+=queue.size(); + } + for (int i = 0; i < queues.length; i++) { + Queue queue = cbQueues[i]; + res+=queue.size(); + } + return res; + } + + /** + * @return true if DispatcherThread is not shut down + */ + public boolean isShutDown() { + return ! shutDown; + } + + /** + * terminate operation after emptying Q + */ + public void shutDown() { + shutDown=true; + } + + /** + * terminate operation immediately. Pending messages in Q are lost + */ + public void shutDownImmediate() { + throw new RuntimeException("unimplemented"); + } + + public boolean isEmpty() { + for (int i = 0; i < queues.length; i++) { + Queue queue = queues[i]; + if ( ! queue.isEmpty() ) + return false; + } + for (int i = 0; i < cbQueues.length; i++) { + Queue queue = cbQueues[i]; + if ( ! queue.isEmpty() ) + return false; + } + return true; + } + + /** + * blocking method, use for debugging only. + */ + public void waitEmpty(long nanos) { + while( ! isEmpty() ) + LockSupport.parkNanos(nanos); + } + + public Scheduler getScheduler() { + return scheduler; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.nustaq.kontraktor.impl.DispatcherThread.run` reads without synchronization from `this.org.nustaq.kontraktor.impl.DispatcherThread.shutDown`. Potentially races with write in method `DispatcherThread.splitTo(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DispatcherThread.run() + +### Procedure Id: +org.nustaq.kontraktor.impl.DispatcherThread.run():void.7dc16a4ec9d10d19bf1aeb2b8b2f0b53 + +### File: +src/main/java/org/nustaq/kontraktor/impl/DispatcherThread.java + +### Key: +DispatcherThread.java|run|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +8a2793d2c7c6636abf0efe3f6ee9111a + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3944/instruction.md b/inferredbugs-3944/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c2cc3d5e72a00b2a7a5b748a4135287d15dfb0fc --- /dev/null +++ b/inferredbugs-3944/instruction.md @@ -0,0 +1,449 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** kontraktor +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nustaq.kontraktor.impl; + +import org.nustaq.kontraktor.*; +import io.jaq.mpsc.MpscConcurrentQueue; + +import java.lang.reflect.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Queue; +import java.util.concurrent.locks.LockSupport; + +/** + * Copyright (c) 2012, Ruediger Moeller. All rights reserved. + * + * 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., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + * + * Date: 03.01.14 + * Time: 22:19 + * To change this template use File | Settings | File Templates. + */ + +/** + * Implements the default dispatcher/scheduling of actors. + * For each actor created from "outside" (not from within another actor). A new DispatcherThread is created + * automatically. An actor created from within another actor inherits the dispatcher of the enclosing actor + * by default. + * Calls from actors sharing the same dispatcher are done directly (no queueing). Calls across actors in + * different dispatchers are put to the Channel of the receiving dispatcher. Note that cross-dispatcher calls + * are like 1000 times slower than inbound calls. + * + * Each dispatcher owns exactly one single thread. + * Note that dispatchers must be terminated if not needed any longer, as a thread is associated with them. + * + * For more sophisticated applications it might be appropriate to manually set up dispatchers (Actors.assignDispatcher()). + * The Actors.Channel method allows to specifiy a dedicated dispatcher on which to run the actor. This way it is possible + * to exactly balance and control the number of threads created and which thread operates a set of actors. + * + */ +public class DispatcherThread extends Thread { + + + public static final int PROFILE_INTERVAL = 255; + public static final int SCHEDULE_PER_PROFILE = 32; + Scheduler scheduler; + + /** + * defines the strategy applied when idling + */ + ArrayList queueList = new ArrayList<>(); + Queue queues[] = new Queue[0]; + Queue cbQueues[]= new Queue[0]; + + protected int instanceNum; + + protected boolean shutDown = false; + + public DispatcherThread(Scheduler scheduler) { + this.scheduler = scheduler; + } + + @Override + public String toString() { + return "DispatcherThread{" + + " name:"+getName()+ + '}'; + } + + public void addActor(Actor a) { + synchronized (queueList) { + queueList.add(a); + } + } + + public void removeActor(Actor a) { + synchronized (queueList) { + queueList.remove(a); + } + } + + public void run() { + int emptyCount = 0; + boolean isShutDown = false; + while( ! isShutDown ) { + + if ( pollQs() ) { + emptyCount = 0; + } + else { + emptyCount++; + scheduler.yield(emptyCount); + if (shutDown) // access volatile only when idle + isShutDown = true; + if ( scheduler.getBackoffStrategy().isSleeping(emptyCount) && System.currentTimeMillis()-created > 3000 ) { + if ( queueList.size() == 0 ) { + shutDown = true; + } else { + scheduler.tryStopThread(this); + } + } + } + } + scheduler.threadStopped(this); + for ( int i = 0; i < 100; i++ ) { + LockSupport.parkNanos(1000*1000*5); + if ( queueList.size() > 0 ) { + System.out.println("Severe: zombie dispatcher thread detected"); + run(); // for now keep things going .. + break; + } + } + System.out.println("thread died"); + } + + // if list of queues to schedule has changed, + // apply the change. needs to be done in thread + void applyQueueList() { + synchronized (queueList) { + Queue queues[] = new Queue[queueList.size()]; + Queue cbQueues[] = new Queue[queueList.size()]; + for (int i = 0; i < queues.length; i++) { + queues[i] = queueList.get(i).__mailbox; + cbQueues[i] = queueList.get(i).__cbQueue; + } + this.queues = queues; + this.cbQueues = cbQueues; + } + } + + // poll all queues in queue arr round robin + int count = 0; + protected CallEntry pollQueues(Queue[] cbQueues, Queue[] queueArr) { + if ( count >= queueArr.length ) { + // check for changed queueList each run FIXME: too often ! + count = 0; + if ( queueArr.length != queueList.size() ) { + applyQueueList(); + } + if ( queueArr.length == 0 ) { + return null; + } + } + CallEntry res = (CallEntry) cbQueues[count].poll(); + if ( res == null ) + res = (CallEntry) queueArr[count].poll(); + + count++; + return res; + } + + + // return true if msg was avaiable + int profileCounter = 0; + int schedCounter = 0; + int loadCounter=0; // counts load peaks in direct seq + int nextProfile = 511; + long created = System.currentTimeMillis(); + + public boolean pollQs() { + CallEntry poll = pollQueues(cbQueues, queues); // first callback queues + if (poll != null) { + try { + Actor.sender.set(poll.getTargetActor()); + Object invoke = null; + profileCounter++; + if ( profileCounter > nextProfile && queueList.size() > 1 && poll.getTarget() instanceof Actor ) { + profileCounter = 0; + invoke = profiledCall(poll); + } else { + invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); + } + if (poll.getFutureCB() != null) { + final Future futureCB = poll.getFutureCB(); // the future of caller side + final Promise invokeResult = (Promise) invoke; // the future returned sync from call + invokeResult.then( + new Callback() { + @Override + public void receiveResult(Object result, Object error) { + futureCB.receiveResult(result, error ); + } + } + ); + } + return true; + } catch ( Exception e) { + if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { + Actor actor = (Actor) poll.getTarget(); + actor.__stopped = true; + removeActor(actor); + applyQueueList(); + return true; + } + if (poll.getFutureCB() != null) + poll.getFutureCB().receiveResult(null, e); + if (e.getCause() != null) + e.getCause().printStackTrace(); + else + e.printStackTrace(); + } + } + return false; + } + + private Object profiledCall(CallEntry poll) throws IllegalAccessException, InvocationTargetException { + nextProfile = (int) (PROFILE_INTERVAL + Math.random() * 13); + schedCounter++; + + long nanos = System.nanoTime(); + Object invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); + nanos = System.nanoTime() - nanos; + ((Actor) poll.getTarget()).__nanos = (((Actor) poll.getTarget()).__nanos * 31 + nanos) / 32; + + if (schedCounter > SCHEDULE_PER_PROFILE) { + schedCounter = 0; + checkForSplit(); + } + return invoke; + } + + private void checkForSplit() { + int load = getLoad(); + if (load > 80 && queueList.size() > 1 && System.currentTimeMillis()-created > 1000 ) { + loadCounter++; + if (loadCounter > 2) { + loadCounter = 0; + scheduler.rebalance(this); + } + } + } + + // must be called in thread + public void splitTo( DispatcherThread newOne ) { + System.out.println("SPLIT " + scheduler.getMaxThreads()); + synchronized (queueList) { + long myTime = 0; + long otherTime = 0; + Collections.sort(queueList, new Comparator() { + @Override + public int compare(Actor o1, Actor o2) { + return (o1.__nanos - o2.__nanos) > 0 ? -1 : 1; + } + }); + for (int i = 0; i < queueList.size(); i++) { + Actor act = queueList.get(i); + long nan = act.__nanos; + if (otherTime < myTime) { + otherTime += nan; + } else { + myTime += nan; + } + } + //if ( 8*myTime > otherTime && 8*otherTime > myTime ) + // { + myTime = otherTime = 0; + for (int i = 0; i < queueList.size(); i++) { + Actor act = queueList.get(i); + long nan = act.__nanos; + if (otherTime < myTime) { + newOne.queueList.add(act); + queueList.remove(act); + i--; + otherTime += nan; + act.__currentDispatcher = newOne; + } else { + myTime += nan; + } + } + System.out.println("distributeion " + myTime + ":" + otherTime + " actors " + queues.length); + created = System.currentTimeMillis(); + applyQueueList(); + newOne.applyQueueList(); + } + } + + /** + * @return percentage of queue fill of max actor + */ + public int getLoad() { + int res = 0; + for (int i = 0; i < queues.length; i++) { + MpscConcurrentQueue queue = (MpscConcurrentQueue) queues[i]; + int load = queue.size() * 100 / queue.getCapacity(); + if ( load > res ) + res = load; + } + return res; + } + + /** + * @return profiling based load + */ + public long getLoadNanos() { + long res = 0; + for (int i = 0; i < queueList.size(); i++) { + Actor a = queueList.get(i); + res += a.__nanos; + } + return res; + } + + // FIXME: bad for concurrentlinkedq + public int getQSize() { + int res = 0; + for (int i = 0; i < queues.length; i++) { + Queue queue = queues[i]; + res+=queue.size(); + } + for (int i = 0; i < queues.length; i++) { + Queue queue = cbQueues[i]; + res+=queue.size(); + } + return res; + } + + /** + * @return true if DispatcherThread is not shut down + */ + public boolean isShutDown() { + return ! shutDown; + } + + /** + * terminate operation after emptying Q + */ + public void shutDown() { + shutDown=true; + } + + /** + * terminate operation immediately. Pending messages in Q are lost + */ + public void shutDownImmediate() { + throw new RuntimeException("unimplemented"); + } + + public boolean isEmpty() { + for (int i = 0; i < queues.length; i++) { + Queue queue = queues[i]; + if ( ! queue.isEmpty() ) + return false; + } + for (int i = 0; i < cbQueues.length; i++) { + Queue queue = cbQueues[i]; + if ( ! queue.isEmpty() ) + return false; + } + return true; + } + + /** + * blocking method, use for debugging only. + */ + public void waitEmpty(long nanos) { + while( ! isEmpty() ) + LockSupport.parkNanos(nanos); + } + + public Scheduler getScheduler() { + return scheduler; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.nustaq.kontraktor.impl.DispatcherThread.isEmpty` reads without synchronization from `this.org.nustaq.kontraktor.impl.DispatcherThread.queues`. Potentially races with write in method `DispatcherThread.splitTo(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean DispatcherThread.isEmpty() + +### Procedure Id: +org.nustaq.kontraktor.impl.DispatcherThread.isEmpty():boolean.c21c8af742805be917f6b309d802fda7 + +### File: +src/main/java/org/nustaq/kontraktor/impl/DispatcherThread.java + +### Key: +DispatcherThread.java|isEmpty|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +7e687773f3ac57781b4aec5510c18086 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3945/instruction.md b/inferredbugs-3945/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b769c19ccd225ea9468d82a9a953f2680308e49d --- /dev/null +++ b/inferredbugs-3945/instruction.md @@ -0,0 +1,373 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** kontraktor +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nustaq.kontraktor.impl; + +import org.nustaq.kontraktor.*; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Queue; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Created by ruedi on 13.06.14. + */ +public class ElasticScheduler implements Scheduler { + + int maxThread = 8; // Runtime.getRuntime().availableProcessors(); + protected BackOffStrategy backOffStrategy = new BackOffStrategy(); // FIXME: should not be static + DispatcherThread threads[]; + + int defQSize = 30000; + protected ExecutorService exec = Executors.newCachedThreadPool(); + protected Timer delayedCalls = new Timer(); + + public ElasticScheduler(int maxThreads, int defQSize) { + this.maxThread = maxThreads; + this.defQSize = defQSize; + threads = new DispatcherThread[maxThreads]; + } + + @Override + public int getMaxThreads() { + return maxThread; + } + + @Override + public int getDefaultQSize() { + return defQSize; + } + +// @Override + public Future put2QueuePolling(CallEntry e) { + final Future fut; + if (e.hasFutureResult()) { + fut = new Promise(); + e.setFutureCB(new CallbackWrapper( e.getSendingActor() ,new Callback() { + @Override + public void receiveResult(Object result, Object error) { + fut.receiveResult(result,error); + } + })); + } else + fut = null; + put2QueuePolling(e.getTargetActor().__mailbox, e); + return fut; + } + + @Override + public void yield(int count) { + backOffStrategy.yield(count); + } + + @Override + public void put2QueuePolling(Queue q, Object o) { + int count = 0; + while ( ! q.offer(o) ) { + yield(count++); + } + } + + @Override + public Object dispatchCall(Actor sendingActor, Actor receiver, String methodName, Object args[]) { + // System.out.println("dispatch "+methodName+" "+Thread.currentThread()); + // here sender + receiver are known in a ST context + Actor actor = receiver.getActor(); + Method method = actor.__getCachedMethod(methodName, actor); + + int count = 0; + // scan for callbacks in arguments .. + for (int i = 0; i < args.length; i++) { + Object arg = args[i]; + if ( arg instanceof Callback) { + args[i] = new CallbackWrapper<>(sendingActor,(Callback) arg); + } + } + + CallEntry e = new CallEntry( + actor, // target + method, + args, + Actor.sender.get(), // enqueuer + actor + ); + return put2QueuePolling(e); + } + + public void threadStopped(DispatcherThread th) { + synchronized(threads) { + for (int i = 0; i < threads.length; i++) { + if (threads[i] == th) { + threads[i] = null; + return; + } + } + } + throw new RuntimeException("Oops. Unknown Thread"); + } + + class CallbackInvokeHandler implements InvocationHandler { + + final Object target; + final Actor targetActor; + + public CallbackInvokeHandler(Object target, Actor act) { + this.target = target; + this.targetActor = act; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if ( method.getDeclaringClass() == Object.class ) + return method.invoke(proxy,args); // toString, hashCode etc. invoke sync (danger if hashcode access local state) + if ( target != null ) { + CallEntry ce = new CallEntry(target,method,args, Actor.sender.get(), targetActor); + put2QueuePolling(targetActor.__cbQueue, ce); + } + return null; + } + } + + @Override + public InvocationHandler getInvoker(Actor dispatcher, Object toWrap) { + return new CallbackInvokeHandler(toWrap, dispatcher); + } + + /** + * Creates a wrapper on the given object enqueuing all calls to INTERFACE methods of the given object to the given actors's queue. + * This is used to enable processing of resulting callback's in the callers thread. + * see also @InThread annotation. + * @param callback + * @param + * @return + */ + @Override + public T inThread(Actor actor, T callback) { + Class[] interfaces = callback.getClass().getInterfaces(); + InvocationHandler invoker = actor.__scheduler.getInvoker(actor, callback); + if ( invoker == null ) // called from outside actor world + { + return callback; // callback in callee thread + } + return (T) Proxy.newProxyInstance(callback.getClass().getClassLoader(), interfaces, invoker); + } + + @Override + public void delayedCall(int millis, final Runnable toRun) { + delayedCalls.schedule(new TimerTask() { + @Override + public void run() { + toRun.run(); + } + }, millis); + } + + @Override + public void runBlockingCall(Actor emitter, final Callable toCall, Callback resultHandler) { + final CallbackWrapper resultWrapper = new CallbackWrapper<>(emitter,resultHandler); + exec.execute(new Runnable() { + @Override + public void run() { + try { + resultWrapper.receiveResult(toCall.call(), null); + } catch (Throwable th) { + resultWrapper.receiveResult(null, th); + } + } + }); + } + + /** + * wait for all futures to complete and return an array of fulfilled futures + * + * e.g. Yield( f1, f2 ).then( (f,e) -> System.out.println( f[0].getResult() + f[1].getResult() ) ); + * @param futures + * @return + */ + @Override + public Future yield(Future... futures) { + Promise res = new Promise(); + yield(futures, 0, res); + return res; + } + + @Override + public DispatcherThread assignDispatcher() { + synchronized (threads) { // FIXME race condition if thread terminates inbetween returning and new assignment + int minLoad = Integer.MAX_VALUE; + DispatcherThread minThread = findMinLoadThread(minLoad); + if ( minThread != null ) { + return minThread; + } + DispatcherThread newThreadIfPossible = createNewThreadIfPossible(); + if ( newThreadIfPossible != null ) { + newThreadIfPossible.start(); + return newThreadIfPossible; + } + } + throw new RuntimeException("could not assign thread. This is a severe error"); + } + + private DispatcherThread findMinLoadThread(int minLoad) { + synchronized (threads) { + DispatcherThread minThread = null; + for (int i = 0; i < threads.length; i++) { + DispatcherThread thread = threads[i]; + if (thread != null) { + int load = thread.getLoad(); + if (load < minLoad) { + minLoad = load; + minThread = thread; + } + } + } + return minThread; + } + } + + private DispatcherThread createNewThreadIfPossible() { + synchronized (threads) { + for (int i = 0; i < threads.length; i++) { + DispatcherThread thread = threads[i]; + if (thread == null) { + DispatcherThread th = new DispatcherThread(this); + threads[i] = th; + return th; + } + } + } + return null; + } + + /** called from inside overloaded thread with load + * all actors assigned to the calling thread therefore can be safely moved + * @param dispatcherThread + */ + @Override + public void rebalance(DispatcherThread dispatcherThread) { + int load = dispatcherThread.getLoad(); + DispatcherThread minLoadThread = createNewThreadIfPossible(); + if ( minLoadThread != null ) { + // split + dispatcherThread.splitTo(minLoadThread); + minLoadThread.start(); + return; + } + minLoadThread = findMinLoadThread(load / 4); + if ( minLoadThread == null ) { + // does not pay off. stay on current +// System.out.println("no rebalance possible"); + return; + } + // move cheapest actor up to half load + synchronized (dispatcherThread.queueList) { + long minNanos = Long.MAX_VALUE; + Actor minActor = null; + for (int i = 0; i < dispatcherThread.queueList.size(); i++) { + Actor actor = dispatcherThread.queueList.get(i); + if (actor.__nanos < minNanos) { + minNanos = actor.__nanos; + minActor = actor; + } + } + if (minActor != null) { + // System.out.println("move "+minActor+" from "+dispatcherThread+" to "+minLoadThread); + dispatcherThread.removeActor(minActor); + minLoadThread.addActor(minActor); + dispatcherThread.applyQueueList(); + } + } + } + + private void yield(final Future futures[], final int index, final Future result) { + if ( index < futures.length ) { + futures[index].then(new Callback() { + @Override + public void receiveResult(Object res, Object error) { + yield(futures, index + 1, result); + } + }); + } else { + result.receiveResult(futures, null); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.nustaq.kontraktor.impl.ElasticScheduler.rebalance` indirectly reads without synchronization from `dispatcherThread.org.nustaq.kontraktor.impl.DispatcherThread.queues`. Potentially races with write in method `ElasticScheduler.rebalance(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ElasticScheduler.rebalance(DispatcherThread) + +### Procedure Id: +org.nustaq.kontraktor.impl.ElasticScheduler.rebalance(org.nustaq.kontraktor.impl.DispatcherThread):v.5b0635d7ebc1ce716aec2c27e92e5d04 + +### File: +src/main/java/org/nustaq/kontraktor/impl/ElasticScheduler.java + +### Key: +ElasticScheduler.java|rebalance|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +7463c27d65b9671d993156cd97cf96bc + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3974/instruction.md b/inferredbugs-3974/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..800a0439562e6e9d7b3d976cf8c24a5881a61ac8 --- /dev/null +++ b/inferredbugs-3974/instruction.md @@ -0,0 +1,158 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nuls +**Bug ID:** 95 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * MIT License + *

    + * Copyright (c) 2017-2018 nuls.io + *

    + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

    + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + *

    + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.nuls.consensus.event.handler; + +import io.nuls.consensus.cache.manager.tx.ConfirmingTxCacheManager; +import io.nuls.consensus.cache.manager.tx.OrphanTxCacheManager; +import io.nuls.consensus.cache.manager.tx.ReceivedTxCacheManager; +import io.nuls.consensus.download.DownloadCacheHandler; +import io.nuls.consensus.event.BlockEvent; +import io.nuls.consensus.manager.BlockManager; +import io.nuls.core.chain.entity.Block; +import io.nuls.core.chain.entity.Transaction; +import io.nuls.core.context.NulsContext; +import io.nuls.core.utils.log.Log; +import io.nuls.event.bus.handler.AbstractEventHandler; +import io.nuls.ledger.entity.tx.AbstractCoinTransaction; +import io.nuls.network.service.NetworkService; + +/** + * @author facjas + * @date 2017/11/16 + */ +public class BlockEventHandler extends AbstractEventHandler { + + private BlockManager blockCacheManager = BlockManager.getInstance(); + private NetworkService networkService = NulsContext.getServiceBean(NetworkService.class); + + @Override + public void onEvent(BlockEvent event, String fromId) { + Block block = event.getEventBody(); + if (null == block) { + Log.warn("recieved a null blockEvent form " + fromId); + return; + } + //BlockLog.debug("download("+fromId+") block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + block.getHeader().getPackingAddress()); +// if (BlockBatchDownloadUtils.getInstance().downloadedBlock(fromId, block)) { +// return; +// } + + //blockCacheManager.addBlock(block, true, fromId); + for (Transaction tx : block.getTxs()) { + Transaction cachedTx = ConfirmingTxCacheManager.getInstance().getTx(tx.getHash()); + if (null == cachedTx) { + cachedTx = ReceivedTxCacheManager.getInstance().getTx(tx.getHash()); + } + if (null == cachedTx) { + cachedTx = OrphanTxCacheManager.getInstance().getTx(tx.getHash()); + } + if (cachedTx != null && cachedTx.getStatus() != tx.getStatus()) { + tx.setStatus(cachedTx.getStatus()); + if(!(tx instanceof AbstractCoinTransaction)){ + continue; + } + AbstractCoinTransaction coinTx = (AbstractCoinTransaction) tx; + AbstractCoinTransaction cachedCoinTx = (AbstractCoinTransaction) cachedTx; + coinTx.setCoinData(cachedCoinTx.getCoinData()); +// Log.error("the transaction status is wrong!"); + } + } + DownloadCacheHandler.receiveBlock(block); + + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `tx.getHash()` could be null and is dereferenced by call to `getTx(...)` at line 65. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BlockEventHandler.onEvent(BlockEvent,String) + +### Procedure Id: +io.nuls.consensus.event.handler.BlockEventHandler.onEvent(io.nuls.consensus.event.BlockEvent,java.la.ad94e7f6b37701979f7d07540cf83a9e + +### File: +consensus-impl/src/main/java/io/nuls/consensus/event/handler/BlockEventHandler.java + +### Key: +BlockEventHandler.java|onEvent|NULL_DEREFERENCE + +### Node Key: +7e9fc31bc469440d6384630f8b346526 + +### Hash: +cf12897195a154a9ea0ecd58b21cd526 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3980/instruction.md b/inferredbugs-3980/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a984b6b9c6b1633c108392b125c722c2655d1b6f --- /dev/null +++ b/inferredbugs-3980/instruction.md @@ -0,0 +1,199 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nuls +**Bug ID:** 68 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * MIT License + *

    + * Copyright (c) 2017-2018 nuls.io + *

    + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

    + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + *

    + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.nuls.consensus.event.handler; + +import io.nuls.consensus.cache.manager.block.TemporaryCacheManager; +import io.nuls.consensus.cache.manager.tx.OrphanTxCacheManager; +import io.nuls.consensus.cache.manager.tx.ReceivedTxCacheManager; +import io.nuls.consensus.entity.GetTxGroupParam; +import io.nuls.consensus.entity.RedPunishData; +import io.nuls.consensus.event.BlockHeaderEvent; +import io.nuls.consensus.event.GetTxGroupRequest; +import io.nuls.consensus.event.SmallBlockEvent; +import io.nuls.consensus.manager.BlockManager; +import io.nuls.consensus.thread.ConsensusMeetingRunner; +import io.nuls.consensus.utils.DownloadDataUtils; +import io.nuls.core.chain.entity.Block; +import io.nuls.core.chain.entity.BlockHeader; +import io.nuls.core.chain.entity.NulsDigestData; +import io.nuls.core.chain.entity.Transaction; +import io.nuls.core.constant.ErrorCode; +import io.nuls.core.constant.SeverityLevelEnum; +import io.nuls.core.context.NulsContext; +import io.nuls.core.exception.NulsRuntimeException; +import io.nuls.core.validate.ValidateResult; +import io.nuls.db.entity.NodePo; +import io.nuls.event.bus.handler.AbstractEventHandler; +import io.nuls.event.bus.service.intf.EventBroadcaster; +import io.nuls.network.service.NetworkService; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author facjas + * @date 2017/11/16 + */ +public class SmallBlockHandler extends AbstractEventHandler { + private TemporaryCacheManager temporaryCacheManager = TemporaryCacheManager.getInstance(); + private ReceivedTxCacheManager receivedTxCacheManager = ReceivedTxCacheManager.getInstance(); + private OrphanTxCacheManager orphanTxCacheManager = OrphanTxCacheManager.getInstance(); + private DownloadDataUtils downloadDataUtils = DownloadDataUtils.getInstance(); + private NetworkService networkService = NulsContext.getServiceBean(NetworkService.class); + private BlockManager blockManager = BlockManager.getInstance(); + private EventBroadcaster eventBroadcaster = NulsContext.getServiceBean(EventBroadcaster.class); + + @Override + public void onEvent(SmallBlockEvent event, String fromId) { + ValidateResult result = event.getEventBody().verify(); + if (result.isFailed()) { + return; + } + temporaryCacheManager.cacheSmallBlock(event.getEventBody()); + downloadDataUtils.removeSmallBlock(event.getEventBody().getBlockHash().getDigestHex()); + GetTxGroupRequest request = new GetTxGroupRequest(); + GetTxGroupParam param = new GetTxGroupParam(); + param.setBlockHash(event.getEventBody().getBlockHash()); + for (NulsDigestData hash : event.getEventBody().getTxHashList()) { + if (!receivedTxCacheManager.txExist(hash) && !orphanTxCacheManager.txExist(hash)) { + param.addHash(hash); + } + } + if (param.getTxHashList().isEmpty()) { + BlockHeader header = temporaryCacheManager.getBlockHeader(event.getEventBody().getBlockHash().getDigestHex()); + if (null == header) { + return; + } + Block block = new Block(); + block.setHeader(header); + List txs = new ArrayList<>(); + for (NulsDigestData txHash : event.getEventBody().getTxHashList()) { + Transaction tx = receivedTxCacheManager.getTx(txHash); + + if (null == tx) { + tx = orphanTxCacheManager.getTx(txHash); + } + if (null == tx) { + throw new NulsRuntimeException(ErrorCode.DATA_ERROR); + } + txs.add(tx); + } + block.setTxs(txs); + ValidateResult vResult = block.verify(); + if (null == vResult || (vResult.isFailed() && vResult.getErrorCode() != ErrorCode.ORPHAN_TX)) { + if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) { + RedPunishData data = vResult.getObject(); + ConsensusMeetingRunner.putPunishData(data); + networkService.blackNode(fromId, NodePo.BLACK); + } else { + networkService.removeNode(fromId, NodePo.YELLOW); + } + return; + } + blockManager.addBlock(block, false, fromId); + downloadDataUtils.removeTxGroup(block.getHeader().getHash().getDigestHex()); + + BlockHeaderEvent headerEvent = new BlockHeaderEvent(); + headerEvent.setEventBody(header); + eventBroadcaster.broadcastHashAndCacheAysn(headerEvent, false, fromId); + return; + } + request.setEventBody(param); + this.eventBroadcaster.sendToNode(request, fromId); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `vResult` last assigned on line 103 could be null and is dereferenced at line 105. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SmallBlockHandler.onEvent(SmallBlockEvent,String) + +### Procedure Id: +io.nuls.consensus.event.handler.SmallBlockHandler.onEvent(io.nuls.consensus.event.SmallBlockEvent,ja.70a73ee2551cfcd51fffe014440691d5 + +### File: +consensus-impl/src/main/java/io/nuls/consensus/event/handler/SmallBlockHandler.java + +### Key: +SmallBlockHandler.java|onEvent|NULL_DEREFERENCE + +### Node Key: +13f969d83a3eb47b8e32fbd4781040c5 + +### Hash: +12185baca6adb71e92ab100b304982e3 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3986/instruction.md b/inferredbugs-3986/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..98d62f0f21bd4df1d2ba58525266d76057c11926 --- /dev/null +++ b/inferredbugs-3986/instruction.md @@ -0,0 +1,161 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nuls +**Bug ID:** 69 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * MIT License + * + * Copyright (c) 2017-2018 nuls.io + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.nuls.consensus.event.handler; + +import io.nuls.consensus.entity.TxGroup; +import io.nuls.consensus.entity.GetTxGroupParam; +import io.nuls.consensus.event.GetTxGroupRequest; +import io.nuls.consensus.event.TxGroupEvent; +import io.nuls.consensus.service.intf.BlockService; +import io.nuls.core.chain.entity.Block; +import io.nuls.core.chain.entity.NulsDigestData; +import io.nuls.core.chain.entity.Transaction; +import io.nuls.core.constant.ErrorCode; +import io.nuls.core.context.NulsContext; +import io.nuls.core.exception.NulsRuntimeException; +import io.nuls.core.utils.log.Log; +import io.nuls.event.bus.handler.AbstractEventHandler; +import io.nuls.event.bus.service.intf.EventBroadcaster; +import io.nuls.ledger.service.intf.LedgerService; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author facjas + * @date 2017/11/16 + */ +public class GetTxGroupHandler extends AbstractEventHandler { + + private EventBroadcaster eventBroadcaster = NulsContext.getServiceBean(EventBroadcaster.class); + private BlockService blockService =NulsContext.getServiceBean(BlockService.class); + + @Override + public void onEvent(GetTxGroupRequest event, String fromId) { + GetTxGroupParam eventBody = event.getEventBody(); + Block block = blockService.getBlock(eventBody.getBlockHash().getDigestHex()); + if (null == block) { + return; + } + TxGroupEvent txGroupEvent = new TxGroupEvent(); + TxGroup txGroup = new TxGroup(); + txGroup.setBlockHash(block.getHeader().getHash()); + List txList = getTxList(block,eventBody.getTxHashList()); + txGroup.setTxList(txList); + txGroupEvent.setEventBody(txGroup); + eventBroadcaster.sendToNode(txGroupEvent, fromId); + } + + private List getTxList(Block block, List txHashList) { + List txList = new ArrayList<>(); + Map allTxMap = new HashMap<>(); + for (int i = 0; i < block.getHeader().getTxCount(); i++) { + Transaction tx = block.getTxs().get(i); + allTxMap.put(tx.getHash().getDigestHex(), i); + } + for (NulsDigestData hash : txHashList) { + txList.add(block.getTxs().get(allTxMap.get(hash.getDigestHex()))); + } + if (txList.size() != txHashList.size()) { + throw new NulsRuntimeException(ErrorCode.DATA_ERROR); + } + return txList; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `allTxMap.get(hash.getDigestHex())` could be null and is dereferenced at line 80. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List GetTxGroupHandler.getTxList(Block,List) + +### Procedure Id: +io.nuls.consensus.event.handler.GetTxGroupHandler.getTxList(io.nuls.core.chain.entity.Block,java.uti.cac6cf16282a5d3369a8c03d4553276a + +### File: +consensus-impl/src/main/java/io/nuls/consensus/event/handler/GetTxGroupHandler.java + +### Key: +GetTxGroupHandler.java|getTxList|NULL_DEREFERENCE + +### Node Key: +641e16f7c5696be98b8f9d94c200704c + +### Hash: +f512f3ed04361194aec3322cc991d2c0 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3987/instruction.md b/inferredbugs-3987/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..88d2ff27e562a4d70af486e37d27b496e43e8b3b --- /dev/null +++ b/inferredbugs-3987/instruction.md @@ -0,0 +1,554 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nuls +**Bug ID:** 56 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * MIT License + * + * Copyright (c) 2017-2018 nuls.io + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.nuls.ledger.service.impl; + +import io.nuls.account.entity.Account; +import io.nuls.account.entity.Address; +import io.nuls.account.service.intf.AccountService; +import io.nuls.core.chain.entity.Na; +import io.nuls.core.chain.entity.NulsDigestData; +import io.nuls.core.chain.entity.Transaction; +import io.nuls.core.constant.ErrorCode; +import io.nuls.core.constant.TransactionConstant; +import io.nuls.core.constant.TxStatusEnum; +import io.nuls.core.exception.NulsException; +import io.nuls.core.exception.NulsRuntimeException; +import io.nuls.core.script.P2PKHScript; +import io.nuls.core.utils.io.NulsByteBuffer; +import io.nuls.core.utils.log.Log; +import io.nuls.core.utils.spring.lite.annotation.Autowired; +import io.nuls.db.dao.TxAccountRelationDataService; +import io.nuls.db.dao.UtxoInputDataService; +import io.nuls.db.dao.UtxoOutputDataService; +import io.nuls.db.entity.TxAccountRelationPo; +import io.nuls.db.entity.UtxoInputPo; +import io.nuls.db.entity.UtxoOutputPo; +import io.nuls.db.transactional.annotation.DbSession; +import io.nuls.ledger.entity.*; +import io.nuls.ledger.entity.params.Coin; +import io.nuls.ledger.entity.params.CoinTransferData; +import io.nuls.ledger.entity.tx.LockNulsTransaction; +import io.nuls.ledger.entity.tx.UnlockNulsTransaction; +import io.nuls.ledger.service.intf.CoinDataProvider; +import io.nuls.ledger.util.UtxoTransactionTool; +import io.nuls.ledger.util.UtxoTransferTool; + +import java.util.*; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +/** + * @author Niels + * @date 2017/12/21 + */ +public class UtxoCoinDataProvider implements CoinDataProvider { + + private LedgerCacheService ledgerCacheService = LedgerCacheService.getInstance(); + @Autowired + private UtxoOutputDataService outputDataService; + @Autowired + private UtxoInputDataService inputDataService; + @Autowired + private TxAccountRelationDataService relationDataService; + @Autowired + private AccountService accountService; + + private UtxoCoinManager coinManager = UtxoCoinManager.getInstance(); + + private Lock lock = new ReentrantLock(); + + @Override + public CoinData parse(NulsByteBuffer byteBuffer) throws NulsException { + CoinData coinData = byteBuffer.readNulsData(new UtxoData()); + return coinData; + } + + @Override + public void approve(CoinData coinData, Transaction tx) throws NulsException { + //spent the transaction specified output in the cache when the newly received transaction is approved. + UtxoData utxoData = (UtxoData) coinData; + for (UtxoInput input : utxoData.getInputs()) { + input.setTxHash(tx.getHash()); + } + for (UtxoOutput output : utxoData.getOutputs()) { + output.setTxHash(tx.getHash()); + } + + List unSpends = new ArrayList<>(); + Set addressSet = new HashSet<>(); + try { + //update inputs referenced utxo status + for (int i = 0; i < utxoData.getInputs().size(); i++) { + UtxoInput input = utxoData.getInputs().get(i); + UtxoOutput unSpend = ledgerCacheService.getUtxo(input.getKey()); + if (null == unSpend) { + throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "the output is not exist!"); + } + if (!unSpend.isUsable()) { + throw new NulsRuntimeException(ErrorCode.UTXO_UNUSABLE); + } + if (OutPutStatusEnum.UTXO_CONFIRM_UNSPEND == unSpend.getStatus()) { + unSpend.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND); + } else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == unSpend.getStatus()) { + unSpend.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_SPEND); + } + unSpends.add(unSpend); + addressSet.add(unSpend.getAddress()); + } + + //cache new utxo ,it is unConfirm + approveProcessOutput(utxoData.getOutputs(), tx, addressSet); + } catch (Exception e) { + //rollback + for (UtxoOutput output : unSpends) { + if (OutPutStatusEnum.UTXO_CONFIRM_SPEND.equals(output.getStatus())) { + ledgerCacheService.updateUtxoStatus(output.getKey(), OutPutStatusEnum.UTXO_CONFIRM_UNSPEND, OutPutStatusEnum.UTXO_CONFIRM_SPEND); + } else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND.equals(output.getStatus())) { + ledgerCacheService.updateUtxoStatus(output.getKey(), OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND, OutPutStatusEnum.UTXO_UNCONFIRM_SPEND); + } + } + // remove cache new utxo + for (int i = 0; i < utxoData.getOutputs().size(); i++) { + UtxoOutput output = utxoData.getOutputs().get(i); + ledgerCacheService.removeUtxo(output.getKey()); + } + throw e; + } finally { + //calc balance + for (String address : addressSet) { + UtxoTransactionTool.getInstance().calcBalance(address, false); + } + } + } + + private void approveProcessOutput(List outputs, Transaction tx, Set addressSet) { + for (int i = 0; i < outputs.size(); i++) { + UtxoOutput output = outputs.get(i); + if (tx instanceof LockNulsTransaction && i == 0) { + output.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK); + } else if (output.getLockTime() > 0) { + output.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK); + } else { + output.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND); + } + ledgerCacheService.putUtxo(output.getKey(), output); + addressSet.add(output.getAddress()); + } + } + + /** + * 1. change spending output status (cache and database) + * 2. save new input + * 3. save new unSpend output (cache and database) + * 4. finally, calc balance + */ + @Override + @DbSession + public void save(CoinData coinData, Transaction tx) throws NulsException { + UtxoData utxoData = (UtxoData) coinData; + + List inputPoList = new ArrayList<>(); + List spends = new ArrayList<>(); + List spendPoList = new ArrayList<>(); + List txRelations = new ArrayList<>(); + Set addressSet = new HashSet<>(); + + try { + processDataInput(utxoData, inputPoList, spends, spendPoList, addressSet); + + List outputPoList = new ArrayList<>(); + for (int i = 0; i < utxoData.getOutputs().size(); i++) { + UtxoOutput output = utxoData.getOutputs().get(i); + output = ledgerCacheService.getUtxo(output.getKey()); + if (output == null) { + throw new NulsRuntimeException(ErrorCode.DATA_NOT_FOUND); + } + if (output.isConfirm() || OutPutStatusEnum.UTXO_SPENT == output.getStatus()) { + Log.error("-----------------------------------save() output status is" + output.getStatus().name()); + throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "use a not legal utxo"); + } + + if (OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK == output.getStatus()) { + output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_CONSENSUS_LOCK); + } else if (OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK == output.getStatus()) { + output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_TIME_LOCK); + } else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == output.getStatus()) { + output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND); + } else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND == output.getStatus()) { + output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND); + } + + UtxoOutputPo outputPo = UtxoTransferTool.toOutputPojo(output); + outputPoList.add(outputPo); + addressSet.add(Address.fromHashs(output.getAddress()).getBase58()); + } + + for (String address : addressSet) { + TxAccountRelationPo relationPo = new TxAccountRelationPo(tx.getHash().getDigestHex(), address); + txRelations.add(relationPo); + } + + outputDataService.updateStatus(spendPoList); + + inputDataService.save(inputPoList); + + outputDataService.save(outputPoList); + + relationDataService.save(txRelations); + + afterSaveDatabase(spends, utxoData, tx); + + for (String address : addressSet) { + UtxoTransactionTool.getInstance().calcBalance(address, true); + } + } catch (Exception e) { + //rollback +// Log.warn(e.getMessage(), e); +// for (UtxoOutput output : utxoData.getOutputs()) { +// ledgerCacheService.removeUtxo(output.getKey()); +// } +// for (UtxoOutput spend : spends) { +// ledgerCacheService.updateUtxoStatus(spend.getKey(), UtxoOutput.UTXO_CONFIRM_LOCK, UtxoOutput.UTXO_SPENT); +// } + throw e; + } + } + + //Check if the input referenced output has been spent + private void processDataInput(UtxoData utxoData, List inputPoList, + List spends, List spendPoList, + Set addressSet) { + boolean update; + for (int i = 0; i < utxoData.getInputs().size(); i++) { + UtxoInput input = utxoData.getInputs().get(i); + UtxoOutput spend = ledgerCacheService.getUtxo(input.getKey()); + if (spend == null) { + throw new NulsRuntimeException(ErrorCode.DATA_NOT_FOUND, "the output is not exist!"); + } + //change utxo status, + update = ledgerCacheService.updateUtxoStatus(spend.getKey(), OutPutStatusEnum.UTXO_SPENT, OutPutStatusEnum.UTXO_CONFIRM_SPEND); + if (!update) { + Log.error("-----------------------------------save() input referenced status is" + spend.getStatus().name()); + throw new NulsRuntimeException(ErrorCode.UTXO_STATUS_CHANGE); + } + spends.add(spend); + spendPoList.add(UtxoTransferTool.toOutputPojo(spend)); + inputPoList.add(UtxoTransferTool.toInputPojo(input)); + addressSet.add(spend.getAddress()); + } + } + + private void afterSaveDatabase(List spends, UtxoData utxoData, Transaction tx) { + for (int i = 0; i < spends.size(); i++) { + ledgerCacheService.removeUtxo(spends.get(i).getKey()); + } + } + + @Override + @DbSession + public void rollback(CoinData coinData, Transaction tx) { + UtxoData utxoData = (UtxoData) coinData; + if (utxoData == null) { + return; + } + + Set addressSet = new HashSet<>(); + if (TxStatusEnum.AGREED.equals(tx.getStatus())) { + for (UtxoInput input : utxoData.getInputs()) { + UtxoOutput from = ledgerCacheService.getUtxo(input.getKey()); + if (from != null) { + if (from.getStatus() == OutPutStatusEnum.UTXO_SPENT) { + from.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND); + } else if (from.getStatus() == OutPutStatusEnum.UTXO_CONFIRM_SPEND) { + from.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND); + } else if (from.getStatus() == OutPutStatusEnum.UTXO_UNCONFIRM_SPEND) { + from.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND); + } + addressSet.add(from.getAddress()); + } + } + for (int i = utxoData.getOutputs().size() - 1; i >= 0; i--) { + UtxoOutput output = utxoData.getOutputs().get(i); + ledgerCacheService.removeUtxo(output.getKey()); + addressSet.add(output.getAddress()); + } + } else if (tx.getStatus().equals(TxStatusEnum.CONFIRMED)) { + //process output + outputDataService.deleteByHash(tx.getHash().getDigestHex()); + for (int i = utxoData.getOutputs().size() - 1; i >= 0; i--) { + UtxoOutput output = utxoData.getOutputs().get(i); + ledgerCacheService.removeUtxo(output.getKey()); + addressSet.add(output.getAddress()); + } + + //process input + //1. delete input (database) + //2. change input referenced output status (database) + //3. cache and calc balance + inputDataService.deleteByHash(tx.getHash().getDigestHex()); + Map keyMap = new HashMap<>(); + for (int i = utxoData.getInputs().size() - 1; i >= 0; i--) { + UtxoInput input = utxoData.getInputs().get(i); + keyMap.clear(); + keyMap.put("txHash", input.getFromHash().getDigestHex()); + keyMap.put("outIndex", input.getFromIndex()); + UtxoOutputPo outputPo = outputDataService.get(keyMap); + outputPo.setStatus(UtxoOutputPo.USABLE); + outputDataService.updateStatus(outputPo); + addressSet.add(outputPo.getAddress()); + + UtxoOutput output = UtxoTransferTool.toOutput(outputPo); + ledgerCacheService.putUtxo(output.getKey(), output); + } + relationDataService.deleteRelation(tx.getHash().getDigestHex(), addressSet); + } + + for (String address : addressSet) { + UtxoTransactionTool.getInstance().calcBalance(address, false); + } + } + + @Override + public CoinData createByTransferData(Transaction tx, CoinTransferData coinParam, String password) throws NulsException { + lock.lock(); + try { + UtxoData utxoData = new UtxoData(); + List inputs = new ArrayList<>(); + List outputs = new ArrayList<>(); + // Na totalNa = Na.ZERO; + + if (coinParam.getTotalNa().equals(Na.ZERO)) { + utxoData.setInputs(inputs); + utxoData.setOutputs(outputs); + return utxoData; + } + + long inputValue = 0; + if (!coinParam.getFrom().isEmpty()) { + //find unSpends to create inputs for this tx + Na totalFee = Na.ZERO; + if (tx instanceof UnlockNulsTransaction) { + totalFee = coinParam.getFee(); + } else { + totalFee = coinParam.getTotalNa().add(coinParam.getFee()); + } + + List unSpends = coinManager.getAccountsUnSpend(coinParam.getFrom(), totalFee); + if (unSpends.isEmpty()) { + throw new NulsException(ErrorCode.BALANCE_NOT_ENOUGH); + } + + for (int i = 0; i < unSpends.size(); i++) { + UtxoOutput output = unSpends.get(i); + UtxoInput input = new UtxoInput(); + input.setFrom(output); + input.setFromHash(output.getTxHash()); + input.setFromIndex(output.getIndex()); + input.setTxHash(tx.getHash()); + input.setIndex(i); + inputValue += output.getValue(); + + inputs.add(input); + } + } + + //get EcKey for output's script + Account account = null; + byte[] priKey = null; + if (coinParam.getPriKey() != null) { + priKey = coinParam.getPriKey(); + } else if (!coinParam.getFrom().isEmpty()) { + account = accountService.getAccount(coinParam.getFrom().get(0)); + if (account == null) { + throw new NulsException(ErrorCode.ACCOUNT_NOT_EXIST); + } + if (account.isEncrypted() && account.isLocked()) { + if (!account.unlock(password)) { + throw new NulsException(ErrorCode.PASSWORD_IS_WRONG); + } + priKey = account.getPriKey(); + account.lock(); + } else { + priKey = account.getPriKey(); + } + } + + //create outputs + int i = 0; + long outputValue = 0; + for (Map.Entry> entry : coinParam.getToMap().entrySet()) { + String address = entry.getKey(); + List coinList = entry.getValue(); + for (Coin coin : coinList) { + UtxoOutput output = new UtxoOutput(); + output.setAddress(address); + output.setValue(coin.getNa().getValue()); + if (output.getLockTime() > 0) { + output.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK); + } else if (tx instanceof LockNulsTransaction) { + output.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK); + } else { + output.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND); + } + + output.setIndex(i); + P2PKHScript p2PKHScript = new P2PKHScript(new NulsDigestData(NulsDigestData.DIGEST_ALG_SHA160, new Address(address).getHash160())); + output.setP2PKHScript(p2PKHScript); + if (coin.getUnlockHeight() > 0) { + output.setLockTime(coin.getUnlockHeight()); + } else if (coin.getUnlockTime() > 0) { + output.setLockTime(coin.getUnlockTime()); + } else { + output.setLockTime(0L); + } + output.setTxHash(tx.getHash()); + outputValue += output.getValue(); + outputs.add(output); + + i++; + } + } + + //the balance leave to myself + long balance = 0; + if (outputValue > 0) { + balance = inputValue - outputValue - coinParam.getFee().getValue(); + } else { + balance = inputValue - coinParam.getTotalNa().getValue() - coinParam.getFee().getValue(); + } + if (balance > 0) { + UtxoOutput output = new UtxoOutput(); + output.setAddress(inputs.get(0).getFrom().getAddress()); + output.setValue(balance); + output.setIndex(i); + output.setTxHash(tx.getHash()); + output.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND); + P2PKHScript p2PKHScript = new P2PKHScript(new NulsDigestData(NulsDigestData.DIGEST_ALG_SHA160, account.getHash160())); + output.setP2PKHScript(p2PKHScript); + outputs.add(output); + } + utxoData.setInputs(inputs); + utxoData.setOutputs(outputs); + return utxoData; + } finally { + lock.unlock(); + } + } + + @Override + public void afterParse(CoinData coinData, Transaction tx) { + UtxoData utxoData = (UtxoData) coinData; + if (null != utxoData.getInputs()) { + for (UtxoInput input : utxoData.getInputs()) { + input.setTxHash(tx.getHash()); + } + } + if (tx instanceof LockNulsTransaction) { + utxoData.getOutputs().get(0).setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK); + } +// Na totalNa = Na.ZERO; +// if (null != utxoData.getOutputs()) { +// for (int i = 0; i < utxoData.getOutputs().size(); i++) { +// UtxoOutput output = utxoData.getOutputs().get(i); +// output.setTxHash(tx.getHash()); +// } +// } +// coinData.setTotalNa(totalNa); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `io.nuls.ledger.service.impl.UtxoCoinDataProvider.approve` indirectly reads without synchronization from `i18n.I18nUtils.io.nuls.core.i18n.I18nUtils.nowMapping`. Potentially races with write in method `UtxoCoinDataProvider.createByTransferData(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void UtxoCoinDataProvider.approve(CoinData,Transaction) + +### Procedure Id: +io.nuls.ledger.service.impl.UtxoCoinDataProvider.approve(io.nuls.ledger.entity.CoinData,io.nuls.core.2629360427d82ff16d3c9e8f11e38f18 + +### File: +ledger-impl/src/main/java/io/nuls/ledger/service/impl/UtxoCoinDataProvider.java + +### Key: +UtxoCoinDataProvider.java|approve|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +e84760d9fb0d9f5e97a79ce0da490584 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3988/instruction.md b/inferredbugs-3988/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..220600bafefdcd33f9d0465f8c038974f9a1de7e --- /dev/null +++ b/inferredbugs-3988/instruction.md @@ -0,0 +1,901 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nuls +**Bug ID:** 105 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * MIT License + * * + * Copyright (c) 2017-2018 nuls.io + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.nuls.ledger.service.impl; + +import io.nuls.core.constant.ErrorCode; +import io.nuls.core.dto.Page; +import io.nuls.core.exception.NulsException; +import io.nuls.core.exception.NulsRuntimeException; +import io.nuls.core.model.Result; +import io.nuls.core.utils.date.TimeService; +import io.nuls.core.utils.log.BlockLog; +import io.nuls.core.utils.log.Log; +import io.nuls.core.utils.param.AssertUtil; +import io.nuls.core.utils.spring.lite.annotation.Autowired; +import io.nuls.core.utils.str.StringUtils; +import io.nuls.core.validate.ValidateResult; +import io.nuls.db.dao.*; +import io.nuls.db.entity.*; +import io.nuls.db.transactional.annotation.DbSession; +import io.nuls.event.bus.service.intf.EventBroadcaster; +import io.nuls.ledger.constant.LedgerConstant; +import io.nuls.ledger.entity.*; +import io.nuls.ledger.entity.params.Coin; +import io.nuls.ledger.entity.params.CoinTransferData; +import io.nuls.ledger.entity.params.OperationType; +import io.nuls.ledger.entity.tx.AbstractCoinTransaction; +import io.nuls.ledger.entity.tx.LockNulsTransaction; +import io.nuls.ledger.entity.tx.TransferTransaction; +import io.nuls.ledger.service.intf.LedgerService; +import io.nuls.ledger.util.UtxoTransactionTool; +import io.nuls.ledger.util.UtxoTransferTool; +import io.nuls.protocol.constant.TransactionConstant; +import io.nuls.protocol.constant.TxStatusEnum; +import io.nuls.protocol.context.NulsContext; +import io.nuls.protocol.event.TransactionEvent; +import io.nuls.protocol.model.Block; +import io.nuls.protocol.model.Na; +import io.nuls.protocol.model.NulsDigestData; +import io.nuls.protocol.model.Transaction; +import io.nuls.protocol.service.intf.TransactionService; +import io.nuls.protocol.utils.TransactionManager; + +import java.io.IOException; +import java.util.*; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +/** + * @author Niels + * @date 2017/11/13 + */ +public class UtxoLedgerServiceImpl implements LedgerService { + + @Autowired + private TransactionDataService txDao; + @Autowired + TransactionLocalDataService localTxDao; + @Autowired + private UtxoInputDataService inputDataService; + @Autowired + private UtxoOutputDataService outputDataService; + @Autowired + private EventBroadcaster eventBroadcaster; + @Autowired + private BlockHeaderService blockHeaderDao; + @Autowired + private TxAccountRelationDataService relationDataService; + + private LedgerCacheService ledgerCacheService = LedgerCacheService.getInstance(); + + private Lock lock = new ReentrantLock(); + + @Override + public Transaction getTx(NulsDigestData hash) { + TransactionLocalPo localPo = localTxDao.get(hash.getDigestHex()); + if (localPo != null) { + try { + Transaction tx = UtxoTransferTool.toTransaction(localPo); + return tx; + } catch (Exception e) { + Log.error(e); + } + } + TransactionPo po = txDao.get(hash.getDigestHex()); + if (null == po) { + return null; + } + try { + Transaction tx = UtxoTransferTool.toTransaction(po); + return tx; + } catch (Exception e) { + Log.error(e); + } + return null; + } + + @Override + public Transaction getTx(String fromHash, int fromIndex) { + UtxoInputPo inputPo = inputDataService.getByFromHash(fromHash, fromIndex); + if (inputPo == null) { + return null; + } + TransactionPo po = txDao.get(inputPo.getTxHash()); + try { + return UtxoTransferTool.toTransaction(po); + } catch (Exception e) { + Log.error(e); + } + return null; + } + + @Override + public List getTxList(String address, int txType) throws Exception { + if (StringUtils.isBlank(address) && txType == 0) { + throw new NulsRuntimeException(ErrorCode.PARAMETER_ERROR); + } + List txList = new ArrayList<>(); + + if (StringUtils.isNotBlank(address) && NulsContext.LOCAL_ADDRESS_LIST.contains(address)) { + List poList = localTxDao.getTxs(null, address, txType, 0, 0); + for (TransactionLocalPo po : poList) { + txList.add(UtxoTransferTool.toTransaction(po)); + } + } else { + List poList = txDao.getTxs(null, address, txType, 0, 0); + for (TransactionPo po : poList) { + txList.add(UtxoTransferTool.toTransaction(po)); + } + } + return txList; + } + + @Override + public long getTxCount(Long blockHeight, String address, int txType) throws Exception { + long count = 0; + boolean isLocal = NulsContext.LOCAL_ADDRESS_LIST.contains(address); + if (isLocal) { + count = localTxDao.getTxsCount(blockHeight, address, txType); + } else { + count = txDao.getTxsCount(blockHeight, address, txType); + } + return count; + } + + @Override + public List getTxList(Long blockHeight, String address, int txType, int pageNumber, int pageSize) throws Exception { + List txList = null; + if (StringUtils.isNotBlank(address) && NulsContext.LOCAL_ADDRESS_LIST.contains(address)) { + txList = getLocalTxList(blockHeight, address, txType, pageNumber, pageSize); + } else { + txList = new ArrayList<>(); + List poList; + poList = txDao.getTxs(blockHeight, address, txType, pageNumber, pageSize); + for (TransactionPo po : poList) { + txList.add(UtxoTransferTool.toTransaction(po)); + } + } + return txList; + } + + public List getLocalTxList(Long blockHeight, String address, int txType, int pageNumber, int pageSize) throws Exception { + List txList = new ArrayList<>(); + List poList = localTxDao.getTxs(blockHeight, address, txType, pageNumber, pageSize); + for (TransactionLocalPo po : poList) { + txList.add(UtxoTransferTool.toTransaction(po)); + } + + List localTx = getWaitingTxList(); + Map outputMap = new HashMap<>(); + for (Transaction tx : localTx) { + AbstractCoinTransaction transaction = (AbstractCoinTransaction) tx; + UtxoData utxoData = (UtxoData) transaction.getCoinData(); + + for (UtxoOutput output : utxoData.getOutputs()) { + outputMap.put(output.getKey(), output); + } + } + for (Transaction tx : txList) { + if (!(tx instanceof AbstractCoinTransaction)) { + continue; + } + AbstractCoinTransaction transaction = (AbstractCoinTransaction) tx; + UtxoData utxoData = (UtxoData) transaction.getCoinData(); + for (UtxoInput input : utxoData.getInputs()) { + if (input.getFrom() == null) { + if (outputMap.containsKey(input.getKey())) { + input.setFrom(outputMap.get(input.getKey())); + } + } + } + } + return txList; + } + + @Override + public List getTxList(String blockHash) throws Exception { + List txList = new ArrayList<>(); + BlockHeaderPo header = blockHeaderDao.getHeader(blockHash); + if (header == null) { + return txList; + } + List poList = txDao.getTxs(header.getHeight()); + if (null == poList || poList.isEmpty()) { + return txList; + } + for (TransactionPo po : poList) { + txList.add(UtxoTransferTool.toTransaction(po)); + } + return txList; + } + + @Override + public List getTxList(long startHeight, long endHeight) throws Exception { + List txList = new ArrayList<>(); + List poList = txDao.getTxs(startHeight, endHeight); + for (TransactionPo po : poList) { + txList.add(UtxoTransferTool.toTransaction(po)); + } + return txList; + } + + @Override + public List getTxList(long height) throws Exception { + List txList = new ArrayList<>(); + List poList = txDao.getTxs(height); + for (TransactionPo po : poList) { + txList.add(UtxoTransferTool.toTransaction(po)); + } + return txList; + } + + @Override + public Page getTxList(Long height, int type, int pageNum, int pageSize) throws Exception { + Page poPage = txDao.getTxs(height, type, pageNum, pageSize); + Page txPage = new Page<>(poPage); + List txList = new ArrayList<>(); + for (TransactionPo po : poPage.getList()) { + txList.add(UtxoTransferTool.toTransaction(po)); + } + txPage.setList(txList); + return txPage; + } + + @Override + public Balance getBalance(String address) { + Balance balance = ledgerCacheService.getBalance(address); + if (balance == null) { + return null; + } + long usable = 0; + long locked = 0; + + List unSpends = ledgerCacheService.getUnSpends(address); + UtxoCoinManager.getInstance().filterUtxoByLocalTxs(address, unSpends); + + for (UtxoOutput output : unSpends) { + if (output.isLocked(NulsContext.getInstance().getBestHeight())) { + locked += output.getValue(); + } else { + usable += output.getValue(); + } + } + + balance.setUsable(Na.valueOf(usable)); + balance.setLocked(Na.valueOf(locked)); + balance.setBalance(Na.valueOf(usable + locked)); + return balance; + } + + @Override + public Balance getBalances() { + Balance balances = new Balance(); + for (String address : NulsContext.LOCAL_ADDRESS_LIST) { + Balance balance = getBalance(address); + if (balance == null) { + continue; + } + balances.setLocked(balances.getLocked().add(balance.getLocked())); + balances.setUsable(balances.getUsable().add(balance.getUsable())); + } + balances.setBalance(balances.getLocked().add(balances.getUsable())); + return balances; + } + +// public Balance getBalance(String address) { +// if (StringUtils.isNotBlank(address)) { +// Balance balance = ledgerCacheService.getBalance(address); +// return balance; +// } else { +// Balance allBalance = new Balance(); +// long usable = 0; +// long locked = 0; +// for (String addr : NulsContext.LOCAL_ADDRESS_LIST) { +// Balance balance = ledgerCacheService.getBalance(addr); +// if (null != balance) { +// usable += balance.getUsable().getValue(); +// locked += balance.getLocked().getValue(); +// } +// } +// allBalance.setUsable(Na.valueOf(usable)); +// allBalance.setLocked(Na.valueOf(locked)); +// allBalance.setBalance(Na.valueOf(usable + locked)); +// return allBalance; +// } +// } + + @Override + public Na getTxFee(int txType) { + Block bestBlock = NulsContext.getInstance().getBestBlock(); + if (null == bestBlock) { + return LedgerConstant.TRANSACTION_FEE; + } + long blockHeight = bestBlock.getHeader().getHeight(); + if (txType == TransactionConstant.TX_TYPE_COIN_BASE || + txType == TransactionConstant.TX_TYPE_SMALL_CHANGE + || txType == TransactionConstant.TX_TYPE_CANCEL_DEPOSIT + ) { + return Na.ZERO; + } + long x = blockHeight / LedgerConstant.BLOCK_COUNT_OF_YEAR + 1; + return LedgerConstant.TRANSACTION_FEE.div(x); + } + + @Override + public Result transfer(String address, String password, String toAddress, Na amount, String remark) { + CoinTransferData coinData = new CoinTransferData(OperationType.TRANSFER, amount, address, toAddress, getTxFee(TransactionConstant.TX_TYPE_TRANSFER)); + return transfer(coinData, password, remark); + } + + private Result transfer(CoinTransferData coinData, String password, String remark) { + TransferTransaction tx = null; + try { + tx = UtxoTransactionTool.getInstance().createTransferTx(coinData, password, remark); + ValidateResult result = this.verifyTx(tx, this.getWaitingTxList()); + if (result.isFailed()) { + throw new NulsException(result.getErrorCode()); + } + this.saveLocalTx(tx); + TransactionEvent event = new TransactionEvent(); + event.setEventBody(tx); + eventBroadcaster.publishToLocal(event); + } catch (Exception e) { + Log.error(e); + return new Result(false, e.getMessage()); + } + return new Result(true, "OK", tx.getHash().getDigestHex()); + } + + @Override + public Result transfer(List addressList, String password, String toAddress, Na amount, String remark) { + CoinTransferData coinData = new CoinTransferData(OperationType.TRANSFER, amount, addressList, toAddress, getTxFee(TransactionConstant.TX_TYPE_TRANSFER)); + return transfer(coinData, password, remark); + } + + @Override + public Result lock(String address, String password, Na amount, long unlockTime, String remark) { + LockNulsTransaction tx = null; + try { + CoinTransferData coinData = new CoinTransferData(OperationType.LOCK, amount, address, getTxFee(TransactionConstant.TX_TYPE_LOCK)); + coinData.addTo(new Coin(address, amount, unlockTime, 0)); + tx = UtxoTransactionTool.getInstance().createLockNulsTx(coinData, password, remark); + + tx.verify(); + TransactionEvent event = new TransactionEvent(); + event.setEventBody(tx); + eventBroadcaster.publishToLocal(event); + + } catch (Exception e) { + Log.error(e); + try { + rollbackTx(tx, null); + } catch (NulsException e1) { + Log.error(e1); + } + return new Result(false, e.getMessage()); + } + + return new Result(true, "OK", tx.getHash().getDigestHex()); + } + + @Override + @DbSession + public void saveTxList(List txList, long blockHeight) throws IOException { + lock.lock(); + try { + boolean isMine; + List poList = new ArrayList<>(); + List localPoList = new ArrayList<>(); + for (int i = 0; i < txList.size(); i++) { + isMine = false; + Transaction tx = txList.get(i); + TransactionPo po = UtxoTransferTool.toTransactionPojo(tx, blockHeight); + poList.add(po); + if (tx.getType() == TransactionConstant.TX_TYPE_CANCEL_DEPOSIT) { + TransactionLocalPo localPo = localTxDao.get(tx.getHash().getDigestHex()); + if (localPo != null) { + localPo.setTxStatus(TransactionLocalPo.CONFIRM); + localPo.setBlockHeight(tx.getBlockHeight()); + localTxDao.update(localPo); + continue; + } + } else { + isMine = this.checkTxIsMine(tx); + } + if (isMine) { + TransactionLocalPo localPo = UtxoTransferTool.toLocalTransactionPojo(tx); + localPoList.add(localPo); + } + } + int successCount = txDao.save(poList); + if (successCount != poList.size()) { + throw new NulsRuntimeException(ErrorCode.FAILED, "save block txs fail , totalCount : " + poList.size() + " , successCount : " + successCount); + } + + for (TransactionLocalPo localPo : localPoList) { + TransactionLocalPo po = localTxDao.get(localPo.getHash()); + localPo.setTxStatus(TransactionLocalPo.CONFIRM); + if (po != null) { + localTxDao.update(localPo); + } else { + localTxDao.save(localPo); + } + } + } catch (Exception e) { + Log.error(e); + throw e; + } finally { + lock.unlock(); + } + } + + @Override + public boolean saveLocalTx(Transaction tx) throws IOException { + try { + ValidateResult validateResult = this.conflictDetectTx(tx, this.getWaitingTxList()); + if (validateResult.isFailed()) { + throw new NulsRuntimeException(validateResult.getErrorCode(), validateResult.getMessage()); + } + } catch (Exception e) { + Log.error(e); + throw new NulsRuntimeException(e); + } + TransactionLocalPo localPo = UtxoTransferTool.toLocalTransactionPojo(tx); + localPo.setTxStatus(TransactionLocalPo.UNCONFIRM); + localTxDao.save(localPo); + // save relation + if (tx instanceof AbstractCoinTransaction) { + AbstractCoinTransaction abstractTx = (AbstractCoinTransaction) tx; + UtxoData utxoData = (UtxoData) abstractTx.getCoinData(); + if (utxoData.getInputs() != null && !utxoData.getInputs().isEmpty()) { + UtxoInput input = utxoData.getInputs().get(0); + UtxoOutput output = input.getFrom(); + TxAccountRelationPo relationPo = new TxAccountRelationPo(); + relationPo.setTxHash(tx.getHash().getDigestHex()); + relationPo.setAddress(output.getAddress()); + relationDataService.save(relationPo); + } + } +// if (tx instanceof AbstractCoinTransaction) { +// AbstractCoinTransaction abstractTx = (AbstractCoinTransaction) tx; +// UtxoData utxoData = (UtxoData) abstractTx.getCoinData(); +// +// for (UtxoOutput output : utxoData.getOutputs()) { +// if (output.isUsable() && NulsContext.LOCAL_ADDRESS_LIST.contains(output.getAddress())) { +// output.setTxHash(tx.getHash()); +// ledgerCacheService.putUtxo(output.getKey(), output, false); +// } +// } +// } + return true; + } + + @Override + @DbSession + public void removeLocalTxs(String address) { + List relationList = relationDataService.selectByAddress(address); + for (TxAccountRelationPo po : relationList) { + localTxDao.delete(po.getTxHash()); + } + } + + @Override + @DbSession + public void saveTxInLocal(String address) { + List poList = txDao.getTxs(null, address, 0, 0, 0); + if (poList.isEmpty()) { + return; + } + List localPoList = new ArrayList<>(); + + for (TransactionPo po : poList) { + TransactionLocalPo localPo = localTxDao.get(po.getHash()); + if (localPo != null) { + continue; + } + + localPo = new TransactionLocalPo(po, Transaction.TRANSFER_RECEIVE); + for (UtxoInputPo inputPo : po.getInputs()) { + if (inputPo.getFromOutPut().getAddress().equals(address)) { + localPo.setTransferType(Transaction.TRANSFER_SEND); + break; + } + } + localPo.setTxStatus(TransactionLocalPo.CONFIRM); + localTxDao.save(localPo); + //localPoList.add(localPo); + } + //localTxDao.save(localPoList); + } + + + @Override + public boolean checkTxIsMine(Transaction tx) { + if (tx instanceof AbstractCoinTransaction) { + return UtxoTransactionTool.getInstance().isMine((AbstractCoinTransaction) tx); + } + return false; + } + + @Override + public boolean checkTxIsMine(Transaction tx, String address) { + if (tx instanceof AbstractCoinTransaction) { + return UtxoTransactionTool.getInstance().isMine((AbstractCoinTransaction) tx, address); + } + return false; + } + + @Override + public boolean checkTxIsMySend(Transaction tx) { + if (tx instanceof AbstractCoinTransaction) { + return UtxoTransactionTool.getInstance().isMySend((AbstractCoinTransaction) tx); + } + return false; + } + + @Override + public boolean checkTxIsMySend(Transaction tx, String address) { + if (tx instanceof AbstractCoinTransaction) { + return UtxoTransactionTool.getInstance().isMySend((AbstractCoinTransaction) tx, address); + } + return false; + } + + @Override + + public void rollbackTx(Transaction tx, Block block) throws NulsException { + AssertUtil.canNotEmpty(tx, ErrorCode.NULL_PARAMETER); + BlockLog.debug("rollback tx:{}", tx.getHash()); + List serviceList = getServiceList(tx.getClass()); + for (TransactionService service : serviceList) { + service.onRollback(tx, block); + } + tx.setStatus(TxStatusEnum.UNCONFIRM); + } + + @Override + @DbSession + public void commitTx(Transaction tx, Block block) throws NulsException { + AssertUtil.canNotEmpty(tx, ErrorCode.NULL_PARAMETER); +// if (tx.getStatus() != TxStatusEnum.AGREED) { +// return; +// } + List serviceList = getServiceList(tx.getClass()); + List commitedServiceList = new ArrayList<>(); + try { + for (TransactionService service : serviceList) { + service.onCommit(tx, block); + commitedServiceList.add(service); + } + } catch (Exception e) { + Log.error(e); + for (int i = commitedServiceList.size() - 1; i >= 0; i--) { + TransactionService service = commitedServiceList.get(i); + service.onRollback(tx, block); + } + throw e; + } + tx.setStatus(TxStatusEnum.CONFIRMED); + } + + @Override + public ValidateResult conflictDetectTx(Transaction tx, List txList) throws NulsException { + AssertUtil.canNotEmpty(tx, ErrorCode.NULL_PARAMETER); + if (null == txList || txList.isEmpty()) { + return ValidateResult.getSuccessResult(); + } + List serviceList = getServiceList(tx.getClass()); + ValidateResult result = null; + + for (TransactionService service : serviceList) { + result = service.conflictDetect(tx, txList); + if (result.isFailed()) { + break; + } + } + + return result; + } + + @Override + public void deleteTx(Transaction tx) { + txDao.delete(tx.getHash().getDigestHex()); + } + + @Override + @DbSession + public void deleteTx(long blockHeight) { + List txList = txDao.getTxs(blockHeight); + for (TransactionPo tx : txList) { + txDao.delete(tx.getHash()); + TransactionLocalPo localPo = localTxDao.get(tx.getHash()); + if (localPo != null) { + if (localPo.getType() == TransactionConstant.TX_TYPE_COIN_BASE) { + localTxDao.delete(localPo.getHash()); + } + localPo.setTxStatus(TransactionLocalPo.UNCONFIRM); + localTxDao.update(localPo); + } + } + } + + @Override + public long getBlockReward(long blockHeight) { + return outputDataService.getRewardByBlockHeight(blockHeight); + } + + @Override + public Long getBlockFee(Long blockHeight) { + return txDao.getFeeByHeight(blockHeight); + } + + @Override + public long getLastDayTimeReward() { + return outputDataService.getLastDayTimeReward(); + } + + @Override + public long getAccountReward(String address, long lastTime) { + return outputDataService.getAccountReward(address, lastTime); + } + + @Override + public long getAgentReward(String address, int type) { + return outputDataService.getAgentReward(address, type); + } + + @Override + public void unlockTxApprove(String txHash) { +// boolean b = true; +// int index = 0; +// while (b) { +// UtxoOutput output = ledgerCacheService.getUtxo(txHash + "-" + index); +// if (output != null) { +// if (OutPutStatusEnum.UTXO_CONFIRMED_CONSENSUS_LOCK == output.getStatus()) { +// output.setStatus(OutPutStatusEnum.UTXO_CONFIRMED_UNSPENT); +// } +// UtxoTransactionTool.getInstance().calcBalance(output.getAddress(), false); +// index++; +// } else { +// b = false; +// } +// } + } + + @Override + @DbSession + public void unlockTxSave(String txHash) { + Log.debug("-------------- exit agent unlockTxSave ------------------txHash:" + txHash); + outputDataService.unlockTxOutput(txHash); + String key = txHash + "-" + 0; + UtxoOutput output = ledgerCacheService.getUtxo(key); + output.setStatus(OutPutStatusEnum.UTXO_UNSPENT); + ledgerCacheService.putUtxo(key, output, true); +// UtxoTransactionTool.getInstance().calcBalance(output.getAddress(), false); + } + + @Override + @DbSession + public void unlockTxRollback(String txHash) { + Log.debug("-------------- exit agent unlockTxRollback ------------------txHash:" + txHash); + outputDataService.lockTxOutput(txHash); + Map keyMap = new HashMap<>(); + + keyMap.put("txHash", txHash); + keyMap.put("outIndex", 0); + UtxoOutputPo po = outputDataService.get(keyMap); + if (po != null) { + po.setStatus(UtxoOutputPo.LOCKED); + outputDataService.update(po); + UtxoOutput output = UtxoTransferTool.toOutput(po); + ledgerCacheService.putUtxo(output.getKey(), output, true); + } + } + + @Override + public Page getLockUtxo(String address, Integer pageNumber, Integer pageSize) { + List lockOutputs = new ArrayList<>(); + long count = outputDataService.getLockUtxoCount(address, TimeService.currentTimeMillis(), NulsContext.getInstance().getBestHeight()); + List localTxs = UtxoCoinManager.getInstance().getLocalUnConfirmTxs(); + for (int i = localTxs.size() - 1; i >= 0; i--) { + AbstractCoinTransaction tx = localTxs.get(i); + UtxoData utxoData = (UtxoData) tx.getCoinData(); + for (int j = utxoData.getOutputs().size() - 1; j >= 0; j--) { + UtxoOutput output = utxoData.getOutputs().get(j); + if (output.isLocked(NulsContext.getInstance().getBestHeight()) && NulsContext.LOCAL_ADDRESS_LIST.contains(output.getAddress())) { + output.setCreateTime(tx.getTime()); + output.setTxType(tx.getType()); + lockOutputs.add(output); + } + } + } + + int start = (pageNumber - 1) * pageSize; + if (lockOutputs.size() >= start + pageSize) { + lockOutputs = lockOutputs.subList(start, start + pageSize); + Page page = new Page(pageNumber, pageSize); + page.setList(lockOutputs); + page.setTotal(count); + return page; + } else if (start < lockOutputs.size()) { + lockOutputs = lockOutputs.subList(start, lockOutputs.size()); + start = 0; + pageSize = pageSize - lockOutputs.size(); + } else { + start = start - lockOutputs.size(); + } + + Collections.reverse(lockOutputs); + List poList = outputDataService.getLockUtxo(address, TimeService.currentTimeMillis(), NulsContext.getInstance().getBestHeight(), start, pageSize); + for (UtxoOutputPo po : poList) { + lockOutputs.add(UtxoTransferTool.toOutput(po)); + } + Page page = new Page(pageNumber, pageSize); + page.setTotal(count); + page.setList(lockOutputs); + return page; + } + + @Override + public Balance getAccountUtxo(String address, Na amount) { + UtxoBalance balance = new UtxoBalance(); + List unSpends = UtxoCoinManager.getInstance().getAccountUnSpend(address, amount); + balance.setUnSpends(unSpends); + return balance; + } + + public List getServiceList(Class txClass) { + List list = new ArrayList<>(); + Class clazz = txClass; + while (!clazz.equals(Transaction.class)) { + TransactionService txService = TransactionManager.getService(clazz); + if (null != txService) { + list.add(0, txService); + } + clazz = clazz.getSuperclass(); + } + return list; + } + + @Override + public void resetLedgerCache() { +// ledgerCacheService.clear(); +// UtxoCoinManager.getInstance().cacheAllUnSpendUtxo(); + } + + @Override + public List getWaitingTxList() throws NulsException { + List poList = localTxDao.getUnConfirmTxs(); + List txList = new ArrayList<>(); + for (TransactionLocalPo po : poList) { + Transaction tx = UtxoTransferTool.toTransaction(po); + txList.add(tx); + } + return txList; + } + + @Override + @DbSession + public void deleteLocalTx(String txHash) { + this.localTxDao.delete(txHash); + } + + @Override + public ValidateResult verifyTx(Transaction tx, List txList) { + ValidateResult result = tx.verify(); + if (result.isFailed() && result.getErrorCode() == ErrorCode.ORPHAN_TX) { + AbstractCoinTransaction coinTx = (AbstractCoinTransaction) tx; + result = coinTx.getCoinDataProvider().verifyCoinData(coinTx, txList); + if (result.isSuccess()) { + coinTx.setSkipInputValidator(true); + result = coinTx.verify(); + coinTx.setSkipInputValidator(false); + } + } + return result; + } + + @Override + public void verifyTxWithException(Transaction tx, List txList) { + ValidateResult result = this.verifyTx(tx, txList); + if (result.isFailed()) { + throw new NulsRuntimeException(result.getErrorCode(), result.getMessage()); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `io.nuls.ledger.service.impl.UtxoLedgerServiceImpl.getTx` indirectly reads without synchronization from `n$15.io.nuls.protocol.context.NulsContext.bestBlock`. Potentially races with write in method `UtxoLedgerServiceImpl.saveTxList(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Transaction UtxoLedgerServiceImpl.getTx(NulsDigestData) + +### Procedure Id: +io.nuls.ledger.service.impl.UtxoLedgerServiceImpl.getTx(io.nuls.protocol.model.NulsDigestData):io.nu.727188f4049803f29f5415940d055783 + +### File: +ledger-impl/src/main/java/io/nuls/ledger/service/impl/UtxoLedgerServiceImpl.java + +### Key: +UtxoLedgerServiceImpl.java|getTx|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +b9e7d9af29ae9868f35da501c3f179d1 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-3989/instruction.md b/inferredbugs-3989/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..68b2ab39317b66c34a38def841e186131d572abb --- /dev/null +++ b/inferredbugs-3989/instruction.md @@ -0,0 +1,277 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nuls +**Bug ID:** 51 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * MIT License + * + * Copyright (c) 2017-2018 nuls.io + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.nuls.consensus.utils; + +import io.nuls.consensus.cache.manager.block.TemporaryCacheManager; +import io.nuls.consensus.cache.manager.tx.ReceivedTxCacheManager; +import io.nuls.consensus.entity.GetSmallBlockParam; +import io.nuls.consensus.entity.GetTxGroupParam; +import io.nuls.consensus.entity.RedPunishData; +import io.nuls.consensus.event.GetSmallBlockRequest; +import io.nuls.consensus.event.GetTxGroupRequest; +import io.nuls.consensus.event.notice.AssembledBlockNotice; +import io.nuls.consensus.manager.BlockManager; +import io.nuls.consensus.thread.ConsensusMeetingRunner; +import io.nuls.consensus.thread.DataDownloadThread; +import io.nuls.core.chain.entity.*; +import io.nuls.core.constant.ErrorCode; +import io.nuls.core.constant.NulsConstant; +import io.nuls.core.constant.SeverityLevelEnum; +import io.nuls.core.context.NulsContext; +import io.nuls.core.exception.NulsRuntimeException; +import io.nuls.core.thread.manager.TaskManager; +import io.nuls.core.utils.str.StringUtils; +import io.nuls.core.validate.ValidateResult; +import io.nuls.db.entity.NodePo; +import io.nuls.event.bus.service.intf.EventBroadcaster; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author Niels + * @date 2018/1/12 + */ +public class DownloadDataUtils { + + private static final DownloadDataUtils INSTANCE = new DownloadDataUtils(); + + private DownloadDataUtils() { + TaskManager.createAndRunThread(NulsConstant.MODULE_ID_CONSENSUS, "data-download-consensu", new DataDownloadThread()); + } + + public static DownloadDataUtils getInstance() { + return INSTANCE; + } + + private EventBroadcaster eventBroadcaster = NulsContext.getServiceBean(EventBroadcaster.class); + private ReceivedTxCacheManager txCacheManager = ReceivedTxCacheManager.getInstance(); + private TemporaryCacheManager temporaryCacheManager = TemporaryCacheManager.getInstance(); + private BlockManager blockManager = BlockManager.getInstance(); + + + private final Map smbRequest = new HashMap<>(); + private final Map tgRequest = new HashMap<>(); + private final Map smbRequestCount = new HashMap<>(); + private final Map tgRequestCount = new HashMap<>(); + + public void requestSmallBlock(NulsDigestData blockHash, String nodeId) { + GetSmallBlockRequest request = new GetSmallBlockRequest(); + GetSmallBlockParam param = new GetSmallBlockParam(); + param.setBlockHash(blockHash); + request.setEventBody(param); + smbRequest.put(blockHash.getDigestHex(), System.currentTimeMillis()); + Integer value = smbRequestCount.get(blockHash.getDigestHex()); + if (value == null) { + value = 0; + } + smbRequestCount.put(blockHash.getDigestHex(), 1 + value); + if (StringUtils.isBlank(nodeId)) { + eventBroadcaster.broadcastAndCache(request, false); + } else { + eventBroadcaster.sendToNode(request, nodeId); + } + } + + public void requestTxGroup(NulsDigestData blockHash, String nodeId) { + GetTxGroupRequest request = new GetTxGroupRequest(); + GetTxGroupParam data = new GetTxGroupParam(); + data.setBlockHash(blockHash); + List txHashList = new ArrayList<>(); + + SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex()); + for (NulsDigestData txHash : smb.getTxHashList()) { + boolean exist = txCacheManager.txExist(txHash); + if (!exist) { + txHashList.add(txHash); + } + } + if (txHashList.isEmpty()) { + BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex()); + if (null == header) { + return; + } + Block block = new Block(); + block.setHeader(header); + List txs = new ArrayList<>(); + for (NulsDigestData txHash : smb.getTxHashList()) { + Transaction tx = txCacheManager.getTx(txHash); + if (null == tx) { + throw new NulsRuntimeException(ErrorCode.DATA_ERROR); + } + txs.add(tx); + } + block.setTxs(txs); + ValidateResult vResult = block.verify(); + if (null == vResult || vResult.isFailed()) { + if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) { + RedPunishData redPunishData = vResult.getObject(); + ConsensusMeetingRunner.putPunishData(redPunishData); + } + return; + } + blockManager.addBlock(block, false,nodeId); + AssembledBlockNotice notice = new AssembledBlockNotice(); + notice.setEventBody(header); + eventBroadcaster.publishToLocal(notice); + return; + } + data.setTxHashList(txHashList); + request.setEventBody(data); + tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis()); + Integer value = tgRequestCount.get(blockHash.getDigestHex()); + if (null == value) { + value = 0; + } + tgRequestCount.put(blockHash.getDigestHex(), 1 + value); + if (StringUtils.isBlank(nodeId)) { + eventBroadcaster.broadcastAndCache(request, false); + } else { + eventBroadcaster.sendToNode(request, nodeId); + } + } + + public void removeSmallBlock(String blockHash) { + smbRequest.remove(blockHash); + smbRequestCount.remove(blockHash); + } + + public void removeTxGroup(String blockHash) { + tgRequest.remove(blockHash); + tgRequestCount.remove(blockHash); + } + + public void remove(String blockHash) { + smbRequest.remove(blockHash); + tgRequest.remove(blockHash); + smbRequestCount.remove(blockHash); + tgRequestCount.remove(blockHash); + } + + public void reRequest() { + this.reRequestSmallBlock(); + this.reReqesetTxGroup(); + } + + private void reReqesetTxGroup() { + for (String hash : this.tgRequest.keySet()) { + Long time = tgRequest.get(hash); + if (null != time && (System.currentTimeMillis() - time) >= 1000L) { + this.requestTxGroup(NulsDigestData.fromDigestHex(hash), null); + } + if (tgRequestCount.get(hash) >= 10) { + this.removeTxGroup(hash); + } + } + + } + + private void reRequestSmallBlock() { + for (String hash : this.tgRequest.keySet()) { + Long time = tgRequest.get(hash); + if (null != time && (System.currentTimeMillis() - time) >= 1000L) { + this.requestSmallBlock(NulsDigestData.fromDigestHex(hash), null); + } + if (smbRequestCount.get(hash) >= 10) { + this.removeTxGroup(hash); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `redPunishData` last assigned on line 131 could be null and is dereferenced by call to `putPunishData(...)` at line 132. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DownloadDataUtils.requestTxGroup(NulsDigestData,String) + +### Procedure Id: +io.nuls.consensus.utils.DownloadDataUtils.requestTxGroup(io.nuls.core.chain.entity.NulsDigestData,ja.643614b7508a701ef6b3efa267b81d8c + +### File: +consensus-impl/src/main/java/io/nuls/consensus/utils/DownloadDataUtils.java + +### Key: +DownloadDataUtils.java|requestTxGroup|NULL_DEREFERENCE + +### Node Key: +dc4c40cbb2bc94519d4917c9db2506da + +### Hash: +9c63a8c963d324c2b4fd7aefa6fff7ad + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-4013/instruction.md b/inferredbugs-4013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..150f428e5571cd1327198e3ceaaf0636292ea907 --- /dev/null +++ b/inferredbugs-4013/instruction.md @@ -0,0 +1,292 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nuls +**Bug ID:** 87 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * MIT License + *

    + * Copyright (c) 2017-2018 nuls.io + *

    + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

    + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + *

    + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.nuls.consensus.entity.block; + +import io.nuls.consensus.constant.PocConsensusConstant; +import io.nuls.core.chain.entity.BlockHeader; +import io.nuls.core.chain.entity.NulsDigestData; +import io.nuls.core.chain.intf.NulsCloneable; +import io.nuls.core.utils.str.StringUtils; + +import java.util.*; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.locks.ReentrantLock; + +/** + * @author Niels + * @date 2018/1/11 + */ +public class BlockHeaderChain implements NulsCloneable { + private final String id; + private List headerDigestList = new CopyOnWriteArrayList<>(); + private final ReentrantLock lock = new ReentrantLock(); + private HeaderDigest lastHd; + + public BlockHeaderChain() { + this.id = StringUtils.getNewUUID(); + } + + public BlockHeaderChain getBifurcateChain(BlockHeader header) { + int index = indexOf(header.getPreHash().getDigestHex(), header.getHeight() - 1, header.getTime()); + if (index == -1) { + return new BlockHeaderChain(); + } + List list = new CopyOnWriteArrayList<>(headerDigestList.subList(0, index)); + list.add(new HeaderDigest(header.getHash().getDigestHex(), header.getHeight(), header.getTime())); + BlockHeaderChain chain = new BlockHeaderChain(); + chain.setHeaderDigestList(list); + return chain; + } + + private int indexOf(String hash, long height, long time) { + HeaderDigest hd = new HeaderDigest(hash, height, time); + return headerDigestList.indexOf(hd); + } + + public boolean addHeader(BlockHeader header) { + lock.lock(); + if (null != lastHd && !this.lastHd.getHash().equals(header.getPreHash().getDigestHex())) { + return false; + } + HeaderDigest newHd = new HeaderDigest(header.getHash().getDigestHex(), header.getHeight(), header.getTime()); + headerDigestList.add(newHd); + this.lastHd = newHd; + lock.unlock(); + return true; + } + + public void destroy() { + headerDigestList.clear(); + } + + + public void removeHeaderDigest(String hashHex) { + for (HeaderDigest hd : headerDigestList) { + if (hd.getHash().equals(hashHex)) { + removeHeaderDigest(hd.getHeight()); + return; + } + } + } + + private void removeHeaderDigest(long height) { + for (int i = headerDigestList.size() - 1; i >= 0; i--) { + HeaderDigest headerDigest = headerDigestList.get(i); + if (headerDigest.getHeight() <= height) { + headerDigestList.remove(headerDigest); + } + } + } + + public void rollbackHeaderDigest(String hash) { + for (int i = 0; i < headerDigestList.size(); i++) { + HeaderDigest headerDigest = headerDigestList.get(i); + if (headerDigest.getHash().equals(hash)) { + headerDigestList.remove(headerDigest); + for (int x = i + 1; x < headerDigestList.size(); x++) { + headerDigestList.remove(x); + } + this.lastHd = null; + break; + } + } + } + + public HeaderDigest rollback() { + lock.lock(); + if (headerDigestList.isEmpty()) { + lock.unlock(); + return null; + } + HeaderDigest headerDigest = headerDigestList.get(headerDigestList.size() - 1); + headerDigestList.remove(headerDigestList.size() - 1); + this.lastHd = null; + lock.unlock(); + return headerDigest; + } + + public int size() { + return headerDigestList.size(); + } + + @Override + public Object copy() { + return this; + } + + public List getHeaderDigestList() { + return headerDigestList; + } + + public void setHeaderDigestList(List headerDigestList) { + this.headerDigestList = headerDigestList; + } + + public HeaderDigest getHeaderDigest(long height) { + for (int i = 0; i < this.headerDigestList.size(); i++) { + HeaderDigest hd = this.headerDigestList.get(i); + if (null == hd) { + continue; + } + if (hd.getHeight() == height) { + return hd; + } + } + return null; + } + + public HeaderDigest getHeaderDigest(String hashHex) { + for (int i = 0; i < this.headerDigestList.size(); i++) { + HeaderDigest hd = this.headerDigestList.get(i); + if (null == hd) { + continue; + } + if (hd.getHash().equals(hashHex)) { + return hd; + } + } + return null; + } + + public boolean contains(HeaderDigest hd) { + return headerDigestList.contains(hd); + } + + public boolean contains(BlockHeader header) { + return headerDigestList.contains(new HeaderDigest(header.getHash().getDigestHex(), header.getHeight(), header.getTime())); + } + + @Override + public boolean equals(Object object) { + if (null == object) { + return false; + } + if (!(object instanceof BlockHeaderChain)) { + return false; + } + return this.id.equals(((BlockHeaderChain) object).getId()); + } + + public String getId() { + return id; + } + + public Set getHashSet() { + Set hashSet = new HashSet<>(); + for (HeaderDigest hd : this.headerDigestList) { + hashSet.add(hd.getHash()); + } + return hashSet; + } + + public HeaderDigest getFirstHd() { + HeaderDigest headerDigest = headerDigestList.get(0); + return headerDigest; + } + + public HeaderDigest getLastHd() { + if (null == lastHd) { + List list = new ArrayList<>(headerDigestList); + if(list.size() > 0) { + this.lastHd = list.get(list.size() - 1); + } + } + return lastHd; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `io.nuls.consensus.entity.block.BlockHeaderChain.rollbackHeaderDigest` writes to field `this.io.nuls.consensus.entity.block.BlockHeaderChain.lastHd` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BlockHeaderChain.rollbackHeaderDigest(String) + +### Procedure Id: +io.nuls.consensus.entity.block.BlockHeaderChain.rollbackHeaderDigest(java.lang.String):void.114b34c4bacd85a6d8ea56e43e71fc3c + +### File: +consensus-impl/src/main/java/io/nuls/consensus/entity/block/BlockHeaderChain.java + +### Key: +BlockHeaderChain.java|rollbackHeaderDigest|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +a4b2e8edc615c8cf83a3e6df49b7b44e + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-4103/instruction.md b/inferredbugs-4103/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..127ae4b95fc54dd6c851682aeb9fcd8b41251de8 --- /dev/null +++ b/inferredbugs-4103/instruction.md @@ -0,0 +1,181 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nuls +**Bug ID:** 25 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * MIT License + * + * Copyright (c) 2017-2018 nuls.io + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.nuls.network.module.impl; + + +import io.nuls.core.constant.ErrorCode; +import io.nuls.core.context.NulsContext; +import io.nuls.core.event.EventManager; +import io.nuls.core.exception.NulsRuntimeException; +import io.nuls.core.thread.manager.TaskManager; +import io.nuls.core.utils.cfg.ConfigLoader; +import io.nuls.core.utils.log.Log; +import io.nuls.network.NetworkContext; +import io.nuls.network.constant.NetworkConstant; +import io.nuls.network.message.entity.GetNodeEvent; +import io.nuls.network.message.entity.GetVersionEvent; +import io.nuls.network.message.entity.NodeEvent; +import io.nuls.network.message.entity.VersionEvent; +import io.nuls.network.module.AbstractNetworkModule; +import io.nuls.network.service.NetworkService; +import io.nuls.network.service.impl.NetworkServiceImpl; + +import java.io.IOException; + +/** + * @author vivi + * @date 2017/11/21 + */ +public class NetworkModuleBootstrap extends AbstractNetworkModule { + + private NetworkService networkService; + + @Override + public void init() { + try { + NetworkContext.setNetworkConfig(ConfigLoader.loadProperties(NetworkConstant.NETWORK_PROPERTIES)); + } catch (IOException e) { + Log.error(e); + throw new NulsRuntimeException(ErrorCode.IO_ERROR); + } + this.registerService(NetworkServiceImpl.class); + networkService = NulsContext.getServiceBean(NetworkService.class); + networkService.init(); + this.registerEvent(); + + } + + private void registerEvent() { + EventManager.putEvent(GetVersionEvent.class); + EventManager.putEvent(VersionEvent.class); + EventManager.putEvent(GetNodeEvent.class); + EventManager.putEvent(NodeEvent.class); + } + + @Override + public void start() { + networkService.start(); + } + + @Override + public void shutdown() { + networkService.shutdown(); + } + + @Override + public void destroy() { + shutdown(); + } + + @Override + public String getInfo() { + StringBuilder str = new StringBuilder(); + str.append("\nmoduleName:"); + str.append(getModuleName()); + str.append(",p2p module info:"); + str.append("here is info"); + return str.toString(); + } + + @Override + public int getVersion() { + return 0; + } + + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `NetworkModuleBootstrap.networkService` last assigned on line 63 could be null and is dereferenced at line 64. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NetworkModuleBootstrap.init() + +### Procedure Id: +io.nuls.network.module.impl.NetworkModuleBootstrap.init():void.003cbb4fc1386c5369f5dbe4379e382d + +### File: +network-impl/src/main/java/io/nuls/network/module/impl/NetworkModuleBootstrap.java + +### Key: +NetworkModuleBootstrap.java|init|NULL_DEREFERENCE + +### Node Key: +0e06fee57af576d84f5c655c69ed7f37 + +### Hash: +643d545aaa9851b39f69ea65de8c7a6d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-4104/instruction.md b/inferredbugs-4104/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e54e94c6c01c7bf8f663f210ffcb22b34fe5c19 --- /dev/null +++ b/inferredbugs-4104/instruction.md @@ -0,0 +1,322 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** wetech-admin +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * 文 件 名:WebUtil.java + * 版 权:Copyright 2012 JESHING Tech.Co.Ltd.All Rights Reserved. + * 描 述: + * 修 改 人:王波 + * 修改时间:2014-4-3 + * 修改内容:新增 + */ +package tech.wetech.admin.common.utils; + +import java.util.List; +import java.util.regex.Pattern; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +/** + * Web 工具类 + * + * @author 王波 + * @author 赵卉华 修改为非静态方法, 增加由调用方传入HttpServletRequest的构造方法
    + * 解决在404和500页面, 通过RequestContextHolder.getRequestAttributes()获取Request报空指针的问题 + * @version C01 2014-4-3 + * @since v1.0 + */ +public class WebUtil { + + private final HttpServletRequest request; + + /** + * 实例 + */ + private static final WebUtil instance = new WebUtil(); + + /** + * 构造函数 + */ + private WebUtil() { + this.request = null; + } + + /** + * 构造函数 + */ + public WebUtil(HttpServletRequest request) { + this.request = request; + } + + /** + * 获取实例 + * + * @author 赵卉华 + * @return WebUtil实例 + */ + public static WebUtil getInstance() { + return instance; + } + + /** + * 返回当前请求对象 + * + * @return 当前请求对象 + */ + public HttpServletRequest getRequest() { + if (request != null) { + return request; + } + return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + } + + /** + * 获取 session + * + * @return session;session不存在时创建一个; + */ + public HttpSession getSession() { + return getRequest().getSession(); + } + + /** + * 获取 session + * + * @param create SESSION不存在时是否创建 + * @return session + */ + public HttpSession getSession(boolean create) { + return getRequest().getSession(create); + } + + /** + * 获取 session id + * + * @return session + */ + public String getSessionId() { + HttpSession session = getSession(false); + return session == null ? null : session.getId(); + } + + /** + * 设置SESSION属性 + * + * @author 赵卉华 + * @param name 属性名称 + * @param value 属性值 + */ + public void setSessionAttribute(String name, Object value) { + HttpSession session = getSession(); + session.setAttribute(name, value); + } + + /** + * 获取session 属性 + * + * @param name 属性名称 + * @return 属性值;session 不存在时返回null;session中没有该熟属性时返回null + */ + public Object getSessionAttribute(String name) { + HttpSession session = getRequest().getSession(false); + return session != null ? session.getAttribute(name) : null; + } + + /** + * 获取session 属性 + * + * @param 返回对象的类型 + * @param name 属性名称 + * @param type 对象类型 + * @return 属性值;session 不存在时返回null;session中没有该熟属性时返回null + */ + @SuppressWarnings("unchecked") + public T getSessionAttribute(String name, Class type) { + return (T) getSessionAttribute(name); + } + + /** + * 获取session属性列表 + * + * @param 返回对象的类型 + * @param name 属性名称 + * @param type 对象类型 + * @return 属性值列表;session 不存在时返回null;session中没有该熟属性时返回null + */ + @SuppressWarnings("unchecked") + public List getSessionAttributes(String name, Class type) { + return (List) getSessionAttribute(name); + } + + /** + * 获取Web工程容器路径
    + * 如果部署为ROOT将返回空字符串, 否则返回斜杠加工程名; 如工程名为cheetah-site-web, 返回/cheetah-site-web + * + * @return context path + */ + public String getContextPath() { + return getRequest().getContextPath(); + } + + /** + * 获取应用根目录 + * + * @return root path + */ + public String getWebRoot() { + return getRequest().getSession().getServletContext().getRealPath("/"); + } + + /** + * 获取相对于根目录的路径 + * + * @param path 相对路径 + * @return root path + */ + public String getWebRoot(String path) { + return getRequest().getSession().getServletContext().getRealPath("/") + path; + } + + /** + * 根据服务器请求信息替换URL中的占位符
    + * 如: getServerURL("http://{ServerName}:{ServerPort}/xxx/")
    + * 返回 http://127.0.0.1:8080/xxx/ + * + * @author 赵卉华 + * @param url 替换前的URL + * @return 替换后的URL + */ + public String getServerURL(String url) { + if (url == null) { + return url; + } + url = url.trim(); + if (url.indexOf("{") < 0 || url.indexOf("}") < 0) { + return url; + } + // 获取服务器请求信息 + HttpServletRequest request = getRequest(); + String scheme = request.getScheme(); + String host = request.getServerName(); + String port = String.valueOf(request.getServerPort()); + // ContextPath是以/斜杠开头的, substring(1)去掉斜杠 + String ctx = request.getContextPath(); + if (ctx != null && ctx.length() > 0) { + ctx = request.getContextPath().substring(1); + } + // 占位符正则表达式 + Pattern pScheme = Pattern.compile("\\{[Ss]cheme\\}"); + Pattern pHost = Pattern.compile("\\{[Ss]erverName\\}"); + Pattern pPort = Pattern.compile("\\{[Ss]erverPort\\}"); + Pattern pCtx = Pattern.compile("\\{[Cc]ontextPath\\}"); + // 替换占位符 + url = pScheme.matcher(url).replaceFirst(scheme); + url = pHost.matcher(url).replaceFirst(host); + url = pPort.matcher(url).replaceFirst(port); + url = pCtx.matcher(url).replaceFirst(ctx); + return Pattern.compile("(? 0) && (!(line.startsWith("#")))) set.add(line.trim().toLowerCase()); + } + br.close(); + serverLog.logInfo("PROXY", "read " + setname + " set from file " + filename); + } catch (IOException e) {} + return set; + } + + private static TreeMap loadMap(String mapname, String filename, String sep) { + TreeMap map = new TreeMap(); + try { + BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); + String line; + int pos; + while ((line = br.readLine()) != null) { + line = line.trim(); + if ((line.length() > 0) && (!(line.startsWith("#"))) && ((pos = line.indexOf(sep)) > 0)) + map.put(line.substring(0, pos).trim().toLowerCase(), line.substring(pos + sep.length()).trim()); + } + br.close(); + serverLog.logInfo("PROXY", "read " + mapname + " map from file " + filename); + } catch (IOException e) {} + return map; + } + + public static TreeMap loadBlacklist(String mapname, String filenames, String sep) { + TreeMap map = new TreeMap(); + if (switchboard == null) return map; // not initialized yet + File listsPath = new File(switchboard.getRootPath(), switchboard.getConfig("listsPath", "DATA/LISTS")); + String filenamesarray[] = filenames.split(","); + String filename = ""; + if(filenamesarray.length >0) + for(int i = 0; i < filenamesarray.length; i++) + map.putAll(loadMap(mapname, (new File(listsPath, filenamesarray[i])).toString(), sep)); + return map; + } + + private static String domain(String host) { + String domain = host; + int pos = domain.lastIndexOf("."); + if (pos >= 0) { + // truncate from last part + domain = domain.substring(0, pos); + pos = domain.lastIndexOf("."); + if (pos >= 0) { + // truncate from first part + domain = domain.substring(pos + 1); + } + } + return domain; + } + + private boolean blacklistedURL(String hostlow, String path) { + if (blackListURLs == null) return false; + + int index = 0; + + // [TL] While "." are found within the string + while ((index = hostlow.indexOf(".", index + 1)) != -1) { + if (blackListURLs.get(hostlow.substring(0, index + 1) + "*") != null) { + //System.out.println("Host blocked: " + hostlow.substring(0, index+1) + "*"); + return true; + } + } + + index = hostlow.length(); + while ((index = hostlow.lastIndexOf(".", index - 1)) != -1) { + if (blackListURLs.get("*" + hostlow.substring(index, hostlow.length())) != null) { + //System.out.println("Host blocked: " + "*" + hostlow.substring(index, host.length())); + return true; + } + } + + String pp = ""; // path-pattern + return (((pp = (String) blackListURLs.get(hostlow)) != null) && + ((pp.equals("*")) || (path.substring(1).matches(pp)))); + } + + public void handleOutgoingCookies(httpHeader requestHeader, String targethost, String clienthost) { + /* + The syntax for the header is: + + cookie = "Cookie:" cookie-version + 1*((";" | ",") cookie-value) + cookie-value = NAME "=" VALUE [";" path] [";" domain] + cookie-version = "$Version" "=" value + NAME = attr + VALUE = value + path = "$Path" "=" value + domain = "$Domain" "=" value + */ + if (requestHeader.containsKey("Cookie")) { + Object[] entry = new Object[]{new Date(), clienthost, requestHeader.getMultiple("Cookie")}; + switchboard.outgoingCookies.put(targethost, entry); + } + } + + public void handleIncomingCookies(httpHeader respondHeader, String serverhost, String targetclient) { + /* + The syntax for the Set-Cookie response header is + + set-cookie = "Set-Cookie:" cookies + cookies = 1#cookie + cookie = NAME "=" VALUE *(";" cookie-av) + NAME = attr + VALUE = value + cookie-av = "Comment" "=" value + | "Domain" "=" value + | "Max-Age" "=" value + | "Path" "=" value + | "Secure" + | "Version" "=" 1*DIGIT + */ + if (respondHeader.containsKey("Set-Cookie")) { + Object[] entry = new Object[]{new Date(), targetclient, respondHeader.getMultiple("Set-Cookie")}; + switchboard.incomingCookies.put(serverhost, entry); + } + } + + public void doGet(Properties conProp, httpHeader requestHeader, OutputStream respond) throws IOException { + // prepare response + // conProp : a collection of properties about the connection, like URL + // requestHeader : The header lines of the connection from the request + // args : the argument values of a connection, like &-values in GET and values within boundaries in POST + // files : files within POST boundaries, same key as in args + + if (yacyTrigger) de.anomic.yacy.yacyCore.triggerOnlineAction(); + + Date requestDate = new Date(); // remember the time... + String method = conProp.getProperty("METHOD"); + String host = conProp.getProperty("HOST"); + String path = conProp.getProperty("PATH"); // always starts with leading '/' + String args = conProp.getProperty("ARGS"); // may be null if no args were given + String ip = conProp.getProperty("CLIENTIP"); // the ip from the connecting peer + + int port; + int pos; + + if ((pos = host.indexOf(":")) < 0) { + port = 80; + } else { + port = Integer.parseInt(host.substring(pos + 1)); + host = host.substring(0, pos); + } + + String ext; + if ((pos = path.lastIndexOf('.')) < 0) { + ext = ""; + } else { + ext = path.substring(pos + 1).toLowerCase(); + } + + URL url = null; + try { + if (args == null) + url = new URL("http", host, port, path); + else + url = new URL("http", host, port, path + "?" + args); + } catch (MalformedURLException e) { + serverLog.logError("PROXY", "ERROR: internal error with url generation: host=" + + host + ", port=" + port + ", path=" + path + ", args=" + args); + url = null; + } + //System.out.println("GENERATED URL:" + url.toString()); // debug + + // check the blacklist + // blacklist idea inspired by [AS]: + // respond a 404 for all AGIS ("all you get is shit") servers + String hostlow = host.toLowerCase(); + if (blacklistedURL(hostlow, path)) { + try { + respondHeader(respond,"404 Not Found (AGIS)", new httpHeader(null)); + respond.write(("404 (generated): URL '" + hostlow + "' blocked by yacy proxy (blacklisted)\r\n").getBytes()); + respond.flush(); + serverLog.logInfo("PROXY", "AGIS blocking of host '" + hostlow + "'"); // debug + return; + } catch (Exception ee) {} + } + + // handle outgoing cookies + handleOutgoingCookies(requestHeader, host, ip); + + // set another userAgent, if not yellowlisted + if ((yellowList != null) && (!(yellowList.contains(domain(hostlow))))) { + // change the User-Agent + requestHeader.put("User-Agent", userAgent); + } + + // set a scraper and a htmlFilter + OutputStream hfos = null; + htmlFilterContentScraper scraper = null; + + // resolve yacy and yacyh domains + String yAddress = yacyCore.seedDB.resolveYacyAddress(host); + + // re-calc the url path + String remotePath = (args == null) ? path : (path + "?" + args); // with leading '/' + + // attach possible yacy-sublevel-domain + if ((yAddress != null) && + ((pos = yAddress.indexOf("/")) >= 0) && + (!(remotePath.startsWith("/env"))) // this is the special path, staying always at root-level + ) remotePath = yAddress.substring(pos) + remotePath; + + // decide wether to use a cache entry or connect to the network + File cacheFile = cacheManager.getCachePath(url); + String urlHash = plasmaCrawlLURL.urlHash(url); + httpHeader cachedResponseHeader = null; + boolean cacheExists = ((cacheFile.exists()) && (cacheFile.isFile()) && + ((cachedResponseHeader = cacheManager.getCachedResponse(urlHash)) != null)); + + // why are files unzipped upon arrival? why not zip all files in cache? + // This follows from the following premises + // (a) no file shall be unzip-ed more than once to prevent unnessesary computing time + // (b) old cache entries shall be comparable with refill-entries to detect/distiguish case 3+4 + // (c) the indexing mechanism needs files unzip-ed, a schedule could do that later + // case b and c contradicts, if we use a scheduler, because files in a stale cache would be unzipped + // and the newly arrival would be zipped and would have to be unzipped upon load. But then the + // scheduler is superfluous. Therefore the only reminding case is + // (d) cached files shall be either all zipped or unzipped + // case d contradicts with a, because files need to be unzipped for indexing. Therefore + // the only remaining case is to unzip files right upon load. Thats what we do here. + + // finally use existing cache if appropriate + // here we must decide weather or not to save the data + // to a cache + // we distinguish four CACHE STATE cases: + // 1. cache fill + // 2. cache fresh - no refill + // 3. cache stale - refill - necessary + // 4. cache stale - refill - superfluous + // in two of these cases we trigger a scheduler to handle newly arrived files: + // case 1 and case 3 + plasmaHTCache.Entry cacheEntry; + if ((cacheExists) && + ((cacheEntry = cacheManager.newEntry(requestDate, 0, url, requestHeader, "200 OK", + cachedResponseHeader, null, + switchboard.defaultProxyProfile)).shallUseCache())) { + // we respond on the request by using the cache, the cache is fresh + + try { + // replace date field in old header by actual date, this is according to RFC + cachedResponseHeader.put("Date", httpc.dateString(httpc.nowDate())); + + // maybe the content length is missing + if (!(cachedResponseHeader.containsKey("CONTENT-LENGTH"))) + cachedResponseHeader.put("CONTENT-LENGTH", Long.toString(cacheFile.length())); + + // check if we can send a 304 instead the complete content + if (requestHeader.containsKey("IF-MODIFIED-SINCE")) { + // conditional request: freshness of cache for that condition was already + // checked within shallUseCache(). Now send only a 304 response + log.logInfo("CACHE HIT/304 " + cacheFile.toString()); + + // send cached header with replaced date and added length + respondHeader(respond, "304 OK", cachedResponseHeader); // respond with 'not modified' + + } else { + // unconditional request: send content of cache + log.logInfo("CACHE HIT/203 " + cacheFile.toString()); + + // send cached header with replaced date and added length + respondHeader(respond, "203 OK", cachedResponseHeader); // respond with 'non-authoritative' + + // make a transformer + if ((!(transformer.isIdentityTransformer())) && + ((ext == null) || (!(switchboard.extensionBlack.contains(ext)))) && + ((cachedResponseHeader == null) || (httpd.isTextMime(cachedResponseHeader.mime(), switchboard.mimeWhite)))) { + hfos = new htmlFilterOutputStream(respond, null, transformer, (ext.length() == 0)); + } else { + hfos = respond; + } + + // send also the complete body now from the cache + // simply read the file and transfer to out socket + InputStream is = new FileInputStream(cacheFile); + byte[] buffer = new byte[2048]; + int l; + while ((l = is.read(buffer)) > 0) {hfos.write(buffer, 0, l);} + is.close(); + if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); + } + // that's it! + } catch (SocketException e) { + // this happens if the client stops loading the file + // we do nothing here + respondError(respond, "111 socket error: " + e.getMessage(), 1, url.toString()); + } + respond.flush(); + return; + } + + // the cache does either not exist or is (supposed to be) stale + long sizeBeforeDelete = -1; + if (cacheExists) { + // delete the cache + sizeBeforeDelete = cacheFile.length(); + cacheFile.delete(); + } + + // take a new file from the server + httpc remote = null; + httpc.response res = null; + + try { + // open the connection + if (yAddress == null) { + remote = newhttpc(host, port, timeout); + } else { + remote = newhttpc(yAddress, timeout); + } + //System.out.println("HEADER: CLIENT TO PROXY = " + requestHeader.toString()); // DEBUG + + // send request + res = remote.GET(remotePath, requestHeader); + long contentLength = res.responseHeader.contentLength(); + + // reserver cache entry + cacheEntry = cacheManager.newEntry(requestDate, 0, url, requestHeader, res.status, res.responseHeader, null, switchboard.defaultProxyProfile); + + // handle file types + if (((ext == null) || (!(switchboard.extensionBlack.contains(ext)))) && + (httpd.isTextMime(res.responseHeader.mime(), switchboard.mimeWhite))) { + // this is a file that is a possible candidate for parsing by the indexer + if (transformer.isIdentityTransformer()) { + log.logDebug("create passthrough (parse candidate) for url " + url); + // no transformation, only passthrough + // this is especially the case if the bluelist is empty + // in that case, the content is not scraped here but later + hfos = respond; + } else { + // make a scraper and transformer + log.logDebug("create scraper for url " + url); + scraper = new htmlFilterContentScraper(url); + hfos = new htmlFilterOutputStream(respond, scraper, transformer, (ext.length() == 0)); + if (((htmlFilterOutputStream) hfos).binarySuspect()) { + scraper = null; // forget it, may be rubbish + log.logDebug("Content of " + url + " is probably binary. deleted scraper."); + } + cacheEntry.scraper = scraper; + } + } else { + log.logDebug("Resource " + url + " has wrong extension (" + ext + ") or wrong mime-type (" + res.responseHeader.mime() + "). not scraped"); + scraper = null; + hfos = respond; + cacheEntry.scraper = scraper; + } + + // handle incoming cookies + handleIncomingCookies(res.responseHeader, host, ip); + + // request has been placed and result has been returned. work off response + try { + respondHeader(respond, res.status, res.responseHeader); + String storeError; + if ((storeError = cacheEntry.shallStoreCache()) == null) { + // we write a new cache entry + if ((contentLength > 0) && // known + (contentLength < 1048576)) {// 1 MB + // ok, we don't write actually into a file, only to RAM, and schedule writing the file. + byte[] cacheArray = res.writeContent(hfos); + log.logDebug("writeContent of " + url + " produced cacheArray = " + ((cacheArray == null) ? "null" : ("size=" + cacheArray.length))); + + if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); + + if (sizeBeforeDelete == -1) { + // totally fresh file + cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert + cacheManager.stackProcess(cacheEntry, cacheArray); + } else if (sizeBeforeDelete == cacheArray.length) { + // before we came here we deleted a cache entry + cacheArray = null; + cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD; + cacheManager.stackProcess(cacheEntry); // unnecessary update + } else { + // before we came here we deleted a cache entry + cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD; + cacheManager.stackProcess(cacheEntry, cacheArray); // necessary update, write response header to cache + } + } else { + // the file is too big to cache it in the ram, or the size is unknown + // write to file right here. + cacheFile.getParentFile().mkdirs(); + res.writeContent(hfos, cacheFile); + if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); + log.logDebug("for write-file of " + url + ": contentLength = " + contentLength + ", sizeBeforeDelete = " + sizeBeforeDelete); + if (sizeBeforeDelete == -1) { + // totally fresh file + cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert + cacheManager.stackProcess(cacheEntry); + } else if (sizeBeforeDelete == cacheFile.length()) { + // before we came here we deleted a cache entry + cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD; + cacheManager.stackProcess(cacheEntry); // unnecessary update + } else { + // before we came here we deleted a cache entry + cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD; + cacheManager.stackProcess(cacheEntry); // necessary update, write response header to cache + } + // beware! all these writings will not fill the cacheEntry.cacheArray + // that means they are not available for the indexer (except they are scraped before) + } + } else { + // no caching + log.logDebug(cacheFile.toString() + " not cached: " + storeError); + res.writeContent(hfos, null); + if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); + if (sizeBeforeDelete == -1) { + // no old file and no load. just data passing + cacheEntry.status = plasmaHTCache.CACHE_PASSING; + cacheManager.stackProcess(cacheEntry); + } else { + // before we came here we deleted a cache entry + cacheEntry.status = plasmaHTCache.CACHE_STALE_NO_RELOAD; + cacheManager.stackProcess(cacheEntry); + } + } + } catch (SocketException e) { + // this may happen if the client suddenly closes its connection + // maybe the user has stopped loading + // in that case, we are not responsible and just forget it + // but we clean the cache also, since it may be only partial + // and most possible corrupted + if (cacheFile.exists()) cacheFile.delete(); + respondHeader(respond,"404 client unexpectedly closed connection", new httpHeader(null)); + } catch (IOException e) { + // can have various reasons + if (cacheFile.exists()) cacheFile.delete(); + if (e.getMessage().indexOf("Corrupt GZIP trailer") >= 0) { + // just do nothing, we leave it this way + log.logDebug("ignoring bad gzip trail for URL " + url + " (" + e.getMessage() + ")"); + } else { + respondHeader(respond,"404 client unexpectedly closed connection", new httpHeader(null)); + log.logDebug("IOError for URL " + url + " (" + e.getMessage() + ") - responded 404"); + e.printStackTrace(); + } + } + remote.close(); + } catch (Exception e) { + // this may happen if the targeted host does not exist or anything with the + // remote server was wrong. + // in any case, sending a 404 is appropriate + try { + if ((e.toString().indexOf("unknown host")) > 0) { + respondHeader(respond,"404 unknown host", new httpHeader(null)); + } else { + respondHeader(respond,"404 Not Found", new httpHeader(null)); + respond.write(("Exception occurred:\r\n").getBytes()); + respond.write((e.toString() + "\r\n").getBytes()); + respond.write(("[TRACE: ").getBytes()); + e.printStackTrace(new PrintStream(respond)); + respond.write(("]\r\n").getBytes()); + } + } catch (Exception ee) {} + } finally { + if (remote != null) httpc.returnInstance(remote); + } + respond.flush(); + } + + + private void respondError(OutputStream respond, String origerror, int errorcase, String url) { + try { + // set rewrite values + serverObjects tp = new serverObjects(); + tp.put("errormessage", errorcase); + tp.put("httperror", origerror); + tp.put("url", url); + + // rewrite the file + File file = new File(htRootPath, "/proxymsg/error.html"); + byte[] result; + ByteArrayOutputStream o = new ByteArrayOutputStream(); + FileInputStream fis = new FileInputStream(file); + httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes()); + o.close(); + result = o.toByteArray(); + + // return header + httpHeader header = new httpHeader(); + header.put("Date", httpc.dateString(httpc.nowDate())); + header.put("Content-type", "text/html"); + header.put("Content-length", "" + o.size()); + header.put("Pragma", "no-cache"); + + // write the array to the client + respondHeader(respond, origerror, header); + serverFileUtils.write(result, respond); + respond.flush(); + } catch (IOException e) { + + } + } + + public void doHead(Properties conProp, httpHeader requestHeader, OutputStream respond) throws IOException { + String method = conProp.getProperty("METHOD"); + String host = conProp.getProperty("HOST"); + String path = conProp.getProperty("PATH"); + String args = conProp.getProperty("ARGS"); // may be null if no args were given + int port; + int pos; + if ((pos = host.indexOf(":")) < 0) { + port = 80; + } else { + port = Integer.parseInt(host.substring(pos + 1)); + host = host.substring(0, pos); + } + + // check the blacklist, inspired by [AS]: respond a 404 for all AGIS (all you get is shit) servers + String hostlow = host.toLowerCase(); + if (blacklistedURL(hostlow, path)) { + try { + respondHeader(respond,"404 Not Found (AGIS)", new httpHeader(null)); + respond.write(("404 (generated): URL '" + hostlow + "' blocked by yacy proxy (blacklisted)\r\n").getBytes()); + respond.flush(); + serverLog.logInfo("PROXY", "AGIS blocking of host '" + hostlow + "'"); // debug + return; + } catch (Exception ee) {} + } + + // set another userAgent, if not yellowlisted + if (!(yellowList.contains(domain(hostlow)))) { + // change the User-Agent + requestHeader.put("User-Agent", userAgent); + } + + // resolve yacy and yacyh domains + String yAddress = yacyCore.seedDB.resolveYacyAddress(host); + + // re-calc the url path + String remotePath = (args == null) ? path : (path + "?" + args); + + // attach possible yacy-sublevel-domain + if ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0)) remotePath = yAddress.substring(pos) + remotePath; + + httpc remote = null; + httpc.response res = null; + + try { + // open the connection + if (yAddress == null) { + remote = newhttpc(host, port, timeout); + } else { + remote = newhttpc(yAddress, timeout); // with [AS] patch + } + res = remote.HEAD(remotePath, requestHeader); + respondHeader(respond, res.status, res.responseHeader); + } catch (Exception e) { + try { + respondHeader(respond,"404 Not Found", new httpHeader(null)); + respond.write(("Exception occurred:\r\n").getBytes()); + respond.write((e.toString() + "\r\n").getBytes()); + respond.write(("[TRACE: ").getBytes()); + e.printStackTrace(new PrintStream(respond)); + respond.write(("]\r\n").getBytes()); + } catch (Exception ee) {} + } finally { + if (remote != null) httpc.returnInstance(remote); + } + + respond.flush(); + } + + public void doPost(Properties conProp, httpHeader requestHeader, OutputStream respond, PushbackInputStream body) throws IOException { + String host = conProp.getProperty("HOST"); + String path = conProp.getProperty("PATH"); + String args = conProp.getProperty("ARGS"); // may be null if no args were given + int port; + int pos; + if ((pos = host.indexOf(":")) < 0) { + port = 80; + } else { + port = Integer.parseInt(host.substring(pos + 1)); + host = host.substring(0, pos); + } + + // set another userAgent, if not yellowlisted + if (!(yellowList.contains(domain(host).toLowerCase()))) { + // change the User-Agent + requestHeader.put("User-Agent", userAgent); + } + + // resolve yacy and yacyh domains + String yAddress = yacyCore.seedDB.resolveYacyAddress(host); + + // re-calc the url path + String remotePath = (args == null) ? path : (path + "?" + args); + + // attach possible yacy-sublevel-domain + if ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0)) remotePath = yAddress.substring(pos) + remotePath; + + httpc remote = null; + httpc.response res = null; + + try { + if (yAddress == null) { + remote = newhttpc(host, port, timeout); + } else { + remote = newhttpc(yAddress, timeout); + } + res = remote.POST(remotePath, requestHeader, body); + respondHeader(respond, res.status, res.responseHeader); + res.writeContent(respond, null); + remote.close(); + } catch (Exception e) { + try { + respondHeader(respond,"404 Not Found", new httpHeader(null)); + respond.write(("Exception occurred:\r\n").getBytes()); + respond.write((e.toString() + "\r\n").getBytes()); + respond.write(("[TRACE: ").getBytes()); + e.printStackTrace(new PrintStream(respond)); + respond.write(("]\r\n").getBytes()); + } catch (Exception ee) {} + } finally { + if (remote != null) httpc.returnInstance(remote); + } + respond.flush(); + } + + public void doConnect(Properties conProp, de.anomic.http.httpHeader requestHeader, InputStream clientIn, OutputStream clientOut) throws IOException { + String host = conProp.getProperty("HOST"); + int port = Integer.parseInt(conProp.getProperty("PORT")); + String httpVersion = conProp.getProperty("HTTP"); + int timeout = Integer.parseInt(switchboard.getConfig("clientTimeout", "10000")); + + // possibly branch into PROXY-PROXY connection + if (remoteProxyUse) { + httpc remoteProxy = null; + try { + remoteProxy = httpc.getInstance(host, port, timeout, false, remoteProxyHost, remoteProxyPort); + httpc.response response = remoteProxy.CONNECT(host, port, requestHeader); + response.print(); + if (response.success()) { + // replace connection details + host = remoteProxyHost; + port = remoteProxyPort; + // go on (see below) + } else { + // pass error response back to client + respondHeader(clientOut, response.status, response.responseHeader); + return; + } + } catch (Exception e) { + throw new IOException(e.getMessage()); + } finally { + if (remoteProxy != null) httpc.returnInstance(remoteProxy); + } + } + + // try to establish connection to remote host + Socket sslSocket = new Socket(host, port); + sslSocket.setSoTimeout(timeout); // waiting time for write + sslSocket.setSoLinger(true, timeout); // waiting time for read + InputStream promiscuousIn = sslSocket.getInputStream(); + OutputStream promiscuousOut = sslSocket.getOutputStream(); + + // now then we can return a success message + clientOut.write((httpVersion + " 200 Connection established" + serverCore.crlfString + + "Proxy-agent: YACY" + serverCore.crlfString + + serverCore.crlfString).getBytes()); + + log.logInfo("SSL CONNECTION TO " + host + ":" + port + " ESTABLISHED"); + + // start stream passing with mediate processes + try { + Mediate cs = new Mediate(sslSocket, clientIn, promiscuousOut); + Mediate sc = new Mediate(sslSocket, promiscuousIn, clientOut); + cs.start(); + sc.start(); + while ((sslSocket != null) && + (sslSocket.isBound()) && + (!(sslSocket.isClosed())) && + (sslSocket.isConnected()) && + ((cs.isAlive()) || (sc.isAlive()))) { + // idle + try {Thread.currentThread().sleep(1000);} catch (InterruptedException e) {} // wait a while + } + // set stop mode + cs.pleaseTerminate(); + sc.pleaseTerminate(); + // wake up thread + cs.interrupt(); + sc.interrupt(); + // ...hope they have terminated... + } catch (IOException e) { + //System.out.println("promiscuous termination: " + e.getMessage()); + } + + } + + public class Mediate extends Thread { + + boolean terminate; + Socket socket; + InputStream in; + OutputStream out; + + public Mediate(Socket socket, InputStream in, OutputStream out) throws IOException { + this.terminate = false; + this.in = in; + this.out = out; + this.socket = socket; + } + + public void run() { + byte[] buffer = new byte[512]; + int len; + try { + while ((socket != null) && + (socket.isBound()) && + (!(socket.isClosed())) && + (socket.isConnected()) && + (!(terminate)) && + (in != null) && + (out != null) && + ((len = in.read(buffer)) >= 0) + ) { + out.write(buffer, 0, len); + } + } catch (IOException e) {} + } + + public void pleaseTerminate() { + terminate = true; + } + } + + private httpc newhttpc(String server, int port, int timeout) throws IOException { + // a new httpc connection, combined with possible remote proxy + boolean useProxy = remoteProxyUse; + // check no-proxy rule + if ((useProxy) && (!(remoteProxyAllowProxySet.contains(server)))) { + if (remoteProxyDisallowProxySet.contains(server)) { + useProxy = false; + } else { + // analyse remoteProxyNoProxy; + // set either remoteProxyAllowProxySet or remoteProxyDisallowProxySet accordingly + int i = 0; + while (i < remoteProxyNoProxyPatterns.length) { + if (server.matches(remoteProxyNoProxyPatterns[i])) { + // disallow proxy for this server + remoteProxyDisallowProxySet.add(server); + useProxy = false; + break; + } + i++; + } + if (i == remoteProxyNoProxyPatterns.length) { + // no pattern matches: allow server + remoteProxyAllowProxySet.add(server); + } + } + } + // branch to server/proxy + if (useProxy) { + return httpc.getInstance(server, port, timeout, false, remoteProxyHost, remoteProxyPort); + } else { + return httpc.getInstance(server, port, timeout, false); + } + } + + private httpc newhttpc(String address, int timeout) throws IOException { + // a new httpc connection for :/ syntax + // this is called when a '.yacy'-domain is used + int p = address.indexOf(":"); + if (p < 0) return null; + String server = address.substring(0, p); + address = address.substring(p + 1); + // remove possible path elements (may occur for 'virtual' subdomains + p = address.indexOf("/"); + if (p >= 0) address = address.substring(0, p); // cut it off + int port = Integer.parseInt(address); + // normal creation of httpc object + return newhttpc(server, port, timeout); + } + + private void respondHeader(OutputStream respond, String status, httpHeader header) throws IOException, SocketException { + + // prepare header + //header.put("Server", "AnomicHTTPD (www.anomic.de)"); + if (!(header.containsKey("date"))) header.put("Date", httpc.dateString(httpc.nowDate())); + if (!(header.containsKey("content-type"))) header.put("Content-type", "text/html"); // fix this + + StringBuffer headerStringBuffer = new StringBuffer(200); + + // write status line + headerStringBuffer.append("HTTP/1.1 ").append(status).append("\r\n"); + + //System.out.println("HEADER: PROXY TO CLIENT = " + header.toString()); // DEBUG + + // write header + Iterator i = header.keySet().iterator(); + String key; + String value; + char tag; + int count; + //System.out.println("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"); + while (i.hasNext()) { + key = (String) i.next(); + tag = key.charAt(0); + if ((tag != '*') && (tag != '#')) { // '#' in key is reserved for proxy attributes as artificial header values + count = header.keyCount(key); + for (int j = 0; j < count; j++) { + headerStringBuffer.append(key).append(": ").append((String) header.getSingle(key, j)).append("\r\n"); + } + //System.out.println("#" + key + ": " + value); + } + } + headerStringBuffer.append("\r\n"); + + // end header + respond.write(headerStringBuffer.toString().getBytes()); + respond.flush(); + } + + + private void textMessage(OutputStream out, String body) throws IOException { + out.write(("HTTP/1.1 200 OK\r\n").getBytes()); + out.write(("Server: AnomicHTTPD (www.anomic.de)\r\n").getBytes()); + out.write(("Date: " + httpc.dateString(httpc.nowDate()) + "\r\n").getBytes()); + out.write(("Content-type: text/plain\r\n").getBytes()); + out.write(("Content-length: " + body.length() +"\r\n").getBytes()); + out.write(("\r\n").getBytes()); + out.flush(); + out.write(body.getBytes()); + out.flush(); + } + + private void transferFile(OutputStream out, File f) throws IOException { + InputStream source = new FileInputStream(f); + byte[] buffer = new byte[4096]; + int bytes_read; + while ((bytes_read = source.read(buffer)) > 0) out.write(buffer, 0, bytes_read); + out.flush(); + source.close(); + } + +} + +/* +proxy test: + +http://www.chipchapin.com/WebTools/cookietest.php? +http://xlists.aza.org/moderator/cookietest/cookietest1.php +http://vancouver-webpages.com/proxy/cache-test.html + +*/ + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 169 is not released after line 177. +**Note**: potential exception at line 171 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +HashSet httpdProxyHandler.loadSet(String,String) + +### Procedure Id: +de.anomic.http.httpdProxyHandler.loadSet(java.lang.String,java.lang.String):java.util.HashSet.4546d49311f98035170bb01aebe21f24 + +### File: +source/de/anomic/http/httpdProxyHandler.java + +### Key: +httpdProxyHandler.java|loadSet|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +4a821c56283b45052e9ffb95c2c53509 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-4135/instruction.md b/inferredbugs-4135/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2709fbeda0f2fb447694000f0d07c1d28de74710 --- /dev/null +++ b/inferredbugs-4135/instruction.md @@ -0,0 +1,181 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** yacy_search_server +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +// serverFileUtils.java +// ------------------------------------------- +// (C) by Michael Peter Christen; mc@anomic.de +// first published on http://www.anomic.de +// Frankfurt, Germany, 2004 +// last major change: 05.08.2004 +// +// 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 +// +// Using this software in any meaning (reading, learning, copying, compiling, +// running) means that you agree that the Author(s) is (are) not responsible +// for cost, loss of data or any harm that may be caused directly or indirectly +// by usage of this softare or this documentation. The usage of this software +// is on your own risk. The installation and usage (starting/running) of this +// software may allow other people or application to access your computer and +// any attached devices and is highly dependent on the configuration of the +// software which must be done by the user of the software; the author(s) is +// (are) also not responsible for proper configuration and usage of the +// software, even if provoked by documentation provided together with +// the software. +// +// Any changes to this file according to the GPL as documented in the file +// gpl.txt aside this file in the shipment you received can be done to the +// lines that follows this copyright notice here, but changes must not be +// done inside the copyright notive above. A re-distribution must contain +// the intact and unchanged copyright notice. +// Contributions and changes to the program code must be marked as such. + +package de.anomic.server; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +public final class serverFileUtils { + + public static void copy(InputStream source, OutputStream dest) throws IOException { + byte[] buffer = new byte[4096]; + int c; + while ((c = source.read(buffer)) > 0) dest.write(buffer, 0, c); + dest.flush(); + } + + public static void copy(InputStream source, File dest) throws IOException { + FileOutputStream fos = new FileOutputStream(dest); + copy(source, fos); + fos.close(); + } + + public static void copy(File source, OutputStream dest) throws IOException { + InputStream fis = new FileInputStream(source); + copy(fis, dest); + fis.close(); + } + + public static void copy(File source, File dest) throws IOException { + FileInputStream fis = new FileInputStream(source); + FileOutputStream fos = new FileOutputStream(dest); + copy(fis, fos); + fis.close(); + fos.close(); + } + + public static byte[] read(InputStream source) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + copy(source, baos); + baos.close(); + return baos.toByteArray(); + } + + public static byte[] read(File source) throws IOException { + byte[] buffer = new byte[(int) source.length()]; + InputStream fis = new FileInputStream(source); + int p = 0; + int c; + while ((c = fis.read(buffer, p, buffer.length - p)) > 0) p += c; + fis.close(); + return buffer; + } + + public static void write(byte[] source, OutputStream dest) throws IOException { + copy(new ByteArrayInputStream(source), dest); + } + + public static void write(byte[] source, File dest) throws IOException { + copy(new ByteArrayInputStream(source), dest); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired by call to `FileInputStream(...)` at line 90 is not released after line 95. +**Note**: potential exception at line 93 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +byte[] serverFileUtils.read(File) + +### Procedure Id: +de.anomic.server.serverFileUtils.read(java.io.File):byte[].5b34e48d8d29fd6b68e4a268cc46af90 + +### File: +source/de/anomic/server/serverFileUtils.java + +### Key: +serverFileUtils.java|read|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +9d5d10fa8a42fffff78ff07a12d66cb0 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-4150/instruction.md b/inferredbugs-4150/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..37d410ac7312003a025cf6e85fa9bc747b2405f8 --- /dev/null +++ b/inferredbugs-4150/instruction.md @@ -0,0 +1,219 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-tracer +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.common.tracer.core.base; + +import com.alipay.common.tracer.core.TestUtil; +import com.alipay.common.tracer.core.appender.TracerLogRootDaemon; +import com.alipay.common.tracer.core.appender.builder.XStringBuilder; +import com.alipay.common.tracer.core.reporter.type.TracerSystemLogEnum; +import org.apache.commons.io.FileUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * AbstractTestBase + * + * @author yangguanchao + * @since 2017/07/01 + */ +public abstract class AbstractTestBase { + + public static final String MAP_PREFIX = "M|"; + + /** + * Tracer Log Root Director Path + */ + public static String logDirectoryPath = TracerLogRootDaemon.LOG_FILE_DIR; + + /** + * Clean Tracer Log Root Directory + */ + @BeforeClass + public static void beforeClass() { + for (File file : customFileLog("").listFiles()) { + if (file.getPath().contains("tracer-self.log") || file.getPath().contains("sync.log") + || file.getPath().contains("rpc-profile.log") + || file.getPath().contains("middleware_error.log")) { + continue; + } + FileUtils.deleteQuietly(file); + } + } + + @Before + public void commonBeforeMethod() throws IOException { + File file = customFileLog(TracerSystemLogEnum.MIDDLEWARE_ERROR.getDefaultLogName()); + if (file.exists()) { + FileUtils.writeStringToFile(file, ""); + } + file = customFileLog(TracerSystemLogEnum.RPC_PROFILE.getDefaultLogName()); + if (file.exists()) { + FileUtils.writeStringToFile(file, ""); + } + file = tracerSelfLog(); + if (file.exists()) { + FileUtils.writeStringToFile(file, ""); + } + } + + /** + * Check whether is error message printed. + * + * @return + * @throws IOException + */ + protected boolean checkSelfLogContainsError() throws IOException { + File tracerSelfLog = tracerSelfLog(); + if (!tracerSelfLog.exists()) { + return false; + } + String selfLogContent = FileUtils.readFileToString(tracerSelfLog); + return selfLogContent.contains("ERROR"); + } + + protected static File customFileLog(String fileName) { + return new File(logDirectoryPath + File.separator + fileName); + } + + protected static File tracerSelfLog() { + return new File(logDirectoryPath + File.separator + "tracer-self.log"); + } + + protected static File middlewareErrorLog() { + return new File(logDirectoryPath + File.separator + + TracerSystemLogEnum.MIDDLEWARE_ERROR.getDefaultLogName()); + } + + /** + * 检查传入的参数和日志中的内容是否匹配 + * + * @param params String Array which is compared with logContent. + * @param logContent String Content which is split up with comma + * @return + */ + public static boolean checkResult(List params, String logContent) { + Assert.assertNotNull(params); + Assert.assertNotNull(logContent); + + List slots = Arrays.asList(logContent.split(String + .valueOf(XStringBuilder.DEFAULT_SEPARATOR))); + + assertEquals("日志内容中的栏位数量为 " + slots.size() + ";参数的栏位数量为" + params.size() + ";两者不一致", + params.size(), slots.size()); + + for (int i = 0; i < params.size(); i++) { + String param = params.get(i); + String slot = slots.get(i); + if (param == null) { + if (slot == null || "null".equals(slot)) { + continue; + } + } + if (param.length() > 2 && param.startsWith("M|")) { + Assert.assertTrue("日志和参数中的第 " + i + " 栏内容不一致,日志中为 " + slot + ";参数中为 " + param, + TestUtil.compareSlotMap(param.substring(2), slot)); + } else { + Assert.assertTrue("日志和参数中的第 " + i + " 栏内容不一致,日志中为 " + slot + ";参数中为 " + param, + param.equals(slot)); + } + } + return true; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `customFileLog("").listFiles()` could be null and is dereferenced at line 55. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AbstractTestBase.beforeClass() + +### Procedure Id: +com.alipay.common.tracer.core.base.AbstractTestBase.beforeClass():void.de5c1c845de58166e043ba945051241c + +### File: +tracer-core/src/test/java/com/alipay/common/tracer/core/base/AbstractTestBase.java + +### Key: +AbstractTestBase.java|beforeClass|NULL_DEREFERENCE + +### Node Key: +24ee14a57e8a90ab88fc833015223ecd + +### Hash: +5ca8a12dda4a486cf77bb411d84e8a2f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-4151/instruction.md b/inferredbugs-4151/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..526ccfb9923c4fee84f10b7615a6da4bca451fa5 --- /dev/null +++ b/inferredbugs-4151/instruction.md @@ -0,0 +1,343 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** Mybatis-PageHelper +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2017 abel533@gmail.com + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.github.pagehelper; + +import com.github.pagehelper.cache.Cache; +import com.github.pagehelper.cache.CacheFactory; +import com.github.pagehelper.util.MSUtils; +import com.github.pagehelper.util.StringUtil; +import org.apache.ibatis.cache.CacheKey; +import org.apache.ibatis.executor.Executor; +import org.apache.ibatis.mapping.BoundSql; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.plugin.*; +import org.apache.ibatis.session.Configuration; +import org.apache.ibatis.session.ResultHandler; +import org.apache.ibatis.session.RowBounds; + +import java.lang.reflect.Field; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +/** + * Mybatis - 通用分页拦截器
    + * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper + * + * @author liuzh/abel533/isea533 + * @version 5.0.0 + */ +@SuppressWarnings({"rawtypes", "unchecked"}) +@Intercepts( + { + @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), + @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}), + } +) +public class PageInterceptor implements Interceptor { + //缓存count查询的ms + protected Cache msCountMap = null; + private volatile Dialect dialect; + private String default_dialect_class = "com.github.pagehelper.PageHelper"; + private Field additionalParametersField; + private String countSuffix = "_COUNT"; + + @Override + public Object intercept(Invocation invocation) throws Throwable { + try { + Object[] args = invocation.getArgs(); + MappedStatement ms = (MappedStatement) args[0]; + Object parameter = args[1]; + RowBounds rowBounds = (RowBounds) args[2]; + ResultHandler resultHandler = (ResultHandler) args[3]; + Executor executor = (Executor) invocation.getTarget(); + CacheKey cacheKey; + BoundSql boundSql; + //由于逻辑关系,只会进入一次 + if(args.length == 4){ + //4 个参数时 + boundSql = ms.getBoundSql(parameter); + cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql); + } else { + //6 个参数时 + cacheKey = (CacheKey) args[4]; + boundSql = (BoundSql) args[5]; + } + + // Spring bean 方式配置时,如果没有配置属性就不会执行下面的 setProperties 方法,就不会初始化 + // 因此这里会出现 null 的情况 fixed #26 + if(dialect == null){ + synchronized (default_dialect_class){ + if(dialect == null){ + setProperties(new Properties()); + } + } + } + List resultList; + //调用方法判断是否需要进行分页,如果不需要,直接返回结果 + if (!dialect.skip(ms, parameter, rowBounds)) { + //反射获取动态参数 + String msId = ms.getId(); + Configuration configuration = ms.getConfiguration(); + Map additionalParameters = (Map) additionalParametersField.get(boundSql); + //判断是否需要进行 count 查询 + if (dialect.beforeCount(ms, parameter, rowBounds)) { + String countMsId = msId + countSuffix; + Long count; + //先判断是否存在手写的 count 查询 + MappedStatement countMs = getExistedMappedStatement(configuration, countMsId); + if(countMs != null){ + count = executeManualCount(executor, countMs, parameter, boundSql, resultHandler); + } else { + countMs = msCountMap.get(countMsId); + //自动创建 + if (countMs == null) { + //根据当前的 ms 创建一个返回值为 Long 类型的 ms + countMs = MSUtils.newCountMappedStatement(ms, countMsId); + msCountMap.put(countMsId, countMs); + } + count = executeAutoCount(executor, countMs, parameter, boundSql, rowBounds, resultHandler); + } + //处理查询总数 + //返回 true 时继续分页查询,false 时直接返回 + if (!dialect.afterCount(count, parameter, rowBounds)) { + //当查询总数为 0 时,直接返回空的结果 + return dialect.afterPage(new ArrayList(), parameter, rowBounds); + } + } + //判断是否需要进行分页查询 + if (dialect.beforePage(ms, parameter, rowBounds)) { + //生成分页的缓存 key + CacheKey pageKey = cacheKey; + //处理参数对象 + parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey); + //调用方言获取分页 sql + String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey); + BoundSql pageBoundSql = new BoundSql(configuration, pageSql, boundSql.getParameterMappings(), parameter); + //设置动态参数 + for (String key : additionalParameters.keySet()) { + pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key)); + } + //执行分页查询 + resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql); + } else { + //不执行分页的情况下,也不执行内存分页 + resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql); + } + } else { + //rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页 + resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql); + } + return dialect.afterPage(resultList, parameter, rowBounds); + } finally { + dialect.afterAll(); + } + } + + /** + * 执行手动设置的 count 查询,该查询支持的参数必须和被分页的方法相同 + * + * @param executor + * @param countMs + * @param parameter + * @param boundSql + * @param resultHandler + * @return + * @throws IllegalAccessException + * @throws SQLException + */ + private Long executeManualCount(Executor executor, MappedStatement countMs, + Object parameter, BoundSql boundSql, + ResultHandler resultHandler) throws IllegalAccessException, SQLException { + CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql); + BoundSql countBoundSql = countMs.getBoundSql(parameter); + Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey, countBoundSql); + Long count = ((Number) ((List) countResultList).get(0)).longValue(); + return count; + } + + /** + * 执行自动生成的 count 查询 + * + * @param executor + * @param countMs + * @param parameter + * @param boundSql + * @param rowBounds + * @param resultHandler + * @return + * @throws IllegalAccessException + * @throws SQLException + */ + private Long executeAutoCount(Executor executor, MappedStatement countMs, + Object parameter, BoundSql boundSql, + RowBounds rowBounds, ResultHandler resultHandler) throws IllegalAccessException, SQLException { + Map additionalParameters = (Map) additionalParametersField.get(boundSql); + //创建 count 查询的缓存 key + CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql); + //调用方言获取 count sql + String countSql = dialect.getCountSql(countMs, boundSql, parameter, rowBounds, countKey); + //countKey.update(countSql); + BoundSql countBoundSql = new BoundSql(countMs.getConfiguration(), countSql, boundSql.getParameterMappings(), parameter); + //当使用动态 SQL 时,可能会产生临时的参数,这些参数需要手动设置到新的 BoundSql 中 + for (String key : additionalParameters.keySet()) { + countBoundSql.setAdditionalParameter(key, additionalParameters.get(key)); + } + //执行 count 查询 + Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey, countBoundSql); + Long count = (Long) ((List) countResultList).get(0); + return count; + } + + /** + * 尝试获取已经存在的在 MS,提供对手写count和page的支持 + * + * @param configuration + * @param msId + * @return + */ + private MappedStatement getExistedMappedStatement(Configuration configuration, String msId){ + MappedStatement mappedStatement = null; + try { + mappedStatement = configuration.getMappedStatement(msId, false); + } catch (Throwable t){ + //ignore + } + return mappedStatement; + } + + @Override + public Object plugin(Object target) { + return Plugin.wrap(target, this); + } + + @Override + public void setProperties(Properties properties) { + //缓存 count ms + msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties); + String dialectClass = properties.getProperty("dialect"); + if (StringUtil.isEmpty(dialectClass)) { + dialectClass = default_dialect_class; + } + try { + Class aClass = Class.forName(dialectClass); + dialect = (Dialect) aClass.newInstance(); + } catch (Exception e) { + throw new PageException(e); + } + dialect.setProperties(properties); + + String countSuffix = properties.getProperty("countSuffix"); + if (StringUtil.isNotEmpty(countSuffix)) { + this.countSuffix = countSuffix; + } + + try { + //反射获取 BoundSql 中的 additionalParameters 属性 + additionalParametersField = BoundSql.class.getDeclaredField("additionalParameters"); + additionalParametersField.setAccessible(true); + } catch (NoSuchFieldException e) { + throw new PageException(e); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.github.pagehelper.PageInterceptor.setProperties` reads without synchronization from `this.com.github.pagehelper.PageInterceptor.additionalParametersField`. Potentially races with write in method `PageInterceptor.intercept(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PageInterceptor.setProperties(Properties) + +### Procedure Id: +com.github.pagehelper.PageInterceptor.setProperties(java.util.Properties):void.7f6f30bd159da648d37afbfa1aa82ef6 + +### File: +src/main/java/com/github/pagehelper/PageInterceptor.java + +### Key: +PageInterceptor.java|setProperties|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +a54822aaa99e33def2f917fb2b0b1a2c + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-4156/instruction.md b/inferredbugs-4156/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f8931e8ddaa751541ce545b8faeade3cddbcadad --- /dev/null +++ b/inferredbugs-4156/instruction.md @@ -0,0 +1,343 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** Mybatis-PageHelper +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2017 abel533@gmail.com + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.github.pagehelper; + +import com.github.pagehelper.cache.Cache; +import com.github.pagehelper.cache.CacheFactory; +import com.github.pagehelper.util.MSUtils; +import com.github.pagehelper.util.StringUtil; +import org.apache.ibatis.cache.CacheKey; +import org.apache.ibatis.executor.Executor; +import org.apache.ibatis.mapping.BoundSql; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.plugin.*; +import org.apache.ibatis.session.Configuration; +import org.apache.ibatis.session.ResultHandler; +import org.apache.ibatis.session.RowBounds; + +import java.lang.reflect.Field; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +/** + * Mybatis - 通用分页拦截器
    + * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper + * + * @author liuzh/abel533/isea533 + * @version 5.0.0 + */ +@SuppressWarnings({"rawtypes", "unchecked"}) +@Intercepts( + { + @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), + @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}), + } +) +public class PageInterceptor implements Interceptor { + //缓存count查询的ms + protected Cache msCountMap = null; + private volatile Dialect dialect; + private String default_dialect_class = "com.github.pagehelper.PageHelper"; + private Field additionalParametersField; + private String countSuffix = "_COUNT"; + + @Override + public Object intercept(Invocation invocation) throws Throwable { + try { + Object[] args = invocation.getArgs(); + MappedStatement ms = (MappedStatement) args[0]; + Object parameter = args[1]; + RowBounds rowBounds = (RowBounds) args[2]; + ResultHandler resultHandler = (ResultHandler) args[3]; + Executor executor = (Executor) invocation.getTarget(); + CacheKey cacheKey; + BoundSql boundSql; + //由于逻辑关系,只会进入一次 + if(args.length == 4){ + //4 个参数时 + boundSql = ms.getBoundSql(parameter); + cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql); + } else { + //6 个参数时 + cacheKey = (CacheKey) args[4]; + boundSql = (BoundSql) args[5]; + } + + // Spring bean 方式配置时,如果没有配置属性就不会执行下面的 setProperties 方法,就不会初始化 + // 因此这里会出现 null 的情况 fixed #26 + if(dialect == null){ + synchronized (default_dialect_class){ + if(dialect == null){ + setProperties(new Properties()); + } + } + } + List resultList; + //调用方法判断是否需要进行分页,如果不需要,直接返回结果 + if (!dialect.skip(ms, parameter, rowBounds)) { + //反射获取动态参数 + String msId = ms.getId(); + Configuration configuration = ms.getConfiguration(); + Map additionalParameters = (Map) additionalParametersField.get(boundSql); + //判断是否需要进行 count 查询 + if (dialect.beforeCount(ms, parameter, rowBounds)) { + String countMsId = msId + countSuffix; + Long count; + //先判断是否存在手写的 count 查询 + MappedStatement countMs = getExistedMappedStatement(configuration, countMsId); + if(countMs != null){ + count = executeManualCount(executor, countMs, parameter, boundSql, resultHandler); + } else { + countMs = msCountMap.get(countMsId); + //自动创建 + if (countMs == null) { + //根据当前的 ms 创建一个返回值为 Long 类型的 ms + countMs = MSUtils.newCountMappedStatement(ms, countMsId); + msCountMap.put(countMsId, countMs); + } + count = executeAutoCount(executor, countMs, parameter, boundSql, rowBounds, resultHandler); + } + //处理查询总数 + //返回 true 时继续分页查询,false 时直接返回 + if (!dialect.afterCount(count, parameter, rowBounds)) { + //当查询总数为 0 时,直接返回空的结果 + return dialect.afterPage(new ArrayList(), parameter, rowBounds); + } + } + //判断是否需要进行分页查询 + if (dialect.beforePage(ms, parameter, rowBounds)) { + //生成分页的缓存 key + CacheKey pageKey = cacheKey; + //处理参数对象 + parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey); + //调用方言获取分页 sql + String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey); + BoundSql pageBoundSql = new BoundSql(configuration, pageSql, boundSql.getParameterMappings(), parameter); + //设置动态参数 + for (String key : additionalParameters.keySet()) { + pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key)); + } + //执行分页查询 + resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql); + } else { + //不执行分页的情况下,也不执行内存分页 + resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql); + } + } else { + //rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页 + resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql); + } + return dialect.afterPage(resultList, parameter, rowBounds); + } finally { + dialect.afterAll(); + } + } + + /** + * 执行手动设置的 count 查询,该查询支持的参数必须和被分页的方法相同 + * + * @param executor + * @param countMs + * @param parameter + * @param boundSql + * @param resultHandler + * @return + * @throws IllegalAccessException + * @throws SQLException + */ + private Long executeManualCount(Executor executor, MappedStatement countMs, + Object parameter, BoundSql boundSql, + ResultHandler resultHandler) throws IllegalAccessException, SQLException { + CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql); + BoundSql countBoundSql = countMs.getBoundSql(parameter); + Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey, countBoundSql); + Long count = ((Number) ((List) countResultList).get(0)).longValue(); + return count; + } + + /** + * 执行自动生成的 count 查询 + * + * @param executor + * @param countMs + * @param parameter + * @param boundSql + * @param rowBounds + * @param resultHandler + * @return + * @throws IllegalAccessException + * @throws SQLException + */ + private Long executeAutoCount(Executor executor, MappedStatement countMs, + Object parameter, BoundSql boundSql, + RowBounds rowBounds, ResultHandler resultHandler) throws IllegalAccessException, SQLException { + Map additionalParameters = (Map) additionalParametersField.get(boundSql); + //创建 count 查询的缓存 key + CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql); + //调用方言获取 count sql + String countSql = dialect.getCountSql(countMs, boundSql, parameter, rowBounds, countKey); + //countKey.update(countSql); + BoundSql countBoundSql = new BoundSql(countMs.getConfiguration(), countSql, boundSql.getParameterMappings(), parameter); + //当使用动态 SQL 时,可能会产生临时的参数,这些参数需要手动设置到新的 BoundSql 中 + for (String key : additionalParameters.keySet()) { + countBoundSql.setAdditionalParameter(key, additionalParameters.get(key)); + } + //执行 count 查询 + Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey, countBoundSql); + Long count = (Long) ((List) countResultList).get(0); + return count; + } + + /** + * 尝试获取已经存在的在 MS,提供对手写count和page的支持 + * + * @param configuration + * @param msId + * @return + */ + private MappedStatement getExistedMappedStatement(Configuration configuration, String msId){ + MappedStatement mappedStatement = null; + try { + mappedStatement = configuration.getMappedStatement(msId, false); + } catch (Throwable t){ + //ignore + } + return mappedStatement; + } + + @Override + public Object plugin(Object target) { + return Plugin.wrap(target, this); + } + + @Override + public void setProperties(Properties properties) { + //缓存 count ms + msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties); + String dialectClass = properties.getProperty("dialect"); + if (StringUtil.isEmpty(dialectClass)) { + dialectClass = default_dialect_class; + } + try { + Class aClass = Class.forName(dialectClass); + dialect = (Dialect) aClass.newInstance(); + } catch (Exception e) { + throw new PageException(e); + } + dialect.setProperties(properties); + + String countSuffix = properties.getProperty("countSuffix"); + if (StringUtil.isNotEmpty(countSuffix)) { + this.countSuffix = countSuffix; + } + + try { + //反射获取 BoundSql 中的 additionalParameters 属性 + additionalParametersField = BoundSql.class.getDeclaredField("additionalParameters"); + additionalParametersField.setAccessible(true); + } catch (NoSuchFieldException e) { + throw new PageException(e); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.github.pagehelper.PageInterceptor.intercept` reads without synchronization from `this.com.github.pagehelper.PageInterceptor.countSuffix`. Potentially races with write in method `PageInterceptor.setProperties(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object PageInterceptor.intercept(Invocation) + +### Procedure Id: +com.github.pagehelper.PageInterceptor.intercept(org.apache.ibatis.plugin.Invocation):java.lang.Objec.ec26e9d4e10a980f77b8ca004ccf40b7 + +### File: +src/main/java/com/github/pagehelper/PageInterceptor.java + +### Key: +PageInterceptor.java|intercept|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +1cc0c58708ec328d78b78463f2cd0d35 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-4157/instruction.md b/inferredbugs-4157/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d2288fe92fb3d863a7b2a41f5330ef75f02b5d74 --- /dev/null +++ b/inferredbugs-4157/instruction.md @@ -0,0 +1,343 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** Mybatis-PageHelper +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2017 abel533@gmail.com + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.github.pagehelper; + +import com.github.pagehelper.cache.Cache; +import com.github.pagehelper.cache.CacheFactory; +import com.github.pagehelper.util.MSUtils; +import com.github.pagehelper.util.StringUtil; +import org.apache.ibatis.cache.CacheKey; +import org.apache.ibatis.executor.Executor; +import org.apache.ibatis.mapping.BoundSql; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.plugin.*; +import org.apache.ibatis.session.Configuration; +import org.apache.ibatis.session.ResultHandler; +import org.apache.ibatis.session.RowBounds; + +import java.lang.reflect.Field; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +/** + * Mybatis - 通用分页拦截器
    + * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper + * + * @author liuzh/abel533/isea533 + * @version 5.0.0 + */ +@SuppressWarnings({"rawtypes", "unchecked"}) +@Intercepts( + { + @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), + @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}), + } +) +public class PageInterceptor implements Interceptor { + //缓存count查询的ms + protected Cache msCountMap = null; + private volatile Dialect dialect; + private String default_dialect_class = "com.github.pagehelper.PageHelper"; + private Field additionalParametersField; + private String countSuffix = "_COUNT"; + + @Override + public Object intercept(Invocation invocation) throws Throwable { + try { + Object[] args = invocation.getArgs(); + MappedStatement ms = (MappedStatement) args[0]; + Object parameter = args[1]; + RowBounds rowBounds = (RowBounds) args[2]; + ResultHandler resultHandler = (ResultHandler) args[3]; + Executor executor = (Executor) invocation.getTarget(); + CacheKey cacheKey; + BoundSql boundSql; + //由于逻辑关系,只会进入一次 + if(args.length == 4){ + //4 个参数时 + boundSql = ms.getBoundSql(parameter); + cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql); + } else { + //6 个参数时 + cacheKey = (CacheKey) args[4]; + boundSql = (BoundSql) args[5]; + } + + // Spring bean 方式配置时,如果没有配置属性就不会执行下面的 setProperties 方法,就不会初始化 + // 因此这里会出现 null 的情况 fixed #26 + if(dialect == null){ + synchronized (default_dialect_class){ + if(dialect == null){ + setProperties(new Properties()); + } + } + } + List resultList; + //调用方法判断是否需要进行分页,如果不需要,直接返回结果 + if (!dialect.skip(ms, parameter, rowBounds)) { + //反射获取动态参数 + String msId = ms.getId(); + Configuration configuration = ms.getConfiguration(); + Map additionalParameters = (Map) additionalParametersField.get(boundSql); + //判断是否需要进行 count 查询 + if (dialect.beforeCount(ms, parameter, rowBounds)) { + String countMsId = msId + countSuffix; + Long count; + //先判断是否存在手写的 count 查询 + MappedStatement countMs = getExistedMappedStatement(configuration, countMsId); + if(countMs != null){ + count = executeManualCount(executor, countMs, parameter, boundSql, resultHandler); + } else { + countMs = msCountMap.get(countMsId); + //自动创建 + if (countMs == null) { + //根据当前的 ms 创建一个返回值为 Long 类型的 ms + countMs = MSUtils.newCountMappedStatement(ms, countMsId); + msCountMap.put(countMsId, countMs); + } + count = executeAutoCount(executor, countMs, parameter, boundSql, rowBounds, resultHandler); + } + //处理查询总数 + //返回 true 时继续分页查询,false 时直接返回 + if (!dialect.afterCount(count, parameter, rowBounds)) { + //当查询总数为 0 时,直接返回空的结果 + return dialect.afterPage(new ArrayList(), parameter, rowBounds); + } + } + //判断是否需要进行分页查询 + if (dialect.beforePage(ms, parameter, rowBounds)) { + //生成分页的缓存 key + CacheKey pageKey = cacheKey; + //处理参数对象 + parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey); + //调用方言获取分页 sql + String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey); + BoundSql pageBoundSql = new BoundSql(configuration, pageSql, boundSql.getParameterMappings(), parameter); + //设置动态参数 + for (String key : additionalParameters.keySet()) { + pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key)); + } + //执行分页查询 + resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql); + } else { + //不执行分页的情况下,也不执行内存分页 + resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql); + } + } else { + //rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页 + resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql); + } + return dialect.afterPage(resultList, parameter, rowBounds); + } finally { + dialect.afterAll(); + } + } + + /** + * 执行手动设置的 count 查询,该查询支持的参数必须和被分页的方法相同 + * + * @param executor + * @param countMs + * @param parameter + * @param boundSql + * @param resultHandler + * @return + * @throws IllegalAccessException + * @throws SQLException + */ + private Long executeManualCount(Executor executor, MappedStatement countMs, + Object parameter, BoundSql boundSql, + ResultHandler resultHandler) throws IllegalAccessException, SQLException { + CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql); + BoundSql countBoundSql = countMs.getBoundSql(parameter); + Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey, countBoundSql); + Long count = ((Number) ((List) countResultList).get(0)).longValue(); + return count; + } + + /** + * 执行自动生成的 count 查询 + * + * @param executor + * @param countMs + * @param parameter + * @param boundSql + * @param rowBounds + * @param resultHandler + * @return + * @throws IllegalAccessException + * @throws SQLException + */ + private Long executeAutoCount(Executor executor, MappedStatement countMs, + Object parameter, BoundSql boundSql, + RowBounds rowBounds, ResultHandler resultHandler) throws IllegalAccessException, SQLException { + Map additionalParameters = (Map) additionalParametersField.get(boundSql); + //创建 count 查询的缓存 key + CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql); + //调用方言获取 count sql + String countSql = dialect.getCountSql(countMs, boundSql, parameter, rowBounds, countKey); + //countKey.update(countSql); + BoundSql countBoundSql = new BoundSql(countMs.getConfiguration(), countSql, boundSql.getParameterMappings(), parameter); + //当使用动态 SQL 时,可能会产生临时的参数,这些参数需要手动设置到新的 BoundSql 中 + for (String key : additionalParameters.keySet()) { + countBoundSql.setAdditionalParameter(key, additionalParameters.get(key)); + } + //执行 count 查询 + Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey, countBoundSql); + Long count = (Long) ((List) countResultList).get(0); + return count; + } + + /** + * 尝试获取已经存在的在 MS,提供对手写count和page的支持 + * + * @param configuration + * @param msId + * @return + */ + private MappedStatement getExistedMappedStatement(Configuration configuration, String msId){ + MappedStatement mappedStatement = null; + try { + mappedStatement = configuration.getMappedStatement(msId, false); + } catch (Throwable t){ + //ignore + } + return mappedStatement; + } + + @Override + public Object plugin(Object target) { + return Plugin.wrap(target, this); + } + + @Override + public void setProperties(Properties properties) { + //缓存 count ms + msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties); + String dialectClass = properties.getProperty("dialect"); + if (StringUtil.isEmpty(dialectClass)) { + dialectClass = default_dialect_class; + } + try { + Class aClass = Class.forName(dialectClass); + dialect = (Dialect) aClass.newInstance(); + } catch (Exception e) { + throw new PageException(e); + } + dialect.setProperties(properties); + + String countSuffix = properties.getProperty("countSuffix"); + if (StringUtil.isNotEmpty(countSuffix)) { + this.countSuffix = countSuffix; + } + + try { + //反射获取 BoundSql 中的 additionalParameters 属性 + additionalParametersField = BoundSql.class.getDeclaredField("additionalParameters"); + additionalParametersField.setAccessible(true); + } catch (NoSuchFieldException e) { + throw new PageException(e); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.github.pagehelper.PageInterceptor.intercept` reads without synchronization from `this.com.github.pagehelper.PageInterceptor.additionalParametersField`. Potentially races with write in method `PageInterceptor.setProperties(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object PageInterceptor.intercept(Invocation) + +### Procedure Id: +com.github.pagehelper.PageInterceptor.intercept(org.apache.ibatis.plugin.Invocation):java.lang.Objec.ec26e9d4e10a980f77b8ca004ccf40b7 + +### File: +src/main/java/com/github/pagehelper/PageInterceptor.java + +### Key: +PageInterceptor.java|intercept|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +3f5abe62b427edd3330972f64fc8a382 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-4160/instruction.md b/inferredbugs-4160/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..869886fbfc8f2787f6d7d8fb6c2a6256b4cfb1bc --- /dev/null +++ b/inferredbugs-4160/instruction.md @@ -0,0 +1,836 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** giraph +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.giraph.zk; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.net.ConnectException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketTimeoutException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.apache.commons.io.FileUtils; +import org.apache.giraph.graph.GiraphJob; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FileStatus; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.mapreduce.Mapper; +import org.apache.log4j.Logger; +import org.apache.zookeeper.server.quorum.QuorumPeerMain; + +/** + * Manages the election of ZooKeeper servers, starting/stopping the services, + * etc. + */ +public class ZooKeeperManager { + /** Job context (mainly for progress) */ + private Mapper.Context context; + /** Hadoop configuration */ + private final Configuration conf; + /** Class logger */ + private static final Logger LOG = Logger.getLogger(ZooKeeperManager.class); + /** Task partition, to ensure uniqueness */ + private final int taskPartition; + /** HDFS base directory for all file-based coordination */ + private final Path baseDirectory; + /** + * HDFS task ZooKeeper candidate/completed + * directory for all file-based coordination + */ + private final Path taskDirectory; + /** + * HDFS ZooKeeper server ready/done directory + * for all file-based coordination + */ + private final Path serverDirectory; + /** HDFS path to whether the task is done */ + private final Path myClosedPath; + /** Polling msecs timeout */ + private final int pollMsecs; + /** Server count */ + private final int serverCount; + /** File system */ + private final FileSystem fs; + /** ZooKeeper process */ + private Process zkProcess = null; + /** Thread that gets the zkProcess output */ + private StreamCollector zkProcessCollector = null; + /** ZooKeeper local file system directory */ + private String zkDir = null; + /** ZooKeeper config file path */ + private String configFilePath = null; + /** ZooKeeper server list */ + private final Map zkServerPortMap = + new TreeMap(); + /** ZooKeeper base port */ + private int zkBasePort = -1; + /** Final ZooKeeper server port list (for clients) */ + private String zkServerPortString; + /** My hostname */ + private String myHostname = null; + /** Job id, to ensure uniqueness */ + private final String jobId; + /** + * Default local ZooKeeper prefix directory to use (where ZooKeeper server + * files will go) + */ + private final String zkDirDefault; + + + /** Separates the hostname and task in the candidate stamp */ + private static final String HOSTNAME_TASK_SEPARATOR = " "; + /** The ZooKeeperString filename prefix */ + private static final String ZOOKEEPER_SERVER_LIST_FILE_PREFIX = + "zkServerList_"; + /** Denotes that the computation is done for a partition */ + private static final String COMPUTATION_DONE_SUFFIX = ".COMPUTATION_DONE"; + /** State of the application */ + public enum State { + FAILED, + FINISHED + } + + /** + * Generate the final ZooKeeper coordination directory on HDFS + * + * @return directory path with job id + */ + final private String getFinalZooKeeperPath() { + return GiraphJob.ZOOKEEPER_MANAGER_DIR_DEFAULT + "/" + jobId; + } + + /** + * Collects the output of a stream and dumps it to the log. + */ + private static class StreamCollector extends Thread { + /** Input stream to dump */ + private final InputStream is; + + /** + * Constructor. + * @param is InputStream to dump to LOG.info + */ + public StreamCollector(final InputStream is) { + super(StreamCollector.class.getName()); + this.is = is; + } + + @Override + public void run() { + InputStreamReader streamReader = new InputStreamReader(is); + BufferedReader bufferedReader = new BufferedReader(streamReader); + String line = null; + try { + while ((line = bufferedReader.readLine()) != null) { + LOG.debug(line); + } + } catch (IOException e) { + LOG.error("run: Ignoring IOException", e); + } + } + } + + public ZooKeeperManager(Mapper.Context context) + throws IOException { + this.context = context; + conf = context.getConfiguration(); + taskPartition = conf.getInt("mapred.task.partition", -1); + jobId = conf.get("mapred.job.id", "Unknown Job"); + baseDirectory = + new Path(conf.get(GiraphJob.ZOOKEEPER_MANAGER_DIRECTORY, + getFinalZooKeeperPath())); + taskDirectory = new Path(baseDirectory, + "_task"); + serverDirectory = new Path(baseDirectory, + "_zkServer"); + myClosedPath = new Path(taskDirectory, + Integer.toString(taskPartition) + + COMPUTATION_DONE_SUFFIX); + pollMsecs = conf.getInt( + GiraphJob.ZOOKEEPER_SERVERLIST_POLL_MSECS, + GiraphJob.ZOOKEEPER_SERVERLIST_POLL_MSECS_DEFAULT); + serverCount = conf.getInt( + GiraphJob.ZOOKEEPER_SERVER_COUNT, + GiraphJob.ZOOKEEPER_SERVER_COUNT_DEFAULT); + String jobLocalDir = conf.get("job.local.dir"); + if (jobLocalDir != null) { // for non-local jobs + zkDirDefault = jobLocalDir + + "/_bspZooKeeper"; + } else { + zkDirDefault = System.getProperty("user.dir") + "/_bspZooKeeper"; + } + zkDir = conf.get(GiraphJob.ZOOKEEPER_DIR, zkDirDefault); + configFilePath = zkDir + "/zoo.cfg"; + zkBasePort = conf.getInt( + GiraphJob.ZOOKEEPER_SERVER_PORT, + GiraphJob.ZOOKEEPER_SERVER_PORT_DEFAULT); + + + myHostname = InetAddress.getLocalHost().getCanonicalHostName(); + fs = FileSystem.get(conf); + } + + /** + * Create the candidate stamps and decide on the servers to start if + * you are partition 0. + * @throws IOException + * @throws InterruptedException + */ + public void setup() throws IOException, InterruptedException { + createCandidateStamp(); + getZooKeeperServerList(); + } + + /** + * Create a HDFS stamp for this task. If another task already + * created it, then this one will fail, which is fine. + * @return true if create, false otherwise + */ + public void createCandidateStamp() { + try { + fs.mkdirs(baseDirectory); + LOG.info("createCandidateStamp: Made the directory " + + baseDirectory); + } catch (IOException e) { + LOG.error("createCandidateStamp: Failed to mkdirs " + + baseDirectory); + } + + Path myCandidacyPath = new Path( + taskDirectory, myHostname + + HOSTNAME_TASK_SEPARATOR + taskPartition); + try { + if (LOG.isInfoEnabled()) { + LOG.info("createCandidateStamp: Creating my filestamp " + + myCandidacyPath); + } + fs.createNewFile(myCandidacyPath); + } catch (IOException e) { + LOG.error("createCandidateStamp: Failed (maybe previous task " + + "failed) to create filestamp " + myCandidacyPath, e); + } + } + + /** + * Every task must create a stamp to let the ZooKeeper servers know that + * they can shutdown. This also lets the task know that it was already + * completed. + */ + private void createZooKeeperClosedStamp() { + try { + LOG.info("createZooKeeperClosedStamp: Creating my filestamp " + + myClosedPath); + fs.createNewFile(myClosedPath); + } catch (IOException e) { + LOG.error("createZooKeeperClosedStamp: Failed (maybe previous task " + + "failed) to create filestamp " + myClosedPath); + } + } + + /** + * Check if all the computation is done. + * @return true if all computation is done. + */ + public boolean computationDone() { + try { + return fs.exists(myClosedPath); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Task 0 will call this to create the ZooKeeper server list. The result is + * a file that describes the ZooKeeper servers through the filename. + * @throws IOException + * @throws InterruptedException + */ + private void createZooKeeperServerList() + throws IOException, InterruptedException { + int candidateRetrievalAttempt = 0; + Map hostnameTaskMap = + new TreeMap(); + while (true) { + FileStatus [] fileStatusArray = + fs.listStatus(taskDirectory); + hostnameTaskMap.clear(); + if (fileStatusArray.length > 0) { + for (int i = 0; i < fileStatusArray.length; ++i) { + String[] hostnameTaskArray = + fileStatusArray[i].getPath().getName().split( + HOSTNAME_TASK_SEPARATOR); + if (hostnameTaskArray.length != 2) { + throw new RuntimeException( + "getZooKeeperServerList: Task 0 failed " + + "to parse " + + fileStatusArray[i].getPath().getName()); + } + if (!hostnameTaskMap.containsKey(hostnameTaskArray[0])) { + hostnameTaskMap.put(hostnameTaskArray[0], + new Integer(hostnameTaskArray[1])); + } + } + if (LOG.isInfoEnabled()) { + LOG.info("getZooKeeperServerList: Got " + + hostnameTaskMap.keySet() + " " + + hostnameTaskMap.size() + " hosts from " + + fileStatusArray.length + " candidates when " + + serverCount + " required (polling period is " + + pollMsecs + ") on attempt " + + candidateRetrievalAttempt); + } + if (hostnameTaskMap.size() >= serverCount) { + break; + } + ++candidateRetrievalAttempt; + Thread.sleep(pollMsecs); + } + } + StringBuffer serverListFile = + new StringBuffer(ZOOKEEPER_SERVER_LIST_FILE_PREFIX); + int numServers = 0; + for (Map.Entry hostnameTask : + hostnameTaskMap.entrySet()) { + serverListFile.append(hostnameTask.getKey() + + HOSTNAME_TASK_SEPARATOR + hostnameTask.getValue() + + HOSTNAME_TASK_SEPARATOR); + if (++numServers == serverCount) { + break; + } + } + Path serverListPath = + new Path(baseDirectory, serverListFile.toString()); + if (LOG.isInfoEnabled()) { + LOG.info("createZooKeeperServerList: Creating the final " + + "ZooKeeper file '" + serverListPath + "'"); + } + fs.createNewFile(serverListPath); + } + + /** + * Make an attempt to get the server list file by looking for a file in + * the appropriate directory with the prefix + * ZOOKEEPER_SERVER_LIST_FILE_PREFIX. + * @return null if not found or the filename if found + * @throws IOException + */ + private String getServerListFile() throws IOException { + String serverListFile = null; + FileStatus [] fileStatusArray = + fs.listStatus(baseDirectory); + for (FileStatus fileStatus : fileStatusArray) { + if (fileStatus.getPath().getName().startsWith( + ZOOKEEPER_SERVER_LIST_FILE_PREFIX)) { + serverListFile = fileStatus.getPath().getName(); + break; + } + } + return serverListFile; + } + + /** + * Task 0 is the designated master and will generate the server list + * (unless it has already done so). Other + * tasks will consume the file after it is created (just the filename). + * @throws IOException + * @throws InterruptedException + */ + private void getZooKeeperServerList() + throws IOException, InterruptedException { + int serverListFileAttempt = 0; + String serverListFile = null; + + if (taskPartition == 0) { + serverListFile = getServerListFile(); + if (serverListFile == null) { + createZooKeeperServerList(); + } + } + + while (true) { + serverListFile = getServerListFile(); + if (LOG.isInfoEnabled()) { + LOG.info("getZooKeeperServerList: For task " + taskPartition + + ", got file '" + serverListFile + + "' (polling period is " + + pollMsecs + ")"); + } + if (serverListFile != null) { + break; + } + ++serverListFileAttempt; + try { + Thread.sleep(pollMsecs); + } catch (InterruptedException e) { + LOG.warn("getZooKeeperServerList: Strange interrupted " + + "exception " + e.getMessage()); + } + + } + + List serverHostList = Arrays.asList(serverListFile.substring( + ZOOKEEPER_SERVER_LIST_FILE_PREFIX.length()).split( + HOSTNAME_TASK_SEPARATOR)); + if (LOG.isInfoEnabled()) { + LOG.info("getZooKeeperServerList: Found " + serverHostList + " " + + serverHostList.size() + + " hosts in filename '" + serverListFile + "'"); + } + if (serverHostList.size() != serverCount * 2) { + throw new IllegalStateException( + "getZooKeeperServerList: Impossible " + + " that " + serverHostList.size() + + " != 2 * " + + serverCount + " asked for."); + } + + for (int i = 0; i < serverHostList.size(); i += 2) { + zkServerPortMap.put(serverHostList.get(i), + Integer.parseInt(serverHostList.get(i+1))); + } + zkServerPortString = ""; + for (String server : zkServerPortMap.keySet()) { + if (zkServerPortString.length() > 0) { + zkServerPortString += ","; + } + zkServerPortString += server + ":" + zkBasePort; + } + } + + /** + * Users can get the server port string to connect to ZooKeeper + * @return server port string - comma separated + */ + public String getZooKeeperServerPortString() { + return zkServerPortString; + } + + /** + * Whoever is elected to be a ZooKeeper server must generate a config file + * locally. + */ + private void generateZooKeeperConfigFile(List serverList) { + if (LOG.isInfoEnabled()) { + LOG.info("generateZooKeeperConfigFile: Creating file " + + configFilePath + " in " + zkDir + " with base port " + + zkBasePort); + } + try { + File zkDirFile = new File(this.zkDir); + zkDirFile.mkdirs(); + File configFile = new File(configFilePath); + configFile.delete(); + configFile.createNewFile(); + configFile.setWritable(true, false); // writable by everybody + OutputStreamWriter writer = new FileWriter(configFilePath); + writer.write("tickTime=" + GiraphJob.DEFAULT_ZOOKEEPER_TICK_TIME + "\n"); + writer.write("dataDir=" + this.zkDir + "\n"); + writer.write("clientPort=" + zkBasePort + "\n"); + writer.write("maxClientCnxns=" + + GiraphJob.DEFAULT_ZOOKEEPER_MAX_CLIENT_CNXNS +"\n"); + writer.write("minSessionTimeout=" + + GiraphJob.DEFAULT_ZOOKEEPER_MIN_SESSION_TIMEOUT +"\n"); + writer.write("maxSessionTimeout=" + + GiraphJob.DEFAULT_ZOOKEEPER_MAX_SESSION_TIMEOUT +"\n"); + writer.write("initLimit=" + + GiraphJob.DEFAULT_ZOOKEEPER_INIT_LIMIT + "\n"); + writer.write("syncLimit=" + + GiraphJob.DEFAULT_ZOOKEEPER_SYNC_LIMIT + "\n"); + writer.write("snapCount=" + + GiraphJob.DEFAULT_ZOOKEEPER_SNAP_COUNT + "\n"); + if (serverList.size() != 1) { + writer.write("electionAlg=0\n"); + for (int i = 0; i < serverList.size(); ++i) { + writer.write("server." + i + "=" + serverList.get(i) + + ":" + (zkBasePort + 1) + + ":" + (zkBasePort + 2) + "\n"); + if (myHostname.equals(serverList.get(i))) { + OutputStreamWriter myidWriter = new FileWriter( + zkDir + "/myid"); + myidWriter.write(i + "\n"); + myidWriter.close(); + } + } + } + writer.flush(); + writer.close(); + } catch (IOException e) { + throw new IllegalStateException( + "generateZooKeeperConfigFile: Failed to write file", e); + } + } + + /** + * If this task has been selected, online a ZooKeeper server. Otherwise, + * wait until this task knows that the ZooKeeper servers have been onlined. + */ + public void onlineZooKeeperServers() { + Integer taskId = zkServerPortMap.get(myHostname); + if ((taskId != null) && (taskId.intValue() == taskPartition)) { + File zkDirFile = new File(this.zkDir); + try { + if (LOG.isInfoEnabled()) { + LOG.info("onlineZooKeeperServers: Trying to delete old " + + "directory " + this.zkDir); + } + FileUtils.deleteDirectory(zkDirFile); + } catch (IOException e) { + LOG.warn("onlineZooKeeperServers: Failed to delete " + + "directory " + this.zkDir); + } + generateZooKeeperConfigFile( + new ArrayList(zkServerPortMap.keySet())); + ProcessBuilder processBuilder = new ProcessBuilder(); + List commandList = new ArrayList(); + String javaHome = System.getProperty("java.home"); + if (javaHome == null) { + throw new IllegalArgumentException( + "onlineZooKeeperServers: java.home is not set!"); + } + commandList.add(javaHome + "/bin/java"); + commandList.add(conf.get(GiraphJob.ZOOKEEPER_JAVA_OPTS, + GiraphJob.ZOOKEEPER_JAVA_OPTS_DEFAULT)); + commandList.add("-cp"); + Path fullJarPath = new Path(conf.get(GiraphJob.ZOOKEEPER_JAR)); + commandList.add(fullJarPath.toString()); + commandList.add(QuorumPeerMain.class.getName()); + commandList.add(configFilePath); + processBuilder.command(commandList); + File execDirectory = new File(zkDir); + processBuilder.directory(execDirectory); + processBuilder.redirectErrorStream(true); + LOG.info("onlineZooKeeperServers: Attempting to start ZooKeeper " + + "server with command " + commandList); + try { + synchronized (this) { + zkProcess = processBuilder.start(); + } + zkProcessCollector = + new StreamCollector(zkProcess.getInputStream()); + zkProcessCollector.start(); + Runnable runnable = new Runnable() { + public void run() { + synchronized (this) { + if (zkProcess != null) { + LOG.warn("onlineZooKeeperServers: "+ + "Forced a shutdown hook kill of the " + + "ZooKeeper process."); + zkProcess.destroy(); + } + } + } + }; + Runtime.getRuntime().addShutdownHook(new Thread(runnable)); + } catch (IOException e) { + LOG.error("onlineZooKeeperServers: Failed to start " + + "ZooKeeper process"); + throw new RuntimeException(e); + } + + /* + * Once the server is up and running, notify that this server is up + * and running by dropping a ready stamp. + */ + int connectAttempts = 0; + while (connectAttempts < 5) { + try { + if (LOG.isInfoEnabled()) { + LOG.info("onlineZooKeeperServers: Connect attempt " + + connectAttempts + " trying to connect to " + + myHostname + ":" + zkBasePort + + " with poll msecs = " + pollMsecs); + } + InetSocketAddress zkServerAddress = + new InetSocketAddress(myHostname, zkBasePort); + Socket testServerSock = new Socket(); + testServerSock.connect(zkServerAddress, 5000); + LOG.info("onlineZooKeeperServers: Connected!"); + break; + } catch (SocketTimeoutException e) { + LOG.warn("onlineZooKeeperServers: Got " + + "SocketTimeoutException", e); + } catch (ConnectException e) { + LOG.warn("onlineZooKeeperServers: Got " + + "ConnectException", e); + } catch (IOException e) { + LOG.warn("onlineZooKeeperServers: Got " + + "IOException", e); + } + + ++connectAttempts; + try { + Thread.sleep(pollMsecs); + } catch (InterruptedException e) { + LOG.warn("onlineZooKeeperServers: Sleep of " + pollMsecs + + " interrupted - " + e.getMessage()); + } + } + if (connectAttempts == 5) { + throw new IllegalStateException( + "onlineZooKeeperServers: Failed to connect in 5 tries!"); + } + Path myReadyPath = new Path( + serverDirectory, myHostname + + HOSTNAME_TASK_SEPARATOR + taskPartition); + try { + if (LOG.isInfoEnabled()) { + LOG.info("onlineZooKeeperServers: Creating my filestamp " + + myReadyPath); + } + fs.createNewFile(myReadyPath); + } catch (IOException e) { + LOG.error("onlineZooKeeperServers: Failed (maybe previous " + + "task failed) to create filestamp " + myReadyPath); + } + } + else { + List foundList = new ArrayList(); + int readyRetrievalAttempt = 0; + while (true) { + try { + FileStatus [] fileStatusArray = + fs.listStatus(serverDirectory); + foundList.clear(); + if ((fileStatusArray != null) && + (fileStatusArray.length > 0)) { + for (int i = 0; i < fileStatusArray.length; ++i) { + String[] hostnameTaskArray = + fileStatusArray[i].getPath().getName().split( + HOSTNAME_TASK_SEPARATOR); + if (hostnameTaskArray.length != 2) { + throw new RuntimeException( + "getZooKeeperServerList: Task 0 failed " + + "to parse " + + fileStatusArray[i].getPath().getName()); + } + foundList.add(hostnameTaskArray[0]); + } + if (LOG.isInfoEnabled()) { + LOG.info("onlineZooKeeperServers: Got " + + foundList + " " + + foundList.size() + " hosts from " + + fileStatusArray.length + + " ready servers when " + + serverCount + + " required (polling period is " + + pollMsecs + ") on attempt " + + readyRetrievalAttempt); + } + if (foundList.containsAll(zkServerPortMap.keySet())) { + break; + } + } else { + if (LOG.isInfoEnabled()) { + LOG.info("onlineZooKeeperSErvers: Empty " + + "directory " + serverDirectory + + ", waiting " + pollMsecs + " msecs."); + } + } + Thread.sleep(pollMsecs); + ++readyRetrievalAttempt; + } catch (IOException e) { + throw new RuntimeException(e); + } catch (InterruptedException e) { + LOG.warn("onlineZooKeeperServers: Strange interrupt from " + + e.getMessage()); + } + } + } + } + + /** + * Wait for all map tasks to signal completion. + * + * @param totalMapTasks Number of map tasks to wait for + */ + private void waitUntilAllTasksDone(int totalMapTasks) { + int attempt = 0; + while (true) { + try { + FileStatus [] fileStatusArray = + fs.listStatus(taskDirectory); + int totalDone = 0; + if (fileStatusArray.length > 0) { + for (int i = 0; i < fileStatusArray.length; ++i) { + if (fileStatusArray[i].getPath().getName().endsWith( + COMPUTATION_DONE_SUFFIX)) { + ++totalDone; + } + } + } + LOG.info("waitUntilAllTasksDone: Got " + totalDone + + " and " + totalMapTasks + + " desired (polling period is " + + pollMsecs + ") on attempt " + + attempt); + if (totalDone >= totalMapTasks) { + break; + } + ++attempt; + Thread.sleep(pollMsecs); + context.progress(); + } catch (IOException e) { + LOG.warn("waitUntilAllTasksDone: Got IOException.", e); + } catch (InterruptedException e) { + LOG.warn("waitUntilAllTasksDone: Got InterruptedException" + e); + } + } + } + + /** + * Notify the ZooKeeper servers that this partition is done with all + * ZooKeeper communication. If this task is running a ZooKeeper server, + * kill it when all partitions are done and wait for + * completion. Clean up the ZooKeeper local directory as well. + * + * @param success when true, call @createZooKeeperClosedStamp + */ + public void offlineZooKeeperServers(State state) { + if (state == State.FINISHED) { + createZooKeeperClosedStamp(); + } + synchronized (this) { + if (zkProcess != null) { + int totalMapTasks = conf.getInt("mapred.map.tasks", -1); + waitUntilAllTasksDone(totalMapTasks); + zkProcess.destroy(); + int exitValue = -1; + File zkDirFile = null; + try { + zkProcessCollector.join(); + exitValue = zkProcess.waitFor(); + zkDirFile = new File(zkDir); + FileUtils.deleteDirectory(zkDirFile); + } catch (InterruptedException e) { + LOG.warn("offlineZooKeeperServers: " + + "InterruptedException, but continuing ", + e); + } catch (IOException e) { + LOG.warn("offlineZooKeeperSevers: " + + "IOException, but continuing", + e); + } + if (LOG.isInfoEnabled()) { + LOG.info("offlineZooKeeperServers: waitFor returned " + + exitValue + " and deleted directory " + zkDir); + } + zkProcess = null; + } + } + } + + /** + * Is this task running a ZooKeeper server? Only could be true if called + * after onlineZooKeeperServers(). + * + * @return true if running a ZooKeeper server, false otherwise + */ + public boolean runsZooKeeper() { + synchronized (this) { + return zkProcess != null; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.giraph.zk.ZooKeeperManager.onlineZooKeeperServers` reads without synchronization from `this.org.apache.giraph.zk.ZooKeeperManager.zkProcess`. Potentially races with write in method `ZooKeeperManager.onlineZooKeeperServers()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ZooKeeperManager.onlineZooKeeperServers() + +### Procedure Id: +org.apache.giraph.zk.ZooKeeperManager.onlineZooKeeperServers():void.a727034a4ecf5b9abafcf564c09ce0d5 + +### File: +src/main/java/org/apache/giraph/zk/ZooKeeperManager.java + +### Key: +ZooKeeperManager.java|onlineZooKeeperServers|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +0ff8e99f74524f86e2f90cb5fd01a542 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-4161/instruction.md b/inferredbugs-4161/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c0cf9d78677a6029079f60521f55f66b8565a902 --- /dev/null +++ b/inferredbugs-4161/instruction.md @@ -0,0 +1,2064 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** giraph +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to Yahoo! under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. Yahoo! licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.giraph.graph; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutput; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NavigableMap; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import org.apache.commons.codec.binary.Base64; + +import org.apache.log4j.Logger; +import org.apache.hadoop.fs.FSDataOutputStream; +import org.apache.hadoop.fs.FileStatus; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.fs.PathFilter; +import org.apache.hadoop.io.Text; +import org.apache.hadoop.io.Writable; +import org.apache.hadoop.io.WritableComparable; + +import org.apache.hadoop.mapred.RunningJob; +import org.apache.hadoop.mapreduce.Counter; +import org.apache.hadoop.mapreduce.InputSplit; +import org.apache.hadoop.mapreduce.Mapper; + +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher.Event.EventType; +import org.apache.zookeeper.ZooDefs.Ids; + +import org.apache.giraph.bsp.BspInputFormat; +import org.apache.giraph.bsp.CentralizedService; +import org.apache.giraph.bsp.CentralizedServiceMaster; +import org.apache.giraph.graph.GraphMapper.MapFunctions; +import org.apache.giraph.zk.BspEvent; +import org.apache.giraph.zk.PredicateLock; + +/** + * Zookeeper-based implementation of {@link CentralizedService}. + */ +@SuppressWarnings("rawtypes") +public class BspServiceMaster< + I extends WritableComparable, + V extends Writable, + E extends Writable, M extends Writable> + extends BspService + implements CentralizedServiceMaster { + /** Class logger */ + private static final Logger LOG = Logger.getLogger(BspServiceMaster.class); + /** Synchronizes vertex ranges */ + private Object vertexRangeSynchronization = new Object(); + /** Superstep counter */ + private Counter superstepCounter = null; + /** Vertex counter */ + private Counter vertexCounter = null; + /** Finished vertex counter */ + private Counter finishedVertexCounter = null; + /** Edge counter */ + private Counter edgeCounter = null; + /** Sent messages counter */ + private Counter sentMessagesCounter = null; + /** Workers on this superstep */ + private Counter currentWorkersCounter = null; + /** Am I the master? */ + private boolean isMaster = false; + /** Max number of workers */ + private final int maxWorkers; + /** Min number of workers */ + private final int minWorkers; + /** Min % responded workers */ + private final float minPercentResponded; + /** Poll period in msecs */ + private final int msecsPollPeriod; + /** Max number of poll attempts */ + private final int maxPollAttempts; + /** Min number of long tails before printing */ + private final int partitionLongTailMinPrint; + /** Last finalized checkpoint */ + private long lastCheckpointedSuperstep = -1; + /** State of the superstep changed */ + private final BspEvent superstepStateChanged = + new PredicateLock(); + + public BspServiceMaster( + String serverPortList, + int sessionMsecTimeout, + Mapper.Context context, + GraphMapper graphMapper) { + super(serverPortList, sessionMsecTimeout, context, graphMapper); + registerBspEvent(superstepStateChanged); + + maxWorkers = + getConfiguration().getInt(GiraphJob.MAX_WORKERS, -1); + minWorkers = + getConfiguration().getInt(GiraphJob.MIN_WORKERS, -1); + minPercentResponded = + getConfiguration().getFloat(GiraphJob.MIN_PERCENT_RESPONDED, + 100.0f); + msecsPollPeriod = + getConfiguration().getInt(GiraphJob.POLL_MSECS, + GiraphJob.POLL_MSECS_DEFAULT); + maxPollAttempts = + getConfiguration().getInt(GiraphJob.POLL_ATTEMPTS, + GiraphJob.POLL_ATTEMPTS_DEFAULT); + partitionLongTailMinPrint = getConfiguration().getInt( + GiraphJob.PARTITION_LONG_TAIL_MIN_PRINT, + GiraphJob.PARTITION_LONG_TAIL_MIN_PRINT_DEFAULT); + } + + @Override + public void setJobState(State state, + long applicationAttempt, + long desiredSuperstep) { + JSONObject jobState = new JSONObject(); + try { + jobState.put(JSONOBJ_STATE_KEY, state.toString()); + jobState.put(JSONOBJ_APPLICATION_ATTEMPT_KEY, applicationAttempt); + jobState.put(JSONOBJ_SUPERSTEP_KEY, desiredSuperstep); + } catch (JSONException e) { + throw new RuntimeException("setJobState: Coudn't put " + + state.toString()); + } + if (LOG.isInfoEnabled()) { + LOG.info("setJobState: " + jobState.toString() + " on superstep " + + getSuperstep()); + } + try { + getZkExt().createExt(MASTER_JOB_STATE_PATH + "/jobState", + jobState.toString().getBytes(), + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT_SEQUENTIAL, + true); + } catch (KeeperException.NodeExistsException e) { + throw new IllegalStateException( + "setJobState: Imposible that " + + MASTER_JOB_STATE_PATH + " already exists!", e); + } catch (KeeperException e) { + throw new IllegalStateException( + "setJobState: Unknown KeeperException for " + + MASTER_JOB_STATE_PATH, e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "setJobState: Unknown InterruptedException for " + + MASTER_JOB_STATE_PATH, e); + } + + if (state == BspService.State.FAILED) { + failJob(); + } + } + + /** + * Master uses this to calculate the {@link VertexInputFormat} + * input splits and write it to ZooKeeper. + * + * @param numWorkers Number of available workers + * @throws InstantiationException + * @throws IllegalAccessException + * @throws IOException + * @throws InterruptedException + */ + private List generateInputSplits(int numWorkers) { + VertexInputFormat vertexInputFormat = + BspUtils.createVertexInputFormat(getConfiguration()); + List splits; + try { + splits = vertexInputFormat.getSplits(getContext(), numWorkers); + return splits; + } catch (IOException e) { + throw new IllegalStateException( + "generateInputSplits: Got IOException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "generateInputSplits: Got InterruptedException", e); + } + } + + /** + * When there is no salvaging this job, fail it. + * + * @throws IOException + */ + private void failJob() { + LOG.fatal("failJob: Killing job " + getJobId()); + try { + @SuppressWarnings("deprecation") + org.apache.hadoop.mapred.JobClient jobClient = + new org.apache.hadoop.mapred.JobClient( + (org.apache.hadoop.mapred.JobConf) + getConfiguration()); + @SuppressWarnings("deprecation") + org.apache.hadoop.mapred.JobID jobId = + org.apache.hadoop.mapred.JobID.forName(getJobId()); + RunningJob job = jobClient.getJob(jobId); + job.killJob(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Get the healthy and unhealthy workers for a superstep + * + * @param superstep superstep to check + * @param healthyWorkerList filled in with current data + * @param unhealthyWorkerList filled in with current data + */ + private void getWorkers(long superstep, + List healthyWorkerList, + List unhealthyWorkerList) { + String healthyWorkerPath = + getWorkerHealthyPath(getApplicationAttempt(), superstep); + String unhealthyWorkerPath = + getWorkerUnhealthyPath(getApplicationAttempt(), superstep); + + try { + getZkExt().createExt(healthyWorkerPath, + null, + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT, + true); + } catch (KeeperException.NodeExistsException e) { + if (LOG.isDebugEnabled()) { + LOG.debug("getWorkers: " + healthyWorkerPath + + " already exists, no need to create."); + } + } catch (KeeperException e) { + throw new IllegalStateException("getWorkers: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException("getWorkers: IllegalStateException" + , e); + } + + try { + getZkExt().createExt(unhealthyWorkerPath, + null, + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT, + true); + } catch (KeeperException.NodeExistsException e) { + if (LOG.isDebugEnabled()) { + LOG.debug("getWorkers: " + healthyWorkerPath + + " already exists, no need to create."); + } + } catch (KeeperException e) { + throw new IllegalStateException("getWorkers: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException("getWorkers: IllegalStateException" + , e); + } + + List currentHealthyWorkerList = null; + List currentUnhealthyWorkerList = null; + try { + currentHealthyWorkerList = + getZkExt().getChildrenExt(healthyWorkerPath, true, false, false); + } catch (KeeperException.NoNodeException e) { + LOG.info("getWorkers: No node for " + healthyWorkerPath); + } catch (KeeperException e) { + throw new IllegalStateException("getWorkers: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException("getWorkers: IllegalStateException" + , e); + } + + try { + currentUnhealthyWorkerList = + getZkExt().getChildrenExt(unhealthyWorkerPath, true, false, false); + } catch (KeeperException.NoNodeException e) { + LOG.info("getWorkers: No node for " + unhealthyWorkerPath); + } catch (KeeperException e) { + throw new IllegalStateException("getWorkers: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException("getWorkers: IllegalStateException" + , e); + } + + healthyWorkerList.clear(); + if (currentHealthyWorkerList != null) { + for (String healthyWorker : currentHealthyWorkerList) { + healthyWorkerList.add(healthyWorker); + } + } + + unhealthyWorkerList.clear(); + if (currentUnhealthyWorkerList != null) { + for (String unhealthyWorker : currentUnhealthyWorkerList) { + unhealthyWorkerList.add(unhealthyWorker); + } + } + } + + /** + * Check the workers to ensure that a minimum number of good workers exists + * out of the total that have reported. + * + * @return map of healthy worker list to JSONArray(hostname, port) + */ + private Map checkWorkers() { + boolean failJob = true; + int pollAttempt = 0; + List healthyWorkerList = new ArrayList(); + List unhealthyWorkerList = new ArrayList(); + int totalResponses = -1; + while (pollAttempt < maxPollAttempts) { + getWorkers( + getSuperstep(), healthyWorkerList, unhealthyWorkerList); + totalResponses = healthyWorkerList.size() + + unhealthyWorkerList.size(); + if ((totalResponses * 100.0f / maxWorkers) >= + minPercentResponded) { + failJob = false; + break; + } + getContext().setStatus(getGraphMapper().getMapFunctions() + " " + + "checkWorkers: Only found " + + totalResponses + + " responses of " + maxWorkers + + " needed to start superstep " + + getSuperstep()); + if (getWorkerHealthRegistrationChangedEvent().waitMsecs( + msecsPollPeriod)) { + if (LOG.isDebugEnabled()) { + LOG.debug("checkWorkers: Got event that health " + + "registration changed, not using poll attempt"); + } + getWorkerHealthRegistrationChangedEvent().reset(); + continue; + } + if (LOG.isInfoEnabled()) { + LOG.info("checkWorkers: Only found " + totalResponses + + " responses of " + maxWorkers + + " needed to start superstep " + + getSuperstep() + ". Sleeping for " + + msecsPollPeriod + " msecs and used " + pollAttempt + + " of " + maxPollAttempts + " attempts."); + // Find the missing workers if there are only a few + if ((maxWorkers - totalResponses) <= partitionLongTailMinPrint) { + Set partitionSet = new TreeSet(); + for (String hostnamePartitionId : healthyWorkerList) { + int lastIndex = hostnamePartitionId.lastIndexOf("_"); + Integer partition = Integer.parseInt( + hostnamePartitionId.substring(lastIndex + 1)); + partitionSet.add(partition); + } + for (String hostnamePartitionId : unhealthyWorkerList) { + int lastIndex = hostnamePartitionId.lastIndexOf("_"); + Integer partition = Integer.parseInt( + hostnamePartitionId.substring(lastIndex + 1)); + partitionSet.add(partition); + } + for (int i = 1; i <= maxWorkers; ++i) { + if (partitionSet.contains(new Integer(i))) { + continue; + } else if (i == getTaskPartition()) { + continue; + } else { + LOG.info("checkWorkers: No response from "+ + "partition " + i + " (could be master)"); + } + } + } + } + ++pollAttempt; + } + if (failJob) { + LOG.warn("checkWorkers: Did not receive enough processes in " + + "time (only " + totalResponses + " of " + + minWorkers + " required)"); + return null; + } + + if (healthyWorkerList.size() < minWorkers) { + LOG.warn("checkWorkers: Only " + healthyWorkerList.size() + + " available when " + minWorkers + " are required."); + return null; + } + + Map workerHostnamePortMap = + new HashMap(); + for (String healthyWorker: healthyWorkerList) { + String healthyWorkerPath = null; + try { + healthyWorkerPath = + getWorkerHealthyPath(getApplicationAttempt(), + getSuperstep()) + "/" + healthyWorker; + JSONArray hostnamePortArray = + new JSONArray( + new String(getZkExt().getData(healthyWorkerPath, + false, + null))); + workerHostnamePortMap.put(healthyWorker, hostnamePortArray); + } catch (JSONException e) { + throw new RuntimeException( + "checkWorkers: Problem fetching hostname and port for " + + healthyWorker + " in " + healthyWorkerPath); + } catch (KeeperException e) { + throw new IllegalStateException( + "checkWorkers: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "checkWorkers: IllegalStateException", e); + } + } + + return workerHostnamePortMap; + } + + public int createInputSplits() { + // Only the 'master' should be doing this. Wait until the number of + // processes that have reported health exceeds the minimum percentage. + // If the minimum percentage is not met, fail the job. Otherwise + // generate the input splits + try { + if (getZkExt().exists(INPUT_SPLIT_PATH, false) != null) { + LOG.info(INPUT_SPLIT_PATH + + " already exists, no need to create"); + return Integer.parseInt( + new String( + getZkExt().getData(INPUT_SPLIT_PATH, false, null))); + } + } catch (KeeperException.NoNodeException e) { + if (LOG.isInfoEnabled()) { + LOG.info("createInputSplits: Need to create the " + + "input splits at " + INPUT_SPLIT_PATH); + } + } catch (KeeperException e) { + throw new IllegalStateException( + "createInputSplits: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "createInputSplits: IllegalStateException", e); + } + + // When creating znodes, in case the master has already run, resume + // where it left off. + Map healthyWorkerHostnamePortMap = checkWorkers(); + if (healthyWorkerHostnamePortMap == null) { + setJobState(State.FAILED, -1, -1); + } + + List splitList = + generateInputSplits(healthyWorkerHostnamePortMap.size()); + if (healthyWorkerHostnamePortMap.size() > splitList.size()) { + LOG.warn("createInputSplits: Number of inputSplits=" + + splitList.size() + " < " + + healthyWorkerHostnamePortMap.size() + + "=number of healthy processes"); + } + else if (healthyWorkerHostnamePortMap.size() < splitList.size()) { + LOG.fatal("masterGenerateInputSplits: Number of inputSplits=" + + splitList.size() + " > " + + healthyWorkerHostnamePortMap.size() + + "=number of healthy processes"); + setJobState(State.FAILED, -1, -1); + } + String inputSplitPath = null; + for (int i = 0; i< splitList.size(); ++i) { + try { + ByteArrayOutputStream byteArrayOutputStream = + new ByteArrayOutputStream(); + DataOutput outputStream = + new DataOutputStream(byteArrayOutputStream); + InputSplit inputSplit = splitList.get(i); + Text.writeString(outputStream, + inputSplit.getClass().getName()); + ((Writable) inputSplit).write(outputStream); + inputSplitPath = INPUT_SPLIT_PATH + "/" + i; + getZkExt().createExt(inputSplitPath, + byteArrayOutputStream.toByteArray(), + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT, + true); + if (LOG.isDebugEnabled()) { + LOG.debug("createInputSplits: Created input split " + + "with index " + i + " serialized as " + + byteArrayOutputStream.toString()); + } + } catch (KeeperException.NodeExistsException e) { + if (LOG.isInfoEnabled()) { + LOG.info("createInputSplits: Node " + + inputSplitPath + " already exists."); + } + } catch (KeeperException e) { + throw new IllegalStateException( + "createInputSplits: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "createInputSplits: IllegalStateException", e); + } catch (IOException e) { + throw new IllegalStateException( + "createInputSplits: IOException", e); + } + } + + // Let workers know they can start trying to load the input splits + try { + getZkExt().create(INPUT_SPLITS_ALL_READY_PATH, + null, + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT); + } catch (KeeperException.NodeExistsException e) { + LOG.info("createInputSplits: Node " + + INPUT_SPLITS_ALL_READY_PATH + " already exists."); + } catch (KeeperException e) { + throw new IllegalStateException( + "createInputSplits: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "createInputSplits: IllegalStateException", e); + } + + return splitList.size(); + } + + /** + * Read the finalized checkpoint file and associated metadata files for the + * checkpoint. Assign one worker per checkpoint point (and associated + * vertex ranges). Remove any unused chosen workers + * (this is safe since it wasn't finalized). The workers can then + * find the vertex ranges within the files. It is an + * optimization to prevent all workers from searching all the files. + * Also read in the aggregator data from the finalized checkpoint + * file. + * + * @param superstep checkpoint set to examine. + * @throws IOException + * @throws InterruptedException + * @throws KeeperException + */ + private void mapFilesToWorkers(long superstep, + List chosenWorkerList) + throws IOException, KeeperException, InterruptedException { + FileSystem fs = getFs(); + List validMetadataPathList = new ArrayList(); + String finalizedCheckpointPath = + getCheckpointBasePath(superstep) + CHECKPOINT_FINALIZED_POSTFIX; + DataInputStream finalizedStream = + fs.open(new Path(finalizedCheckpointPath)); + int prefixFileCount = finalizedStream.readInt(); + for (int i = 0; i < prefixFileCount; ++i) { + String metadataFilePath = + finalizedStream.readUTF() + CHECKPOINT_METADATA_POSTFIX; + validMetadataPathList.add(new Path(metadataFilePath)); + } + + // Set the merged aggregator data if it exists. + int aggregatorDataSize = finalizedStream.readInt(); + if (aggregatorDataSize > 0) { + byte [] aggregatorZkData = new byte[aggregatorDataSize]; + int actualDataRead = + finalizedStream.read(aggregatorZkData, 0, aggregatorDataSize); + if (actualDataRead != aggregatorDataSize) { + throw new RuntimeException( + "mapFilesToWorkers: Only read " + actualDataRead + " of " + + aggregatorDataSize + " aggregator bytes from " + + finalizedCheckpointPath); + } + String mergedAggregatorPath = + getMergedAggregatorPath(getApplicationAttempt(), superstep - 1); + if (LOG.isInfoEnabled()) { + LOG.info("mapFilesToWorkers: Reloading merged aggregator " + + "data '" + Arrays.toString(aggregatorZkData) + + "' to previous checkpoint in path " + + mergedAggregatorPath); + } + if (getZkExt().exists(mergedAggregatorPath, false) == null) { + getZkExt().createExt(mergedAggregatorPath, + aggregatorZkData, + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT, + true); + } + else { + getZkExt().setData(mergedAggregatorPath, aggregatorZkData, -1); + } + } + finalizedStream.close(); + + Map> workerFileSetMap = + new HashMap>(); + // Reading the metadata files. For now, implement simple algorithm: + // 1. Every file is set an input split and the partitions are mapped + // accordingly + // 2. Every worker gets a hint about which files to look in to find + // the input splits + int chosenWorkerListIndex = 0; + int inputSplitIndex = 0; + I maxVertexIndex = BspUtils.createVertexIndex(getConfiguration()); + for (Path metadataPath : validMetadataPathList) { + String checkpointFilePrefix = metadataPath.toString(); + checkpointFilePrefix = + checkpointFilePrefix.substring( + 0, + checkpointFilePrefix.length() - + CHECKPOINT_METADATA_POSTFIX.length()); + DataInputStream metadataStream = fs.open(metadataPath); + long entries = metadataStream.readLong(); + JSONArray vertexRangeMetaArray = new JSONArray(); + JSONArray vertexRangeArray = new JSONArray(); + String chosenWorker = + chosenWorkerList.get(chosenWorkerListIndex); + for (long i = 0; i < entries; ++i) { + long dataPos = metadataStream.readLong(); + Long vertexCount = metadataStream.readLong(); + Long edgeCount = metadataStream.readLong(); + maxVertexIndex.readFields(metadataStream); + if (LOG.isDebugEnabled()) { + LOG.debug("mapFileToWorkers: File " + metadataPath + + " with position " + dataPos + ", vertex count " + + vertexCount + " assigned to " + chosenWorker); + } + ByteArrayOutputStream outputStream = + new ByteArrayOutputStream(); + DataOutput output = new DataOutputStream(outputStream); + maxVertexIndex.write(output); + + JSONObject vertexRangeObj = new JSONObject(); + + try { + vertexRangeObj.put(JSONOBJ_NUM_VERTICES_KEY, + vertexCount); + vertexRangeObj.put(JSONOBJ_NUM_EDGES_KEY, + edgeCount); + vertexRangeObj.put(JSONOBJ_HOSTNAME_ID_KEY, + chosenWorker); + vertexRangeObj.put(JSONOBJ_CHECKPOINT_FILE_PREFIX_KEY, + checkpointFilePrefix); + vertexRangeObj.put(JSONOBJ_MAX_VERTEX_INDEX_KEY, + Base64.encodeBase64String( + outputStream.toByteArray())); + vertexRangeMetaArray.put(vertexRangeObj); + vertexRangeArray.put(outputStream.toString("UTF-8")); + } catch (JSONException e) { + throw new IllegalStateException( + "mapFilesToWorkers: JSONException ", e); + } + + if (!workerFileSetMap.containsKey(chosenWorker)) { + workerFileSetMap.put(chosenWorker, new HashSet()); + } + Set fileSet = workerFileSetMap.get(chosenWorker); + fileSet.add(metadataPath.toString()); + } + metadataStream.close(); + + String inputSplitPathFinishedPath = + INPUT_SPLIT_PATH + "/" + inputSplitIndex + + INPUT_SPLIT_FINISHED_NODE; + if (LOG.isDebugEnabled()) { + LOG.debug("mapFilesToWorkers: Assigning (if not empty) " + + chosenWorker + " the following vertexRanges: " + + vertexRangeArray.toString()); + } + + // Assign the input splits if there is at least one vertex range + if (vertexRangeArray.length() == 0) { + continue; + } + try { + if (LOG.isInfoEnabled()) { + LOG.info("mapFilesToWorkers: vertexRangeMetaArray size=" + + vertexRangeMetaArray.toString().length()); + } + getZkExt().createExt(inputSplitPathFinishedPath, + vertexRangeMetaArray.toString().getBytes(), + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT, + true); + } catch (KeeperException e) { + throw new IllegalStateException( + "mapFilesToWorkers: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "mapFilesToWorkers: IllegalStateException", e); + } + ++inputSplitIndex; + ++chosenWorkerListIndex; + if (chosenWorkerListIndex == chosenWorkerList.size()) { + chosenWorkerListIndex = 0; + } + } + } + + public void setup() { + // Might have to manually load a checkpoint. + // In that case, the input splits are not set, they will be faked by + // the checkpoint files. Each checkpoint file will be an input split + // and the input split + superstepCounter = getContext().getCounter( + "Giraph Stats", "Superstep"); + vertexCounter = getContext().getCounter( + "Giraph Stats", "Aggregate vertices"); + finishedVertexCounter = getContext().getCounter( + "Giraph Stats", "Aggregate finished vertices"); + edgeCounter = getContext().getCounter( + "Giraph Stats", "Aggregate edges"); + sentMessagesCounter = getContext().getCounter( + "Giraph Stats", "Sent messages"); + currentWorkersCounter = getContext().getCounter( + "Giraph Stats", "Current workers"); + if (getRestartedSuperstep() == -1) { + return; + } + else if (getRestartedSuperstep() < -1) { + LOG.fatal("setup: Impossible to restart superstep " + + getRestartedSuperstep()); + setJobState(BspService.State.FAILED, -1, -1); + } else { + superstepCounter.increment(getRestartedSuperstep()); + } + + } + + public boolean becomeMaster() { + // Create my bid to become the master, then try to become the worker + // or return false. + String myBid = null; + try { + myBid = + getZkExt().createExt(MASTER_ELECTION_PATH + + "/" + getHostnamePartitionId(), + null, + Ids.OPEN_ACL_UNSAFE, + CreateMode.EPHEMERAL_SEQUENTIAL, + true); + } catch (KeeperException e) { + throw new IllegalStateException( + "becomeMaster: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "becomeMaster: IllegalStateException", e); + } + while (true) { + JSONObject jobState = getJobState(); + try { + if ((jobState != null) && + State.valueOf(jobState.getString(JSONOBJ_STATE_KEY)) == + State.FINISHED) { + if (LOG.isInfoEnabled()) { + LOG.info("becomeMaster: Job is finished, " + + "give up trying to be the master!"); + } + isMaster = false; + return isMaster; + } + } catch (JSONException e) { + throw new IllegalStateException( + "becomeMaster: Couldn't get state from " + jobState, e); + } + try { + List masterChildArr = + getZkExt().getChildrenExt( + MASTER_ELECTION_PATH, true, true, true); + if (LOG.isInfoEnabled()) { + LOG.info("becomeMaster: First child is '" + + masterChildArr.get(0) + "' and my bid is '" + + myBid + "'"); + } + if (masterChildArr.get(0).equals(myBid)) { + LOG.info("becomeMaster: I am now the master!"); + isMaster = true; + return isMaster; + } + LOG.info("becomeMaster: Waiting to become the master..."); + getMasterElectionChildrenChangedEvent().waitForever(); + getMasterElectionChildrenChangedEvent().reset(); + } catch (KeeperException e) { + throw new IllegalStateException( + "becomeMaster: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "becomeMaster: IllegalStateException", e); + } + } + } + + /** + * Collect and aggregate the worker statistics for a particular superstep. + * + * @param superstep Superstep to aggregate on + * @return JSONObject with all the aggregated fields + */ + private JSONObject aggregateWorkerStats(long superstep) { + long aggregateFinishedVertices = 0; + long aggregateVertices = 0; + long aggregateEdges = 0; + long aggregateSentMessages = 0; + // Superstep 0 is special since there is no computation, just get + // the stats from the input splits finished nodes. Otherwise, get the + // stats from the all the worker selected nodes + if (superstep == 0) { + List inputSplitList = null; + try { + inputSplitList = getZkExt().getChildrenExt( + INPUT_SPLIT_PATH, false, false, true); + } catch (KeeperException e) { + throw new IllegalStateException( + "aggregateWorkerStats: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "aggregateWorkerStats: IllegalStateException", e); + } + for (String inputSplitPath : inputSplitList) { + JSONArray statArray = null; + try { + String inputSplitFinishedPath = inputSplitPath + + INPUT_SPLIT_FINISHED_NODE; + byte [] zkData = + getZkExt().getData(inputSplitFinishedPath, false, null); + if (zkData == null || zkData.length == 0) { + continue; + } + statArray = new JSONArray(new String(zkData)); + if (LOG.isDebugEnabled()) { + LOG.debug("aggregateWorkerStats: input split path " + + inputSplitPath + " got " + statArray); + } + } catch (JSONException e) { + throw new IllegalStateException( + "aggregateWorkerStats: JSONException", e); + } catch (KeeperException e) { + throw new IllegalStateException( + "aggregateWorkerStats: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "aggregateWorkerStats: InterruptedException", e); + } + for (int i = 0; i < statArray.length(); ++i) { + try { + aggregateVertices += + statArray.getJSONObject(i).getLong( + JSONOBJ_NUM_VERTICES_KEY); + aggregateEdges += + statArray.getJSONObject(i).getLong( + JSONOBJ_NUM_EDGES_KEY); + } catch (JSONException e) { + throw new IllegalStateException( + "aggregateWorkerStats: JSONException", e); + } + } + } + } + else { + String workerFinishedPath = + getWorkerFinishedPath(getApplicationAttempt(), superstep); + List workerFinishedPathList = null; + try { + workerFinishedPathList = + getZkExt().getChildrenExt( + workerFinishedPath, false, false, true); + } catch (KeeperException e) { + throw new IllegalStateException( + "aggregateWorkerStats: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "aggregateWorkerStats: InterruptedException", e); + } + + for (String finishedPath : workerFinishedPathList) { + JSONObject aggregatorStatObj= null; + try { + byte [] zkData = + getZkExt().getData(finishedPath, false, null); + aggregatorStatObj = new JSONObject(new String(zkData)); + aggregateFinishedVertices += + aggregatorStatObj.getLong(JSONOBJ_FINISHED_VERTICES_KEY); + aggregateVertices += + aggregatorStatObj.getLong(JSONOBJ_NUM_VERTICES_KEY); + aggregateEdges += + aggregatorStatObj.getLong(JSONOBJ_NUM_EDGES_KEY); + aggregateSentMessages += + aggregatorStatObj.getLong(JSONOBJ_NUM_MESSAGES_KEY); + } catch (JSONException e) { + throw new IllegalStateException( + "aggregateWorkerStats: JSONException", e); + } catch (KeeperException e) { + throw new IllegalStateException( + "aggregateWorkerStats: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "aggregateWorkerStats: InterruptedException", e); + } + } + } + + JSONObject aggregateStats = new JSONObject(); + try { + aggregateStats.put(JSONOBJ_FINISHED_VERTICES_KEY, + aggregateFinishedVertices); + aggregateStats.put(JSONOBJ_NUM_VERTICES_KEY, + aggregateVertices); + aggregateStats.put(JSONOBJ_NUM_EDGES_KEY, + aggregateEdges); + aggregateStats.put(JSONOBJ_NUM_MESSAGES_KEY, + aggregateSentMessages); + } catch (JSONException e) { + throw new IllegalStateException( + "aggregateWorkerStats: Failed to put the aggregator " + + "stats together", e); + } + if (LOG.isInfoEnabled()) { + LOG.info("aggregateWorkerStats: Aggregation found " + + aggregateFinishedVertices + " of " + + aggregateVertices + + " vertices finished, " + aggregateEdges + + " edges, " + aggregateSentMessages + + " messages sent on superstep = " + getSuperstep()); + } + return aggregateStats; + } + + /** + * Get the aggregator values for a particular superstep, + * aggregate and save them. + * + * @param superstep superstep to check + */ + private void collectAndProcessAggregatorValues(long superstep) { + if (superstep <= 0) { + return; + } + Map> aggregatorMap = + new TreeMap>(); + String workerFinishedPath = + getWorkerFinishedPath(getApplicationAttempt(), superstep); + List hostnameIdPathList = null; + try { + hostnameIdPathList = + getZkExt().getChildrenExt( + workerFinishedPath, false, false, true); + } catch (KeeperException e) { + throw new IllegalStateException( + "collectAndProcessAggregatorValues: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "collectAndProcessAggregatorValues: InterruptedException", e); + } + + for (String hostnameIdPath : hostnameIdPathList) { + JSONObject aggregatorsStatObj = null; + JSONArray aggregatorArray = null; + try { + byte [] zkData = + getZkExt().getData(hostnameIdPath, false, null); + aggregatorsStatObj = new JSONObject(new String(zkData)); + } catch (KeeperException e) { + throw new IllegalStateException( + "collectAndProcessAggregatorValues: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "collectAndProcessAggregatorValues: InterruptedException", + e); + } catch (JSONException e) { + throw new IllegalStateException( + "collectAndProcessAggregatorValues: JSONException", e); + } + try { + aggregatorArray = aggregatorsStatObj.getJSONArray( + JSONOBJ_AGGREGATOR_VALUE_ARRAY_KEY); + } catch (JSONException e) { + if (LOG.isDebugEnabled()) { + LOG.debug("collectAndProcessAggregatorValues: " + + "No aggregators" + " for " + hostnameIdPath); + } + continue; + } + for (int i = 0; i < aggregatorArray.length(); ++i) { + try { + if (LOG.isInfoEnabled()) { + LOG.info("collectAndProcessAggregatorValues: " + + "Getting aggregators from " + + aggregatorArray.getJSONObject(i)); + } + String aggregatorName = + aggregatorArray.getJSONObject(i).getString( + AGGREGATOR_NAME_KEY); + String aggregatorClassName = + aggregatorArray.getJSONObject(i).getString( + AGGREGATOR_CLASS_NAME_KEY); + @SuppressWarnings("unchecked") + Aggregator aggregator = + (Aggregator) aggregatorMap.get(aggregatorName); + boolean firstTime = false; + if (aggregator == null) { + @SuppressWarnings("unchecked") + Aggregator aggregatorWritable = + (Aggregator) getAggregator(aggregatorName); + aggregator = aggregatorWritable; + if (aggregator == null) { + @SuppressWarnings("unchecked") + Class> aggregatorClass = + (Class>) + Class.forName(aggregatorClassName); + aggregator = registerAggregator( + aggregatorName, + aggregatorClass); + } + aggregatorMap.put(aggregatorName, aggregator); + firstTime = true; + } + Writable aggregatorValue = + aggregator.createAggregatedValue(); + InputStream input = + new ByteArrayInputStream( + Base64.decodeBase64( + aggregatorArray.getJSONObject(i). + getString(AGGREGATOR_VALUE_KEY))); + aggregatorValue.readFields(new DataInputStream(input)); + if (LOG.isDebugEnabled()) { + LOG.debug("collectAndProcessAggregatorValues: " + + "aggregator value size=" + input.available() + + " for aggregator=" + aggregatorName + + " value=" + aggregatorValue); + } + if (firstTime) { + aggregator.setAggregatedValue(aggregatorValue); + } else { + aggregator.aggregate(aggregatorValue); + } + } catch (IOException e) { + throw new IllegalStateException( + "collectAndProcessAggregatorValues: " + + "IOException when reading aggregator data " + + aggregatorArray, e); + } catch (JSONException e) { + throw new IllegalStateException( + "collectAndProcessAggregatorValues: " + + "JSONException when reading aggregator data " + + aggregatorArray, e); + } catch (ClassNotFoundException e) { + throw new IllegalStateException( + "collectAndProcessAggregatorValues: " + + "ClassNotFoundException when reading aggregator data " + + aggregatorArray, e); + } catch (InstantiationException e) { + throw new IllegalStateException( + "collectAndProcessAggregatorValues: " + + "InstantiationException when reading aggregator data " + + aggregatorArray, e); + } catch (IllegalAccessException e) { + throw new IllegalStateException( + "collectAndProcessAggregatorValues: " + + "IOException when reading aggregator data " + + aggregatorArray, e); + } + } + } + if (aggregatorMap.size() > 0) { + String mergedAggregatorPath = + getMergedAggregatorPath(getApplicationAttempt(), superstep); + byte [] zkData = null; + JSONArray aggregatorArray = new JSONArray(); + for (Map.Entry> entry : + aggregatorMap.entrySet()) { + try { + ByteArrayOutputStream outputStream = + new ByteArrayOutputStream(); + DataOutput output = new DataOutputStream(outputStream); + entry.getValue().getAggregatedValue().write(output); + + JSONObject aggregatorObj = new JSONObject(); + aggregatorObj.put(AGGREGATOR_NAME_KEY, + entry.getKey()); + aggregatorObj.put( + AGGREGATOR_VALUE_KEY, + Base64.encodeBase64String(outputStream.toByteArray())); + aggregatorArray.put(aggregatorObj); + if (LOG.isInfoEnabled()) { + LOG.info("collectAndProcessAggregatorValues: " + + "Trying to add aggregatorObj " + + aggregatorObj + "(" + + entry.getValue().getAggregatedValue() + + ") to merged aggregator path " + + mergedAggregatorPath); + } + } catch (IOException e) { + throw new IllegalStateException( + "collectAndProcessAggregatorValues: " + + "IllegalStateException", e); + } catch (JSONException e) { + throw new IllegalStateException( + "collectAndProcessAggregatorValues: JSONException", e); + } + } + try { + zkData = aggregatorArray.toString().getBytes(); + getZkExt().createExt(mergedAggregatorPath, + zkData, + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT, + true); + } catch (KeeperException.NodeExistsException e) { + LOG.warn("collectAndProcessAggregatorValues: " + + mergedAggregatorPath+ + " already exists!"); + } catch (KeeperException e) { + throw new IllegalStateException( + "collectAndProcessAggregatorValues: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "collectAndProcessAggregatorValues: IllegalStateException", + e); + } + if (LOG.isInfoEnabled()) { + LOG.info("collectAndProcessAggregatorValues: Finished " + + "loading " + + mergedAggregatorPath+ " with aggregator values " + + aggregatorArray); + } + } + } + + /** + * Finalize the checkpoint file prefixes by taking the chosen workers and + * writing them to a finalized file. Also write out the master + * aggregated aggregator array from the previous superstep. + * + * @param superstep superstep to finalize + * @param chosenWorkerList list of chosen workers that will be finalized + * @throws IOException + * @throws InterruptedException + * @throws KeeperException + */ + private void finalizeCheckpoint( + long superstep, + List chosenWorkerList) + throws IOException, KeeperException, InterruptedException { + Path finalizedCheckpointPath = + new Path(getCheckpointBasePath(superstep) + + CHECKPOINT_FINALIZED_POSTFIX); + try { + getFs().delete(finalizedCheckpointPath, false); + } catch (IOException e) { + LOG.warn("finalizedValidCheckpointPrefixes: Removed old file " + + finalizedCheckpointPath); + } + + // Format: + // + // ... + // + FSDataOutputStream finalizedOutputStream = + getFs().create(finalizedCheckpointPath); + finalizedOutputStream.writeInt(chosenWorkerList.size()); + for (String chosenWorker : chosenWorkerList) { + String chosenWorkerPrefix = + getCheckpointBasePath(superstep) + "." + chosenWorker; + finalizedOutputStream.writeUTF(chosenWorkerPrefix); + } + String mergedAggregatorPath = + getMergedAggregatorPath(getApplicationAttempt(), superstep - 1); + if (getZkExt().exists(mergedAggregatorPath, false) != null) { + byte [] aggregatorZkData = + getZkExt().getData(mergedAggregatorPath, false, null); + finalizedOutputStream.writeInt(aggregatorZkData.length); + finalizedOutputStream.write(aggregatorZkData); + } + else { + finalizedOutputStream.writeInt(0); + } + finalizedOutputStream.close(); + lastCheckpointedSuperstep = superstep; + } + + /** + * Convert the processed input split data into vertex range assignments + * that can be used on the next superstep. + * + * @param chosenWorkerHostnamePortMap map of chosen workers to + * a hostname and port array + */ + private void inputSplitsToVertexRanges( + Map chosenWorkerHostnamePortMap) { + List inputSplitPathList = null; + List> vertexRangeList = + new ArrayList>(); + try { + inputSplitPathList = getZkExt().getChildrenExt(INPUT_SPLIT_PATH, + false, + false, + true); + int numRanges = 0; + for (String inputSplitPath : inputSplitPathList) { + String inputSplitFinishedPath = inputSplitPath + + INPUT_SPLIT_FINISHED_NODE; + byte [] zkData = + getZkExt().getData(inputSplitFinishedPath, false, null); + if (zkData == null || zkData.length == 0) { + if (LOG.isInfoEnabled()) { + LOG.info("inputSplitsToVertexRanges: No vertex ranges " + + "in " + inputSplitFinishedPath); + } + continue; + } + JSONArray statArray = new JSONArray(new String(zkData)); + JSONObject vertexRangeObj = null; + for (int i = 0; i < statArray.length(); ++i) { + vertexRangeObj = statArray.getJSONObject(i); + String hostnamePartitionId = + vertexRangeObj.getString(JSONOBJ_HOSTNAME_ID_KEY); + if (!chosenWorkerHostnamePortMap.containsKey( + hostnamePartitionId)) { + LOG.fatal("inputSplitsToVertexRanges: Worker " + + hostnamePartitionId + " died, failing."); + setJobState(State.FAILED, -1, -1); + } + JSONArray hostnamePortArray = + chosenWorkerHostnamePortMap.get(hostnamePartitionId); + vertexRangeObj.put(JSONOBJ_HOSTNAME_KEY, + hostnamePortArray.getString(0)); + vertexRangeObj.put(JSONOBJ_PORT_KEY, + hostnamePortArray.getString(1)); + Class indexClass = + BspUtils.getVertexIndexClass(getConfiguration()); + VertexRange vertexRange = + new VertexRange(indexClass, vertexRangeObj); + vertexRangeList.add(vertexRange); + ++numRanges; + } + } + + JSONArray vertexRangeAssignmentArray = + new JSONArray(); + for (VertexRange vertexRange : vertexRangeList) { + vertexRangeAssignmentArray.put(vertexRange.toJSONObject()); + } + String vertexRangeAssignmentsPath = + getVertexRangeAssignmentsPath(getApplicationAttempt(), + getSuperstep()); + if (LOG.isInfoEnabled()) { + LOG.info("inputSplitsToVertexRanges: Assigning " + numRanges + + " vertex ranges of total length " + + vertexRangeAssignmentArray.toString().length() + + " to path " + vertexRangeAssignmentsPath); + } + getZkExt().createExt(vertexRangeAssignmentsPath, + vertexRangeAssignmentArray.toString().getBytes(), + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT, + true); + } catch (KeeperException e) { + throw new IllegalStateException( + "inputSplitsToVertexRanges: KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "inputSplitsToVertexRanges: IllegalStateException", e); + } catch (JSONException e) { + throw new IllegalStateException( + "inputSplitsToVertexRanges: JSONException", e); + } catch (IOException e) { + throw new IllegalStateException( + "inputSplitsToVertexRanges: IOException", e); + } catch (InstantiationException e) { + throw new IllegalStateException( + "inputSplitsToVertexRanges: InstantiationException", e); + } catch (IllegalAccessException e) { + throw new IllegalStateException( + "inputSplitsToVertexRanges: IllegalAccessException", e); + } + } + + /** + * Balance the vertex ranges before the next superstep computation begins. + * Wait until the vertex ranges data has been moved to the correct + * worker prior to continuing. + * + * @param vertexRangeBalancer balancer to use + * @param chosenWorkerHostnamePortMap workers available + * @throws JSONException + * @throws IOException + * @throws UnsupportedEncodingException + */ + private void balanceVertexRanges( + VertexRangeBalancer vertexRangeBalancer, + Map chosenWorkerHostnamePortMap) { + vertexRangeBalancer.setSuperstep(getSuperstep()); + vertexRangeBalancer.setWorkerHostnamePortMap( + chosenWorkerHostnamePortMap); + NavigableMap> vertexRangeMap = + getVertexRangeMap(getSuperstep() - 1); + vertexRangeBalancer.setPrevVertexRangeMap(vertexRangeMap); + NavigableMap> nextVertexRangeMap = + vertexRangeBalancer.rebalance(); + vertexRangeBalancer.setNextVertexRangeMap(nextVertexRangeMap); + vertexRangeBalancer.setPreviousHostnamePort(); + nextVertexRangeMap = vertexRangeBalancer.getNextVertexRangeMap(); + if (nextVertexRangeMap.size() != vertexRangeMap.size()) { + throw new IllegalArgumentException( + "balanceVertexRanges: Next vertex range count " + + nextVertexRangeMap.size() + " != " + vertexRangeMap.size()); + } + JSONArray vertexRangeAssignmentArray = new JSONArray(); + VertexRange maxVertexRange = null; // TODO: delete after Bug 4340282 fixed. + for (VertexRange vertexRange : + nextVertexRangeMap.values()) { + try { + vertexRangeAssignmentArray.put( + vertexRange.toJSONObject()); + if (maxVertexRange == null || // TODO: delete after Bug 4340282 fixed. + vertexRange.toJSONObject().toString().length() < + maxVertexRange.toJSONObject().toString().length()) { + maxVertexRange = vertexRange; + } + } catch (IOException e) { + throw new IllegalStateException( + "balanceVertexRanges: IOException", e); + } catch (JSONException e) { + throw new IllegalStateException( + "balanceVertexRanges: JSONException", e); + } + } + if (vertexRangeAssignmentArray.length() == 0) { + throw new RuntimeException( + "balanceVertexRanges: Impossible there are no vertex ranges "); + } + + byte[] vertexAssignmentBytes = null; + try { + vertexAssignmentBytes = + vertexRangeAssignmentArray.toString().getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException( + "balanceVertexranges: Cannot get bytes from " + + vertexRangeAssignmentArray.toString(), e); + } + + // TODO: delete after Bug 4340282 fixed. + if (LOG.isInfoEnabled()) { + try { + LOG.info("balanceVertexRanges: numVertexRanges=" + + nextVertexRangeMap.values().size() + + " lengthVertexRanges=" + vertexAssignmentBytes.length + + " maxVertexRangeLength=" + + maxVertexRange.toJSONObject().toString().length()); + } catch (IOException e) { + throw new RuntimeException( + "balanceVertexRanges: IOException fetching " + + maxVertexRange.toString(), e); + } catch (JSONException e) { + throw new RuntimeException( + "balanceVertexRanges: JSONException fetching " + + maxVertexRange.toString(), e); + } + } + + String vertexRangeAssignmentsPath = + getVertexRangeAssignmentsPath(getApplicationAttempt(), + getSuperstep()); + try { + getZkExt().createExt(vertexRangeAssignmentsPath, + vertexAssignmentBytes, + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT, + true); + } catch (KeeperException.NodeExistsException e) { + if (LOG.isInfoEnabled()) { + LOG.info("balanceVertexRanges: Node " + + vertexRangeAssignmentsPath + " already exists", e); + } + } catch (KeeperException e) { + LOG.fatal("balanceVertexRanges: Got KeeperException", e); + throw new IllegalStateException( + "balanceVertexRanges: Got KeeperException", e); + } catch (InterruptedException e) { + LOG.fatal("balanceVertexRanges: Got InterruptedException", e); + throw new IllegalStateException( + "balanceVertexRanges: Got InterruptedException", e); + } + + long changes = vertexRangeBalancer.getVertexRangeChanges(); + if (LOG.isInfoEnabled()) { + LOG.info("balanceVertexRanges: Waiting on " + changes + + " vertex range changes"); + } + if (changes == 0) { + return; + } + + String vertexRangeExchangePath = + getVertexRangeExchangePath(getApplicationAttempt(), getSuperstep()); + List workerExchangeList = null; + try { + getZkExt().createExt(vertexRangeExchangePath, + null, + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT, + true); + } catch (KeeperException.NodeExistsException e) { + if (LOG.isInfoEnabled()) { + LOG.info("balanceVertexRanges: " + vertexRangeExchangePath + + "exists"); + } + } catch (KeeperException e) { + throw new IllegalStateException( + "balanceVertexRanges: Got KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "balanceVertexRanges: Got InterruptedException", e); + } + while (true) { + try { + workerExchangeList = + getZkExt().getChildrenExt( + vertexRangeExchangePath, true, false, false); + } catch (KeeperException e) { + throw new IllegalStateException( + "balanceVertexRanges: Got KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "balanceVertexRanges: Got InterruptedException", e); + } + if (workerExchangeList.size() == changes) { + break; + } + getVertexRangeExchangeChildrenChangedEvent().waitForever(); + getVertexRangeExchangeChildrenChangedEvent().reset(); + } + String vertexRangeExchangeFinishedPath = + getVertexRangeExchangeFinishedPath(getApplicationAttempt(), + getSuperstep()); + try { + getZkExt().createExt(vertexRangeExchangeFinishedPath, + null, + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT, + true); + } catch (KeeperException e) { + throw new IllegalStateException( + "balanceVertexRanges: Got KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "balanceVertexRanges: Got InterruptedException", e); + } + } + + /** + * Check whether the workers chosen for this superstep are still alive + * + * @param chosenWorkerHealthPath Path to the healthy workers in ZooKeeper + * @param chosenWorkerSet Set of the healthy workers + * @return true if they are all alive, false otherwise. + * @throws InterruptedException + * @throws KeeperException + */ + private boolean superstepChosenWorkerAlive( + String chosenWorkerHealthPath, + Set chosenWorkerSet) + throws KeeperException, InterruptedException { + List chosenWorkerHealthyList = + getZkExt().getChildrenExt(chosenWorkerHealthPath, + true, + false, + false); + Set chosenWorkerHealthySet = + new HashSet(chosenWorkerHealthyList); + boolean allChosenWorkersHealthy = true; + for (String chosenWorker : chosenWorkerSet) { + if (!chosenWorkerHealthySet.contains(chosenWorker)) { + allChosenWorkersHealthy = false; + LOG.warn("superstepChosenWorkerAlive: Missing chosen worker " + + chosenWorker + " on superstep " + getSuperstep()); + } + } + return allChosenWorkersHealthy; + } + + @Override + public void restartFromCheckpoint(long checkpoint) { + // Process: + // 1. Remove all old input split data + // 2. Increase the application attempt and set to the correct checkpoint + // 3. Send command to all workers to restart their tasks + try { + getZkExt().deleteExt(INPUT_SPLIT_PATH, -1, true); + } catch (InterruptedException e) { + throw new RuntimeException( + "retartFromCheckpoint: InterruptedException", e); + } catch (KeeperException e) { + throw new RuntimeException( + "retartFromCheckpoint: KeeperException", e); + } + setApplicationAttempt(getApplicationAttempt() + 1); + setCachedSuperstep(checkpoint); + setRestartedSuperstep(checkpoint); + setJobState(BspService.State.START_SUPERSTEP, + getApplicationAttempt(), + checkpoint); + } + + /** + * Only get the finalized checkpoint files + */ + public static class FinalizedCheckpointPathFilter implements PathFilter { + @Override + public boolean accept(Path path) { + if (path.getName().endsWith( + BspService.CHECKPOINT_FINALIZED_POSTFIX)) { + return true; + } else { + return false; + } + } + } + + @Override + public long getLastGoodCheckpoint() throws IOException { + // Find the last good checkpoint if none have been written to the + // knowledge of this master + if (lastCheckpointedSuperstep == -1) { + FileStatus[] fileStatusArray = + getFs().listStatus(new Path(CHECKPOINT_BASE_PATH), + new FinalizedCheckpointPathFilter()); + if (fileStatusArray == null) { + return -1; + } + Arrays.sort(fileStatusArray); + lastCheckpointedSuperstep = getCheckpoint( + fileStatusArray[fileStatusArray.length - 1].getPath()); + LOG.info("getLastGoodCheckpoint: Found last good checkpoint " + + lastCheckpointedSuperstep + " from " + + fileStatusArray[fileStatusArray.length - 1]. + getPath().toString()); + } + return lastCheckpointedSuperstep; + } + + @Override + public SuperstepState coordinateSuperstep() throws + KeeperException, InterruptedException { + // 1. Get chosen workers and set up watches on them. + // 2. Assign partitions to the workers + // or possibly reload from a superstep + // 3. Wait for all workers to complete + // 4. Collect and process aggregators + // 5. Create superstep finished node + // 6. If the checkpoint frequency is met, finalize the checkpoint + Map chosenWorkerHostnamePortMap = checkWorkers(); + if (chosenWorkerHostnamePortMap == null) { + LOG.fatal("coordinateSuperstep: Not enough healthy workers for " + + "superstep " + getSuperstep()); + setJobState(State.FAILED, -1, -1); + } else { + for (Entry entry : + chosenWorkerHostnamePortMap.entrySet()) { + String workerHealthyPath = + getWorkerHealthyPath(getApplicationAttempt(), + getSuperstep()) + "/" + entry.getKey(); + if (getZkExt().exists(workerHealthyPath, true) == null) { + LOG.warn("coordinateSuperstep: Chosen worker " + + workerHealthyPath + + " is no longer valid, failing superstep"); + } + } + } + + currentWorkersCounter.increment(chosenWorkerHostnamePortMap.size() - + currentWorkersCounter.getValue()); + if (getRestartedSuperstep() == getSuperstep()) { + try { + if (LOG.isInfoEnabled()) { + LOG.info("coordinateSuperstep: Reloading from superstep " + + getSuperstep()); + } + mapFilesToWorkers( + getRestartedSuperstep(), + new ArrayList( + chosenWorkerHostnamePortMap.keySet())); + inputSplitsToVertexRanges(chosenWorkerHostnamePortMap); + } catch (IOException e) { + throw new IllegalStateException( + "coordinateSuperstep: Failed to reload", e); + } + } else { + if (getSuperstep() > 0) { + VertexRangeBalancer vertexRangeBalancer = + BspUtils.createVertexRangeBalancer( + getConfiguration()); + synchronized (vertexRangeSynchronization) { + balanceVertexRanges(vertexRangeBalancer, + chosenWorkerHostnamePortMap); + } + } + } + + String finishedWorkerPath = + getWorkerFinishedPath(getApplicationAttempt(), getSuperstep()); + try { + getZkExt().createExt(finishedWorkerPath, + null, + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT, + true); + } catch (KeeperException.NodeExistsException e) { + if (LOG.isDebugEnabled()) { + LOG.debug("coordinateSuperstep: finishedWorkers " + + finishedWorkerPath + + " already exists, no need to create"); + } + } + String workerHealthyPath = + getWorkerHealthyPath(getApplicationAttempt(), getSuperstep()); + List finishedWorkerList = null; + long nextInfoMillis = System.currentTimeMillis(); + while (true) { + try { + finishedWorkerList = + getZkExt().getChildrenExt(finishedWorkerPath, + true, + false, + false); + } catch (KeeperException e) { + throw new IllegalStateException( + "coordinateSuperstep: Couldn't get children of " + + finishedWorkerPath, e); + } + if (LOG.isDebugEnabled()) { + LOG.debug("coordinateSuperstep: Got finished worker list = " + + finishedWorkerList + ", size = " + + finishedWorkerList.size() + + ", chosen worker list = " + + chosenWorkerHostnamePortMap.keySet() + ", size = " + + chosenWorkerHostnamePortMap.size() + + " from " + finishedWorkerPath); + } + + if (LOG.isInfoEnabled() && + (System.currentTimeMillis() > nextInfoMillis)) { + nextInfoMillis = System.currentTimeMillis() + 30000; + LOG.info("coordinateSuperstep: " + finishedWorkerList.size() + + " out of " + + chosenWorkerHostnamePortMap.size() + + " chosen workers finished on superstep " + + getSuperstep()); + } + getContext().setStatus(getGraphMapper().getMapFunctions() + " " + + finishedWorkerList.size() + + " finished out of " + + chosenWorkerHostnamePortMap.size() + + " on superstep " + getSuperstep()); + if (finishedWorkerList.containsAll( + chosenWorkerHostnamePortMap.keySet())) { + break; + } + getSuperstepStateChangedEvent().waitForever(); + getSuperstepStateChangedEvent().reset(); + + // Did a worker die? + if ((getSuperstep() > 0) && + !superstepChosenWorkerAlive( + workerHealthyPath, + chosenWorkerHostnamePortMap.keySet())) { + return SuperstepState.WORKER_FAILURE; + } + } + collectAndProcessAggregatorValues(getSuperstep()); + JSONObject globalInfoObject = aggregateWorkerStats(getSuperstep()); + + // Convert the input split stats to vertex ranges in superstep 0 + if (getSuperstep() == 0) { + inputSplitsToVertexRanges(chosenWorkerHostnamePortMap); + } + + // Let everyone know the aggregated application state through the + // superstep + String superstepFinishedNode = + getSuperstepFinishedPath(getApplicationAttempt(), getSuperstep()); + try { + getZkExt().createExt(superstepFinishedNode, + globalInfoObject.toString().getBytes(), + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT, + true); + vertexCounter.increment( + globalInfoObject.getLong(JSONOBJ_NUM_VERTICES_KEY) - + vertexCounter.getValue()); + finishedVertexCounter.increment( + globalInfoObject.getLong(JSONOBJ_FINISHED_VERTICES_KEY) - + finishedVertexCounter.getValue()); + edgeCounter.increment( + globalInfoObject.getLong(JSONOBJ_NUM_EDGES_KEY) - + edgeCounter.getValue()); + sentMessagesCounter.increment( + globalInfoObject.getLong(JSONOBJ_NUM_MESSAGES_KEY) - + sentMessagesCounter.getValue()); + } catch (JSONException e) { + throw new IllegalStateException("coordinateSuperstep: " + + "JSONException", e); + } + + + // Finalize the valid checkpoint file prefixes and possibly + // the aggregators. + if (checkpointFrequencyMet(getSuperstep())) { + try { + finalizeCheckpoint( + getSuperstep(), + new ArrayList(chosenWorkerHostnamePortMap.keySet())); + } catch (IOException e) { + throw new IllegalStateException( + "coordinateSuperstep: IOException on finalizing checkpoint", + e); + } + } + + // Clean up the old supersteps (always keep this one) + long removeableSuperstep = getSuperstep() - 1; + if ((getConfiguration().getBoolean( + GiraphJob.KEEP_ZOOKEEPER_DATA, + GiraphJob.KEEP_ZOOKEEPER_DATA_DEFAULT) == false) && + (removeableSuperstep >= 0)) { + String oldSuperstepPath = + getSuperstepPath(getApplicationAttempt()) + "/" + + (removeableSuperstep); + try { + if (LOG.isInfoEnabled()) { + LOG.info("coordinateSuperstep: Cleaning up old Superstep " + + oldSuperstepPath); + } + getZkExt().deleteExt(oldSuperstepPath, + -1, + true); + } catch (KeeperException.NoNodeException e) { + LOG.warn("coordinateBarrier: Already cleaned up " + + oldSuperstepPath); + } catch (KeeperException e) { + throw new IllegalStateException( + "coordinateSuperstep: KeeperException on " + + "finalizing checkpoint", e); + } + } + incrCachedSuperstep(); + superstepCounter.increment(1); + try { + if ((globalInfoObject.getLong(JSONOBJ_FINISHED_VERTICES_KEY) == + globalInfoObject.getLong(JSONOBJ_NUM_VERTICES_KEY)) && + (globalInfoObject.getLong(JSONOBJ_NUM_MESSAGES_KEY)) == 0) { + return SuperstepState.ALL_SUPERSTEPS_DONE; + } else { + return SuperstepState.THIS_SUPERSTEP_DONE; + } + } catch (JSONException e) { + throw new IllegalStateException( + "coordinateSuperstep: JSONException on checking if " + + "the application is done", e); + } + } + + /** + * Need to clean up ZooKeeper nicely. Make sure all the masters and workers + * have reported ending their ZooKeeper connections. + */ + private void cleanUpZooKeeper() { + try { + getZkExt().createExt(CLEANED_UP_PATH, + null, + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT, + true); + } catch (KeeperException.NodeExistsException e) { + if (LOG.isInfoEnabled()) { + LOG.info("cleanUpZooKeeper: Node " + CLEANED_UP_PATH + + " already exists, no need to create."); + } + } catch (KeeperException e) { + throw new IllegalStateException( + "cleanupZooKeeper: Got KeeperException", e); + } catch (InterruptedException e) { + throw new IllegalStateException( + "cleanupZooKeeper: Got IllegalStateException", e); + } + // Need to wait for the number of workers and masters to complete + int maxTasks = BspInputFormat.getMaxTasks(getConfiguration()); + if ((getGraphMapper().getMapFunctions() == MapFunctions.ALL) || + (getGraphMapper().getMapFunctions() == + MapFunctions.ALL_EXCEPT_ZOOKEEPER)) { + maxTasks *= 2; + } + List cleanedUpChildrenList = null; + while (true) { + try { + cleanedUpChildrenList = + getZkExt().getChildrenExt( + CLEANED_UP_PATH, true, false, true); + if (LOG.isInfoEnabled()) { + LOG.info("cleanUpZooKeeper: Got " + + cleanedUpChildrenList.size() + " of " + + maxTasks + " desired children from " + + CLEANED_UP_PATH); + } + if (cleanedUpChildrenList.size() == maxTasks) { + break; + } + if (LOG.isInfoEnabled()) { + LOG.info("cleanedUpZooKeeper: Waiting for the " + + "children of " + CLEANED_UP_PATH + + " to change since only got " + + cleanedUpChildrenList.size() + " nodes."); + } + } + catch (Exception e) { + // We are in the cleanup phase -- just log the error + LOG.error("cleanUpZooKeeper: Got exception, but will continue", + e); + return; + } + + getCleanedUpChildrenChangedEvent().waitForever(); + getCleanedUpChildrenChangedEvent().reset(); + } + + // At this point, all processes have acknowledged the cleanup, + // and the master can do any final cleanup + try { + if (getConfiguration().getBoolean( + GiraphJob.KEEP_ZOOKEEPER_DATA, + GiraphJob.KEEP_ZOOKEEPER_DATA_DEFAULT) == false) { + if (LOG.isInfoEnabled()) { + LOG.info("cleanupZooKeeper: Removing the following path " + + "and all children - " + BASE_PATH); + } + getZkExt().deleteExt(BASE_PATH, -1, true); + } + } catch (Exception e) { + LOG.error("cleanupZooKeeper: Failed to do cleanup of " + + BASE_PATH, e); + } + } + + @Override + public void cleanup() throws IOException { + // All master processes should denote they are done by adding special + // znode. Once the number of znodes equals the number of partitions + // for workers and masters, the master will clean up the ZooKeeper + // znodes associated with this job. + String cleanedUpPath = CLEANED_UP_PATH + "/" + + getTaskPartition() + MASTER_SUFFIX; + try { + String finalFinishedPath = + getZkExt().createExt(cleanedUpPath, + null, + Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT, + true); + if (LOG.isInfoEnabled()) { + LOG.info("cleanup: Notifying master its okay to cleanup with " + + finalFinishedPath); + } + } catch (KeeperException.NodeExistsException e) { + if (LOG.isInfoEnabled()) { + LOG.info("cleanup: Couldn't create finished node '" + + cleanedUpPath); + } + } catch (KeeperException e) { + LOG.error("cleanup: Got KeeperException, continuing", e); + } catch (InterruptedException e) { + LOG.error("cleanup: Got InterruptedException, continuing", e); + } + + if (isMaster) { + cleanUpZooKeeper(); + // If desired, cleanup the checkpoint directory + if (getConfiguration().getBoolean( + GiraphJob.CLEANUP_CHECKPOINTS_AFTER_SUCCESS, + GiraphJob.CLEANUP_CHECKPOINTS_AFTER_SUCCESS_DEFAULT)) { + boolean success = + getFs().delete(new Path(CHECKPOINT_BASE_PATH), true); + if (LOG.isInfoEnabled()) { + LOG.info("cleanup: Removed HDFS checkpoint directory (" + + CHECKPOINT_BASE_PATH + ") with return = " + + success + " since this job succeeded "); + } + } + } + + try { + getZkExt().close(); + } catch (InterruptedException e) { + // cleanup phase -- just log the error + LOG.error("cleanup: Zookeeper failed to close", e); + } + } + + /** + * Event that the master watches that denotes if a worker has done something + * that changes the state of a superstep (either a worker completed or died) + * + * @return Event that denotes a superstep state change + */ + final public BspEvent getSuperstepStateChangedEvent() { + return superstepStateChanged; + } + + /** + * Should this worker failure cause the current superstep to fail? + * + * @param failedWorkerPath Full path to the failed worker + */ + final private void checkHealthyWorkerFailure(String failedWorkerPath) { + synchronized(vertexRangeSynchronization) { + if (getSuperstepFromPath(failedWorkerPath) < getSuperstep()) { + return; + } + + // Check all the workers used in this superstep + NavigableMap> vertexRangeMap = + getVertexRangeMap(getSuperstep()); + String hostnameId = + getHealthyHostnameIdFromPath(failedWorkerPath); + for (VertexRange vertexRange : + vertexRangeMap.values()) { + if (vertexRange.getHostnameId().equals(hostnameId) || + ((vertexRange.getPreviousHostnameId() != null) && + vertexRange.getPreviousHostnameId().equals( + hostnameId))) { + LOG.warn("checkHealthyWorkerFailure: " + + "at least one healthy worker went down " + + "for superstep " + getSuperstep() + " - " + + hostnameId + ", will try to restart from " + + "checkpointed superstep " + + lastCheckpointedSuperstep); + superstepStateChanged.signal(); + } + } + } + } + + @Override + public boolean processEvent(WatchedEvent event) { + boolean foundEvent = false; + if (event.getPath().contains(WORKER_HEALTHY_DIR) && + (event.getType() == EventType.NodeDeleted)) { + if (LOG.isDebugEnabled()) { + LOG.debug("processEvent: Healthy worker died (node deleted) " + + "in " + event.getPath()); + } + checkHealthyWorkerFailure(event.getPath()); + superstepStateChanged.signal(); + foundEvent = true; + } else if (event.getPath().contains(WORKER_FINISHED_DIR) && + event.getType() == EventType.NodeChildrenChanged) { + if (LOG.isDebugEnabled()) { + LOG.debug("processEvent: Worker finished (node change) " + + "event - superstepStateChanged signaled"); + } + superstepStateChanged.signal(); + foundEvent = true; + } + + return foundEvent; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.giraph.graph.BspServiceMaster.coordinateSuperstep` indirectly reads without synchronization from `this.org.apache.giraph.graph.BspService.cachedSuperstep`. Potentially races with write in method `BspServiceMaster.setup()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +CentralizedServiceMaster$SuperstepState BspServiceMaster.coordinateSuperstep() + +### Procedure Id: +org.apache.giraph.graph.BspServiceMaster.coordinateSuperstep():org.apache.giraph.bsp.CentralizedServ.fc0b416b6fdf9a13ac14b9acfcc65086 + +### File: +src/main/java/org/apache/giraph/graph/BspServiceMaster.java + +### Key: +BspServiceMaster.java|coordinateSuperstep|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +c33877331bebe8a0e7704d46e6ed5d92 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-4167/instruction.md b/inferredbugs-4167/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7f3ddda61d1cb89040cf0afde03574d4852c39d5 --- /dev/null +++ b/inferredbugs-4167/instruction.md @@ -0,0 +1,813 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** underscore-java +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * The MIT License (MIT) + * + * Copyright 2015 Valentyn Kolesnikov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.github.underscore; + +import org.junit.Test; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.NoSuchElementException; + +import static java.util.Arrays.asList; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +/** + * Underscore library unit test. + * + * @author Valentyn Kolesnikov + */ +public class ArraysTest { + +/* +_.first([5, 4, 3, 2, 1]); +=> 5 +_.first([5, 4, 3, 2, 1], 2); +=> [5, 4] +*/ + @Test + public void first() { + final Integer result = $.first(asList(5, 4, 3, 2, 1)); + assertEquals("5", result.toString()); + final Object resultChain = $.chain(asList(5, 4, 3, 2, 1)).first().item(); + assertEquals("5", resultChain.toString()); + final Object resultChainTwo = $.chain(asList(5, 4, 3, 2, 1)).first(2).value(); + assertEquals("[5, 4]", resultChainTwo.toString()); + final List resultList = $.first(asList(5, 4, 3, 2, 1), 2); + assertEquals("[5, 4]", resultList.toString()); + final int resultInt = $.first(new Integer[] {5, 4, 3, 2, 1}); + assertEquals(5, resultInt); + final int resultPred = $.first(asList(5, 4, 3, 2, 1), new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(4, resultPred); + final int resultPredObj = new $(asList(5, 4, 3, 2, 1)).first(new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(4, resultPredObj); + } + + @Test + public void firstOrNull() { + final Integer result = $.firstOrNull(asList(5, 4, 3, 2, 1)); + assertEquals("5", result.toString()); + final Integer resultObj = new $(asList(5, 4, 3, 2, 1)).firstOrNull(); + assertEquals("5", resultObj.toString()); + assertNull($.firstOrNull(Collections.emptyList())); + assertNull(new $(Collections.emptyList()).firstOrNull()); + final int resultPred = $.firstOrNull(asList(5, 4, 3, 2, 1), new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(4, resultPred); + assertNull($.firstOrNull(Collections.emptyList(), new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + })); + final int resultPredObj = new $(asList(5, 4, 3, 2, 1)).firstOrNull(new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(4, resultPredObj); + assertNull(new $(Collections.emptyList()).firstOrNull(new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + })); + } + + @Test(expected = NoSuchElementException.class) + public void firstEmpty() { + $.first(asList()); + } + +/* +_.head([5, 4, 3, 2, 1]); +=> 5 +_.head([5, 4, 3, 2, 1], 2); +=> [5, 4] +*/ + @Test + public void head() { + final Integer result = $.head(asList(5, 4, 3, 2, 1)); + assertEquals("5", result.toString()); + final Integer resultObj = new $(asList(5, 4, 3, 2, 1)).head(); + assertEquals("5", resultObj.toString()); + final List resultList = $.head(asList(5, 4, 3, 2, 1), 2); + assertEquals("[5, 4]", resultList.toString()); + final List resultListObj = new $(asList(5, 4, 3, 2, 1)).head(2); + assertEquals("[5, 4]", resultListObj.toString()); + final int resultInt = $.head(new Integer[] {5, 4, 3, 2, 1}); + assertEquals(5, resultInt); + } + +/* +_.rest([5, 4, 3, 2, 1]); +=> [4, 3, 2, 1] +_.rest([5, 4, 3, 2, 1], 2); +=> [3, 2, 1] +*/ + @Test + @SuppressWarnings("unchecked") + public void rest() { + final List result = $.rest(asList(5, 4, 3, 2, 1)); + assertEquals("[4, 3, 2, 1]", result.toString()); + final List resultChain = $.chain(asList(5, 4, 3, 2, 1)).rest().value(); + assertEquals("[4, 3, 2, 1]", resultChain.toString()); + final List result2 = $.rest(asList(5, 4, 3, 2, 1), 2); + assertEquals("[3, 2, 1]", result2.toString()); + final List result2Chain = $.chain(asList(5, 4, 3, 2, 1)).rest(2).value(); + assertEquals("[3, 2, 1]", result2Chain.toString()); + final Object[] resultArray = $.rest(new Integer[] {5, 4, 3, 2, 1}); + assertEquals("[4, 3, 2, 1]", asList(resultArray).toString()); + final Object[] resultArray2 = $.rest(new Integer[] {5, 4, 3, 2, 1}, 2); + assertEquals("[3, 2, 1]", asList(resultArray2).toString()); + } + +/* +_.chunk(['a', 'b', 'c', 'd'], 2); +// → [['a', 'b'], ['c', 'd']] + +_.chunk(['a', 'b', 'c', 'd'], 3); +// → [['a', 'b', 'c'], ['d']] +*/ + @Test + @SuppressWarnings("unchecked") + public void chunk() { + assertEquals("[[a, b], [c, d]]", $.chunk(asList("a", "b", "c", "d"), 2).toString()); + assertEquals("[[a, b], [c, d]]", new $(asList("a", "b", "c", "d")).chunk(2).toString()); + assertEquals("[[a, b], [c, d]]", $.chain(asList("a", "b", "c", "d")).chunk(2).value().toString()); + assertEquals("[[a, b, c], [d]]", $.chunk(asList("a", "b", "c", "d"), 3).toString()); + } + +/* +_.tail([5, 4, 3, 2, 1]); +=> [4, 3, 2, 1] +_.tail([5, 4, 3, 2, 1], 2); +=> [3, 2, 1] +*/ + @Test + public void tail() { + final List result = $.tail(asList(5, 4, 3, 2, 1)); + assertEquals("[4, 3, 2, 1]", result.toString()); + final List result2 = $.tail(asList(5, 4, 3, 2, 1), 2); + assertEquals("[3, 2, 1]", result2.toString()); + final Object[] resultArray = $.tail(new Integer[] {5, 4, 3, 2, 1}); + assertEquals("[4, 3, 2, 1]", asList(resultArray).toString()); + final List resultArrayObj = new $(asList(5, 4, 3, 2, 1)).tail(); + assertEquals("[4, 3, 2, 1]", resultArrayObj.toString()); + final Object[] resultArray2 = $.tail(new Integer[] {5, 4, 3, 2, 1}, 2); + assertEquals("[3, 2, 1]", asList(resultArray2).toString()); + final List resultArray2Obj = new $(asList(5, 4, 3, 2, 1)).tail(2); + assertEquals("[3, 2, 1]", resultArray2Obj.toString()); + } + +/* +_.drop([5, 4, 3, 2, 1]); +=> [4, 3, 2, 1] +_.drop([5, 4, 3, 2, 1], 2); +=> [3, 2, 1] +*/ + @Test + public void drop() { + final List result = $.drop(asList(5, 4, 3, 2, 1)); + assertEquals("[4, 3, 2, 1]", result.toString()); + final List result2 = $.drop(asList(5, 4, 3, 2, 1), 2); + assertEquals("[3, 2, 1]", result2.toString()); + final Object[] resultArray = $.drop(new Integer[] {5, 4, 3, 2, 1}); + assertEquals("[4, 3, 2, 1]", asList(resultArray).toString()); + final Object[] resultArray2 = $.drop(new Integer[] {5, 4, 3, 2, 1}, 2); + assertEquals("[3, 2, 1]", asList(resultArray2).toString()); + } + + +/* +_.initial([5, 4, 3, 2, 1]); +=> [5, 4, 3, 2] +_.initial([5, 4, 3, 2, 1], 2); +=> [5, 4, 3] +*/ + @Test + @SuppressWarnings("unchecked") + public void initial() { + final List result = $.initial(asList(5, 4, 3, 2, 1)); + assertEquals("[5, 4, 3, 2]", result.toString()); + final List resultChain = $.chain(asList(5, 4, 3, 2, 1)).initial().value(); + assertEquals("[5, 4, 3, 2]", resultChain.toString()); + final List resultList = $.initial(asList(5, 4, 3, 2, 1), 2); + assertEquals("[5, 4, 3]", resultList.toString()); + final List resultListChain = $.chain(asList(5, 4, 3, 2, 1)).initial(2).value(); + assertEquals("[5, 4, 3]", resultListChain.toString()); + final Integer[] resultArray = $.initial(new Integer[] {5, 4, 3, 2, 1}); + assertEquals("[5, 4, 3, 2]", asList(resultArray).toString()); + final Integer[] resultListArray = $.initial(new Integer[] {5, 4, 3, 2, 1}, 2); + assertEquals("[5, 4, 3]", asList(resultListArray).toString()); + List res = new $(asList(1, 2, 3, 4, 5)).initial(); + assertEquals("initial one item did not work", asList(1, 2, 3, 4), res); + res = new $(asList(1, 2, 3, 4, 5)).initial(3); + assertEquals("initial multi item did not wok", asList(1, 2), res); + } + +/* +_.last([5, 4, 3, 2, 1]); +=> 1 +*/ + @Test + @SuppressWarnings("unchecked") + public void last() { + final Integer result = $.last(asList(5, 4, 3, 2, 1)); + assertEquals("1", result.toString()); + final List resultTwo = $.last(asList(5, 4, 3, 2, 1), 2); + assertEquals("[2, 1]", resultTwo.toString()); + final Object resultChain = $.chain(asList(5, 4, 3, 2, 1)).last().item(); + assertEquals("1", resultChain.toString()); + final Object resultChainTwo = $.chain(asList(5, 4, 3, 2, 1)).last(2).value(); + assertEquals("[2, 1]", resultChainTwo.toString()); + final Integer resultArray = $.last(new Integer[] {5, 4, 3, 2, 1}); + assertEquals("1", resultArray.toString()); + Integer res = new $(asList(1, 2, 3, 4, 5)).last(); + assertEquals("last one item did not work", 5, res.intValue()); + List resList = new $(asList(1, 2, 3, 4, 5)).last(3); + assertEquals("last multi item did not wok", asList(3, 4, 5), resList); + final int resultPred = $.last(asList(5, 4, 3, 2, 1), new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(2, resultPred); + final int resultPredObj = new $(asList(5, 4, 3, 2, 1)).last(new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(2, resultPredObj); + } + + @Test + public void lastOrNull() { + final Integer result = $.lastOrNull(asList(5, 4, 3, 2, 1)); + assertEquals("1", result.toString()); + final Integer resultObj = new $(asList(5, 4, 3, 2, 1)).lastOrNull(); + assertEquals("1", resultObj.toString()); + assertNull($.lastOrNull(Collections.emptyList())); + assertNull(new $(Collections.emptyList()).lastOrNull()); + final int resultPred = $.lastOrNull(asList(5, 4, 3, 2, 1), new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(2, resultPred); + assertNull($.lastOrNull(Collections.emptyList(), new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + })); + final int resultPredObj = new $(asList(5, 4, 3, 2, 1)).lastOrNull(new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(2, resultPredObj); + assertNull(new $(Collections.emptyList()).lastOrNull(new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + })); + } +/* +_.compact([0, 1, false, 2, '', 3]); +=> [1, 2, 3] +*/ + @Test + @SuppressWarnings("unchecked") + public void compact() { + final List result = $.compact(asList(0, 1, false, 2, "", 3)); + assertEquals("[1, 2, 3]", result.toString()); + final List result2 = $.compact(asList(0, 1, false, 2, "", 3), 1); + assertEquals("[0, false, 2, , 3]", result2.toString()); + final List result3 = $.compact(asList(0, 1, null, 2, "", 3)); + assertEquals("[1, 2, 3]", result3.toString()); + final List resultChain = $.chain(asList(0, 1, false, 2, "", 3)).compact().value(); + assertEquals("[1, 2, 3]", resultChain.toString()); + final List result2Chain = $.chain(asList(0, 1, false, 2, "", 3)).compact(1).value(); + assertEquals("[0, false, 2, , 3]", result2Chain.toString()); + final List result4 = new $(asList(0, 1, false, 2, "", 3)).compact(); + assertEquals("[1, 2, 3]", result4.toString()); + final List result5 = new $(asList(0, 1, false, 2, "", 3)).compact(1); + assertEquals("[0, false, 2, , 3]", result5.toString()); + final List result6 = new $(asList(0, 1, null, 2, "", 3)).compact(1); + assertEquals("[0, null, 2, , 3]", result6.toString()); + final List result7 = new $(asList(0, 1, null, 2, "", 3)).compact((Integer) null); + assertEquals("[0, 1, 2, , 3]", result7.toString()); + final Object[] resultArray = $.compact(new Object[] {0, 1, false, 2, "", 3}); + assertEquals("[1, 2, 3]", asList(resultArray).toString()); + final Object[] resultArray2 = $.compact(new Object[] {0, 1, false, 2, "", 3}, 1); + assertEquals("[0, false, 2, , 3]", asList(resultArray2).toString()); + } + +/* +_.flatten([1, [2], [3, [[4]]]]); +=> [1, 2, 3, 4]; +*/ + @Test + @SuppressWarnings("unchecked") + public void flatten() { + final List result = $.flatten(asList(1, asList(2, asList(3, asList(asList(4)))))); + assertEquals("[1, 2, 3, 4]", result.toString()); + final List result2 = $.flatten(asList(1, asList(2, asList(3, asList(asList(4))))), true); + assertEquals("[1, 2, [3, [[4]]]]", result2.toString()); + final List result3 = $.flatten(asList(1, asList(2, asList(3, asList(asList(4))))), false); + assertEquals("[1, 2, 3, 4]", result3.toString()); + final List resultObj = new $(asList(1, asList(2, asList(3, asList(asList(4)))))).flatten(); + assertEquals("[1, 2, 3, 4]", resultObj.toString()); + final List resultObj2 = new $(asList(1, asList(2, asList(3, asList(asList(4)))))).flatten(true); + assertEquals("[1, 2, [3, [[4]]]]", resultObj2.toString()); + final List resultObj3 = new $(asList(1, asList(2, asList(3, asList(asList(4)))))).flatten(false); + assertEquals("[1, 2, 3, 4]", resultObj3.toString()); + } + +/* +_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); +=> [2, 3, 4] +*/ + @Test + public void without() { + final List result = $.without(asList(1, 2, 1, 0, 3, 1, 4), 0, 1); + assertEquals("[2, 3, 4]", result.toString()); + final List result2 = $.without(asList(1, 2, 1, 0, 3, 1, 4), 1); + assertEquals("[2, 0, 3, 4]", result2.toString()); + final List result3 = $.without(asList(null, 2, null, 0, 3, null, 4), (Integer) null); + assertEquals("[2, 0, 3, 4]", result3.toString()); + final Object[] resultArray = $.without(new Integer[] {1, 2, 1, 0, 3, 1, 4}, 0, 1); + assertEquals("[2, 3, 4]", asList(resultArray).toString()); + final Object[] resultArray2 = $.without(new Integer[] {1, 2, 1, 0, 3, 1, 4}, 1); + assertEquals("[2, 0, 3, 4]", asList(resultArray2).toString()); + } + +/* +_.sortedIndex([10, 20, 30, 40, 50], 35); +=> 3 +*/ + @Test + public void sortedIndex() { + final Integer result = $.sortedIndex(asList(10, 20, 30, 40, 50), 35); + assertEquals(3, result.intValue()); + final Integer result2 = $.sortedIndex(new Integer[] {10, 20, 30, 40, 50}, 35); + assertEquals(3, result2.intValue()); + final Integer result3 = $.sortedIndex(asList(10, 20, 30, 40, 50), 60); + assertEquals(-1, result3.intValue()); + } + + @Test + public void sortedIndex2() { + class Person implements Comparable { + public final String name; + public final Integer age; + public Person(final String name, final Integer age) { + this.name = name; + this.age = age; + } + public int compareTo(Person person) { + return person.age - this.age; + } + public String toString() { + return name + ", " + age; + } + } + final int result = + $.sortedIndex(asList(new Person("moe", 40), new Person("moe", 50), + new Person("curly", 60)), new Person("moe", 50), "age"); + assertEquals(1, result); + final int result2 = + $.sortedIndex(asList(new Person("moe", 40), new Person("moe", 50), + new Person("curly", 60)), new Person("moe", 70), "age"); + assertEquals(-1, result2); + final int resultArray = + $.sortedIndex(new Person[] {new Person("moe", 40), new Person("moe", 50), + new Person("curly", 60)}, new Person("moe", 50), "age"); + assertEquals(1, resultArray); + } + + @Test(expected = IllegalArgumentException.class) + public void sortedIndex2Error() { + class Person implements Comparable { + public int compareTo(Person person) { + return 0; + } + } + $.sortedIndex(asList(new Person()), new Person(), "age"); + } + +/* +_.uniq([1, 2, 1, 3, 1, 4]); +=> [1, 2, 3, 4] +*/ + @Test + @SuppressWarnings("unchecked") + public void uniq() { + final List result = $.uniq(asList(1, 2, 1, 3, 1, 4)); + assertEquals("[1, 2, 3, 4]", result.toString()); + final Object[] resultArray = $.uniq(new Integer[] {1, 2, 1, 3, 1, 4}); + assertEquals("[1, 2, 3, 4]", asList(resultArray).toString()); + class Person { + public final String name; + public final Integer age; + public Person(final String name, final Integer age) { + this.name = name; + this.age = age; + } + public String toString() { + return name + ", " + age; + } + } + final Collection resultObject = + $.uniq(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)), + new Function1() { + public String apply(Person person) { + return person.name; + } + }); + assertEquals("[moe, 50, curly, 60]", resultObject.toString()); + final List resultObjectChain = + $.chain(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60))).uniq( + new Function1() { + public String apply(Person person) { + return person.name; + } + }).value(); + assertEquals("[moe, 50, curly, 60]", resultObjectChain.toString()); + assertEquals("[1, 2, 3, 4, 5]", $.chain(asList(1, 2, 3, 3, 4, 5)).uniq().value().toString()); + final Object[] resultObjectArray = + $.uniq(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)).toArray(new Person[]{}), + new Function1() { + public String apply(Person person) { + return person.name; + } + }); + assertEquals("[moe, 50, curly, 60]", asList(resultObjectArray).toString()); + } + +/* +_.distinct([1, 2, 1, 3, 1, 4]); +=> [1, 2, 3, 4] +*/ + @Test + @SuppressWarnings("unchecked") + public void distinct() { + final List result = $.distinct(asList(1, 2, 1, 3, 1, 4)); + assertEquals("[1, 2, 3, 4]", result.toString()); + final Object[] resultArray = $.distinct(new Integer[] {1, 2, 1, 3, 1, 4}); + assertEquals("[1, 2, 3, 4]", asList(resultArray).toString()); + class Person { + public final String name; + public final Integer age; + public Person(final String name, final Integer age) { + this.name = name; + this.age = age; + } + public String toString() { + return name + ", " + age; + } + } + final Collection resultObject = + $.distinctBy(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)), + new Function1() { + public String apply(Person person) { + return person.name; + } + }); + assertEquals("[moe, 50, curly, 60]", resultObject.toString()); + final List resultObjectChain = + $.chain(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60))).distinctBy( + new Function1() { + public String apply(Person person) { + return person.name; + } + }).value(); + assertEquals("[moe, 50, curly, 60]", resultObjectChain.toString()); + assertEquals("[1, 2, 3, 4, 5]", $.chain(asList(1, 2, 3, 3, 4, 5)).distinct().value().toString()); + final Object[] resultObjectArray = + $.distinctBy(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)).toArray(new Person[]{}), + new Function1() { + public String apply(Person person) { + return person.name; + } + }); + assertEquals("[moe, 50, curly, 60]", asList(resultObjectArray).toString()); + } + +/* +_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); +=> [1, 2] +*/ + @Test + @SuppressWarnings("unchecked") + public void intersection() { + final List result = $.intersection(asList(1, 2, 3), asList(101, 2, 1, 10), asList(2, 1)); + assertEquals("[1, 2]", result.toString()); + final List resultObj = new $(asList(1, 2, 3)).intersectionWith(asList(101, 2, 1, 10), asList(2, 1)); + assertEquals("[1, 2]", resultObj.toString()); + final List resultChain = $.chain(asList(1, 2, 3)).intersection(asList(101, 2, 1, 10), + asList(2, 1)).value(); + assertEquals("[1, 2]", resultChain.toString()); + final Object[] resultArray = $.intersection(new Integer[] {1, 2, 3}, new Integer[] {101, 2, 1, 10}); + assertEquals("[1, 2]", asList(resultArray).toString()); + } + +/* +_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); +=> [1, 2, 3, 101, 10] +*/ + @Test + @SuppressWarnings("unchecked") + public void union() { + final List result = $.union(asList(1, 2, 3), asList(101, 2, 1, 10), asList(2, 1)); + assertEquals("[1, 2, 3, 101, 10]", result.toString()); + final List resultObj = new $(asList(1, 2, 3)).unionWith(asList(101, 2, 1, 10), asList(2, 1)); + assertEquals("[1, 2, 3, 101, 10]", resultObj.toString()); + final List resultChain = $.chain(asList(1, 2, 3)).union(asList(101, 2, 1, 10), asList(2, 1)).value(); + assertEquals("[1, 2, 3, 101, 10]", resultChain.toString()); + final Object[] resultArray = $.union(new Integer[] {1, 2, 3}, new Integer[] {101, 2, 1, 10}); + assertEquals("[1, 2, 3, 101, 10]", asList(resultArray).toString()); + } + +/* +_.difference([1, 2, 3, 4, 5], [5, 2, 10]); +=> [1, 3, 4] +*/ + @Test + @SuppressWarnings("unchecked") + public void difference() { + final List result = $.difference(asList(1, 2, 3, 4, 5), asList(5, 2, 10)); + assertEquals("[1, 3, 4]", result.toString()); + final List resultObj = new $(asList(1, 2, 3, 4, 5)).differenceWith(asList(5, 2, 10)); + assertEquals("[1, 3, 4]", resultObj.toString()); + final List resultChain = $.chain(asList(1, 2, 3, 4, 5)).difference(asList(5, 2, 10)).value(); + assertEquals("[1, 3, 4]", resultChain.toString()); + final List resultList = $.difference(asList(1, 2, 3, 4, 5), asList(5, 2, 10), asList(8, 4)); + assertEquals("[1, 3]", resultList.toString()); + final Object[] resultArray = $.difference(new Integer[] {1, 2, 3, 4, 5}, new Integer[] {5, 2, 10}); + assertEquals("[1, 3, 4]", asList(resultArray).toString()); + final Object[] resultArray2 = $.difference(new Integer[] {1, 2, 3, 4, 5}, + new Integer[] {5, 2, 10}, new Integer[] {8, 4}); + assertEquals("[1, 3]", asList(resultArray2).toString()); + } + +/* +_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); +=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]] +*/ + @Test + @SuppressWarnings("unchecked") + public void zip() { + final List> result = $.zip( + asList("moe", "larry", "curly"), asList("30", "40", "50"), asList("true", "false", "false")); + assertEquals("[[moe, 30, true], [larry, 40, false], [curly, 50, false]]", result.toString()); + } + +/* +_.unzip(["moe", 30, true], ["larry", 40, false], ["curly", 50, false]); +=> [['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]] +*/ + @Test + @SuppressWarnings("unchecked") + public void unzip() { + final List> result = $.unzip( + asList("moe", "30", "true"), asList("larry", "40", "false"), asList("curly", "50", "false")); + assertEquals("[[moe, larry, curly], [30, 40, 50], [true, false, false]]", result.toString()); + } + +/* +_.object(['moe', 'larry', 'curly'], [30, 40, 50]); +=> {moe: 30, larry: 40, curly: 50} +*/ + @Test + public void object() { + final List> result = $.object( + asList("moe", "larry", "curly"), asList("30", "40", "50")); + assertEquals("[(moe, 30), (larry, 40), (curly, 50)]", result.toString()); + } + +/* +_.indexOf([1, 2, 3], 2); +=> 1 +*/ + @Test + public void indexOf() { + final Integer result = $.indexOf(asList(1, 2, 3), 2); + assertEquals(1, result.intValue()); + final Integer resultArray = $.indexOf(new Integer[] {1, 2, 3}, 2); + assertEquals(1, resultArray.intValue()); + } + +/* +_.lastIndexOf([1, 2, 3, 1, 2, 3], 2); +=> 4 +*/ + @Test + public void lastIndexOf() { + final Integer result = $.lastIndexOf(asList(1, 2, 3, 1, 2, 3), 2); + assertEquals(4, result.intValue()); + final Integer resultArray = $.lastIndexOf(new Integer[] {1, 2, 3, 1, 2, 3}, 2); + assertEquals(4, resultArray.intValue()); + } + +/* +_.findIndex([1, 2, 3], function(item) {return item % 2 === 0; }); +=> 1 +*/ + @Test + public void findIndex() { + final Integer result = $.findIndex(asList(1, 2, 3), new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(1, result.intValue()); + final Integer resultNotFound = $.findIndex(asList(1, 2, 3), new Predicate() { + public Boolean apply(Integer item) { + return item > 3; + } + }); + assertEquals(-1, resultNotFound.intValue()); + final Integer resultArray = $.findIndex(new Integer[] {1, 2, 3}, new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(1, resultArray.intValue()); + } + +/* +_.findLastIndex([1, 2, 3, 4, 5], function(item) {return item % 2 === 0; }); +=> 3 +*/ + @Test + public void findLastIndex() { + final Integer result = $.findLastIndex(asList(1, 2, 3, 4, 5), new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(3, result.intValue()); + final Integer resultNotFound = $.findLastIndex(asList(1, 2, 3, 4, 5), new Predicate() { + public Boolean apply(Integer item) { + return item > 5; + } + }); + assertEquals(-1, resultNotFound.intValue()); + final Integer resultArray = $.findLastIndex(new Integer[] {1, 2, 3, 4, 5}, new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(3, resultArray.intValue()); + } + +/* +_.range(10); +=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +_.range(1, 11); +=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +_.range(0, 30, 5); +=> [0, 5, 10, 15, 20, 25] +_.range(0, -10, -1); +=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] +_.range(0); +=> [] +*/ + @Test + public void range() { + final int[] result = $.range(10); + assertArrayEquals(new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, result); + final List resultChain = $.chain("").range(10).value(); + assertEquals("[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]", resultChain.toString()); + final int[] result2 = $.range(1, 11); + assertArrayEquals(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, result2); + final List result2Chain = $.chain("").range(1, 11).value(); + assertEquals("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", result2Chain.toString()); + final int[] result3 = $.range(0, 30, 5); + assertArrayEquals(new int[] {0, 5, 10, 15, 20, 25}, result3); + final List result3Chain = $.chain("").range(0, 30, 5).value(); + assertEquals("[0, 5, 10, 15, 20, 25]", result3Chain.toString()); + final int[] result4 = $.range(0, -10, -1); + assertArrayEquals(new int[] {0, -1, -2, -3, -4, -5, -6, -7, -8, -9}, result4); + final int[] result5 = $.range(0); + assertArrayEquals(new int[] {}, result5); + } + +/* +_.lastIndex([1, 2, 3, 4, 5]); +=> 4 +*/ + @Test + public void lastIndex() { + assertEquals(4, $.lastIndex(asList(1, 2, 3, 4, 5))); + assertEquals(4, $.lastIndex(new Integer[]{1, 2, 3, 4, 5})); + assertEquals(4, $.lastIndex(new int[]{1, 2, 3, 4, 5})); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `__new(com.github.underscore.$).firstOrNull(__new(com.github.underscore.ArraysTest$5))` could be null and is dereferenced at line 96. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ArraysTest.firstOrNull() + +### Procedure Id: +com.github.underscore.ArraysTest.firstOrNull():void.e7a2227a1a87f837224fd8bc00338484 + +### File: +src/test/java/com/github/underscore/ArraysTest.java + +### Key: +ArraysTest.java|firstOrNull|NULL_DEREFERENCE + +### Node Key: +3392ddd9e7af3710d0647e5067e4a3e1 + +### Hash: +3b11431f4f8a5375e073929cabcd8cdf + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-4168/instruction.md b/inferredbugs-4168/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..388c0b6fd79e1fc76191f60b0e12cb71c36eb45c --- /dev/null +++ b/inferredbugs-4168/instruction.md @@ -0,0 +1,1834 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** underscore-java +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * The MIT License (MIT) + * + * Copyright (c) 2014 Valentyn Kolesnikov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.github.underscore; + +import java.util.*; +import org.junit.Test; +import static java.util.Arrays.asList; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertNull; + +/** + * Underscore library unit test. + * + * @author Valentyn Kolesnikov + */ +public class _Test { + +/* +_.each([1, 2, 3], alert); +=> alerts each number in turn... +*/ + @Test + public void each() { + final List result = new ArrayList(); + _.each(asList(1, 2, 3), new Block() { + public void apply(Integer item) { + result.add(item); + } + }); + assertEquals("[1, 2, 3]", result.toString()); + } + +/* +_.forEach([1, 2, 3], alert); +=> alerts each number in turn... +*/ + @Test + public void forEach() { + final List result = new ArrayList(); + _.forEach(asList(1, 2, 3), new Block() { + public void apply(Integer item) { + result.add(item); + } + }); + assertEquals("[1, 2, 3]", result.toString()); + } + +/* +_([1, 2, 3]).forEach(alert); +=> alerts each number in turn... +*/ + @Test + public void forEachObj() { + final List result = new ArrayList(); + new _(asList(1, 2, 3)).forEach(new Block() { + public void apply(Integer item) { + result.add(item); + } + }); + assertEquals("[1, 2, 3]", result.toString()); + } + +/* +_.each({one: 1, two: 2, three: 3}, alert); +=> alerts each number value in turn... +*/ + @Test + public void eachMap() { + final List result = new ArrayList(); + _.>each(new LinkedHashMap() {{ put("one", 1); put("two", 2); put("three", 3); }}.entrySet(), + new Block>() { + public void apply(Map.Entry item) { + result.add(item.getKey()); + } + }); + assertEquals("[one, two, three]", result.toString()); + } + +/* +_.map([1, 2, 3], function(num){ return num * 3; }); +=> [3, 6, 9] +*/ + @Test + public void map() { + List result = _.map(asList(1, 2, 3), new Function1() { + public Integer apply(Integer item) { + return item * 3; + } + }); + assertEquals("[3, 6, 9]", result.toString()); + } + +/* +_.collect([1, 2, 3], function(num){ return num * 3; }); +=> [3, 6, 9] +*/ + @Test + public void collect() { + List result = _.collect(asList(1, 2, 3), new Function1() { + public Integer apply(Integer item) { + return item * 3; + } + }); + assertEquals("[3, 6, 9]", result.toString()); + Set resultSet = _.collect(new LinkedHashSet(asList(1, 2, 3)), new Function1() { + public Integer apply(Integer item) { + return item * 3; + } + }); + assertEquals("[3, 6, 9]", resultSet.toString()); + } +/* +_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; }); +=> [3, 6, 9] +*/ + @Test + public void mapMap() { + final Set result = + _.map(new LinkedHashMap() {{ put(1, "one"); put(2, "two"); put(3, "three"); }}.entrySet(), + new Function1, Integer>() { + public Integer apply(Map.Entry item) { + return item.getKey() * 3; + } + }); + assertEquals("[3, 6, 9]", result.toString()); + } + +/* +var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0); +=> 6 +*/ + @Test + public void reduce() { + final Integer result = + _.reduce(asList(1, 2, 3), + new FunctionAccum() { + public Integer apply(Integer item1, Integer item2) { + return item1 + item2; + } + }, + 0); + assertEquals("6", result.toString()); + } + +/* +var list = [[0, 1], [2, 3], [4, 5]]; +var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); +=> [4, 5, 2, 3, 0, 1] +*/ + @Test + public void reduceRight() { + final List result = + _.reduceRight(asList(asList(0, 1), asList(2, 3), asList(4, 5)), + new FunctionAccum, List>() { + public List apply(List item1, List item2) { + List list = new ArrayList(item1); + list.addAll(item2); + return list; + } + }, + Collections.emptyList() + ); + assertEquals("[4, 5, 2, 3, 0, 1]", result.toString()); + } + +/* +var list = [[0, 1], [2, 3], [4, 5]]; +var flat = _.inject(list, function(a, b) { return a.concat(b); }, []); +=> [0, 1, 2, 3, 4, 5] +*/ + @Test + public void inject() { + final List result = + _.inject(asList(asList(0, 1), asList(2, 3), asList(4, 5)), + new FunctionAccum, List>() { + public List apply(List item1, List item2) { + List list = new ArrayList(item1); + list.addAll(item2); + return list; + } + }, + Collections.emptyList() + ); + assertEquals("[0, 1, 2, 3, 4, 5]", result.toString()); + } + +/* +var list = [[0, 1], [2, 3], [4, 5]]; +var flat = _.foldl(list, function(a, b) { return a.concat(b); }, []); +=> [0, 1, 2, 3, 4, 5] +*/ + @Test + public void foldl() { + final List result = + _.foldl(asList(asList(0, 1), asList(2, 3), asList(4, 5)), + new FunctionAccum, List>() { + public List apply(List item1, List item2) { + List list = new ArrayList(item1); + list.addAll(item2); + return list; + } + }, + Collections.emptyList() + ); + assertEquals("[0, 1, 2, 3, 4, 5]", result.toString()); + } + +/* +var list = [[0, 1], [2, 3], [4, 5]]; +var flat = _.foldr(list, function(a, b) { return a.concat(b); }, []); +=> [4, 5, 2, 3, 0, 1] +*/ + @Test + public void foldr() { + final List result = + _.foldr(asList(asList(0, 1), asList(2, 3), asList(4, 5)), + new FunctionAccum, List>() { + public List apply(List item1, List item2) { + List list = new ArrayList(item1); + list.addAll(item2); + return list; + } + }, + Collections.emptyList() + ); + assertEquals("[4, 5, 2, 3, 0, 1]", result.toString()); + } + +/* +_.contains([1, 2, 3], 3); +=> true +*/ + @Test + public void contains() { + final boolean result = _.contains(asList(1, 2, 3), 3); + assertTrue(result); + } + +/* +var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); +=> 2 +*/ + @Test + public void find() { + final Integer result = _.find(asList(1, 2, 3, 4, 5, 6), + new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals("2", result.toString()); + } + +/* +var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); +=> 2 +*/ + @Test + public void detect() { + final Integer result = _.detect(asList(1, 2, 3, 4, 5, 6), + new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals("2", result.toString()); + } + +/* +var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); +=> [2, 4, 6] +*/ + @Test + public void filter() { + final List result = _.filter(asList(1, 2, 3, 4, 5, 6), + new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals("[2, 4, 6]", result.toString()); + } + +/* +var evens = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); +=> [2, 4, 6] +*/ + @Test + public void reject() { + final List result = _.reject(asList(1, 2, 3, 4, 5, 6), + new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals("[1, 3, 5]", result.toString()); + final Set resultSet = _.reject(new LinkedHashSet(asList(1, 2, 3, 4, 5, 6)), + new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals("[1, 3, 5]", resultSet.toString()); + } + +/* +var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); +=> [2, 4, 6] +*/ + @Test + public void select() { + final List result = _.select(asList(1, 2, 3, 4, 5, 6), + new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals("[2, 4, 6]", result.toString()); + final Set resultSet = _.select(new LinkedHashSet(asList(1, 2, 3, 4, 5, 6)), + new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals("[2, 4, 6]", resultSet.toString()); + } + +/* +_.all([1, 2, 3, 4], function(num) { return num % 2 === 0; }); // false +_.all([1, 2, 3, 4], function(num) { return num < 5; }); // true +*/ + @Test + public void all() { + final Boolean result1 = _.all(asList(1, 2, 3, 4), + new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + final Boolean result2 = _.all(asList(1, 2, 3, 4), + new Predicate() { + public Boolean apply(Integer item) { + return item < 5; + } + }); + assertFalse(result1); + assertTrue(result2); + } + +/* +_.any([1, 2, 3, 4], function(num) { return num % 2 === 0; }); // true +_.any([1, 2, 3, 4], function(num) { return num === 5; }); // false +*/ + @Test + public void any() { + final Boolean result1 = _.any(asList(1, 2, 3, 4), + new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + final Boolean result2 = _.any(asList(1, 2, 3, 4), + new Predicate() { + public Boolean apply(Integer item) { + return item == 5; + } + }); + assertTrue(result1); + assertFalse(result2); + } + +/* +_.include([1, 2, 3], 3); // true +*/ + @Test + public void include() { + final Boolean result = _.include(asList(1, 2, 3), 3); + assertTrue(result); + } + +/* +_.invoke([" foo ", " bar"], "trim"); // ["foo", "bar"] +*/ + @Test + public void invoke() throws Exception { + assertEquals(_.invoke(asList(" foo ", " bar"), "trim"), asList("foo", "bar")); + assertEquals(_.invoke(asList("foo", "bar"), "concat", Arrays.asList("1")), asList("foo1", "bar1")); + } + + @Test(expected = IllegalArgumentException.class) + public void invoke2() throws Exception { + _.invoke(asList("foo", 123), "concat", Arrays.asList("1")); + } + +/* +_.where(listOfPlays, {author: "Shakespeare", year: 1611}); +=> [{title: "Cymbeline", author: "Shakespeare", year: 1611}, + {title: "The Tempest", author: "Shakespeare", year: 1611}] +*/ + @Test + public void where() { + class Book { + public final String title; + public final String author; + public final Integer year; + public Book(final String title, final String author, final Integer year) { + this.title = title; + this.author = author; + this.year = year; + } + public String toString() { + return "title: " + title + ", author: " + author + ", year: " + year; + } + }; + List listOfPlays = + new ArrayList() {{ + add(new Book("Cymbeline2", "Shakespeare", 1614)); + add(new Book("Cymbeline", "Shakespeare", 1611)); + add(new Book("The Tempest", "Shakespeare", 1611)); + }}; + assertEquals("[title: Cymbeline, author: Shakespeare, year: 1611," + + " title: The Tempest, author: Shakespeare, year: 1611]", + _.where(listOfPlays, asList( + Tuple.create("author", "Shakespeare"), + Tuple.create("year", Integer.valueOf(1611)))).toString()); + assertEquals("[title: Cymbeline, author: Shakespeare, year: 1611," + + " title: The Tempest, author: Shakespeare, year: 1611]", + _.where(listOfPlays, asList( + Tuple.create("author", "Shakespeare"), + Tuple.create("author2", "Shakespeare"), + Tuple.create("year", Integer.valueOf(1611)))).toString()); + assertEquals("[title: Cymbeline, author: Shakespeare, year: 1611," + + " title: The Tempest, author: Shakespeare, year: 1611]", + _.where(new LinkedHashSet(listOfPlays), asList( + Tuple.create("author", "Shakespeare"), + Tuple.create("year", Integer.valueOf(1611)))).toString()); + assertEquals("[title: Cymbeline, author: Shakespeare, year: 1611," + + " title: The Tempest, author: Shakespeare, year: 1611]", + _.where(new LinkedHashSet(listOfPlays), asList( + Tuple.create("author", "Shakespeare"), + Tuple.create("author2", "Shakespeare"), + Tuple.create("year", Integer.valueOf(1611)))).toString()); + } + +/* +_.findWhere(listOfPlays, {author: "Shakespeare", year: 1611}) +=> {title: "Cymbeline", author: "Shakespeare", year: 1611} +*/ + @Test + public void findWhere() { + class Book { + public final String title; + public final String author; + public final Integer year; + public Book(final String title, final String author, final Integer year) { + this.title = title; + this.author = author; + this.year = year; + } + public String toString() { + return "title: " + title + ", author: " + author + ", year: " + year; + } + }; + List listOfPlays = + new ArrayList() {{ + add(new Book("Cymbeline2", "Shakespeare", 1614)); + add(new Book("Cymbeline", "Shakespeare", 1611)); + add(new Book("The Tempest", "Shakespeare", 1611)); + }}; + assertEquals("title: Cymbeline, author: Shakespeare, year: 1611", + _.findWhere(listOfPlays, asList( + Tuple.create("author", "Shakespeare"), + Tuple.create("year", Integer.valueOf(1611)))).toString()); + assertEquals("title: Cymbeline, author: Shakespeare, year: 1611", + _.findWhere(listOfPlays, asList( + Tuple.create("author", "Shakespeare"), + Tuple.create("author2", "Shakespeare"), + Tuple.create("year", Integer.valueOf(1611)))).toString()); + } + +/* +_.first([5, 4, 3, 2, 1]); +=> 5 +_.first([5, 4, 3, 2, 1], 2); +=> [5, 4] +*/ + @Test + public void first() { + final Integer result = _.first(asList(5, 4, 3, 2, 1)); + assertEquals("5", result.toString()); + final Object resultChain = _.chain(asList(5, 4, 3, 2, 1)).first().item(); + assertEquals("5", resultChain.toString()); + final Object resultChainTwo = _.chain(asList(5, 4, 3, 2, 1)).first(2).value(); + assertEquals("[5, 4]", resultChainTwo.toString()); + final List resultList = _.first(asList(5, 4, 3, 2, 1), 2); + assertEquals("[5, 4]", resultList.toString()); + final int resultInt = _.first(new Integer[] {5, 4, 3, 2, 1}); + assertEquals(5, resultInt); + } + +/* +_.head([5, 4, 3, 2, 1]); +=> 5 +_.head([5, 4, 3, 2, 1], 2); +=> [5, 4] +*/ + @Test + public void head() { + final Integer result = _.head(asList(5, 4, 3, 2, 1)); + assertEquals("5", result.toString()); + final Integer resultObj = new _(asList(5, 4, 3, 2, 1)).head(); + assertEquals("5", resultObj.toString()); + final List resultList = _.head(asList(5, 4, 3, 2, 1), 2); + assertEquals("[5, 4]", resultList.toString()); + final List resultListObj = new _(asList(5, 4, 3, 2, 1)).head(2); + assertEquals("[5, 4]", resultListObj.toString()); + final int resultInt = _.head(new Integer[] {5, 4, 3, 2, 1}); + assertEquals(5, resultInt); + } + +/* +_.initial([5, 4, 3, 2, 1]); +=> [5, 4, 3, 2] +_.initial([5, 4, 3, 2, 1], 2); +=> [5, 4, 3] +*/ + @Test + public void initial() { + final List result = _.initial(asList(5, 4, 3, 2, 1)); + assertEquals("[5, 4, 3, 2]", result.toString()); + final List resultChain = _.chain(asList(5, 4, 3, 2, 1)).initial().value(); + assertEquals("[5, 4, 3, 2]", resultChain.toString()); + final List resultList = _.initial(asList(5, 4, 3, 2, 1), 2); + assertEquals("[5, 4, 3]", resultList.toString()); + final List resultListChain = _.chain(asList(5, 4, 3, 2, 1)).initial(2).value(); + assertEquals("[5, 4, 3]", resultListChain.toString()); + final Integer[] resultArray = _.initial(new Integer[] {5, 4, 3, 2, 1}); + assertEquals("[5, 4, 3, 2]", asList(resultArray).toString()); + final Integer[] resultListArray = _.initial(new Integer[] {5, 4, 3, 2, 1}, 2); + assertEquals("[5, 4, 3]", asList(resultListArray).toString()); + } + +/* +_.last([5, 4, 3, 2, 1]); +=> 1 +*/ + @Test + public void last() { + final Integer result = _.last(asList(5, 4, 3, 2, 1)); + assertEquals("1", result.toString()); + final List resultTwo = _.last(asList(5, 4, 3, 2, 1), 2); + assertEquals("[2, 1]", resultTwo.toString()); + final Object resultChain = _.chain(asList(5, 4, 3, 2, 1)).last().item(); + assertEquals("1", resultChain.toString()); + final Object resultChainTwo = _.chain(asList(5, 4, 3, 2, 1)).last(2).value(); + assertEquals("[2, 1]", resultChainTwo.toString()); + final Integer resultArray = _.last(new Integer[] {5, 4, 3, 2, 1}); + assertEquals("1", resultArray.toString()); + } + +/* +_.tail([5, 4, 3, 2, 1]); +=> [4, 3, 2, 1] +_.tail([5, 4, 3, 2, 1], 2); +=> [3, 2, 1] +*/ + @Test + public void tail() { + final List result = _.tail(asList(5, 4, 3, 2, 1)); + assertEquals("[4, 3, 2, 1]", result.toString()); + final List result2 = _.tail(asList(5, 4, 3, 2, 1), 2); + assertEquals("[3, 2, 1]", result2.toString()); + final Object[] resultArray = _.tail(new Integer[] {5, 4, 3, 2, 1}); + assertEquals("[4, 3, 2, 1]", asList(resultArray).toString()); + final List resultArrayObj = new _(asList(5, 4, 3, 2, 1)).tail(); + assertEquals("[4, 3, 2, 1]", resultArrayObj.toString()); + final Object[] resultArray2 = _.tail(new Integer[] {5, 4, 3, 2, 1}, 2); + assertEquals("[3, 2, 1]", asList(resultArray2).toString()); + final List resultArray2Obj = new _(asList(5, 4, 3, 2, 1)).tail(2); + assertEquals("[3, 2, 1]", resultArray2Obj.toString()); + } + +/* +_.drop([5, 4, 3, 2, 1]); +=> [4, 3, 2, 1] +_.drop([5, 4, 3, 2, 1], 2); +=> [3, 2, 1] +*/ + @Test + public void drop() { + final List result = _.drop(asList(5, 4, 3, 2, 1)); + assertEquals("[4, 3, 2, 1]", result.toString()); + final List result2 = _.drop(asList(5, 4, 3, 2, 1), 2); + assertEquals("[3, 2, 1]", result2.toString()); + final Object[] resultArray = _.drop(new Integer[] {5, 4, 3, 2, 1}); + assertEquals("[4, 3, 2, 1]", asList(resultArray).toString()); + final Object[] resultArray2 = _.drop(new Integer[] {5, 4, 3, 2, 1}, 2); + assertEquals("[3, 2, 1]", asList(resultArray2).toString()); + } + +/* +_.rest([5, 4, 3, 2, 1]); +=> [4, 3, 2, 1] +_.rest([5, 4, 3, 2, 1], 2); +=> [3, 2, 1] +*/ + @Test + public void rest() { + final List result = _.rest(asList(5, 4, 3, 2, 1)); + assertEquals("[4, 3, 2, 1]", result.toString()); + final List resultChain = _.chain(asList(5, 4, 3, 2, 1)).rest().value(); + assertEquals("[4, 3, 2, 1]", resultChain.toString()); + final List result2 = _.rest(asList(5, 4, 3, 2, 1), 2); + assertEquals("[3, 2, 1]", result2.toString()); + final List result2Chain = _.chain(asList(5, 4, 3, 2, 1)).rest(2).value(); + assertEquals("[3, 2, 1]", result2Chain.toString()); + final Object[] resultArray = _.rest(new Integer[] {5, 4, 3, 2, 1}); + assertEquals("[4, 3, 2, 1]", asList(resultArray).toString()); + final Object[] resultArray2 = _.rest(new Integer[] {5, 4, 3, 2, 1}, 2); + assertEquals("[3, 2, 1]", asList(resultArray2).toString()); + } + + +/* +_.flatten([1, [2], [3, [[4]]]]); +=> [1, 2, 3, 4]; +*/ + @Test + public void flatten() { + final List result = _.flatten(asList(1, asList(2, asList(3, asList(asList(4)))))); + assertEquals("[1, 2, 3, 4]", result.toString()); + final List result2 = _.flatten(asList(1, asList(2, asList(3, asList(asList(4))))), true); + assertEquals("[1, 2, [3, [[4]]]]", result2.toString()); + final List result3 = _.flatten(asList(1, asList(2, asList(3, asList(asList(4))))), false); + assertEquals("[1, 2, 3, 4]", result3.toString()); + final List resultObj = new _(asList(1, asList(2, asList(3, asList(asList(4)))))).flatten(); + assertEquals("[1, 2, 3, 4]", resultObj.toString()); + final List resultObj2 = new _(asList(1, asList(2, asList(3, asList(asList(4)))))).flatten(true); + assertEquals("[1, 2, [3, [[4]]]]", resultObj2.toString()); + final List resultObj3 = new _(asList(1, asList(2, asList(3, asList(asList(4)))))).flatten(false); + assertEquals("[1, 2, 3, 4]", resultObj3.toString()); + } + +/* +_.compact([0, 1, false, 2, '', 3]); +=> [1, 2, 3] +*/ + @Test + public void compact() { + final List result = _.compact(asList(0, 1, false, 2, "", 3)); + assertEquals("[1, 2, 3]", result.toString()); + final List result2 = _.compact(asList(0, 1, false, 2, "", 3), 1); + assertEquals("[0, false, 2, , 3]", result2.toString()); + final List result3 = new _(asList(0, 1, false, 2, "", 3)).compact(); + assertEquals("[1, 2, 3]", result3.toString()); + final List result4 = new _(asList(0, 1, false, 2, "", 3)).compact(1); + assertEquals("[0, false, 2, , 3]", result4.toString()); + final Object[] resultArray = _.compact(new Object[] {0, 1, false, 2, "", 3}); + assertEquals("[1, 2, 3]", asList(resultArray).toString()); + final Object[] resultArray2 = _.compact(new Object[] {0, 1, false, 2, "", 3}, 1); + assertEquals("[0, false, 2, , 3]", asList(resultArray2).toString()); + } + +/* +_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); +=> [2, 3, 4] +*/ + @Test + public void without() { + final List result = _.without(asList(1, 2, 1, 0, 3, 1, 4), 0, 1); + assertEquals("[2, 3, 4]", result.toString()); + final List result2 = _.without(asList(1, 2, 1, 0, 3, 1, 4), 1); + assertEquals("[2, 0, 3, 4]", result2.toString()); + final Object[] resultArray = _.without(new Integer[] {1, 2, 1, 0, 3, 1, 4}, 0, 1); + assertEquals("[2, 3, 4]", asList(resultArray).toString()); + final Object[] resultArray2 = _.without(new Integer[] {1, 2, 1, 0, 3, 1, 4}, 1); + assertEquals("[2, 0, 3, 4]", asList(resultArray2).toString()); + } + +/* +var numbers = [10, 5, 100, 2, 1000]; +_.max(numbers); +=> 1000 +*/ + @Test + public void max() { + final Integer result = _.max(asList(10, 5, 100, 2, 1000)); + assertEquals("1000", result.toString()); + final Integer resultComp = _.max(asList(10, 5, 100, 2, 1000), + new Function1() { + public Integer apply(Integer item) { + return -item; + } + }); + assertEquals("2", resultComp.toString()); + class Person { + public final String name; + public final Integer age; + public Person(final String name, final Integer age) { + this.name = name; + this.age = age; + } + }; + final Person resultPerson = _.max(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 60)), + new Function1() { + public Integer apply(Person item) { + return item.age; + } + }); + assertEquals("curly", resultPerson.name); + assertEquals(60, resultPerson.age); + } + +/* +var numbers = [10, 5, 100, 2, 1000]; +_.min(numbers); +=> 2 +*/ + @Test + public void min() { + final Integer result = _.min(asList(10, 5, 100, 2, 1000)); + assertEquals("2", result.toString()); + final Integer resultComp = _.min(asList(10, 5, 100, 2, 1000), + new Function1() { + public Integer apply(Integer item) { + return -item; + } + }); + assertEquals("1000", resultComp.toString()); + class Person { + public final String name; + public final Integer age; + public Person(final String name, final Integer age) { + this.name = name; + this.age = age; + } + }; + final Person resultPerson = _.min(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 60)), + new Function1() { + public Integer apply(Person item) { + return item.age; + } + }); + assertEquals("moe", resultPerson.name); + assertEquals(40, resultPerson.age); + } + +/* +_.shuffle([1, 2, 3, 4, 5, 6]); +=> [4, 1, 6, 3, 5, 2] +*/ + @Test + public void shuffle() { + final List result = _.shuffle(asList(1, 2, 3, 4, 5, 6)); + assertEquals(6, result.size()); + } + +/* +_.sample([1, 2, 3, 4, 5, 6]); +=> 4 + +_.sample([1, 2, 3, 4, 5, 6], 3); +=> [1, 6, 2] +*/ + @Test + public void sample() { + final Integer result = _.sample(asList(1, 2, 3, 4, 5, 6)); + assertTrue(result >= 1 && result <= 6); + final Set resultList = _.sample(asList(1, 2, 3, 4, 5, 6), 3); + assertEquals(3, resultList.size()); + } + +/* +var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}]; +_.pluck(stooges, 'name'); +=> ["moe", "larry", "curly"] +*/ + @Test + public void pluck() throws Exception { + class Person { + public final String name; + public final Integer age; + public Person(final String name, final Integer age) { + this.name = name; + this.age = age; + } + }; + final List resultEmpty = + _.pluck(asList(), "name"); + assertEquals("[]", resultEmpty.toString()); + final List result = + _.pluck(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 40)), "name"); + assertEquals("[moe, larry, curly]", result.toString()); + final Set resultEmpty2 = + _.pluck(new LinkedHashSet(asList()), "name"); + assertEquals("[]", resultEmpty2.toString()); + final Set resultSet = + _.pluck(new LinkedHashSet(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 40))), "name"); + assertEquals("[moe, larry, curly]", resultSet.toString()); + } + + @Test(expected = IllegalArgumentException.class) + public void pluck2() throws Exception { + class Person { + public final String name; + public final Integer age; + public Person(final String name, final Integer age) { + this.name = name; + this.age = age; + } + }; + _.pluck(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 40)), "name2"); + } + + @Test(expected = IllegalArgumentException.class) + public void pluck3() throws Exception { + class Person { + public final String name; + public final Integer age; + public Person(final String name, final Integer age) { + this.name = name; + this.age = age; + } + }; + _.pluck(new LinkedHashSet(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 40))), "name2"); + } +/* +_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); }); +=> [5, 4, 6, 3, 1, 2] +*/ + @Test + public void sortBy() throws Exception { + final List result = + _.sortBy(asList(1, 2, 3, 4, 5, 6), + new Function1() { + public Integer apply(Integer item) { + return Double.valueOf(Math.sin(item) * 1000).intValue(); + } + }); + assertEquals("[5, 4, 6, 3, 1, 2]", result.toString()); + } + +/* +_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); }); +=> {1: [1.3], 2: [2.1, 2.4]} +*/ + @Test + public void groupBy() throws Exception { + final Map> result = + _.groupBy(asList(1.3, 2.1, 2.4), + new Function1() { + public Double apply(Double num) { + return Math.floor(num); + } + }); + assertEquals("{1.0=[1.3], 2.0=[2.1, 2.4]}", result.toString()); + } + +/* +var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}]; +_.indexBy(stooges, 'age'); +=> { + "40": {name: 'moe', age: 40}, + "50": {name: 'larry', age: 50}, + "60": {name: 'curly', age: 60} +} +*/ + @Test + public void indexBy() throws Exception { + class Person { + public final String name; + public final Integer age; + public Person(final String name, final Integer age) { + this.name = name; + this.age = age; + } + public String toString() { + return name + ", " + age; + } + }; + final Map> result = + _.indexBy(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 60)), "age"); + assertEquals("{40=[moe, 40], 50=[larry, 50], 60=[curly, 60]}", result.toString()); + final Map> result2 = + _.indexBy(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 60)), "age2"); + assertEquals("{null=[moe, 40, larry, 50, curly, 60]}", result2.toString()); + } + +/* +var stooges = [{name: 'moe', age: 40}, {name: 'moe', age: 50}, {name: 'curly', age: 60}]; +_.countBy(stooges, 'age'); +=> {moe: 2, curly: 1} +*/ + @Test + public void countBy() throws Exception { + class Person { + public final String name; + public final Integer age; + public Person(final String name, final Integer age) { + this.name = name; + this.age = age; + } + public String toString() { + return name + ", " + age; + } + }; + final Map result = + _.countBy(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)), + new Function1() { + public String apply(Person person) { + return person.name; + } + }); + assertEquals("{moe=2, curly=1}", result.toString()); + } + +/* +(function(){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4); +=> [2, 3, 4] +*/ + @Test + public void toArray() throws Exception { + final Object[] result = _.toArray(asList(1, 2, 3, 4)); + assertEquals("1", result[0].toString()); + } + +/* +_.size({one: 1, two: 2, three: 3}); +=> 3 +*/ + @Test + public void size() throws Exception { + final int result = _.size(asList(1, 2, 3, 4)); + assertEquals(4, result); + } + +/* +_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); +=> [1, 2, 3, 101, 10] +*/ + @Test + public void union() throws Exception { + final List result = _.union(asList(1, 2, 3), asList(101, 2, 1, 10), asList(2, 1)); + assertEquals("[1, 2, 3, 101, 10]", result.toString()); + final Object[] resultArray = _.union(new Integer[] {1, 2, 3}, new Integer[] {101, 2, 1, 10}); + assertEquals("[[1, 2, 3, 101, 10]]", asList(result).toString()); + } + +/* +_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); +=> [1, 2] +*/ + @Test + public void intersection() throws Exception { + final List result = _.intersection(asList(1, 2, 3), asList(101, 2, 1, 10), asList(2, 1)); + assertEquals("[1, 2]", result.toString()); + final Object[] resultArray = _.intersection(new Integer[] {1, 2, 3}, new Integer[] {101, 2, 1, 10}); + assertEquals("[1, 2]", asList(resultArray).toString()); + } + +/* +_.difference([1, 2, 3, 4, 5], [5, 2, 10]); +=> [1, 3, 4] +*/ + @Test + public void difference() throws Exception { + final List result = _.difference(asList(1, 2, 3, 4, 5), asList(5, 2, 10)); + assertEquals("[1, 3, 4]", result.toString()); + final Object[] resultArray = _.difference(new Integer[] {1, 2, 3, 4, 5}, new Integer[] {5, 2, 10}); + assertEquals("[1, 3, 4]", asList(resultArray).toString()); + } + +/* +_.uniq([1, 2, 1, 3, 1, 4]); +=> [1, 2, 3, 4] +*/ + @Test + public void uniq() throws Exception { + final List result = _.uniq(asList(1, 2, 1, 3, 1, 4)); + assertEquals("[1, 2, 3, 4]", result.toString()); + final Object[] resultArray = _.uniq(new Integer[] {1, 2, 1, 3, 1, 4}); + assertEquals("[1, 2, 3, 4]", asList(resultArray).toString()); + class Person { + public final String name; + public final Integer age; + public Person(final String name, final Integer age) { + this.name = name; + this.age = age; + } + public String toString() { + return name + ", " + age; + } + }; + final Collection resultObject = + _.uniq(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)), + new Function1() { + public String apply(Person person) { + return person.name; + } + }); + assertEquals("[moe, 50, curly, 60]", resultObject.toString()); + final List resultObjectChain = + _.chain(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60))).uniq( + new Function1() { + public String apply(Person person) { + return person.name; + } + }).value(); + assertEquals("[moe, 50, curly, 60]", resultObjectChain.toString()); + final Object[] resultObjectArray = + _.uniq(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)).toArray(new Person[]{}), + new Function1() { + public String apply(Person person) { + return person.name; + } + }); + assertEquals("[moe, 50, curly, 60]", asList(resultObjectArray).toString()); + } + +/* +_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); +=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]] +*/ + @Test + public void zip() throws Exception { + final List> result = _.zip( + asList("moe", "larry", "curly"), asList("30", "40", "50"), asList("true", "false", "false")); + assertEquals("[[moe, 30, true], [larry, 40, false], [curly, 50, false]]", result.toString()); + } + +/* +_.object(['moe', 'larry', 'curly'], [30, 40, 50]); +=> {moe: 30, larry: 40, curly: 50} +*/ + @Test + public void object() throws Exception { + final List> result = _.object( + asList("moe", "larry", "curly"), asList("30", "40", "50")); + assertEquals("[(moe, 30), (larry, 40), (curly, 50)]", result.toString()); + } + +/* +_.indexOf([1, 2, 3], 2); +=> 1 +*/ + @Test + public void indexOf() throws Exception { + final Integer result = _.indexOf(asList(1, 2, 3), 2); + assertEquals(1, result); + final Integer resultArray = _.indexOf(new Integer[] {1, 2, 3}, 2); + assertEquals(1, resultArray); + } + +/* +_.lastIndexOf([1, 2, 3, 1, 2, 3], 2); +=> 4 +*/ + @Test + public void lastIndexOf() throws Exception { + final Integer result = _.lastIndexOf(asList(1, 2, 3, 1, 2, 3), 2); + assertEquals(4, result); + final Integer resultArray = _.lastIndexOf(new Integer[] {1, 2, 3, 1, 2, 3}, 2); + assertEquals(4, resultArray); + } + +/* +_.findIndex([1, 2, 3], function(item) {return item % 2 === 0; }); +=> 1 +*/ + @Test + public void findIndex() throws Exception { + final Integer result = _.findIndex(asList(1, 2, 3), new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(1, result); + final Integer resultNotFound = _.findIndex(asList(1, 2, 3), new Predicate() { + public Boolean apply(Integer item) { + return item > 3; + } + }); + assertEquals(-1, resultNotFound); + final Integer resultArray = _.findIndex(new Integer[] {1, 2, 3}, new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(1, resultArray); + } + +/* +_.findKey([1, 2, 3], function(item) {return item % 2 === 0; }); +=> 2 +*/ + @Test + public void findKey() throws Exception { + final Integer result = _.findKey(asList(1, 2, 3), new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(2, result); + final Integer resultNotFound = _.findKey(asList(1, 2, 3), new Predicate() { + public Boolean apply(Integer item) { + return item > 3; + } + }); + assertNull(resultNotFound); + final Integer resultArray = _.findKey(new Integer[] {1, 2, 3}, new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(2, resultArray); + } + +/* +_.findLastIndex([1, 2, 3, 4, 5], function(item) {return item % 2 === 0; }); +=> 3 +*/ + @Test + public void findLastIndex() throws Exception { + final Integer result = _.findLastIndex(asList(1, 2, 3, 4, 5), new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(3, result); + final Integer resultNotFound = _.findLastIndex(asList(1, 2, 3, 4, 5), new Predicate() { + public Boolean apply(Integer item) { + return item > 5; + } + }); + assertEquals(-1, resultNotFound); + final Integer resultArray = _.findLastIndex(new Integer[] {1, 2, 3, 4, 5}, new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(3, resultArray); + } + +/* +_.findLastKey([1, 2, 3, 4, 5], function(item) {return item % 2 === 0; }); +=> 4 +*/ + @Test + public void findLastKey() throws Exception { + final Integer result = _.findLastKey(asList(1, 2, 3, 4, 5), new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(4, result); + final Integer resultNotFound = _.findLastKey(asList(1, 2, 3, 4, 5), new Predicate() { + public Boolean apply(Integer item) { + return item > 5; + } + }); + assertNull(resultNotFound); + final Integer resultArray = _.findLastKey(new Integer[] {1, 2, 3, 4, 5}, new Predicate() { + public Boolean apply(Integer item) { + return item % 2 == 0; + } + }); + assertEquals(4, resultArray); + } + +/* +_.sortedIndex([10, 20, 30, 40, 50], 35); +=> 3 +*/ + @Test + public void sortedIndex() throws Exception { + final Integer result = _.sortedIndex(asList(10, 20, 30, 40, 50), 35); + assertEquals(3, result); + final Integer result2 = _.sortedIndex(new Integer[] {10, 20, 30, 40, 50}, 35); + assertEquals(3, result2); + final Integer result3 = _.sortedIndex(asList(10, 20, 30, 40, 50), 60); + assertEquals(-1, result3); + } + + @Test + public void sortedIndex2() throws Exception { + class Person implements Comparable { + public final String name; + public final Integer age; + public Person(final String name, final Integer age) { + this.name = name; + this.age = age; + } + public int compareTo(Person person) { + return person.age - this.age; + } + public String toString() { + return name + ", " + age; + } + }; + final int result = + _.sortedIndex(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)), new Person("moe", 50), "age"); + assertEquals(1, result); + final int result2 = + _.sortedIndex(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)), new Person("moe", 70), "age"); + assertEquals(-1, result2); + final int resultArray = + _.sortedIndex(new Person[] {new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)}, new Person("moe", 50), "age"); + assertEquals(1, resultArray); + } + +/* +_.range(10); +=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +_.range(1, 11); +=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +_.range(0, 30, 5); +=> [0, 5, 10, 15, 20, 25] +_.range(0, -10, -1); +=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] +_.range(0); +=> [] +*/ + @Test + public void range() throws Exception { + final int[] result = _.range(10); + assertArrayEquals(new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, result); + final int[] result2 = _.range(1, 11); + assertArrayEquals(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, result2); + final int[] result3 = _.range(0, 30, 5); + assertArrayEquals(new int[] {0, 5, 10, 15, 20, 25}, result3); + final int[] result4 = _.range(0, -10, -1); + assertArrayEquals(new int[] {0, -1, -2, -3, -4, -5, -6, -7, -8, -9}, result4); + final int[] result5 = _.range(0); + assertArrayEquals(new int[] {}, result5); + } + +/* +_.partition([0, 1, 2, 3, 4, 5], isOdd); +=> [[1, 3, 5], [0, 2, 4]] +*/ + @Test + public void partition() throws Exception { + final List> result = _.partition(asList(0, 1, 2, 3, 4, 5), new Predicate() { + public Boolean apply(final Integer item) { + return item % 2 == 1; + } + }); + assertEquals("[1, 3, 5]", result.get(0).toString()); + assertEquals("[0, 2, 4]", result.get(1).toString()); + final List[] resultArray = _.partition(new Integer[] {0, 1, 2, 3, 4, 5}, new Predicate() { + public Boolean apply(final Integer item) { + return item % 2 == 1; + } + }); + assertEquals("[1, 3, 5]", resultArray[0].toString()); + assertEquals("[0, 2, 4]", resultArray[1].toString()); + } + +/* +var stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}]; +var youngest = _.chain(stooges) + .sortBy(function(stooge){ return stooge.age; }) + .map(function(stooge){ return stooge.name + ' is ' + stooge.age; }) + .first() + .value(); +=> "moe is 21" +*/ + @Test + public void chain() throws Exception { + final List> stooges = new ArrayList>() {{ + add(new LinkedHashMap() {{ put("name", "curly"); put("age", 25); }}); + add(new LinkedHashMap() {{ put("name", "moe"); put("age", 21); }}); + add(new LinkedHashMap() {{ put("name", "larry"); put("age", 23); }}); + }}; + final String youngest = _.chain(stooges) + .sortBy( + new Function1, String>() { + public String apply(Map item) { + return item.get("age").toString(); + } + }) + .map( + new Function1, String>() { + public String apply(Map item) { + return item.get("name") + " is " + item.get("age"); + } + }) + .first().item().toString(); + assertEquals("moe is 21", youngest); + } + + @Test + public void chainSet() throws Exception { + final Set> stooges = new HashSet>() {{ + add(new LinkedHashMap() {{ put("name", "curly"); put("age", 25); }}); + add(new LinkedHashMap() {{ put("name", "moe"); put("age", 21); }}); + add(new LinkedHashMap() {{ put("name", "larry"); put("age", 23); }}); + }}; + final String youngest = _.chain(stooges) + .sortBy( + new Function1, String>() { + public String apply(Map item) { + return item.get("age").toString(); + } + }) + .map( + new Function1, String>() { + public String apply(Map item) { + return item.get("name") + " is " + item.get("age"); + } + }) + .first().item().toString(); + assertEquals("moe is 21", youngest); + } + + @Test + public void chainArray() throws Exception { + final List> stooges = new ArrayList>() {{ + add(new LinkedHashMap() {{ put("name", "curly"); put("age", 25); }}); + add(new LinkedHashMap() {{ put("name", "moe"); put("age", 21); }}); + add(new LinkedHashMap() {{ put("name", "larry"); put("age", 23); }}); + }}; + final String youngest = _.chain(stooges.toArray()) + .sortBy( + new Function1, String>() { + public String apply(Map item) { + return item.get("age").toString(); + } + }) + .map( + new Function1, String>() { + public String apply(Map item) { + return item.get("name") + " is " + item.get("age"); + } + }) + .first().item().toString(); + assertEquals("moe is 21", youngest); + } + +/* +var lyrics = [ + {line: 1, words: "I'm a lumberjack and I'm okay"}, + {line: 2, words: "I sleep all night and I work all day"}, + {line: 3, words: "He's a lumberjack and he's okay"}, + {line: 4, words: "He sleeps all night and he works all day"} +]; + +_.chain(lyrics) + .map(function(line) { return line.words.split(' '); }) + .flatten() + .reduce(function(counts, word) { + counts[word] = (counts[word] || 0) + 1; + return counts; + }, {}) + .value(); + +=> {lumberjack: 2, all: 4, night: 2 ... } +*/ + @Test + public void chain2() throws Exception { + final List> lyrics = new ArrayList>() {{ + add(new LinkedHashMap() {{ put("line", 1); put("words", "I'm a lumberjack and I'm okay"); }}); + add(new LinkedHashMap() {{ put("line", 2); put("words", "I sleep all night and I work all day"); }}); + add(new LinkedHashMap() {{ put("line", 3); put("words", "He's a lumberjack and he's okay"); }}); + add(new LinkedHashMap() {{ put("line", 4); put("words", "He sleeps all night and he works all day"); }}); + }}; + final String result = _.chain(lyrics) + .map( + new Function1, List>() { + public List apply(Map item) { + return asList(String.valueOf(item.get("words")).split(" ")); + } + }) + .flatten() + .reduce( + new FunctionAccum, String>() { + public Map apply(Map accum, String item) { + if (accum.get(item) == null) { + accum.put(item, 1); + } else { + accum.put(item, ((Integer) accum.get(item)) + 1); + } + return accum; + } + }, + new LinkedHashMap() + ) + .item().toString(); + assertEquals("{I'm=2, a=2, lumberjack=2, and=4, okay=2, I=2, sleep=1, all=4, night=2, work=1, day=2, He's=1," + + " he's=1, He=1, sleeps=1, he=1, works=1}", result); + } + +/* +var lyrics = [ + {line: 1, words: "I'm a lumberjack and I'm okay"}, + {line: 2, words: "I sleep all night and I work all day"}, + {line: 3, words: "He's a lumberjack and he's okay"}, + {line: 4, words: "He sleeps all night and he works all day"} +]; + +_.chain(lyrics) + .map(function(line) { return line.words.split(' '); }) + .flatten() + .reduceRight(function(counts, word) { + counts[word] = (counts[word] || 0) + 1; + return counts; + }, {}) + .value(); + +=> {day=2, all=4, works=1 ... } +*/ + @Test + public void chain3() throws Exception { + final List> lyrics = new ArrayList>() {{ + add(new LinkedHashMap() {{ put("line", 1); put("words", "I'm a lumberjack and I'm okay"); }}); + add(new LinkedHashMap() {{ put("line", 2); put("words", "I sleep all night and I work all day"); }}); + add(new LinkedHashMap() {{ put("line", 3); put("words", "He's a lumberjack and he's okay"); }}); + add(new LinkedHashMap() {{ put("line", 4); put("words", "He sleeps all night and he works all day"); }}); + }}; + final String result = _.chain(lyrics) + .map( + new Function1, List>() { + public List apply(Map item) { + return asList(String.valueOf(item.get("words")).split(" ")); + } + }) + .flatten() + .reduceRight( + new FunctionAccum, String>() { + public Map apply(Map accum, String item) { + if (accum.get(item) == null) { + accum.put(item, 1); + } else { + accum.put(item, ((Integer) accum.get(item)) + 1); + } + return accum; + } + }, + new LinkedHashMap() + ) + .item().toString(); + assertEquals("{day=2, all=4, works=1, he=1, and=4, night=2, sleeps=1," + + " He=1, okay=2, he's=1, lumberjack=2, a=2, He's=1, work=1, I=2, sleep=1, I'm=2}", result); + } + +/* +var doctors = [ + { number: 1, actor: "William Hartnell", begin: 1963, end: 1966 }, + { number: 9, actor: "Christopher Eccleston", begin: 2005, end: 2005 }, + { number: 10, actor: "David Tennant", begin: 2005, end: 2010 } +]; +_.chain(doctors) + .filter(function(doctor) { + return doctor.begin > 2000; + }) + .reject(function(doctor) { + return doctor.begin > 2009; + }) + .map(function(doctor) { + return { + doctorNumber: "#" + doctor.number, + playedBy: doctor.actor, + yearsPlayed: doctor.end - doctor.begin + 1 + }; + }) + .value(); + +=> [{ doctorNumber: "#9", playedBy: "Christopher Eccleston", yearsPlayed: 1 }] +*/ + @Test + public void chain4() throws Exception { + final List> doctors = new ArrayList>() {{ + add(new LinkedHashMap() {{ put("number", 1); put("actor", "William Hartnell"); put("begin", 1963); put("end", 1966); }}); + add(new LinkedHashMap() {{ put("number", 9); put("actor", "Christopher Eccleston"); put("begin", 2005); put("end", 2005); }}); + add(new LinkedHashMap() {{ put("number", 10); put("actor", "David Tennant"); put("begin", 2005); put("end", 2010); }}); + }}; + final String result = _.chain(doctors) + .filter( + new Predicate>() { + public Boolean apply(Map item) { + return (Integer) item.get("begin") > 2000; + } + }) + .reject( + new Predicate>() { + public Boolean apply(Map item) { + return (Integer) item.get("end") > 2009; + } + }) + .map( + new Function1, Map>() { + public Map apply(final Map item) { + return new LinkedHashMap() {{ + put("doctorNumber", "#" + item.get("number")); + put("playedBy", item.get("actor")); + put("yearsPlayed", (Integer) item.get("end") - (Integer) item.get("begin") + 1); + }}; + } + }) + .value().toString(); + assertEquals("[{doctorNumber=#9, playedBy=Christopher Eccleston, yearsPlayed=1}]", result); + } + +/* +var compiled = _.template("hello: <%= name %>"); +compiled({name: 'moe'}); +=> "hello: moe" +*/ + @Test + public void template() throws Exception { + Template>> compiled = _.template("hello: <%= name %>"); + assertEquals("hello: moe", compiled.apply(new LinkedHashMap() {{ put("name", "moe"); }}.entrySet())); + } + + @Test + public void template2() throws Exception { + Template>> compiled = _.template("hello: <%= name %>, hello2: <%= name %>"); + assertEquals("hello: moe, hello2: moe", compiled.apply(new LinkedHashMap() {{ put("name", "moe"); }}.entrySet())); + } + + @Test + public void template3() throws Exception { + Template>> compiled = _.template("hello: <%= name %>, hello2: <%= name2 %>"); + assertEquals("hello: moe, hello2: moe2", compiled.apply( + new LinkedHashMap() {{ put("name", "moe"); put("name2", "moe2"); }}.entrySet())); + } +/* +var list = "<% _.each(people, function(name) { %>
  • <%= name %>
  • <% }); %>"; +_.template(list, {people: ['moe', 'curly', 'larry']}); +=> "
  • moe
  • curly
  • larry
  • " +*/ + @Test + public void templateEach() throws Exception { + String list = "<% _.each(people, function(name) { %>
  • <%= name %>
  • <% }); %>"; + Template>> compiled = _.template(list); + assertEquals("
  • moe
  • curly
  • larry
  • ", + compiled.apply(new LinkedHashMap() {{ put("people", asList("moe", "curly", "larry")); }}.entrySet())); + } + +/* +var template = _.template("<%- value %>"); +template({value: ' and tags + Document doc = Jsoup.parse("\n"); + assertEquals(" \n", doc.head().html()); + } + + @Test public void testContainerOutput() { + Document doc = Jsoup.parse("Hello there

    Hello

    there

    Another
    "); + assertEquals("Hello there", doc.select("title").first().outerHtml()); + assertEquals("
    \n

    Hello

    \n

    there

    \n
    ", doc.select("div").first().outerHtml()); + assertEquals("
    \n

    Hello

    \n

    there

    \n
    \n
    \n Another\n
    ", doc.select("body").first().html()); + } + + @Test public void testSetText() { + String h = "
    Hello

    there now

    "; + Document doc = Jsoup.parse(h); + assertEquals("Hello there now", doc.text()); // need to sort out node whitespace + assertEquals("there now", doc.select("p").get(0).text()); + + Element div = doc.getElementById("1").text("Gone"); + assertEquals("Gone", div.text()); + assertEquals(0, doc.select("p").size()); + } + + @Test public void testAddNewElement() { + Document doc = Jsoup.parse("

    Hello

    "); + Element div = doc.getElementById("1"); + div.appendElement("p").text("there"); + div.appendElement("P").attr("CLASS", "second").text("now"); + // manually specifying tag and attributes should now preserve case, regardless of parse mode + assertEquals("

    Hello

    there

    now

    ", + TextUtil.stripNewlines(doc.html())); + + // check sibling index (with short circuit on reindexChildren): + Elements ps = doc.select("p"); + for (int i = 0; i < ps.size(); i++) { + assertEquals(i, ps.get(i).siblingIndex); + } + } + + @Test public void testAddBooleanAttribute() { + Element div = new Element(Tag.valueOf("div"), ""); + + div.attr("true", true); + + div.attr("false", "value"); + div.attr("false", false); + + assertTrue(div.hasAttr("true")); + assertEquals("", div.attr("true")); + + List attributes = div.attributes().asList(); + assertEquals("There should be one attribute", 1, attributes.size()); + assertTrue("Attribute should be boolean", attributes.get(0) instanceof BooleanAttribute); + + assertFalse(div.hasAttr("false")); + + assertEquals("
    ", div.outerHtml()); + } + + @Test public void testAppendRowToTable() { + Document doc = Jsoup.parse("
    1
    "); + Element table = doc.select("tbody").first(); + table.append("2"); + + assertEquals("
    1
    2
    ", TextUtil.stripNewlines(doc.body().html())); + } + + @Test public void testPrependRowToTable() { + Document doc = Jsoup.parse("
    1
    "); + Element table = doc.select("tbody").first(); + table.prepend("2"); + + assertEquals("
    2
    1
    ", TextUtil.stripNewlines(doc.body().html())); + + // check sibling index (reindexChildren): + Elements ps = doc.select("tr"); + for (int i = 0; i < ps.size(); i++) { + assertEquals(i, ps.get(i).siblingIndex); + } + } + + @Test public void testPrependElement() { + Document doc = Jsoup.parse("

    Hello

    "); + Element div = doc.getElementById("1"); + div.prependElement("p").text("Before"); + assertEquals("Before", div.child(0).text()); + assertEquals("Hello", div.child(1).text()); + } + + @Test public void testAddNewText() { + Document doc = Jsoup.parse("

    Hello

    "); + Element div = doc.getElementById("1"); + div.appendText(" there & now >"); + assertEquals("

    Hello

    there & now >", TextUtil.stripNewlines(div.html())); + } + + @Test public void testPrependText() { + Document doc = Jsoup.parse("

    Hello

    "); + Element div = doc.getElementById("1"); + div.prependText("there & now > "); + assertEquals("there & now > Hello", div.text()); + assertEquals("there & now >

    Hello

    ", TextUtil.stripNewlines(div.html())); + } + + @Test(expected = IllegalArgumentException.class) public void testThrowsOnAddNullText() { + Document doc = Jsoup.parse("

    Hello

    "); + Element div = doc.getElementById("1"); + div.appendText(null); + } + + @Test(expected = IllegalArgumentException.class) public void testThrowsOnPrependNullText() { + Document doc = Jsoup.parse("

    Hello

    "); + Element div = doc.getElementById("1"); + div.prependText(null); + } + + @Test public void testAddNewHtml() { + Document doc = Jsoup.parse("

    Hello

    "); + Element div = doc.getElementById("1"); + div.append("

    there

    now

    "); + assertEquals("

    Hello

    there

    now

    ", TextUtil.stripNewlines(div.html())); + + // check sibling index (no reindexChildren): + Elements ps = doc.select("p"); + for (int i = 0; i < ps.size(); i++) { + assertEquals(i, ps.get(i).siblingIndex); + } + } + + @Test public void testPrependNewHtml() { + Document doc = Jsoup.parse("

    Hello

    "); + Element div = doc.getElementById("1"); + div.prepend("

    there

    now

    "); + assertEquals("

    there

    now

    Hello

    ", TextUtil.stripNewlines(div.html())); + + // check sibling index (reindexChildren): + Elements ps = doc.select("p"); + for (int i = 0; i < ps.size(); i++) { + assertEquals(i, ps.get(i).siblingIndex); + } + } + + @Test public void testSetHtml() { + Document doc = Jsoup.parse("

    Hello

    "); + Element div = doc.getElementById("1"); + div.html("

    there

    now

    "); + assertEquals("

    there

    now

    ", TextUtil.stripNewlines(div.html())); + } + + @Test public void testSetHtmlTitle() { + Document doc = Jsoup.parse(""); + + Element title = doc.getElementById("1"); + title.html("good"); + assertEquals("good", title.html()); + title.html("bad"); + assertEquals("<i>bad</i>", title.html()); + + Element head = doc.getElementById("2"); + head.html("<i>bad</i>"); + assertEquals("<i>bad</i>", head.html()); + } + + @Test public void testWrap() { + Document doc = Jsoup.parse("

    Hello

    There

    "); + Element p = doc.select("p").first(); + p.wrap("
    "); + assertEquals("

    Hello

    There

    ", TextUtil.stripNewlines(doc.body().html())); + + Element ret = p.wrap("

    What?

    "); + assertEquals("

    Hello

    What?

    There

    ", + TextUtil.stripNewlines(doc.body().html())); + + assertEquals(ret, p); + } + + @Test public void before() { + Document doc = Jsoup.parse("

    Hello

    There

    "); + Element p1 = doc.select("p").first(); + p1.before("
    one
    two
    "); + assertEquals("
    one
    two

    Hello

    There

    ", TextUtil.stripNewlines(doc.body().html())); + + doc.select("p").last().before("

    Three

    "); + assertEquals("
    one
    two

    Hello

    Three

    There

    ", TextUtil.stripNewlines(doc.body().html())); + } + + @Test public void after() { + Document doc = Jsoup.parse("

    Hello

    There

    "); + Element p1 = doc.select("p").first(); + p1.after("
    one
    two
    "); + assertEquals("

    Hello

    one
    two

    There

    ", TextUtil.stripNewlines(doc.body().html())); + + doc.select("p").last().after("

    Three

    "); + assertEquals("

    Hello

    one
    two

    There

    Three

    ", TextUtil.stripNewlines(doc.body().html())); + } + + @Test public void testWrapWithRemainder() { + Document doc = Jsoup.parse("

    Hello

    "); + Element p = doc.select("p").first(); + p.wrap("

    There!

    "); + assertEquals("

    Hello

    There!

    ", TextUtil.stripNewlines(doc.body().html())); + } + + @Test public void testHasText() { + Document doc = Jsoup.parse("

    Hello

    "); + Element div = doc.select("div").first(); + Elements ps = doc.select("p"); + + assertTrue(div.hasText()); + assertTrue(ps.first().hasText()); + assertFalse(ps.last().hasText()); + } + + @Test public void dataset() { + Document doc = Jsoup.parse("
    Hello

    Hello

    "); + Element div = doc.select("div").first(); + Map dataset = div.dataset(); + Attributes attributes = div.attributes(); + + // size, get, set, add, remove + assertEquals(2, dataset.size()); + assertEquals("jsoup", dataset.get("name")); + assertEquals("jar", dataset.get("package")); + + dataset.put("name", "jsoup updated"); + dataset.put("language", "java"); + dataset.remove("package"); + + assertEquals(2, dataset.size()); + assertEquals(4, attributes.size()); + assertEquals("jsoup updated", attributes.get("data-name")); + assertEquals("jsoup updated", dataset.get("name")); + assertEquals("java", attributes.get("data-language")); + assertEquals("java", dataset.get("language")); + + attributes.put("data-food", "bacon"); + assertEquals(3, dataset.size()); + assertEquals("bacon", dataset.get("food")); + + attributes.put("data-", "empty"); + assertEquals(null, dataset.get("")); // data- is not a data attribute + + Element p = doc.select("p").first(); + assertEquals(0, p.dataset().size()); + + } + + @Test public void parentlessToString() { + Document doc = Jsoup.parse(""); + Element img = doc.select("img").first(); + assertEquals("", img.toString()); + + img.remove(); // lost its parent + assertEquals("", img.toString()); + } + + @Test public void testClone() { + Document doc = Jsoup.parse("

    One

    Two

    "); + + Element p = doc.select("p").get(1); + Element clone = p.clone(); + + assertNull(clone.parent()); // should be orphaned + assertEquals(0, clone.siblingIndex); + assertEquals(1, p.siblingIndex); + assertNotNull(p.parent()); + + clone.append("Three"); + assertEquals("

    TwoThree

    ", TextUtil.stripNewlines(clone.outerHtml())); + assertEquals("

    One

    Two

    ", TextUtil.stripNewlines(doc.body().html())); // not modified + + doc.body().appendChild(clone); // adopt + assertNotNull(clone.parent()); + assertEquals("

    One

    Two

    TwoThree

    ", TextUtil.stripNewlines(doc.body().html())); + } + + @Test public void testClonesClassnames() { + Document doc = Jsoup.parse("
    "); + Element div = doc.select("div").first(); + Set classes = div.classNames(); + assertEquals(2, classes.size()); + assertTrue(classes.contains("one")); + assertTrue(classes.contains("two")); + + Element copy = div.clone(); + Set copyClasses = copy.classNames(); + assertEquals(2, copyClasses.size()); + assertTrue(copyClasses.contains("one")); + assertTrue(copyClasses.contains("two")); + copyClasses.add("three"); + copyClasses.remove("one"); + + assertTrue(classes.contains("one")); + assertFalse(classes.contains("three")); + assertFalse(copyClasses.contains("one")); + assertTrue(copyClasses.contains("three")); + + assertEquals("", div.html()); + assertEquals("", copy.html()); + } + + @Test public void testTagNameSet() { + Document doc = Jsoup.parse("
    Hello"); + doc.select("i").first().tagName("em"); + assertEquals(0, doc.select("i").size()); + assertEquals(1, doc.select("em").size()); + assertEquals("Hello", doc.select("div").first().html()); + } + + @Test public void testHtmlContainsOuter() { + Document doc = Jsoup.parse("Check
    Hello there
    "); + doc.outputSettings().indentAmount(0); + assertTrue(doc.html().contains(doc.select("title").outerHtml())); + assertTrue(doc.html().contains(doc.select("div").outerHtml())); + } + + @Test public void testGetTextNodes() { + Document doc = Jsoup.parse("

    One Two Three
    Four

    "); + List textNodes = doc.select("p").first().textNodes(); + + assertEquals(3, textNodes.size()); + assertEquals("One ", textNodes.get(0).text()); + assertEquals(" Three ", textNodes.get(1).text()); + assertEquals(" Four", textNodes.get(2).text()); + + assertEquals(0, doc.select("br").first().textNodes().size()); + } + + @Test public void testManipulateTextNodes() { + Document doc = Jsoup.parse("

    One Two Three
    Four

    "); + Element p = doc.select("p").first(); + List textNodes = p.textNodes(); + + textNodes.get(1).text(" three-more "); + textNodes.get(2).splitText(3).text("-ur"); + + assertEquals("One Two three-more Fo-ur", p.text()); + assertEquals("One three-more Fo-ur", p.ownText()); + assertEquals(4, p.textNodes().size()); // grew because of split + } + + @Test public void testGetDataNodes() { + Document doc = Jsoup.parse("

    Fix Six

    "); + Element script = doc.select("script").first(); + Element style = doc.select("style").first(); + Element p = doc.select("p").first(); + + List scriptData = script.dataNodes(); + assertEquals(1, scriptData.size()); + assertEquals("One Two", scriptData.get(0).getWholeData()); + + List styleData = style.dataNodes(); + assertEquals(1, styleData.size()); + assertEquals("Three Four", styleData.get(0).getWholeData()); + + List pData = p.dataNodes(); + assertEquals(0, pData.size()); + } + + @Test public void elementIsNotASiblingOfItself() { + Document doc = Jsoup.parse("

    One

    Two

    Three

    "); + Element p2 = doc.select("p").get(1); + + assertEquals("Two", p2.text()); + Elements els = p2.siblingElements(); + assertEquals(2, els.size()); + assertEquals("

    One

    ", els.get(0).outerHtml()); + assertEquals("

    Three

    ", els.get(1).outerHtml()); + } + + @Test public void testChildThrowsIndexOutOfBoundsOnMissing() { + Document doc = Jsoup.parse("

    One

    Two

    "); + Element div = doc.select("div").first(); + + assertEquals(2, div.children().size()); + assertEquals("One", div.child(0).text()); + + try { + div.child(3); + fail("Should throw index out of bounds"); + } catch (IndexOutOfBoundsException e) {} + } + + @Test + public void moveByAppend() { + // test for https://github.com/jhy/jsoup/issues/239 + // can empty an element and append its children to another element + Document doc = Jsoup.parse("
    Text

    One

    Text

    Two

    "); + Element div1 = doc.select("div").get(0); + Element div2 = doc.select("div").get(1); + + assertEquals(4, div1.childNodeSize()); + List children = div1.childNodes(); + assertEquals(4, children.size()); + + div2.insertChildren(0, children); + + assertEquals(0, children.size()); // children is backed by div1.childNodes, moved, so should be 0 now + assertEquals(0, div1.childNodeSize()); + assertEquals(4, div2.childNodeSize()); + assertEquals("
    \n
    \n Text \n

    One

    Text \n

    Two

    \n
    ", + doc.body().html()); + } + + @Test + public void insertChildrenArgumentValidation() { + Document doc = Jsoup.parse("
    Text

    One

    Text

    Two

    "); + Element div1 = doc.select("div").get(0); + Element div2 = doc.select("div").get(1); + List children = div1.childNodes(); + + try { + div2.insertChildren(6, children); + fail(); + } catch (IllegalArgumentException e) {} + + try { + div2.insertChildren(-5, children); + fail(); + } catch (IllegalArgumentException e) { + } + + try { + div2.insertChildren(0, (Collection) null); + fail(); + } catch (IllegalArgumentException e) { + } + } + + @Test + public void insertChildrenAtPosition() { + Document doc = Jsoup.parse("
    Text1

    One

    Text2

    Two

    Text3

    Three

    "); + Element div1 = doc.select("div").get(0); + Elements p1s = div1.select("p"); + Element div2 = doc.select("div").get(1); + + assertEquals(2, div2.childNodeSize()); + div2.insertChildren(-1, p1s); + assertEquals(2, div1.childNodeSize()); // moved two out + assertEquals(4, div2.childNodeSize()); + assertEquals(3, p1s.get(1).siblingIndex()); // should be last + + List els = new ArrayList(); + Element el1 = new Element(Tag.valueOf("span"), "").text("Span1"); + Element el2 = new Element(Tag.valueOf("span"), "").text("Span2"); + TextNode tn1 = new TextNode("Text4", ""); + els.add(el1); + els.add(el2); + els.add(tn1); + + assertNull(el1.parent()); + div2.insertChildren(-2, els); + assertEquals(div2, el1.parent()); + assertEquals(7, div2.childNodeSize()); + assertEquals(3, el1.siblingIndex()); + assertEquals(4, el2.siblingIndex()); + assertEquals(5, tn1.siblingIndex()); + } + + @Test + public void insertChildrenAsCopy() { + Document doc = Jsoup.parse("
    Text

    One

    Text

    Two

    "); + Element div1 = doc.select("div").get(0); + Element div2 = doc.select("div").get(1); + Elements ps = doc.select("p").clone(); + ps.first().text("One cloned"); + div2.insertChildren(-1, ps); + + assertEquals(4, div1.childNodeSize()); // not moved -- cloned + assertEquals(2, div2.childNodeSize()); + assertEquals("
    Text

    One

    Text

    Two

    One cloned

    Two

    ", + TextUtil.stripNewlines(doc.body().html())); + } + + @Test + public void testCssPath() { + Document doc = Jsoup.parse("
    A
    B
    C
    "); + Element divA = doc.select("div").get(0); + Element divB = doc.select("div").get(1); + Element divC = doc.select("div").get(2); + assertEquals(divA.cssSelector(), "#id1"); + assertEquals(divB.cssSelector(), "html > body > div:nth-child(2)"); + assertEquals(divC.cssSelector(), "html > body > div.c1.c2"); + + assertTrue(divA == doc.select(divA.cssSelector()).first()); + assertTrue(divB == doc.select(divB.cssSelector()).first()); + assertTrue(divC == doc.select(divC.cssSelector()).first()); + } + + + @Test + public void testClassNames() { + Document doc = Jsoup.parse("
    C
    "); + Element div = doc.select("div").get(0); + + assertEquals("c1 c2", div.className()); + + final Set set1 = div.classNames(); + final Object[] arr1 = set1.toArray(); + assertTrue(arr1.length==2); + assertEquals("c1", arr1[0]); + assertEquals("c2", arr1[1]); + + // Changes to the set should not be reflected in the Elements getters + set1.add("c3"); + assertTrue(2==div.classNames().size()); + assertEquals("c1 c2", div.className()); + + // Update the class names to a fresh set + final Set newSet = new LinkedHashSet(3); + newSet.addAll(set1); + newSet.add("c3"); + + div.classNames(newSet); + + + assertEquals("c1 c2 c3", div.className()); + + final Set set2 = div.classNames(); + final Object[] arr2 = set2.toArray(); + assertTrue(arr2.length==3); + assertEquals("c1", arr2[0]); + assertEquals("c2", arr2[1]); + assertEquals("c3", arr2[2]); + } + + @Test + public void testHashAndEqualsAndValue() { + // .equals and hashcode are identity. value is content. + + String doc1 = "

    One

    One

    Two

    One

    " + + "

    One

    One

    Two

    One

    "; + + Document doc = Jsoup.parse(doc1); + Elements els = doc.select("p"); + + /* + for (Element el : els) { + System.out.println(el.hashCode() + " - " + el.outerHtml()); + } + + 0 1534787905 -

    One

    + 1 1534787905 -

    One

    + 2 1539683239 -

    Two

    + 3 1535455211 -

    One

    + 4 1534787905 -

    One

    + 5 1534787905 -

    One

    + 6 1539683239 -

    Two

    + 7 1535455211 -

    One

    + */ + assertEquals(8, els.size()); + Element e0 = els.get(0); + Element e1 = els.get(1); + Element e2 = els.get(2); + Element e3 = els.get(3); + Element e4 = els.get(4); + Element e5 = els.get(5); + Element e6 = els.get(6); + Element e7 = els.get(7); + + assertEquals(e0, e0); + assertTrue(e0.hasSameValue(e1)); + assertTrue(e0.hasSameValue(e4)); + assertTrue(e0.hasSameValue(e5)); + assertFalse(e0.equals(e2)); + assertFalse(e0.hasSameValue(e2)); + assertFalse(e0.hasSameValue(e3)); + assertFalse(e0.hasSameValue(e6)); + assertFalse(e0.hasSameValue(e7)); + + assertEquals(e0.hashCode(), e0.hashCode()); + assertFalse(e0.hashCode() == (e2.hashCode())); + assertFalse(e0.hashCode() == (e3).hashCode()); + assertFalse(e0.hashCode() == (e6).hashCode()); + assertFalse(e0.hashCode() == (e7).hashCode()); + } + + @Test public void testRelativeUrls() { + String html = "One two Three Four Five"; + Document doc = Jsoup.parse(html, "http://example.com/bar/"); + Elements els = doc.select("a"); + + assertEquals("http://example.com/bar/one.html", els.get(0).absUrl("href")); + assertEquals("http://example.com/bar/two.html", els.get(1).absUrl("href")); + assertEquals("http://example.com/three.html", els.get(2).absUrl("href")); + assertEquals("http://example2.com/four/", els.get(3).absUrl("href")); + assertEquals("https://example2.com/five/", els.get(4).absUrl("href")); + } + + @Test + public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { + Document doc = new Document(""); + Element body = doc.appendElement("body"); + body.appendElement("div1"); + body.appendElement("div2"); + final Element div3 = body.appendElement("div3"); + div3.text("Check"); + final Element div4 = body.appendElement("div4"); + + ArrayList toMove = new ArrayList(); + toMove.add(div3); + toMove.add(div4); + + body.insertChildren(0, toMove); + + String result = doc.toString().replaceAll("\\s+", ""); + assertEquals("Check", result); + } + + @Test + public void testHashcodeIsStableWithContentChanges() { + Element root = new Element(Tag.valueOf("root"), ""); + + HashSet set = new HashSet(); + // Add root node: + set.add(root); + + root.appendChild(new Element(Tag.valueOf("a"), "")); + assertTrue(set.contains(root)); + } + + @Test + public void testNamespacedElements() { + // Namespaces with ns:tag in HTML must be translated to ns|tag in CSS. + String html = ""; + Document doc = Jsoup.parse(html, "http://example.com/bar/"); + Elements els = doc.select("fb|comments"); + assertEquals(1, els.size()); + assertEquals("html > body > fb|comments", els.get(0).cssSelector()); + } + + @Test + public void testChainedRemoveAttributes() { + String html = "Text"; + Document doc = Jsoup.parse(html); + Element a = doc.select("a").first(); + a + .removeAttr("zero") + .removeAttr("one") + .removeAttr("two") + .removeAttr("three") + .removeAttr("four") + .removeAttr("five"); + assertEquals("Text", a.outerHtml()); + } + + @Test + public void testLoopedRemoveAttributes() { + String html = "Text

    Two

    "; + Document doc = Jsoup.parse(html); + for (Element el : doc.getAllElements()) { + el.clearAttributes(); + } + + assertEquals("Text\n

    Two

    ", doc.body().html()); + } + + @Test + public void testIs() { + String html = "

    One Two Three

    Another

    "; + Document doc = Jsoup.parse(html); + Element p = doc.select("p").first(); + + assertTrue(p.is("p")); + assertFalse(p.is("div")); + assertTrue(p.is("p:has(a)")); + assertTrue(p.is("p:first-child")); + assertFalse(p.is("p:last-child")); + assertTrue(p.is("*")); + assertTrue(p.is("div p")); + + Element q = doc.select("p").last(); + assertTrue(q.is("p")); + assertTrue(q.is("p ~ p")); + assertTrue(q.is("p + p")); + assertTrue(q.is("p:last-child")); + assertFalse(q.is("p a")); + assertFalse(q.is("a")); + } + + + @Test public void elementByTagName() { + Element a = new Element("P"); + assertTrue(a.tagName().equals("P")); + } + + @Test public void testChildrenElements() { + String html = "

    One

    Two

    Three
    Four"; + Document doc = Jsoup.parse(html); + Element div = doc.select("div").first(); + Element p = doc.select("p").first(); + Element span = doc.select("span").first(); + Element foo = doc.select("foo").first(); + Element img = doc.select("img").first(); + + Elements docChildren = div.children(); + assertEquals(2, docChildren.size()); + assertEquals("

    One

    ", docChildren.get(0).outerHtml()); + assertEquals("

    Two

    ", docChildren.get(1).outerHtml()); + assertEquals(3, div.childNodes().size()); + assertEquals("Three", div.childNodes().get(2).outerHtml()); + + assertEquals(1, p.children().size()); + assertEquals("One", p.children().text()); + + assertEquals(0, span.children().size()); + assertEquals(1, span.childNodes().size()); + assertEquals("Four", span.childNodes().get(0).outerHtml()); + + assertEquals(0, foo.children().size()); + assertEquals(0, foo.childNodes().size()); + assertEquals(0, img.children().size()); + assertEquals(0, img.childNodes().size()); + } + + @Test public void testShadowElementsAreUpdated() { + String html = "

    One

    Two

    Three
    Four"; + Document doc = Jsoup.parse(html); + Element div = doc.select("div").first(); + Elements els = div.children(); + List nodes = div.childNodes(); + + assertEquals(2, els.size()); // the two Ps + assertEquals(3, nodes.size()); // the "Three" textnode + + Element p3 = new Element("p").text("P3"); + Element p4 = new Element("p").text("P4"); + div.insertChildren(1, p3); + div.insertChildren(3, p4); + Elements els2 = div.children(); + + // first els should not have changed + assertEquals(2, els.size()); + assertEquals(4, els2.size()); + + assertEquals("

    One

    \n" + + "

    P3

    \n" + + "

    Two

    \n" + + "

    P4

    Three", div.html()); + assertEquals("P3", els2.get(1).text()); + assertEquals("P4", els2.get(3).text()); + + p3.after("AnotherOne

    \n" + + "

    P3

    \n" + + "Another\n" + + "

    Two

    \n" + + "

    P4

    Three", div.html()); + } + + @Test public void classNamesAndAttributeNameIsCaseInsensitive() { + String html = "

    One

    "; + Document doc = Jsoup.parse(html); + Element p = doc.select("p").first(); + assertEquals("SomeText AnotherText", p.className()); + assertTrue(p.classNames().contains("SomeText")); + assertTrue(p.classNames().contains("AnotherText")); + assertTrue(p.hasClass("SomeText")); + assertTrue(p.hasClass("sometext")); + assertTrue(p.hasClass("AnotherText")); + assertTrue(p.hasClass("anothertext")); + + Element p1 = doc.select(".SomeText").first(); + Element p2 = doc.select(".sometext").first(); + Element p3 = doc.select("[class=SomeText AnotherText]").first(); + Element p4 = doc.select("[Class=SomeText AnotherText]").first(); + Element p5 = doc.select("[class=sometext anothertext]").first(); + Element p6 = doc.select("[class=SomeText AnotherText]").first(); + Element p7 = doc.select("[class^=sometext]").first(); + Element p8 = doc.select("[class$=nothertext]").first(); + Element p9 = doc.select("[class^=sometext]").first(); + Element p10 = doc.select("[class$=AnotherText]").first(); + + assertEquals("One", p1.text()); + assertEquals(p1, p2); + assertEquals(p1, p3); + assertEquals(p1, p4); + assertEquals(p1, p5); + assertEquals(p1, p6); + assertEquals(p1, p7); + assertEquals(p1, p8); + assertEquals(p1, p9); + assertEquals(p1, p10); + } + + @Test + public void testAppendTo() { + String parentHtml = "
    "; + String childHtml = "
    "; + + Element parentElement = Jsoup.parse(parentHtml).getElementsByClass("a").first(); + Element childElement = Jsoup.parse(childHtml).getElementsByClass("b").first(); + + childElement.attr("class", "test-class").appendTo(parentElement).attr("id", "testId"); + assertEquals("test-class", childElement.attr("class")); + assertEquals("testId", childElement.attr("id")); + assertThat(parentElement.attr("id"), not(equalTo("testId"))); + assertThat(parentElement.attr("class"), not(equalTo("test-class"))); + assertSame(childElement, parentElement.children().first()); + assertSame(parentElement, childElement.parent()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `childElement` last assigned on line 1142 could be null and is dereferenced at line 1144. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ElementTest.testAppendTo() + +### Procedure Id: +org.jsoup.nodes.ElementTest.testAppendTo():void.54fe29a1e66646fc0c72518523abcb0d + +### File: +src/test/java/org/jsoup/nodes/ElementTest.java + +### Key: +ElementTest.java|testAppendTo|NULL_DEREFERENCE + +### Node Key: +3677875e6aead27ee1320f16c80d8b0f + +### Hash: +844940693bf1e609f7add745c7248783 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7781/instruction.md b/inferredbugs-7781/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4b14f402b6f3ece40b4b212abe34c41d51b31d33 --- /dev/null +++ b/inferredbugs-7781/instruction.md @@ -0,0 +1,246 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** mongojack +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2011 VZ Netzwerke Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.vz.mongodb.jackson; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.junit.Test; + +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.hamcrest.core.IsNull.nullValue; +import static org.junit.Assert.assertThat; + +public class TestIdAnnotatedClass extends MongoDBTestBase { + + private JacksonDBCollection createCollFor(T object, Class keyType) throws Exception { + // Stupid generics... + return (JacksonDBCollection) getCollection(object.getClass(), keyType); + } + + @Test + public void testIdFieldAnnotated() throws Exception { + IdFieldAnnotated o = new IdFieldAnnotated(); + o.id = "blah"; + JacksonDBCollection coll = createCollFor(o, String.class); + WriteResult writeResult = coll.insert(o); + assertThat(writeResult.getSavedId(), equalTo("blah")); + assertThat(writeResult.getDbObject().get("id"), nullValue()); + IdFieldAnnotated result = coll.findOneById("blah"); + assertThat(result, notNullValue()); + assertThat(result.id, equalTo("blah")); + } + + public static class IdFieldAnnotated { + @Id + public String id; + } + + @Test + public void testJpaIdFieldAnnotated() throws Exception { + JpaIdFieldAnnotated o = new JpaIdFieldAnnotated(); + o.id = "blah"; + JacksonDBCollection coll = createCollFor(o, String.class); + WriteResult writeResult = coll.insert(o); + assertThat(writeResult.getSavedId(), equalTo("blah")); + assertThat(writeResult.getDbObject().get("id"), nullValue()); + JpaIdFieldAnnotated result = coll.findOneById("blah"); + assertThat(result, notNullValue()); + assertThat(result.id, equalTo("blah")); + } + + public static class JpaIdFieldAnnotated { + @javax.persistence.Id + public String id; + } + + @Test + public void testGetterSetterAnnotated() throws Exception { + GetterSetterAnnotated o = new GetterSetterAnnotated(); + o.setId("blah"); + JacksonDBCollection coll = createCollFor(o, String.class); + WriteResult writeResult = coll.insert(o); + assertThat(writeResult.getSavedId(), equalTo("blah")); + assertThat(writeResult.getDbObject().get("id"), nullValue()); + GetterSetterAnnotated result = coll.findOneById("blah"); + assertThat(result, notNullValue()); + assertThat(result.getId(), equalTo("blah")); + } + + public static class GetterSetterAnnotated { + private String id; + + @Id + public String getId() { + return id; + } + + @Id + public void setId(String id) { + this.id = id; + } + } + + @Test + public void testCreatorGetterAnnotated() throws Exception { + CreatorGetterAnnotated o = new CreatorGetterAnnotated("blah"); + JacksonDBCollection coll = createCollFor(o, String.class); + WriteResult writeResult = coll.insert(o); + assertThat(writeResult.getSavedId(), equalTo("blah")); + assertThat(writeResult.getDbObject().get("id"), nullValue()); + CreatorGetterAnnotated result = coll.findOneById("blah"); + assertThat(result, notNullValue()); + assertThat(result.getId(), equalTo("blah")); + } + + public static class CreatorGetterAnnotated { + private final String id; + + @JsonCreator + public CreatorGetterAnnotated(@Id String id) { + this.id = id; + } + + @Id + public String getId() { + return id; + } + } + + @Test + public void testObjectIdFieldAnnotated() throws Exception { + ObjectIdFieldAnnotated o = new ObjectIdFieldAnnotated(); + JacksonDBCollection coll = createCollFor(o, String.class); + WriteResult writeResult = coll.insert(o); + assertThat(writeResult.getDbObject().get("_id"), instanceOf(org.bson.types.ObjectId.class)); + assertThat(writeResult.getSavedId(), instanceOf(String.class)); + assertThat(writeResult.getDbObject().get("id"), nullValue()); + ObjectIdFieldAnnotated result = coll.findOneById(writeResult.getSavedId()); + assertThat(result, notNullValue()); + assertThat(result.id, equalTo(writeResult.getSavedId())); + } + + public static class ObjectIdFieldAnnotated { + @Id + @ObjectId + public String id; + } + + @Test + public void testCreatorGetterObjectIdAnnotated() throws Exception { + CreatorGetterObjectIdAnnotated o = new CreatorGetterObjectIdAnnotated(null); + JacksonDBCollection coll = createCollFor(o, String.class); + WriteResult writeResult = coll.insert(o); + assertThat(writeResult.getSavedId(), notNullValue()); + assertThat(writeResult.getSavedId(), instanceOf(String.class)); + assertThat(writeResult.getDbObject().get("id"), nullValue()); + assertThat(writeResult.getSavedId(), equalTo(writeResult.getDbObject().get("_id").toString())); + CreatorGetterObjectIdAnnotated result = coll.findOneById(writeResult.getSavedId()); + assertThat(result, notNullValue()); + assertThat(result.getId(), equalTo(writeResult.getSavedId())); + } + + public static class CreatorGetterObjectIdAnnotated { + private final String id; + + @JsonCreator + public CreatorGetterObjectIdAnnotated(@Id @ObjectId String id) { + this.id = id; + } + + @Id + @ObjectId + public String getId() { + return id; + } + } + + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `result` last assigned on line 60 could be null and is dereferenced at line 62. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestIdAnnotatedClass.testJpaIdFieldAnnotated() + +### Procedure Id: +net.vz.mongodb.jackson.TestIdAnnotatedClass.testJpaIdFieldAnnotated():void.1f906fd87ed30cd9b42f89f043c6bd89 + +### File: +src/test/java/net/vz/mongodb/jackson/TestIdAnnotatedClass.java + +### Key: +TestIdAnnotatedClass.java|testJpaIdFieldAnnotated|NULL_DEREFERENCE + +### Node Key: +c3e9b7adf0862874433e40544c2a4023 + +### Hash: +d023e6656ee381677920d97b030d02d6 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7786/instruction.md b/inferredbugs-7786/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5a37a2d707a1f88683e744a48e2ed3913e5a8d91 --- /dev/null +++ b/inferredbugs-7786/instruction.md @@ -0,0 +1,1737 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** mongojack +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2011 VZ Netzwerke Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.vz.mongodb.jackson; + +import com.mongodb.*; +import net.vz.mongodb.jackson.internal.FetchableDBRef; +import net.vz.mongodb.jackson.internal.util.IdHandler; +import net.vz.mongodb.jackson.internal.util.IdHandlerFactory; +import net.vz.mongodb.jackson.internal.JacksonCollectionKey; +import net.vz.mongodb.jackson.internal.MongoAnnotationIntrospector; +import net.vz.mongodb.jackson.internal.MongoJacksonHandlerInstantiator; +import net.vz.mongodb.jackson.internal.MongoJacksonMapperModule; +import net.vz.mongodb.jackson.internal.object.BsonObjectGenerator; +import net.vz.mongodb.jackson.internal.object.BsonObjectTraversingParser; +import net.vz.mongodb.jackson.internal.stream.JacksonDBObject; +import net.vz.mongodb.jackson.internal.stream.JacksonDecoderFactory; +import net.vz.mongodb.jackson.internal.util.SerializationUtils; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.type.JavaType; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * A DBCollection that marshals/demarshals objects to/from Jackson annotated classes. It provides a very thin wrapper + * over an existing DBCollection. + * + * @author James Roper + * @since 1.0 + */ +public class JacksonDBCollection { + + public enum Feature { + /** + * Deserialise objects directly from the MongoDB stream. This is the default, as it performs the best. If set + * to false, then it uses the MongoDB driver to deserialise objects to DBObjects, and then traverses those + * objects to do the Jackson parsing. This may be desirable, for example, when auto hydrating of objects is + * enabled, because in order to hydrate objects, a second connection needs to be made to MongoDB, which has the + * potential to deadlock when the connection pool gets exhausted when using stream deserialization. Using + * object deserialization, the hydration occurs after the connection to load the object has been returned to + * the pool. + */ + USE_STREAM_DESERIALIZATION(true), + + /** + * Automatically hydrate all DB references. This is not advised, either declare the objects to be of type + * {@link net.vz.mongodb.jackson.DBRef}, and hydrate by calling fetch(), or declare it as the referenced type + * and use {@link net.vz.mongodb.jackson.JacksonDBCollection.hydrate()} to hydrate the referenced types. + *

    + * If using this feature, it is strongly recommended that you set {@link Feature.USE_STREAM_DESERIALIZATION} to + * false, to avoid potential deadlocks. + */ + AUTO_HYDRATE(false); + + Feature(boolean enabledByDefault) { + this.enabledByDefault = enabledByDefault; + } + + private final boolean enabledByDefault; + + public boolean isEnabledByDefault() { + return enabledByDefault; + } + } + + private static final ObjectMapper DEFAULT_OBJECT_MAPPER = new ObjectMapper(); + + static { + // Configure to use the object id annotation introspector + DEFAULT_OBJECT_MAPPER.registerModule(MongoJacksonMapperModule.INSTANCE); + DEFAULT_OBJECT_MAPPER.setHandlerInstantiator(new MongoJacksonHandlerInstantiator( + new MongoAnnotationIntrospector(DEFAULT_OBJECT_MAPPER.getDeserializationConfig()))); + } + + private final DBCollection dbCollection; + private final JavaType type; + private final JavaType keyType; + private final ObjectMapper objectMapper; + private final IdHandler idHandler; + private final JacksonDecoderFactory decoderFactory; + private final Map features; + + /** + * Cache of referenced collections + */ + private final Map referencedCollectionCache = new ConcurrentHashMap(); + + protected JacksonDBCollection(DBCollection dbCollection, JavaType type, JavaType keyType, ObjectMapper objectMapper, + Map features) { + this.dbCollection = dbCollection; + this.type = type; + this.keyType = keyType; + this.objectMapper = objectMapper; + this.decoderFactory = new JacksonDecoderFactory(this, objectMapper, type); + // We want to find how we should serialize the ID, in case it is passed to us + try { + this.idHandler = (IdHandler) IdHandlerFactory.getIdHandlerForProperty(objectMapper, type.getRawClass(), keyType.getRawClass()); + } catch (JsonMappingException e) { + throw new MongoJsonMappingException("Unable to introspect class", e); + } + if (features == null) { + this.features = new ConcurrentHashMap(); + } else { + this.features = features; + } + } + + /** + * Wraps a DB collection in a JacksonDBCollection + * + * @param dbCollection The DB collection to wrap + * @param type The type of objects to deserialise to + * @return The wrapped collection + */ + public static JacksonDBCollection wrap(DBCollection dbCollection, Class type) { + return new JacksonDBCollection(dbCollection, DEFAULT_OBJECT_MAPPER.constructType(type), + DEFAULT_OBJECT_MAPPER.constructType(Object.class), DEFAULT_OBJECT_MAPPER, null); + } + + /** + * Wraps a DB collection in a JacksonDBCollection + * + * @param dbCollection The DB collection to wrap + * @param type The type of objects to deserialise to + * @param keyType The type of the objects key + * @return The wrapped collection + */ + public static JacksonDBCollection wrap(DBCollection dbCollection, Class type, Class keyType) { + return new JacksonDBCollection(dbCollection, DEFAULT_OBJECT_MAPPER.constructType(type), + DEFAULT_OBJECT_MAPPER.constructType(keyType), DEFAULT_OBJECT_MAPPER, null); + } + + /** + * Wraps a DB collection in a JacksonDBCollection + * + * @param dbCollection The DB collection to wrap + * @param type The type of objects to deserialise to + * @param keyType The type of the objects key + * @param view The JSON view to use for serialisation + * @return The wrapped collection + */ + public static JacksonDBCollection wrap(DBCollection dbCollection, Class type, Class keyType, Class view) { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.withModule(MongoJacksonMapperModule.INSTANCE); + objectMapper.setSerializationConfig(objectMapper.getSerializationConfig().withView(view)); + objectMapper.setHandlerInstantiator(new MongoJacksonHandlerInstantiator( + (MongoAnnotationIntrospector) objectMapper.getDeserializationConfig().getAnnotationIntrospector())); + return new JacksonDBCollection(dbCollection, DEFAULT_OBJECT_MAPPER.constructType(type), + DEFAULT_OBJECT_MAPPER.constructType(keyType), objectMapper, null); + } + + /** + * Wraps a DB collection in a JacksonDBCollection, using the given object mapper + * + * @param dbCollection The DB collection to wrap + * @param type The type of objects to deserialise to + * @param objectMapper The ObjectMapper + * @return The wrapped collection + */ + public static JacksonDBCollection wrap(DBCollection dbCollection, Class type, Class keyType, ObjectMapper objectMapper) { + return new JacksonDBCollection(dbCollection, objectMapper.constructType(type), + objectMapper.constructType(keyType), objectMapper, null); + } + + /** + * Enable the given feature + * + * @param feature The feature to enable + * @return this object + */ + public JacksonDBCollection enable(Feature feature) { + features.put(feature, true); + return this; + } + + /** + * Disable the given feature + * + * @param feature The feature to disable + * @return this object + */ + public JacksonDBCollection disable(Feature feature) { + features.put(feature, false); + return this; + } + + /** + * Whether the given feature is enabled + * + * @param feature The feature to check + * @return whether it is enabled + */ + public boolean isEnabled(Feature feature) { + Boolean enabled = features.get(feature); + if (enabled == null) { + return feature.isEnabledByDefault(); + } else { + return enabled; + } + } + + + /** + * Get the underlying db collection + * + * @return The underlying db collection + */ + public DBCollection getDbCollection() { + return dbCollection; + } + + /** + * Inserts an object into the database. + * if the objects _id is null, one will be generated + * you can get the _id that was generated by calling getSavedObject() or getSavedId() on the result + * + * @param object The object to insert + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult insert(T object) throws MongoException { + DBObject dbObject = convertToDbObject(object); + return new WriteResult(this, dbCollection.insert(dbObject), dbObject); + } + + /** + * Inserts an object into the database. + * if the objects _id is null, one will be generated + * you can get the _id that was generated by calling getSavedObject() or getSavedId() on the result + * + * @param object The object to insert + * @param concern the write concern + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult insert(T object, WriteConcern concern) throws MongoException { + DBObject dbObject = convertToDbObject(object); + return new WriteResult(this, dbCollection.insert(dbObject, concern), dbObject); + } + + /** + * Inserts objects into the database. + * if the objects _id is null, one will be generated + * you can get the _id that were generated by calling getSavedObjects() or getSavedIds() on the result + * + * @param objects The objects to insert + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult insert(T... objects) throws MongoException { + DBObject[] dbObjects = convertToDbObjects(objects); + return new WriteResult(this, dbCollection.insert(dbObjects), dbObjects); + } + + + /** + * Inserts objects into the database. + * if the objects _id is null, one will be generated + * you can get the _id that were generated by calling getSavedObjects() or getSavedIds() on the result + * + * @param objects The objects to insert + * @param concern the write concern + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult insert(WriteConcern concern, T... objects) throws MongoException { + DBObject[] dbObjects = convertToDbObjects(objects); + return new WriteResult(this, dbCollection.insert(concern, dbObjects), dbObjects); + } + + /** + * Inserts objects into the database. + * if the objects _id is null, one will be generated + * you can get the _id that were generated by calling getSavedObjects() or getSavedIds() on the result + * + * @param list The objects to insert + * @return The result + * @throws MongoException If an error occurred + */ + @SuppressWarnings({"unchecked"}) + public WriteResult insert(List list) throws MongoException { + return insert(list.toArray((T[]) new Object[list.size()])); + } + + /** + * Inserts objects into the database. + * if the objects _id is null, one will be generated + * you can get the _id that were generated by calling getSavedObjects() or getSavedIds() on the result + * + * @param list The objects to insert + * @param concern the write concern + * @return The result + * @throws MongoException If an error occurred + */ + @SuppressWarnings({"unchecked"}) + public WriteResult insert(List list, WriteConcern concern) throws MongoException { + return insert(concern, list.toArray((T[]) new Object[list.size()])); + } + + /** + * Performs an update operation. + * + * @param query search query for old object to update + * @param object object with which to update query + * @param upsert if the database should create the element if it does not exist + * @param multi if the update should be applied to all objects matching (db version 1.1.3 and above). An object will + * not be inserted if it does not exist in the collection and upsert=true and multi=true. + * See http://www.mongodb.org/display/DOCS/Atomic+Operations + * @param concern the write concern + * @return The write result + * @throws MongoException If an error occurred + */ + public WriteResult update(DBObject query, DBObject object, boolean upsert, boolean multi, WriteConcern concern) throws MongoException { + return new WriteResult(this, dbCollection.update(serializeFields(query), object, upsert, multi, concern)); + } + + /** + * Performs an update operation. + * + * @param query search query for old object to update + * @param update update with which to update query + * @param upsert if the database should create the element if it does not exist + * @param multi if the update should be applied to all objects matching (db version 1.1.3 and above). An object will + * not be inserted if it does not exist in the collection and upsert=true and multi=true. + * See http://www.mongodb.org/display/DOCS/Atomic+Operations + * @param concern the write concern + * @return The write result + * @throws MongoException If an error occurred + */ + public WriteResult update(DBObject query, DBUpdate.Builder update, boolean upsert, boolean multi, WriteConcern concern) throws MongoException { + return this.update(query, update.serialiseAndGet(objectMapper), upsert, multi, concern); + } + + /** + * Performs an update operation. + * + * @param query search query for old object to update + * @param object object with which to update query + * @param upsert if the database should create the element if it does not exist + * @param multi if the update should be applied to all objects matching (db version 1.1.3 and above). An object will + * not be inserted if it does not exist in the collection and upsert=true and multi=true. + * See http://www.mongodb.org/display/DOCS/Atomic+Operations + * @param concern the write concern + * @return The write result + * @throws MongoException If an error occurred + */ + public WriteResult update(T query, T object, boolean upsert, boolean multi, WriteConcern concern) throws MongoException { + return update(convertToDbObject(query), convertToDbObject(object), upsert, multi, concern); + } + + /** + * Performs an update operation. + * + * @param query search query for old object to update + * @param object object with which to update q + * @param upsert if the database should create the element if it does not exist + * @param multi if the update should be applied to all objects matching (db version 1.1.3 and above). An object will + * not be inserted if it does not exist in the collection and upsert=true and multi=true. + * See http://www.mongodb.org/display/DOCS/Atomic+Operations + * @param concern the write concern + * @param encoder the DBEncoder to use + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult update(DBObject query, DBObject object, boolean upsert, boolean multi, WriteConcern concern, DBEncoder encoder) throws MongoException { + return new WriteResult(this, dbCollection.update(serializeFields(query), object, upsert, multi, concern, encoder)); + } + + /** + * Performs an update operation. + * + * @param query search query for old object to update + * @param object object with which to update q + * @param upsert if the database should create the element if it does not exist + * @param multi if the update should be applied to all objects matching (db version 1.1.3 and above). An object will + * not be inserted if it does not exist in the collection and upsert=true and multi=true. + * See http://www.mongodb.org/display/DOCS/Atomic+Operations + * @param concern the write concern + * @param encoder the DBEncoder to use + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult update(T query, T object, boolean upsert, boolean multi, WriteConcern concern, DBEncoder encoder) throws MongoException { + return update(convertToDbObject(query), convertToDbObject(object), upsert, multi, concern, encoder); + } + + /** + * calls {@link DBCollection#update(com.mongodb.DBObject, com.mongodb.DBObject, boolean, boolean, com.mongodb.WriteConcern)} with default WriteConcern. + * + * @param query search query for old object to update + * @param object object with which to update q + * @param upsert if the database should create the element if it does not exist + * @param multi if the update should be applied to all objects matching (db version 1.1.3 and above) + * See http://www.mongodb.org/display/DOCS/Atomic+Operations + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult update(DBObject query, DBObject object, boolean upsert, boolean multi) + throws MongoException { + return update(query, object, upsert, multi, getWriteConcern()); + } + + /** + * Performs an update operation. + * + * @param query search query for old object to update + * @param update update with which to update query + * @param upsert if the database should create the element if it does not exist + * @param multi if the update should be applied to all objects matching (db version 1.1.3 and above). An object will + * not be inserted if it does not exist in the collection and upsert=true and multi=true. + * See http://www.mongodb.org/display/DOCS/Atomic+Operations + * @return The write result + * @throws MongoException If an error occurred + */ + public WriteResult update(DBObject query, DBUpdate.Builder update, boolean upsert, boolean multi) throws MongoException { + return this.update(query, update.serialiseAndGet(objectMapper), upsert, multi); + } + + /** + * calls {@link DBCollection#update(com.mongodb.DBObject, com.mongodb.DBObject, boolean, boolean, com.mongodb.WriteConcern)} with default WriteConcern. + * + * @param query search query for old object to update + * @param object object with which to update q + * @param upsert if the database should create the element if it does not exist + * @param multi if the update should be applied to all objects matching (db version 1.1.3 and above) + * See http://www.mongodb.org/display/DOCS/Atomic+Operations + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult update(T query, T object, boolean upsert, boolean multi) + throws MongoException { + return update(query, object, upsert, multi, getWriteConcern()); + } + + /** + * calls {@link DBCollection#update(com.mongodb.DBObject, com.mongodb.DBObject, boolean, boolean)} with upsert=false and multi=false + * + * @param query search query for old object to update + * @param object object with which to update query + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult update(DBObject query, DBObject object) throws MongoException { + return update(query, object, false, false); + } + + /** + * Performs an update operation. + * + * @param query search query for old object to update + * @param update update with which to update query + * @return The write result + * @throws MongoException If an error occurred + */ + public WriteResult update(DBObject query, DBUpdate.Builder update) throws MongoException { + return this.update(query, update.serialiseAndGet(objectMapper)); + } + + + /** + * calls {@link DBCollection#update(com.mongodb.DBObject, com.mongodb.DBObject, boolean, boolean)} with upsert=false and multi=false + * + * @param query search query for old object to update + * @param object object with which to update query + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult update(T query, T object) throws MongoException { + return update(query, object, false, false); + } + + /** + * calls {@link DBCollection#update(com.mongodb.DBObject, com.mongodb.DBObject, boolean, boolean)} with upsert=false and multi=false + * + * @param id the id of the object to update + * @param object object with which to update query + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult updateById(K id, T object) throws MongoException { + return update(createIdQuery(id), convertToDbObject(object), false, false); + } + + /** + * Performs an update operation. + * + * @param id The id of the document to update + * @param update update with which to update query + * @return The write result + * @throws MongoException If an error occurred + */ + public WriteResult updateById(K id, DBUpdate.Builder update) throws MongoException { + return this.update(createIdQuery(id), update.serialiseAndGet(objectMapper)); + } + + /** + * calls {@link DBCollection#update(com.mongodb.DBObject, com.mongodb.DBObject, boolean, boolean)} with upsert=false and multi=true + * + * @param query search query for old object to update + * @param object object with which to update query + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult updateMulti(DBObject query, DBObject object) throws MongoException { + return update(query, object, false, true); + } + + /** + * calls {@link DBCollection#update(com.mongodb.DBObject, com.mongodb.DBObject, boolean, boolean)} with upsert=false and multi=true + * + * @param query search query for old object to update + * @param update update with which to update query + * @return The write result + * @throws MongoException If an error occurred + */ + public WriteResult updateMulti(DBObject query, DBUpdate.Builder update) throws MongoException { + return this.updateMulti(query, update.serialiseAndGet(objectMapper)); + } + + /** + * calls {@link DBCollection#update(com.mongodb.DBObject, com.mongodb.DBObject, boolean, boolean)} with upsert=false and multi=true + * + * @param query search query for old object to update + * @param object object with which to update query + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult updateMulti(T query, T object) throws MongoException { + return update(query, object, false, true); + } + + + /** + * Removes objects from the database collection. + * + * @param query the object that documents to be removed must match + * @param concern WriteConcern for this operation + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult remove(DBObject query, WriteConcern concern) throws MongoException { + return new WriteResult(this, dbCollection.remove(serializeFields(query), concern)); + } + + /** + * Removes objects from the database collection. + * + * @param object the object that documents to be removed must match + * @param concern WriteConcern for this operation + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult remove(T object, WriteConcern concern) throws MongoException { + return new WriteResult(this, dbCollection.remove(convertToDbObject(object), concern)); + } + + /** + * Removes objects from the database collection. + * + * @param query the object that documents to be removed must match + * @param concern WriteConcern for this operation + * @param encoder the DBEncoder to use + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult remove(DBObject query, WriteConcern concern, DBEncoder encoder) throws MongoException { + return new WriteResult(this, dbCollection.remove(serializeFields(query), concern, encoder)); + } + + /** + * calls {@link DBCollection#remove(com.mongodb.DBObject, com.mongodb.WriteConcern)} with the default WriteConcern + * + * @param query the query that documents to be removed must match + * @return The write result + * @throws MongoException If an error occurred + */ + public WriteResult remove(DBObject query) throws MongoException { + return new WriteResult(this, dbCollection.remove(serializeFields(query))); + } + + /** + * calls {@link DBCollection#remove(com.mongodb.DBObject, com.mongodb.WriteConcern)} with the default WriteConcern + * + * @param object the object that documents to be removed must match + * @return The write result + * @throws MongoException If an error occurred + */ + public WriteResult remove(T object) throws MongoException { + return new WriteResult(this, dbCollection.remove(convertToDbObject(object))); + } + + /** + * calls {@link DBCollection#remove(com.mongodb.DBObject, com.mongodb.WriteConcern)} with the default WriteConcern + * + * @param id the id of the document to remove + * @return The write result + * @throws MongoException If an error occurred + */ + public WriteResult removeById(K id) throws MongoException { + return new WriteResult(this, dbCollection.remove(createIdQuery(id))); + } + + /** + * Finds the first document in the query and updates it. + * + * @param query query to match + * @param fields fields to be returned + * @param sort sort to apply before picking first document + * @param remove if true, document found will be removed + * @param update update to apply + * @param returnNew if true, the updated document is returned, otherwise the old document is returned (or it would be lost forever) + * @param upsert do upsert (insert if document not present) + * @return the object + */ + public T findAndModify(DBObject query, DBObject fields, DBObject sort, boolean remove, DBObject update, boolean returnNew, boolean upsert) { + return convertFromDbObject(dbCollection.findAndModify(serializeFields(query), fields, sort, remove, update, returnNew, upsert)); + } + + + /** + * calls {@link DBCollection#findAndModify(com.mongodb.DBObject, com.mongodb.DBObject, com.mongodb.DBObject, boolean, com.mongodb.DBObject, boolean, boolean)} + * with fields=null, remove=false, returnNew=false, upsert=false + * + * @param query The query + * @param sort The sort + * @param update The update to apply + * @return the old object + */ + public T findAndModify(DBObject query, DBObject sort, DBObject update) { + return findAndModify(query, null, sort, false, update, false, false); + } + + /** + * calls {@link DBCollection#findAndModify(com.mongodb.DBObject, com.mongodb.DBObject, com.mongodb.DBObject, boolean, com.mongodb.DBObject, boolean, boolean)} + * with fields=null, sort=null, remove=false, returnNew=false, upsert=false + * + * @param query The query + * @param update The update to apply + * @return the old object + */ + public T findAndModify(DBObject query, DBObject update) { + return findAndModify(query, null, null, false, update, false, false); + } + + /** + * calls {@link DBCollection#findAndModify(com.mongodb.DBObject, com.mongodb.DBObject, com.mongodb.DBObject, boolean, com.mongodb.DBObject, boolean, boolean)} + * with fields=null, sort=null, remove=true, returnNew=false, upsert=false + * + * @param query The query + * @return the removed object + */ + public T findAndRemove(DBObject query) { + return findAndModify(query, null, null, true, null, false, false); + } + + /** + * calls {@link DBCollection#createIndex(com.mongodb.DBObject, com.mongodb.DBObject)} with default index options + * + * @param keys an object with a key set of the fields desired for the index + * @throws MongoException If an error occurred + */ + public final void createIndex(final DBObject keys) throws MongoException { + dbCollection.createIndex(keys); + } + + /** + * Forces creation of an index on a set of fields, if one does not already exist. + * + * @param keys The keys to index + * @param options The options + * @throws MongoException If an error occurred + */ + public void createIndex(DBObject keys, DBObject options) throws MongoException { + dbCollection.createIndex(keys, options); + } + + /** + * Forces creation of an index on a set of fields, if one does not already exist. + * + * @param keys The keys to index + * @param options The index options + * @param encoder the DBEncoder to use + * @throws MongoException If an error occurred + */ + public void createIndex(DBObject keys, DBObject options, DBEncoder encoder) throws MongoException { + dbCollection.createIndex(keys, options, encoder); + } + + /** + * Creates an ascending index on a field with default options, if one does not already exist. + * + * @param name name of field to index on + */ + public final void ensureIndex(final String name) { + ensureIndex(new BasicDBObject(name, 1)); + } + + /** + * calls {@link DBCollection#ensureIndex(com.mongodb.DBObject, com.mongodb.DBObject)} with default options + * + * @param keys an object with a key set of the fields desired for the index + * @throws MongoException If an error occurred + */ + public final void ensureIndex(final DBObject keys) throws MongoException { + dbCollection.ensureIndex(keys); + } + + /** + * calls {@link DBCollection#ensureIndex(com.mongodb.DBObject, java.lang.String, boolean)} with unique=false + * + * @param keys fields to use for index + * @param name an identifier for the index + * @throws MongoException If an error occurred + */ + public void ensureIndex(DBObject keys, String name) throws MongoException { + ensureIndex(keys, name, false); + } + + /** + * Ensures an index on this collection (that is, the index will be created if it does not exist). + * + * @param keys fields to use for index + * @param name an identifier for the index. If null or empty, the default name will be used. + * @param unique if the index should be unique + * @throws MongoException If an error occurred + */ + public void ensureIndex(DBObject keys, String name, boolean unique) throws MongoException { + dbCollection.ensureIndex(keys, name, unique); + } + + /** + * Creates an index on a set of fields, if one does not already exist. + * + * @param keys an object with a key set of the fields desired for the index + * @param optionsIN options for the index (name, unique, etc) + * @throws MongoException If an error occurred + */ + public void ensureIndex(final DBObject keys, final DBObject optionsIN) throws MongoException { + dbCollection.ensureIndex(keys, optionsIN); + } + + /** + * Clears all indices that have not yet been applied to this collection. + */ + public void resetIndexCache() { + dbCollection.resetIndexCache(); + } + + /** + * Set hint fields for this collection (to optimize queries). + * + * @param lst a list of DBObjects to be used as hints + */ + public void setHintFields(List lst) { + dbCollection.setHintFields(lst); + } + + + /** + * Queries for an object in this collection. + * + * @param query object for which to search + * @return an iterator over the results + * @throws MongoException If an error occurred + */ + public DBCursor find(DBObject query) throws MongoException { + return new DBCursor(this, dbCollection.find(serializeFields(query))); + } + + /** + * Queries for an object in this collection. + * + * @param query object for which to search + * @return an iterator over the results + * @throws MongoException If an error occurred + */ + public DBCursor find(T query) throws MongoException { + return new DBCursor(this, dbCollection.find(convertToDbObject(query))); + } + + /** + * Queries for an object in this collection. + *

    + *

    + * An empty DBObject will match every document in the collection. + * Regardless of fields specified, the _id fields are always returned. + *

    + *

    + * An example that returns the "x" and "_id" fields for every document + * in the collection that has an "x" field: + *

    + *
    +     * BasicDBObject keys = new BasicDBObject();
    +     * keys.put("x", 1);
    +     * 

    + * DBCursor cursor = collection.find(new BasicDBObject(), keys); + *

    + * + * @param query object for which to search + * @param keys fields to return + * @return a cursor to iterate over results + */ + public final DBCursor find(DBObject query, DBObject keys) { + return new DBCursor(this, dbCollection.find(serializeFields(query), keys)); + } + + /** + * Queries for an object in this collection. + *

    + *

    + * An empty DBObject will match every document in the collection. + * Regardless of fields specified, the _id fields are always returned. + *

    + * To keys object should have non null values for every key that you want to return + * + * @param query object for which to search + * @param keys fields to return + * @return a cursor to iterate over results + */ + public final DBCursor find(T query, T keys) { + return new DBCursor(this, dbCollection.find(convertToDbObject(query), convertToDbObject(keys))); + } + + + /** + * Queries for all objects in this collection. + * + * @return a cursor which will iterate over every object + * @throws MongoException If an error occurred + */ + public final DBCursor find() throws MongoException { + return new DBCursor(this, dbCollection.find()); + } + + /** + * Returns a single object from this collection. + * + * @return the object found, or null if the collection is empty + * @throws MongoException If an error occurred + */ + public T findOne() throws MongoException { + return findOne(new BasicDBObject()); + } + + /** + * Find an object by the given id + * + * @param id The id + * @return The object + * @throws MongoException If an error occurred + */ + public T findOneById(K id) throws MongoException { + return findOneById(id, (DBObject) null); + } + + /** + * Find an object by the given id + * + * @param id The id + * @return The object + * @throws MongoException If an error occurred + */ + public T findOneById(K id, DBObject fields) throws MongoException { + return findOne(createIdQuery(id), fields); + } + + /** + * Find an object by the given id + * + * @param id The id + * @return The object + * @throws MongoException If an error occurred + */ + public T findOneById(K id, T fields) throws MongoException { + return findOneById(id, convertToDbObject(fields)); + } + + /** + * Returns a single object from this collection matching the query. + * + * @param query the query object + * @return the object found, or null if no such object exists + * @throws MongoException If an error occurred + */ + public T findOne(DBObject query) throws MongoException { + return findOne(query, null); + } + + /** + * Returns a single object from this collection matching the query. + * + * @param query the query object + * @return the object found, or null if no such object exists + * @throws MongoException If an error occurred + */ + public T findOne(T query) throws MongoException { + return findOne(query, null); + } + + /** + * Returns a single object from this collection matching the query. + * + * @param query the query object + * @param fields the fields to return + * @return the object found, or null if no such object exists + */ + public T findOne(DBObject query, DBObject fields) { + return findOne(query, fields, getReadPreference()); + } + + /** + * Returns a single object from this collection matching the query. + * + * @param query the query object + * @param fields an object for which every non null field will be returned + * @return the object found, or null if no such object exists + */ + public T findOne(T query, T fields) { + return findOne(query, fields, getReadPreference()); + } + + /** + * Returns a single object from this collection matching the query. + * + * @param query the query object + * @param fields fields to return + * @param readPref The read preference + * @return the object found, or null if no such object exists + */ + public T findOne(DBObject query, DBObject fields, ReadPreference readPref) { + DBCursor cursor = find(query, fields).setReadPreference(readPref); + if (cursor.hasNext()) { + return cursor.next(); + } else { + return null; + } + } + + /** + * Returns a single object from this collection matching the query. + * + * @param query the query object + * @param fields an object for which every non null field will be returned + * @param readPref The read preferences + * @return the object found, or null if no such object exists + */ + public T findOne(T query, T fields, ReadPreference readPref) { + DBCursor cursor = find(query, fields).setReadPreference(readPref); + if (cursor.hasNext()) { + return cursor.next(); + } else { + return null; + } + } + + /** + * Fetch a collection of dbrefs. This is more efficient than fetching one at a time. + * + * @param collection the collection to fetch + * @param The type of the reference + * @return The collection of referenced objcets + */ + public List fetch(Collection> collection) { + return fetch(collection, null); + } + + /** + * Fetch a collection of dbrefs. This is more efficient than fetching one at a time. + * + * @param collection the collection to fetch + * @param fields The fields to retrieve for each of the documents + * @return The collection of referenced objcets + */ + public List fetch(Collection> collection, DBObject fields) { + Map> collectionsToIds = new HashMap>(); + for (DBRef ref : collection) { + if (ref instanceof FetchableDBRef) { + JacksonCollectionKey key = ((FetchableDBRef) ref).getCollectionKey(); + List ids = collectionsToIds.get(key); + if (ids == null) { + ids = new ArrayList(); + collectionsToIds.put(key, ids); + } + ids.add(getReferenceCollection(key).convertToDbId(ref.getId())); + } + } + List results = new ArrayList(); + for (Map.Entry> entry : collectionsToIds.entrySet()) { + for (R result : this.getReferenceCollection(entry.getKey()).find( + new QueryBuilder().put("_id").in(entry.getValue()).get(), fields)) { + results.add(result); + } + } + return results; + } + + /** + * calls {@link DBCollection#save(com.mongodb.DBObject, com.mongodb.WriteConcern)} with default WriteConcern + * + * @param object the object to save + * will add _id field to jo if needed + * @return The result + */ + public final WriteResult save(T object) { + return save(object, getWriteConcern()); + } + + /** + * Saves an object to this collection (does insert or update based on the object _id). + * + * @param object the DBObject to save + * @param concern the write concern + * @return The result + * @throws MongoException If an error occurred + */ + public WriteResult save(T object, WriteConcern concern) throws MongoException { + DBObject dbObject = convertToDbObject(object); + return new WriteResult(this, dbCollection.save(dbObject, concern), dbObject); + } + + /** + * Drops all indices from this collection + * + * @throws MongoException If an error occurred + */ + public void dropIndexes() throws MongoException { + dropIndexes("*"); + } + + + /** + * Drops an index from this collection + * + * @param name the index name + * @throws MongoException If an error occurred + */ + public void dropIndexes(String name) throws MongoException { + dbCollection.dropIndexes(name); + } + + /** + * Drops (deletes) this collection. Use with care. + * + * @throws MongoException If an error occurred + */ + public void drop() throws MongoException { + dbCollection.drop(); + } + + /** + * returns the number of documents in this collection. + * + * @return The count + * @throws MongoException If an error occurred + */ + public long count() + throws MongoException { + return getCount(new BasicDBObject(), null); + } + + /** + * returns the number of documents that match a query. + * + * @param query query to match + * @return The count + * @throws MongoException If an error occurred + */ + public long count(DBObject query) throws MongoException { + return getCount(query, null); + } + + + /** + * calls {@link DBCollection#getCount(com.mongodb.DBObject, com.mongodb.DBObject)} with an empty query and null fields. + * + * @return number of documents that match query + * @throws MongoException If an error occurred + */ + public long getCount() throws MongoException { + return getCount(new BasicDBObject(), null); + } + + /** + * calls {@link DBCollection#getCount(com.mongodb.DBObject, com.mongodb.DBObject)} with null fields. + * + * @param query query to match + * @return The count + * @throws MongoException If an error occurred + */ + public long getCount(DBObject query) throws MongoException { + return getCount(query, null); + } + + /** + * calls {@link DBCollection#getCount(com.mongodb.DBObject, com.mongodb.DBObject)} with null fields. + * + * @param query query to match + * @return The count + * @throws MongoException If an error occurred + */ + public long getCount(T query) throws MongoException { + return getCount(query, null); + } + + /** + * calls {@link DBCollection#getCount(com.mongodb.DBObject, com.mongodb.DBObject, long, long)} with limit=0 and skip=0 + * + * @param query query to match + * @param fields fields to return + * @return The count + * @throws MongoException If an error occurred + */ + public long getCount(DBObject query, DBObject fields) throws MongoException { + return getCount(query, fields, 0, 0); + } + + /** + * calls {@link DBCollection#getCount(com.mongodb.DBObject, com.mongodb.DBObject, long, long)} with limit=0 and skip=0 + * + * @param query query to match + * @param fields fields to return + * @return The count + * @throws MongoException If an error occurred + */ + public long getCount(T query, T fields) throws MongoException { + return getCount(query, fields, 0, 0); + } + + /** + * Returns the number of documents in the collection + * that match the specified query + * + * @param query query to select documents to count + * @param fields fields to return + * @param limit limit the count to this value + * @param skip number of entries to skip + * @return number of documents that match query and fields + * @throws MongoException If an error occurred + */ + public long getCount(DBObject query, DBObject fields, long limit, long skip) throws MongoException { + return dbCollection.getCount(serializeFields(query), fields, limit, skip); + } + + /** + * Returns the number of documents in the collection + * that match the specified query + * + * @param query query to select documents to count + * @param fields fields to return + * @param limit limit the count to this value + * @param skip number of entries to skip + * @return number of documents that match query and fields + * @throws MongoException If an error occurred + */ + public long getCount(T query, T fields, long limit, long skip) throws MongoException { + return dbCollection.getCount(convertToDbObject(query), convertToDbObject(fields), limit, skip); + } + + /** + * Calls {@link DBCollection#rename(java.lang.String, boolean)} with dropTarget=false + * + * @param newName new collection name (not a full namespace) + * @return the new collection + * @throws MongoException If an error occurred + */ + public JacksonDBCollection rename(String newName) throws MongoException { + return rename(newName, false); + } + + /** + * renames of this collection to newName + * + * @param newName new collection name (not a full namespace) + * @param dropTarget if a collection with the new name exists, whether or not to drop it + * @return the new collection + * @throws MongoException If an error occurred + */ + public JacksonDBCollection rename(String newName, boolean dropTarget) throws MongoException { + return new JacksonDBCollection(dbCollection.rename(newName, dropTarget), type, keyType, objectMapper, features); + } + + /** + * calls {@link DBCollection#group(com.mongodb.DBObject, com.mongodb.DBObject, com.mongodb.DBObject, java.lang.String, java.lang.String)} with finalize=null + * + * @param key - { a : true } + * @param cond - optional condition on query + * @param reduce javascript reduce function + * @param initial initial value for first match on a key + * @return The results + * @throws MongoException If an error occurred + * @see http://www.mongodb.org/display/DOCS/Aggregation + */ + public DBObject group(DBObject key, DBObject cond, DBObject initial, String reduce) throws MongoException { + return group(key, cond, initial, reduce, null); + } + + /** + * Applies a group operation + * + * @param key - { a : true } + * @param cond - optional condition on query + * @param reduce javascript reduce function + * @param initial initial value for first match on a key + * @param finalize An optional function that can operate on the result(s) of the reduce function. + * @return The results + * @throws MongoException If an error occurred + * @see http://www.mongodb.org/display/DOCS/Aggregation + */ + public DBObject group(DBObject key, DBObject cond, DBObject initial, String reduce, String finalize) + throws MongoException { + GroupCommand cmd = new GroupCommand(dbCollection, key, cond, initial, reduce, finalize); + return group(cmd); + } + + /** + * Applies a group operation + * + * @param cmd the group command + * @return The results + * @throws MongoException + * @see http://www.mongodb.org/display/DOCS/Aggregation + */ + public DBObject group(GroupCommand cmd) { + return dbCollection.group(cmd); + } + + /** + * find distinct values for a key + * + * @param key The key + * @return The results + */ + public List distinct(String key) { + return distinct(key, new BasicDBObject()); + } + + /** + * find distinct values for a key + * + * @param key The key + * @param query query to match + * @return The results + */ + public List distinct(String key, DBObject query) { + return dbCollection.distinct(key, serializeFields(query)); + } + + /** + * performs a map reduce operation + * Runs the command in REPLACE output mode (saves to named collection) + * + * @param map map function in javascript code + * @param outputTarget optional - leave null if want to use temp collection + * @param reduce reduce function in javascript code + * @param query to match + * @return The output + * @throws MongoException If an error occurred + */ + @Deprecated + public com.mongodb.MapReduceOutput mapReduce(String map, String reduce, String outputTarget, DBObject query) throws MongoException { + return mapReduce(new MapReduceCommand(dbCollection, map, reduce, outputTarget, MapReduceCommand.OutputType.REPLACE, serializeFields(query))); + } + + /** + * performs a map reduce operation + * Specify an outputType to control job execution + * * INLINE - Return results inline + * * REPLACE - Replace the output collection with the job output + * * MERGE - Merge the job output with the existing contents of outputTarget + * * REDUCE - Reduce the job output with the existing contents of + * outputTarget + * + * @param map map function in javascript code + * @param outputTarget optional - leave null if want to use temp collection + * @param outputType set the type of job output + * @param reduce reduce function in javascript code + * @param query to match + * @return The output + * @throws MongoException If an error occurred + */ + @Deprecated + public com.mongodb.MapReduceOutput mapReduce(String map, String reduce, String outputTarget, MapReduceCommand.OutputType outputType, DBObject query) + throws MongoException { + return mapReduce(new MapReduceCommand(dbCollection, map, reduce, outputTarget, outputType, serializeFields(query))); + } + + /** + * performs a map reduce operation + * + * @param command object representing the parameters + * @return The results + * @throws MongoException If an error occurred + */ + @Deprecated + public com.mongodb.MapReduceOutput mapReduce(MapReduceCommand command) throws MongoException { + return dbCollection.mapReduce(command); + } + + /** + * performs a map reduce operation + * + * @param command object representing the parameters + * @return The output + * @throws MongoException If an error occurred + */ + @Deprecated + public com.mongodb.MapReduceOutput mapReduce(DBObject command) throws MongoException { + return dbCollection.mapReduce(command); + } + + /** + * Performs a map reduce operation + * + * @param command The command to execute + * @return The output + * @throws MongoException If an error occurred + */ + public MapReduceOutput mapReduce(MapReduce.MapReduceCommand command) throws MongoException { + return new MapReduceOutput(this, dbCollection.mapReduce(command.build(this)), command.getResultType(), + command.getKeyType()); + } + + /** + * Return a list of the indexes for this collection. Each object + * in the list is the "info document" from MongoDB + * + * @return list of index documents + */ + public List getIndexInfo() { + return dbCollection.getIndexInfo(); + } + + /** + * Drops an index from this collection + * + * @param keys keys of the index + * @throws MongoException If an error occurred + */ + public void dropIndex(DBObject keys) throws MongoException { + dbCollection.dropIndex(keys); + } + + /** + * Drops an index from this collection + * + * @param name name of index to drop + * @throws MongoException If an error occurred + */ + public void dropIndex(String name) throws MongoException { + dbCollection.dropIndex(name); + } + + /** + * gets the collections statistics ("collstats" command) + * + * @return the stats + */ + public CommandResult getStats() { + return dbCollection.getStats(); + } + + /** + * returns whether or not this is a capped collection + * + * @return whether it is capped + */ + public boolean isCapped() { + return dbCollection.isCapped(); + } + + /** + * Finds a collection that is prefixed with this collection's name. + * A typical use of this might be + *
    +     *    DBCollection users = mongo.getCollection( "wiki" ).getCollection( "users" );
    +     * 
    + * Which is equivalent to + *
    + * DBCollection users = mongo.getCollection( "wiki.users" ); + *
    + * + * @param n the name of the collection to find + * @param type The type of the collection + * @return the matching collection + */ + public JacksonDBCollection getCollection(String n, Class type, Class keyType) { + return wrap(getDB().getCollection(getName() + "." + n), type, keyType, objectMapper); + } + + /** + * Returns the name of this collection. + * + * @return the name of this collection + */ + public String getName() { + return dbCollection.getName(); + } + + /** + * Returns the full name of this collection, with the database name as a prefix. + * + * @return the name of this collection + */ + public String getFullName() { + return dbCollection.getFullName(); + } + + /** + * Returns the database this collection is a member of. + * + * @return this collection's database + */ + public DB getDB() { + return dbCollection.getDB(); + } + + @Override + public int hashCode() { + return dbCollection.hashCode(); + } + + @Override + public boolean equals(Object o) { + return o == this; + } + + @Override + public String toString() { + return dbCollection.toString(); + } + + /** + * Set the write concern for this collection. Will be used for + * writes to this collection. Overrides any setting of write + * concern at the DB level. See the documentation for + * {@link WriteConcern} for more information. + * + * @param concern write concern to use + */ + public void setWriteConcern(WriteConcern concern) { + dbCollection.setWriteConcern(concern); + } + + /** + * Get the write concern for this collection. + * + * @return THe write concern + */ + public WriteConcern getWriteConcern() { + return dbCollection.getWriteConcern(); + } + + /** + * Sets the read preference for this collection. Will be used as default + * for reads from this collection; overrides DB & Connection level settings. + * See the * documentation for {@link ReadPreference} for more information. + * + * @param preference Read Preference to use + */ + public void setReadPreference(ReadPreference preference) { + dbCollection.setReadPreference(preference); + } + + /** + * Gets the read preference + * + * @return The read preference + */ + public ReadPreference getReadPreference() { + return dbCollection.getReadPreference(); + } + + /** + * adds a default query option + * + * @param option The option to add + */ + public void addOption(int option) { + dbCollection.addOption(option); + } + + /** + * sets the default query options + * + * @param options The options + */ + public void setOptions(int options) { + dbCollection.setOptions(options); + } + + /** + * resets the default query options + */ + public void resetOptions() { + dbCollection.resetOptions(); + } + + /** + * gets the default query options + * + * @return The options + */ + public int getOptions() { + return dbCollection.getOptions(); + } + + /** + * Get the type of this collection + * + * @return The type + */ + public JacksonCollectionKey getCollectionKey() { + return new JacksonCollectionKey(getName(), type, keyType); + } + + /** + * Get a collection for loading a reference of the given type + * + * @param collectionName The name of the collection + * @param type The type of the object + * @param keyType the type of the id + * @return The collection + */ + public JacksonDBCollection getReferenceCollection(String collectionName, JavaType type, JavaType keyType) { + return getReferenceCollection(new JacksonCollectionKey(collectionName, type, keyType)); + } + + /** + * Get a collection for loading a reference of the given type + * + * @param collectionKey The key for the collection + * @return The collection + */ + public JacksonDBCollection getReferenceCollection(JacksonCollectionKey collectionKey) { + JacksonDBCollection collection = referencedCollectionCache.get(collectionKey); + if (collection == null) { + collection = new JacksonDBCollection(getDB().getCollection(collectionKey.getName()), + collectionKey.getType(), collectionKey.getKeyType(), objectMapper, features); + referencedCollectionCache.put(collectionKey, collection); + } + return collection; + } + + JacksonDecoderFactory getDecoderFactory() { + return decoderFactory; + } + + DBObject createIdQuery(K object) { + return new BasicDBObject("_id", convertToDbId(object)); + } + + Object convertToDbId(K object) { + if (object instanceof org.bson.types.ObjectId) { + // Do not try and convert it + return object; + } else { + return idHandler.toDbId(object); + } + } + + public K convertFromDbId(Object object) { + return idHandler.fromDbId(object); + } + + DBObject convertToDbObject(T object) throws MongoException { + if (object == null) { + return null; + } + BsonObjectGenerator generator = new BsonObjectGenerator(); + try { + objectMapper.writeValue(generator, object); + } catch (JsonMappingException e) { + throw new MongoJsonMappingException(e); + } catch (IOException e) { + // This shouldn't happen + throw new MongoException("Unknown error occurred converting BSON to object", e); + } + return generator.getDBObject(); + } + + DBObject[] convertToDbObjects(T... objects) throws MongoException { + // Yay for generic array creation + DBObject[] results = new DBObject[objects.length]; + for (int i = 0; i < objects.length; i++) { + results[i] = convertToDbObject(objects[i]); + } + return results; + } + + T convertFromDbObject(DBObject dbObject) throws MongoException { + if (dbObject == null) { + return null; + } + if (dbObject instanceof JacksonDBObject) { + return (T) ((JacksonDBObject) dbObject).getObject(); + } + try { + return (T) objectMapper.readValue(new BsonObjectTraversingParser(this, dbObject), type); + } catch (JsonMappingException e) { + throw new MongoJsonMappingException(e); + } catch (IOException e) { + // This shouldn't happen + throw new MongoException("Unknown error occurred converting BSON to object", e); + } + } + + S convertFromDbObject(DBObject dbObject, Class clazz) throws MongoException { + if (dbObject == null) { + return null; + } + if (dbObject instanceof JacksonDBObject) { + return (S) ((JacksonDBObject) dbObject).getObject(); + } + try { + return objectMapper.readValue(new BsonObjectTraversingParser(this, dbObject), clazz); + } catch (JsonMappingException e) { + throw new MongoJsonMappingException(e); + } catch (IOException e) { + // This shouldn't happen + throw new MongoException("Unknown error occurred converting BSON to object", e); + } + } + + @SuppressWarnings({"unchecked"}) + T[] convertFromDbObjects(DBObject... dbObjects) throws MongoException { + T[] results = (T[]) new Object[dbObjects.length]; + for (int i = 0; i < dbObjects.length; i++) { + results[i] = convertFromDbObject(dbObjects[i]); + } + return results; + } + + DBObject serializeFields(DBObject value) { + return SerializationUtils.serializeFields(objectMapper, value); + } + + Object serializeField(Object value) { + return SerializationUtils.serializeField(objectMapper, value); + } + + ObjectMapper getObjectMapper() { + return objectMapper; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `convertToDbObject(query)` could be null and is dereferenced by call to `update(...)` at line 367. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +WriteResult JacksonDBCollection.update(Object,Object,boolean,boolean,WriteConcern) + +### Procedure Id: +net.vz.mongodb.jackson.JacksonDBCollection.update(java.lang.Object,java.lang.Object,boolean,boolean,.77d942bb7a2f45914c7ae311609b540c + +### File: +src/main/java/net/vz/mongodb/jackson/JacksonDBCollection.java + +### Key: +JacksonDBCollection.java|update|NULL_DEREFERENCE + +### Node Key: +1dfab92481fd78b6f6a49c9740c7b167 + +### Hash: +e7fc63c04fa3e293dfe9699ce57dfa74 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7788/instruction.md b/inferredbugs-7788/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9cb09df88cdc0139a5bb57cad6fe145023a541aa --- /dev/null +++ b/inferredbugs-7788/instruction.md @@ -0,0 +1,281 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** mongojack +**Bug ID:** 19 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2011 VZ Netzwerke Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.vz.mongodb.jackson; + +import org.hamcrest.Matchers; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +public class TestObjectIdHandling extends MongoDBTestBase { + + @Test + public void testObjectIdGenerated() { + ObjectIdId object = new ObjectIdId(); + + JacksonDBCollection coll = getCollection(ObjectIdId.class, + org.bson.types.ObjectId.class); + + org.bson.types.ObjectId id = coll.insert(object).getSavedId(); + ObjectIdId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testObjectIdSaved() { + ObjectIdId object = new ObjectIdId(); + org.bson.types.ObjectId id = new org.bson.types.ObjectId(); + object._id = id; + + JacksonDBCollection coll = getCollection(ObjectIdId.class, + org.bson.types.ObjectId.class); + + coll.insert(object); + ObjectIdId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + public static class ObjectIdId { + public org.bson.types.ObjectId _id; + } + + @Test + public void testObjectIdAnnotationOnStringGenerated() { + StringId object = new StringId(); + + JacksonDBCollection coll = getCollection(StringId.class, String.class); + + String id = coll.insert(object).getSavedId(); + // Check that it's a valid object id + assertTrue(org.bson.types.ObjectId.isValid(id)); + StringId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testObjectIdAnnotationOnStringSaved() { + StringId object = new StringId(); + String id = new org.bson.types.ObjectId().toString(); + object._id = id; + + JacksonDBCollection coll = getCollection(StringId.class, String.class); + + coll.insert(object); + StringId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testRemoveByIdWithObjectId() { + JacksonDBCollection coll = getCollection(StringId.class, String.class); + String id = coll.insert(new StringId()).getSavedId(); + coll.insert(new StringId()); + assertThat(coll.find().toArray(), hasSize(2)); + coll.removeById(id); + List results = coll.find().toArray(); + assertThat(results, hasSize(1)); + assertThat(results.get(0)._id, not(Matchers.equalTo(id))); + } + + @Test + public void testFindOneByIdWithObjectId() { + JacksonDBCollection coll = getCollection(StringId.class, String.class); + StringId object = new StringId(); + net.vz.mongodb.jackson.WriteResult writeResult = coll.insert(object); + assertThat(writeResult.getDbObject().get("_id"), instanceOf(org.bson.types.ObjectId.class)); + String id = writeResult.getSavedId(); + assertThat(id, instanceOf(String.class)); + StringId result = coll.findOneById(id); + assertThat(result._id, Matchers.equalTo(id)); + } + + public static class StringId { + @ObjectId + public String _id; + } + + @Test + public void testObjectIdAnnotationOnByteArrayGenerated() { + ByteArrayId object = new ByteArrayId(); + + JacksonDBCollection coll = getCollection(ByteArrayId.class, byte[].class); + + byte[] id = coll.insert(object).getSavedId(); + // Check that it's a valid object id, should be 12 bytes + assertEquals(12, id.length); + ByteArrayId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testObjectIdAnnotationOnByteArraySaved() { + ByteArrayId object = new ByteArrayId(); + byte[] id = new org.bson.types.ObjectId().toByteArray(); + object._id = id; + + JacksonDBCollection coll = getCollection(ByteArrayId.class, byte[].class); + + coll.insert(object); + ByteArrayId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + public static class ByteArrayId { + @ObjectId + public byte[] _id; + } + + @Test + public void testCollectionOfObjectIds() { + ObjectIdCollection object = new ObjectIdCollection(); + object._id = "id"; + object.list = Arrays.asList(org.bson.types.ObjectId.get(), org.bson.types.ObjectId.get()); + + JacksonDBCollection coll = getCollection(ObjectIdCollection.class, String.class); + coll.insert(object); + + ObjectIdCollection result = coll.findOneById("id"); + assertThat(result.list, equalTo(object.list)); + } + + public static class ObjectIdCollection { + public String _id; + public List list; + } + + @Test + public void testCollectionOfObjectIdStrings() { + StringIdCollection object = new StringIdCollection(); + object._id = "id"; + object.list = Arrays.asList(org.bson.types.ObjectId.get().toString(), org.bson.types.ObjectId.get().toString()); + + JacksonDBCollection coll = getCollection(StringIdCollection.class, String.class); + coll.insert(object); + + StringIdCollection result = coll.findOneById("id"); + assertThat(result.list, equalTo(object.list)); + } + + public static class StringIdCollection { + public String _id; + @ObjectId + public List list; + } + + @Test + public void testCollectionOfObjectIdByteArrays() { + ByteArrayIdCollection object = new ByteArrayIdCollection(); + object._id = "id"; + object.list = Arrays.asList(org.bson.types.ObjectId.get().toByteArray(), org.bson.types.ObjectId.get().toByteArray()); + + JacksonDBCollection coll = getCollection(ByteArrayIdCollection.class, String.class); + coll.insert(object); + + ByteArrayIdCollection result = coll.findOneById("id"); + assertThat(result.list, hasSize(2)); + assertThat(result.list.get(0), equalTo(object.list.get(0))); + assertThat(result.list.get(1), equalTo(object.list.get(1))); + } + + public static class ByteArrayIdCollection { + public String _id; + @ObjectId + public List list; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `result` last assigned on line 86 could be null and is dereferenced at line 87. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestObjectIdHandling.testObjectIdAnnotationOnStringSaved() + +### Procedure Id: +net.vz.mongodb.jackson.TestObjectIdHandling.testObjectIdAnnotationOnStringSaved():void.9268c7cdf6cc8e356b91b9bd498782d5 + +### File: +src/test/java/net/vz/mongodb/jackson/TestObjectIdHandling.java + +### Key: +TestObjectIdHandling.java|testObjectIdAnnotationOnStringSaved|NULL_DEREFERENCE + +### Node Key: +2acc12e05b0902ef2ca0b1741f78fa6e + +### Hash: +300455b14e604d48595007c92593d86e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7808/instruction.md b/inferredbugs-7808/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d22b81ee05fd7fb6d5df3da9444111170e26c303 --- /dev/null +++ b/inferredbugs-7808/instruction.md @@ -0,0 +1,526 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** amazon-kinesis-client +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2019 Amazon.com, Inc. or its affiliates. + * Licensed under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package software.amazon.kinesis.retrieval.polling; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static software.amazon.kinesis.utils.ProcessRecordsInputMatcher.eqProcessRecordsInput; + +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.apache.commons.lang3.StringUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; + +import io.reactivex.Flowable; +import io.reactivex.schedulers.Schedulers; +import lombok.extern.slf4j.Slf4j; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.services.kinesis.model.ExpiredIteratorException; +import software.amazon.awssdk.services.kinesis.model.GetRecordsResponse; +import software.amazon.awssdk.services.kinesis.model.Record; +import software.amazon.kinesis.common.InitialPositionInStreamExtended; +import software.amazon.kinesis.lifecycle.ShardConsumerNotifyingSubscriber; +import software.amazon.kinesis.lifecycle.events.ProcessRecordsInput; +import software.amazon.kinesis.metrics.NullMetricsFactory; +import software.amazon.kinesis.retrieval.GetRecordsRetrievalStrategy; +import software.amazon.kinesis.retrieval.KinesisClientRecord; +import software.amazon.kinesis.retrieval.RecordsRetrieved; +import software.amazon.kinesis.retrieval.RetryableRetrievalException; +import software.amazon.kinesis.retrieval.kpl.ExtendedSequenceNumber; + +/** + * Test class for the PrefetchRecordsPublisher class. + */ +@RunWith(MockitoJUnitRunner.class) +@Slf4j +public class PrefetchRecordsPublisherTest { + private static final int SIZE_512_KB = 512 * 1024; + private static final int SIZE_1_MB = 2 * SIZE_512_KB; + private static final int MAX_RECORDS_PER_CALL = 10000; + private static final int MAX_SIZE = 5; + private static final int MAX_RECORDS_COUNT = 15000; + private static final long IDLE_MILLIS_BETWEEN_CALLS = 0L; + + @Mock + private GetRecordsRetrievalStrategy getRecordsRetrievalStrategy; + @Mock + private KinesisDataFetcher dataFetcher; + @Mock + private InitialPositionInStreamExtended initialPosition; + @Mock + private ExtendedSequenceNumber sequenceNumber; + + private List records; + private ExecutorService executorService; + private LinkedBlockingQueue spyQueue; + private PrefetchRecordsPublisher getRecordsCache; + private String operation = "ProcessTask"; + private GetRecordsResponse getRecordsResponse; + private Record record; + + @Before + public void setup() { + when(getRecordsRetrievalStrategy.getDataFetcher()).thenReturn(dataFetcher); + + executorService = spy(Executors.newFixedThreadPool(1)); + getRecordsCache = new PrefetchRecordsPublisher( + MAX_SIZE, + 3 * SIZE_1_MB, + MAX_RECORDS_COUNT, + MAX_RECORDS_PER_CALL, + getRecordsRetrievalStrategy, + executorService, + IDLE_MILLIS_BETWEEN_CALLS, + new NullMetricsFactory(), + operation, + "shardId"); + spyQueue = spy(getRecordsCache.getRecordsResultQueue); + records = spy(new ArrayList<>()); + getRecordsResponse = GetRecordsResponse.builder().records(records).build(); + + when(getRecordsRetrievalStrategy.getRecords(eq(MAX_RECORDS_PER_CALL))).thenReturn(getRecordsResponse); + } + + @Test + public void testGetRecords() { + record = Record.builder().data(createByteBufferWithSize(SIZE_512_KB)).build(); + + when(records.size()).thenReturn(1000); + + final List expectedRecords = records.stream() + .map(KinesisClientRecord::fromRecord).collect(Collectors.toList()); + + getRecordsCache.start(sequenceNumber, initialPosition); + ProcessRecordsInput result = getRecordsCache.getNextResult().processRecordsInput(); + + assertEquals(expectedRecords, result.records()); + + verify(executorService).execute(any()); + verify(getRecordsRetrievalStrategy, atLeast(1)).getRecords(eq(MAX_RECORDS_PER_CALL)); + } + + // TODO: Broken test + @Test + @Ignore + public void testFullCacheByteSize() { + record = Record.builder().data(createByteBufferWithSize(SIZE_1_MB)).build(); + + when(records.size()).thenReturn(500); + + records.add(record); + + getRecordsCache.start(sequenceNumber, initialPosition); + + // Sleep for a few seconds for the cache to fill up. + sleep(2000); + + verify(getRecordsRetrievalStrategy, times(3)).getRecords(eq(MAX_RECORDS_PER_CALL)); + assertEquals(spyQueue.size(), 3); + } + + @Test + public void testFullCacheRecordsCount() { + int recordsSize = 4500; + when(records.size()).thenReturn(recordsSize); + + getRecordsCache.start(sequenceNumber, initialPosition); + + sleep(2000); + + int callRate = (int) Math.ceil((double) MAX_RECORDS_COUNT/recordsSize); +// TODO: fix this verification +// verify(getRecordsRetrievalStrategy, times(callRate)).getRecords(MAX_RECORDS_PER_CALL); +// assertEquals(spyQueue.size(), callRate); + assertTrue(callRate < MAX_SIZE); + } + + @Test + public void testFullCacheSize() { + int recordsSize = 200; + when(records.size()).thenReturn(recordsSize); + + getRecordsCache.start(sequenceNumber, initialPosition); + + // Sleep for a few seconds for the cache to fill up. + sleep(2000); + + verify(getRecordsRetrievalStrategy, times(MAX_SIZE + 1)).getRecords(eq(MAX_RECORDS_PER_CALL)); + assertEquals(spyQueue.size(), MAX_SIZE); + } + + // TODO: Broken tests + @Test + @Ignore + public void testMultipleCacheCalls() { + int recordsSize = 20; + record = Record.builder().data(createByteBufferWithSize(1024)).build(); + + IntStream.range(0, recordsSize).forEach(i -> records.add(record)); + final List expectedRecords = records.stream() + .map(KinesisClientRecord::fromRecord).collect(Collectors.toList()); + + getRecordsCache.start(sequenceNumber, initialPosition); + ProcessRecordsInput processRecordsInput = getRecordsCache.getNextResult().processRecordsInput(); + + verify(executorService).execute(any()); + assertEquals(expectedRecords, processRecordsInput.records()); + assertNotNull(processRecordsInput.cacheEntryTime()); + assertNotNull(processRecordsInput.cacheExitTime()); + + sleep(2000); + + ProcessRecordsInput processRecordsInput2 = getRecordsCache.getNextResult().processRecordsInput(); + assertNotEquals(processRecordsInput, processRecordsInput2); + assertEquals(expectedRecords, processRecordsInput2.records()); + assertNotEquals(processRecordsInput2.timeSpentInCache(), Duration.ZERO); + + assertTrue(spyQueue.size() <= MAX_SIZE); + } + + @Test(expected = IllegalStateException.class) + public void testGetNextRecordsWithoutStarting() { + verify(executorService, times(0)).execute(any()); + getRecordsCache.getNextResult(); + } + + @Test(expected = IllegalStateException.class) + public void testCallAfterShutdown() { + when(executorService.isShutdown()).thenReturn(true); + getRecordsCache.getNextResult(); + } + + @Test + public void testExpiredIteratorException() { + log.info("Starting tests"); + when(getRecordsRetrievalStrategy.getRecords(MAX_RECORDS_PER_CALL)).thenThrow(ExpiredIteratorException.class) + .thenReturn(getRecordsResponse); + + getRecordsCache.start(sequenceNumber, initialPosition); + + doNothing().when(dataFetcher).restartIterator(); + + getRecordsCache.getNextResult(); + + sleep(1000); + + verify(dataFetcher).restartIterator(); + } + + @Test + public void testRetryableRetrievalExceptionContinues() { + + GetRecordsResponse response = GetRecordsResponse.builder().millisBehindLatest(100L).records(Collections.emptyList()).build(); + when(getRecordsRetrievalStrategy.getRecords(anyInt())).thenThrow(new RetryableRetrievalException("Timeout", new TimeoutException("Timeout"))).thenReturn(response); + + getRecordsCache.start(sequenceNumber, initialPosition); + + RecordsRetrieved records = getRecordsCache.getNextResult(); + assertThat(records.processRecordsInput().millisBehindLatest(), equalTo(response.millisBehindLatest())); + } + + @Test(timeout = 1000L) + public void testNoDeadlockOnFullQueue() { + // + // Fixes https://github.com/awslabs/amazon-kinesis-client/issues/448 + // + // This test is to verify that the drain of a blocked queue no longer deadlocks. + // If the test times out before starting the subscriber it means something went wrong while filling the queue. + // After the subscriber is started one of the things that can trigger a timeout is a deadlock. + // + GetRecordsResponse response = GetRecordsResponse.builder().records( + Record.builder().data(SdkBytes.fromByteArray(new byte[] { 1, 2, 3 })).sequenceNumber("123").build()) + .build(); + when(getRecordsRetrievalStrategy.getRecords(anyInt())).thenReturn(response); + + getRecordsCache.start(sequenceNumber, initialPosition); + + // + // Wait for the queue to fill up, and the publisher to block on adding items to the queue. + // + log.info("Waiting for queue to fill up"); + while (getRecordsCache.getRecordsResultQueue.size() < MAX_SIZE) { + Thread.yield(); + } + + log.info("Queue is currently at {} starting subscriber", getRecordsCache.getRecordsResultQueue.size()); + AtomicInteger receivedItems = new AtomicInteger(0); + final int expectedItems = MAX_SIZE * 3; + + Object lock = new Object(); + + Subscriber delegateSubscriber = new Subscriber() { + Subscription sub; + + @Override + public void onSubscribe(Subscription s) { + sub = s; + s.request(1); + } + + @Override + public void onNext(RecordsRetrieved recordsRetrieved) { + receivedItems.incrementAndGet(); + if (receivedItems.get() >= expectedItems) { + synchronized (lock) { + log.info("Notifying waiters"); + lock.notifyAll(); + } + sub.cancel(); + } else { + sub.request(1); + } + } + + @Override + public void onError(Throwable t) { + log.error("Caught error", t); + throw new RuntimeException(t); + } + + @Override + public void onComplete() { + fail("onComplete not expected in this test"); + } + }; + + Subscriber subscriber = new ShardConsumerNotifyingSubscriber(delegateSubscriber, getRecordsCache); + + synchronized (lock) { + log.info("Awaiting notification"); + Flowable.fromPublisher(getRecordsCache).subscribeOn(Schedulers.computation()) + .observeOn(Schedulers.computation(), true, 8).subscribe(subscriber); + try { + lock.wait(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + verify(getRecordsRetrievalStrategy, atLeast(expectedItems)).getRecords(anyInt()); + assertThat(receivedItems.get(), equalTo(expectedItems)); + } + + @Test + public void testResetClearsRemainingData() { + List responses = Stream.iterate(0, i -> i + 1).limit(10).map(i -> { + Record record = Record.builder().partitionKey("record-" + i).sequenceNumber("seq-" + i) + .data(SdkBytes.fromByteArray(new byte[] { 1, 2, 3 })).approximateArrivalTimestamp(Instant.now()) + .build(); + String nextIterator = "shard-iter-" + (i + 1); + return GetRecordsResponse.builder().records(record).nextShardIterator(nextIterator).build(); + }).collect(Collectors.toList()); + + RetrieverAnswer retrieverAnswer = new RetrieverAnswer(responses); + + when(getRecordsRetrievalStrategy.getRecords(anyInt())).thenAnswer(retrieverAnswer); + doAnswer(a -> { + String resetTo = a.getArgumentAt(0, String.class); + retrieverAnswer.resetIteratorTo(resetTo); + return null; + }).when(dataFetcher).resetIterator(anyString(), anyString(), any()); + + getRecordsCache.start(sequenceNumber, initialPosition); + + RecordsRetrieved lastProcessed = getRecordsCache.getNextResult(); + RecordsRetrieved expected = getRecordsCache.getNextResult(); + + // + // Skip some of the records the cache + // + getRecordsCache.getNextResult(); + getRecordsCache.getNextResult(); + + verify(getRecordsRetrievalStrategy, atLeast(2)).getRecords(anyInt()); + + while(getRecordsCache.getRecordsResultQueue.remainingCapacity() > 0) { + Thread.yield(); + } + + getRecordsCache.restartFrom(lastProcessed); + RecordsRetrieved postRestart = getRecordsCache.getNextResult(); + + assertThat(postRestart.processRecordsInput(), eqProcessRecordsInput(expected.processRecordsInput())); + verify(dataFetcher).resetIterator(eq(responses.get(0).nextShardIterator()), + eq(responses.get(0).records().get(0).sequenceNumber()), any()); + + } + + private static class RetrieverAnswer implements Answer { + + private final List responses; + private Iterator iterator; + + public RetrieverAnswer(List responses) { + this.responses = responses; + this.iterator = responses.iterator(); + } + + public void resetIteratorTo(String nextIterator) { + Iterator newIterator = responses.iterator(); + while(newIterator.hasNext()) { + GetRecordsResponse current = newIterator.next(); + if (StringUtils.equals(nextIterator, current.nextShardIterator())) { + if (!newIterator.hasNext()) { + iterator = responses.iterator(); + } else { + newIterator.next(); + iterator = newIterator; + } + break; + } + } + } + + @Override + public GetRecordsResponse answer(InvocationOnMock invocation) throws Throwable { + GetRecordsResponse response = iterator.next(); + if (!iterator.hasNext()) { + iterator = responses.iterator(); + } + return response; + } + } + + @After + public void shutdown() { + getRecordsCache.shutdown(); + verify(executorService).shutdownNow(); + } + + private void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) {} + } + + private SdkBytes createByteBufferWithSize(int size) { + return SdkBytes.fromByteArray(new byte[size]); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `software.amazon.kinesis.retrieval.polling.PrefetchRecordsPublisherTest.testGetRecords` indirectly reads without synchronization from `this.software.amazon.kinesis.retrieval.polling.PrefetchRecordsPublisherTest.getRecordsCache.software.amazon.kinesis.retrieval.polling.PrefetchRecordsPublisher.started`. Potentially races with write in method `PrefetchRecordsPublisherTest.testNoDeadlockOnFullQueue()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PrefetchRecordsPublisherTest.testGetRecords() + +### Procedure Id: +software.amazon.kinesis.retrieval.polling.PrefetchRecordsPublisherTest.testGetRecords():void.c61684424029313317c7b40f3b370b58 + +### File: +amazon-kinesis-client/src/test/java/software/amazon/kinesis/retrieval/polling/PrefetchRecordsPublisherTest.java + +### Key: +PrefetchRecordsPublisherTest.java|testGetRecords|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +1981130468de73972979947b230158f8 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7830/instruction.md b/inferredbugs-7830/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0a862e8f361d9141e5088c7d03d7a544d5529b87 --- /dev/null +++ b/inferredbugs-7830/instruction.md @@ -0,0 +1,160 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 104 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.apache.logging.log4j.core.appender; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.CoreLoggerContexts; +import org.apache.logging.log4j.core.config.ConfigurationFactory; +import org.junit.Before; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.*; + +import static org.junit.Assert.*; + +/** + * Tests that logged strings appear in the file, + * that the default file size is used if not specified + * and that the file is shrunk to its actual usage when done. + * + * @since 2.1 + */ +public class MemoryMappedFileAppenderSimpleTest { + + final String LOGFILE = "target/MemoryMappedFileAppenderTest.log"; + + @Before + public void before() { + System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "MemoryMappedFileAppenderTest.xml"); + } + + @Test + public void testMemMapBasics() throws Exception { + final File f = new File(LOGFILE); + if (f.exists()) { + assertTrue(f.delete()); + } + assertTrue(!f.exists()); + + final Logger log = LogManager.getLogger(); + try { + log.warn("Test log1"); + assertTrue(f.exists()); + assertEquals("initial length", MemoryMappedFileManager.DEFAULT_REGION_LENGTH, f.length()); + + log.warn("Test log2"); + assertEquals("not grown", MemoryMappedFileManager.DEFAULT_REGION_LENGTH, f.length()); + } finally { + CoreLoggerContexts.stopLoggerContext(false); + } + final int LINESEP = System.getProperty("line.separator").length(); + assertEquals("Shrunk to actual used size", 186 + 2 * LINESEP, f.length()); + + String line1, line2, line3; + try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) { + line1 = reader.readLine(); + line2 = reader.readLine(); + line3 = reader.readLine(); + } + assertNotNull(line1); + assertThat(line1, containsString("Test log1")); + + assertNotNull(line2); + assertThat(line2, containsString("Test log2")); + + assertNull("only two lines were logged", line3); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getProperty("line.separator")` could be null and is dereferenced at line 69. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MemoryMappedFileAppenderSimpleTest.testMemMapBasics() + +### Procedure Id: +org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderSimpleTest.testMemMapBasics():void.5d81912ec36f3f7c003d981f0e4f3f7f + +### File: +log4j-core/src/test/java/org/apache/logging/log4j/core/appender/MemoryMappedFileAppenderSimpleTest.java + +### Key: +MemoryMappedFileAppenderSimpleTest.java|testMemMapBasics|NULL_DEREFERENCE + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +da713e76d3f5a13e2b8a59578329b7bb + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7837/instruction.md b/inferredbugs-7837/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..53d81d48c65ca83093d4e33bfb5b2fed1347096b --- /dev/null +++ b/inferredbugs-7837/instruction.md @@ -0,0 +1,169 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 102 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.apache.logging.log4j.core.appender; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.CoreLoggerContexts; +import org.apache.logging.log4j.core.config.ConfigurationFactory; +import org.apache.logging.log4j.core.util.Integers; +import org.junit.Before; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.*; + +import static org.junit.Assert.*; + +/** + * Tests that logged strings and their location appear in the file, + * that the file size is the next power of two of the specified mapped region length + * and that the file is shrunk to its actual usage when done. + * + * @since 2.1 + */ +public class MemoryMappedFileAppenderLocationTest { + + final String LOGFILE = "target/MemoryMappedFileAppenderLocationTest.log"; + + @Before + public void before() { + System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, + "MemoryMappedFileAppenderLocationTest.xml"); + } + + @Test + public void testMemMapLocation() throws Exception { + final File f = new File(LOGFILE); + if (f.exists()) { + assertTrue(f.delete()); + } + assertTrue(!f.exists()); + + final int expectedFileLength = Integers.ceilingNextPowerOfTwo(32000); + assertEquals(32768, expectedFileLength); + + final Logger log = LogManager.getLogger(); + try { + log.warn("Test log1"); + assertTrue(f.exists()); + assertEquals("initial length", expectedFileLength, f.length()); + + log.warn("Test log2"); + assertEquals("not grown", expectedFileLength, f.length()); + } finally { + CoreLoggerContexts.stopLoggerContext(false); + } + final int LINESEP = System.getProperty("line.separator").length(); + assertEquals("Shrunk to actual used size", 474 + 2 * LINESEP, f.length()); + + String line1, line2, line3; + try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) { + line1 = reader.readLine(); + line2 = reader.readLine(); + line3 = reader.readLine(); + } + assertNotNull(line1); + assertThat(line1, containsString("Test log1")); + final String location1 = "org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation(MemoryMappedFileAppenderLocationTest.java:65)"; + assertThat(line1, containsString(location1)); + + assertNotNull(line2); + assertThat(line2, containsString("Test log2")); + final String location2 = "org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation(MemoryMappedFileAppenderLocationTest.java:69)"; + assertThat(line2, containsString(location2)); + + assertNull("only two lines were logged", line3); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getProperty("line.separator")` could be null and is dereferenced at line 74. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MemoryMappedFileAppenderLocationTest.testMemMapLocation() + +### Procedure Id: +org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation():voi.75b20c9ddcff577144a1ef7e81856d80 + +### File: +log4j-core/src/test/java/org/apache/logging/log4j/core/appender/MemoryMappedFileAppenderLocationTest.java + +### Key: +MemoryMappedFileAppenderLocationTest.java|testMemMapLocation|NULL_DEREFERENCE + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +3cf8d332881eb069b4f281c9b677a0de + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7916/instruction.md b/inferredbugs-7916/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3ffe4cd1fef9fabdb68f1bf3100c7281f3622808 --- /dev/null +++ b/inferredbugs-7916/instruction.md @@ -0,0 +1,440 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 112 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.apache.logging.log4j.core.async; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.impl.Log4jLogEvent; +import org.apache.logging.log4j.core.impl.LogEventFactory; +import org.apache.logging.log4j.core.impl.MutableLogEvent; +import org.apache.logging.log4j.core.impl.ReusableLogEventFactory; +import org.apache.logging.log4j.core.jmx.RingBufferAdmin; +import org.apache.logging.log4j.core.util.Constants; +import org.apache.logging.log4j.message.ReusableMessage; +import org.apache.logging.log4j.status.StatusLogger; + +import com.lmax.disruptor.EventFactory; +import com.lmax.disruptor.EventTranslatorTwoArg; +import com.lmax.disruptor.ExceptionHandler; +import com.lmax.disruptor.RingBuffer; +import com.lmax.disruptor.Sequence; +import com.lmax.disruptor.SequenceReportingEventHandler; +import com.lmax.disruptor.WaitStrategy; +import com.lmax.disruptor.dsl.Disruptor; +import com.lmax.disruptor.dsl.ProducerType; + +/** + * Helper class decoupling the {@code AsyncLoggerConfig} class from the LMAX Disruptor library. + *

    + * {@code AsyncLoggerConfig} is a plugin, and will be loaded even if users do not configure any {@code } or + * {@code } elements in the configuration. If {@code AsyncLoggerConfig} has inner classes that extend or + * implement classes from the Disruptor library, a {@code NoClassDefFoundError} is thrown if the Disruptor jar is not in + * the classpath when the PluginManager loads the {@code AsyncLoggerConfig} plugin from the pre-defined plugins + * definition file. + *

    + * This class serves to make the dependency on the Disruptor optional, so that these classes are only loaded when the + * {@code AsyncLoggerConfig} is actually used. + */ +public class AsyncLoggerConfigDisruptor implements AsyncLoggerConfigDelegate { + + private static final int MAX_DRAIN_ATTEMPTS_BEFORE_SHUTDOWN = 200; + private static final int SLEEP_MILLIS_BETWEEN_DRAIN_ATTEMPTS = 50; + private static final Logger LOGGER = StatusLogger.getLogger(); + + /** + * RingBuffer events contain all information necessary to perform the work in a separate thread. + */ + public static class Log4jEventWrapper { + public Log4jEventWrapper() { + } + + public Log4jEventWrapper(MutableLogEvent mutableLogEvent) { + event = mutableLogEvent; + } + + private AsyncLoggerConfig loggerConfig; + private LogEvent event; + + /** + * Release references held by ring buffer to allow objects to be garbage-collected. + */ + public void clear() { + loggerConfig = null; + if (event instanceof MutableLogEvent) { + ((MutableLogEvent) event).clear(); + } else { + event = null; + } + } + + @Override + public String toString() { + return String.valueOf(event); + } + } + + /** + * EventHandler performs the work in a separate thread. + */ + private static class Log4jEventWrapperHandler implements SequenceReportingEventHandler { + private static final int NOTIFY_PROGRESS_THRESHOLD = 50; + private Sequence sequenceCallback; + private int counter; + + @Override + public void setSequenceCallback(final Sequence sequenceCallback) { + this.sequenceCallback = sequenceCallback; + } + + @Override + public void onEvent(final Log4jEventWrapper event, final long sequence, final boolean endOfBatch) + throws Exception { + event.event.setEndOfBatch(endOfBatch); + event.loggerConfig.asyncCallAppenders(event.event); + event.clear(); + + notifyIntermediateProgress(sequence); + } + + /** + * Notify the BatchEventProcessor that the sequence has progressed. Without this callback the sequence would not + * be progressed until the batch has completely finished. + */ + private void notifyIntermediateProgress(final long sequence) { + if (++counter > NOTIFY_PROGRESS_THRESHOLD) { + sequenceCallback.set(sequence); + counter = 0; + } + } + } + + /** + * Factory used to populate the RingBuffer with events. These event objects are then re-used during the life of the + * RingBuffer. + */ + private static final EventFactory FACTORY = new EventFactory() { + @Override + public Log4jEventWrapper newInstance() { + return new Log4jEventWrapper(); + } + }; + + /** + * Factory used to populate the RingBuffer with events. These event objects are then re-used during the life of the + * RingBuffer. + */ + private static final EventFactory MUTABLE_FACTORY = new EventFactory() { + @Override + public Log4jEventWrapper newInstance() { + return new Log4jEventWrapper(new MutableLogEvent()); + } + }; + + /** + * Object responsible for passing on data to a specific RingBuffer event. + */ + private static final EventTranslatorTwoArg TRANSLATOR = + new EventTranslatorTwoArg() { + + @Override + public void translateTo(final Log4jEventWrapper ringBufferElement, final long sequence, + final LogEvent logEvent, final AsyncLoggerConfig loggerConfig) { + ringBufferElement.event = logEvent; + ringBufferElement.loggerConfig = loggerConfig; + } + }; + + /** + * Object responsible for passing on data to a RingBuffer event with a MutableLogEvent. + */ + private static final EventTranslatorTwoArg MUTABLE_TRANSLATOR = + new EventTranslatorTwoArg() { + + @Override + public void translateTo(final Log4jEventWrapper ringBufferElement, final long sequence, + final LogEvent logEvent, final AsyncLoggerConfig loggerConfig) { + ((MutableLogEvent) ringBufferElement.event).initFrom(logEvent); + ringBufferElement.loggerConfig = loggerConfig; + } + }; + + private static final ThreadFactory THREAD_FACTORY = new DaemonThreadFactory("AsyncLoggerConfig-"); + + private int ringBufferSize; + private AsyncEventRouter asyncEventRouter; + private Boolean mutable = Boolean.FALSE; + + private volatile Disruptor disruptor; + private ExecutorService executor; + private long backgroundThreadId; // LOG4J2-471 + private EventFactory factory; + private EventTranslatorTwoArg translator; + + public AsyncLoggerConfigDisruptor() { + } + + // called from AsyncLoggerConfig constructor + @Override + public void setLogEventFactory(final LogEventFactory logEventFactory) { + // if any AsyncLoggerConfig uses a ReusableLogEventFactory + // then we need to populate our ringbuffer with MutableLogEvents + this.mutable = mutable || (logEventFactory instanceof ReusableLogEventFactory); + } + + /** + * Increases the reference count and creates and starts a new Disruptor and associated thread if none currently + * exists. + * + * @see #stop() + */ + public synchronized void start() { + if (disruptor != null) { + LOGGER.trace("AsyncLoggerConfigDisruptor not starting new disruptor for this configuration, " + + "using existing object."); + return; + } + LOGGER.trace("AsyncLoggerConfigDisruptor creating new disruptor for this configuration."); + ringBufferSize = DisruptorUtil.calculateRingBufferSize("AsyncLoggerConfig.RingBufferSize"); + final WaitStrategy waitStrategy = DisruptorUtil.createWaitStrategy("AsyncLoggerConfig.WaitStrategy"); + executor = Executors.newSingleThreadExecutor(THREAD_FACTORY); + backgroundThreadId = DisruptorUtil.getExecutorThreadId(executor); + asyncEventRouter = AsyncEventRouterFactory.create(); + + translator = mutable ? MUTABLE_TRANSLATOR : TRANSLATOR; + factory = mutable ? MUTABLE_FACTORY : FACTORY; + disruptor = new Disruptor<>(factory, ringBufferSize, executor, ProducerType.MULTI, waitStrategy); + + final ExceptionHandler errorHandler = DisruptorUtil.getAsyncLoggerConfigExceptionHandler(); + disruptor.handleExceptionsWith(errorHandler); + + final Log4jEventWrapperHandler[] handlers = {new Log4jEventWrapperHandler()}; + disruptor.handleEventsWith(handlers); + + LOGGER.debug("Starting AsyncLoggerConfig disruptor for this configuration with ringbufferSize={}, " + + "waitStrategy={}, exceptionHandler={}...", disruptor.getRingBuffer().getBufferSize(), waitStrategy + .getClass().getSimpleName(), errorHandler); + disruptor.start(); + } + + /** + * Decreases the reference count. If the reference count reached zero, the Disruptor and its associated thread are + * shut down and their references set to {@code null}. + */ + public synchronized void stop() { + final Disruptor temp = disruptor; + if (temp == null) { + LOGGER.trace("AsyncLoggerConfigDisruptor: disruptor for this configuration already shut down."); + return; // disruptor was already shut down by another thread + } + LOGGER.trace("AsyncLoggerConfigDisruptor: shutting down disruptor for this configuration."); + + // We must guarantee that publishing to the RingBuffer has stopped before we call disruptor.shutdown(). + disruptor = null; // client code fails with NPE if log after stop = OK + + // Calling Disruptor.shutdown() will wait until all enqueued events are fully processed, + // but this waiting happens in a busy-spin. To avoid (postpone) wasting CPU, + // we sleep in short chunks, up to 10 seconds, waiting for the ringbuffer to drain. + for (int i = 0; hasBacklog(temp) && i < MAX_DRAIN_ATTEMPTS_BEFORE_SHUTDOWN; i++) { + try { + Thread.sleep(SLEEP_MILLIS_BETWEEN_DRAIN_ATTEMPTS); // give up the CPU for a while + } catch (final InterruptedException e) { // ignored + } + } + temp.shutdown(); // busy-spins until all events currently in the disruptor have been processed + + LOGGER.trace("AsyncLoggerConfigDisruptor: shutting down disruptor executor for this configuration."); + executor.shutdown(); // finally, kill the processor thread + executor = null; // release reference to allow GC + + if (DiscardingAsyncEventRouter.getDiscardCount(asyncEventRouter) > 0) { + LOGGER.trace("AsyncLoggerConfigDisruptor: {} discarded {} events.", asyncEventRouter, + DiscardingAsyncEventRouter.getDiscardCount(asyncEventRouter)); + } + } + + /** + * Returns {@code true} if the specified disruptor still has unprocessed events. + */ + private static boolean hasBacklog(final Disruptor theDisruptor) { + final RingBuffer ringBuffer = theDisruptor.getRingBuffer(); + return !ringBuffer.hasAvailableCapacity(ringBuffer.getBufferSize()); + } + + @Override + public EventRoute getEventRoute(final Level logLevel) { + final int remainingCapacity = remainingDisruptorCapacity(); + if (remainingCapacity < 0) { + return EventRoute.DISCARD; + } + return asyncEventRouter.getRoute(backgroundThreadId, logLevel); + } + + private int remainingDisruptorCapacity() { + final Disruptor temp = disruptor; + if (hasLog4jBeenShutDown(temp)) { + return -1; + } + return (int) temp.getRingBuffer().remainingCapacity(); + } + + /** + * Returns {@code true} if the specified disruptor is null. + */ + private boolean hasLog4jBeenShutDown(final Disruptor aDisruptor) { + if (aDisruptor == null) { // LOG4J2-639 + LOGGER.warn("Ignoring log event after log4j was shut down"); + return true; + } + return false; + } + + @Override + public void enqueueEvent(final LogEvent event, final AsyncLoggerConfig asyncLoggerConfig) { + // LOG4J2-639: catch NPE if disruptor field was set to null after our check above + try { + final LogEvent logEvent = prepareEvent(event); + enqueue(logEvent, asyncLoggerConfig); + } catch (final NullPointerException npe) { + // Note: NPE prevents us from adding a log event to the disruptor after it was shut down, + // which could cause the publishEvent method to hang and never return. + LOGGER.warn("Ignoring log event after log4j was shut down."); + } + } + + private LogEvent prepareEvent(final LogEvent event) { + final LogEvent logEvent = ensureImmutable(event); + if (logEvent instanceof Log4jLogEvent && logEvent.getMessage() instanceof ReusableMessage) { + ((Log4jLogEvent) logEvent).makeMessageImmutable(); + } + return logEvent; + } + + private void enqueue(final LogEvent logEvent, final AsyncLoggerConfig asyncLoggerConfig) { + disruptor.getRingBuffer().publishEvent(translator, logEvent, asyncLoggerConfig); + } + + @Override + public boolean tryEnqueue(final LogEvent event, final AsyncLoggerConfig asyncLoggerConfig) { + final LogEvent logEvent = prepareEvent(event); + return disruptor.getRingBuffer().tryPublishEvent(translator, logEvent, asyncLoggerConfig); + } + + private LogEvent ensureImmutable(final LogEvent event) { + LogEvent result = event; + if (event instanceof RingBufferLogEvent) { + // Deal with special case where both types of Async Loggers are used together: + // RingBufferLogEvents are created by the all-loggers-async type, but + // this event is also consumed by the some-loggers-async type (this class). + // The original event will be re-used and modified in an application thread later, + // so take a snapshot of it, which can be safely processed in the + // some-loggers-async background thread. + result = ((RingBufferLogEvent) event).createMemento(); + } + return result; + } + + /* + * (non-Javadoc) + * + * @see org.apache.logging.log4j.core.async.AsyncLoggerConfigDelegate#createRingBufferAdmin(java.lang.String, + * java.lang.String) + */ + @Override + public RingBufferAdmin createRingBufferAdmin(final String contextName, final String loggerConfigName) { + return RingBufferAdmin.forAsyncLoggerConfig(disruptor.getRingBuffer(), contextName, loggerConfigName); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.logging.log4j.core.async.AsyncLoggerConfigDisruptor.getEventRoute` reads without synchronization from `this.org.apache.logging.log4j.core.async.AsyncLoggerConfigDisruptor.asyncEventRouter`. Potentially races with write in method `AsyncLoggerConfigDisruptor.start()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +EventRoute AsyncLoggerConfigDisruptor.getEventRoute(Level) + +### Procedure Id: +org.apache.logging.log4j.core.async.AsyncLoggerConfigDisruptor.getEventRoute(org.apache.logging.log4.b5eda271ff4c553e447a364496a0b16e + +### File: +log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigDisruptor.java + +### Key: +AsyncLoggerConfigDisruptor.java|getEventRoute|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +ff6d31af5ace5fba697604821fd64386 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7920/instruction.md b/inferredbugs-7920/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b39e9a5e1a5c823f4f09a452b12244eda3152a59 --- /dev/null +++ b/inferredbugs-7920/instruction.md @@ -0,0 +1,228 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 77 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import static org.junit.Assert.*; + + +/** + * Utiities for serialization tests. + */ +public class SerializationTestHelper { + /** + * Private constructor. + */ + private SerializationTestHelper() { + } + + /** + * Creates a clone by serializing object and + * deserializing byte stream. + * + * @param obj object to serialize and deserialize. + * @return clone + * @throws IOException on IO error. + * @throws ClassNotFoundException if class not found. + */ + public static Object serializeClone(final Object obj) + throws IOException, ClassNotFoundException { + final ByteArrayOutputStream memOut = new ByteArrayOutputStream(); + final ObjectOutputStream objOut = new ObjectOutputStream(memOut); + objOut.writeObject(obj); + objOut.close(); + + final ByteArrayInputStream src = new ByteArrayInputStream(memOut.toByteArray()); + final ObjectInputStream objIs = new ObjectInputStream(src); + + return objIs.readObject(); + } + + /** + * Deserializes a specified file. + * + * @param witness serialization file, may not be null. + * @return deserialized object. + * @throws Exception thrown on IO or deserialization exception. + */ + public static Object deserializeStream(final String witness) throws Exception { + final FileInputStream fileIs = new FileInputStream(witness); + final ObjectInputStream objIs = new ObjectInputStream(fileIs); + try { + return objIs.readObject(); + } finally { + objIs.close(); + } + } + + /** + * Checks the serialization of an object against an file + * containing the expected serialization. + * + * @param witness name of file containing expected serialization. + * @param obj object to be serialized. + * @param skip positions in serialized stream that should not be compared. + * @param endCompare position to stop comparison. + * @throws Exception thrown on IO or serialization exception. + */ + public static void assertSerializationEquals( + final String witness, final Object obj, final int[] skip, + final int endCompare) throws Exception { + final ByteArrayOutputStream memOut = new ByteArrayOutputStream(); + final ObjectOutputStream objOut = new ObjectOutputStream(memOut); + objOut.writeObject(obj); + objOut.close(); + + assertStreamEquals(witness, memOut.toByteArray(), skip, endCompare); + } + + /** + * Asserts the serialized form of an object. + * + * @param witness file name of expected serialization. + * @param actual byte array of actual serialization. + * @param skip positions to skip comparison. + * @param endCompare position to stop comparison. + * @throws IOException thrown on IO or serialization exception. + */ + public static void assertStreamEquals( + final String witness, final byte[] actual, final int[] skip, + final int endCompare) throws IOException { + final File witnessFile = new File(witness); + + if (witnessFile.exists()) { + int skipIndex = 0; + final byte[] expected = new byte[actual.length]; + final FileInputStream is = new FileInputStream(witnessFile); + final int bytesRead = is.read(expected); + is.close(); + + if (bytesRead < endCompare) { + assertEquals(bytesRead, actual.length); + } + + int endScan = actual.length; + + if (endScan > endCompare) { + endScan = endCompare; + } + + for (int i = 0; i < endScan; i++) { + if ((skipIndex < skip.length) && (skip[skipIndex] == i)) { + skipIndex++; + } else { + if (expected[i] != actual[i]) { + assertEquals( + "Difference at offset " + i, expected[i], actual[i]); + } + } + } + } else { + // + // if the file doesn't exist then + // assume that we are setting up and need to write it + final FileOutputStream os = new FileOutputStream(witnessFile); + os.write(actual); + os.close(); + fail("Writing witness file " + witness); + } + } +} + + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired to `fileIs` by call to `FileInputStream(...)` at line 72 is not released after line 73. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object SerializationTestHelper.deserializeStream(String) + +### Procedure Id: +org.apache.log4j.util.SerializationTestHelper.deserializeStream(java.lang.String):java.lang.Object.275681355609342bcaabddbfb8267e53 + +### File: +log4j-1.2-api/src/test/java/org/apache/log4j/util/SerializationTestHelper.java + +### Key: +SerializationTestHelper.java|deserializeStream|RESOURCE_LEAK + +### Node Key: +da6943b6ed41aef54880409d2b07047d + +### Hash: +880078fb408be453ac17e9c2b1b709f7 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7927/instruction.md b/inferredbugs-7927/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4cda219ade72644879afef8825009a3adeb7f0b2 --- /dev/null +++ b/inferredbugs-7927/instruction.md @@ -0,0 +1,197 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.apache.logging.log4j.core.config; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.LoggerContext; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; +import java.util.Map; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertEquals; + +/** + * + */ +public class TestConfigurator { + + private static final String CONFIG_NAME = "ConfigTest"; + + + @Test + public void testFromFile() throws Exception { + Configurator.intitalize("Test1", null, "target/test-classes/log4j2-config.xml"); + Logger logger = LogManager.getLogger("org.apache.test.TestConfigurator"); + LoggerContext ctx = (LoggerContext) LogManager.getContext(false); + Configuration config = ctx.getConfiguration(); + assertNotNull("No configuration", config); + assertTrue("Incorrect Configuration. Expected " + CONFIG_NAME + " but found " + config.getName(), + CONFIG_NAME.equals(config.getName())); + Map map = config.getAppenders(); + assertNotNull("No Appenders", map != null && map.size() > 0); + assertTrue("Wrong configuration", map.containsKey("List")); + Configurator.shutdown(); + config = ctx.getConfiguration(); + assertTrue("Incorrect Configuration. Expected " + DefaultConfiguration.DEFAULT_NAME + " but found " + + config.getName(), DefaultConfiguration.DEFAULT_NAME.equals(config.getName())); + } + + @Test + public void testFromClassPath() throws Exception { + Configurator.intitalize("Test1", null, "log4j2-config.xml"); + Logger logger = LogManager.getLogger("org.apache.test.TestConfigurator"); + LoggerContext ctx = (LoggerContext) LogManager.getContext(false); + Configuration config = ctx.getConfiguration(); + assertNotNull("No configuration", config); + assertTrue("Incorrect Configuration. Expected " + CONFIG_NAME + " but found " + config.getName(), + CONFIG_NAME.equals(config.getName())); + Map map = config.getAppenders(); + assertNotNull("No Appenders", map != null && map.size() > 0); + assertTrue("Wrong configuration", map.containsKey("List")); + Configurator.shutdown(); + config = ctx.getConfiguration(); + assertTrue("Incorrect Configuration. Expected " + DefaultConfiguration.DEFAULT_NAME + " but found " + + config.getName(), DefaultConfiguration.DEFAULT_NAME.equals(config.getName())); + } + + @Test + public void testByName() throws Exception { + Configurator.intitalize("-config", null, null); + Logger logger = LogManager.getLogger("org.apache.test.TestConfigurator"); + LoggerContext ctx = (LoggerContext) LogManager.getContext(false); + Configuration config = ctx.getConfiguration(); + assertNotNull("No configuration", config); + assertTrue("Incorrect Configuration. Expected " + CONFIG_NAME + " but found " + config.getName(), + CONFIG_NAME.equals(config.getName())); + Map map = config.getAppenders(); + assertNotNull("No Appenders", map != null && map.size() > 0); + assertTrue("Wrong configuration", map.containsKey("List")); + Configurator.shutdown(); + config = ctx.getConfiguration(); + assertTrue("Incorrect Configuration. Expected " + DefaultConfiguration.DEFAULT_NAME + " but found " + + config.getName(), DefaultConfiguration.DEFAULT_NAME.equals(config.getName())); + } + + @Test + public void testReconfiguration() throws Exception { + File file = new File("target/test-classes/log4j2-config.xml"); + file.setLastModified(System.currentTimeMillis() - 120000); + Configurator.intitalize("Test1", null, "target/test-classes/log4j2-config.xml"); + Logger logger = LogManager.getLogger("org.apache.test.TestConfigurator"); + LoggerContext ctx = (LoggerContext) LogManager.getContext(false); + Configuration config = ctx.getConfiguration(); + assertNotNull("No configuration", config); + assertTrue("Incorrect Configuration. Expected " + CONFIG_NAME + " but found " + config.getName(), + CONFIG_NAME.equals(config.getName())); + Map map = config.getAppenders(); + assertNotNull("No Appenders", map != null && map.size() > 0); + assertTrue("Wrong configuration", map.containsKey("List")); + + Thread.sleep(500); + file.setLastModified(System.currentTimeMillis()); + for (int i = 0; i < 17; ++i) { + logger.debug("Test message " + i); + } + Configuration newConfig = ctx.getConfiguration(); + assertTrue("Configuration not reset", newConfig != config); + Configurator.shutdown(); + config = ctx.getConfiguration(); + assertTrue("Incorrect Configuration. Expected " + DefaultConfiguration.DEFAULT_NAME + " but found " + + config.getName(), DefaultConfiguration.DEFAULT_NAME.equals(config.getName())); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `map` last assigned on line 87 could be null and is dereferenced at line 89. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestConfigurator.testByName() + +### Procedure Id: +org.apache.logging.log4j.core.config.TestConfigurator.testByName():void.fb491e8ab3334a466889e7e386db2c03 + +### File: +core/src/test/java/org/apache/logging/log4j/core/config/TestConfigurator.java + +### Key: +TestConfigurator.java|testByName|NULL_DEREFERENCE + +### Node Key: +47a0cb555453391d4b0a0dd6396ca857 + +### Hash: +145eaac0e11932f7f38ede5999ed9a0d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7929/instruction.md b/inferredbugs-7929/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d4d967a5037d366b2ab03f328714e9f485e9c969 --- /dev/null +++ b/inferredbugs-7929/instruction.md @@ -0,0 +1,188 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.logging.log4j.core.appender.rolling.helper; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.channels.FileChannel; + + +/** + * File rename action. + */ +public final class FileRenameAction extends ActionBase { + /** + * Source. + */ + private final File source; + + /** + * Destination. + */ + private final File destination; + + /** + * If true, rename empty files, otherwise delete empty files. + */ + private final boolean renameEmptyFiles; + + /** + * Creates an FileRenameAction. + * + * @param src current file name. + * @param dst new file name. + * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. + */ + public FileRenameAction(final File src, final File dst, boolean renameEmptyFiles) { + source = src; + destination = dst; + this.renameEmptyFiles = renameEmptyFiles; + } + + /** + * Rename file. + * + * @return true if successfully renamed. + */ + public boolean execute() { + return execute(source, destination, renameEmptyFiles); + } + + /** + * Rename file. + * + * @param source current file name. + * @param destination new file name. + * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. + * @return true if successfully renamed. + */ + public static boolean execute(final File source, final File destination, boolean renameEmptyFiles) { + if (renameEmptyFiles || (source.length() > 0)) { + try { + return source.renameTo(destination); + } catch (Exception ex) { + try { + copyFile(source, destination); + return source.delete(); + } catch (IOException iex) { + } + } + } + + return false; + } + + private static void copyFile(final File source, final File destination) throws IOException { + if (!destination.exists()) { + destination.createNewFile(); + } + + FileChannel srcChannel = null; + FileChannel destChannel = null; + try { + srcChannel = new FileInputStream(source).getChannel(); + destChannel = new FileOutputStream(destination).getChannel(); + destChannel.transferFrom(srcChannel, 0, srcChannel.size()); + } + finally { + if(srcChannel != null) { + srcChannel.close(); + } + if (destChannel != null) { + destChannel.close(); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileOutputStream` acquired by call to `FileOutputStream(...)` at line 101 is not released after line 112. +**Note**: potential exception at line 106 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void FileRenameAction.copyFile(File,File) + +### Procedure Id: +org.apache.logging.log4j.core.appender.rolling.helper.FileRenameAction.copyFile(java.io.File,java.io.1468efcd4648ad2016219ad17e114c57 + +### File: +log4j2-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/helper/FileRenameAction.java + +### Key: +FileRenameAction.java|copyFile|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +2df6d96cdfa49960a5642f03e4a5b94d + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7942/instruction.md b/inferredbugs-7942/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cff7fff58741369966b5fd8207b9550b83228a67 --- /dev/null +++ b/inferredbugs-7942/instruction.md @@ -0,0 +1,166 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.apache.logging.log4j.core.filter; + +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.Lifecycle; +import org.apache.logging.log4j.core.LogEvent; + +import java.util.Iterator; + +/** + * + */ +public class Filterable { + private volatile Filters filters = new Filters(null); + private boolean hasFilters; + + public synchronized void addFilter(Filter filter) { + filters = Filters.addFilter(filters, filter); + hasFilters = filters.hasFilters(); + } + + public synchronized void removeFilter(Filter filter) { + filters = Filters.removeFilter(filters, filter); + hasFilters = filters.hasFilters(); + } + + public synchronized void clearFilters() { + filters = new Filters(null); + hasFilters = false; + } + + public Iterator getFilters() { + return filters.iterator(); + } + + public boolean hasFilters() { + return hasFilters; + } + + public int filterCount() { + return filters.size(); + } + + protected void startFilters() { + for (Filter filter : filters) { + if ((filter instanceof Lifecycle)) { + ((Lifecycle)filter).start(); + } + } + } + + protected void stopFilters() { + for (Filter filter : filters) { + if ((filter instanceof Lifecycle)) { + ((Lifecycle)filter).stop(); + } + } + } + + protected synchronized void setFilters(Filters newFilters) { + filters = newFilters == null ? new Filters(null) : newFilters; + hasFilters = filters.hasFilters(); + } + + protected boolean isFiltered(LogEvent event) { + if (hasFilters) { + for (Filter filter : filters) { + if (filter.filter(event) == Filter.Result.DENY) { + return true; + } + } + } + return false; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.logging.log4j.core.filter.Filterable.isFiltered` reads without synchronization from `this.org.apache.logging.log4j.core.filter.Filterable.hasFilters`. Potentially races with write in method `Filterable.setFilters(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean Filterable.isFiltered(LogEvent) + +### Procedure Id: +org.apache.logging.log4j.core.filter.Filterable.isFiltered(org.apache.logging.log4j.core.LogEvent):b.c0a6311caa8896fdf81581cc504b5564 + +### File: +log4j2-core/src/main/java/org/apache/logging/log4j/core/filter/Filterable.java + +### Key: +Filterable.java|isFiltered|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +4197e46bc135732acefcdf38799299c6 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7943/instruction.md b/inferredbugs-7943/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..944d896e215a54b55dc9bc6c45e44cbf4de03f7f --- /dev/null +++ b/inferredbugs-7943/instruction.md @@ -0,0 +1,301 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.apache.logging.log4j.core.appender; + +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.Layout; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginAttr; +import org.apache.logging.log4j.core.config.plugins.PluginElement; +import org.apache.logging.log4j.core.config.plugins.PluginFactory; +import org.apache.logging.log4j.core.helpers.Loader; +import org.apache.logging.log4j.core.layout.PatternLayout; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.lang.reflect.Constructor; + +/** + * ConsoleAppender appends log events to System.out or + * System.err using a layout specified by the user. The + * default target is System.out. + * @doubt accessing System.out or .err as a byte stream instead of a writer + * bypasses the JVM's knowledge of the proper encoding. (RG) Encoding + * is handled within the Layout. Typically, a Layout will generate a String + * and then call getBytes which may use a configured encoding or the system + * default. OTOH, a Writer cannot print byte streams. + */ +@Plugin(name = "Console", type = "Core", elementType = "appender", printObject = true) +public final class ConsoleAppender extends AbstractOutputStreamAppender { + + private static ConsoleManagerFactory factory = new ConsoleManagerFactory(); + + /** + * Enumeration of console destinations. + */ + public enum Target { + /** Standard output. */ + SYSTEM_OUT, + /** Standard error output. */ + SYSTEM_ERR + } + + private ConsoleAppender(final String name, final Layout layout, final Filter filter, final OutputStreamManager manager, + final boolean handleExceptions) { + super(name, layout, filter, handleExceptions, true, manager); + } + + /** + * Create a Console Appender. + * @param layout The layout to use (required). + * @param filter The Filter or null. + * @param t The target ("SYSTEM_OUT" or "SYSTEM_ERR"). The default is "SYSTEM_OUT". + * @param name The name of the Appender (required). + * @param suppress "true" if exceptions should be hidden from the application, "false" otherwise. + * The default is "true". + * @return The ConsoleAppender. + */ + @PluginFactory + public static ConsoleAppender createAppender(@PluginElement("layout") Layout layout, + @PluginElement("filters") final Filter filter, + @PluginAttr("target") final String t, + @PluginAttr("name") final String name, + @PluginAttr("follow") final String follow, + @PluginAttr("suppressExceptions") final String suppress) { + if (name == null) { + LOGGER.error("No name provided for ConsoleAppender"); + return null; + } + if (layout == null) { + layout = PatternLayout.createLayout(null, null, null, null); + } + final boolean isFollow = follow == null ? false : Boolean.valueOf(follow); + final boolean handleExceptions = suppress == null ? true : Boolean.valueOf(suppress); + final Target target = t == null ? Target.SYSTEM_OUT : Target.valueOf(t); + return new ConsoleAppender(name, layout, filter, getManager(isFollow, target), handleExceptions); + } + + private static OutputStreamManager getManager(final boolean follow, final Target target) { + final String type = target.name(); + final OutputStream os = getOutputStream(follow, target); + return OutputStreamManager.getManager(target.name() + "." + follow, new FactoryData(os, type), factory); + } + + private static OutputStream getOutputStream(final boolean follow, final Target target) { + final PrintStream printStream = target == Target.SYSTEM_OUT ? + follow ? new PrintStream(new SystemOutStream()) : System.out : + follow ? new PrintStream(new SystemErrStream()) : System.err; + if (!System.getProperty("os.name").startsWith("Windows") || Boolean.getBoolean("log4j.skipJansi")) { + return printStream; + } else { + try { + final ClassLoader loader = Loader.getClassLoader(); + // We type the parameter as a wildcard to avoid a hard reference to Jansi. + final Class clazz = loader.loadClass("org.fusesource.jansi.WindowsAnsiOutputStream"); + final Constructor constructor = clazz.getConstructor(OutputStream.class); + return (OutputStream) constructor.newInstance(printStream); + } catch (final ClassNotFoundException cnfe) { + LOGGER.debug("Jansi is not installed"); + } catch (final NoSuchMethodException nsme) { + LOGGER.warn("WindowsAnsiOutputStream is missing the proper constructor"); + } catch (final Exception ex) { + LOGGER.warn("Unable to instantiate WindowsAnsiOutputStream"); + } + return printStream; + } + } + + /** + * An implementation of OutputStream that redirects to the + * current System.err. + * + */ + private static class SystemErrStream extends OutputStream { + public SystemErrStream() { + } + + @Override + public void close() { + } + + @Override + public void flush() { + System.err.flush(); + } + + @Override + public void write(final byte[] b) throws IOException { + System.err.write(b); + } + + @Override + public void write(final byte[] b, final int off, final int len) + throws IOException { + System.err.write(b, off, len); + } + + @Override + public void write(final int b) { + System.err.write(b); + } + } + + /** + * An implementation of OutputStream that redirects to the + * current System.out. + * + */ + private static class SystemOutStream extends OutputStream { + public SystemOutStream() { + } + + @Override + public void close() { + } + + @Override + public void flush() { + System.out.flush(); + } + + @Override + public void write(final byte[] b) throws IOException { + System.out.write(b); + } + + @Override + public void write(final byte[] b, final int off, final int len) + throws IOException { + System.out.write(b, off, len); + } + + @Override + public void write(final int b) throws IOException { + System.out.write(b); + } + } + + /** + * Data to pass to factory method. + */ + private static class FactoryData { + private final OutputStream os; + private final String type; + + /** + * Constructor. + * @param os The OutputStream. + * @param type The name of the target. + */ + public FactoryData(final OutputStream os, final String type) { + this.os = os; + this.type = type; + } + } + + /** + * Factory to create the Appender. + */ + private static class ConsoleManagerFactory implements ManagerFactory { + + /** + * Create an OutputStreamManager. + * @param name The name of the entity to manage. + * @param data The data required to create the entity. + * @return The OutputStreamManager + */ + public OutputStreamManager createManager(final String name, final FactoryData data) { + return new OutputStreamManager(data.os, data.type); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PrintStream` acquired to `printStream` by call to `new()` at line 100 is not released after line 111. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +OutputStream ConsoleAppender.getOutputStream(boolean,ConsoleAppender$Target) + +### Procedure Id: +org.apache.logging.log4j.core.appender.ConsoleAppender.getOutputStream(boolean,org.apache.logging.lo.8f89f2e850d3c9643f2d7c59a88171be + +### File: +core/src/main/java/org/apache/logging/log4j/core/appender/ConsoleAppender.java + +### Key: +ConsoleAppender.java|getOutputStream|RESOURCE_LEAK + +### Node Key: +8467886b3d9399dca647a30e4635bfca + +### Hash: +0d201ffa5006de3a3e34c3f8de38720c + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7944/instruction.md b/inferredbugs-7944/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6cfefbb49e5f9206ddea39ea8abb217675063ee2 --- /dev/null +++ b/inferredbugs-7944/instruction.md @@ -0,0 +1,435 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.apache.log4j; + +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.helpers.NameUtil; +import org.apache.logging.log4j.message.LocalizedMessage; +import org.apache.logging.log4j.message.Message; +import org.apache.logging.log4j.message.ObjectMessage; + +import java.util.Map; +import java.util.ResourceBundle; +import java.util.WeakHashMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + + +/** + * Implementation of the Category class for compatibility, despite it having been deprecated a long, long time ago. + */ +public class Category { + + private static org.apache.log4j.LoggerFactory loggerFactory = new PrivateFactory(); + + private static final Map> CONTEXT_MAP = + new WeakHashMap>(); + + private static final String FQCN = Category.class.getName(); + + /** + * Resource bundle for localized messages. + */ + protected ResourceBundle bundle = null; + + private final org.apache.logging.log4j.core.Logger logger; + + /** + * Constructor used by Logger to specify a LoggerContext. + * @param context The LoggerContext. + * @param name The name of the Logger. + */ + protected Category(LoggerContext context, String name) { + this.logger = context.getLogger(name); + } + + /** + * Constructor exposed by Log4j 1.2. + * @param name The name of the Logger. + */ + protected Category(String name) { + this((LoggerContext) PrivateManager.getContext(), name); + } + + private Category(org.apache.logging.log4j.core.Logger logger) { + this.logger = logger; + } + + public static Category getInstance(String name) { + return getInstance((LoggerContext) PrivateManager.getContext(), name, loggerFactory); + } + + static Category getInstance(LoggerContext context, String name) { + return getInstance(context, name, loggerFactory); + } + + static Category getInstance(LoggerContext context, String name, org.apache.log4j.LoggerFactory factory) { + ConcurrentMap loggers = getLoggersMap(context); + Logger logger = loggers.get(name); + if (logger != null) { + return logger; + } + logger = factory.makeNewLoggerInstance(context, name); + Logger prev = loggers.putIfAbsent(name, logger); + return prev == null ? logger : prev; + } + + public static Category getInstance(Class clazz) { + return getInstance(clazz.getName()); + } + + static Category getInstance(LoggerContext context, Class clazz) { + return getInstance(context, clazz.getName()); + } + + public final String getName() { + return logger.getName(); + } + + org.apache.logging.log4j.core.Logger getLogger() { + return logger; + } + + public final Category getParent() { + org.apache.logging.log4j.core.Logger parent = logger.getParent(); + if (parent == null) { + return null; + } + ConcurrentMap loggers = getLoggersMap(logger.getContext()); + Logger l = loggers.get(parent.getName()); + return l == null ? new Category(parent) : l; + } + + public static Category getRoot() { + return getInstance(""); + } + + + static Category getRoot(LoggerContext context) { + return getInstance(context, ""); + } + + private static ConcurrentMap getLoggersMap(LoggerContext context) { + synchronized (CONTEXT_MAP) { + ConcurrentMap map = CONTEXT_MAP.get(context); + if (map == null) { + map = new ConcurrentHashMap(); + CONTEXT_MAP.put(context, map); + } + return map; + } + } + + public final Level getEffectiveLevel() { + org.apache.logging.log4j.Level level = logger.getLevel(); + + switch (level) { + case TRACE: + return Level.TRACE; + case DEBUG: + return Level.DEBUG; + case INFO: + return Level.INFO; + case WARN: + return Level.WARN; + default: + return Level.ERROR; + } + } + + public final Priority getChainedPriority() { + return getEffectiveLevel(); + } + + public final Level getLevel() { + return getEffectiveLevel(); + } + + public void setLevel(Level level) { + logger.setLevel(org.apache.logging.log4j.Level.toLevel(level.levelStr)); + } + + public final Level getPriority() { + return getEffectiveLevel(); + } + + public void setPriority(Priority priority) { + logger.setLevel(org.apache.logging.log4j.Level.toLevel(priority.levelStr)); + } + + public void debug(Object message) { + maybeLog(FQCN, org.apache.logging.log4j.Level.DEBUG, message, null); + } + + public void debug(Object message, Throwable t) { + maybeLog(FQCN, org.apache.logging.log4j.Level.DEBUG, message, t); + } + + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + public void error(Object message) { + maybeLog(FQCN, org.apache.logging.log4j.Level.ERROR, message, null); + } + + public void error(Object message, Throwable t) { + maybeLog(FQCN, org.apache.logging.log4j.Level.ERROR, message, t); + } + + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } + + public void warn(Object message) { + maybeLog(FQCN, org.apache.logging.log4j.Level.WARN, message, null); + } + + public void warn(Object message, Throwable t) { + maybeLog(FQCN, org.apache.logging.log4j.Level.WARN, message, t); + } + + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + public void fatal(Object message) { + maybeLog(FQCN, org.apache.logging.log4j.Level.FATAL, message, null); + } + + public void fatal(Object message, Throwable t) { + maybeLog(FQCN, org.apache.logging.log4j.Level.FATAL, message, t); + } + + public boolean isFatalEnabled() { + return logger.isFatalEnabled(); + } + + public void info(Object message) { + maybeLog(FQCN, org.apache.logging.log4j.Level.INFO, message, null); + } + + public void info(Object message, Throwable t) { + maybeLog(FQCN, org.apache.logging.log4j.Level.INFO, message, t); + } + + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + public void trace(Object message) { + maybeLog(FQCN, org.apache.logging.log4j.Level.TRACE, message, null); + } + + public void trace(Object message, Throwable t) { + maybeLog(FQCN, org.apache.logging.log4j.Level.TRACE, message, t); + } + + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + public boolean isEnabledFor(Priority level) { + org.apache.logging.log4j.Level lvl = org.apache.logging.log4j.Level.toLevel(level.toString()); + return isEnabledFor(lvl); + } + + public void forcedLog(String fqcn, Priority level, Object message, Throwable t) { + org.apache.logging.log4j.Level lvl = org.apache.logging.log4j.Level.toLevel(level.toString()); + logger.log(null, fqcn, lvl, new ObjectMessage(message), t); + } + + public boolean exists(String name) { + return PrivateManager.getContext().hasLogger(name); + } + + public boolean getAdditivity() { + return logger.isAdditive(); + } + + public void setAdditivity(boolean additivity) { + logger.setAdditive(additivity); + } + + public void setResourceBundle(ResourceBundle bundle) { + this.bundle = bundle; + } + + public ResourceBundle getResourceBundle() { + if (bundle != null) { + return bundle; + } + int i = 0; + String name = logger.getName(); + ConcurrentMap loggers = getLoggersMap(logger.getContext()); + while ((name = NameUtil.getSubName(name)) != null) { + if (loggers.containsKey(name)) { + ResourceBundle rb = loggers.get(name).bundle; + if (rb != null) { + return rb; + } + } + } + return null; + } + + public void l7dlog(Priority priority, String key, Throwable t) { + if (isEnabledFor(priority)) { + Message msg = new LocalizedMessage(bundle, key, null); + forcedLog(FQCN, priority, msg, t); + } + } + + public void l7dlog(Priority priority, String key, Object[] params, Throwable t) { + if (isEnabledFor(priority)) { + Message msg = new LocalizedMessage(bundle, key, params); + forcedLog(FQCN, priority, msg, t); + } + } + + public void log(Priority priority, Object message, Throwable t) { + if (isEnabledFor(priority)) { + Message msg = new ObjectMessage(message); + forcedLog(FQCN, priority, msg, t); + } + } + + public void log(Priority priority, Object message) { + if (isEnabledFor(priority)) { + Message msg = new ObjectMessage(message); + forcedLog(FQCN, priority, msg, null); + } + } + + public void log(String fqcn, Priority priority, Object message, Throwable t) { + if (isEnabledFor(priority)) { + Message msg = new ObjectMessage(message); + forcedLog(fqcn, priority, msg, t); + } + } + + private void maybeLog(String fqcn, org.apache.logging.log4j.Level level, + Object message, Throwable throwable) { + if (logger.isEnabled(level, null, message, throwable)) { + logger.log(null, FQCN, level, new ObjectMessage(message), throwable); + } + } + + /** + * Private logger factory. + */ + private static class PrivateFactory implements org.apache.log4j.LoggerFactory { + + public Logger makeNewLoggerInstance(LoggerContext context, String name) { + return new Logger(context, name); + } + } + + /** + * Private LogManager. + */ + private static class PrivateManager extends org.apache.logging.log4j.LogManager { + private static final String FQCN = Category.class.getName(); + + public static org.apache.logging.log4j.spi.LoggerContext getContext() { + return getContext(FQCN, false); + } + + public static org.apache.logging.log4j.Logger getLogger(String name) { + return getLogger(FQCN, name); + } + } + + private boolean isEnabledFor(org.apache.logging.log4j.Level level) { + return logger.isEnabled(level, null, null); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `level.toString()` could be null and is dereferenced at line 253. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Category.forcedLog(String,Priority,Object,Throwable) + +### Procedure Id: +org.apache.log4j.Category.forcedLog(java.lang.String,org.apache.log4j.Priority,java.lang.Object,java.0736ed27313e681786e76a65a91e1125 + +### File: +log4j12-api/src/main/java/org/apache/log4j/Category.java + +### Key: +Category.java|forcedLog|NULL_DEREFERENCE + +### Node Key: +7e85dd3f92a796473a4393e5d5562e7a + +### Hash: +0181f83760e2618c90019c79133e20a6 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7972/instruction.md b/inferredbugs-7972/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f7fb4376a999185a00a438cbdef02b7d354d0e7e --- /dev/null +++ b/inferredbugs-7972/instruction.md @@ -0,0 +1,378 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** YCSB +**Bug ID:** 23 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) 2016 YCSB contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You + * may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. See accompanying + * LICENSE file. + */ + +package com.yahoo.ycsb.workloads; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import com.yahoo.ycsb.ByteIterator; +import com.yahoo.ycsb.DB; +import com.yahoo.ycsb.RandomByteIterator; +import com.yahoo.ycsb.WorkloadException; +import com.yahoo.ycsb.generator.DiscreteGenerator; +import com.yahoo.ycsb.generator.ExponentialGenerator; +import com.yahoo.ycsb.generator.HotspotIntegerGenerator; +import com.yahoo.ycsb.generator.NumberGenerator; +import com.yahoo.ycsb.generator.UniformIntegerGenerator; +import com.yahoo.ycsb.generator.ZipfianGenerator; + +/** + * Typical RESTFul services benchmarking scenario. Represents a set of client + * calling REST operations like HTTP DELETE, GET, POST, PUT on a web service. + * This scenario is completely different from CoreWorkload which is mainly + * designed for databases benchmarking. However due to some reusable + * functionality this class extends {@link CoreWorkload} and overrides necessary + * methods like init, doTransaction etc. + */ +public class RestWorkload extends CoreWorkload { + + /** + * The name of the property for the proportion of transactions that are + * delete. + */ + public static final String DELETE_PROPORTION_PROPERTY = "deleteproportion"; + + /** + * The default proportion of transactions that are delete. + */ + public static final String DELETE_PROPORTION_PROPERTY_DEFAULT = "0.00"; + + /** + * The name of the property for the file that holds the field length size for insert operations. + */ + public static final String FIELD_LENGTH_DISTRIBUTION_FILE_PROPERTY = "fieldlengthdistfile"; + + /** + * The default file name that holds the field length size for insert operations. + */ + public static final String FIELD_LENGTH_DISTRIBUTION_FILE_PROPERTY_DEFAULT = "fieldLengthDistFile.txt"; + + /** + * In web services even though the CRUD operations follow the same request + * distribution, they have different traces and distribution parameter + * values. Hence configuring the parameters of these operations separately + * makes the benchmark more flexible and capable of generating better + * realistic workloads. + */ + // Read related properties. + private static final String READ_TRACE_FILE = "url.trace.read"; + private static final String READ_TRACE_FILE_DEFAULT = "readtrace.txt"; + private static final String READ_ZIPFIAN_CONSTANT = "readzipfconstant"; + private static final String READ_ZIPFIAN_CONSTANT_DEAFULT = "0.99"; + private static final String READ_RECORD_COUNT_PROPERTY = "readrecordcount"; + // Insert related properties. + private static final String INSERT_TRACE_FILE = "url.trace.insert"; + private static final String INSERT_TRACE_FILE_DEFAULT = "inserttrace.txt"; + private static final String INSERT_ZIPFIAN_CONSTANT = "insertzipfconstant"; + private static final String INSERT_ZIPFIAN_CONSTANT_DEAFULT = "0.99"; + private static final String INSERT_SIZE_ZIPFIAN_CONSTANT = "insertsizezipfconstant"; + private static final String INSERT_SIZE_ZIPFIAN_CONSTANT_DEAFULT = "0.99"; + private static final String INSERT_RECORD_COUNT_PROPERTY = "insertrecordcount"; + // Delete related properties. + private static final String DELETE_TRACE_FILE = "url.trace.delete"; + private static final String DELETE_TRACE_FILE_DEFAULT = "deletetrace.txt"; + private static final String DELETE_ZIPFIAN_CONSTANT = "deletezipfconstant"; + private static final String DELETE_ZIPFIAN_CONSTANT_DEAFULT = "0.99"; + private static final String DELETE_RECORD_COUNT_PROPERTY = "deleterecordcount"; + // Delete related properties. + private static final String UPDATE_TRACE_FILE = "url.trace.update"; + private static final String UPDATE_TRACE_FILE_DEFAULT = "updatetrace.txt"; + private static final String UPDATE_ZIPFIAN_CONSTANT = "updatezipfconstant"; + private static final String UPDATE_ZIPFIAN_CONSTANT_DEAFULT = "0.99"; + private static final String UPDATE_RECORD_COUNT_PROPERTY = "updaterecordcount"; + + private Map readUrlMap; + private Map insertUrlMap; + private Map deleteUrlMap; + private Map updateUrlMap; + private int readRecordCount; + private int insertRecordCount; + private int deleteRecordCount; + private int updateRecordCount; + private NumberGenerator readKeyChooser; + private NumberGenerator insertKeyChooser; + private NumberGenerator deleteKeyChooser; + private NumberGenerator updateKeyChooser; + + @Override + public void init(Properties p) throws WorkloadException { + + readRecordCount = Integer.parseInt(p.getProperty(READ_RECORD_COUNT_PROPERTY, String.valueOf(Integer.MAX_VALUE))); + insertRecordCount = Integer + .parseInt(p.getProperty(INSERT_RECORD_COUNT_PROPERTY, String.valueOf(Integer.MAX_VALUE))); + deleteRecordCount = Integer + .parseInt(p.getProperty(DELETE_RECORD_COUNT_PROPERTY, String.valueOf(Integer.MAX_VALUE))); + updateRecordCount = Integer + .parseInt(p.getProperty(UPDATE_RECORD_COUNT_PROPERTY, String.valueOf(Integer.MAX_VALUE))); + + readUrlMap = getTrace(p.getProperty(READ_TRACE_FILE, READ_TRACE_FILE_DEFAULT), readRecordCount); + insertUrlMap = getTrace(p.getProperty(INSERT_TRACE_FILE, INSERT_TRACE_FILE_DEFAULT), insertRecordCount); + deleteUrlMap = getTrace(p.getProperty(DELETE_TRACE_FILE, DELETE_TRACE_FILE_DEFAULT), deleteRecordCount); + updateUrlMap = getTrace(p.getProperty(UPDATE_TRACE_FILE, UPDATE_TRACE_FILE_DEFAULT), updateRecordCount); + + operationchooser = createOperationGenerator(p); + + // Common distribution for all operations. + String requestDistrib = p.getProperty(REQUEST_DISTRIBUTION_PROPERTY, REQUEST_DISTRIBUTION_PROPERTY_DEFAULT); + + double readZipfconstant = Double + .parseDouble(p.getProperty(READ_ZIPFIAN_CONSTANT, READ_ZIPFIAN_CONSTANT_DEAFULT)); + readKeyChooser = getKeyChooser(requestDistrib, readUrlMap.size(), readZipfconstant, p); + double updateZipfconstant = Double + .parseDouble(p.getProperty(UPDATE_ZIPFIAN_CONSTANT, UPDATE_ZIPFIAN_CONSTANT_DEAFULT)); + updateKeyChooser = getKeyChooser(requestDistrib, updateUrlMap.size(), updateZipfconstant, p); + double insertZipfconstant = Double + .parseDouble(p.getProperty(INSERT_ZIPFIAN_CONSTANT, INSERT_ZIPFIAN_CONSTANT_DEAFULT)); + insertKeyChooser = getKeyChooser(requestDistrib, insertUrlMap.size(), insertZipfconstant, p); + double deleteZipfconstant = Double + .parseDouble(p.getProperty(DELETE_ZIPFIAN_CONSTANT, DELETE_ZIPFIAN_CONSTANT_DEAFULT)); + deleteKeyChooser = getKeyChooser(requestDistrib, deleteUrlMap.size(), deleteZipfconstant, p); + + fieldlengthgenerator = getFieldLengthGenerator(p); + } + + public static DiscreteGenerator createOperationGenerator(final Properties p) { + // Re-using CoreWorkload method. + final DiscreteGenerator operationChooser = CoreWorkload.createOperationGenerator(p); + // Needs special handling for delete operations not supported in CoreWorkload. + double deleteproportion = Double + .parseDouble(p.getProperty(DELETE_PROPORTION_PROPERTY, DELETE_PROPORTION_PROPERTY_DEFAULT)); + if (deleteproportion > 0) + operationChooser.addValue(deleteproportion, "DELETE"); + return operationChooser; + } + + private static NumberGenerator getKeyChooser(String requestDistrib, int recordCount, double zipfContant, + Properties p) throws WorkloadException { + NumberGenerator keychooser = null; + + switch(requestDistrib) { + case "exponential": + double percentile = Double.parseDouble(p.getProperty(ExponentialGenerator.EXPONENTIAL_PERCENTILE_PROPERTY, + ExponentialGenerator.EXPONENTIAL_PERCENTILE_DEFAULT)); + double frac = Double.parseDouble(p.getProperty(ExponentialGenerator.EXPONENTIAL_FRAC_PROPERTY, + ExponentialGenerator.EXPONENTIAL_FRAC_DEFAULT)); + keychooser = new ExponentialGenerator(percentile, recordCount * frac); + break; + case "uniform": + keychooser = new UniformIntegerGenerator(0, recordCount - 1); + break; + case "zipfian": + keychooser = new ZipfianGenerator(recordCount, zipfContant); + break; + case "latest": + throw new WorkloadException("Latest request distribution is not supported for RestWorkload."); + case "hotspot": + double hotsetfraction = Double + .parseDouble(p.getProperty(HOTSPOT_DATA_FRACTION, HOTSPOT_DATA_FRACTION_DEFAULT)); + double hotopnfraction = Double + .parseDouble(p.getProperty(HOTSPOT_OPN_FRACTION, HOTSPOT_OPN_FRACTION_DEFAULT)); + keychooser = new HotspotIntegerGenerator(0, recordCount - 1, hotsetfraction, hotopnfraction); + break; + default: + throw new WorkloadException("Unknown request distribution \"" + requestDistrib + "\""); + } + return keychooser; + } + + protected static NumberGenerator getFieldLengthGenerator(Properties p) throws WorkloadException { + // Re-using CoreWorkload method. + NumberGenerator fieldLengthGenerator = CoreWorkload.getFieldLengthGenerator(p); + String fieldlengthdistribution = p.getProperty( + FIELD_LENGTH_DISTRIBUTION_PROPERTY, FIELD_LENGTH_DISTRIBUTION_PROPERTY_DEFAULT); + // Needs special handling for Zipfian distribution for variable Zipf Constant. + if (fieldlengthdistribution.compareTo("zipfian") == 0) { + int fieldlength = + Integer.parseInt(p.getProperty(FIELD_LENGTH_PROPERTY, FIELD_LENGTH_PROPERTY_DEFAULT)); + double insertsizezipfconstant = Double + .parseDouble(p.getProperty(INSERT_SIZE_ZIPFIAN_CONSTANT, INSERT_SIZE_ZIPFIAN_CONSTANT_DEAFULT)); + fieldLengthGenerator = new ZipfianGenerator(1, fieldlength, insertsizezipfconstant); + } + return fieldLengthGenerator; + } + + /** + * Reads the trace file and returns a URL map. + */ + private static Map getTrace(String filePath, int recordCount) + throws WorkloadException { + Map urlMap = new HashMap(); + int count = 0; + String line; + try { + FileReader inputFile = new FileReader(filePath); + BufferedReader bufferReader = new BufferedReader(inputFile); + while ((line = bufferReader.readLine()) != null) { + urlMap.put(count++, line.trim()); + if (count >= recordCount) + break; + } + bufferReader.close(); + } catch (IOException e) { + throw new WorkloadException( + "Error while reading the trace. Please make sure the trace file path is correct. " + + e.getLocalizedMessage()); + } + return urlMap; + } + + /** + * Not required for Rest Clients as data population is service specific. + */ + @Override + public boolean doInsert(DB db, Object threadstate) { + return false; + } + + @Override + public boolean doTransaction(DB db, Object threadstate) { + switch (operationchooser.nextString()) { + case "UPDATE": + doTransactionUpdate(db); + break; + case "INSERT": + doTransactionInsert(db); + break; + case "DELETE": + doTransactionDelete(db); + break; + default: + doTransactionRead(db); + } + return true; + } + + /** + * Returns next URL to be called. + */ + private String getNextURL(int opType) { + if (opType == 1) + return readUrlMap.get(readKeyChooser.nextValue().intValue()); + else if (opType == 2) + return insertUrlMap.get(insertKeyChooser.nextValue().intValue()); + else if (opType == 3) + return deleteUrlMap.get(deleteKeyChooser.nextValue().intValue()); + else + return updateUrlMap.get(updateKeyChooser.nextValue().intValue()); + } + + @Override + public void doTransactionRead(DB db) { + HashMap result = new HashMap(); + db.read(null, getNextURL(1), null, result); + } + + @Override + public void doTransactionInsert(DB db) { + HashMap value = new HashMap(); + // Create random bytes of insert data with a specific size. + value.put("data", new RandomByteIterator(fieldlengthgenerator.nextValue().longValue())); + db.insert(null, getNextURL(2), value); + } + + public void doTransactionDelete(DB db) { + db.delete(null, getNextURL(3)); + } + + @Override + public void doTransactionUpdate(DB db) { + HashMap value = new HashMap(); + // Create random bytes of update data with a specific size. + value.put("data", new RandomByteIterator(fieldlengthgenerator.nextValue().longValue())); + db.update(null, getNextURL(4), value); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `CoreWorkload.operationchooser.nextString()` could be null and is dereferenced at line 248. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean RestWorkload.doTransaction(DB,Object) + +### Procedure Id: +com.yahoo.ycsb.workloads.RestWorkload.doTransaction(com.yahoo.ycsb.DB,java.lang.Object):boolean.98f86525aeaa84452d351900674ee5ac + +### File: +core/src/main/java/com/yahoo/ycsb/workloads/RestWorkload.java + +### Key: +RestWorkload.java|doTransaction|NULL_DEREFERENCE + +### Node Key: +7bd17c1126d78fe17b36ab2ac6be1419 + +### Hash: +b6dbb5e6890bb69ae0df9a89b185b102 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7973/instruction.md b/inferredbugs-7973/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..52bc1aa7ea9c0659380f384bfb8ea37882b998c4 --- /dev/null +++ b/inferredbugs-7973/instruction.md @@ -0,0 +1,508 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** YCSB +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * MongoDB client binding for YCSB. + * + * Submitted by Yen Pai on 5/11/2010. + * + * https://gist.github.com/000a66b8db2caf42467b#file_mongo_database.java + * + */ + +package com.yahoo.ycsb.db; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.Vector; +import java.util.concurrent.atomic.AtomicInteger; + +import com.mongodb.client.model.InsertManyOptions; +import org.bson.Document; +import org.bson.types.Binary; + +import com.mongodb.MongoClient; +import com.mongodb.MongoClientURI; +import com.mongodb.ReadPreference; +import com.mongodb.WriteConcern; +import com.mongodb.bulk.BulkWriteResult; +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoCursor; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.BulkWriteOptions; +import com.mongodb.client.model.InsertOneModel; +import com.mongodb.client.model.UpdateOptions; +import com.mongodb.client.result.DeleteResult; +import com.mongodb.client.result.UpdateResult; +import com.yahoo.ycsb.ByteArrayByteIterator; +import com.yahoo.ycsb.ByteIterator; +import com.yahoo.ycsb.DB; +import com.yahoo.ycsb.DBException; + +/** + * MongoDB client for YCSB framework. + * + * Properties to set: + * + * mongodb.url=mongodb://localhost:27017 + * mongodb.writeConcern=acknowledged + * + * @author ypai + */ +public class MongoDbClient extends DB { + + /** Used to include a field in a response. */ + protected static final Integer INCLUDE = Integer.valueOf(1); + + /** The options to use for inserting many documents */ + protected static final InsertManyOptions INSERT_MANY_OPTIONS = + new InsertManyOptions().ordered(false); + + /** + * The database name to access. + */ + private static String databaseName; + + /** The database name to access. */ + private static MongoDatabase database; + + /** + * Count the number of times initialized to teardown on the last + * {@link #cleanup()}. + */ + private static final AtomicInteger initCount = new AtomicInteger(0); + + /** A singleton Mongo instance. */ + private static MongoClient mongoClient; + + /** The default read preference for the test */ + private static ReadPreference readPreference; + + /** The default write concern for the test. */ + private static WriteConcern writeConcern; + + /** The batch size to use for inserts. */ + private static int batchSize; + + /** The bulk inserts pending for the thread. */ + private final List bulkInserts = new ArrayList(); + + /** + * Cleanup any state for this DB. Called once per DB instance; there is one + * DB instance per client thread. + */ + @Override + public void cleanup() throws DBException { + if (initCount.decrementAndGet() == 0) { + try { + mongoClient.close(); + } + catch (Exception e1) { + System.err.println("Could not close MongoDB connection pool: " + + e1.toString()); + e1.printStackTrace(); + return; + } + finally { + database = null; + mongoClient = null; + } + } + } + + /** + * Delete a record from the database. + * + * @param table + * The name of the table + * @param key + * The record key of the record to delete. + * @return Zero on success, a non-zero error code on error. See the + * {@link DB} class's description for a discussion of error codes. + */ + @Override + public int delete(String table, String key) { + try { + MongoCollection collection = database + .getCollection(table); + + Document query = new Document("_id", key); + DeleteResult result = collection.withWriteConcern(writeConcern) + .deleteOne(query); + if (result.wasAcknowledged() && result.getDeletedCount() == 0) { + System.err.println("Nothing deleted for key " + key); + return 1; + } + return 0; + } + catch (Exception e) { + System.err.println(e.toString()); + return 1; + } + } + + /** + * Initialize any state for this DB. Called once per DB instance; there is + * one DB instance per client thread. + */ + @Override + public void init() throws DBException { + initCount.incrementAndGet(); + synchronized (INCLUDE) { + if (mongoClient != null) { + return; + } + + Properties props = getProperties(); + + // Set insert batchsize, default 1 - to be YCSB-original equivalent + batchSize = Integer.parseInt(props.getProperty("batchsize", "1")); + + // Just use the standard connection format URL + // http://docs.mongodb.org/manual/reference/connection-string/ + // to configure the client. + String url = props.getProperty("mongodb.url", null); + boolean defaultedUrl = false; + if (url == null) { + defaultedUrl = true; + url = "mongodb://localhost:27017/ycsb?w=1"; + } + + url = OptionsSupport.updateUrl(url, props); + + if (!url.startsWith("mongodb://")) { + System.err + .println("ERROR: Invalid URL: '" + + url + + "'. Must be of the form " + + "'mongodb://:,:/database?options'. " + + "http://docs.mongodb.org/manual/reference/connection-string/"); + System.exit(1); + } + + try { + MongoClientURI uri = new MongoClientURI(url); + + String uriDb = uri.getDatabase(); + if (!defaultedUrl && (uriDb != null) && !uriDb.isEmpty() + && !"admin".equals(uriDb)) { + databaseName = uriDb; + } + else { + //If no database is specified in URI, use "ycsb" + databaseName = "ycsb"; + + } + + + readPreference = uri.getOptions().getReadPreference(); + writeConcern = uri.getOptions().getWriteConcern(); + + mongoClient = new MongoClient(uri); + database = mongoClient.getDatabase(databaseName); + + System.out.println("mongo client connection created with " + + url); + } + catch (Exception e1) { + System.err + .println("Could not initialize MongoDB connection pool for Loader: " + + e1.toString()); + e1.printStackTrace(); + return; + } + } + } + + /** + * Insert a record in the database. Any field/value pairs in the specified + * values HashMap will be written into the record with the specified record + * key. + * + * @param table + * The name of the table + * @param key + * The record key of the record to insert. + * @param values + * A HashMap of field/value pairs to insert in the record + * @return Zero on success, a non-zero error code on error. See the + * {@link DB} class's description for a discussion of error codes. + */ + @Override + public int insert(String table, String key, + HashMap values) { + try { + MongoCollection collection = database + .getCollection(table); + Document toInsert = new Document("_id", key); + for (Map.Entry entry : values.entrySet()) { + toInsert.put(entry.getKey(), entry.getValue().toArray()); + } + + bulkInserts.add(toInsert); + if (bulkInserts.size() == batchSize) { + collection.withWriteConcern(writeConcern) + .insertMany(bulkInserts, INSERT_MANY_OPTIONS); + bulkInserts.clear(); + } + return 0; + } + catch (Exception e) { + System.err.println("Exception while trying bulk insert with " + + bulkInserts.size()); + e.printStackTrace(); + return 1; + } + + } + + /** + * Read a record from the database. Each field/value pair from the result + * will be stored in a HashMap. + * + * @param table + * The name of the table + * @param key + * The record key of the record to read. + * @param fields + * The list of fields to read, or null for all of them + * @param result + * A HashMap of field/value pairs for the result + * @return Zero on success, a non-zero error code on error or "not found". + */ + @Override + public int read(String table, String key, Set fields, + HashMap result) { + try { + MongoCollection collection = database + .getCollection(table); + Document query = new Document("_id", key); + + FindIterable findIterable = collection + .withReadPreference(readPreference) + .find(query); + + Document queryResult = null; + if (fields != null) { + Document projection = new Document(); + for (String field : fields) { + projection.put(field, INCLUDE); + } + findIterable.projection(projection); + } + + queryResult = findIterable.first(); + + if (queryResult != null) { + fillMap(result, queryResult); + } + return queryResult != null ? 0 : 1; + } + catch (Exception e) { + System.err.println(e.toString()); + return 1; + } + } + + /** + * Perform a range scan for a set of records in the database. Each + * field/value pair from the result will be stored in a HashMap. + * + * @param table + * The name of the table + * @param startkey + * The record key of the first record to read. + * @param recordcount + * The number of records to read + * @param fields + * The list of fields to read, or null for all of them + * @param result + * A Vector of HashMaps, where each HashMap is a set field/value + * pairs for one record + * @return Zero on success, a non-zero error code on error. See the + * {@link DB} class's description for a discussion of error codes. + */ + @Override + public int scan(String table, String startkey, int recordcount, + Set fields, Vector> result) { + MongoCursor cursor = null; + try { + MongoCollection collection = database + .getCollection(table); + + Document scanRange = new Document("$gte", startkey); + Document query = new Document("_id", scanRange); + Document sort = new Document("_id", INCLUDE); + Document projection = null; + if (fields != null) { + projection = new Document(); + for (String fieldName : fields) { + projection.put(fieldName, INCLUDE); + } + } + + cursor = collection.withReadPreference(readPreference).find(query) + .projection(projection).sort(sort).limit(recordcount).iterator(); + if (!cursor.hasNext()) { + System.err.println("Nothing found in scan for key " + startkey); + return 1; + } + while (cursor.hasNext()) { + HashMap resultMap = new HashMap(); + + Document obj = cursor.next(); + fillMap(resultMap, obj); + + result.add(resultMap); + } + + return 0; + } + catch (Exception e) { + System.err.println(e.toString()); + return 1; + } + finally { + if (cursor != null) { + cursor.close(); + } + } + } + + /** + * Update a record in the database. Any field/value pairs in the specified + * values HashMap will be written into the record with the specified record + * key, overwriting any existing values with the same field name. + * + * @param table + * The name of the table + * @param key + * The record key of the record to write. + * @param values + * A HashMap of field/value pairs to update in the record + * @return Zero on success, a non-zero error code on error. See this class's + * description for a discussion of error codes. + */ + @Override + public int update(String table, String key, + HashMap values) { + try { + MongoCollection collection = database + .getCollection(table); + + Document query = new Document("_id", key); + Document fieldsToSet = new Document(); + for (Map.Entry entry : values.entrySet()) { + fieldsToSet.put(entry.getKey(), entry.getValue().toArray()); + } + Document update = new Document("$set", fieldsToSet); + + UpdateResult result = collection.withWriteConcern(writeConcern) + .updateOne(query, update); + if (result.wasAcknowledged() && result.getMatchedCount() == 0) { + System.err.println("Nothing updated for key " + key); + return 1; + } + return 0; + } + catch (Exception e) { + System.err.println(e.toString()); + return 1; + } + } + + /** + * Fills the map with the values from the DBObject. + * + * @param resultMap + * The map to fill/ + * @param obj + * The object to copy values from. + */ + protected void fillMap(HashMap resultMap, Document obj) { + for (Map.Entry entry : obj.entrySet()) { + if (entry.getValue() instanceof Binary) { + resultMap.put(entry.getKey(), new ByteArrayByteIterator( + ((Binary) entry.getValue()).getData())); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.yahoo.ycsb.db.MongoDbClient.scan` reads without synchronization from `db.MongoDbClient.com.yahoo.ycsb.db.MongoDbClient.readPreference`. Potentially races with write in method `MongoDbClient.init()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int MongoDbClient.scan(String,String,int,Set,Vector) + +### Procedure Id: +com.yahoo.ycsb.db.MongoDbClient.scan(java.lang.String,java.lang.String,int,java.util.Set,java.util.V.d73ab9ae2d8995ac49284245957f32f3 + +### File: +mongodb/src/main/java/com/yahoo/ycsb/db/MongoDbClient.java + +### Key: +MongoDbClient.java|scan|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +41b8524d14faec78babc2f5840378351 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7975/instruction.md b/inferredbugs-7975/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5fbc83664d22c30a83bace9502f9f93fb8ee3814 --- /dev/null +++ b/inferredbugs-7975/instruction.md @@ -0,0 +1,508 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** YCSB +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * MongoDB client binding for YCSB. + * + * Submitted by Yen Pai on 5/11/2010. + * + * https://gist.github.com/000a66b8db2caf42467b#file_mongo_database.java + * + */ + +package com.yahoo.ycsb.db; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.Vector; +import java.util.concurrent.atomic.AtomicInteger; + +import com.mongodb.client.model.InsertManyOptions; +import org.bson.Document; +import org.bson.types.Binary; + +import com.mongodb.MongoClient; +import com.mongodb.MongoClientURI; +import com.mongodb.ReadPreference; +import com.mongodb.WriteConcern; +import com.mongodb.bulk.BulkWriteResult; +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoCursor; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.BulkWriteOptions; +import com.mongodb.client.model.InsertOneModel; +import com.mongodb.client.model.UpdateOptions; +import com.mongodb.client.result.DeleteResult; +import com.mongodb.client.result.UpdateResult; +import com.yahoo.ycsb.ByteArrayByteIterator; +import com.yahoo.ycsb.ByteIterator; +import com.yahoo.ycsb.DB; +import com.yahoo.ycsb.DBException; + +/** + * MongoDB client for YCSB framework. + * + * Properties to set: + * + * mongodb.url=mongodb://localhost:27017 + * mongodb.writeConcern=acknowledged + * + * @author ypai + */ +public class MongoDbClient extends DB { + + /** Used to include a field in a response. */ + protected static final Integer INCLUDE = Integer.valueOf(1); + + /** The options to use for inserting many documents */ + protected static final InsertManyOptions INSERT_MANY_OPTIONS = + new InsertManyOptions().ordered(false); + + /** + * The database name to access. + */ + private static String databaseName; + + /** The database name to access. */ + private static MongoDatabase database; + + /** + * Count the number of times initialized to teardown on the last + * {@link #cleanup()}. + */ + private static final AtomicInteger initCount = new AtomicInteger(0); + + /** A singleton Mongo instance. */ + private static MongoClient mongoClient; + + /** The default read preference for the test */ + private static ReadPreference readPreference; + + /** The default write concern for the test. */ + private static WriteConcern writeConcern; + + /** The batch size to use for inserts. */ + private static int batchSize; + + /** The bulk inserts pending for the thread. */ + private final List bulkInserts = new ArrayList(); + + /** + * Cleanup any state for this DB. Called once per DB instance; there is one + * DB instance per client thread. + */ + @Override + public void cleanup() throws DBException { + if (initCount.decrementAndGet() == 0) { + try { + mongoClient.close(); + } + catch (Exception e1) { + System.err.println("Could not close MongoDB connection pool: " + + e1.toString()); + e1.printStackTrace(); + return; + } + finally { + database = null; + mongoClient = null; + } + } + } + + /** + * Delete a record from the database. + * + * @param table + * The name of the table + * @param key + * The record key of the record to delete. + * @return Zero on success, a non-zero error code on error. See the + * {@link DB} class's description for a discussion of error codes. + */ + @Override + public int delete(String table, String key) { + try { + MongoCollection collection = database + .getCollection(table); + + Document query = new Document("_id", key); + DeleteResult result = collection.withWriteConcern(writeConcern) + .deleteOne(query); + if (result.wasAcknowledged() && result.getDeletedCount() == 0) { + System.err.println("Nothing deleted for key " + key); + return 1; + } + return 0; + } + catch (Exception e) { + System.err.println(e.toString()); + return 1; + } + } + + /** + * Initialize any state for this DB. Called once per DB instance; there is + * one DB instance per client thread. + */ + @Override + public void init() throws DBException { + initCount.incrementAndGet(); + synchronized (INCLUDE) { + if (mongoClient != null) { + return; + } + + Properties props = getProperties(); + + // Set insert batchsize, default 1 - to be YCSB-original equivalent + batchSize = Integer.parseInt(props.getProperty("batchsize", "1")); + + // Just use the standard connection format URL + // http://docs.mongodb.org/manual/reference/connection-string/ + // to configure the client. + String url = props.getProperty("mongodb.url", null); + boolean defaultedUrl = false; + if (url == null) { + defaultedUrl = true; + url = "mongodb://localhost:27017/ycsb?w=1"; + } + + url = OptionsSupport.updateUrl(url, props); + + if (!url.startsWith("mongodb://")) { + System.err + .println("ERROR: Invalid URL: '" + + url + + "'. Must be of the form " + + "'mongodb://:,:/database?options'. " + + "http://docs.mongodb.org/manual/reference/connection-string/"); + System.exit(1); + } + + try { + MongoClientURI uri = new MongoClientURI(url); + + String uriDb = uri.getDatabase(); + if (!defaultedUrl && (uriDb != null) && !uriDb.isEmpty() + && !"admin".equals(uriDb)) { + databaseName = uriDb; + } + else { + //If no database is specified in URI, use "ycsb" + databaseName = "ycsb"; + + } + + + readPreference = uri.getOptions().getReadPreference(); + writeConcern = uri.getOptions().getWriteConcern(); + + mongoClient = new MongoClient(uri); + database = mongoClient.getDatabase(databaseName); + + System.out.println("mongo client connection created with " + + url); + } + catch (Exception e1) { + System.err + .println("Could not initialize MongoDB connection pool for Loader: " + + e1.toString()); + e1.printStackTrace(); + return; + } + } + } + + /** + * Insert a record in the database. Any field/value pairs in the specified + * values HashMap will be written into the record with the specified record + * key. + * + * @param table + * The name of the table + * @param key + * The record key of the record to insert. + * @param values + * A HashMap of field/value pairs to insert in the record + * @return Zero on success, a non-zero error code on error. See the + * {@link DB} class's description for a discussion of error codes. + */ + @Override + public int insert(String table, String key, + HashMap values) { + try { + MongoCollection collection = database + .getCollection(table); + Document toInsert = new Document("_id", key); + for (Map.Entry entry : values.entrySet()) { + toInsert.put(entry.getKey(), entry.getValue().toArray()); + } + + bulkInserts.add(toInsert); + if (bulkInserts.size() == batchSize) { + collection.withWriteConcern(writeConcern) + .insertMany(bulkInserts, INSERT_MANY_OPTIONS); + bulkInserts.clear(); + } + return 0; + } + catch (Exception e) { + System.err.println("Exception while trying bulk insert with " + + bulkInserts.size()); + e.printStackTrace(); + return 1; + } + + } + + /** + * Read a record from the database. Each field/value pair from the result + * will be stored in a HashMap. + * + * @param table + * The name of the table + * @param key + * The record key of the record to read. + * @param fields + * The list of fields to read, or null for all of them + * @param result + * A HashMap of field/value pairs for the result + * @return Zero on success, a non-zero error code on error or "not found". + */ + @Override + public int read(String table, String key, Set fields, + HashMap result) { + try { + MongoCollection collection = database + .getCollection(table); + Document query = new Document("_id", key); + + FindIterable findIterable = collection + .withReadPreference(readPreference) + .find(query); + + Document queryResult = null; + if (fields != null) { + Document projection = new Document(); + for (String field : fields) { + projection.put(field, INCLUDE); + } + findIterable.projection(projection); + } + + queryResult = findIterable.first(); + + if (queryResult != null) { + fillMap(result, queryResult); + } + return queryResult != null ? 0 : 1; + } + catch (Exception e) { + System.err.println(e.toString()); + return 1; + } + } + + /** + * Perform a range scan for a set of records in the database. Each + * field/value pair from the result will be stored in a HashMap. + * + * @param table + * The name of the table + * @param startkey + * The record key of the first record to read. + * @param recordcount + * The number of records to read + * @param fields + * The list of fields to read, or null for all of them + * @param result + * A Vector of HashMaps, where each HashMap is a set field/value + * pairs for one record + * @return Zero on success, a non-zero error code on error. See the + * {@link DB} class's description for a discussion of error codes. + */ + @Override + public int scan(String table, String startkey, int recordcount, + Set fields, Vector> result) { + MongoCursor cursor = null; + try { + MongoCollection collection = database + .getCollection(table); + + Document scanRange = new Document("$gte", startkey); + Document query = new Document("_id", scanRange); + Document sort = new Document("_id", INCLUDE); + Document projection = null; + if (fields != null) { + projection = new Document(); + for (String fieldName : fields) { + projection.put(fieldName, INCLUDE); + } + } + + cursor = collection.withReadPreference(readPreference).find(query) + .projection(projection).sort(sort).limit(recordcount).iterator(); + if (!cursor.hasNext()) { + System.err.println("Nothing found in scan for key " + startkey); + return 1; + } + while (cursor.hasNext()) { + HashMap resultMap = new HashMap(); + + Document obj = cursor.next(); + fillMap(resultMap, obj); + + result.add(resultMap); + } + + return 0; + } + catch (Exception e) { + System.err.println(e.toString()); + return 1; + } + finally { + if (cursor != null) { + cursor.close(); + } + } + } + + /** + * Update a record in the database. Any field/value pairs in the specified + * values HashMap will be written into the record with the specified record + * key, overwriting any existing values with the same field name. + * + * @param table + * The name of the table + * @param key + * The record key of the record to write. + * @param values + * A HashMap of field/value pairs to update in the record + * @return Zero on success, a non-zero error code on error. See this class's + * description for a discussion of error codes. + */ + @Override + public int update(String table, String key, + HashMap values) { + try { + MongoCollection collection = database + .getCollection(table); + + Document query = new Document("_id", key); + Document fieldsToSet = new Document(); + for (Map.Entry entry : values.entrySet()) { + fieldsToSet.put(entry.getKey(), entry.getValue().toArray()); + } + Document update = new Document("$set", fieldsToSet); + + UpdateResult result = collection.withWriteConcern(writeConcern) + .updateOne(query, update); + if (result.wasAcknowledged() && result.getMatchedCount() == 0) { + System.err.println("Nothing updated for key " + key); + return 1; + } + return 0; + } + catch (Exception e) { + System.err.println(e.toString()); + return 1; + } + } + + /** + * Fills the map with the values from the DBObject. + * + * @param resultMap + * The map to fill/ + * @param obj + * The object to copy values from. + */ + protected void fillMap(HashMap resultMap, Document obj) { + for (Map.Entry entry : obj.entrySet()) { + if (entry.getValue() instanceof Binary) { + resultMap.put(entry.getKey(), new ByteArrayByteIterator( + ((Binary) entry.getValue()).getData())); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.yahoo.ycsb.db.MongoDbClient.read` reads without synchronization from `db.MongoDbClient.com.yahoo.ycsb.db.MongoDbClient.readPreference`. Potentially races with write in method `MongoDbClient.init()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int MongoDbClient.read(String,String,Set,HashMap) + +### Procedure Id: +com.yahoo.ycsb.db.MongoDbClient.read(java.lang.String,java.lang.String,java.util.Set,java.util.HashM.08517729c50b4424107f4546f667e881 + +### File: +mongodb/src/main/java/com/yahoo/ycsb/db/MongoDbClient.java + +### Key: +MongoDbClient.java|read|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +9bb7ef2e8f611f47c7a2731aaccb720e + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7980/instruction.md b/inferredbugs-7980/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..771eff7a25c26319829b8d1c468fc58778bee96e --- /dev/null +++ b/inferredbugs-7980/instruction.md @@ -0,0 +1,599 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** YCSB +**Bug ID:** 14 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Licensed under the Apache License, Version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You + * may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. See accompanying + * LICENSE file. + */ + +package com.yahoo.ycsb.db; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; + +import com.yahoo.ycsb.ByteArrayByteIterator; +import com.yahoo.ycsb.ByteIterator; +import com.yahoo.ycsb.DBException; +import com.yahoo.ycsb.Status; +import com.yahoo.ycsb.measurements.Measurements; + +import org.apache.hadoop.security.UserGroupInformation; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hbase.Cell; +import org.apache.hadoop.hbase.CellUtil; +import org.apache.hadoop.hbase.HBaseConfiguration; +import org.apache.hadoop.hbase.TableName; +import org.apache.hadoop.hbase.client.BufferedMutator; +import org.apache.hadoop.hbase.client.BufferedMutatorParams; +import org.apache.hadoop.hbase.client.Connection; +import org.apache.hadoop.hbase.client.ConnectionFactory; +import org.apache.hadoop.hbase.client.Delete; +import org.apache.hadoop.hbase.client.Durability; +import org.apache.hadoop.hbase.client.Get; +import org.apache.hadoop.hbase.client.Put; +import org.apache.hadoop.hbase.client.Result; +import org.apache.hadoop.hbase.client.ResultScanner; +import org.apache.hadoop.hbase.client.Scan; +import org.apache.hadoop.hbase.client.Table; +import org.apache.hadoop.hbase.filter.PageFilter; +import org.apache.hadoop.hbase.util.Bytes; + +import java.io.IOException; +import java.util.ConcurrentModificationException; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.Vector; + +/** + * HBase 1.0 client for YCSB framework. + * + * A modified version of HBaseClient (which targets HBase v0.9) utilizing the + * HBase 1.0.0 API. + * + * This client also adds toggleable client-side buffering and configurable write + * durability. + */ +public class HBaseClient10 extends com.yahoo.ycsb.DB { + private Configuration config = HBaseConfiguration.create(); + + // Must be an object for synchronization and tracking running thread counts. + private static Integer threadCount = 0; + + private boolean debug = false; + + private String tableName = ""; + private static Connection connection = null; + + // Depending on the value of clientSideBuffering, either bufferedMutator + // (clientSideBuffering) or currentTable (!clientSideBuffering) will be used. + private Table currentTable = null; + private BufferedMutator bufferedMutator = null; + + private String columnFamily = ""; + private byte[] columnFamilyBytes; + + /** + * Durability to use for puts and deletes. + */ + private Durability durability = Durability.USE_DEFAULT; + + /** Whether or not a page filter should be used to limit scan length. */ + private boolean usePageFilter = true; + + /** + * If true, buffer mutations on the client. This is the default behavior for + * HBaseClient. For measuring insert/update/delete latencies, client side + * buffering should be disabled. + */ + private boolean clientSideBuffering = false; + private long writeBufferSize = 1024 * 1024 * 12; + + /** + * Initialize any state for this DB. Called once per DB instance; there is one + * DB instance per client thread. + */ + @Override + public void init() throws DBException { + if ("true" + .equals(getProperties().getProperty("clientbuffering", "false"))) { + this.clientSideBuffering = true; + } + if (getProperties().containsKey("writebuffersize")) { + writeBufferSize = + Long.parseLong(getProperties().getProperty("writebuffersize")); + } + + if (getProperties().getProperty("durability") != null) { + this.durability = + Durability.valueOf(getProperties().getProperty("durability")); + } + + if ("kerberos".equalsIgnoreCase(config.get("hbase.security.authentication"))) { + config.set("hadoop.security.authentication", "Kerberos"); + UserGroupInformation.setConfiguration(config); + } + + if ((getProperties().getProperty("principal")!=null) + && (getProperties().getProperty("keytab")!=null)) { + try { + UserGroupInformation.loginUserFromKeytab(getProperties().getProperty("principal"), + getProperties().getProperty("keytab")); + } catch (IOException e) { + System.err.println("Keytab file is not readable or not found"); + throw new DBException(e); + } + } + + try { + synchronized(threadCount) { + ++threadCount; + if (connection == null) { + connection = ConnectionFactory.createConnection(config); + } + } + } catch (java.io.IOException e) { + throw new DBException(e); + } + + if ((getProperties().getProperty("debug") != null) + && (getProperties().getProperty("debug").compareTo("true") == 0)) { + debug = true; + } + + if ("false" + .equals(getProperties().getProperty("hbase.usepagefilter", "true"))) { + usePageFilter = false; + } + + columnFamily = getProperties().getProperty("columnfamily"); + if (columnFamily == null) { + System.err.println("Error, must specify a columnfamily for HBase table"); + throw new DBException("No columnfamily specified"); + } + columnFamilyBytes = Bytes.toBytes(columnFamily); + + // Terminate right now if table does not exist, since the client + // will not propagate this error upstream once the workload + // starts. + String table = com.yahoo.ycsb.workloads.CoreWorkload.table; + try { + final TableName tName = TableName.valueOf(table); + connection.getTable(tName).getTableDescriptor(); + } catch (IOException e) { + throw new DBException(e); + } + } + + /** + * Cleanup any state for this DB. Called once per DB instance; there is one DB + * instance per client thread. + */ + @Override + public void cleanup() throws DBException { + // Get the measurements instance as this is the only client that should + // count clean up time like an update if client-side buffering is + // enabled. + Measurements measurements = Measurements.getMeasurements(); + try { + long st = System.nanoTime(); + if (bufferedMutator != null) { + bufferedMutator.close(); + } + if (currentTable != null) { + currentTable.close(); + } + long en = System.nanoTime(); + final String type = clientSideBuffering ? "UPDATE" : "CLEANUP"; + measurements.measure(type, (int) ((en - st) / 1000)); + synchronized(threadCount) { + --threadCount; + if (threadCount <= 0 && connection != null) { + connection.close(); + connection = null; + } + } + } catch (IOException e) { + throw new DBException(e); + } + } + + public void getHTable(String table) throws IOException { + final TableName tName = TableName.valueOf(table); + this.currentTable = this.connection.getTable(tName); + // suggestions from + // http://ryantwopointoh.blogspot.com/2009/01/ + // performance-of-hbase-importing.html + if (clientSideBuffering) { + final BufferedMutatorParams p = new BufferedMutatorParams(tName); + p.writeBufferSize(writeBufferSize); + this.bufferedMutator = this.connection.getBufferedMutator(p); + } + } + + /** + * Read a record from the database. Each field/value pair from the result will + * be stored in a HashMap. + * + * @param table + * The name of the table + * @param key + * The record key of the record to read. + * @param fields + * The list of fields to read, or null for all of them + * @param result + * A HashMap of field/value pairs for the result + * @return Zero on success, a non-zero error code on error + */ + public Status read(String table, String key, Set fields, + HashMap result) { + // if this is a "new" table, init HTable object. Else, use existing one + if (!tableName.equals(table)) { + currentTable = null; + try { + getHTable(table); + tableName = table; + } catch (IOException e) { + System.err.println("Error accessing HBase table: " + e); + return Status.ERROR; + } + } + + Result r = null; + try { + if (debug) { + System.out + .println("Doing read from HBase columnfamily " + columnFamily); + System.out.println("Doing read for key: " + key); + } + Get g = new Get(Bytes.toBytes(key)); + if (fields == null) { + g.addFamily(columnFamilyBytes); + } else { + for (String field : fields) { + g.addColumn(columnFamilyBytes, Bytes.toBytes(field)); + } + } + r = currentTable.get(g); + } catch (IOException e) { + if (debug) { + System.err.println("Error doing get: " + e); + } + return Status.ERROR; + } catch (ConcurrentModificationException e) { + // do nothing for now...need to understand HBase concurrency model better + return Status.ERROR; + } + + if (r.isEmpty()) { + return Status.NOT_FOUND; + } + + while (r.advance()) { + final Cell c = r.current(); + result.put(Bytes.toString(CellUtil.cloneQualifier(c)), + new ByteArrayByteIterator(CellUtil.cloneValue(c))); + if (debug) { + System.out.println( + "Result for field: " + Bytes.toString(CellUtil.cloneQualifier(c)) + + " is: " + Bytes.toString(CellUtil.cloneValue(c))); + } + } + return Status.OK; + } + + /** + * Perform a range scan for a set of records in the database. Each field/value + * pair from the result will be stored in a HashMap. + * + * @param table + * The name of the table + * @param startkey + * The record key of the first record to read. + * @param recordcount + * The number of records to read + * @param fields + * The list of fields to read, or null for all of them + * @param result + * A Vector of HashMaps, where each HashMap is a set field/value + * pairs for one record + * @return Zero on success, a non-zero error code on error + */ + @Override + public Status scan(String table, String startkey, int recordcount, + Set fields, Vector> result) { + // if this is a "new" table, init HTable object. Else, use existing one + if (!tableName.equals(table)) { + currentTable = null; + try { + getHTable(table); + tableName = table; + } catch (IOException e) { + System.err.println("Error accessing HBase table: " + e); + return Status.ERROR; + } + } + + Scan s = new Scan(Bytes.toBytes(startkey)); + // HBase has no record limit. Here, assume recordcount is small enough to + // bring back in one call. + // We get back recordcount records + s.setCaching(recordcount); + if (this.usePageFilter) { + s.setFilter(new PageFilter(recordcount)); + } + + // add specified fields or else all fields + if (fields == null) { + s.addFamily(columnFamilyBytes); + } else { + for (String field : fields) { + s.addColumn(columnFamilyBytes, Bytes.toBytes(field)); + } + } + + // get results + ResultScanner scanner = null; + try { + scanner = currentTable.getScanner(s); + int numResults = 0; + for (Result rr = scanner.next(); rr != null; rr = scanner.next()) { + // get row key + String key = Bytes.toString(rr.getRow()); + + if (debug) { + System.out.println("Got scan result for key: " + key); + } + + HashMap rowResult = + new HashMap(); + + while (rr.advance()) { + final Cell cell = rr.current(); + rowResult.put(Bytes.toString(CellUtil.cloneQualifier(cell)), + new ByteArrayByteIterator(CellUtil.cloneValue(cell))); + } + + // add rowResult to result vector + result.add(rowResult); + numResults++; + + // PageFilter does not guarantee that the number of results is <= + // pageSize, so this + // break is required. + if (numResults >= recordcount) {// if hit recordcount, bail out + break; + } + } // done with row + } catch (IOException e) { + if (debug) { + System.out.println("Error in getting/parsing scan result: " + e); + } + return Status.ERROR; + } finally { + if (scanner != null) { + scanner.close(); + } + } + + return Status.OK; + } + + /** + * Update a record in the database. Any field/value pairs in the specified + * values HashMap will be written into the record with the specified record + * key, overwriting any existing values with the same field name. + * + * @param table + * The name of the table + * @param key + * The record key of the record to write + * @param values + * A HashMap of field/value pairs to update in the record + * @return Zero on success, a non-zero error code on error + */ + @Override + public Status update(String table, String key, + HashMap values) { + // if this is a "new" table, init HTable object. Else, use existing one + if (!tableName.equals(table)) { + currentTable = null; + try { + getHTable(table); + tableName = table; + } catch (IOException e) { + System.err.println("Error accessing HBase table: " + e); + return Status.ERROR; + } + } + + if (debug) { + System.out.println("Setting up put for key: " + key); + } + Put p = new Put(Bytes.toBytes(key)); + p.setDurability(durability); + for (Map.Entry entry : values.entrySet()) { + byte[] value = entry.getValue().toArray(); + if (debug) { + System.out.println("Adding field/value " + entry.getKey() + "/" + + Bytes.toStringBinary(value) + " to put request"); + } + p.addColumn(columnFamilyBytes, Bytes.toBytes(entry.getKey()), value); + } + + try { + if (clientSideBuffering) { + Preconditions.checkNotNull(bufferedMutator); + bufferedMutator.mutate(p); + } else { + currentTable.put(p); + } + } catch (IOException e) { + if (debug) { + System.err.println("Error doing put: " + e); + } + return Status.ERROR; + } catch (ConcurrentModificationException e) { + // do nothing for now...hope this is rare + return Status.ERROR; + } + + return Status.OK; + } + + /** + * Insert a record in the database. Any field/value pairs in the specified + * values HashMap will be written into the record with the specified record + * key. + * + * @param table + * The name of the table + * @param key + * The record key of the record to insert. + * @param values + * A HashMap of field/value pairs to insert in the record + * @return Zero on success, a non-zero error code on error + */ + @Override + public Status insert(String table, String key, + HashMap values) { + return update(table, key, values); + } + + /** + * Delete a record from the database. + * + * @param table + * The name of the table + * @param key + * The record key of the record to delete. + * @return Zero on success, a non-zero error code on error + */ + @Override + public Status delete(String table, String key) { + // if this is a "new" table, init HTable object. Else, use existing one + if (!tableName.equals(table)) { + currentTable = null; + try { + getHTable(table); + tableName = table; + } catch (IOException e) { + System.err.println("Error accessing HBase table: " + e); + return Status.ERROR; + } + } + + if (debug) { + System.out.println("Doing delete for key: " + key); + } + + final Delete d = new Delete(Bytes.toBytes(key)); + d.setDurability(durability); + try { + if (clientSideBuffering) { + Preconditions.checkNotNull(bufferedMutator); + bufferedMutator.mutate(d); + } else { + currentTable.delete(d); + } + } catch (IOException e) { + if (debug) { + System.err.println("Error doing delete: " + e); + } + return Status.ERROR; + } + + return Status.OK; + } + + @VisibleForTesting + void setConfiguration(final Configuration newConfig) { + this.config = newConfig; + } +} + +/* + * For customized vim control set autoindent set si set shiftwidth=4 + */ + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.yahoo.ycsb.db.HBaseClient10.init` reads without synchronization from `db.HBaseClient10.com.yahoo.ycsb.db.HBaseClient10.threadCount`. Potentially races with write in method `HBaseClient10.init()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void HBaseClient10.init() + +### Procedure Id: +com.yahoo.ycsb.db.HBaseClient10.init():void.3aedd861d1c3e8bddb065639ca6ca62c + +### File: +hbase10/src/main/java/com/yahoo/ycsb/db/HBaseClient10.java + +### Key: +HBaseClient10.java|init|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +bdcd0e4c6f4bceb9fa8659ced1b8a3ee + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7986/instruction.md b/inferredbugs-7986/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29b56699eb658b204370ba2f2b957c39a2124eab --- /dev/null +++ b/inferredbugs-7986/instruction.md @@ -0,0 +1,206 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** dicoogle +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2014 Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/ + * + * This file is part of Dicoogle/dicoogle. + * + * Dicoogle/dicoogle 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 of the License, or + * (at your option) any later version. + * + * Dicoogle/dicoogle 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 Dicoogle. If not, see . + */ +package pt.ua.dicoogle.server.web.servlets.search; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import net.sf.json.JSONArray; +import pt.ua.dicoogle.core.QueryExpressionBuilder; +import pt.ua.dicoogle.core.query.ExportToCSVQueryTask; +import pt.ua.dicoogle.plugins.PluginController; +import pt.ua.dicoogle.sdk.utils.DictionaryAccess; + +public class ExportServlet extends HttpServlet{ + + public enum ExportType{ + LIST, EXPORT_CVS; + } + private ExportType type; + + public ExportServlet(ExportType type) { + this.type = type; + } + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + switch(type){ + case LIST: + doGetTagList(req, resp); + break; + case EXPORT_CVS: + doGetExportCvs(req, resp); + break; + } + } + + private void doGetTagList(HttpServletRequest req, HttpServletResponse resp) throws IOException{ + HashMap< String, Integer> tagList = DictionaryAccess.getInstance().getTagList(); + Iterator iterator = tagList.entrySet().iterator(); + + JSONArray array = new JSONArray(); + + while(iterator.hasNext()) + { + Map.Entry entry = (Entry) iterator.next(); + //JSONObject obj = new JSONObject(); + //obj.put("key", entry.getKey()); + //obj.put("value", entry.getValue()); + + + array.add(entry.getKey()); + } + + resp.getWriter().write(array.toString()); + } + + private void doGetExportCvs(HttpServletRequest req, HttpServletResponse resp) throws IOException{ + resp.setHeader("Content-disposition","attachment; filename=QueryResultsExport.csv"); + String queryString = req.getParameter("query"); + String[] fields = req.getParameterValues("fields"); + String[] providers = req.getParameterValues("providers"); + boolean keyword = Boolean.parseBoolean(req.getParameter("keyword")); + + System.out.println("queryString: "+ queryString); + for(String field: fields) + System.out.println("field: "+ field); + System.out.println("keyword: "+ keyword); + + if(queryString == null) + resp.sendError(401, "Query Parameters not found"); + + if(fields == null || fields.length==0) + resp.sendError(402, "Fields Parameters not found"); + + if (!keyword) { + QueryExpressionBuilder q = new QueryExpressionBuilder(queryString); + queryString = q.getQueryString(); + } + + + List fieldList = new ArrayList<>(fields.length); + Map fieldsMap = new HashMap<>(); + for(String f : fields){ + fieldList.add(f); + fieldsMap.put(f, f); + } + + ExportToCSVQueryTask task = new ExportToCSVQueryTask( fieldList, + resp.getOutputStream()); + + if(providers == null || providers.length == 0) { + PluginController.getInstance().queryAll(task, queryString, fieldsMap); + } else { + List providersList = new ArrayList<>(); + for (String f : providers) { + providersList.add(f); + } + PluginController.getInstance().query(task, providersList, queryString, + fieldsMap); + } + + task.await(); + } + + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `queryString` last assigned on line 85 could be null and is dereferenced by call to `QueryExpressionBuilder(...)` at line 102. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExportServlet.doGetExportCvs(HttpServletRequest,HttpServletResponse) + +### Procedure Id: +pt.ua.dicoogle.server.web.servlets.search.ExportServlet.doGetExportCvs(javax.servlet.http.HttpServle.986b783bb427273ba5522b56a1f576fc + +### File: +dicoogle/src/main/java/pt/ua/dicoogle/server/web/servlets/search/ExportServlet.java + +### Key: +ExportServlet.java|doGetExportCvs|NULL_DEREFERENCE + +### Node Key: +b028e78598b6d149136e4ad1ce0491a0 + +### Hash: +4818e72861150fe7a829569443b59c21 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7987/instruction.md b/inferredbugs-7987/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eb562c70c134532b5ec05c1ecc64348acd4f536b --- /dev/null +++ b/inferredbugs-7987/instruction.md @@ -0,0 +1,365 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** dicoogle +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2014 Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/ + * + * This file is part of Dicoogle/dicoogle. + * + * Dicoogle/dicoogle 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 of the License, or + * (at your option) any later version. + * + * Dicoogle/dicoogle 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 Dicoogle. If not, see . + */ +package pt.ua.dicoogle.server.web.auth; + +import java.io.IOException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +/** + * Handles and manages login requests and the information associated with it. + * + * @author António Novo + */ +public class Session +{ + /** + * Attemps to login using the supplied params. + * + * @param username the user name. + * @param password the users password. + * @return true if the login is successfull, false otherwise. + */ + public static boolean isSuccessfulLogin(String username, String password) + { + LoggedIn result = getSuccessfulLogin(username, password); + + return (result != null); + } + + /** + * Attemps to login using the supplied params. + * + * @param username the user name. + * @param password the users password. + * @return a LoggedIn object if the login is successfull, null otherwise. + */ + public static LoggedIn getSuccessfulLogin(String username, String password) + { + Authentication auth = Authentication.getInstance(); + LoggedIn result = auth.login(username, password); + + return result; + } + + /** + * Check if there is a user logged in on the session supplied. + * + * @param session the HttpSession object of the request. + * @return true if there is a user logged in on the session supplied, false otherwise. + */ + public static boolean isUserLoggedIn(HttpSession session) + { + return (getUserLoggedIn(session) != null); + } + + /** + * Check if there is a user logged in on the session supplied and if (s)he ia an administrator. + * + * @param session the HttpSession object of the request. + * @return true if there is a user logged in on the session supplied and is an administrator, false otherwise. + */ + public static boolean isUserLoggedInAnAdmin(HttpSession session) + { + LoggedIn login = getUserLoggedIn(session); + return ((login != null) && (login.isAdmin())); + } + + /** + * Gets the LoggedIn object that has the information relative to user logged in on the session supplied. + * + * @param session the HttpSession object of the request. + * @return a LoggedIn object if there is a user logged in on the session supplied, null otherwise. + */ + public static LoggedIn getUserLoggedIn(HttpSession session) + { + // if the sessio is invalid + if (session == null) + return null; + + // if the client is not yet aware of (or didn't aceepted/joined) the session + if (session.isNew()) + return null; + + // if no login information was found + Object login = session.getAttribute("login"); + if (login == null) + return null; + + // the client is currently logged in + return (LoggedIn) login; + } + + /** + * If there is a user logged in on the current HttpSession, log out. + * + * @param session the HttpSession object of the request. + * @return if there was a logout action performed or not. + */ + public static boolean logout(HttpServletRequest request) + { + HttpSession session = request.getSession(false); + try + { + session.invalidate(); + } + catch (Exception e ) + { + System.err.println("Tracking session"); + } + + + + // if the sessio is invalid + if (session == null) + return false; + + // if the client is not yet aware of (or didn't aceepted/joined) the session + if (session.isNew()) + return false; + + // if no login information was found + Object login = session.getAttribute("login"); + if (login == null) + return false; + + // the client is currently logged in, so logout + session.removeAttribute("login"); + session.invalidate(); + return true; + } + + /** + * Checks if the request made to a servlet was made by a logged is user, + * or if the request carries the required login information. + *
    + * This is done by first checking if the request has a valid + * (with valid login information) session (like an AJAX request from a + * cookies enabled browser), if not checks if the request parameters + * have valid login information (like made a REST[less] stand-alone + * application), and if none of the above situations happened send an + * adequate response to the client. + * + * @param requiresAdminRights if the current request requires admin rights to be served/performed. + * @return a LoggedIn object if the request is to be served, null otherwise. + */ + public static LoggedIn servletLogin(HttpServletRequest request, HttpServletResponse response, boolean requiresAdminRights) throws IOException + { + // check if there a session and a login information attached to it + HttpSession session = request.getSession(false); + LoggedIn login = getUserLoggedIn(session); + if (login != null) + { + // check if this request needs admin rights and the user has them + if (requiresAdminRights) + { + if (login.isAdmin()) + return login; + else + { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Administrator rights are needed to process this request!"); + return null; + } + } + else + return login; + } + + // since the above failed, check if there is valid login information on the request parameters + String username = request.getParameter("username"); + String password = request.getParameter("password"); + login = getSuccessfulLogin(username, password); + if (login != null) + { + // check if this request needs admin rights and the user has them + if (requiresAdminRights) + { + if (login.isAdmin()) + return login; + else + { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Administrator rights are needed to process this request!"); + return null; + } + } + else + return login; + } + + // both situations failed + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No login information found!"); + return null; + } + + /** + * Checks if the request made to a webapp was made by a logged is user, + * or if the request carries the required login information. + *
    + * This is done by first checking if the request has a valid + * (with valid login information) session (like an AJAX request from a + * cookies enabled browser), if not checks if the request parameters + * have valid login information (like made a REST[less] stand-alone + * application), and if none of the above situations happened send an + * adequate response to the client, on most cases a redirection to the + * login page will be sent. + * + * @param requiresAdminRights if the current request requires admin rights to be served/performed. + * @return a LoggedIn object if the request is to be served, null otherwise. + */ + public static LoggedInStatus webappLogin(HttpServletRequest request, HttpServletResponse response, boolean requiresAdminRights) throws IOException + { + // check if there a session and a login information attached to it + HttpSession session = request.getSession(true); + LoggedIn login = getUserLoggedIn(session); + /*if (login != null) + { + // check if this request needs admin rights and the user has them + if (requiresAdminRights && (! login.isAdmin())) + { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + return new LoggedInStatus(null, LoggedInStatus.S_UNAUTHORIZEDACCESS); + } + + return new LoggedInStatus(login, LoggedInStatus.S_ALREADYLOGGEDIN); + }*/ + + // since the above failed, check if there is valid login information on the request parameters + String username = request.getParameter("username"); + String password = request.getParameter("password"); + login = getSuccessfulLogin(username, password); + if (login != null) + { + // check if this request needs admin rights and the user has them + if (requiresAdminRights && (! login.isAdmin())) + { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + return new LoggedInStatus(null, LoggedInStatus.S_UNAUTHORIZEDACCESS); + } + + // add the login information to the session + session = request.getSession(true); // force the creation of a new session if there is none + session.setAttribute("login", login); + return new LoggedInStatus(login, LoggedInStatus.S_VALIDLOGIN); + } + + // both situations failed + if (! request.getRequestURI().equalsIgnoreCase("/login.jsp")) + response.sendRedirect("/login.jsp"); + if ((username == null) && (password == null)) + return new LoggedInStatus(null, LoggedInStatus.S_NOINFORMATION); + else + return new LoggedInStatus(null, LoggedInStatus.S_INVALIDCREDENTIALS); + } + + /** + * Based on the request referer returns the address of the previously visited + * page or to the default main page if none. + * + * @param request the original http request object. + * @return a string containing the previous URL. + */ + public static String getLastVisitedURL(HttpServletRequest request) + { + String result = "/index.jsp"; + + if (request == null) + return result; + + result = request.getHeader("Referer"); + if (result == null) + result = "/index.jsp"; + + return result; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `session` last assigned on line 257 could be null and is dereferenced at line 258. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +LoggedInStatus Session.webappLogin(HttpServletRequest,HttpServletResponse,boolean) + +### Procedure Id: +pt.ua.dicoogle.server.web.auth.Session.webappLogin(javax.servlet.http.HttpServletRequest,javax.servl.6343ed28ccbf1c3c26fae11fffc1dac7 + +### File: +dicoogle/src/main/java/pt/ua/dicoogle/server/web/auth/Session.java + +### Key: +Session.java|webappLogin|NULL_DEREFERENCE + +### Node Key: +848df93d8487c863f24365c5e444782f + +### Hash: +2fd4c0180f3a40e811aaa48bbf9bbcbf + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7988/instruction.md b/inferredbugs-7988/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..76c42ff81583d9753598608f523effcd19250292 --- /dev/null +++ b/inferredbugs-7988/instruction.md @@ -0,0 +1,183 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** dicoogle +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2014 Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/ + * + * This file is part of Dicoogle/dicoogle. + * + * Dicoogle/dicoogle 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 of the License, or + * (at your option) any later version. + * + * Dicoogle/dicoogle 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 Dicoogle. If not, see . + */ + +package pt.ua.dicoogle.server.web.servlets.accounts; + +import java.io.IOException; +import java.util.UUID; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; +import pt.ua.dicoogle.server.users.Role; +import pt.ua.dicoogle.server.users.User; +import pt.ua.dicoogle.server.users.UsersStruct; +import pt.ua.dicoogle.server.web.auth.LoggedIn; +import pt.ua.dicoogle.server.web.auth.Session; + +/** + * + * @author Frederico Silva + */ +public class LoginServlet extends HttpServlet { + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + //resp.addHeader("Access-Control-Allow-Origin", "*"); + //Try login + // Does not require admini rights. + LoggedIn mLoggedIn = Session.webappLogin(req, resp, false).getLogin(); + //servletLogin(req, resp, true);//auth.login(user, pass); + + if (mLoggedIn == null) { + resp.sendError(401, "Login failed"); + return; + } + + JSONObject json_resp = new JSONObject(); + json_resp.put("user", mLoggedIn.getUserName()); + json_resp.put("admin", mLoggedIn.isAdmin()); + User u = UsersStruct.getInstance().getUser(mLoggedIn.getUserName()); + JSONArray rolesObj = new JSONArray(); + for (Role r : u.getRoles()) + { + rolesObj.add(r.getName()); + } + + json_resp.put("roles", rolesObj); + json_resp.put("token", mLoggedIn.getToken()); + + //Set response content type + resp.setContentType("application/json"); + + //Write response + json_resp.write(resp.getWriter()); + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + //resp.addHeader("Access-Control-Allow-Origin", "*"); + HttpSession session = req.getSession(false); + + LoggedIn mLoggedIn = Session.getUserLoggedIn(session); + if(mLoggedIn == null){ + resp.sendError(401); + return; + } + + JSONObject json_resp = new JSONObject(); + json_resp.put("user", mLoggedIn.getUserName()); + json_resp.put("admin", mLoggedIn.isAdmin()); + User u = UsersStruct.getInstance().getUser(mLoggedIn.getUserName()); + JSONArray rolesObj = new JSONArray(); + for (Role r : u.getRoles()) + { + rolesObj.add(r.getName()); + } + + json_resp.put("roles", rolesObj); + + //Set response content type + resp.setContentType("application/json"); + + //Write response + json_resp.write(resp.getWriter()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `u` last assigned on line 61 could be null and is dereferenced at line 63. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void LoginServlet.doPost(HttpServletRequest,HttpServletResponse) + +### Procedure Id: +pt.ua.dicoogle.server.web.servlets.accounts.LoginServlet.doPost(javax.servlet.http.HttpServletReques.10fd21e278006005f40dc831cb77ce81 + +### File: +dicoogle/src/main/java/pt/ua/dicoogle/server/web/servlets/accounts/LoginServlet.java + +### Key: +LoginServlet.java|doPost|NULL_DEREFERENCE + +### Node Key: +50eb9480b1a39477599a8d0ef0064573 + +### Hash: +d9a99bb1000ccbf739bcec3a8cc0ae6a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8043/instruction.md b/inferredbugs-8043/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..df73dda52e601b9a47c31e22ec876d7e66b73955 --- /dev/null +++ b/inferredbugs-8043/instruction.md @@ -0,0 +1,694 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** hono +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) 2017, 2018 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Bosch Software Innovations GmbH - initial creation + * Red Hat Inc + */ +package org.eclipse.hono.client.impl; + +import java.net.HttpURLConnection; +import java.time.Duration; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.qpid.proton.amqp.messaging.Accepted; +import org.apache.qpid.proton.amqp.messaging.AmqpValue; +import org.apache.qpid.proton.amqp.messaging.Rejected; +import org.apache.qpid.proton.message.Message; +import org.eclipse.hono.client.ClientErrorException; +import org.eclipse.hono.client.RequestResponseClient; +import org.eclipse.hono.client.RequestResponseClientConfigProperties; +import org.eclipse.hono.client.ServerErrorException; +import org.eclipse.hono.client.StatusCodeMapper; +import org.eclipse.hono.config.ClientConfigProperties; +import org.eclipse.hono.util.CacheDirective; +import org.eclipse.hono.util.ExpiringValueCache; +import org.eclipse.hono.util.MessageHelper; +import org.eclipse.hono.util.RequestResponseApiConstants; +import org.eclipse.hono.util.RequestResponseResult; +import org.eclipse.hono.util.TriTuple; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.vertx.core.AsyncResult; +import io.vertx.core.Context; +import io.vertx.core.Future; +import io.vertx.core.Handler; +import io.vertx.core.json.JsonObject; +import io.vertx.proton.ProtonConnection; +import io.vertx.proton.ProtonDelivery; +import io.vertx.proton.ProtonHelper; +import io.vertx.proton.ProtonQoS; +import io.vertx.proton.ProtonReceiver; +import io.vertx.proton.ProtonSender; + +/** + * A Vertx-Proton based parent class for the implementation of API clients that follow the request response pattern. + *

    + * Subclasses only need to implement some abstract helper methods (see the method descriptions) and their own + * API specific methods. This allows for implementation classes that focus on the API specific code. + * + * @param The type of result this client expects the peer to return. + * + */ +public abstract class AbstractRequestResponseClient> + extends AbstractHonoClient implements RequestResponseClient { + + private static final Logger LOG = LoggerFactory.getLogger(AbstractRequestResponseClient.class); + private static final int[] CACHEABLE_STATUS_CODES = new int[] { + HttpURLConnection.HTTP_OK, + HttpURLConnection.HTTP_NOT_AUTHORITATIVE, + HttpURLConnection.HTTP_PARTIAL, + HttpURLConnection.HTTP_MULT_CHOICE, + HttpURLConnection.HTTP_MOVED_PERM, + HttpURLConnection.HTTP_GONE + }; + + private final Map>, Object, Object>> replyMap = new ConcurrentHashMap<>(); + private final String replyToAddress; + private final String targetAddress; + private final String tenantId; + + /** + * A cache to use for responses received from the service. + */ + private ExpiringValueCache responseCache; + + private long requestTimeoutMillis; + + /** + * Creates a request-response client. + *

    + * The client will be ready to use after invoking {@link #createLinks(ProtonConnection)} or + * {@link #createLinks(ProtonConnection, Handler, Handler)} only. + * + * @param context The vert.x context to run message exchanges with the peer on. + * @param config The configuration properties to use. + * @param tenantId The identifier of the tenant that the client is scoped to. May be {@code null}. + * @throws NullPointerException if any of the parameters except tenantId is {@code null}. + */ + AbstractRequestResponseClient(final Context context, final ClientConfigProperties config, final String tenantId) { + super(context, config); + this.requestTimeoutMillis = config.getRequestTimeout(); + this.targetAddress = String.format("%s/%s", getName(), tenantId); + this.replyToAddress = String.format("%s/%s/%s", getName(), tenantId, UUID.randomUUID()); + this.tenantId = tenantId; + } + + /** + * Creates a request-response client for a sender and receiver link. + * + * @param context The vert.x context to run message exchanges with the peer on. + * @param config The configuration properties to use. + * @param tenantId The identifier of the tenant that the client is scoped to. May be {@code null}. + * @param sender The AMQP 1.0 link to use for sending requests to the peer. + * @param receiver The AMQP 1.0 link to use for receiving responses from the peer. + * @throws NullPointerException if any of the parameters except tenantId is {@code null}. + */ + AbstractRequestResponseClient(final Context context, final ClientConfigProperties config, final String tenantId, + final ProtonSender sender, final ProtonReceiver receiver) { + this(context, config, tenantId); + this.sender = Objects.requireNonNull(sender); + this.receiver = Objects.requireNonNull(receiver); + } + + /** + * Sets a cache for responses received from the service. + * + * @param cache The cache or {@code null} if no responses should be cached. + */ + public final void setResponseCache(final ExpiringValueCache cache) { + this.responseCache = cache; + LOG.info("enabling caching of responses from {}", targetAddress); + } + + /** + * Gets the default value for the period of time after which an entry in the response cache + * is considered invalid. + *

    + * The value is derived from the configuration properties as follows: + *

      + *
    1. if the properties are of type {@link RequestResponseClientConfigProperties} + * then the value of its responseCacheDefaultTimeout property is used
    2. + *
    3. otherwise the {@linkplain RequestResponseClientConfigProperties#DEFAULT_RESPONSE_CACHE_TIMEOUT + * default timeout value} is used
    4. + *
    + * + * @return The timeout period in seconds. + */ + protected final long getResponseCacheDefaultTimeout() { + if (config instanceof RequestResponseClientConfigProperties) { + return ((RequestResponseClientConfigProperties) config).getResponseCacheDefaultTimeout(); + } else { + return RequestResponseClientConfigProperties.DEFAULT_RESPONSE_CACHE_TIMEOUT; + } + } + + /** + * Sets the period of time after which any requests are considered to have timed out. + *

    + * The client will fail the result handler passed in to any of the operations if no response + * has been received from the peer after the given amount of time. + *

    + * When setting this property to 0, requests do not time out at all. Note that this will + * allow for unanswered requests piling up in the client, which eventually may cause the + * client to run out of memory. + *

    + * The default value of this property is 200 milliseconds. + * + * @param timoutMillis The number of milliseconds after which a request is considered to have timed out. + * @throws IllegalArgumentException if the value is < 0 + */ + @Override + public final void setRequestTimeout(final long timoutMillis) { + + if (timoutMillis < 0) { + throw new IllegalArgumentException("request timeout must be >= 0"); + } else { + this.requestTimeoutMillis = timoutMillis; + } + } + + /** + * Get the name of the endpoint that this client targets at. + * + * @return The name of the endpoint for this client. + */ + protected abstract String getName(); + + /** + * Build a unique messageId for a request that serves as an identifier for a new message. + * + * @return The unique messageId; + */ + protected abstract String createMessageId(); + + /** + * Creates a result object from the status and payload of a response received from the endpoint. + * + * @param status The status of the response. + * @param payload The String representation of the response's JSON payload (may be {@code null}). + * @param cacheDirective Restrictions regarding the caching of the payload (may be {@code null}). + * @return The result object. + */ + protected abstract R getResult(final int status, final String payload, final CacheDirective cacheDirective); + + /** + * Creates the sender and receiver links to the peer for sending requests + * and receiving responses. + * + * @param con The AMQP 1.0 connection to the peer. + * @return A future indicating the outcome. The future will succeed if the links + * have been created. + * @throws NullPointerException if con is {@code null}. + */ + protected final Future createLinks(final ProtonConnection con) { + return createLinks(con, null, null); + } + + /** + * Creates the sender and receiver links to the peer for sending requests + * and receiving responses. + * + * @param con The AMQP 1.0 connection to the peer. + * @param senderCloseHook A handler to invoke if the peer closes the sender link unexpectedly. + * @param receiverCloseHook A handler to invoke if the peer closes the receiver link unexpectedly. + * @return A future indicating the outcome. The future will succeed if the links + * have been created. + * @throws NullPointerException if connection is {@code null}. + */ + protected final Future createLinks(final ProtonConnection con, final Handler senderCloseHook, final Handler receiverCloseHook) { + + Objects.requireNonNull(con); + + return createReceiver(con, replyToAddress, receiverCloseHook) + .compose(recv -> { + this.receiver = recv; + return createSender(con, targetAddress, senderCloseHook); + }).compose(sender -> { + LOG.debug("request-response client for peer [{}] created", con.getRemoteContainer()); + this.sender = sender; + return Future.succeededFuture(); + }); + } + + private Future createSender(final ProtonConnection con, final String targetAddress, final Handler closeHook) { + + return AbstractHonoClient.createSender(context, config, con, targetAddress, ProtonQoS.AT_LEAST_ONCE, closeHook); + } + + private Future createReceiver(final ProtonConnection con, final String sourceAddress, final Handler closeHook) { + + return AbstractHonoClient.createReceiver(context, config, con, sourceAddress, ProtonQoS.AT_LEAST_ONCE, this::handleResponse, closeHook); + } + + /** + * Handles a response received from the peer. + *

    + * In particular, this method tries to correlate the message with a previous request + * using the message's correlation-id and, if successful, the delivery is accepted + * and the message is passed to the handler registered with the original request. + *

    + * If the response cannot be correlated to a request, e.g. because the request has timed + * out, then the delivery is released and the message is silently discarded. + *

    + * If the client has specified a cache key for the response when sending the request, then the + * {@link #addToCache(Object, RequestResponseResult)} method is invoked + * in order to add the response to the configured cache. + * + * @param delivery The handle for accessing the message's disposition. + * @param message The response message. + */ + protected final void handleResponse(final ProtonDelivery delivery, final Message message) { + + final TriTuple>, Object, Object> handler = replyMap.remove(message.getCorrelationId()); + if (handler != null) { + final R response = getRequestResponseResult(message); + LOG.debug("received response [reply-to: {}, subject: {}, correlation ID: {}, status: {}]", + replyToAddress, message.getSubject(), message.getCorrelationId(), response.getStatus()); + addToCache(handler.two(), response); + handler.one().handle(Future.succeededFuture(response)); + ProtonHelper.accepted(delivery, true); + } else { + LOG.debug("discarding unexpected response [reply-to: {}, correlation ID: {}]", + replyToAddress, message.getCorrelationId()); + ProtonHelper.released(delivery, true); + } + } + + + /** + * Cancels an outstanding request with a given result. + * + * @param correlationId The correlation id of the request to cancel. + * @param result The result to pass to the request's result handler. + * @throws NullPointerException if any of the parameters is {@code null}. + * @throws IllegalArgumentException if the result has not failed. + */ + protected final void cancelRequest(final Object correlationId, final AsyncResult result) { + + Objects.requireNonNull(correlationId); + Objects.requireNonNull(result); + if (!result.failed()) { + throw new IllegalArgumentException("result must be failed"); + } else { + final TriTuple>, Object, Object> handler = replyMap.remove(correlationId); + if (handler != null) { + LOG.debug("canceling request [target: {}, correlation ID: {}]: {}", + targetAddress, correlationId, result.cause().getMessage()); + handler.one().handle(result); + } + } + } + + private R getRequestResponseResult(final Message message) { + final Integer status = MessageHelper.getApplicationProperty( + message.getApplicationProperties(), + MessageHelper.APP_PROPERTY_STATUS, + Integer.class); + final String payload = MessageHelper.getPayload(message); + final CacheDirective cacheDirective = CacheDirective.from(MessageHelper.getCacheDirective(message)); + + return getResult(status, payload, cacheDirective); + } + + /** + * Build a Proton message with a provided subject (serving as the operation that shall be invoked). + * The message can be extended by arbitrary application properties passed in. + *

    + * To enable specific message properties that are not considered here, the method can be overridden by subclasses. + * + * @param subject The subject system property of the message. + * @param appProperties The map containing arbitrary application properties. + * Maybe null if no application properties are needed. + * @return The Proton message constructed from the provided parameters. + * @throws NullPointerException if the subject is {@code null}. + * @throws IllegalArgumentException if the application properties contain not AMQP 1.0 compatible values + * (see {@link AbstractHonoClient#setApplicationProperties(Message, Map)} + */ + private Message createMessage(final String subject, final Map appProperties) { + + Objects.requireNonNull(subject); + final Message msg = ProtonHelper.message(); + final String messageId = createMessageId(); + AbstractHonoClient.setApplicationProperties(msg, appProperties); + msg.setReplyTo(replyToAddress); + msg.setMessageId(messageId); + msg.setSubject(subject); + return msg; + } + + /** + * Creates a request message for a payload and sends it to the peer. + *

    + * This method simply invokes {@link #createAndSendRequest(String, Map, JsonObject, Handler)} + * with {@code null} for the properties parameter. + * + * @param action The operation that the request is supposed to trigger/invoke. + * @param payload The payload to include in the request message as a an AMQP Value section. + * @param resultHandler The handler to notify about the outcome of the request. + * @throws NullPointerException if any of action or result handler is {@code null}. + */ + protected final void createAndSendRequest( + final String action, + final JsonObject payload, + final Handler> resultHandler) { + createAndSendRequest(action, null, payload, resultHandler); + } + + /** + * Creates a request message for a payload and sends it to the peer. + *

    + * This method simply invokes {@link #createAndSendRequest(String, Map, JsonObject, Handler)} + * with {@code null} for the properties parameter. + * + * @param action The operation that the request is supposed to trigger/invoke. + * @param payload The payload to include in the request message as a an AMQP Value section. + * @param resultHandler The handler to notify about the outcome of the request. + * @param cacheKey The key to use for caching the response (if the service allows caching). + * @throws NullPointerException if any of action, result handler or cacheKey is {@code null}. + */ + protected final void createAndSendRequest( + final String action, + final JsonObject payload, + final Handler> resultHandler, + final Object cacheKey) { + createAndSendRequest(action, null, payload, resultHandler, cacheKey); + } + + /** + * Creates a request message for a payload and headers and sends it to the peer. + * + * @param action The operation that the request is supposed to trigger/invoke. + * @param properties The headers to include in the request message as AMQP application properties. + * @param payload The payload to include in the request message as a an AMQP Value section. + * @param resultHandler The handler to notify about the outcome of the request. The handler is failed with + * a {@link ServerErrorException} if the request cannot be sent to the remote service, + * e.g. because there is no connection to the service or there are no credits available + * for sending the request or the request timed out. + * @throws NullPointerException if action or result handler are {@code null}. + * @throws IllegalArgumentException if the properties contain any non-primitive typed values. + * @see AbstractHonoClient#setApplicationProperties(Message, Map) + */ + protected final void createAndSendRequest(final String action, final Map properties, final JsonObject payload, + final Handler> resultHandler) { + createAndSendRequest(action, properties, payload, resultHandler, null); + } + + /** + * Creates a request message for a payload and headers and sends it to the peer. + *

    + * This method first checks if the sender has any credit left. If not, the result handler is failed immediately. + * Otherwise, the request message is sent and a timer is started which fails the result handler, + * if no response is received within requestTimeout milliseconds. + * + * @param action The operation that the request is supposed to trigger/invoke. + * @param properties The headers to include in the request message as AMQP application properties. + * @param payload The payload to include in the request message as a an AMQP Value section. + * @param resultHandler The handler to notify about the outcome of the request. The handler is failed with + * a {@link ServerErrorException} if the request cannot be sent to the remote service, + * e.g. because there is no connection to the service or there are no credits available + * for sending the request or the request timed out. + * @param cacheKey The key to use for caching the response (if the service allows caching). + * @throws NullPointerException if action or result handler are {@code null}. + * @throws IllegalArgumentException if the properties contain any non-primitive typed values. + * @see AbstractHonoClient#setApplicationProperties(Message, Map) + */ + protected final void createAndSendRequest( + final String action, + final Map properties, + final JsonObject payload, + final Handler> resultHandler, + final Object cacheKey) { + + Objects.requireNonNull(action); + Objects.requireNonNull(resultHandler); + + if (isOpen()) { + final Message request = createMessage(action, properties); + if (payload != null) { + request.setContentType(RequestResponseApiConstants.CONTENT_TYPE_APPLICATION_JSON); + request.setBody(new AmqpValue(payload.encode())); + } + sendRequest(request, resultHandler, cacheKey); + } else { + resultHandler.handle(Future.failedFuture(new ServerErrorException( + HttpURLConnection.HTTP_UNAVAILABLE, "sender and/or receiver link is not open"))); + } + } + + /** + * Sends a request message via this client's sender link to the peer. + *

    + * This method first checks if the sender has any credit left. If not, the result handler is failed immediately. + * Otherwise, the request message is sent and a timer is started which fails the result handler, + * if no response is received within requestTimeoutMillis milliseconds. + * + * @param request The message to send. + * @param resultHandler The handler to notify about the outcome of the request. + * @param cacheKey The key to use for caching the response (if the service allows caching). + */ + private final void sendRequest(final Message request, final Handler> resultHandler, final Object cacheKey) { + + context.runOnContext(req -> { + if (sender.sendQueueFull()) { + LOG.debug("cannot send request to peer, no credit left for link [target: {}]", targetAddress); + resultHandler.handle(Future.failedFuture(new ServerErrorException( + HttpURLConnection.HTTP_UNAVAILABLE, "no credit available for sending request"))); + } else { + final Object correlationId = Optional.ofNullable(request.getCorrelationId()).orElse(request.getMessageId()); + final TriTuple>, Object, Object> handler = TriTuple.of(resultHandler, cacheKey, null); + replyMap.put(correlationId, handler); + sender.send(request, deliveryUpdated -> { + if (Rejected.class.isInstance(deliveryUpdated.getRemoteState())) { + final Rejected rejected = (Rejected) deliveryUpdated.getRemoteState(); + if (rejected.getError() != null) { + LOG.debug("service did not accept request [target address: {}, subject: {}, correlation ID: {}]: {}", + targetAddress, request.getSubject(), correlationId, rejected.getError()); + + cancelRequest(correlationId, Future.failedFuture(StatusCodeMapper.from(rejected.getError()))); + } else { + LOG.debug("service did not accept request [target address: {}, subject: {}, correlation ID: {}]", + targetAddress, request.getSubject(), correlationId); + cancelRequest(correlationId, Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST))); + } + } else if (Accepted.class.isInstance(deliveryUpdated.getRemoteState())) { + LOG.trace("service has accepted request [target address: {}, subject: {}, correlation ID: {}]", + targetAddress, request.getSubject(), correlationId); + } else { + LOG.debug("service did not accept request [target address: {}, subject: {}, correlation ID: {}]: {}", + targetAddress, request.getSubject(), correlationId, deliveryUpdated.getRemoteState()); + cancelRequest(correlationId, Future.failedFuture(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE))); + } + }); + if (requestTimeoutMillis > 0) { + context.owner().setTimer(requestTimeoutMillis, tid -> { + cancelRequest(correlationId, Future.failedFuture(new ServerErrorException( + HttpURLConnection.HTTP_UNAVAILABLE, "request timed out after " + requestTimeoutMillis + "ms"))); + }); + } + if (LOG.isDebugEnabled()) { + final String deviceId = MessageHelper.getDeviceId(request); + if (deviceId == null) { + LOG.debug("sent request [target address: {}, subject: {}, correlation ID: {}] to service", + targetAddress, request.getSubject(), correlationId); + } else { + LOG.debug("sent request [target address: {}, subject: {}, correlation ID: {}, device ID: {}] to service", + targetAddress, request.getSubject(), correlationId, deviceId); + } + } + } + }); + } + + /** + * Checks if this client's sender and receiver links are open. + * + * @return {@code true} if a request can be sent to and a response can be received + * from the peer. + */ + @Override + public final boolean isOpen() { + return sender != null && sender.isOpen() && receiver != null && receiver.isOpen(); + } + + @Override + public final void close(final Handler> closeHandler) { + + Objects.requireNonNull(closeHandler); + LOG.info("closing request-response client ..."); + closeLinks(closeHandler); + } + + /** + * Checks if this client supports caching of results. + * + * @return {@code true} if caching is supported. + */ + protected final boolean isCachingEnabled() { + return responseCache != null; + } + + /** + * Gets a response from the cache. + * + * @param key The key to get the response for. + * @return A succeeded future containing the response from the cache + * or a failed future if no response exists for the key + * or the response is expired. + */ + protected Future getResponseFromCache(final Object key) { + + if (responseCache == null) { + return Future.failedFuture(new IllegalStateException("no cache configured")); + } else { + final R result = responseCache.get(key); + if (result == null) { + return Future.failedFuture("cache miss"); + } else { + return Future.succeededFuture(result); + } + } + } + + /** + * Adds a response to the cache. + *

    + * If the cache key is {@code null} or no cache is configured then this method does nothing. + *

    + * Otherwise + *

      + *
    1. if the response does not contain any cache directive and the response's status code is + * one of the codes defined by + * RFC 2616, Section 13.4 Response Cacheability, the response is put to the cache using + * the default timeout returned by {@link #getResponseCacheDefaultTimeout()}
    2. + *
    3. else if the response contains a max-age directive, the response + * is put to the cache using the max age from the directive.
    4. + *
    5. else if the response contains a no-cache directive, the response + * is not put to the cache.
    6. + *
    + * + * @param key The key to use for the response. + * @param response The response to cache. + * @throws NullPointerException if response is {@code null}. + */ + protected final void addToCache(final Object key, final R response) { + + Objects.requireNonNull(response); + + if (responseCache != null && key != null) { + + final CacheDirective cacheDirective = Optional.ofNullable(response.getCacheDirective()) + .orElseGet(() -> { + if (isCacheableStatusCode(response.getStatus())) { + return CacheDirective.maxAgeDirective(getResponseCacheDefaultTimeout()); + } else { + return CacheDirective.noCacheDirective(); + } + }); + + if (cacheDirective.isCachingAllowed()) { + if (cacheDirective.getMaxAge() > 0) { + responseCache.put(key, response, Duration.ofSeconds(cacheDirective.getMaxAge())); + } + } + } + } + + private boolean isCacheableStatusCode(final int code) { + return Arrays.binarySearch(CACHEABLE_STATUS_CODES, code) >= 0; + } + + /** + * Get the tenantId of the tenant for that this client was created for. + + * @return The tenantId for that this client was created for. + */ + protected final String getTenantId() { + return tenantId; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `status` last assigned on line 315 could be null and is dereferenced at line 322. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +RequestResponseResult AbstractRequestResponseClient.getRequestResponseResult(Message) + +### Procedure Id: +org.eclipse.hono.client.impl.AbstractRequestResponseClient.getRequestResponseResult(org.apache.qpid..ea67880c2bde77f704e2cec87646438b + +### File: +client/src/main/java/org/eclipse/hono/client/impl/AbstractRequestResponseClient.java + +### Key: +AbstractRequestResponseClient.java|getRequestResponseResult|NULL_DEREFERENCE + +### Node Key: +7a5878ddad975428c0be666b67754bff + +### Hash: +61906be8efd26f7a442b0e3997ae9141 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8044/instruction.md b/inferredbugs-8044/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..35046e12afc9e8a60c63577eacbbc1de0bb3290a --- /dev/null +++ b/inferredbugs-8044/instruction.md @@ -0,0 +1,601 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** hono +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) 2017 Bosch Software Innovations GmbH. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Bosch Software Innovations GmbH - initial creation + */ + +package org.eclipse.hono.client.impl; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.eclipse.hono.client.HonoClient; +import org.eclipse.hono.client.MessageSender; +import org.eclipse.hono.client.RegistrationClient; +import org.eclipse.hono.client.RequestResponseClient; +import org.eclipse.hono.client.ServerErrorException; +import org.eclipse.hono.connection.ConnectionFactory; +import org.eclipse.hono.util.Constants; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import io.vertx.core.AsyncResult; +import io.vertx.core.Future; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.ext.unit.Async; +import io.vertx.ext.unit.TestContext; +import io.vertx.ext.unit.junit.VertxUnitRunner; +import io.vertx.proton.ProtonClientOptions; +import io.vertx.proton.ProtonConnection; + +/** + * Test cases verifying the behavior of {@code HonoClient}. + * + */ +@RunWith(VertxUnitRunner.class) +public class HonoClientImplTest { + Vertx vertx; + + /** + * Sets up common test bed. + */ + @Before + public void setUp() { + vertx = Vertx.vertx(); + } + + /** + * Cleans up after test execution. + * + * @param ctx The helper to use for running async tests. + */ + @After + public void shutdown(final TestContext ctx) { + if (vertx != null) { + vertx.close(ctx.asyncAssertSuccess()); + } + } + /** + * Verifies that a concurrent request to create a request-response client fails the given + * future for tracking the attempt. + * + * @param ctx The helper to use for running async tests. + */ + @Test + public void testGetOrCreateRequestResponseClientFailsIfInvokedConcurrently(final TestContext ctx) { + + // GIVEN a client that already tries to create a registration client for "tenant" + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); + final Future firstClientTracker = Future.future(); + client.getOrCreateRequestResponseClient("registration/tenant", handler -> { + firstClientTracker.setHandler(creationAttempt -> { + handler.handle(creationAttempt); + }); + }, result -> {}); + + // WHEN an additional, concurrent attempt is made to create a client for "tenant" + final Async creationFailure = ctx.async(); + client.getOrCreateRequestResponseClient("registration/tenant", handler -> { + handler.handle(Future.succeededFuture(mock(RegistrationClient.class))); + }, ctx.asyncAssertFailure(t -> { + ctx.assertTrue(ServerErrorException.class.isInstance(t)); + creationFailure.complete(); + })); + + // succeed first creation attempt, thus invoking result handler + firstClientTracker.complete(mock(RegistrationClient.class)); + + // THEN the concurrent attempt fails immediately without any attempt being made to create another client + creationFailure.await(2000); + } + + /** + * Verifies that a request to create a request-response client is failed immediately when the + * underlying connection to the server fails. + * + * @param ctx The Vertx test context. + */ + @Test + public void testGetOrCreateRequestResponseClientFailsOnConnectionFailure(final TestContext ctx) { + + // GIVEN a client that tries to create a registration client for "tenant" + ProtonConnection con = mock(ProtonConnection.class); + DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con); + final Async connected = ctx.async(); + final Async disconnected = ctx.async(); + HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); + client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete())); + connected.await(200); + + client.getOrCreateRequestResponseClient("registration/tenant", creationResultHandler -> { + ctx.assertFalse(disconnected.isCompleted()); + }, ctx.asyncAssertFailure(cause -> { + disconnected.complete(); + })); + + // WHEN the underlying connection fails + connectionFactory.getDisconnectHandler().handle(con); + + // THEN all creation requests are failed + disconnected.await(200); + } + + /** + * Verifies that a concurrent request to create a sender fails the given future for tracking the attempt. + * + * @param ctx The helper to use for running async tests. + */ + @Test + public void testGetOrCreateTelemetrySenderFailsIfInvokedConcurrently(final TestContext ctx) { + + // GIVEN a client that already tries to create a telemetry sender for "tenant" + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); + final Future firstSenderTracker = Future.future(); + client.getOrCreateSender("telemetry/tenant", handler -> { + firstSenderTracker.setHandler(creationAttempt -> { + handler.handle(creationAttempt); + }); + }, result -> {}); + + // WHEN an additional, concurrent attempt is made to create a telemetry sender for "tenant" + final Async creationFailure = ctx.async(); + client.getOrCreateSender("telemetry/tenant", handler -> { + handler.handle(Future.succeededFuture(mock(MessageSender.class))); + }, ctx.asyncAssertFailure(t -> { + ctx.assertTrue(ServerErrorException.class.isInstance(t)); + creationFailure.complete(); + })); + + // succeed first creation attempt, thus invoking result handler + firstSenderTracker.complete(mock(MessageSender.class)); + + // THEN the concurrent attempt fails immediately without any attempt being made to create another sender + creationFailure.await(2000); + } + + /** + * Verifies that a request to create a message sender is failed immediately when the + * underlying connection to the server fails. + * + * @param ctx The Vertx test context. + */ + @Test + public void testGetOrCreateSenderFailsOnConnectionFailure(final TestContext ctx) { + + // GIVEN a client that tries to create a telemetry sender for "tenant" + ProtonConnection con = mock(ProtonConnection.class); + DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con); + final Async connected = ctx.async(); + final Async disconnected = ctx.async(); + HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); + client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete())); + connected.await(200); + + client.getOrCreateSender("telemetry/tenant", creationResultHandler -> { + ctx.assertFalse(disconnected.isCompleted()); + }, ctx.asyncAssertFailure(cause -> { + disconnected.complete(); + })); + + // WHEN the underlying connection fails + connectionFactory.getDisconnectHandler().handle(con); + + // THEN all creation requests are failed + disconnected.await(200); + } + + /** + * Verifies that a request to create a telemetry consumer is failed immediately when the + * underlying connection to the server fails. + * + * @param ctx The Vertx test context. + */ + @Test + public void testCreateTelemetryConsumerFailsOnConnectionFailure(final TestContext ctx) { + + // GIVEN a client that already tries to create a telemetry sender for "tenant" + ProtonConnection con = mock(ProtonConnection.class); + DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con); + final Async connected = ctx.async(); + final Async disconnected = ctx.async(); + HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); + client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete())); + connected.await(200); + + client.createTelemetryConsumer("tenant", msg -> {}, ctx.asyncAssertFailure(cause -> { + disconnected.complete(); + })); + + // WHEN the underlying connection fails + connectionFactory.getDisconnectHandler().handle(con); + + // THEN all creation requests are failed + disconnected.await(200); + } + + /** + * Verifies that a request to create an event consumer is failed immediately when the + * underlying connection to the server fails. + * + * @param ctx The Vertx test context. + */ + @Test + public void testCreateEventConsumerFailsOnConnectionFailure(final TestContext ctx) { + + // GIVEN a client that already tries to create a telemetry sender for "tenant" + ProtonConnection con = mock(ProtonConnection.class); + DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con); + final Async connected = ctx.async(); + HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); + client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete())); + connected.await(200); + + final Async disconnected = ctx.async(); + client.createEventConsumer("tenant", msg -> {}, ctx.asyncAssertFailure(cause -> { + disconnected.complete(); + })); + + // WHEN the underlying connection fails + connectionFactory.getDisconnectHandler().handle(con); + + // THEN all creation requests are failed + disconnected.await(200); + } + + /** + * Verifies that all sender creation locks are cleared when the connection to the server fails. + * + * @param ctx The Vertx test context. + */ + @Test + public void testDownstreamDisconnectClearsSenderCreationLocks(final TestContext ctx) { + + final ProtonConnection connectionToCreate = mock(ProtonConnection.class); + when(connectionToCreate.getRemoteContainer()).thenReturn("server"); + // expect the connection factory to be invoked twice + // first on initial connection + // second on reconnect + DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(connectionToCreate, 2); + + // GIVEN a client connected to a server + final Async connected = ctx.async(); + HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); + client.connect(new ProtonClientOptions().setReconnectAttempts(1), ctx.asyncAssertSuccess(ok -> connected.complete())); + connected.await(200); + + final Async senderCreationFailure = ctx.async(); + // WHEN the downstream connection fails just when the client wants to open a sender link + client.getOrCreateSender("telemetry/tenant", creationAttemptHandler -> { + connectionFactory.getDisconnectHandler().handle(connectionToCreate); + // the creationAttempHandler will not be invoked at all + }, ctx.asyncAssertFailure(cause -> senderCreationFailure.complete())); + + // THEN the sender creation fails, + senderCreationFailure.await(1000); + // the connection is re-established + connectionFactory.await(1, TimeUnit.SECONDS); + // and the next attempt to create a sender succeeds + final Async senderSupplierInvocation = ctx.async(); + client.getOrCreateSender("telemetry/tenant", creationAttemptHandler -> { + senderSupplierInvocation.complete(); + creationAttemptHandler.handle(Future.succeededFuture(mock(MessageSender.class))); + }, ctx.asyncAssertSuccess()); + senderSupplierInvocation.await(1000); + } + + /** + * Verifies that the client tries to re-establish a lost connection to a server. + * + * @param ctx The Vertx test context. + */ + @Test + public void testDownstreamDisconnectTriggersReconnect(final TestContext ctx) { + + final ProtonConnection connectionToCreate = mock(ProtonConnection.class); + when(connectionToCreate.getRemoteContainer()).thenReturn("server"); + // expect the connection factory to be invoked twice + // first on initial connection + // second on re-connect attempt + DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(connectionToCreate, 2); + + // GIVEN an client connected to a server + final Async connected = ctx.async(); + HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); + client.connect(new ProtonClientOptions().setReconnectAttempts(1), ctx.asyncAssertSuccess(ok -> connected.complete())); + connected.await(200); + + // WHEN the downstream connection fails + connectionFactory.getDisconnectHandler().handle(connectionToCreate); + + // THEN the adapter tries to reconnect to the downstream container + connectionFactory.await(1, TimeUnit.SECONDS); + } + + /** + * Verifies that the client adapter repeatedly tries to connect until a connection is established. + * + * @param ctx The test context. + */ + @Test + public void testConnectTriesToReconnectOnFailedConnectAttempt(final TestContext ctx) { + + // GIVEN a client that cannot connect to the server + ProtonConnection con = mock(ProtonConnection.class); + // expect the connection factory to fail twice and succeed on third connect attempt + DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con, 1, 2); + HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); + + // WHEN trying to connect + Async disconnectHandlerInvocation = ctx.async(); + Async connectionEstablished = ctx.async(); + Handler disconnectHandler = failedCon -> disconnectHandlerInvocation.complete(); + client.connect( + new ProtonClientOptions().setReconnectAttempts(1), + ctx.asyncAssertSuccess(ok -> connectionEstablished.complete()), + disconnectHandler); + + // THEN the client repeatedly tries to connect + connectionEstablished.await(4 * Constants.DEFAULT_RECONNECT_INTERVAL_MILLIS); + // and sets the disconnect handler provided as a param in the connect method invocation + connectionFactory.getDisconnectHandler().handle(con); + disconnectHandlerInvocation.await(1000); + } + + /** + * Verifies that the client tries to re-connect to a server instance if the connection is closed by the peer. + * + * @param ctx The test context. + * + */ + @Test + public void testOnRemoteCloseTriggersReconnection(final TestContext ctx) { + + // GIVEN a client that is connected to a server + ProtonConnection con = mock(ProtonConnection.class); + DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con, 2); + HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); + Async disconnectHandlerInvocation = ctx.async(); + Handler disconnectHandler = failedCon -> disconnectHandlerInvocation.complete(); + client.connect(new ProtonClientOptions().setReconnectAttempts(1), attempt -> {}, disconnectHandler); + + // WHEN the peer closes the connection + connectionFactory.getCloseHandler().handle(Future.failedFuture("shutting down for maintenance")); + + // THEN the client invokes the disconnect handler provided in the original connect method call + disconnectHandlerInvocation.await(500); + } + + /** + * Verifies that it fails to connect after client was shutdown. + * + * @param ctx The test context. + * + */ + @Test + public void testConnectFailsAfterShutdown(final TestContext ctx) { + + // GIVEN a shutdown client + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); + client.shutdown(); + + // WHEN client connects + Async connectionHandlerInvocation = ctx.async(); + Handler> connectionHandler = result -> { + if (result.failed()) { + connectionHandlerInvocation.complete(); + } + }; + client.connect(new ProtonClientOptions(), connectionHandler ); + + //THEN connect fails + connectionHandlerInvocation.await(500); + } + + /** + * Verifies that the client does not try to re-connect to a server instance if the client was shutdown. + * + * @param ctx The test context. + * + */ + @Test + public void testDoesNotTriggerReconnectionAfterShutdown(final TestContext ctx) { + + // GIVEN a client that tries to connect to a server but does not succeed + ProtonConnection con = mock(ProtonConnection.class); + DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con, 1, Integer.MAX_VALUE); + HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory); + Async connectionHandlerInvocation = ctx.async(); + Handler> connectionHandler = result -> { + if (result.failed()) { + connectionHandlerInvocation.complete(); + } + }; + client.connect(new ProtonClientOptions().setReconnectAttempts(1), connectionHandler); + + // WHEN client gets shutdown + client.shutdown(); + + // THEN reconnect gets stopped, i.e. connection fails + connectionHandlerInvocation.await(1000); + } + + private class DisconnectHandlerProvidingConnectionFactory implements ConnectionFactory { + + private Handler disconnectHandler; + private Handler> closeHandler; + private CountDownLatch expectedSucceedingConnectionAttemps; + private CountDownLatch expectedFailingConnectionAttempts; + private ProtonConnection connectionToCreate; + + public DisconnectHandlerProvidingConnectionFactory(final ProtonConnection conToCreate) { + this(conToCreate, 1); + } + + public DisconnectHandlerProvidingConnectionFactory(final ProtonConnection conToCreate, final int expectedSucceedingConnectionAttempts) { + this(conToCreate, expectedSucceedingConnectionAttempts, 0); + } + + public DisconnectHandlerProvidingConnectionFactory(final ProtonConnection conToCreate, final int expectedSucceedingConnectionAttempts, + final int expectedFailingConnectionAttempts) { + this.connectionToCreate = conToCreate; + this.expectedSucceedingConnectionAttemps = new CountDownLatch(expectedSucceedingConnectionAttempts); + this.expectedFailingConnectionAttempts = new CountDownLatch(expectedFailingConnectionAttempts); + } + + @Override + public void connect( + final ProtonClientOptions options, + final Handler> closeHandler, + final Handler disconnectHandler, + final Handler> connectionResultHandler) { + connect(options, null, null, closeHandler, disconnectHandler, connectionResultHandler); + } + + @Override + public void connect( + final ProtonClientOptions options, + final String username, + final String password, + final Handler> closeHandler, + final Handler disconnectHandler, + final Handler> connectionResultHandler) { + + this.closeHandler = closeHandler; + this.disconnectHandler = disconnectHandler; + if (expectedFailingConnectionAttempts.getCount() > 0) { + expectedFailingConnectionAttempts.countDown(); + connectionResultHandler.handle(Future.failedFuture("cannot connect")); + } else { + expectedSucceedingConnectionAttemps.countDown(); + connectionResultHandler.handle(Future.succeededFuture(connectionToCreate)); + } + } + + @Override + public String getName() { + return "client"; + } + + @Override + public String getHost() { + return "server"; + } + + @Override + public int getPort() { + return Constants.PORT_AMQP; + } + + @Override + public String getPathSeparator() { + return Constants.DEFAULT_PATH_SEPARATOR; + } + + public Handler getDisconnectHandler() { + return disconnectHandler; + } + + public Handler> getCloseHandler() { + return closeHandler; + } + + public boolean await(long timeout, TimeUnit unit) { + try { + return expectedSucceedingConnectionAttemps.await(timeout, unit); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `connectionFactory.getDisconnectHandler()` could be null and is dereferenced at line 322. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void HonoClientImplTest.testDownstreamDisconnectTriggersReconnect(TestContext) + +### Procedure Id: +org.eclipse.hono.client.impl.HonoClientImplTest.testDownstreamDisconnectTriggersReconnect(io.vertx.e.4fa14ed0bbe6f6bb85967cefcc765a4f + +### File: +client/src/test/java/org/eclipse/hono/client/impl/HonoClientImplTest.java + +### Key: +HonoClientImplTest.java|testDownstreamDisconnectTriggersReconnect|NULL_DEREFERENCE + +### Node Key: +2c28ed546cbb1713e2441d81645be2f7 + +### Hash: +6a06024178b8e71f34f4f51b2cbf7467 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8081/instruction.md b/inferredbugs-8081/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b8f8b1108b8b5a9fa979d613deda248af341d0b4 --- /dev/null +++ b/inferredbugs-8081/instruction.md @@ -0,0 +1,2662 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sqlline +**Bug ID:** 35 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +// Licensed to Julian Hyde under one or more contributor license +// agreements. See the NOTICE file distributed with this work for +// additional information regarding copyright ownership. +// +// Julian Hyde licenses this file to you under the Modified BSD License +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/BSD-3-Clause +*/ +package sqlline; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.h2.util.StringUtils; +import org.hamcrest.BaseMatcher; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hsqldb.jdbc.CustomDatabaseMetadata; +import org.hsqldb.jdbc.JDBCConnection; +import org.hsqldb.jdbc.JDBCDatabaseMetaData; +import org.hsqldb.jdbc.JDBCResultSet; +import org.hsqldb.jdbc.JDBCResultSetMetaData; +import org.jline.builtins.Commands; +import org.jline.terminal.Terminal; +import org.junit.jupiter.api.Test; + +import mockit.Expectations; +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.internal.reflection.FieldReflection; +import net.hydromatic.scott.data.hsqldb.ScottHsqldb; +import sqlline.extensions.CustomApplication; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Executes tests of the command-line arguments to SqlLine. + */ +public class SqlLineArgsTest { + private static final ConnectionSpec CONNECTION_SPEC = ConnectionSpec.HSQLDB; + private ConnectionSpec connectionSpec; + + public SqlLineArgsTest() { + connectionSpec = CONNECTION_SPEC; + } + + static SqlLine.Status begin(SqlLine sqlLine, OutputStream os, + boolean saveHistory, String... args) { + try { + PrintStream beelineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(beelineOutputStream); + sqlLine.setErrorStream(beelineOutputStream); + final InputStream is = new ByteArrayInputStream(new byte[0]); + return sqlLine.begin(args, is, saveHistory); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Execute a script with "beeline -f". + * + * @return The stderr and stdout from running the script + * @param args Script arguments + */ + private static Pair run(String... args) { + try { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = begin(beeLine, os, false, args); + return new Pair(status, os.toString("UTF8")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + private Pair runScript(File scriptFile, boolean flag, String outputFileName) { + return runScript(connectionSpec, scriptFile, flag, outputFileName); + } + + private static Pair runScript(ConnectionSpec connectionSpec, File scriptFile, + boolean flag, String outputFileName) { + List args = new ArrayList<>(); + Collections.addAll(args, + "-d", connectionSpec.driver, + "-u", connectionSpec.url, + "-n", connectionSpec.username, + "-p", connectionSpec.password); + if (flag) { + args.add("-f"); + args.add(scriptFile.getAbsolutePath()); + } else { + args.add("--run=" + scriptFile.getAbsolutePath()); + } + if (outputFileName != null) { + args.add("-log"); + args.add(outputFileName); + } + return run(args.toArray(new String[0])); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * Tests for presence of an expected pattern in the output (stdout or stderr). + * + * @param scriptText Script text + * @param flag Command flag (--run or -f) + * @param statusMatcher Checks whether status is as expected + * @param outputMatcher Checks whether output is as expected + */ + private void checkScriptFile(String scriptText, boolean flag, + Matcher statusMatcher, + Matcher outputMatcher) { + try { + // Put the script content in a temp file + File scriptFile = createTempFile("foo", "temp"); + PrintStream os = + new PrintStream( + new FileOutputStream(scriptFile), + false, + StandardCharsets.UTF_8.name()); + os.print(scriptText); + os.close(); + + Pair pair = runScript(scriptFile, flag, null); + + // Check output before status. It gives a better clue what went wrong. + assertThat(toLinux(pair.output), outputMatcher); + assertThat(pair.status, statusMatcher); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Windows line separators in a string into Linux line separators; + * a Linux string is unchanged. */ + private static String toLinux(String s) { + return s.replaceAll("\r\n", "\n"); + } + + private File createTempFile(String prefix, String suffix) { + return createTempFile(prefix, suffix, null); + } + + private File createTempFile(String prefix, String suffix, Path directory) { + try { + final File file = directory == null + ? Files.createTempFile(prefix, suffix).toFile() + : Files.createTempFile(directory, prefix, suffix).toFile(); + file.deleteOnExit(); + return file; + } catch (IOException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMultilineScriptWithComments() { + final String script1Text = + "!set incremental true\n" + + "-- a comment \n values\n--comment\n (\n1\n, ' ab'\n--comment\n)\n;\n"; + + checkScriptFile(script1Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-------------+-----+\n" + + "| C1 | C2 |\n" + + "+-------------+-----+\n" + + "| 1 | ab |\n" + + "+-------------+-----+")); + + final String script2Text = + "!set incremental true\n" + + "--comment \n --comment2 \nvalues (';\n' /* comment */, '\"'" + + "/*multiline;\n ;\n comment*/)\n -- ; \n; -- comment"; + + checkScriptFile(script2Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-----+----+\n" + + "| C1 | C2 |\n" + + "+-----+----+\n" + + "| ; \n" + + " | \" |\n" + + "+-----+----+")); + } + + /** + * Attempt to execute a simple script file with the -f option to SqlLine. + * Test for presence of an expected pattern + * in the output (stdout or stderr), fail if not found. + */ + @Test + public void testPositiveScriptFile() { + checkScriptFile("call 100 + 23;\n", + true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * As above, but using '-run' rather than '-f'. + */ + @Test + public void testPositiveScriptFileUsingRun() { + checkScriptFile("call 100 + 23;\n", + false, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * Test case for + * [SQLLINE-42], + * Script fails if first line is a comment. + */ + @Test + public void testScriptFileStartsWithComment() { + final String scriptText = "-- a comment\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileStartsWithEmptyLine() { + final String scriptText = "\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileContainsComment() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithComments() { + final String scriptText = "--comment\n\n" + + "values \n10 \n+ \n23;\n\n\n" + + "-- a comment\n" + + "\n\nvalues " + + "--comment inside\n\n" + + "100 --comment inside\n\n" + + "+ \n\n23\n\n\n;\n\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithMultilineQuotedStrings() { + final String scriptText = "--comment\n\n" + + "values '\nmultiline;\n;\n; string\n'" + + ";\n\n\n" + + "values '\nmultiline2;\n;\n; string2\n'" + + ";\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString("multiline2;"), containsString("; string2"))); + } + + @Test + public void testScriptWithMultilineStatementsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment\n\n" + + "values 1;values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 1 |\n" + + "+----+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + + @Test + public void testScriptWithMultilineStatementsAndCommentsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment;;\n\n" + + "select * from (values ';') t (\";\");/*;select 1;*/values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+---+\n" + + "| ; |\n" + + "+---+\n" + + "| ; |\n" + + "+---+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + /** + * Tests sql with H2 specific one-line comment '//' + */ + @Test + public void testMultilineScriptWithH2Comments() { + final SqlLine sqlLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + final File tmpHistoryFile = createTempFile("queryToExecute", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + final String script = "\n" + + "\n" + + "!set incremental true\n" + + "\n" + + "\n" + + "select * from information_schema.tables// ';\n" + + "// \";" + + ";\n" + + "\n" + + "\n"; + bw.write(script); + bw.flush(); + } + SqlLine.Status status = + begin(sqlLine, os, false, + "-u", ConnectionSpec.H2.url, + "-n", ConnectionSpec.H2.username, + "--run=" + tmpHistoryFile.getAbsolutePath()); + assertThat(status, equalTo(SqlLine.Status.OK)); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |" + + " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |"; + assertThat(output, containsString(expected)); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-72] + * Allow quoted file names (including spaces) in !record, + * !run and !script commands. */ + @Test + public void testScriptFilenameWithSpace() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23;\n"; + File scriptFile = createTempFile("Script with Spaces", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + allOf(containsString(" 33 "), containsString(" 123 "))); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScriptWithOutput() { + final String scriptText = "!set maxcolumnwidth 20\n" + + "!set incremental true\n" + + "values 100 + 123;\n" + + "-- a comment\n" + + "values 100 + 253;\n"; + + File scriptFile = createTempFile("Script file name", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + + File outputFile = createTempFile("testScriptWithOutput", ".out"); + runScript(scriptFile, true, outputFile.getAbsolutePath()); + assertFileContains(outputFile, + allOf(containsString("| 223 |"), + containsString("| 353 |"))); + final boolean delete = outputFile.delete(); + assertThat(delete, is(true)); + } + + /** + * Values that contain null. + */ + @Test + public void testNull() { + final String script = "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString( + "+-------------+-------------+-----+\n" + + "| C1 | C2 | C3 |\n" + + "+-------------+-------------+-----+\n" + + "| 1 | null | |\n" + + "+-------------+-------------+-----+\n")); + } + + @Test + public void testScan() { + final String expectedLine0 = "Compliant Version Driver Class"; + final String expectedLine1 = "yes 2.4 org.hsqldb.jdbc.JDBCDriver"; + checkScriptFile("!scan\n", false, + equalTo(SqlLine.Status.OK), + allOf(containsString(expectedLine0), containsString(expectedLine1))); + } + + /** + * Table output without header. + */ + @Test + public void testTableOutputNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("| 1 | null | |\n")); + } + + /** + * Csv output without header. + */ + @Test + public void testCsvNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set outputformat csv\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("'1','null',''\n")); + } + + /** + * Tests the "close" command, + * [HIVE-5768] + * Beeline connection cannot be closed with '!close' command and + * [SQLLINE-139] + * Look for the exact match if there are multiple matches. + */ + @Test + public void testClose() { + final String expected = "!close\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile("!close\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + /** + * Test case for + * [SQLLINE-32] + * !help set' should print documentation for all variables. + */ + @Test + public void testHelpSet() { + final String expected = "1/1 !help set\n" + + "!set List / set a sqlline variable\n" + + "\n" + + "Variables:\n" + + "\n" + + "Variable Value Description\n" + + "=============== ========== " + + "==================================================\n" + + "autoCommit true/false " + + "Enable/disable automatic transaction commit\n" + + "autoSave true/false Automatically save preferences\n"; + checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + + // Make sure that each variable (autoCommit, autoSave, color, etc.) has a + // line in the output of '!help set' + final SqlLine sqlLine = new SqlLine(); + String help = sqlLine.loc("help-set") + + sqlLine.loc("variables"); + + final TreeSet propertyNamesMixed = + Arrays.stream(BuiltInProperty.values()) + .map(BuiltInProperty::propertyName) + .collect(Collectors.toCollection(TreeSet::new)); + for (String p : propertyNamesMixed) { + assertThat(help, containsString("\n" + p + " ")); + } + assertThat(propertyNamesMixed.contains("autoCommit"), + is(true)); + assertThat(propertyNamesMixed.contains("autocommit"), + is(false)); + assertThat(propertyNamesMixed.contains("trimScripts"), + is(true)); + + while (help.length() > 0) { + int i = help.indexOf("\n", 1); + if (i < 0) { + break; + } + if (i > 78) { + fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i)); + } + help = help.substring(i); + } + } + + /** + * Test case for + * [SQLLINE-39] + * 'help set' should not break long lines. + * + *

    But it should break 'help all', which consists of a single long line. + */ + @Test + public void testHelpAll() { + // Note that "connections" has been broken onto a new line. + final String expected = "1/1 !help all\n" + + "!all Execute the specified SQL against all the current\n" + + " connections\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help all\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + + /** + * Tests "!go <non-existent connection indexes>". + */ + @Test + public void testGoFailing() { + final String[] connectionIndexes = {"321", "invalid"}; + for (String connectionIndex : connectionIndexes) { + final String script = "!go " + connectionIndex + "\n"; + final String expected = "Invalid connection: " + connectionIndex; + checkScriptFile(script, false, + // Status.OTHER as checking of fail cases + equalTo(SqlLine.Status.OTHER), containsString(expected)); + } + } + + /** + * Tests "!help go". "go" and "#" are synonyms. + */ + @Test + public void testHelpGo() { + for (String c : new String[] {"go", "#"}) { + final String expected = "1/1 !help " + c + "\n" + + "!go Select the current connection\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help " + c + "\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + } + + /** + * Test case for + * !?, !# + * and other one-symbol length commands stopped working + * + *

    '!?' should work in the same way as '!help'. + */ + @Test + public void testHelpAsQuestionMark() { + final String script = "!?\n"; + final String expected = + "!autocommit Set autocommit mode on or off"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + allOf(not(containsString("Unknown command: ?")), + containsString(expected))); + } + + /** + * Test case for + * [SQLLINE-49] + * !manual command fails. + */ + @Test + public void testManual() { + final String expectedLine = "sqlline version"; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + new MockUp() { + @Mock + void less(Terminal terminal, InputStream in, PrintStream out, + PrintStream err, Path currentDir, String[] argv) { + } + }; + + SqlLine beeLine = new SqlLine(); + SqlLine.Status status = + begin(beeLine, baos, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + beeLine.runCommands(new DispatchCallback(), "!manual"); + String output = baos.toString("UTF8"); + + assertThat(output, containsString(expectedLine)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-38] + * Expand ~ to user's home directory. */ + @Test + public void testRunFromHome() { + try { + Path tmpDir = + Files.createTempDirectory( + Paths.get(System.getProperty("user.home")), + "tmpdir" + System.nanoTime()); + tmpDir.toFile().deleteOnExit(); + + File tmpFile = createTempFile("test", ".sql", tmpDir); + try (Writer fw = new OutputStreamWriter( + new FileOutputStream(tmpFile), StandardCharsets.UTF_8)) { + fw.write("!set outputformat csv\n"); + fw.write("values (1, 2, 3, 4, 5);"); + fw.flush(); + checkScriptFile("!run ~" + File.separatorChar + + tmpDir.getFileName() + + File.separatorChar + tmpFile.getName().toString(), + false, + equalTo(SqlLine.Status.OK), + allOf(containsString("!set outputformat csv"), + containsString("values (1, 2, 3, 4, 5);"))); + } + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-26] + * Flush output for each command when using !record command. + */ + @Test + public void testRecord() { + File file = createTempFile("sqlline", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + /** Test case for + * [SQLLINE-62] + * Expand ~ to user's home directory. */ + @Test + public void testRecordHome() { + File home = new File(System.getProperty("user.home")); + File file; + for (int i = 0;; i++) { + file = new File(home, "sqlline" + i + ".log"); + if (!file.exists()) { + break; + } + } + file.deleteOnExit(); + final String s = "Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "2/4 !set outputformat csv\n" + + "3/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "4/4 !record\n"; + checkScriptFile("!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n", + false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/4 !record .*.log\n" + + s + + "Recording stopped.\n" + + ".*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, RegexMatcher.of(s)); + final boolean delete = file.delete(); + assertThat(delete, is(true)); + } + + /** + * As {@link #testRecord()}, but file name is double-quoted and contains a + * space. + */ + @Test + public void testRecordFilenameWithSpace() { + File file = createTempFile("sqlline file with spaces", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + private static void assertFileContains(File file, Matcher matcher) { + try (BufferedReader br = new BufferedReader( + new InputStreamReader(new FileInputStream(file), + StandardCharsets.UTF_8.name()))) { + final StringWriter stringWriter = new StringWriter(); + for (;;) { + final String line = br.readLine(); + if (line == null) { + break; + } + stringWriter.write(line); + stringWriter.write("\n"); + } + assertThat(toLinux(stringWriter.toString()), matcher); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-61] + * Add !nickname command. + */ + @Test + public void testNickname() { + final String script = "!set outputformat csv\n" + + "values 1;\n" + + "!nickname foo\n" + + "values 2;\n"; + final String expected = "(?s)1/4 !set outputformat csv\n" + + "2/4 values 1;\n" + + "'C1'\n" + + "'1'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/4 !nickname foo\n" + + "4/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * The first command should fail and the second command should not execute. + */ + @Test + public void testBreakOnErrorScriptFile() { + checkScriptFile("select * from abcdefg01;\ncall 100 + 23;\n", + true, + equalTo(SqlLine.Status.OTHER), + not(containsString(" 123 "))); + } + + /** + * Emulation of Apache Hive behavior with throwing exceptions + * while calling {@link DatabaseMetaData#storesUpperCaseIdentifiers()} + * and {@link DatabaseMetaData#supportsTransactionIsolationLevel(int)}. + * + *

    Also please see + * [SQLLINE-183]. + * + * @param meta Mocked JDBCDatabaseMetaData + */ + @Test + public void testExecutionWithNotSupportedMethods( + @Mocked final JDBCDatabaseMetaData meta) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + + // emulate apache hive behavior + meta.supportsTransactionIsolationLevel(4); + result = new SQLException("Method not supported"); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback dc = new DispatchCallback(); + sqlLine.initArgs(args, dc); + os.reset(); + sqlLine.runCommands(dc, + "!set incremental true", + "values 1;"); + final String output = os.toString("UTF8"); + final String line0 = "+-------------+"; + final String line1 = "| C1 |"; + final String line2 = "+-------------+"; + final String line3 = "| 1 |"; + final String line4 = "+-------------+"; + assertThat(output, + CoreMatchers.allOf(containsString(line0), + containsString(line1), + containsString(line2), + containsString(line3), + containsString(line4))); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + @Test + public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta, + @Mocked final JDBCResultSet resultSet) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getSQLKeywords(); + result = ""; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + // Generate an exception on a call to resultSet.next + resultSet.next(); + result = new SQLException("Generated Exception."); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + // If sqlline is not initialized, handleSQLException will print + // the entire stack trace. + // To prevent that, forcibly set init to true. + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "CREATE TABLE rsTest ( a int);", + "insert into rsTest values (1);", + "insert into rsTest values (2);", + "select a from rsTest; "); + String output = os.toString("UTF8"); + assertThat(output, containsString("Generated Exception")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Attempts to execute a missing script file with the -f option to SqlLine. + */ + @Test + public void testNegativeScriptFile() { + // Create and delete a temp file + File scriptFile = createTempFile("sqllinenegative", "temp"); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OTHER)); + assertThat(pair.output, not(containsString(" 123 "))); + } + + /** Displays usage. */ + @Test + public void testUsage() { + Pair pair = run("--help"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + private int countUsage(String output) { + int n = 0; + for (String line : output.split("\n")) { + if (line.contains("Usage")) { + ++n; + } + } + return n; + } + + /** Invalid arguments. */ + @Test + public void testInvalidArguments() { + Pair pair = run("--fuzz"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + /** Result of executing sqlline: status code and output. */ + static class Pair { + final SqlLine.Status status; + final String output; + + Pair(SqlLine.Status status, String output) { + this.status = status; + this.output = output; + } + } + + @Test + public void testIsolationSetting() { + final String script0 = "!isolation TRANSACTION_NONE\n"; + final String expected = "Transaction isolation level TRANSACTION_NONE " + + "is not supported. Default (TRANSACTION_READ_COMMITTED) " + + "will be used instead."; + checkScriptFile(script0, true, equalTo(SqlLine.Status.OTHER), + containsString(expected)); + } + + @Test + public void testDefaultIsolation() { + final String script1 = "!isolation default\n"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + allOf(not(containsString("Transaction isolation level")), + not(containsString("is not supported")))); + } + + /** + * HIVE-4566, "NullPointerException if typeinfo and nativesql commands are + * executed at beeline before a DB connection is established". + */ + @Test + public void testNPE() { + SqlLine sqlLine = new SqlLine(); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + + try { + sqlLine.runCommands(new DispatchCallback(), "!typeinfo"); + String output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + + sqlLine.runCommands(new DispatchCallback(), "!nativesql"); + output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandlerOnStartup() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final String[] args = { + "-e", "!set maxwidth 80", + "-ch", "sqlline.extensions.HelloWorldCommandHandler"}; + begin(sqlLine, os, false, args); + + try { + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!test"); + output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello test")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandler() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + begin(sqlLine, os, false, "-e", "!set maxwidth 80"); + + try { + final String script = "!commandhandler" + + " sqlline.extensions.HelloWorld2CommandHandler" + + " sqlline.extensions.HelloWorldCommandHandler"; + sqlLine.runCommands(new DispatchCallback(), script); + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD2")); + final String expected = "Could not add command handler " + + "sqlline.extensions.HelloWorldCommandHandler as one of commands " + + "[hello, test] is already present"; + assertThat(output, containsString(expected)); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello2")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testTablesCsv() { + final String script = "!set outputformat csv\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("'TABLE_CAT','TABLE_SCHEM','TABLE_NAME',"), + containsString("'PUBLIC','SCOTT','SALGRADE','TABLE','',"))); + } + + /** + * java.lang.NullPointerException test case from + * https://github.com/julianhyde/sqlline/pull/86#issuecomment-410868361 + */ + @Test + public void testCsvDelimiterAndQuoteCharacter() { + final String script = "!set outputformat csv\n" + + "!set csvDelimiter null\n" + + "!set csvQuoteCharacter @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!set csvDelimiter ##\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@null@C2@null@C3@null@C4@null@C5@null@C6@"; + final String line2 = + "@#@null@@@#@@@null@1@null@1969-07-20@null@@null@ 1'2\"3\t4@"; + final String line3 = "@C1@##@C2@##@C3@##@C4@##@C5@##@C6@"; + final String line4 = "@#@##@@@#@@@##@1@##@1969-07-20@##@@##@ 1'2\"3\t4@"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testCsvOneLiner() { + final String script = "!outputformat csv \"'\" @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!outputformat csv & default\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@'@C2@'@C3@'@C4@'@C5@'@C6@"; + final String line2 = + "@#@'@@@#@@@'@1@'@1969-07-20@'@@'@ 1'2\"3\t4@"; + final String line3 = "'C1'&'C2'&'C3'&'C4'&'C5'&'C6'"; + final String line4 = + "'#'&'@#@'&'1'&'1969-07-20'&''&' 1''2\"3\t4'"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testSetForNulls() { + final String script = "!set numberFormat null\n" + + "!set\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("numberFormat null")); + } + + @Test + public void testSetNonIntValuesToIntProperties() { + SqlLine sqlLine = new SqlLine(); + final String headerIntervalScript = "!set headerinterval abc\n"; + checkScriptFile(headerIntervalScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "headerinterval", "abc"))); + + final String rowLimitScript = "!set rowlimit xxx\n"; + checkScriptFile(rowLimitScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "rowlimit", "xxx"))); + } + + @Test + public void testSelectXmlAttributes() { + final String script = "!set outputformat xmlattr\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ']]> 1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString("&4\"/>"))); + } + + @Test + public void testSelectXmlElements() { + final String script = "!set outputformat xmlelements\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' ]]>1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString(""), + containsString("1"), + containsString("-1.5"), + containsString("TRUE"), + containsString("1969-07-20"), + containsString("null"), + containsString(" ]]>1'2\"3\t<>&4"), + containsString(""), + containsString(""))); + } + + @Test + public void testTablesJson() { + final String script = "!set outputformat json\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"TABLE_CAT\":\"PUBLIC\"," + + "\"TABLE_SCHEM\":\"SYSTEM_LOBS\",\"TABLE_NAME\":\"BLOCKS\"," + + "\"TABLE_TYPE\":\"SYSTEM TABLE\",\"REMARKS\":null," + + "\"TYPE_CAT\":null,"))); + } + + @Test + public void testSelectJson() { + final String script = "!set outputformat json\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"C1\":1,\"C2\":-1.5,\"C3\":true," + + "\"C4\":\"1969-07-20\",\"C5\":null," + + "\"C6\":\" 1'2\\\"3\\t4\"}"))); + } + + @Test + public void testNullValue() { + final String script = "!set nullValue %%%\n" + + "!set outputformat csv\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue \"'\"\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue null\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'%%%','-1.5','%%%','1969-07-20','%%%','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'''','-1.5','''','1969-07-20','''','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'null','-1.5','null','1969-07-20','null','null'"))); + } + + @Test + public void testTimeFormat() { + // Use System.err as it is used in sqlline.SqlLineOpts#set + final PrintStream originalErr = System.err; + try { + final ByteArrayOutputStream errBaos = new ByteArrayOutputStream(); + System.setErr( + new PrintStream(errBaos, false, StandardCharsets.UTF_8.name())); + + // successful patterns + final String okTimeFormat = "!set timeFormat HH:mm:ss\n"; + final String defaultTimeFormat = "!set timeFormat default\n"; + final String okDateFormat = "!set dateFormat YYYY-MM-dd\n"; + final String defaultDateFormat = "!set dateFormat default\n"; + final String okTimestampFormat = "!set timestampFormat default\n"; + final String defaultTimestampFormat = "!set timestampFormat default\n"; + + // successful cases + final SqlLine sqlLine = new SqlLine(); + sqlLine.runCommands(new DispatchCallback(), okTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + + // failed patterns + final String wrongTimeFormat = "!set timeFormat qwerty\n"; + final String wrongDateFormat = "!set dateFormat ASD\n"; + final String wrongTimestampFormat = + "!set timestampFormat 'YYYY-MM-ddTHH:MI:ss'\n"; + + // failed cases + sqlLine.runCommands(new DispatchCallback(), wrongTimeFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'q'")); + sqlLine.runCommands(new DispatchCallback(), wrongDateFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'A'")); + sqlLine.runCommands(new DispatchCallback(), wrongTimestampFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'T'")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } finally { + // Set error stream back + System.setErr(originalErr); + } + } + + /** + * Test case for + * [SQLLINE-203] + * !indexes command fails because of Hive bug. + * The bug in question is + * [HIVE-20983] + * HiveResultSetMetaData.getColumnDisplaySize throws for SHORT column. + * + * @param meta Mocked hsqldb {@link JDBCResultSetMetaData} to use in the test + */ + @Test + public void testOutputWithFailingColumnDisplaySize( + @Mocked final JDBCResultSetMetaData meta) { + try { + new Expectations() { + { + meta.getColumnCount(); + result = 3; + + meta.getColumnLabel(1); + result = "TABLE_CAT"; + + meta.getColumnLabel(2); + result = "TABLE_SCHEM"; + + meta.getColumnLabel(3); + result = "TABLE_NAME"; + + meta.getColumnDisplaySize(1); + result = new Exception("getColumnDisplaySize exception"); + } + }; + + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "!set incremental true", + "!set maxwidth 80", + "!set verbose true", + "!indexes"); + assertThat(os.toString("UTF8"), not(containsString("Exception"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests the {@code !connect} command with interactive password submission. + */ + @Test + public void testConnectWithoutPassword() { + new MockUp() { + @Mock + String readPassword(String url) { + return ""; + } + }; + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} property outside of the URL: + * + *

    + * !connect -p PASSWORD_HASH TRUE jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} and {@code ALLOW_LITERALS} properties + * outside of the URL: + * + *
    + * !connect -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE + * jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter2() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!set maxwidth 80"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "select 1;"); + String output = os.toString("UTF8"); + final String expected = "Error:"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing the password in as a hash: + * + *
    + * !connect "jdbc:h2:mem; PASSWORD_HASH=TRUE" sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbProperty() { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + try { + beeLine.runCommands(dc, "!set maxwidth 80"); + + // fail attempt + String fakeNonEmptyPassword = "nonEmptyPasswd"; + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE\" " + + ConnectionSpec.H2.username + + " \"" + fakeNonEmptyPassword + "\""); + String output = os.toString("UTF8"); + final String expected0 = "Error:"; + assertThat(output, containsString(expected0)); + os.reset(); + + // success attempt + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE;ALLOW_LITERALS=NONE\" " + + ConnectionSpec.H2.username + " \"" + + StringUtils.convertBytesToHex(bytes) + + "\""); + beeLine.runCommands(dc, "!set incremental true"); + beeLine.runCommands(dc, "!tables"); + output = os.toString("UTF8"); + final String expected1 = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected1)); + + beeLine.runCommands(dc, "select 5;"); + output = os.toString("UTF8"); + final String expected2 = "Error:"; + assertThat(output, containsString(expected2)); + os.reset(); + + beeLine.runCommands(new DispatchCallback(), "!quit"); + output = os.toString("UTF8"); + assertThat(output, + allOf(not(containsString("Error:")), containsString("!quit"))); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + private static PrintStream getPrintStream(OutputStream os) { + try { + return new PrintStream(os, false, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testReconnect() { + final String script = "!reconnect"; + final String expected = "Reconnecting to \"jdbc:hsqldb:res:scott\"...\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + @Test + public void testTables() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxcolumnwidth 15\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = + "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | |"; + final String line1 = + "| PUBLIC | SYSTEM_LOBS | BLOCKS | SYSTEM TABLE | |"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + @Test + public void testTablesH2() { + connectionSpec = ConnectionSpec.H2; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + /** + * Test case for + * [SQLLINE-107] + * Script fails if the wrong driver is specified with -d option + * and there is a valid registered driver for the specified url. + * + */ + @Test + public void testTablesH2WithErrorDriver() { + connectionSpec = ConnectionSpec.ERROR_H2_DRIVER; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + final String message = "Could not find driver " + + connectionSpec.driver + + "; using registered driver org.h2.Driver instead"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString(message), + not(containsString("NullPointerException")), + containsString(line0), + containsString(line1))); + } + + @Test + public void testH2TablesWithErrorUrl() { + connectionSpec = ConnectionSpec.ERROR_H2_URL; + final String script = "!tables\n"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + CoreMatchers.allOf(containsString("No suitable driver"), + not(containsString("NullPointerException")))); + } + + @Test + public void testEmptyMetadata() { + final String script = "!metadata\n"; + final String line = "Usage: metadata "; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + /** Tests that methods inherited from Object are not included in the list + * of possible metadata methods. */ + @Test + public void testPossibleMetadataValues() { + final String script = "!metadata 1\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString("allProceduresAreCallable"), + containsString("getIndexInfo"), + not(containsString("Exception")), + not(containsString("equals")), + not(containsString("notify")), + not(containsString("wait")), + not(containsString("toString")), + not(containsString("hashCode")), + not(containsString("notifyAll")))); + } + + @Test + public void testMetadataForClassHierarchy() { + final SqlLine beeLine = new SqlLine(); + + new MockUp() { + @Mock + public DatabaseMetaData getMetaData() throws SQLException { + return new CustomDatabaseMetadata( + (JDBCConnection) beeLine.getConnection()); + } + }; + + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.HSQLDB.url + " \"" + + ConnectionSpec.HSQLDB.username + "\" \"" + + ConnectionSpec.HSQLDB.password + "\""); + os.reset(); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + assertThat(output, + allOf(containsString("TABLE_CAT"), + not(containsString("No such method \"getTables\"")))); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testEmptyRecord() { + final String line = "Usage: record "; + checkScriptFile("!record", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyRun() { + final String line = "Usage: run "; + checkScriptFile("!run", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyScript() { + final String line = "Usage: script "; + checkScriptFile("!script", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEscapeSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxColumnWidth 15\n" + + "!set escapeOutput yes\n" + + "values \n" + + "('\n" + + "multiline\n" + + "value') \n" + + ";\n"; + final String line1 = "" + + "+-----------------+\n" + + "| C1 |\n" + + "+-----------------+\n" + + "| \\nmultiline \\nvalue |\n" + + "+-----------------+\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!sql \n" + + "values \n" + + "(1, 2) \n" + + ";\n"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 1 | 2 |\n" + + "+-------------+-------------+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAllMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!all \n" + + "values \n" + + "(1, '2') \n" + + ";\n"; + final String line1 = "" + + "+-------------+----+\n" + + "| C1 | C2 |\n" + + "+-------------+----+\n" + + "| 1 | 2 |\n" + + "+-------------+----+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAppInfoMessage() { + Pair pair = run("-e", "!set maxwidth 80"); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + containsString(Application.DEFAULT_APP_INFO_MESSAGE)); + + String[] args = {"-e", "!set maxwidth 80", "-ac", "INCORRECT_CLASS_NAME"}; + pair = run(args); + assertThat(pair.output, + containsString("Could not initialize INCORRECT_CLASS_NAME")); + assertThat(pair.output, + containsString(CustomApplication.DEFAULT_APP_INFO_MESSAGE)); + + String[] args2 = {"-e", "!set maxwidth 80", + "-ac", "sqlline.extensions.CustomApplication"}; + pair = run(args2); + assertThat(pair.output, + containsString(CustomApplication.CUSTOM_INFO_MESSAGE)); + } + + @Test + public void testCustomOutputFormats() { + // json format was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!set outputformat json\n" + + "values 1;"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("Unknown outputFormat \"json\"")); + } + + @Test + public void testCustomCommands() { + // table command was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Unknown command: tables")); + } + + @Test + public void testAppConfigReset() { + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!appconfig sqlline.Application\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("TABLE_CAT")); + } + + @Test + public void testCustomOpts() { + // nulls are displayed as custom_null + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "values(null)"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("custom_null")); + } + + @Test + public void testScanForEmptyAllowedDrivers() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.emptyList(); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("No driver classes found")); + } + + @Test + public void testScanForOnlyH2Allowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.h2.Driver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 1.4 org.h2.Driver"), + not(containsString("org.hsqldb.jdbc.JDBCDriver")))); + } + + @Test + public void testScanForOnlyHsqldbAllowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.hsqldb.jdbc.JDBCDriver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 2.4 org.hsqldb.jdbc.JDBCDriver"), + not(containsString("org.h2.Driver")))); + } + + @Test + public void testVersion() { + final String script = "!set\n"; + try { + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(new Application().getVersion())); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSetVersion() { + final String script = "!set version test-version\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("version property is read only")); + } + + @Test + public void testSetPropertySuccess() { + final String script = "!set timeout\n" + + "!set timeout 200\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("timeout -1"), + containsString("timeout 200"))); + } + + @Test + public void testSetPropertyFailure() { + final String script = "!set unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testSetUsage() { + final String script = "!set 1 2 3"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: set [all | []]")); + } + + @Test + public void testSetWrongValueToEnumTypeProperties() { + Collection propertiesWithAvailableValues = + Arrays.stream(BuiltInProperty.values()) + .filter(t -> !t.getAvailableValues().isEmpty()) + .collect(Collectors.toSet()); + final String wrongValue = "wrong_value"; + for (BuiltInProperty property: propertiesWithAvailableValues) { + final String script = + "!set " + property.propertyName() + " " + wrongValue + "\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf( + containsString("Unknown " + property.propertyName() + " \"" + + wrongValue + "\""), + not(containsString("Exception")))); + } + } + + @Test + public void testResetSuccess() { + final String script = "!set timeout 200\n" + + "!reset timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("[timeout] was reset to [-1]")); + } + + @Test + public void testResetFailure() { + final String script = "!reset unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testResetAll() { + final String script = "!set timeout 200\n" + + "!reset all\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("All properties were reset to their defaults."), + containsString("timeout -1"))); + } + + @Test + public void testResetUsage() { + final String script = "!reset"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: reset (all | )")); + } + + @Test + public void testRerun() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:!/ 4\n" + + "1536743104551:!/ 5\n" + + "1536743104551:!/ 2\n" + + "1536743104551:!/ 7\n" + + "1536743107526:!history\n" + + "1536743115431:!/ 3\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set incremental true", + "!set maxcolumnwidth 30", + "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + "\"\""); + os.reset(); + + beeLine.runCommands(dc, "!/ 1"); + String output = os.toString("UTF8"); + final String expected0 = "+----------------------------+"; + final String expected1 = "| C1 |"; + final String expected2 = "1 row selected"; + assertThat(output, + allOf(containsString(expected0), + containsString(expected1), + containsString(expected2))); + os.reset(); + + beeLine.runCommands(dc, "!/ 4"); + output = os.toString("UTF8"); + String expectedLine3 = "Cycled rerun of commands from history [2, 4]"; + assertThat(output, containsString(expectedLine3)); + os.reset(); + + beeLine.runCommands(dc, "!/ 3"); + output = os.toString("UTF8"); + String expectedLine4 = "Cycled rerun of commands from history [3, 5, 7]"; + assertThat(output, containsString(expectedLine4)); + os.reset(); + + beeLine.runCommands(dc, "!/ 8"); + output = os.toString("UTF8"); + String expectedLine5 = "Cycled rerun of commands from history [8]"; + assertThat(output, containsString(expectedLine5)); + os.reset(); + + beeLine.runCommands(dc, "!rerun " + Integer.MAX_VALUE); + output = os.toString("UTF8"); + String expectedLine6 = + "Usage: rerun , available range of offset is -7..8"; + assertThat(output, containsString(expectedLine6)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMaxColumnWidthIncremental() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line2 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line3 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testMaxColumnWidthBuffered() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line1 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line2 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line3 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + /** Tests with incrementalBufferRows = -1; query stays in non-incremental + * mode. */ + @Test + public void testIncrementalBufferRows() { + final String script1 = "!set incrementalBufferRows -1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line1 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + /** Tests with incrementalBufferRows = 0; query goes straight into + * incremental mode. */ + @Test + public void testIncrementalBufferRows2() { + final String script2 = "!set incrementalBufferRows 0\n" + + "!set incremental false\n" + + "select * from (values (1, 2), (1, 20), (111, 20), (11, 2222), (1, 22))"; + final String line2 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 1 | 2 |\n" + + "| 1 | 20 |\n" + + "| 111 | 20 |\n" + + "| 11 | 2222 |\n" + + "| 1 | 22 |\n" + + "+----+----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + } + + /** Tests with incrementalBufferRows = 1; query starts in non-incremental mode + * and switches to incremental after 1 row. */ + @Test + public void testIncrementalBufferRows3() { + final String script3 = "!set incrementalBufferRows 1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222), (111, 2222))"; + final String line3 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "| 111 | 2222 |\n" + + "+----+----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + } + + /** Tests with incrementalBufferRows = 4; query starts in non-incremental mode + * and rows run out before the limit is reached. */ + @Test + public void testIncrementalBufferRows4() { + final String script4 = "!set incrementalBufferRows 4\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line4 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testIncrementalBufferRows5() { + // With incrementalBufferRows default (1000), query starts and + // stays in incremental mode. + final String script5 = "!set incrementalBufferRows default\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2))"; + final String line5 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "+----+----+"; + checkScriptFile(script5, true, equalTo(SqlLine.Status.OK), + containsString(line5)); + } + + @Test + public void testMaxHistoryFileRows() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:SELECT \\n 'asd' as \"sdf\", 4 \\n \\n as \\n c2;\\n\n" + + "1536743104551:SELECT \\n 'asd' \\n as \\n c2;\\n\n" + + "1536743104551:!/ 2\n" + + "1536743104551:SELECT \\n 2123 \\n as \\n c2 from dual;\\n\n" + + "1536743107526:!history\n" + + "1536743115431:SELECT \\n 2 \\n as \\n c2;\n" + + "1536743115431:SELECT \\n '213' \\n as \\n c1;\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + bw.close(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + final int maxLines = 3; + beeLine.runCommands(dc, "!set maxHistoryFileRows " + maxLines); + os.reset(); + beeLine.runCommands(dc, "!history"); + assertEquals(maxLines + 1, + os.toString("UTF8").split("\\s+\\d{2}:\\d{2}:\\d{2}\\s+").length); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSave() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + SqlLine.Status status = begin(beeLine, os, false, + "-e", "!save"); + assertThat(status, equalTo(SqlLine.Status.OK)); + final DispatchCallback dc = new DispatchCallback(); + + assertThat(os.toString("UTF8"), + containsString("Saving preferences to")); + os.reset(); + beeLine.runCommands(dc, "!set"); + assertThat(os.toString("UTF8"), + allOf(containsString("autoCommit"), + not(containsString("Unknown property:")))); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScript() { + final File file = createTempFile("sqlline", ".script"); + final String script = "!script " + file.getAbsolutePath() + "\n" + + "values (100, 200);\n" + + "!set maxcolumnwidth -1\n" + + "!script\n" + + "values (1, 2);\n"; + final String expected = "(?s)1/5 !script.*" + + "2/5 values \\(100, 200\\);.*" + + "3/5 !set maxcolumnwidth -1.*" + + "4/5 !script.*" + + "5/5 values \\(1, 2\\);.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + + final String output = "values \\(100, 200\\);\n" + + "!set maxcolumnwidth -1\n"; + assertFileContains(file, RegexMatcher.of(output)); + } + + @Test + public void testStartupArgsWithoutUrl() { + try { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests setting the "confirm" property. + */ + @Test + public void testConfirmFlag() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + begin(line, os, false, "-e", "!set confirm true"); + assertThat(line.getOpts().getConfirm(), is(true)); + begin(line, os, false, "-e", "!set confirm false"); + assertThat(line.getOpts().getConfirm(), is(false)); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests that the "confirm" property works. + */ + @Test + public void testConfirmFlagEffects() { + new MockUp() { + @Mock + int getUserAnswer(String question, int... allowedAnswers) { + return 'n'; + } + }; + + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + assertThat(line.getOpts().getConfirmPattern(), is("default")); + String script = "CREATE TABLE dummy_test(pk int);\n" + + "INSERT INTO dummy_test(pk) VALUES(1);\n" + + "INSERT INTO dummy_test(pk) VALUES(2);\n" + + "INSERT INTO dummy_test(pk) VALUES(3);\n" + + "DELETE FROM dummy_test;\n" + + "DROP TABLE dummy_test;\n"; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OK), + containsString(" ")); + + script = "!set confirm true\n" + script; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OTHER), + containsString(line.loc("abort-action"))); + } + + /** + * Tests that the "confirmPattern" property works. + */ + @Test + public void testConfirmPattern() { + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i:(TRUNCATE|ALTER))\""); + assertThat(line.getOpts().getConfirmPattern(), + is("^(?i:(TRUNCATE|ALTER))")); + + begin(line, os, false, "-e", "!set confirmPattern default"); + assertThat(line.getOpts().getConfirmPattern(), + is(line.loc("default-confirm-pattern"))); + } + + /** + * Test for illegal regex in confirmPattern + */ + @Test + public void testExceptionConfirmPattern() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + SqlLine.Status status = + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i*:(TRUNCATE|ALTER))\""); + assertThat(status, equalTo(SqlLine.Status.OK)); + assertThat(os.toString("UTF8"), containsString("invalid regex")); + os.reset(); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** Information necessary to create a JDBC connection. Specify one to run + * tests against a different database. (hsqldb is the default.) */ + public static class ConnectionSpec { + public final String url; + public final String username; + public final String password; + public final String driver; + + public ConnectionSpec(String url, String username, String password, + String driver) { + this.url = url; + this.username = username; + this.password = password; + this.driver = driver; + } + + public static final ConnectionSpec H2 = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec ERROR_H2_DRIVER = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "ERROR_DRIVER"); + + public static final ConnectionSpec ERROR_H2_URL = + new ConnectionSpec("ERROR_URL", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec HSQLDB = + new ConnectionSpec( + ScottHsqldb.URI, ScottHsqldb.USER, ScottHsqldb.PASSWORD, + "org.hsqldb.jdbcDriver"); + + public static final ConnectionSpec MYSQL = + new ConnectionSpec( + "jdbc:mysql://localhost/scott", "scott", "tiger", + "com.mysql.jdbc.Driver"); + } + + /** Regular expression matcher. */ + private static class RegexMatcher extends BaseMatcher { + private final String pattern; + + RegexMatcher(String pattern) { + super(); + this.pattern = pattern; + } + + public static RegexMatcher of(String pattern) { + return new RegexMatcher(pattern); + } + + public boolean matches(Object o) { + return o instanceof String + && ((String) o).matches(pattern); + } + + public void describeTo(Description description) { + description.appendText("regular expression ").appendText(pattern); + } + } + +} + +// End SqlLineArgsTest.java + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PrintStream` acquired by call to `SqlLine()` at line 1486 is not released after line 1489. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SqlLineArgsTest.testConnectWithDbPropertyAsParameter() + +### Procedure Id: +sqlline.SqlLineArgsTest.testConnectWithDbPropertyAsParameter():void.f13f470edfe26a8fc2768df48a148821 + +### File: +src/test/java/sqlline/SqlLineArgsTest.java + +### Key: +SqlLineArgsTest.java|testConnectWithDbPropertyAsParameter|RESOURCE_LEAK + +### Node Key: +b2d15307b6382364ce2ba477b6f118cb + +### Hash: +982987025bdfba1fcdc97a1bcb10186e + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8088/instruction.md b/inferredbugs-8088/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d5efd8c7be0c5bb4fd0c61c2a8b5a7054cadb3c9 --- /dev/null +++ b/inferredbugs-8088/instruction.md @@ -0,0 +1,2663 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sqlline +**Bug ID:** 20 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +// Licensed to Julian Hyde under one or more contributor license +// agreements. See the NOTICE file distributed with this work for +// additional information regarding copyright ownership. +// +// Julian Hyde licenses this file to you under the Modified BSD License +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/BSD-3-Clause +*/ +package sqlline; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.h2.util.StringUtils; +import org.hamcrest.BaseMatcher; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hsqldb.jdbc.CustomDatabaseMetadata; +import org.hsqldb.jdbc.JDBCConnection; +import org.hsqldb.jdbc.JDBCDatabaseMetaData; +import org.hsqldb.jdbc.JDBCResultSet; +import org.hsqldb.jdbc.JDBCResultSetMetaData; +import org.jline.builtins.Commands; +import org.jline.terminal.Terminal; +import org.junit.jupiter.api.Test; + +import mockit.Expectations; +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.internal.reflection.FieldReflection; +import net.hydromatic.scott.data.hsqldb.ScottHsqldb; +import sqlline.extensions.CustomApplication; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Executes tests of the command-line arguments to SqlLine. + */ +public class SqlLineArgsTest { + private static final ConnectionSpec CONNECTION_SPEC = ConnectionSpec.HSQLDB; + private ConnectionSpec connectionSpec; + + public SqlLineArgsTest() { + connectionSpec = CONNECTION_SPEC; + } + + static SqlLine.Status begin(SqlLine sqlLine, OutputStream os, + boolean saveHistory, String... args) { + try { + PrintStream beelineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(beelineOutputStream); + sqlLine.setErrorStream(beelineOutputStream); + final InputStream is = new ByteArrayInputStream(new byte[0]); + return sqlLine.begin(args, is, saveHistory); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Execute a script with "beeline -f". + * + * @return The stderr and stdout from running the script + * @param args Script arguments + */ + private static Pair run(String... args) { + try { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = begin(beeLine, os, false, args); + return new Pair(status, os.toString("UTF8")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + private Pair runScript(File scriptFile, boolean flag, String outputFileName) { + return runScript(connectionSpec, scriptFile, flag, outputFileName); + } + + private static Pair runScript(ConnectionSpec connectionSpec, File scriptFile, + boolean flag, String outputFileName) { + List args = new ArrayList<>(); + Collections.addAll(args, + "-d", connectionSpec.driver, + "-u", connectionSpec.url, + "-n", connectionSpec.username, + "-p", connectionSpec.password); + if (flag) { + args.add("-f"); + args.add(scriptFile.getAbsolutePath()); + } else { + args.add("--run=" + scriptFile.getAbsolutePath()); + } + if (outputFileName != null) { + args.add("-log"); + args.add(outputFileName); + } + return run(args.toArray(new String[0])); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * Tests for presence of an expected pattern in the output (stdout or stderr). + * + * @param scriptText Script text + * @param flag Command flag (--run or -f) + * @param statusMatcher Checks whether status is as expected + * @param outputMatcher Checks whether output is as expected + */ + private void checkScriptFile(String scriptText, boolean flag, + Matcher statusMatcher, + Matcher outputMatcher) { + try { + // Put the script content in a temp file + File scriptFile = createTempFile("foo", "temp"); + PrintStream os = + new PrintStream( + new FileOutputStream(scriptFile), + false, + StandardCharsets.UTF_8.name()); + os.print(scriptText); + os.close(); + + Pair pair = runScript(scriptFile, flag, null); + + // Check output before status. It gives a better clue what went wrong. + assertThat(toLinux(pair.output), outputMatcher); + assertThat(pair.status, statusMatcher); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Windows line separators in a string into Linux line separators; + * a Linux string is unchanged. */ + private static String toLinux(String s) { + return s.replaceAll("\r\n", "\n"); + } + + private File createTempFile(String prefix, String suffix) { + return createTempFile(prefix, suffix, null); + } + + private File createTempFile(String prefix, String suffix, Path directory) { + try { + final File file = directory == null + ? Files.createTempFile(prefix, suffix).toFile() + : Files.createTempFile(directory, prefix, suffix).toFile(); + file.deleteOnExit(); + return file; + } catch (IOException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMultilineScriptWithComments() { + final String script1Text = + "!set incremental true\n" + + "-- a comment \n values\n--comment\n (\n1\n, ' ab'\n--comment\n)\n;\n"; + + checkScriptFile(script1Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-------------+-----+\n" + + "| C1 | C2 |\n" + + "+-------------+-----+\n" + + "| 1 | ab |\n" + + "+-------------+-----+")); + + final String script2Text = + "!set incremental true\n" + + "--comment \n --comment2 \nvalues (';\n' /* comment */, '\"'" + + "/*multiline;\n ;\n comment*/)\n -- ; \n; -- comment"; + + checkScriptFile(script2Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-----+----+\n" + + "| C1 | C2 |\n" + + "+-----+----+\n" + + "| ; \n" + + " | \" |\n" + + "+-----+----+")); + } + + /** + * Attempt to execute a simple script file with the -f option to SqlLine. + * Test for presence of an expected pattern + * in the output (stdout or stderr), fail if not found. + */ + @Test + public void testPositiveScriptFile() { + checkScriptFile("call 100 + 23;\n", + true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * As above, but using '-run' rather than '-f'. + */ + @Test + public void testPositiveScriptFileUsingRun() { + checkScriptFile("call 100 + 23;\n", + false, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * Test case for + * [SQLLINE-42], + * Script fails if first line is a comment. + */ + @Test + public void testScriptFileStartsWithComment() { + final String scriptText = "-- a comment\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileStartsWithEmptyLine() { + final String scriptText = "\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileContainsComment() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithComments() { + final String scriptText = "--comment\n\n" + + "values \n10 \n+ \n23;\n\n\n" + + "-- a comment\n" + + "\n\nvalues " + + "--comment inside\n\n" + + "100 --comment inside\n\n" + + "+ \n\n23\n\n\n;\n\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithMultilineQuotedStrings() { + final String scriptText = "--comment\n\n" + + "values '\nmultiline;\n;\n; string\n'" + + ";\n\n\n" + + "values '\nmultiline2;\n;\n; string2\n'" + + ";\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString("multiline2;"), containsString("; string2"))); + } + + @Test + public void testScriptWithMultilineStatementsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment\n\n" + + "values 1;values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 1 |\n" + + "+----+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + + @Test + public void testScriptWithMultilineStatementsAndCommentsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment;;\n\n" + + "select * from (values ';') t (\";\");/*;select 1;*/values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+---+\n" + + "| ; |\n" + + "+---+\n" + + "| ; |\n" + + "+---+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + /** + * Tests sql with H2 specific one-line comment '//' + */ + @Test + public void testMultilineScriptWithH2Comments() { + final SqlLine sqlLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + final File tmpHistoryFile = createTempFile("queryToExecute", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + final String script = "\n" + + "\n" + + "!set incremental true\n" + + "\n" + + "\n" + + "select * from information_schema.tables// ';\n" + + "// \";" + + ";\n" + + "\n" + + "\n"; + bw.write(script); + bw.flush(); + } + SqlLine.Status status = + begin(sqlLine, os, false, + "-u", ConnectionSpec.H2.url, + "-n", ConnectionSpec.H2.username, + "--run=" + tmpHistoryFile.getAbsolutePath()); + assertThat(status, equalTo(SqlLine.Status.OK)); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |" + + " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |"; + assertThat(output, containsString(expected)); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-72] + * Allow quoted file names (including spaces) in !record, + * !run and !script commands. */ + @Test + public void testScriptFilenameWithSpace() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23;\n"; + File scriptFile = createTempFile("Script with Spaces", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + allOf(containsString(" 33 "), containsString(" 123 "))); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScriptWithOutput() { + final String scriptText = "!set maxcolumnwidth 20\n" + + "!set incremental true\n" + + "values 100 + 123;\n" + + "-- a comment\n" + + "values 100 + 253;\n"; + + File scriptFile = createTempFile("Script file name", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + + File outputFile = createTempFile("testScriptWithOutput", ".out"); + runScript(scriptFile, true, outputFile.getAbsolutePath()); + assertFileContains(outputFile, + allOf(containsString("| 223 |"), + containsString("| 353 |"))); + final boolean delete = outputFile.delete(); + assertThat(delete, is(true)); + } + + /** + * Values that contain null. + */ + @Test + public void testNull() { + final String script = "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString( + "+-------------+-------------+-----+\n" + + "| C1 | C2 | C3 |\n" + + "+-------------+-------------+-----+\n" + + "| 1 | null | |\n" + + "+-------------+-------------+-----+\n")); + } + + @Test + public void testScan() { + final String expectedLine0 = "Compliant Version Driver Class"; + final String expectedLine1 = "yes 2.4 org.hsqldb.jdbc.JDBCDriver"; + checkScriptFile("!scan\n", false, + equalTo(SqlLine.Status.OK), + allOf(containsString(expectedLine0), containsString(expectedLine1))); + } + + /** + * Table output without header. + */ + @Test + public void testTableOutputNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("| 1 | null | |\n")); + } + + /** + * Csv output without header. + */ + @Test + public void testCsvNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set outputformat csv\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("'1','null',''\n")); + } + + /** + * Tests the "close" command, + * [HIVE-5768] + * Beeline connection cannot be closed with '!close' command and + * [SQLLINE-139] + * Look for the exact match if there are multiple matches. + */ + @Test + public void testClose() { + final String expected = "!close\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile("!close\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + /** + * Test case for + * [SQLLINE-32] + * !help set' should print documentation for all variables. + */ + @Test + public void testHelpSet() { + final String expected = "1/1 !help set\n" + + "!set List / set a sqlline variable\n" + + "\n" + + "Variables:\n" + + "\n" + + "Variable Value Description\n" + + "=============== ========== " + + "==================================================\n" + + "autoCommit true/false " + + "Enable/disable automatic transaction commit\n" + + "autoSave true/false Automatically save preferences\n"; + checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + + // Make sure that each variable (autoCommit, autoSave, color, etc.) has a + // line in the output of '!help set' + final SqlLine sqlLine = new SqlLine(); + String help = sqlLine.loc("help-set") + + sqlLine.loc("variables"); + + final TreeSet propertyNamesMixed = + Arrays.stream(BuiltInProperty.values()) + .map(BuiltInProperty::propertyName) + .collect(Collectors.toCollection(TreeSet::new)); + for (String p : propertyNamesMixed) { + assertThat(help, containsString("\n" + p + " ")); + } + assertThat(propertyNamesMixed.contains("autoCommit"), + is(true)); + assertThat(propertyNamesMixed.contains("autocommit"), + is(false)); + assertThat(propertyNamesMixed.contains("trimScripts"), + is(true)); + + while (help.length() > 0) { + int i = help.indexOf("\n", 1); + if (i < 0) { + break; + } + if (i > 78) { + fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i)); + } + help = help.substring(i); + } + } + + /** + * Test case for + * [SQLLINE-39] + * 'help set' should not break long lines. + * + *

    But it should break 'help all', which consists of a single long line. + */ + @Test + public void testHelpAll() { + // Note that "connections" has been broken onto a new line. + final String expected = "1/1 !help all\n" + + "!all Execute the specified SQL against all the current\n" + + " connections\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help all\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + + /** + * Tests "!go <non-existent connection indexes>". + */ + @Test + public void testGoFailing() { + final String[] connectionIndexes = {"321", "invalid"}; + for (String connectionIndex : connectionIndexes) { + final String script = "!go " + connectionIndex + "\n"; + final String expected = "Invalid connection: " + connectionIndex; + checkScriptFile(script, false, + // Status.OTHER as checking of fail cases + equalTo(SqlLine.Status.OTHER), containsString(expected)); + } + } + + /** + * Tests "!help go". "go" and "#" are synonyms. + */ + @Test + public void testHelpGo() { + for (String c : new String[] {"go", "#"}) { + final String expected = "1/1 !help " + c + "\n" + + "!go Select the current connection\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help " + c + "\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + } + + /** + * Test case for + * !?, !# + * and other one-symbol length commands stopped working + * + *

    '!?' should work in the same way as '!help'. + */ + @Test + public void testHelpAsQuestionMark() { + final String script = "!?\n"; + final String expected = + "!autocommit Set autocommit mode on or off"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + allOf(not(containsString("Unknown command: ?")), + containsString(expected))); + } + + /** + * Test case for + * [SQLLINE-49] + * !manual command fails. + */ + @Test + public void testManual() { + final String expectedLine = "sqlline version"; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + new MockUp() { + @Mock + void less(Terminal terminal, InputStream in, PrintStream out, + PrintStream err, Path currentDir, String[] argv) { + } + }; + + SqlLine beeLine = new SqlLine(); + SqlLine.Status status = + begin(beeLine, baos, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + beeLine.runCommands(new DispatchCallback(), "!manual"); + String output = baos.toString("UTF8"); + + assertThat(output, containsString(expectedLine)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-38] + * Expand ~ to user's home directory. */ + @Test + public void testRunFromHome() { + try { + Path tmpDir = + Files.createTempDirectory( + Paths.get(System.getProperty("user.home")), + "tmpdir" + System.nanoTime()); + tmpDir.toFile().deleteOnExit(); + + File tmpFile = createTempFile("test", ".sql", tmpDir); + try (Writer fw = new OutputStreamWriter( + new FileOutputStream(tmpFile), StandardCharsets.UTF_8)) { + fw.write("!set outputformat csv\n"); + fw.write("values (1, 2, 3, 4, 5);"); + fw.flush(); + checkScriptFile("!run ~" + File.separatorChar + + tmpDir.getFileName() + + File.separatorChar + tmpFile.getName().toString(), + false, + equalTo(SqlLine.Status.OK), + allOf(containsString("!set outputformat csv"), + containsString("values (1, 2, 3, 4, 5);"))); + } + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-26] + * Flush output for each command when using !record command. + */ + @Test + public void testRecord() { + File file = createTempFile("sqlline", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + /** Test case for + * [SQLLINE-62] + * Expand ~ to user's home directory. */ + @Test + public void testRecordHome() { + File home = new File(System.getProperty("user.home")); + File file; + for (int i = 0;; i++) { + file = new File(home, "sqlline" + i + ".log"); + if (!file.exists()) { + break; + } + } + file.deleteOnExit(); + final String s = "Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "2/4 !set outputformat csv\n" + + "3/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "4/4 !record\n"; + checkScriptFile("!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n", + false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/4 !record .*.log\n" + + s + + "Recording stopped.\n" + + ".*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, RegexMatcher.of(s)); + final boolean delete = file.delete(); + assertThat(delete, is(true)); + } + + /** + * As {@link #testRecord()}, but file name is double-quoted and contains a + * space. + */ + @Test + public void testRecordFilenameWithSpace() { + File file = createTempFile("sqlline file with spaces", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + private static void assertFileContains(File file, Matcher matcher) { + try (BufferedReader br = new BufferedReader( + new InputStreamReader(new FileInputStream(file), + StandardCharsets.UTF_8.name()))) { + final StringWriter stringWriter = new StringWriter(); + for (;;) { + final String line = br.readLine(); + if (line == null) { + break; + } + stringWriter.write(line); + stringWriter.write("\n"); + } + assertThat(toLinux(stringWriter.toString()), matcher); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-61] + * Add !nickname command. + */ + @Test + public void testNickname() { + final String script = "!set outputformat csv\n" + + "values 1;\n" + + "!nickname foo\n" + + "values 2;\n"; + final String expected = "(?s)1/4 !set outputformat csv\n" + + "2/4 values 1;\n" + + "'C1'\n" + + "'1'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/4 !nickname foo\n" + + "4/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * The first command should fail and the second command should not execute. + */ + @Test + public void testBreakOnErrorScriptFile() { + checkScriptFile("select * from abcdefg01;\ncall 100 + 23;\n", + true, + equalTo(SqlLine.Status.OTHER), + not(containsString(" 123 "))); + } + + /** + * Emulation of Apache Hive behavior with throwing exceptions + * while calling {@link DatabaseMetaData#storesUpperCaseIdentifiers()} + * and {@link DatabaseMetaData#supportsTransactionIsolationLevel(int)}. + * + *

    Also please see + * [SQLLINE-183]. + * + * @param meta Mocked JDBCDatabaseMetaData + */ + @Test + public void testExecutionWithNotSupportedMethods( + @Mocked final JDBCDatabaseMetaData meta) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + + // emulate apache hive behavior + meta.supportsTransactionIsolationLevel(4); + result = new SQLException("Method not supported"); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback dc = new DispatchCallback(); + sqlLine.initArgs(args, dc); + os.reset(); + sqlLine.runCommands(dc, + "!set incremental true", + "values 1;"); + final String output = os.toString("UTF8"); + final String line0 = "+-------------+"; + final String line1 = "| C1 |"; + final String line2 = "+-------------+"; + final String line3 = "| 1 |"; + final String line4 = "+-------------+"; + assertThat(output, + CoreMatchers.allOf(containsString(line0), + containsString(line1), + containsString(line2), + containsString(line3), + containsString(line4))); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + @Test + public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta, + @Mocked final JDBCResultSet resultSet) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getSQLKeywords(); + result = ""; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + // Generate an exception on a call to resultSet.next + resultSet.next(); + result = new SQLException("Generated Exception."); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + // If sqlline is not initialized, handleSQLException will print + // the entire stack trace. + // To prevent that, forcibly set init to true. + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "CREATE TABLE rsTest ( a int);", + "insert into rsTest values (1);", + "insert into rsTest values (2);", + "select a from rsTest; "); + String output = os.toString("UTF8"); + assertThat(output, containsString("Generated Exception")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Attempts to execute a missing script file with the -f option to SqlLine. + */ + @Test + public void testNegativeScriptFile() { + // Create and delete a temp file + File scriptFile = createTempFile("sqllinenegative", "temp"); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OTHER)); + assertThat(pair.output, not(containsString(" 123 "))); + } + + /** Displays usage. */ + @Test + public void testUsage() { + Pair pair = run("--help"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + private int countUsage(String output) { + int n = 0; + for (String line : output.split("\n")) { + if (line.contains("Usage")) { + ++n; + } + } + return n; + } + + /** Invalid arguments. */ + @Test + public void testInvalidArguments() { + Pair pair = run("--fuzz"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + /** Result of executing sqlline: status code and output. */ + static class Pair { + final SqlLine.Status status; + final String output; + + Pair(SqlLine.Status status, String output) { + this.status = status; + this.output = output; + } + } + + @Test + public void testIsolationSetting() { + final String script0 = "!isolation TRANSACTION_NONE\n"; + final String expected = "Transaction isolation level TRANSACTION_NONE " + + "is not supported. Default (TRANSACTION_READ_COMMITTED) " + + "will be used instead."; + checkScriptFile(script0, true, equalTo(SqlLine.Status.OTHER), + containsString(expected)); + } + + @Test + public void testDefaultIsolation() { + final String script1 = "!isolation default\n"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + allOf(not(containsString("Transaction isolation level")), + not(containsString("is not supported")))); + } + + /** + * HIVE-4566, "NullPointerException if typeinfo and nativesql commands are + * executed at beeline before a DB connection is established". + */ + @Test + public void testNPE() { + SqlLine sqlLine = new SqlLine(); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + + try { + sqlLine.runCommands(new DispatchCallback(), "!typeinfo"); + String output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + + sqlLine.runCommands(new DispatchCallback(), "!nativesql"); + output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandlerOnStartup() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final String[] args = { + "-e", "!set maxwidth 80", + "-ch", "sqlline.extensions.HelloWorldCommandHandler"}; + begin(sqlLine, os, false, args); + + try { + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!test"); + output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello test")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandler() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + begin(sqlLine, os, false, "-e", "!set maxwidth 80"); + + try { + final String script = "!commandhandler" + + " sqlline.extensions.HelloWorld2CommandHandler" + + " sqlline.extensions.HelloWorldCommandHandler"; + sqlLine.runCommands(new DispatchCallback(), script); + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD2")); + final String expected = "Could not add command handler " + + "sqlline.extensions.HelloWorldCommandHandler as one of commands " + + "[hello, test] is already present"; + assertThat(output, containsString(expected)); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello2")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testTablesCsv() { + final String script = "!set outputformat csv\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("'TABLE_CAT','TABLE_SCHEM','TABLE_NAME',"), + containsString("'PUBLIC','SCOTT','SALGRADE','TABLE','',"))); + } + + /** + * java.lang.NullPointerException test case from + * https://github.com/julianhyde/sqlline/pull/86#issuecomment-410868361 + */ + @Test + public void testCsvDelimiterAndQuoteCharacter() { + final String script = "!set outputformat csv\n" + + "!set csvDelimiter null\n" + + "!set csvQuoteCharacter @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!set csvDelimiter ##\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@null@C2@null@C3@null@C4@null@C5@null@C6@"; + final String line2 = + "@#@null@@@#@@@null@1@null@1969-07-20@null@@null@ 1'2\"3\t4@"; + final String line3 = "@C1@##@C2@##@C3@##@C4@##@C5@##@C6@"; + final String line4 = "@#@##@@@#@@@##@1@##@1969-07-20@##@@##@ 1'2\"3\t4@"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testCsvOneLiner() { + final String script = "!outputformat csv \"'\" @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!outputformat csv & default\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@'@C2@'@C3@'@C4@'@C5@'@C6@"; + final String line2 = + "@#@'@@@#@@@'@1@'@1969-07-20@'@@'@ 1'2\"3\t4@"; + final String line3 = "'C1'&'C2'&'C3'&'C4'&'C5'&'C6'"; + final String line4 = + "'#'&'@#@'&'1'&'1969-07-20'&''&' 1''2\"3\t4'"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testSetForNulls() { + final String script = "!set numberFormat null\n" + + "!set\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("numberFormat null")); + } + + @Test + public void testSetNonIntValuesToIntProperties() { + SqlLine sqlLine = new SqlLine(); + final String headerIntervalScript = "!set headerinterval abc\n"; + checkScriptFile(headerIntervalScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "headerinterval", "abc"))); + + final String rowLimitScript = "!set rowlimit xxx\n"; + checkScriptFile(rowLimitScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "rowlimit", "xxx"))); + } + + @Test + public void testSelectXmlAttributes() { + final String script = "!set outputformat xmlattr\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ']]> 1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString("&4\"/>"))); + } + + @Test + public void testSelectXmlElements() { + final String script = "!set outputformat xmlelements\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' ]]>1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString(""), + containsString("1"), + containsString("-1.5"), + containsString("TRUE"), + containsString("1969-07-20"), + containsString("null"), + containsString(" ]]>1'2\"3\t<>&4"), + containsString(""), + containsString(""))); + } + + @Test + public void testTablesJson() { + final String script = "!set outputformat json\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"TABLE_CAT\":\"PUBLIC\"," + + "\"TABLE_SCHEM\":\"SYSTEM_LOBS\",\"TABLE_NAME\":\"BLOCKS\"," + + "\"TABLE_TYPE\":\"SYSTEM TABLE\",\"REMARKS\":null," + + "\"TYPE_CAT\":null,"))); + } + + @Test + public void testSelectJson() { + final String script = "!set outputformat json\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"C1\":1,\"C2\":-1.5,\"C3\":true," + + "\"C4\":\"1969-07-20\",\"C5\":null," + + "\"C6\":\" 1'2\\\"3\\t4\"}"))); + } + + @Test + public void testNullValue() { + final String script = "!set nullValue %%%\n" + + "!set outputformat csv\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue \"'\"\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue null\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'%%%','-1.5','%%%','1969-07-20','%%%','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'''','-1.5','''','1969-07-20','''','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'null','-1.5','null','1969-07-20','null','null'"))); + } + + @Test + public void testTimeFormat() { + // Use System.err as it is used in sqlline.SqlLineOpts#set + final PrintStream originalErr = System.err; + try { + final ByteArrayOutputStream errBaos = new ByteArrayOutputStream(); + System.setErr( + new PrintStream(errBaos, false, StandardCharsets.UTF_8.name())); + + // successful patterns + final String okTimeFormat = "!set timeFormat HH:mm:ss\n"; + final String defaultTimeFormat = "!set timeFormat default\n"; + final String okDateFormat = "!set dateFormat YYYY-MM-dd\n"; + final String defaultDateFormat = "!set dateFormat default\n"; + final String okTimestampFormat = "!set timestampFormat default\n"; + final String defaultTimestampFormat = "!set timestampFormat default\n"; + + // successful cases + final SqlLine sqlLine = new SqlLine(); + sqlLine.runCommands(new DispatchCallback(), okTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + + // failed patterns + final String wrongTimeFormat = "!set timeFormat qwerty\n"; + final String wrongDateFormat = "!set dateFormat ASD\n"; + final String wrongTimestampFormat = + "!set timestampFormat 'YYYY-MM-ddTHH:MI:ss'\n"; + + // failed cases + sqlLine.runCommands(new DispatchCallback(), wrongTimeFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'q'")); + sqlLine.runCommands(new DispatchCallback(), wrongDateFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'A'")); + sqlLine.runCommands(new DispatchCallback(), wrongTimestampFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'T'")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } finally { + // Set error stream back + System.setErr(originalErr); + } + } + + /** + * Test case for + * [SQLLINE-203] + * !indexes command fails because of Hive bug. + * The bug in question is + * [HIVE-20983] + * HiveResultSetMetaData.getColumnDisplaySize throws for SHORT column. + * + * @param meta Mocked hsqldb {@link JDBCResultSetMetaData} to use in the test + */ + @Test + public void testOutputWithFailingColumnDisplaySize( + @Mocked final JDBCResultSetMetaData meta) { + try { + new Expectations() { + { + meta.getColumnCount(); + result = 3; + + meta.getColumnLabel(1); + result = "TABLE_CAT"; + + meta.getColumnLabel(2); + result = "TABLE_SCHEM"; + + meta.getColumnLabel(3); + result = "TABLE_NAME"; + + meta.getColumnDisplaySize(1); + result = new Exception("getColumnDisplaySize exception"); + } + }; + + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "!set incremental true", + "!set maxwidth 80", + "!set verbose true", + "!indexes"); + assertThat(os.toString("UTF8"), not(containsString("Exception"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests the {@code !connect} command with interactive password submission. + */ + @Test + public void testConnectWithoutPassword() { + new MockUp() { + @Mock + String readPassword(String url) { + return ""; + } + }; + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} property outside of the URL: + * + *

    + * !connect -p PASSWORD_HASH TRUE jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} and {@code ALLOW_LITERALS} properties + * outside of the URL: + * + *
    + * !connect -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE + * jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter2() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!set maxwidth 80"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "select 1;"); + String output = os.toString("UTF8"); + final String expected = "Error:"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing the password in as a hash: + * + *
    + * !connect "jdbc:h2:mem; PASSWORD_HASH=TRUE" sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbProperty() { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + try { + beeLine.runCommands(dc, "!set maxwidth 80"); + + // fail attempt + String fakeNonEmptyPassword = "nonEmptyPasswd"; + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE\" " + + ConnectionSpec.H2.username + + " \"" + fakeNonEmptyPassword + "\""); + String output = os.toString("UTF8"); + final String expected0 = "Error:"; + assertThat(output, containsString(expected0)); + os.reset(); + + // success attempt + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE;ALLOW_LITERALS=NONE\" " + + ConnectionSpec.H2.username + " \"" + + StringUtils.convertBytesToHex(bytes) + + "\""); + beeLine.runCommands(dc, "!set incremental true"); + beeLine.runCommands(dc, "!tables"); + output = os.toString("UTF8"); + final String expected1 = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected1)); + + beeLine.runCommands(dc, "select 5;"); + output = os.toString("UTF8"); + final String expected2 = "Error:"; + assertThat(output, containsString(expected2)); + os.reset(); + + beeLine.runCommands(new DispatchCallback(), "!quit"); + output = os.toString("UTF8"); + assertThat(output, + allOf(not(containsString("Error:")), containsString("!quit"))); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + private static PrintStream getPrintStream(OutputStream os) { + try { + return new PrintStream(os, false, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testReconnect() { + final String script = "!reconnect"; + final String expected = "Reconnecting to \"jdbc:hsqldb:res:scott\"...\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + @Test + public void testTables() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxcolumnwidth 15\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = + "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | |"; + final String line1 = + "| PUBLIC | SYSTEM_LOBS | BLOCKS | SYSTEM TABLE | |"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + @Test + public void testTablesH2() { + connectionSpec = ConnectionSpec.H2; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + /** + * Test case for + * [SQLLINE-107] + * Script fails if the wrong driver is specified with -d option + * and there is a valid registered driver for the specified url. + * + */ + @Test + public void testTablesH2WithErrorDriver() { + connectionSpec = ConnectionSpec.ERROR_H2_DRIVER; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + final String message = "Could not find driver " + + connectionSpec.driver + + "; using registered driver org.h2.Driver instead"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString(message), + not(containsString("NullPointerException")), + containsString(line0), + containsString(line1))); + } + + @Test + public void testH2TablesWithErrorUrl() { + connectionSpec = ConnectionSpec.ERROR_H2_URL; + final String script = "!tables\n"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + CoreMatchers.allOf(containsString("No suitable driver"), + not(containsString("NullPointerException")))); + } + + @Test + public void testEmptyMetadata() { + final String script = "!metadata\n"; + final String line = "Usage: metadata "; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + /** Tests that methods inherited from Object are not included in the list + * of possible metadata methods. */ + @Test + public void testPossibleMetadataValues() { + final String script = "!metadata 1\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString("allProceduresAreCallable"), + containsString("getIndexInfo"), + not(containsString("Exception")), + not(containsString("equals")), + not(containsString("notify")), + not(containsString("wait")), + not(containsString("toString")), + not(containsString("hashCode")), + not(containsString("notifyAll")))); + } + + @Test + public void testMetadataForClassHierarchy() { + final SqlLine beeLine = new SqlLine(); + + new MockUp() { + @Mock + public DatabaseMetaData getMetaData() throws SQLException { + return new CustomDatabaseMetadata( + (JDBCConnection) beeLine.getConnection()); + } + }; + + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.HSQLDB.url + " \"" + + ConnectionSpec.HSQLDB.username + "\" \"" + + ConnectionSpec.HSQLDB.password + "\""); + os.reset(); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + assertThat(output, + allOf(containsString("TABLE_CAT"), + not(containsString("No such method \"getTables\"")))); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testEmptyRecord() { + final String line = "Usage: record "; + checkScriptFile("!record", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyRun() { + final String line = "Usage: run "; + checkScriptFile("!run", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyScript() { + final String line = "Usage: script "; + checkScriptFile("!script", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEscapeSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxColumnWidth 15\n" + + "!set escapeOutput yes\n" + + "values \n" + + "('\n" + + "multiline\n" + + "value') \n" + + ";\n"; + final String line1 = "" + + "+-----------------+\n" + + "| C1 |\n" + + "+-----------------+\n" + + "| \\nmultiline \\nvalue |\n" + + "+-----------------+\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!sql \n" + + "values \n" + + "(1, 2) \n" + + ";\n"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 1 | 2 |\n" + + "+-------------+-------------+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAllMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!all \n" + + "values \n" + + "(1, '2') \n" + + ";\n"; + final String line1 = "" + + "+-------------+----+\n" + + "| C1 | C2 |\n" + + "+-------------+----+\n" + + "| 1 | 2 |\n" + + "+-------------+----+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAppInfoMessage() { + Pair pair = run("-e", "!set maxwidth 80"); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + containsString(Application.DEFAULT_APP_INFO_MESSAGE)); + + String[] args = {"-e", "!set maxwidth 80", "-ac", "INCORRECT_CLASS_NAME"}; + pair = run(args); + assertThat(pair.output, + containsString("Could not initialize INCORRECT_CLASS_NAME")); + assertThat(pair.output, + containsString(CustomApplication.DEFAULT_APP_INFO_MESSAGE)); + + String[] args2 = {"-e", "!set maxwidth 80", + "-ac", "sqlline.extensions.CustomApplication"}; + pair = run(args2); + assertThat(pair.output, + containsString(CustomApplication.CUSTOM_INFO_MESSAGE)); + } + + @Test + public void testCustomOutputFormats() { + // json format was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!set outputformat json\n" + + "values 1;"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("Unknown outputFormat \"json\"")); + } + + @Test + public void testCustomCommands() { + // table command was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Unknown command: tables")); + } + + @Test + public void testAppConfigReset() { + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!appconfig sqlline.Application\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("TABLE_CAT")); + } + + @Test + public void testCustomOpts() { + // nulls are displayed as custom_null + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "values(null)"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("custom_null")); + } + + @Test + public void testScanForEmptyAllowedDrivers() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.emptyList(); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("No driver classes found")); + } + + @Test + public void testScanForOnlyH2Allowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.h2.Driver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 1.4 org.h2.Driver"), + not(containsString("org.hsqldb.jdbc.JDBCDriver")))); + } + + @Test + public void testScanForOnlyHsqldbAllowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.hsqldb.jdbc.JDBCDriver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 2.4 org.hsqldb.jdbc.JDBCDriver"), + not(containsString("org.h2.Driver")))); + } + + @Test + public void testVersion() { + final String script = "!set\n"; + try { + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(new Application().getVersion())); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSetVersion() { + final String script = "!set version test-version\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("version property is read only")); + } + + @Test + public void testSetPropertySuccess() { + final String script = "!set timeout\n" + + "!set timeout 200\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("timeout -1"), + containsString("timeout 200"))); + } + + @Test + public void testSetPropertyFailure() { + final String script = "!set unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testSetUsage() { + final String script = "!set 1 2 3"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: set [all | []]")); + } + + @Test + public void testSetWrongValueToEnumTypeProperties() { + Collection propertiesWithAvailableValues = + Arrays.stream(BuiltInProperty.values()) + .filter(t -> !t.getAvailableValues().isEmpty()) + .collect(Collectors.toSet()); + final String wrongValue = "wrong_value"; + for (BuiltInProperty property: propertiesWithAvailableValues) { + final String script = + "!set " + property.propertyName() + " " + wrongValue + "\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf( + containsString("Unknown " + property.propertyName() + " \"" + + wrongValue + "\""), + not(containsString("Exception")))); + } + } + + @Test + public void testResetSuccess() { + final String script = "!set timeout 200\n" + + "!reset timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("[timeout] was reset to [-1]")); + } + + @Test + public void testResetFailure() { + final String script = "!reset unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testResetAll() { + final String script = "!set timeout 200\n" + + "!reset all\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("All properties were reset to their defaults."), + containsString("timeout -1"))); + } + + @Test + public void testResetUsage() { + final String script = "!reset"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: reset (all | )")); + } + + @Test + public void testRerun() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:!/ 4\n" + + "1536743104551:!/ 5\n" + + "1536743104551:!/ 2\n" + + "1536743104551:!/ 7\n" + + "1536743107526:!history\n" + + "1536743115431:!/ 3\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set incremental true", + "!set maxcolumnwidth 30", + "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + "\"\""); + os.reset(); + + beeLine.runCommands(dc, "!/ 1"); + String output = os.toString("UTF8"); + final String expected0 = "+----------------------------+"; + final String expected1 = "| C1 |"; + final String expected2 = "1 row selected"; + assertThat(output, + allOf(containsString(expected0), + containsString(expected1), + containsString(expected2))); + os.reset(); + + beeLine.runCommands(dc, "!/ 4"); + output = os.toString("UTF8"); + String expectedLine3 = "Cycled rerun of commands from history [2, 4]"; + assertThat(output, containsString(expectedLine3)); + os.reset(); + + beeLine.runCommands(dc, "!/ 3"); + output = os.toString("UTF8"); + String expectedLine4 = "Cycled rerun of commands from history [3, 5, 7]"; + assertThat(output, containsString(expectedLine4)); + os.reset(); + + beeLine.runCommands(dc, "!/ 8"); + output = os.toString("UTF8"); + String expectedLine5 = "Cycled rerun of commands from history [8]"; + assertThat(output, containsString(expectedLine5)); + os.reset(); + + beeLine.runCommands(dc, "!rerun " + Integer.MAX_VALUE); + output = os.toString("UTF8"); + String expectedLine6 = + "Usage: rerun , available range of offset is -7..8"; + assertThat(output, containsString(expectedLine6)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMaxColumnWidthIncremental() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line2 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line3 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testMaxColumnWidthBuffered() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line1 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line2 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line3 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + /** Tests with incrementalBufferRows = -1; query stays in non-incremental + * mode. */ + @Test + public void testIncrementalBufferRows() { + final String script1 = "!set incrementalBufferRows -1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line1 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + /** Tests with incrementalBufferRows = 0; query goes straight into + * incremental mode. */ + @Test + public void testIncrementalBufferRows2() { + final String script2 = "!set incrementalBufferRows 0\n" + + "!set incremental false\n" + + "select * from (values (1, 2), (1, 20), (111, 20), (11, 2222), (1, 22))"; + final String line2 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 1 | 2 |\n" + + "| 1 | 20 |\n" + + "| 111 | 20 |\n" + + "| 11 | 2222 |\n" + + "| 1 | 22 |\n" + + "+----+----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + } + + /** Tests with incrementalBufferRows = 1; query starts in non-incremental mode + * and switches to incremental after 1 row. */ + @Test + public void testIncrementalBufferRows3() { + final String script3 = "!set incrementalBufferRows 1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222), (111, 2222))"; + final String line3 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "| 111 | 2222 |\n" + + "+----+----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + } + + /** Tests with incrementalBufferRows = 4; query starts in non-incremental mode + * and rows run out before the limit is reached. */ + @Test + public void testIncrementalBufferRows4() { + final String script4 = "!set incrementalBufferRows 4\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line4 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testIncrementalBufferRows5() { + // With incrementalBufferRows default (1000), query starts and + // stays in incremental mode. + final String script5 = "!set incrementalBufferRows default\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2))"; + final String line5 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "+----+----+"; + checkScriptFile(script5, true, equalTo(SqlLine.Status.OK), + containsString(line5)); + } + + @Test + public void testMaxHistoryFileRows() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:SELECT \\n 'asd' as \"sdf\", 4 \\n \\n as \\n c2;\\n\n" + + "1536743104551:SELECT \\n 'asd' \\n as \\n c2;\\n\n" + + "1536743104551:!/ 2\n" + + "1536743104551:SELECT \\n 2123 \\n as \\n c2 from dual;\\n\n" + + "1536743107526:!history\n" + + "1536743115431:SELECT \\n 2 \\n as \\n c2;\n" + + "1536743115431:SELECT \\n '213' \\n as \\n c1;\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + bw.close(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + final int maxLines = 3; + beeLine.runCommands(dc, "!set maxHistoryFileRows " + maxLines); + os.reset(); + beeLine.runCommands(dc, "!history"); + assertEquals(maxLines + 1, + os.toString("UTF8").split("\\s+\\d{2}:\\d{2}:\\d{2}\\s+").length); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSave() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + SqlLine.Status status = begin(beeLine, os, false, + "-e", "!save"); + assertThat(status, equalTo(SqlLine.Status.OK)); + final DispatchCallback dc = new DispatchCallback(); + + assertThat(os.toString("UTF8"), + containsString("Saving preferences to")); + os.reset(); + beeLine.runCommands(dc, "!set"); + assertThat(os.toString("UTF8"), + allOf(containsString("autoCommit"), + not(containsString("Unknown property:")))); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScript() { + final File file = createTempFile("sqlline", ".script"); + final String script = "!script " + file.getAbsolutePath() + "\n" + + "values (100, 200);\n" + + "!set maxcolumnwidth -1\n" + + "!script\n" + + "values (1, 2);\n"; + final String expected = "(?s)1/5 !script.*" + + "2/5 values \\(100, 200\\);.*" + + "3/5 !set maxcolumnwidth -1.*" + + "4/5 !script.*" + + "5/5 values \\(1, 2\\);.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + + final String output = "values \\(100, 200\\);\n" + + "!set maxcolumnwidth -1\n"; + assertFileContains(file, RegexMatcher.of(output)); + } + + @Test + public void testStartupArgsWithoutUrl() { + try { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests setting the "confirm" property. + */ + @Test + public void testConfirmFlag() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + begin(line, os, false, "-e", "!set confirm true"); + assertThat(line.getOpts().getConfirm(), is(true)); + begin(line, os, false, "-e", "!set confirm false"); + assertThat(line.getOpts().getConfirm(), is(false)); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests that the "confirm" property works. + */ + @Test + public void testConfirmFlagEffects() { + new MockUp() { + @Mock + int getUserAnswer(String question, int... allowedAnswers) { + return 'n'; + } + }; + + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + assertThat(line.getOpts().getConfirmPattern(), is("default")); + String script = "CREATE TABLE dummy_test(pk int);\n" + + "INSERT INTO dummy_test(pk) VALUES(1);\n" + + "INSERT INTO dummy_test(pk) VALUES(2);\n" + + "INSERT INTO dummy_test(pk) VALUES(3);\n" + + "DELETE FROM dummy_test;\n" + + "DROP TABLE dummy_test;\n"; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OK), + containsString(" ")); + + script = "!set confirm true\n" + script; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OTHER), + containsString(line.loc("abort-action"))); + } + + /** + * Tests that the "confirmPattern" property works. + */ + @Test + public void testConfirmPattern() { + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i:(TRUNCATE|ALTER))\""); + assertThat(line.getOpts().getConfirmPattern(), + is("^(?i:(TRUNCATE|ALTER))")); + + begin(line, os, false, "-e", "!set confirmPattern default"); + assertThat(line.getOpts().getConfirmPattern(), + is(line.loc("default-confirm-pattern"))); + } + + /** + * Test for illegal regex in confirmPattern + */ + @Test + public void testExceptionConfirmPattern() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + SqlLine.Status status = + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i*:(TRUNCATE|ALTER))\""); + assertThat(status, equalTo(SqlLine.Status.OK)); + assertThat(os.toString("UTF8"), containsString("invalid regex")); + os.reset(); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** Information necessary to create a JDBC connection. Specify one to run + * tests against a different database. (hsqldb is the default.) */ + public static class ConnectionSpec { + public final String url; + public final String username; + public final String password; + public final String driver; + + public ConnectionSpec(String url, String username, String password, + String driver) { + this.url = url; + this.username = username; + this.password = password; + this.driver = driver; + } + + public static final ConnectionSpec H2 = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec ERROR_H2_DRIVER = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "ERROR_DRIVER"); + + public static final ConnectionSpec ERROR_H2_URL = + new ConnectionSpec("ERROR_URL", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec HSQLDB = + new ConnectionSpec( + ScottHsqldb.URI, ScottHsqldb.USER, ScottHsqldb.PASSWORD, + "org.hsqldb.jdbcDriver"); + + public static final ConnectionSpec MYSQL = + new ConnectionSpec( + "jdbc:mysql://localhost/scott", "scott", "tiger", + "com.mysql.jdbc.Driver"); + } + + /** Regular expression matcher. */ + private static class RegexMatcher extends BaseMatcher { + private final String pattern; + + RegexMatcher(String pattern) { + super(); + this.pattern = pattern; + } + + public static RegexMatcher of(String pattern) { + return new RegexMatcher(pattern); + } + + public boolean matches(Object o) { + return o instanceof String + && ((String) o).matches(pattern); + } + + public void describeTo(Description description) { + description.appendText("regular expression ").appendText(pattern); + } + } + +} + +// End SqlLineArgsTest.java + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PrintStream` acquired by call to `setOutputStream(...)` at line 966 is not released after line 993. +**Note**: potential exception at line 985 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SqlLineArgsTest.testExecutionException(JDBCDatabaseMetaData,JDBCResultSet) + +### Procedure Id: +sqlline.SqlLineArgsTest.testExecutionException(org.hsqldb.jdbc.JDBCDatabaseMetaData,org.hsqldb.jdbc..281d2ab4b16ce7a76452b4a728f2ad46 + +### File: +src/test/java/sqlline/SqlLineArgsTest.java + +### Key: +SqlLineArgsTest.java|testExecutionException|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +c2726cf9aa6d5d2372b63c5a343812d7 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8100/instruction.md b/inferredbugs-8100/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..55dc7560965f795436e1b3b0575c8be4fcbc1e9e --- /dev/null +++ b/inferredbugs-8100/instruction.md @@ -0,0 +1,2662 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sqlline +**Bug ID:** 17 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +// Licensed to Julian Hyde under one or more contributor license +// agreements. See the NOTICE file distributed with this work for +// additional information regarding copyright ownership. +// +// Julian Hyde licenses this file to you under the Modified BSD License +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/BSD-3-Clause +*/ +package sqlline; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.h2.util.StringUtils; +import org.hamcrest.BaseMatcher; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hsqldb.jdbc.CustomDatabaseMetadata; +import org.hsqldb.jdbc.JDBCConnection; +import org.hsqldb.jdbc.JDBCDatabaseMetaData; +import org.hsqldb.jdbc.JDBCResultSet; +import org.hsqldb.jdbc.JDBCResultSetMetaData; +import org.jline.builtins.Commands; +import org.jline.terminal.Terminal; +import org.junit.jupiter.api.Test; + +import mockit.Expectations; +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.internal.reflection.FieldReflection; +import net.hydromatic.scott.data.hsqldb.ScottHsqldb; +import sqlline.extensions.CustomApplication; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Executes tests of the command-line arguments to SqlLine. + */ +public class SqlLineArgsTest { + private static final ConnectionSpec CONNECTION_SPEC = ConnectionSpec.HSQLDB; + private ConnectionSpec connectionSpec; + + public SqlLineArgsTest() { + connectionSpec = CONNECTION_SPEC; + } + + static SqlLine.Status begin(SqlLine sqlLine, OutputStream os, + boolean saveHistory, String... args) { + try { + PrintStream beelineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(beelineOutputStream); + sqlLine.setErrorStream(beelineOutputStream); + final InputStream is = new ByteArrayInputStream(new byte[0]); + return sqlLine.begin(args, is, saveHistory); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Execute a script with "beeline -f". + * + * @return The stderr and stdout from running the script + * @param args Script arguments + */ + private static Pair run(String... args) { + try { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = begin(beeLine, os, false, args); + return new Pair(status, os.toString("UTF8")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + private Pair runScript(File scriptFile, boolean flag, String outputFileName) { + return runScript(connectionSpec, scriptFile, flag, outputFileName); + } + + private static Pair runScript(ConnectionSpec connectionSpec, File scriptFile, + boolean flag, String outputFileName) { + List args = new ArrayList<>(); + Collections.addAll(args, + "-d", connectionSpec.driver, + "-u", connectionSpec.url, + "-n", connectionSpec.username, + "-p", connectionSpec.password); + if (flag) { + args.add("-f"); + args.add(scriptFile.getAbsolutePath()); + } else { + args.add("--run=" + scriptFile.getAbsolutePath()); + } + if (outputFileName != null) { + args.add("-log"); + args.add(outputFileName); + } + return run(args.toArray(new String[0])); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * Tests for presence of an expected pattern in the output (stdout or stderr). + * + * @param scriptText Script text + * @param flag Command flag (--run or -f) + * @param statusMatcher Checks whether status is as expected + * @param outputMatcher Checks whether output is as expected + */ + private void checkScriptFile(String scriptText, boolean flag, + Matcher statusMatcher, + Matcher outputMatcher) { + try { + // Put the script content in a temp file + File scriptFile = createTempFile("foo", "temp"); + PrintStream os = + new PrintStream( + new FileOutputStream(scriptFile), + false, + StandardCharsets.UTF_8.name()); + os.print(scriptText); + os.close(); + + Pair pair = runScript(scriptFile, flag, null); + + // Check output before status. It gives a better clue what went wrong. + assertThat(toLinux(pair.output), outputMatcher); + assertThat(pair.status, statusMatcher); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Windows line separators in a string into Linux line separators; + * a Linux string is unchanged. */ + private static String toLinux(String s) { + return s.replaceAll("\r\n", "\n"); + } + + private File createTempFile(String prefix, String suffix) { + return createTempFile(prefix, suffix, null); + } + + private File createTempFile(String prefix, String suffix, Path directory) { + try { + final File file = directory == null + ? Files.createTempFile(prefix, suffix).toFile() + : Files.createTempFile(directory, prefix, suffix).toFile(); + file.deleteOnExit(); + return file; + } catch (IOException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMultilineScriptWithComments() { + final String script1Text = + "!set incremental true\n" + + "-- a comment \n values\n--comment\n (\n1\n, ' ab'\n--comment\n)\n;\n"; + + checkScriptFile(script1Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-------------+-----+\n" + + "| C1 | C2 |\n" + + "+-------------+-----+\n" + + "| 1 | ab |\n" + + "+-------------+-----+")); + + final String script2Text = + "!set incremental true\n" + + "--comment \n --comment2 \nvalues (';\n' /* comment */, '\"'" + + "/*multiline;\n ;\n comment*/)\n -- ; \n; -- comment"; + + checkScriptFile(script2Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-----+----+\n" + + "| C1 | C2 |\n" + + "+-----+----+\n" + + "| ; \n" + + " | \" |\n" + + "+-----+----+")); + } + + /** + * Attempt to execute a simple script file with the -f option to SqlLine. + * Test for presence of an expected pattern + * in the output (stdout or stderr), fail if not found. + */ + @Test + public void testPositiveScriptFile() { + checkScriptFile("call 100 + 23;\n", + true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * As above, but using '-run' rather than '-f'. + */ + @Test + public void testPositiveScriptFileUsingRun() { + checkScriptFile("call 100 + 23;\n", + false, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * Test case for + * [SQLLINE-42], + * Script fails if first line is a comment. + */ + @Test + public void testScriptFileStartsWithComment() { + final String scriptText = "-- a comment\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileStartsWithEmptyLine() { + final String scriptText = "\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileContainsComment() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithComments() { + final String scriptText = "--comment\n\n" + + "values \n10 \n+ \n23;\n\n\n" + + "-- a comment\n" + + "\n\nvalues " + + "--comment inside\n\n" + + "100 --comment inside\n\n" + + "+ \n\n23\n\n\n;\n\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithMultilineQuotedStrings() { + final String scriptText = "--comment\n\n" + + "values '\nmultiline;\n;\n; string\n'" + + ";\n\n\n" + + "values '\nmultiline2;\n;\n; string2\n'" + + ";\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString("multiline2;"), containsString("; string2"))); + } + + @Test + public void testScriptWithMultilineStatementsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment\n\n" + + "values 1;values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 1 |\n" + + "+----+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + + @Test + public void testScriptWithMultilineStatementsAndCommentsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment;;\n\n" + + "select * from (values ';') t (\";\");/*;select 1;*/values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+---+\n" + + "| ; |\n" + + "+---+\n" + + "| ; |\n" + + "+---+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + /** + * Tests sql with H2 specific one-line comment '//' + */ + @Test + public void testMultilineScriptWithH2Comments() { + final SqlLine sqlLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + final File tmpHistoryFile = createTempFile("queryToExecute", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + final String script = "\n" + + "\n" + + "!set incremental true\n" + + "\n" + + "\n" + + "select * from information_schema.tables// ';\n" + + "// \";" + + ";\n" + + "\n" + + "\n"; + bw.write(script); + bw.flush(); + } + SqlLine.Status status = + begin(sqlLine, os, false, + "-u", ConnectionSpec.H2.url, + "-n", ConnectionSpec.H2.username, + "--run=" + tmpHistoryFile.getAbsolutePath()); + assertThat(status, equalTo(SqlLine.Status.OK)); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |" + + " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |"; + assertThat(output, containsString(expected)); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-72] + * Allow quoted file names (including spaces) in !record, + * !run and !script commands. */ + @Test + public void testScriptFilenameWithSpace() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23;\n"; + File scriptFile = createTempFile("Script with Spaces", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + allOf(containsString(" 33 "), containsString(" 123 "))); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScriptWithOutput() { + final String scriptText = "!set maxcolumnwidth 20\n" + + "!set incremental true\n" + + "values 100 + 123;\n" + + "-- a comment\n" + + "values 100 + 253;\n"; + + File scriptFile = createTempFile("Script file name", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + + File outputFile = createTempFile("testScriptWithOutput", ".out"); + runScript(scriptFile, true, outputFile.getAbsolutePath()); + assertFileContains(outputFile, + allOf(containsString("| 223 |"), + containsString("| 353 |"))); + final boolean delete = outputFile.delete(); + assertThat(delete, is(true)); + } + + /** + * Values that contain null. + */ + @Test + public void testNull() { + final String script = "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString( + "+-------------+-------------+-----+\n" + + "| C1 | C2 | C3 |\n" + + "+-------------+-------------+-----+\n" + + "| 1 | null | |\n" + + "+-------------+-------------+-----+\n")); + } + + @Test + public void testScan() { + final String expectedLine0 = "Compliant Version Driver Class"; + final String expectedLine1 = "yes 2.4 org.hsqldb.jdbc.JDBCDriver"; + checkScriptFile("!scan\n", false, + equalTo(SqlLine.Status.OK), + allOf(containsString(expectedLine0), containsString(expectedLine1))); + } + + /** + * Table output without header. + */ + @Test + public void testTableOutputNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("| 1 | null | |\n")); + } + + /** + * Csv output without header. + */ + @Test + public void testCsvNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set outputformat csv\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("'1','null',''\n")); + } + + /** + * Tests the "close" command, + * [HIVE-5768] + * Beeline connection cannot be closed with '!close' command and + * [SQLLINE-139] + * Look for the exact match if there are multiple matches. + */ + @Test + public void testClose() { + final String expected = "!close\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile("!close\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + /** + * Test case for + * [SQLLINE-32] + * !help set' should print documentation for all variables. + */ + @Test + public void testHelpSet() { + final String expected = "1/1 !help set\n" + + "!set List / set a sqlline variable\n" + + "\n" + + "Variables:\n" + + "\n" + + "Variable Value Description\n" + + "=============== ========== " + + "==================================================\n" + + "autoCommit true/false " + + "Enable/disable automatic transaction commit\n" + + "autoSave true/false Automatically save preferences\n"; + checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + + // Make sure that each variable (autoCommit, autoSave, color, etc.) has a + // line in the output of '!help set' + final SqlLine sqlLine = new SqlLine(); + String help = sqlLine.loc("help-set") + + sqlLine.loc("variables"); + + final TreeSet propertyNamesMixed = + Arrays.stream(BuiltInProperty.values()) + .map(BuiltInProperty::propertyName) + .collect(Collectors.toCollection(TreeSet::new)); + for (String p : propertyNamesMixed) { + assertThat(help, containsString("\n" + p + " ")); + } + assertThat(propertyNamesMixed.contains("autoCommit"), + is(true)); + assertThat(propertyNamesMixed.contains("autocommit"), + is(false)); + assertThat(propertyNamesMixed.contains("trimScripts"), + is(true)); + + while (help.length() > 0) { + int i = help.indexOf("\n", 1); + if (i < 0) { + break; + } + if (i > 78) { + fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i)); + } + help = help.substring(i); + } + } + + /** + * Test case for + * [SQLLINE-39] + * 'help set' should not break long lines. + * + *

    But it should break 'help all', which consists of a single long line. + */ + @Test + public void testHelpAll() { + // Note that "connections" has been broken onto a new line. + final String expected = "1/1 !help all\n" + + "!all Execute the specified SQL against all the current\n" + + " connections\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help all\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + + /** + * Tests "!go <non-existent connection indexes>". + */ + @Test + public void testGoFailing() { + final String[] connectionIndexes = {"321", "invalid"}; + for (String connectionIndex : connectionIndexes) { + final String script = "!go " + connectionIndex + "\n"; + final String expected = "Invalid connection: " + connectionIndex; + checkScriptFile(script, false, + // Status.OTHER as checking of fail cases + equalTo(SqlLine.Status.OTHER), containsString(expected)); + } + } + + /** + * Tests "!help go". "go" and "#" are synonyms. + */ + @Test + public void testHelpGo() { + for (String c : new String[] {"go", "#"}) { + final String expected = "1/1 !help " + c + "\n" + + "!go Select the current connection\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help " + c + "\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + } + + /** + * Test case for + * !?, !# + * and other one-symbol length commands stopped working + * + *

    '!?' should work in the same way as '!help'. + */ + @Test + public void testHelpAsQuestionMark() { + final String script = "!?\n"; + final String expected = + "!autocommit Set autocommit mode on or off"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + allOf(not(containsString("Unknown command: ?")), + containsString(expected))); + } + + /** + * Test case for + * [SQLLINE-49] + * !manual command fails. + */ + @Test + public void testManual() { + final String expectedLine = "sqlline version"; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + new MockUp() { + @Mock + void less(Terminal terminal, InputStream in, PrintStream out, + PrintStream err, Path currentDir, String[] argv) { + } + }; + + SqlLine beeLine = new SqlLine(); + SqlLine.Status status = + begin(beeLine, baos, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + beeLine.runCommands(new DispatchCallback(), "!manual"); + String output = baos.toString("UTF8"); + + assertThat(output, containsString(expectedLine)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-38] + * Expand ~ to user's home directory. */ + @Test + public void testRunFromHome() { + try { + Path tmpDir = + Files.createTempDirectory( + Paths.get(System.getProperty("user.home")), + "tmpdir" + System.nanoTime()); + tmpDir.toFile().deleteOnExit(); + + File tmpFile = createTempFile("test", ".sql", tmpDir); + try (Writer fw = new OutputStreamWriter( + new FileOutputStream(tmpFile), StandardCharsets.UTF_8)) { + fw.write("!set outputformat csv\n"); + fw.write("values (1, 2, 3, 4, 5);"); + fw.flush(); + checkScriptFile("!run ~" + File.separatorChar + + tmpDir.getFileName() + + File.separatorChar + tmpFile.getName().toString(), + false, + equalTo(SqlLine.Status.OK), + allOf(containsString("!set outputformat csv"), + containsString("values (1, 2, 3, 4, 5);"))); + } + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-26] + * Flush output for each command when using !record command. + */ + @Test + public void testRecord() { + File file = createTempFile("sqlline", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + /** Test case for + * [SQLLINE-62] + * Expand ~ to user's home directory. */ + @Test + public void testRecordHome() { + File home = new File(System.getProperty("user.home")); + File file; + for (int i = 0;; i++) { + file = new File(home, "sqlline" + i + ".log"); + if (!file.exists()) { + break; + } + } + file.deleteOnExit(); + final String s = "Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "2/4 !set outputformat csv\n" + + "3/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "4/4 !record\n"; + checkScriptFile("!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n", + false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/4 !record .*.log\n" + + s + + "Recording stopped.\n" + + ".*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, RegexMatcher.of(s)); + final boolean delete = file.delete(); + assertThat(delete, is(true)); + } + + /** + * As {@link #testRecord()}, but file name is double-quoted and contains a + * space. + */ + @Test + public void testRecordFilenameWithSpace() { + File file = createTempFile("sqlline file with spaces", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + private static void assertFileContains(File file, Matcher matcher) { + try (BufferedReader br = new BufferedReader( + new InputStreamReader(new FileInputStream(file), + StandardCharsets.UTF_8.name()))) { + final StringWriter stringWriter = new StringWriter(); + for (;;) { + final String line = br.readLine(); + if (line == null) { + break; + } + stringWriter.write(line); + stringWriter.write("\n"); + } + assertThat(toLinux(stringWriter.toString()), matcher); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-61] + * Add !nickname command. + */ + @Test + public void testNickname() { + final String script = "!set outputformat csv\n" + + "values 1;\n" + + "!nickname foo\n" + + "values 2;\n"; + final String expected = "(?s)1/4 !set outputformat csv\n" + + "2/4 values 1;\n" + + "'C1'\n" + + "'1'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/4 !nickname foo\n" + + "4/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * The first command should fail and the second command should not execute. + */ + @Test + public void testBreakOnErrorScriptFile() { + checkScriptFile("select * from abcdefg01;\ncall 100 + 23;\n", + true, + equalTo(SqlLine.Status.OTHER), + not(containsString(" 123 "))); + } + + /** + * Emulation of Apache Hive behavior with throwing exceptions + * while calling {@link DatabaseMetaData#storesUpperCaseIdentifiers()} + * and {@link DatabaseMetaData#supportsTransactionIsolationLevel(int)}. + * + *

    Also please see + * [SQLLINE-183]. + * + * @param meta Mocked JDBCDatabaseMetaData + */ + @Test + public void testExecutionWithNotSupportedMethods( + @Mocked final JDBCDatabaseMetaData meta) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + + // emulate apache hive behavior + meta.supportsTransactionIsolationLevel(4); + result = new SQLException("Method not supported"); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback dc = new DispatchCallback(); + sqlLine.initArgs(args, dc); + os.reset(); + sqlLine.runCommands(dc, + "!set incremental true", + "values 1;"); + final String output = os.toString("UTF8"); + final String line0 = "+-------------+"; + final String line1 = "| C1 |"; + final String line2 = "+-------------+"; + final String line3 = "| 1 |"; + final String line4 = "+-------------+"; + assertThat(output, + CoreMatchers.allOf(containsString(line0), + containsString(line1), + containsString(line2), + containsString(line3), + containsString(line4))); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + @Test + public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta, + @Mocked final JDBCResultSet resultSet) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getSQLKeywords(); + result = ""; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + // Generate an exception on a call to resultSet.next + resultSet.next(); + result = new SQLException("Generated Exception."); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + // If sqlline is not initialized, handleSQLException will print + // the entire stack trace. + // To prevent that, forcibly set init to true. + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "CREATE TABLE rsTest ( a int);", + "insert into rsTest values (1);", + "insert into rsTest values (2);", + "select a from rsTest; "); + String output = os.toString("UTF8"); + assertThat(output, containsString("Generated Exception")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Attempts to execute a missing script file with the -f option to SqlLine. + */ + @Test + public void testNegativeScriptFile() { + // Create and delete a temp file + File scriptFile = createTempFile("sqllinenegative", "temp"); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OTHER)); + assertThat(pair.output, not(containsString(" 123 "))); + } + + /** Displays usage. */ + @Test + public void testUsage() { + Pair pair = run("--help"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + private int countUsage(String output) { + int n = 0; + for (String line : output.split("\n")) { + if (line.contains("Usage")) { + ++n; + } + } + return n; + } + + /** Invalid arguments. */ + @Test + public void testInvalidArguments() { + Pair pair = run("--fuzz"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + /** Result of executing sqlline: status code and output. */ + static class Pair { + final SqlLine.Status status; + final String output; + + Pair(SqlLine.Status status, String output) { + this.status = status; + this.output = output; + } + } + + @Test + public void testIsolationSetting() { + final String script0 = "!isolation TRANSACTION_NONE\n"; + final String expected = "Transaction isolation level TRANSACTION_NONE " + + "is not supported. Default (TRANSACTION_READ_COMMITTED) " + + "will be used instead."; + checkScriptFile(script0, true, equalTo(SqlLine.Status.OTHER), + containsString(expected)); + } + + @Test + public void testDefaultIsolation() { + final String script1 = "!isolation default\n"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + allOf(not(containsString("Transaction isolation level")), + not(containsString("is not supported")))); + } + + /** + * HIVE-4566, "NullPointerException if typeinfo and nativesql commands are + * executed at beeline before a DB connection is established". + */ + @Test + public void testNPE() { + SqlLine sqlLine = new SqlLine(); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + + try { + sqlLine.runCommands(new DispatchCallback(), "!typeinfo"); + String output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + + sqlLine.runCommands(new DispatchCallback(), "!nativesql"); + output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandlerOnStartup() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final String[] args = { + "-e", "!set maxwidth 80", + "-ch", "sqlline.extensions.HelloWorldCommandHandler"}; + begin(sqlLine, os, false, args); + + try { + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!test"); + output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello test")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandler() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + begin(sqlLine, os, false, "-e", "!set maxwidth 80"); + + try { + final String script = "!commandhandler" + + " sqlline.extensions.HelloWorld2CommandHandler" + + " sqlline.extensions.HelloWorldCommandHandler"; + sqlLine.runCommands(new DispatchCallback(), script); + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD2")); + final String expected = "Could not add command handler " + + "sqlline.extensions.HelloWorldCommandHandler as one of commands " + + "[hello, test] is already present"; + assertThat(output, containsString(expected)); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello2")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testTablesCsv() { + final String script = "!set outputformat csv\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("'TABLE_CAT','TABLE_SCHEM','TABLE_NAME',"), + containsString("'PUBLIC','SCOTT','SALGRADE','TABLE','',"))); + } + + /** + * java.lang.NullPointerException test case from + * https://github.com/julianhyde/sqlline/pull/86#issuecomment-410868361 + */ + @Test + public void testCsvDelimiterAndQuoteCharacter() { + final String script = "!set outputformat csv\n" + + "!set csvDelimiter null\n" + + "!set csvQuoteCharacter @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!set csvDelimiter ##\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@null@C2@null@C3@null@C4@null@C5@null@C6@"; + final String line2 = + "@#@null@@@#@@@null@1@null@1969-07-20@null@@null@ 1'2\"3\t4@"; + final String line3 = "@C1@##@C2@##@C3@##@C4@##@C5@##@C6@"; + final String line4 = "@#@##@@@#@@@##@1@##@1969-07-20@##@@##@ 1'2\"3\t4@"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testCsvOneLiner() { + final String script = "!outputformat csv \"'\" @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!outputformat csv & default\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@'@C2@'@C3@'@C4@'@C5@'@C6@"; + final String line2 = + "@#@'@@@#@@@'@1@'@1969-07-20@'@@'@ 1'2\"3\t4@"; + final String line3 = "'C1'&'C2'&'C3'&'C4'&'C5'&'C6'"; + final String line4 = + "'#'&'@#@'&'1'&'1969-07-20'&''&' 1''2\"3\t4'"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testSetForNulls() { + final String script = "!set numberFormat null\n" + + "!set\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("numberFormat null")); + } + + @Test + public void testSetNonIntValuesToIntProperties() { + SqlLine sqlLine = new SqlLine(); + final String headerIntervalScript = "!set headerinterval abc\n"; + checkScriptFile(headerIntervalScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "headerinterval", "abc"))); + + final String rowLimitScript = "!set rowlimit xxx\n"; + checkScriptFile(rowLimitScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "rowlimit", "xxx"))); + } + + @Test + public void testSelectXmlAttributes() { + final String script = "!set outputformat xmlattr\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ']]> 1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString("&4\"/>"))); + } + + @Test + public void testSelectXmlElements() { + final String script = "!set outputformat xmlelements\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' ]]>1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString(""), + containsString("1"), + containsString("-1.5"), + containsString("TRUE"), + containsString("1969-07-20"), + containsString("null"), + containsString(" ]]>1'2\"3\t<>&4"), + containsString(""), + containsString(""))); + } + + @Test + public void testTablesJson() { + final String script = "!set outputformat json\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"TABLE_CAT\":\"PUBLIC\"," + + "\"TABLE_SCHEM\":\"SYSTEM_LOBS\",\"TABLE_NAME\":\"BLOCKS\"," + + "\"TABLE_TYPE\":\"SYSTEM TABLE\",\"REMARKS\":null," + + "\"TYPE_CAT\":null,"))); + } + + @Test + public void testSelectJson() { + final String script = "!set outputformat json\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"C1\":1,\"C2\":-1.5,\"C3\":true," + + "\"C4\":\"1969-07-20\",\"C5\":null," + + "\"C6\":\" 1'2\\\"3\\t4\"}"))); + } + + @Test + public void testNullValue() { + final String script = "!set nullValue %%%\n" + + "!set outputformat csv\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue \"'\"\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue null\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'%%%','-1.5','%%%','1969-07-20','%%%','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'''','-1.5','''','1969-07-20','''','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'null','-1.5','null','1969-07-20','null','null'"))); + } + + @Test + public void testTimeFormat() { + // Use System.err as it is used in sqlline.SqlLineOpts#set + final PrintStream originalErr = System.err; + try { + final ByteArrayOutputStream errBaos = new ByteArrayOutputStream(); + System.setErr( + new PrintStream(errBaos, false, StandardCharsets.UTF_8.name())); + + // successful patterns + final String okTimeFormat = "!set timeFormat HH:mm:ss\n"; + final String defaultTimeFormat = "!set timeFormat default\n"; + final String okDateFormat = "!set dateFormat YYYY-MM-dd\n"; + final String defaultDateFormat = "!set dateFormat default\n"; + final String okTimestampFormat = "!set timestampFormat default\n"; + final String defaultTimestampFormat = "!set timestampFormat default\n"; + + // successful cases + final SqlLine sqlLine = new SqlLine(); + sqlLine.runCommands(new DispatchCallback(), okTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + + // failed patterns + final String wrongTimeFormat = "!set timeFormat qwerty\n"; + final String wrongDateFormat = "!set dateFormat ASD\n"; + final String wrongTimestampFormat = + "!set timestampFormat 'YYYY-MM-ddTHH:MI:ss'\n"; + + // failed cases + sqlLine.runCommands(new DispatchCallback(), wrongTimeFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'q'")); + sqlLine.runCommands(new DispatchCallback(), wrongDateFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'A'")); + sqlLine.runCommands(new DispatchCallback(), wrongTimestampFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'T'")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } finally { + // Set error stream back + System.setErr(originalErr); + } + } + + /** + * Test case for + * [SQLLINE-203] + * !indexes command fails because of Hive bug. + * The bug in question is + * [HIVE-20983] + * HiveResultSetMetaData.getColumnDisplaySize throws for SHORT column. + * + * @param meta Mocked hsqldb {@link JDBCResultSetMetaData} to use in the test + */ + @Test + public void testOutputWithFailingColumnDisplaySize( + @Mocked final JDBCResultSetMetaData meta) { + try { + new Expectations() { + { + meta.getColumnCount(); + result = 3; + + meta.getColumnLabel(1); + result = "TABLE_CAT"; + + meta.getColumnLabel(2); + result = "TABLE_SCHEM"; + + meta.getColumnLabel(3); + result = "TABLE_NAME"; + + meta.getColumnDisplaySize(1); + result = new Exception("getColumnDisplaySize exception"); + } + }; + + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "!set incremental true", + "!set maxwidth 80", + "!set verbose true", + "!indexes"); + assertThat(os.toString("UTF8"), not(containsString("Exception"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests the {@code !connect} command with interactive password submission. + */ + @Test + public void testConnectWithoutPassword() { + new MockUp() { + @Mock + String readPassword(String url) { + return ""; + } + }; + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} property outside of the URL: + * + *

    + * !connect -p PASSWORD_HASH TRUE jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} and {@code ALLOW_LITERALS} properties + * outside of the URL: + * + *
    + * !connect -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE + * jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter2() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!set maxwidth 80"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "select 1;"); + String output = os.toString("UTF8"); + final String expected = "Error:"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing the password in as a hash: + * + *
    + * !connect "jdbc:h2:mem; PASSWORD_HASH=TRUE" sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbProperty() { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + try { + beeLine.runCommands(dc, "!set maxwidth 80"); + + // fail attempt + String fakeNonEmptyPassword = "nonEmptyPasswd"; + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE\" " + + ConnectionSpec.H2.username + + " \"" + fakeNonEmptyPassword + "\""); + String output = os.toString("UTF8"); + final String expected0 = "Error:"; + assertThat(output, containsString(expected0)); + os.reset(); + + // success attempt + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE;ALLOW_LITERALS=NONE\" " + + ConnectionSpec.H2.username + " \"" + + StringUtils.convertBytesToHex(bytes) + + "\""); + beeLine.runCommands(dc, "!set incremental true"); + beeLine.runCommands(dc, "!tables"); + output = os.toString("UTF8"); + final String expected1 = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected1)); + + beeLine.runCommands(dc, "select 5;"); + output = os.toString("UTF8"); + final String expected2 = "Error:"; + assertThat(output, containsString(expected2)); + os.reset(); + + beeLine.runCommands(new DispatchCallback(), "!quit"); + output = os.toString("UTF8"); + assertThat(output, + allOf(not(containsString("Error:")), containsString("!quit"))); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + private static PrintStream getPrintStream(OutputStream os) { + try { + return new PrintStream(os, false, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testReconnect() { + final String script = "!reconnect"; + final String expected = "Reconnecting to \"jdbc:hsqldb:res:scott\"...\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + @Test + public void testTables() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxcolumnwidth 15\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = + "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | |"; + final String line1 = + "| PUBLIC | SYSTEM_LOBS | BLOCKS | SYSTEM TABLE | |"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + @Test + public void testTablesH2() { + connectionSpec = ConnectionSpec.H2; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + /** + * Test case for + * [SQLLINE-107] + * Script fails if the wrong driver is specified with -d option + * and there is a valid registered driver for the specified url. + * + */ + @Test + public void testTablesH2WithErrorDriver() { + connectionSpec = ConnectionSpec.ERROR_H2_DRIVER; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + final String message = "Could not find driver " + + connectionSpec.driver + + "; using registered driver org.h2.Driver instead"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString(message), + not(containsString("NullPointerException")), + containsString(line0), + containsString(line1))); + } + + @Test + public void testH2TablesWithErrorUrl() { + connectionSpec = ConnectionSpec.ERROR_H2_URL; + final String script = "!tables\n"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + CoreMatchers.allOf(containsString("No suitable driver"), + not(containsString("NullPointerException")))); + } + + @Test + public void testEmptyMetadata() { + final String script = "!metadata\n"; + final String line = "Usage: metadata "; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + /** Tests that methods inherited from Object are not included in the list + * of possible metadata methods. */ + @Test + public void testPossibleMetadataValues() { + final String script = "!metadata 1\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString("allProceduresAreCallable"), + containsString("getIndexInfo"), + not(containsString("Exception")), + not(containsString("equals")), + not(containsString("notify")), + not(containsString("wait")), + not(containsString("toString")), + not(containsString("hashCode")), + not(containsString("notifyAll")))); + } + + @Test + public void testMetadataForClassHierarchy() { + final SqlLine beeLine = new SqlLine(); + + new MockUp() { + @Mock + public DatabaseMetaData getMetaData() throws SQLException { + return new CustomDatabaseMetadata( + (JDBCConnection) beeLine.getConnection()); + } + }; + + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.HSQLDB.url + " \"" + + ConnectionSpec.HSQLDB.username + "\" \"" + + ConnectionSpec.HSQLDB.password + "\""); + os.reset(); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + assertThat(output, + allOf(containsString("TABLE_CAT"), + not(containsString("No such method \"getTables\"")))); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testEmptyRecord() { + final String line = "Usage: record "; + checkScriptFile("!record", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyRun() { + final String line = "Usage: run "; + checkScriptFile("!run", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyScript() { + final String line = "Usage: script "; + checkScriptFile("!script", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEscapeSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxColumnWidth 15\n" + + "!set escapeOutput yes\n" + + "values \n" + + "('\n" + + "multiline\n" + + "value') \n" + + ";\n"; + final String line1 = "" + + "+-----------------+\n" + + "| C1 |\n" + + "+-----------------+\n" + + "| \\nmultiline \\nvalue |\n" + + "+-----------------+\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!sql \n" + + "values \n" + + "(1, 2) \n" + + ";\n"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 1 | 2 |\n" + + "+-------------+-------------+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAllMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!all \n" + + "values \n" + + "(1, '2') \n" + + ";\n"; + final String line1 = "" + + "+-------------+----+\n" + + "| C1 | C2 |\n" + + "+-------------+----+\n" + + "| 1 | 2 |\n" + + "+-------------+----+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAppInfoMessage() { + Pair pair = run("-e", "!set maxwidth 80"); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + containsString(Application.DEFAULT_APP_INFO_MESSAGE)); + + String[] args = {"-e", "!set maxwidth 80", "-ac", "INCORRECT_CLASS_NAME"}; + pair = run(args); + assertThat(pair.output, + containsString("Could not initialize INCORRECT_CLASS_NAME")); + assertThat(pair.output, + containsString(CustomApplication.DEFAULT_APP_INFO_MESSAGE)); + + String[] args2 = {"-e", "!set maxwidth 80", + "-ac", "sqlline.extensions.CustomApplication"}; + pair = run(args2); + assertThat(pair.output, + containsString(CustomApplication.CUSTOM_INFO_MESSAGE)); + } + + @Test + public void testCustomOutputFormats() { + // json format was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!set outputformat json\n" + + "values 1;"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("Unknown outputFormat \"json\"")); + } + + @Test + public void testCustomCommands() { + // table command was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Unknown command: tables")); + } + + @Test + public void testAppConfigReset() { + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!appconfig sqlline.Application\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("TABLE_CAT")); + } + + @Test + public void testCustomOpts() { + // nulls are displayed as custom_null + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "values(null)"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("custom_null")); + } + + @Test + public void testScanForEmptyAllowedDrivers() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.emptyList(); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("No driver classes found")); + } + + @Test + public void testScanForOnlyH2Allowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.h2.Driver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 1.4 org.h2.Driver"), + not(containsString("org.hsqldb.jdbc.JDBCDriver")))); + } + + @Test + public void testScanForOnlyHsqldbAllowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.hsqldb.jdbc.JDBCDriver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 2.4 org.hsqldb.jdbc.JDBCDriver"), + not(containsString("org.h2.Driver")))); + } + + @Test + public void testVersion() { + final String script = "!set\n"; + try { + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(new Application().getVersion())); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSetVersion() { + final String script = "!set version test-version\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("version property is read only")); + } + + @Test + public void testSetPropertySuccess() { + final String script = "!set timeout\n" + + "!set timeout 200\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("timeout -1"), + containsString("timeout 200"))); + } + + @Test + public void testSetPropertyFailure() { + final String script = "!set unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testSetUsage() { + final String script = "!set 1 2 3"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: set [all | []]")); + } + + @Test + public void testSetWrongValueToEnumTypeProperties() { + Collection propertiesWithAvailableValues = + Arrays.stream(BuiltInProperty.values()) + .filter(t -> !t.getAvailableValues().isEmpty()) + .collect(Collectors.toSet()); + final String wrongValue = "wrong_value"; + for (BuiltInProperty property: propertiesWithAvailableValues) { + final String script = + "!set " + property.propertyName() + " " + wrongValue + "\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf( + containsString("Unknown " + property.propertyName() + " \"" + + wrongValue + "\""), + not(containsString("Exception")))); + } + } + + @Test + public void testResetSuccess() { + final String script = "!set timeout 200\n" + + "!reset timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("[timeout] was reset to [-1]")); + } + + @Test + public void testResetFailure() { + final String script = "!reset unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testResetAll() { + final String script = "!set timeout 200\n" + + "!reset all\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("All properties were reset to their defaults."), + containsString("timeout -1"))); + } + + @Test + public void testResetUsage() { + final String script = "!reset"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: reset (all | )")); + } + + @Test + public void testRerun() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:!/ 4\n" + + "1536743104551:!/ 5\n" + + "1536743104551:!/ 2\n" + + "1536743104551:!/ 7\n" + + "1536743107526:!history\n" + + "1536743115431:!/ 3\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set incremental true", + "!set maxcolumnwidth 30", + "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + "\"\""); + os.reset(); + + beeLine.runCommands(dc, "!/ 1"); + String output = os.toString("UTF8"); + final String expected0 = "+----------------------------+"; + final String expected1 = "| C1 |"; + final String expected2 = "1 row selected"; + assertThat(output, + allOf(containsString(expected0), + containsString(expected1), + containsString(expected2))); + os.reset(); + + beeLine.runCommands(dc, "!/ 4"); + output = os.toString("UTF8"); + String expectedLine3 = "Cycled rerun of commands from history [2, 4]"; + assertThat(output, containsString(expectedLine3)); + os.reset(); + + beeLine.runCommands(dc, "!/ 3"); + output = os.toString("UTF8"); + String expectedLine4 = "Cycled rerun of commands from history [3, 5, 7]"; + assertThat(output, containsString(expectedLine4)); + os.reset(); + + beeLine.runCommands(dc, "!/ 8"); + output = os.toString("UTF8"); + String expectedLine5 = "Cycled rerun of commands from history [8]"; + assertThat(output, containsString(expectedLine5)); + os.reset(); + + beeLine.runCommands(dc, "!rerun " + Integer.MAX_VALUE); + output = os.toString("UTF8"); + String expectedLine6 = + "Usage: rerun , available range of offset is -7..8"; + assertThat(output, containsString(expectedLine6)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMaxColumnWidthIncremental() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line2 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line3 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testMaxColumnWidthBuffered() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line1 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line2 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line3 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + /** Tests with incrementalBufferRows = -1; query stays in non-incremental + * mode. */ + @Test + public void testIncrementalBufferRows() { + final String script1 = "!set incrementalBufferRows -1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line1 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + /** Tests with incrementalBufferRows = 0; query goes straight into + * incremental mode. */ + @Test + public void testIncrementalBufferRows2() { + final String script2 = "!set incrementalBufferRows 0\n" + + "!set incremental false\n" + + "select * from (values (1, 2), (1, 20), (111, 20), (11, 2222), (1, 22))"; + final String line2 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 1 | 2 |\n" + + "| 1 | 20 |\n" + + "| 111 | 20 |\n" + + "| 11 | 2222 |\n" + + "| 1 | 22 |\n" + + "+----+----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + } + + /** Tests with incrementalBufferRows = 1; query starts in non-incremental mode + * and switches to incremental after 1 row. */ + @Test + public void testIncrementalBufferRows3() { + final String script3 = "!set incrementalBufferRows 1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222), (111, 2222))"; + final String line3 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "| 111 | 2222 |\n" + + "+----+----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + } + + /** Tests with incrementalBufferRows = 4; query starts in non-incremental mode + * and rows run out before the limit is reached. */ + @Test + public void testIncrementalBufferRows4() { + final String script4 = "!set incrementalBufferRows 4\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line4 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testIncrementalBufferRows5() { + // With incrementalBufferRows default (1000), query starts and + // stays in incremental mode. + final String script5 = "!set incrementalBufferRows default\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2))"; + final String line5 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "+----+----+"; + checkScriptFile(script5, true, equalTo(SqlLine.Status.OK), + containsString(line5)); + } + + @Test + public void testMaxHistoryFileRows() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:SELECT \\n 'asd' as \"sdf\", 4 \\n \\n as \\n c2;\\n\n" + + "1536743104551:SELECT \\n 'asd' \\n as \\n c2;\\n\n" + + "1536743104551:!/ 2\n" + + "1536743104551:SELECT \\n 2123 \\n as \\n c2 from dual;\\n\n" + + "1536743107526:!history\n" + + "1536743115431:SELECT \\n 2 \\n as \\n c2;\n" + + "1536743115431:SELECT \\n '213' \\n as \\n c1;\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + bw.close(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + final int maxLines = 3; + beeLine.runCommands(dc, "!set maxHistoryFileRows " + maxLines); + os.reset(); + beeLine.runCommands(dc, "!history"); + assertEquals(maxLines + 1, + os.toString("UTF8").split("\\s+\\d{2}:\\d{2}:\\d{2}\\s+").length); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSave() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + SqlLine.Status status = begin(beeLine, os, false, + "-e", "!save"); + assertThat(status, equalTo(SqlLine.Status.OK)); + final DispatchCallback dc = new DispatchCallback(); + + assertThat(os.toString("UTF8"), + containsString("Saving preferences to")); + os.reset(); + beeLine.runCommands(dc, "!set"); + assertThat(os.toString("UTF8"), + allOf(containsString("autoCommit"), + not(containsString("Unknown property:")))); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScript() { + final File file = createTempFile("sqlline", ".script"); + final String script = "!script " + file.getAbsolutePath() + "\n" + + "values (100, 200);\n" + + "!set maxcolumnwidth -1\n" + + "!script\n" + + "values (1, 2);\n"; + final String expected = "(?s)1/5 !script.*" + + "2/5 values \\(100, 200\\);.*" + + "3/5 !set maxcolumnwidth -1.*" + + "4/5 !script.*" + + "5/5 values \\(1, 2\\);.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + + final String output = "values \\(100, 200\\);\n" + + "!set maxcolumnwidth -1\n"; + assertFileContains(file, RegexMatcher.of(output)); + } + + @Test + public void testStartupArgsWithoutUrl() { + try { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests setting the "confirm" property. + */ + @Test + public void testConfirmFlag() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + begin(line, os, false, "-e", "!set confirm true"); + assertThat(line.getOpts().getConfirm(), is(true)); + begin(line, os, false, "-e", "!set confirm false"); + assertThat(line.getOpts().getConfirm(), is(false)); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests that the "confirm" property works. + */ + @Test + public void testConfirmFlagEffects() { + new MockUp() { + @Mock + int getUserAnswer(String question, int... allowedAnswers) { + return 'n'; + } + }; + + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + assertThat(line.getOpts().getConfirmPattern(), is("default")); + String script = "CREATE TABLE dummy_test(pk int);\n" + + "INSERT INTO dummy_test(pk) VALUES(1);\n" + + "INSERT INTO dummy_test(pk) VALUES(2);\n" + + "INSERT INTO dummy_test(pk) VALUES(3);\n" + + "DELETE FROM dummy_test;\n" + + "DROP TABLE dummy_test;\n"; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OK), + containsString(" ")); + + script = "!set confirm true\n" + script; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OTHER), + containsString(line.loc("abort-action"))); + } + + /** + * Tests that the "confirmPattern" property works. + */ + @Test + public void testConfirmPattern() { + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i:(TRUNCATE|ALTER))\""); + assertThat(line.getOpts().getConfirmPattern(), + is("^(?i:(TRUNCATE|ALTER))")); + + begin(line, os, false, "-e", "!set confirmPattern default"); + assertThat(line.getOpts().getConfirmPattern(), + is(line.loc("default-confirm-pattern"))); + } + + /** + * Test for illegal regex in confirmPattern + */ + @Test + public void testExceptionConfirmPattern() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + SqlLine.Status status = + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i*:(TRUNCATE|ALTER))\""); + assertThat(status, equalTo(SqlLine.Status.OK)); + assertThat(os.toString("UTF8"), containsString("invalid regex")); + os.reset(); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** Information necessary to create a JDBC connection. Specify one to run + * tests against a different database. (hsqldb is the default.) */ + public static class ConnectionSpec { + public final String url; + public final String username; + public final String password; + public final String driver; + + public ConnectionSpec(String url, String username, String password, + String driver) { + this.url = url; + this.username = username; + this.password = password; + this.driver = driver; + } + + public static final ConnectionSpec H2 = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec ERROR_H2_DRIVER = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "ERROR_DRIVER"); + + public static final ConnectionSpec ERROR_H2_URL = + new ConnectionSpec("ERROR_URL", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec HSQLDB = + new ConnectionSpec( + ScottHsqldb.URI, ScottHsqldb.USER, ScottHsqldb.PASSWORD, + "org.hsqldb.jdbcDriver"); + + public static final ConnectionSpec MYSQL = + new ConnectionSpec( + "jdbc:mysql://localhost/scott", "scott", "tiger", + "com.mysql.jdbc.Driver"); + } + + /** Regular expression matcher. */ + private static class RegexMatcher extends BaseMatcher { + private final String pattern; + + RegexMatcher(String pattern) { + super(); + this.pattern = pattern; + } + + public static RegexMatcher of(String pattern) { + return new RegexMatcher(pattern); + } + + public boolean matches(Object o) { + return o instanceof String + && ((String) o).matches(pattern); + } + + public void describeTo(Description description) { + description.appendText("regular expression ").appendText(pattern); + } + } + +} + +// End SqlLineArgsTest.java + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PrintStream` acquired by call to `setOutputStream(...)` at line 906 is not released after line 921. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SqlLineArgsTest.testExecutionWithNotSupportedMethods(JDBCDatabaseMetaData) + +### Procedure Id: +sqlline.SqlLineArgsTest.testExecutionWithNotSupportedMethods(org.hsqldb.jdbc.JDBCDatabaseMetaData):v.d8ee33fd10ab47c0dc99be993b0d5bc9 + +### File: +src/test/java/sqlline/SqlLineArgsTest.java + +### Key: +SqlLineArgsTest.java|testExecutionWithNotSupportedMethods|RESOURCE_LEAK + +### Node Key: +70f946c9a4a9a409d83d6bea92c8d347 + +### Hash: +62f8cc6a4fcf7d62b44c921de13d20ec + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8101/instruction.md b/inferredbugs-8101/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4ac2b883f1bcfb037dd7fa242e820b8cf6d6e734 --- /dev/null +++ b/inferredbugs-8101/instruction.md @@ -0,0 +1,5596 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sqlline +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2002,2003,2004,2005 Marc Prud'hommeaux + * Copyright (c) 2004-2010 The Eigenbase Project + * All rights reserved. + * + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted provided + * that the following conditions are met: + * + * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the following + * disclaimer. + * 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. + * Neither the name of the nor the names + * of its contributors may be used to endorse or promote + * products derived from this software without specific + * prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS + * 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 COPYRIGHT + * OWNER 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. + * + * This software is hosted by SourceForge. + * SourceForge is a trademark of VA Linux Systems, Inc. + */ +package sqlline; + +import java.io.*; + +import java.lang.reflect.*; + +import java.net.*; + +import java.sql.*; + +import java.text.*; + +import java.util.*; +import java.util.jar.*; +import java.util.zip.*; + +import jline.*; + + +/** + * A console SQL shell with command completion. + * + *

    TODO: + * + *

      + *
    • User-friendly connection prompts
    • + *
    • Page results
    • + *
    • Handle binary data (blob fields)
    • + *
    • Implement command aliases
    • + *
    • Stored procedure execution
    • + *
    • Binding parameters to prepared statements
    • + *
    • Scripting language
    • + *
    • XA transactions
    • + *
    + * + * @author Marc Prud'hommeaux + */ +public class SqlLine +{ + //~ Static fields/initializers --------------------------------------------- + + private static final ResourceBundle loc = + ResourceBundle.getBundle( + SqlLine.class.getName()); + + private static final String sep = System.getProperty("line.separator"); + public static final String COMMAND_PREFIX = "!"; + + private static final Object[] EMPTY_OBJ_ARRAY = new Object[0]; + + static final SortedSet KNOWN_DRIVERS = + new TreeSet( + Arrays.asList( + new String[] { + "com.merant.datadirect.jdbc.sqlserver.SQLServerDriver", + "com.microsoft.jdbc.sqlserver.SQLServerDriver", + "com.ddtek.jdbc.informix.InformixDriver", + "org.sourceforge.jxdbcon.JXDBConDriver", + "com.ddtek.jdbc.oracle.OracleDriver", + "net.sourceforge.jtds.jdbc.Driver", + "com.pointbase.jdbc.jdbcDriver", + "com.internetcds.jdbc.tds.SybaseDriver", + "org.enhydra.instantdb.jdbc.idbDriver", + "com.sybase.jdbc2.jdbc.SybDriver", + "com.ddtek.jdbc.sybase.SybaseDriver", + "COM.cloudscape.core.JDBCDriver", + "in.co.daffodil.db.jdbc.DaffodilDBDriver", + "com.jnetdirect.jsql.JSQLDriver", + "com.lucidera.jdbc.LucidDbRmiDriver", + "COM.ibm.db2.jdbc.net.DB2Driver", + "org.hsqldb.jdbcDriver", + "com.pointbase.jdbc.jdbcUniversalDriver", + "com.ddtek.jdbc.sqlserver.SQLServerDriver", + "com.ddtek.jdbc.db2.DB2Driver", + "com.merant.datadirect.jdbc.oracle.OracleDriver", + "oracle.jdbc.OracleDriver", + "com.informix.jdbc.IfxDriver", + "com.merant.datadirect.jdbc.informix.InformixDriver", + "com.ibm.db2.jcc.DB2Driver", + "com.pointbase.jdbc.jdbcEmbeddedDriver", + "org.gjt.mm.mysql.Driver", + "org.postgresql.Driver", + "com.mysql.jdbc.Driver", + "oracle.jdbc.driver.OracleDriver", + "interbase.interclient.Driver", + "com.mysql.jdbc.NonRegisteringDriver", + "com.merant.datadirect.jdbc.db2.DB2Driver", + "com.merant.datadirect.jdbc.sybase.SybaseDriver", + "com.internetcds.jdbc.tds.Driver", + "org.hsqldb.jdbcDriver", + "org.hsql.jdbcDriver", + "COM.cloudscape.core.JDBCDriver", + "in.co.daffodil.db.jdbc.DaffodilDBDriver", + "com.ddtek.jdbc.db2.DB2Driver", + "interbase.interclient.Driver", + "com.mysql.jdbc.Driver", + "com.ddtek.jdbc.oracle.OracleDriver", + "org.postgresql.Driver", + "com.pointbase.jdbc.jdbcUniversalDriver", + "org.sourceforge.jxdbcon.JXDBConDriver", + "com.ddtek.jdbc.sqlserver.SQLServerDriver", + "com.jnetdirect.jsql.JSQLDriver", + "com.microsoft.jdbc.sqlserver.SQLServerDriver", + "weblogic.jdbc.mssqlserver4.Driver", + "com.ddtek.jdbc.sybase.SybaseDriver", + "oracle.jdbc.pool.OracleDataSource", + "org.axiondb.jdbc.AxionDriver", + "COM.ibm.db2.jdbc.app.DB2Driver", + "com.ibm.as400.access.AS400JDBCDriver", + "COM.FirstSQL.Dbcp.DbcpDriver", + "COM.ibm.db2.jdbc.net.DB2Driver", + "org.enhydra.instantdb.jdbc.idbDriver", + "com.informix.jdbc.IfxDriver", + "com.microsoft.jdbc.sqlserver.SQLServerDriver", + "com.imaginary.sql.msql.MsqlDriver", + "sun.jdbc.odbc.JdbcOdbcDriver", + "oracle.jdbc.driver.OracleDriver", + "intersolv.jdbc.sequelink.SequeLinkDriver", + "openlink.jdbc2.Driver", + "com.pointbase.jdbc.jdbcUniversalDriver", + "postgres95.PGDriver", + "postgresql.Driver", + "solid.jdbc.SolidDriver", + "centura.java.sqlbase.SqlbaseDriver", + "interbase.interclient.Driver", + "com.mckoi.JDBCDriver", + "com.inet.tds.TdsDriver", + "com.microsoft.jdbc.sqlserver.SQLServerDriver", + "com.thinweb.tds.Driver", + "weblogic.jdbc.mssqlserver4.Driver", + "com.mysql.jdbc.DatabaseMetaData", + "org.gjt.mm.mysql.Driver", + "com.sap.dbtech.jdbc.DriverSapDB", + "com.sybase.jdbc2.jdbc.SybDriver", + "com.sybase.jdbc.SybDriver", + "com.internetcds.jdbc.tds.Driver", + "weblogic.jdbc.pool.Driver", + "com.sqlstream.jdbc.Driver", + "org.luciddb.jdbc.LucidDbClientDriver", + })); + + static { + Class jline; + + try { + jline = Class.forName("jline.ConsoleReader"); + } catch (Throwable t) { + throw new ExceptionInInitializerError(loc("jline-missing")); + } + } + + //~ Instance fields -------------------------------------------------------- + + private SqlLineSignalHandler signalHandler = null; + private boolean exit = false; + private final SqlLine sqlline = this; + private Collection drivers = null; + private Connections connections = new Connections(); + private Completor sqlLineCommandCompletor; + private Map completions = new HashMap(); + private Opts opts = new Opts(System.getProperties()); + String lastProgress = null; + String prompt = "sqlline"; + private Map seenWarnings = new HashMap(); + private final Commands command = new Commands(); + private OutputFile script = null; + private OutputFile record = null; + private ConsoleReader reader; + private List batch = null; + + private final Map formats = + map( + new Object[] { + "vertical", new VerticalOutputFormat(), + "table", new TableOutputFormat(), + "csv", new SeparatedValuesOutputFormat(','), + "tsv", new SeparatedValuesOutputFormat('\t'), + "xmlattr", new XMLAttributeOutputFormat(), + "xmlelements", new XMLElementOutputFormat(), + }); + + private CommandHandler [] commands = + new CommandHandler[] { + new ReflectiveCommandHandler( + new String[] { "quit", "done", "exit" }, + null), + new ReflectiveCommandHandler( + new String[] { "connect", "open" }, + new Completor[] { + new SimpleCompletor(getConnectionURLExamples()) + }), + new ReflectiveCommandHandler( + new String[] { "describe" }, + new Completor[] { new TableNameCompletor() }), + new ReflectiveCommandHandler( + new String[] { "indexes" }, + new Completor[] { new TableNameCompletor() }), + new ReflectiveCommandHandler( + new String[] { "primarykeys" }, + new Completor[] { new TableNameCompletor() }), + new ReflectiveCommandHandler( + new String[] { "exportedkeys" }, + new Completor[] { new TableNameCompletor() }), + new ReflectiveCommandHandler(new String[] { "manual" }, + null), + new ReflectiveCommandHandler( + new String[] { "importedkeys" }, + new Completor[] { new TableNameCompletor() }), + new ReflectiveCommandHandler(new String[] { "procedures" }, + null), + new ReflectiveCommandHandler(new String[] { "tables" }, + null), + new ReflectiveCommandHandler(new String[] { "typeinfo" }, + null), + new ReflectiveCommandHandler( + new String[] { "columns" }, + new Completor[] { new TableNameCompletor() }), + new ReflectiveCommandHandler(new String[] { "reconnect" }, + null), + new ReflectiveCommandHandler( + new String[] { "dropall" }, + new Completor[] { new TableNameCompletor() }), + new ReflectiveCommandHandler(new String[] { "history" }, + null), + new ReflectiveCommandHandler( + new String[] { "metadata" }, + new Completor[] { + new SimpleCompletor(getMetadataMethodNames()) + }), + new ReflectiveCommandHandler(new String[] { "nativesql" }, + null), + new ReflectiveCommandHandler(new String[] { "dbinfo" }, + null), + new ReflectiveCommandHandler(new String[] { "rehash" }, + null), + new ReflectiveCommandHandler(new String[] { "verbose" }, + null), + new ReflectiveCommandHandler( + new String[] { "run" }, + new Completor[] { new FileNameCompletor() }), + new ReflectiveCommandHandler(new String[] { "batch" }, + null), + new ReflectiveCommandHandler(new String[] { "list" }, + null), + new ReflectiveCommandHandler(new String[] { "all" }, + null), + new ReflectiveCommandHandler(new String[] { "go", "#" }, + null), + new ReflectiveCommandHandler( + new String[] { "script" }, + new Completor[] { new FileNameCompletor() }), + new ReflectiveCommandHandler( + new String[] { "record" }, + new Completor[] { new FileNameCompletor() }), + new ReflectiveCommandHandler(new String[] { "brief" }, + null), + new ReflectiveCommandHandler(new String[] { "close" }, + null), + new ReflectiveCommandHandler(new String[] { "closeall" }, + null), + new ReflectiveCommandHandler( + new String[] { "isolation" }, + new Completor[] { new SimpleCompletor(getIsolationLevels()) }), + new ReflectiveCommandHandler( + new String[] { "outputformat" }, + new Completor[] { + new SimpleCompletor( + (String []) formats.keySet().toArray(new String[0])) + }), + new ReflectiveCommandHandler(new String[] { "autocommit" }, + null), + new ReflectiveCommandHandler(new String[] { "commit" }, + null), + new ReflectiveCommandHandler( + new String[] { "properties" }, + new Completor[] { new FileNameCompletor() }), + new ReflectiveCommandHandler(new String[] { "rollback" }, + null), + new ReflectiveCommandHandler(new String[] { "help", "?" }, + null), + new ReflectiveCommandHandler( + new String[] { "set" }, + opts.optionCompletors()), + new ReflectiveCommandHandler(new String[] { "save" }, + null), + new ReflectiveCommandHandler(new String[] { "scan" }, + null), + new ReflectiveCommandHandler(new String[] { "sql" }, + null), + new ReflectiveCommandHandler(new String[] { "call" }, + null), + }; + + //~ Constructors ----------------------------------------------------------- + + SqlLine() + { + // registerKnownDrivers (); + + sqlLineCommandCompletor = new SQLLineCommandCompletor(); + + // attempt to dynamically load signal handler + try { + Class handlerClass = Class.forName("sqlline.SunSignalHandler"); + signalHandler = (SqlLineSignalHandler) handlerClass.newInstance(); + } catch (Throwable t) { + // ignore and leave cancel functionality disabled + } + } + + //~ Methods ---------------------------------------------------------------- + + static Manifest getManifest() + throws IOException + { + URL base = SqlLine.class.getResource("/META-INF/MANIFEST.MF"); + URLConnection c = base.openConnection(); + if (c instanceof JarURLConnection) { + return ((JarURLConnection) c).getManifest(); + } + + return null; + } + + static String getManifestAttribute(String name) + { + try { + Manifest m = getManifest(); + if (m == null) { + return "??"; + } + + Attributes attrs = m.getAttributes("sqlline"); + if (attrs == null) { + return "???"; + } + + String val = attrs.getValue(name); + if ((val == null) || "".equals(val)) { + return "????"; + } + + return val; + } catch (Exception e) { + e.printStackTrace(); + return "?????"; + } + } + + static String getApplicationTitle() + { + Package pack = SqlLine.class.getPackage(); + + return loc( + "app-introduction", + new Object[] { + (pack.getImplementationTitle() == null) ? "sqlline" + : pack.getImplementationTitle(), + (pack.getImplementationVersion() == null) ? "???" + : pack.getImplementationVersion(), + (pack.getImplementationVendor() == null) ? "Marc Prud'hommeaux" + : pack.getImplementationVendor(), + }); + } + + static String getApplicationContactInformation() + { + return getManifestAttribute("Implementation-Vendor"); + } + + static String loc(String res) + { + return loc(res, EMPTY_OBJ_ARRAY); + } + + static String loc(String res, int param) + { + try { + return MessageFormat.format( + new ChoiceFormat(loc.getString(res)).format(param), + new Object[] { new Integer(param) }); + } catch (Exception e) { + return res + ": " + param; + } + } + + static String loc(String res, Object param1) + { + return loc(res, new Object[] { param1 }); + } + + static String loc(String res, Object param1, Object param2) + { + return loc(res, new Object[] { param1, param2 }); + } + + static String loc(String res, Object [] params) + { + try { + return MessageFormat.format(loc.getString(res), params); + } catch (Exception e) { + e.printStackTrace(); + + try { + return res + ": " + Arrays.asList(params); + } catch (Exception e2) { + return res; + } + } + } + + /** + * Starts the program. + */ + public static void main(String [] args) + throws IOException + { + mainWithInputRedirection(args, null); + } + + /** + * Starts the program with redirected input. For redirected output, + * System.setOut and System.setErr can be used, but System.setIn will not + * work. + * + * @param args same as main() + * @param inputStream redirected input, or null to use standard input + */ + public static void mainWithInputRedirection( + String [] args, + InputStream inputStream) + throws IOException + { + SqlLine sqlline = new SqlLine(); + sqlline.begin(args, inputStream); + + // exit the system: useful for Hypersonic and other + // badly-behaving systems + if (!Boolean.getBoolean(Opts.PROPERTY_NAME_EXIT)) { + System.exit(0); + } + } + + DatabaseConnection con() + { + return connections.current(); + } + + Connection conn() + { + if (connections.current() == null) { + throw new IllegalArgumentException(loc("no-current-connection")); + } + if (connections.current().connection == null) { + throw new IllegalArgumentException(loc("no-current-connection")); + } + return connections.current().connection; + } + + DatabaseMetaData meta() + { + if (connections.current() == null) { + throw new IllegalArgumentException(loc("no-current-connection")); + } + if (connections.current().meta == null) { + throw new IllegalArgumentException(loc("no-current-connection")); + } + return connections.current().meta; + } + + public String [] getIsolationLevels() + { + return new String[] { + "TRANSACTION_NONE", + "TRANSACTION_READ_COMMITTED", + "TRANSACTION_READ_UNCOMMITTED", + "TRANSACTION_REPEATABLE_READ", + "TRANSACTION_SERIALIZABLE", + }; + } + + public String [] getMetadataMethodNames() + { + try { + TreeSet mnames = new TreeSet(); + Method [] m = DatabaseMetaData.class.getDeclaredMethods(); + for (int i = 0; (m != null) && (i < m.length); i++) { + mnames.add(m[i].getName()); + } + + return (String []) mnames.toArray(new String[0]); + } catch (Throwable t) { + return new String[0]; + } + } + + public String [] getConnectionURLExamples() + { + return new String[] { + "jdbc:JSQLConnect:///database=", + "jdbc:cloudscape:;create=true", + "jdbc:twtds:sqlserver:///", + "jdbc:daffodilDB_embedded:;create=true", + "jdbc:datadirect:db2://:50000;databaseName=", + "jdbc:inetdae::1433", + "jdbc:datadirect:oracle://:1521;SID=;" + + "MaxPooledStatements=0", + "jdbc:datadirect:sqlserver://:1433;SelectMethod=cursor;" + + "DatabaseName=", + "jdbc:datadirect:sybase://:5000", + "jdbc:db2:///", + "jdbc:hsqldb:", + "jdbc:idb:.properties", + "jdbc:informix-sqli://:1526/:INFORMIXSERVER" + + "=", + "jdbc:interbase:////.gdb", + "jdbc:luciddb:http://", + "jdbc:microsoft:sqlserver://:1433;" + + "DatabaseName=;SelectMethod=cursor", + "jdbc:mysql:///?autoReconnect=true", + "jdbc:oracle:thin:@:1521:", + "jdbc:pointbase:,database.home=,create=true", + "jdbc:postgresql://:5432/", + "jdbc:postgresql:net///", + "jdbc:sybase:Tds::4100/?ServiceName=", + "jdbc:weblogic:mssqlserver4:@:1433", + "jdbc:odbc:", + "jdbc:sequelink://:4003/[Oracle]", + "jdbc:sequelink://:4004/[Informix];Database=", + "jdbc:sequelink://:4005/[Sybase];Database=", + "jdbc:sequelink://:4006/[SQLServer];Database=", + "jdbc:sequelink://:4011/[ODBC MS Access];" + + "Database=", + "jdbc:openlink:///DSN=SQLServerDB/UID=sa/PWD=", + "jdbc:solid://://", + "jdbc:dbaw://:8889/", + }; + } + + /** + * Entry point to creating a {@link ColorBuffer} with color enabled or + * disabled depending on the calue of {@link Opts#getColor}. + */ + ColorBuffer color() + { + return new ColorBuffer(opts.getColor()); + } + + /** + * Entry point to creating a {@link ColorBuffer} with color enabled or + * disabled depending on the calue of {@link Opts#getColor}. + */ + ColorBuffer color(String msg) + { + return new ColorBuffer(msg, opts.getColor()); + } + + /** + * Walk through all the known drivers and try to register them. + */ + void registerKnownDrivers() + { + for (Iterator i = KNOWN_DRIVERS.iterator(); i.hasNext();) { + try { + Class.forName(i.next().toString()); + } catch (Throwable t) { + } + } + } + + boolean initArgs(String [] args) + { + List commands = new LinkedList(); + List files = new LinkedList(); + String driver = null, user = null, pass = null, url = null, cmd = null; + + for (int i = 0; i < args.length; i++) { + if (args[i].equals("--help") || args[i].equals("-h")) { + usage(); + return false; + } + + // -- arguments are treated as properties + if (args[i].startsWith("--")) { + String [] parts = split(args[i].substring(2), "="); + debug(loc("setting-prop", Arrays.asList(parts))); + if (parts.length > 0) { + boolean ret; + + if (parts.length >= 2) { + ret = opts.set(parts[0], parts[1], true); + } else { + ret = opts.set(parts[0], "true", true); + } + + if (!ret) { + return false; + } + } + + continue; + } + + if (args[i].equals("-d")) { + driver = args[i++ + 1]; + } else if (args[i].equals("-n")) { + user = args[i++ + 1]; + } else if (args[i].equals("-p")) { + pass = args[i++ + 1]; + } else if (args[i].equals("-u")) { + url = args[i++ + 1]; + } else if (args[i].equals("-e")) { + commands.add(args[i++ + 1]); + } else { + files.add(args[i]); + } + } + + if (url != null) { + String com = + "!connect " + + url + " " + + (((user == null) || (user.length() == 0)) ? "''" : user) + " " + + (((pass == null) || (pass.length() == 0)) ? "''" : pass) + " " + + ((driver == null) ? "" : driver); + debug("issuing: " + com); + dispatch(com); + } + + // now load properties files + for (Iterator i = files.iterator(); i.hasNext();) { + dispatch("!properties " + i.next()); + } + + if (commands.size() > 0) { + // for single commane execute, disable color + opts.setColor(false); + opts.setHeaderInterval(-1); + + for (Iterator i = commands.iterator(); i.hasNext();) { + String command = i.next().toString(); + debug(loc("executing-command", command)); + dispatch(command); + } + + exit = true; // execute and exit + } + + // if a script file was specified, run the file and quit + if (opts.getRun() != null) { + dispatch("!run " + opts.getRun()); + dispatch("!quit"); + } + + return true; + } + + /** + * Start accepting input from stdin, and dispatch it to the appropriate + * {@link CommandHandler} until the global variable exit is + * true. + */ + void begin(String [] args, InputStream inputStream) + throws IOException + { + try { + // load the options first, so we can override on the command line + opts.load(); + } catch (Exception e) { + } + + ConsoleReader reader = getConsoleReader(inputStream); + if (!(initArgs(args))) { + usage(); + return; + } + + try { + info(getApplicationTitle()); + } catch (Exception e) { + } + + while (!exit) { + try { + dispatch(reader.readLine(getPrompt())); + } catch (EOFException eof) { + // CTRL-D + command.quit(null); + } catch (Throwable t) { + handleException(t); + } + } + + // ### NOTE jvs 10-Aug-2004: Clean up any outstanding + // connections automatically. + command.closeall(null); + } + + public ConsoleReader getConsoleReader(InputStream inputStream) + throws IOException + { + Terminal terminal = Terminal.setupTerminal(); + + if (inputStream != null) { + // ### NOTE: fix for sf.net bug 879425. + reader = + new ConsoleReader( + inputStream, + new PrintWriter(System.out)); + } else { + reader = new ConsoleReader(); + } + + // setup history + ByteArrayInputStream historyBuffer = null; + + if (new File(opts.getHistoryFile()).isFile()) { + try { + // save the current contents of the history buffer. This gets + // around a bug in JLine where setting the output before the + // input will clobber the history input, but setting the + // input before the output will cause the previous commands + // to not be saved to the buffer. + FileInputStream historyIn = + new FileInputStream( + opts.getHistoryFile()); + ByteArrayOutputStream hist = new ByteArrayOutputStream(); + int n; + while ((n = historyIn.read()) != -1) { + hist.write(n); + } + historyIn.close(); + + historyBuffer = new ByteArrayInputStream(hist.toByteArray()); + } catch (Exception e) { + handleException(e); + } + } + + try { + // now set the output for the history + PrintWriter historyOut = + new PrintWriter(new FileWriter( + opts.getHistoryFile())); + reader.getHistory().setOutput(historyOut); + } catch (Exception e) { + handleException(e); + } + + try { + // now load in the previous history + if (historyBuffer != null) { + reader.getHistory().load(historyBuffer); + } + } catch (Exception e) { + handleException(e); + } + + reader.addCompletor(new SQLLineCompletor()); + + return reader; + } + + void usage() + { + output(loc("cmd-usage")); + } + + /** + * Dispatch the specified line to the appropriate {@link CommandHandler}. + * + * @param line the commmand-line to dispatch + * + * @return true if the command was "successful" + */ + boolean dispatch(String line) + { + if (line == null) { + // exit + exit = true; + return true; + } + + if (line.trim().length() == 0) { + return true; + } + + if (isComment(line)) { + return true; + } + + line = line.trim(); + + // save it to the current script, if any + if (script != null) { + script.addLine(line); + } + + if (isHelpRequest(line)) { + line = "!help"; + } + + if (line.startsWith(COMMAND_PREFIX)) { + Map cmdMap = new TreeMap(); + line = line.substring(1); + for (int i = 0; i < commands.length; i++) { + String match = commands[i].matches(line); + if (match != null) { + cmdMap.put(match, commands[i]); + } + } + + if (cmdMap.size() == 0) { + return error(loc("unknown-command", line)); + } else if (cmdMap.size() > 1) { + return error( + loc("multiple-matches", + cmdMap.keySet().toString())); + } else { + return ((CommandHandler) cmdMap.values().iterator().next()) + .execute(line); + } + } else { + return command.sql(line); + } + } + + /** + * Test whether a line requires a continuation. + * + * @param line the line to be tested + * + * @return true if continuation required + */ + boolean needsContinuation(String line) + { + if (isHelpRequest(line)) { + return false; + } + + if (line.startsWith(COMMAND_PREFIX)) { + return false; + } + + if (isComment(line)) { + return false; + } + + String trimmed = line.trim(); + + if (trimmed.length() == 0) { + return false; + } + + return !trimmed.endsWith(";"); + } + + /** + * Test whether a line is a help request other than !help. + * + * @param line the line to be tested + * + * @return true if a help request + */ + boolean isHelpRequest(String line) + { + return line.equals("?") || line.equalsIgnoreCase("help"); + } + + /** + * Test whether a line is a comment. + * + * @param line the line to be tested + * + * @return true if a comment + */ + boolean isComment(String line) + { + // SQL92 comment prefix is "--" + // sqlline also supports shell-style "#" prefix + return line.startsWith("#") || line.startsWith("--"); + } + + /** + * Print the specified message to the console + * + * @param msg the message to print + */ + void output(String msg) + { + output(msg, true); + } + + void info(String msg) + { + if (!(opts.getSilent())) { + output(msg, true, System.err); + } + } + + void info(ColorBuffer msg) + { + if (!(opts.getSilent())) { + output(msg, true, System.err); + } + } + + /** + * Issue the specified error message + * + * @param msg the message to issue + * + * @return false always + */ + boolean error(String msg) + { + output(color().red(msg), true, System.err); + return false; + } + + boolean error(Throwable t) + { + handleException(t); + return false; + } + + void debug(String msg) + { + if (opts.getVerbose()) { + output(color().blue(msg), true, System.err); + } + } + + void output(ColorBuffer msg) + { + output(msg, true); + } + + void output(String msg, boolean newline, PrintStream out) + { + output(color(msg), newline, out); + } + + void output(ColorBuffer msg, boolean newline) + { + output(msg, newline, System.out); + } + + void output(ColorBuffer msg, boolean newline, PrintStream out) + { + if (newline) { + out.println(msg.getColor()); + } else { + out.print(msg.getColor()); + } + + if (record == null) { + return; + } + + // only write to the record file if we are writing a line ... + // otherwise we might get garbage from backspaces and such. + if (newline) { + record.addLine(msg.getMono()); // always just write mono + } + } + + /** + * Print the specified message to the console + * + * @param msg the message to print + * @param newline if false, do not append a newline + */ + void output(String msg, boolean newline) + { + output(color(msg), newline); + } + + void autocommitStatus(Connection c) + throws SQLException + { + info(loc("autocommit-status", c.getAutoCommit() + "")); + } + + /** + * Ensure that autocommit is on for the current connection + * + * @return true if autocommit is set + */ + boolean assertAutoCommit() + { + if (!(assertConnection())) { + return false; + } + + try { + if (con().connection.getAutoCommit()) { + return error(loc("autocommit-needs-off")); + } + } catch (Exception e) { + return error(e); + } + + return true; + } + + /** + * Assert that we have an active, living connection. Print an error message + * if we do not. + * + * @return true if there is a current, active connection + */ + boolean assertConnection() + { + try { + if ((con() == null) || (con().connection == null)) { + return error(loc("no-current-connection")); + } + + if (con().connection.isClosed()) { + return error(loc("connection-is-closed")); + } + } catch (SQLException sqle) { + return error(loc("no-current-connection")); + } + + return true; + } + + /** + * Print out any warnings that exist for the current connection. + */ + void showWarnings() + { + if (con().connection == null) { + return; + } + + if (!opts.getShowWarnings()) { + return; + } + + try { + showWarnings(con().connection.getWarnings()); + } catch (Exception e) { + handleException(e); + } + } + + /** + * Print the specified warning on the console, as well as any warnings that + * are returned from {@link SQLWarning#getNextWarning}. + * + * @param warn the {@link SQLWarning} to print + */ + void showWarnings(SQLWarning warn) + { + if (warn == null) { + return; + } + + if (seenWarnings.get(warn) == null) { + // don't re-display warnings we have already seen + seenWarnings.put(warn, new java.util.Date()); + handleSQLException(warn); + } + + SQLWarning next = warn.getNextWarning(); + if (next != warn) { + showWarnings(next); + } + } + + String getPrompt() + { + if ((con() == null) || (con().url == null)) { + return "sqlline> "; + } else { + return getPrompt(connections.getIndex() + + ": " + con().url) + "> "; + } + } + + static String getPrompt(String url) + { + if ((url == null) || (url.length() == 0)) { + url = "sqlline"; + } + + if (url.indexOf(";") > -1) { + url = url.substring(0, url.indexOf(";")); + } + if (url.indexOf("?") > -1) { + url = url.substring(0, url.indexOf("?")); + } + + if (url.length() > 45) { + url = url.substring(0, 45); + } + + return url; + } + + /** + * Try to obtain the current size of the specified {@link ResultSet} by + * jumping to the last row and getting the row number. + * + * @param rs the {@link ResultSet} to get the size for + * + * @return the size, or -1 if it could not be obtained + */ + int getSize(ResultSet rs) + { + try { + if (rs.getType() == rs.TYPE_FORWARD_ONLY) { + return -1; + } + + rs.last(); + int total = rs.getRow(); + rs.beforeFirst(); + return total; + } catch (SQLException sqle) { + return -1; + } + // JDBC 1 driver error + catch (AbstractMethodError ame) { + return -1; + } + } + + ResultSet getColumns(String table) + throws SQLException + { + if (!(assertConnection())) { + return null; + } + + return con().meta.getColumns( + con().meta.getConnection().getCatalog(), + null, + table, + "%"); + } + + ResultSet getTables() + throws SQLException + { + if (!(assertConnection())) { + return null; + } + + return con().meta.getTables( + con().meta.getConnection().getCatalog(), + null, + "%", + new String[] { "TABLE" }); + } + + String [] getColumnNames(DatabaseMetaData meta) + throws SQLException + { + Set names = new HashSet(); + + info(loc("building-tables")); + + try { + ResultSet columns = getColumns("%"); + + try { + int total = getSize(columns); + int index = 0; + + while (columns.next()) { + // add the following strings: + // 1. column name + // 2. table name + // 3. tablename.columnname + + progress(index++, total); + String name = columns.getString("TABLE_NAME"); + names.add(name); + names.add(columns.getString("COLUMN_NAME")); + names.add( + columns.getString("TABLE_NAME") + "." + + columns.getString("COLUMN_NAME")); + } + + progress(index, index); + } finally { + columns.close(); + } + + info(loc("done")); + + return (String []) names.toArray(new String[0]); + } catch (Throwable t) { + handleException(t); + return new String[0]; + } + } + + //////////////////// + // String utilities + //////////////////// + + /** + * Split the line into an array by tokenizing on space characters + * + * @param line the line to break up + * + * @return an array of individual words + */ + String [] split(String line) + { + return split(line, " "); + } + + /** + * Splits the line into an array of possibly-compound identifiers, observing + * the database's quoting syntax. + * + *

    For example, on Oracle, which uses double-quote (") as quote + * character, + * + *

    !tables "My Schema"."My Table"
    + * + * returns + * + *
    { {"!tables"}, {"My Schema", "My Table"} }
    + * + * @param line the line to break up + * + * @return an array of compound words + */ + String [][] splitCompound(String line) + { + final SqlLine.DatabaseConnection databaseConnection = con(); + final Quoting quoting; + if (databaseConnection == null) { + quoting = Quoting.DEFAULT; + } else { + quoting = databaseConnection.quoting; + } + + int state = SPACE; + int idStart = -1; + final char[] chars = line.toCharArray(); + int n = chars.length; + + // Trim off trailing semicolon and/or whitespace + while (n > 0 + && (Character.isWhitespace(chars[n - 1]) + || chars[n - 1] == ';')) + { + --n; + } + + final List words = new ArrayList(); + final List current = new ArrayList(); + for (int i = 0; i < n;) { + char c = chars[i]; + switch (state) { + case SPACE: + case DOT_SPACE: + ++i; + if (Character.isWhitespace(c)) { + ; + } else if (c == '.') { + state = DOT_SPACE; + } else if (c == quoting.start) { + if (state == SPACE) { + if (current.size() > 0) { + words.add( + current.toArray(new String[current.size()])); + current.clear(); + } + } + state = QUOTED; + idStart = i; + } else { + if (state == SPACE) { + if (current.size() > 0) { + words.add( + current.toArray(new String[current.size()])); + current.clear(); + } + } + state = UNQUOTED; + idStart = i - 1; + } + break; + case QUOTED: + ++i; + if (c == quoting.end) { + if (i < n + && chars[i] == quoting.end) + { + // Repeated quote character inside a quoted identifier. + // Elminate one of the repeats, and we remain inside a + // quoted identifier. + System.arraycopy(chars, i, chars, i - 1, n - i); + --n; + } else { + state = SPACE; + final String word = + new String(chars, idStart, i - idStart - 1); + current.add(word); + } + } + break; + case UNQUOTED: + // We are in an unquoted identifier. Whitespace or dot ends + // the identifier, anything else extends it. + ++i; + if (Character.isWhitespace(c) || c == '.') { + String word = new String(chars, idStart, i - idStart - 1); + if (word.equalsIgnoreCase("NULL")) { + word = null; + } else if (quoting.upper) { + word = word.toUpperCase(); + } + current.add(word); + state = (c == '.') ? DOT_SPACE : SPACE; + } + break; + default: + throw new AssertionError("unexpected state " + state); + } + } + + switch (state) { + case SPACE: + case DOT_SPACE: + break; + case QUOTED: + case UNQUOTED: + // In the middle of a quoted string. Be lenient, and complete the + // word. + String word = new String(chars, idStart, n - idStart); + if (state == UNQUOTED) { + if (word.equalsIgnoreCase("NULL")) { + word = null; + } else if (quoting.upper) { + word = word.toUpperCase(); + } + } + current.add(word); + break; + default: + throw new AssertionError("unexpected state " + state); + } + + if (current.size() > 0) { + words.add(current.toArray(new String[current.size()])); + } + + return (String[][]) words.toArray(new String[words.size()][]); + } + + /** In a region of whitespace. */ + private static final int SPACE = 0; + + /** In a region of whitespace that contains a dot. */ + private static final int DOT_SPACE = 1; + + /** Inside a quoted identifier. */ + private static final int QUOTED = 2; + + /** Inside an unquoted identifier. */ + private static final int UNQUOTED = 3; + + String dequote(String str) + { + if (str == null) { + return null; + } + + while ( + (str.startsWith("'") && str.endsWith("'")) + || (str.startsWith("\"") && str.endsWith("\""))) + { + str = str.substring(1, str.length() - 1); + } + + return str; + } + + String [] split(String line, String delim) + { + StringTokenizer tok = new StringTokenizer(line, delim); + String [] ret = new String[tok.countTokens()]; + int index = 0; + while (tok.hasMoreTokens()) { + String t = tok.nextToken(); + + t = dequote(t); + + ret[index++] = t; + } + + return ret; + } + + static Map map(Object [] obs) + { + Map m = new HashMap(); + for (int i = 0; i < (obs.length - 1); i += 2) { + m.put(obs[i], obs[i + 1]); + } + + return Collections.unmodifiableMap(m); + } + + static boolean getMoreResults(Statement stmnt) + { + try { + return stmnt.getMoreResults(); + } catch (Throwable t) { + return false; + } + } + + static String xmlattrencode(String str) + { + str = replace(str, "\"", """); + str = replace(str, "<", "<"); + return str; + } + + static String replace(String source, String from, String to) + { + if (source == null) { + return null; + } + + if (from.equals(to)) { + return source; + } + + StringBuffer replaced = new StringBuffer(); + + int index = -1; + while ((index = source.indexOf(from)) != -1) { + replaced.append(source.substring(0, index)); + replaced.append(to); + source = source.substring(index + from.length()); + } + + replaced.append(source); + + return replaced.toString(); + } + + /** + * Split the line based on spaces, asserting that the number of words is + * correct. + * + * @param line the line to split + * @param assertLen the number of words to assure + * @param usage the message to output if there are an incorrect number of + * words. + * + * @return the split lines, or null if the assertion failed. + */ + String [] split(String line, int assertLen, String usage) + { + String [] ret = split(line); + + if (ret.length != assertLen) { + error(usage); + return null; + } + + return ret; + } + + /** + * Wrap the specified string by breaking on space characters. + * + * @param toWrap the string to wrap + * @param len the maximum length of any line + * @param start the number of spaces to pad at the beginning of a line + * + * @return the wrapped string + */ + String wrap(String toWrap, int len, int start) + { + String cur = toWrap; + StringBuffer buff = new StringBuffer(); + StringBuffer line = new StringBuffer(); + + char [] head = new char[start]; + Arrays.fill(head, ' '); + + for ( + StringTokenizer tok = new StringTokenizer(toWrap, " "); + tok.hasMoreTokens();) + { + String next = tok.nextToken(); + if ((line.length() + next.length()) > len) { + buff.append(line).append(sep).append(head); + line.setLength(0); + } + + line.append((line.length() == 0) ? "" : " ").append(next); + } + + buff.append(line); + + return buff.toString(); + } + + /** + * Output a progress indicator to the console. + * + * @param cur the current progress + * @param max the maximum progress, or -1 if unknown + */ + void progress(int cur, int max) + { + StringBuffer out = new StringBuffer(); + + if (lastProgress != null) { + char [] back = new char[lastProgress.length()]; + Arrays.fill(back, '\b'); + out.append(back); + } + + String progress = + cur + "/" + ((max == -1) ? "?" : ("" + max)) + " " + + ((max == -1) ? "(??%)" + : ("(" + (cur * 100 / ((max == 0) ? 1 : max)) + "%)")); + ; + + if ((cur >= max) && (max != -1)) { + progress += " " + loc("done") + sep; + lastProgress = null; + } else { + lastProgress = progress; + } + + out.append(progress); + + System.out.print(out.toString()); + System.out.flush(); + } + + /////////////////////////////// + // Exception handling routines + /////////////////////////////// + + void handleException(Throwable e) + { + while (e instanceof InvocationTargetException) { + e = ((InvocationTargetException) e).getTargetException(); + } + + if (e instanceof SQLException) { + handleSQLException((SQLException) e); + } else if (!(opts.getVerbose())) { + if (e.getMessage() == null) { + error(e.getClass().getName()); + } else { + error(e.getMessage()); + } + } else { + e.printStackTrace(System.err); + } + } + + void handleSQLException(SQLException e) + { + if ((e instanceof SQLWarning) && !(opts.getShowWarnings())) { + return; + } + + String type = (e instanceof SQLWarning) ? loc("Warning") : loc("Error"); + + error( + loc((e instanceof SQLWarning) ? "Warning" : "Error", + new Object[] { + (e.getMessage() == null) ? "" : e.getMessage().trim(), + (e.getSQLState() == null) ? "" : e.getSQLState().trim(), + new Integer(e.getErrorCode()) + })); + + if (opts.getVerbose()) { + e.printStackTrace(); + } + + if (!opts.getShowNestedErrs()) { + return; + } + + for ( + SQLException nested = e.getNextException(); + (nested != null) + && (nested != e); + nested = nested.getNextException()) + { + handleSQLException(nested); + } + } + + private boolean scanForDriver(String url) + { + try { + // already registered + if (findRegisteredDriver(url) != null) { + return true; + } + + // first try known drivers... + scanDrivers(true); + + if (findRegisteredDriver(url) != null) { + return true; + } + + // now really scan... + scanDrivers(false); + + if (findRegisteredDriver(url) != null) { + return true; + } + + return false; + } catch (Exception e) { + debug(e.toString()); + return false; + } + } + + private Driver findRegisteredDriver(String url) + { + for ( + Enumeration drivers = DriverManager.getDrivers(); + (drivers != null) && drivers.hasMoreElements();) + { + Driver driver = (Driver) drivers.nextElement(); + try { + if (driver.acceptsURL(url)) { + return driver; + } + } catch (Exception e) { + } + } + + return null; + } + + Driver [] scanDrivers(String line) + throws IOException + { + return scanDrivers(false); + } + + Driver [] scanDrivers(boolean knownOnly) + throws IOException + { + long start = System.currentTimeMillis(); + + Set classNames = new HashSet(); + + if (!knownOnly) { + classNames.addAll( + Arrays.asList( + ClassNameCompletor.getClassNames())); + } + + classNames.addAll(KNOWN_DRIVERS); + + Set driverClasses = new HashSet(); + + for (Iterator i = classNames.iterator(); i.hasNext();) { + String className = i.next().toString(); + + if (className.toLowerCase().indexOf("driver") == -1) { + continue; + } + + try { + Class c = + Class.forName( + className, + false, + Thread.currentThread().getContextClassLoader()); + if (!Driver.class.isAssignableFrom(c)) { + continue; + } + + if (Modifier.isAbstract(c.getModifiers())) { + continue; + } + + // now instantiate and initialize it + driverClasses.add(c.newInstance()); + } catch (Throwable t) { + } + } + info("scan complete in " + + (System.currentTimeMillis() - start) + "ms"); + return (Driver []) driverClasses.toArray(new Driver[0]); + } + + Driver [] scanDriversOLD(String line) + { + long start = System.currentTimeMillis(); + + Set paths = new HashSet(); + Set driverClasses = new HashSet(); + + for ( + StringTokenizer tok = + new StringTokenizer( + System.getProperty("java.ext.dirs"), + System.getProperty("path.separator")); + tok.hasMoreTokens();) + { + File [] files = new File(tok.nextToken()).listFiles(); + for (int i = 0; (files != null) && (i < files.length); i++) { + paths.add(files[i].getAbsolutePath()); + } + } + + for ( + StringTokenizer tok = + new StringTokenizer( + System.getProperty("java.class.path"), + System.getProperty("path.separator")); + tok.hasMoreTokens();) + { + paths.add(new File(tok.nextToken()).getAbsolutePath()); + } + + for (Iterator i = paths.iterator(); i.hasNext();) { + File f = new File((String) i.next()); + output( + color().pad(loc("scanning", f.getAbsolutePath()), 60), + false); + + try { + ZipFile zf = new ZipFile(f); + int total = zf.size(); + int index = 0; + + for ( + Enumeration zfEnum = zf.entries(); + zfEnum.hasMoreElements();) + { + ZipEntry entry = (ZipEntry) zfEnum.nextElement(); + String name = entry.getName(); + progress(index++, total); + + if (name.endsWith(".class")) { + name = name.replace('/', '.'); + name = name.substring(0, name.length() - 6); + + try { + // check for the string "driver" in the class + // to see if we should load it. Not perfect, but + // it is far too slow otherwise. + if (name.toLowerCase().indexOf("driver") != -1) { + Class c = + Class.forName( + name, + false, + getClass().getClassLoader()); + if (Driver.class.isAssignableFrom(c) + && !(Modifier.isAbstract( + c.getModifiers()))) + { + try { + // load and initialize + Class.forName(name); + } catch (Exception e) { + } + driverClasses.add(c.newInstance()); + } + } + } catch (Throwable t) { + } + } + } + + progress(total, total); + } catch (Exception e) { + } + } + + info("scan complete in " + + (System.currentTimeMillis() - start) + "ms"); + return (Driver []) driverClasses.toArray(new Driver[0]); + } + + /////////////////////////////////////// + // ResultSet output formatting classes + /////////////////////////////////////// + + int print(ResultSet rs) + throws SQLException + { + String format = opts.getOutputFormat(); + OutputFormat f = (OutputFormat) formats.get(format); + + if (f == null) { + error( + loc("unknown-format", + new Object[] { + format, formats.keySet() + })); + f = new TableOutputFormat(); + } + + Rows rows; + + if (opts.getIncremental()) { + rows = new IncrementalRows(rs); + } else { + rows = new BufferedRows(rs); + } + + return f.print(rows); + } + + private Statement createStatement() + throws SQLException + { + Statement stmnt = con().connection.createStatement(); + if (opts.timeout > -1) { + stmnt.setQueryTimeout(opts.timeout); + } + if (opts.rowLimit != 0) { + stmnt.setMaxRows(opts.rowLimit); + } + if (signalHandler != null) { + signalHandler.setStmt(stmnt); + } + return stmnt; + } + + void runBatch(List statements) + { + try { + Statement stmnt = createStatement(); + try { + for (Iterator i = statements.iterator(); i.hasNext();) { + stmnt.addBatch(i.next().toString()); + } + + int [] counts = stmnt.executeBatch(); + + output( + color().pad(color().bold("COUNT"), 8).append( + color().bold("STATEMENT"))); + + for (int i = 0; (counts != null) && (i < counts.length); i++) { + output( + color().pad(counts[i] + "", 8).append( + statements.get(i).toString())); + } + } finally { + try { + stmnt.close(); + } catch (Exception e) { + } + } + } catch (Exception e) { + handleException(e); + } + } + + public int runCommands(List cmds) + { + int successCount = 0; + + try { + int index = 1; + int size = cmds.size(); + for (Iterator i = cmds.iterator(); i.hasNext();) { + String cmd = i.next().toString(); + info(color().pad((index++) + "/" + (size), 13).append(cmd)); + boolean success = dispatch(cmd); + + // if we do not force script execution, abort + // when a failure occurs. + if (!success && !opts.getForce()) { + error(loc("abort-on-error", cmd)); + return successCount; + } + successCount += (success == true) ? 1 : 0; + } + } catch (Exception e) { + handleException(e); + } + + return successCount; + } + + private void setCompletions() + throws SQLException, IOException + { + if (con() != null) { + con().setCompletions(opts.getFastConnect()); + } + } + + //~ Inner Interfaces ------------------------------------------------------- + + interface OutputFormat + { + int print(SqlLine.Rows rows); + } + + //////////////////////////// + // Command handling classes + //////////////////////////// + + /** + * A generic command to be executed. Execution of the command should be + * dispatched to the {@link #execute(java.lang.String)} method after + * determining that the command is appropriate with the {@link + * #matches(java.lang.String)} method. + * + * @author Marc Prud'hommeaux + */ + interface CommandHandler + { + /** + * @return the name of the command + */ + public String getName(); + + /** + * @return all the possible names of this command. + */ + public String [] getNames(); + + /** + * @return the short help description for this command. + */ + public String getHelpText(); + + /** + * Check to see if the specified string can be dispatched to this + * command. + * + * @param line the command line to check. + * + * @return the command string that matches, or null if it no match + */ + public String matches(String line); + + /** + * Execute the specified command. + * + * @param line the full command line to execute. + */ + public boolean execute(String line); + + /** + * Returns the completors that can handle parameters. + */ + public Completor [] getParameterCompletors(); + } + + //~ Inner Classes ---------------------------------------------------------- + + /** + * Abstract OutputFormat. + * + * @author Marc Prud'hommeaux + */ + abstract class AbstractOutputFormat + implements OutputFormat + { + public int print(Rows rows) + { + int count = 0; + Rows.Row header = (Rows.Row) rows.next(); + + printHeader(header); + + while (rows.hasNext()) { + printRow(rows, header, (Rows.Row) rows.next()); + count++; + } + + printFooter(header); + + return count; + } + + abstract void printHeader(Rows.Row header); + + abstract void printFooter(Rows.Row header); + + abstract void printRow(Rows rows, Rows.Row header, Rows.Row row); + } + + class XMLAttributeOutputFormat + extends AbstractOutputFormat + { + public void printHeader(Rows.Row header) + { + output(""); + } + + public void printFooter(Rows.Row header) + { + output(""); + } + + public void printRow(Rows rows, Rows.Row header, Rows.Row row) + { + String [] head = header.values; + String [] vals = row.values; + + StringBuffer result = new StringBuffer(" "); + + output(result.toString()); + } + } + + class XMLElementOutputFormat + extends AbstractOutputFormat + { + public void printHeader(Rows.Row header) + { + output(""); + } + + public void printFooter(Rows.Row header) + { + output(""); + } + + public void printRow(Rows rows, Rows.Row header, Rows.Row row) + { + String [] head = header.values; + String [] vals = row.values; + + output(" "); + for (int i = 0; (i < head.length) && (i < vals.length); i++) { + output( + " <" + head[i] + ">" + + (xmlattrencode(vals[i])) + + ""); + } + + output(" "); + } + } + + /** + * OutputFormat for vertical column name: value format. + * + * @author Marc Prud'hommeaux + */ + class VerticalOutputFormat + implements OutputFormat + { + public int print(Rows rows) + { + int count = 0; + Rows.Row header = (Rows.Row) rows.next(); + + while (rows.hasNext()) { + printRow(rows, header, (Rows.Row) rows.next()); + count++; + } + + return count; + } + + public void printRow(Rows rows, Rows.Row header, Rows.Row row) + { + String [] head = header.values; + String [] vals = row.values; + int headwidth = 0; + for (int i = 0; (i < head.length) && (i < vals.length); i++) { + headwidth = Math.max(headwidth, head[i].length()); + } + + headwidth += 2; + + for (int i = 0; (i < head.length) && (i < vals.length); i++) { + output( + color().bold( + color().pad(head[i], headwidth).getMono()).append( + (vals[i] == null) ? "" : vals[i])); + } + + output(""); // spacing + } + } + + /** + * OutputFormat for values separated by a delimiter. TODO: + * Handle character escaping + * + * @author Marc Prud'hommeaux + */ + class SeparatedValuesOutputFormat + implements OutputFormat + { + private char separator; + + public SeparatedValuesOutputFormat(char separator) + { + setSeparator(separator); + } + + public int print(Rows rows) + { + int count = 0; + while (rows.hasNext()) { + printRow(rows, (Rows.Row) rows.next()); + count++; + } + + return count - 1; // sans header row + } + + public void printRow(Rows rows, Rows.Row row) + { + String [] vals = row.values; + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < vals.length; i++) { + buf.append((buf.length() == 0) ? "" : ("" + getSeparator())) + .append('\'').append((vals[i] == null) ? "" : vals[i]).append( + '\''); + } + output(buf.toString()); + } + + public void setSeparator(char separator) + { + this.separator = separator; + } + + public char getSeparator() + { + return this.separator; + } + } + + /** + * OutputFormat for a pretty, table-like format. + * + * @author Marc Prud'hommeaux + */ + class TableOutputFormat + implements OutputFormat + { + public int print(Rows rows) + { + int index = 0; + ColorBuffer header = null; + ColorBuffer headerCols = null; + final int width = opts.getMaxWidth() - 4; + + // normalize the columns sizes + rows.normalizeWidths(); + + for (; rows.hasNext();) { + Rows.Row row = (Rows.Row) rows.next(); + ColorBuffer cbuf = getOutputString(rows, row); + cbuf = cbuf.truncate(width); + + if (index == 0) { + StringBuffer h = new StringBuffer(); + for (int j = 0; j < row.sizes.length; j++) { + for (int k = 0; k < row.sizes[j]; k++) { + h.append('-'); + } + h.append("-+-"); + } + + headerCols = cbuf; + header = + color().green(h.toString()).truncate( + headerCols.getVisibleLength()); + } + + if ((index == 0) + || ((opts.getHeaderInterval() > 0) + && ((index % opts.getHeaderInterval()) == 0) + && opts.getShowHeader())) + { + printRow(header, true); + printRow(headerCols, false); + printRow(header, true); + } + + if (index != 0) { // don't output the header twice + printRow(cbuf, false); + } + + index++; + } + + if ((header != null) && opts.getShowHeader()) { + printRow(header, true); + } + + return index - 1; + } + + void printRow(ColorBuffer cbuff, boolean header) + { + if (header) { + output(color().green("+-").append(cbuff).green("-+")); + } else { + output(color().green("| ").append(cbuff).green(" |")); + } + } + + public ColorBuffer getOutputString(Rows rows, Rows.Row row) + { + return getOutputString(rows, row, " | "); + } + + ColorBuffer getOutputString(Rows rows, Rows.Row row, String delim) + { + ColorBuffer buf = color(); + + for (int i = 0; i < row.values.length; i++) { + if (buf.getVisibleLength() > 0) { + buf.green(delim); + } + + ColorBuffer v; + + if (row.isMeta) { + v = color().center(row.values[i], row.sizes[i]); + if (rows.isPrimaryKey(i)) { + buf.cyan(v.getMono()); + } else { + buf.bold(v.getMono()); + } + } else { + v = color().pad(row.values[i], row.sizes[i]); + if (rows.isPrimaryKey(i)) { + buf.cyan(v.getMono()); + } else { + buf.append(v.getMono()); + } + } + } + + if (row.deleted) { // make deleted rows red + buf = color().red(buf.getMono()); + } else if (row.updated) { // make updated rows blue + buf = color().blue(buf.getMono()); + } else if (row.inserted) { // make new rows green + buf = color().green(buf.getMono()); + } + + return buf; + } + } + + /** + * Abstract base class representing a set of rows to be displayed. + */ + abstract class Rows + implements Iterator + { + final ResultSetMetaData rsMeta; + final Boolean [] primaryKeys; + final NumberFormat numberFormat; + + Rows(ResultSet rs) + throws SQLException + { + rsMeta = rs.getMetaData(); + int count = rsMeta.getColumnCount(); + primaryKeys = new Boolean[count]; + if (opts.getNumberFormat().equals("default")) { + numberFormat = null; + } else { + numberFormat = new DecimalFormat(opts.getNumberFormat()); + } + } + + public void remove() + { + throw new UnsupportedOperationException(); + } + + /** + * Update all of the rows to have the same size, set to the maximum + * length of each column in the Rows. + */ + abstract void normalizeWidths(); + + /** + * Return whether the specified column (0-based index) is a primary key. + * Since this method depends on whether the JDBC driver property + * implements {@link ResultSetMetaData#getTableName} (many do not), it + * is not reliable for all databases. + */ + boolean isPrimaryKey(int col) + { + if (primaryKeys[col] != null) { + return primaryKeys[col].booleanValue(); + } + + try { + // this doesn't always work, since some JDBC drivers (e.g., + // Oracle's) return a blank string from getTableName. + String table = rsMeta.getTableName(col + 1); + String column = rsMeta.getColumnName(col + 1); + + if ((table == null) + || (table.length() == 0) + || (column == null) + || (column.length() == 0)) + { + return (primaryKeys[col] = new Boolean(false)) + .booleanValue(); + } + + ResultSet pks = + con().meta.getPrimaryKeys( + con().meta.getConnection().getCatalog(), + null, + table); + + try { + while (pks.next()) { + if (column.equalsIgnoreCase( + pks.getString("COLUMN_NAME"))) + { + return (primaryKeys[col] = new Boolean(true)) + .booleanValue(); + } + } + } finally { + pks.close(); + } + + return (primaryKeys[col] = new Boolean(false)).booleanValue(); + } catch (SQLException sqle) { + return (primaryKeys[col] = new Boolean(false)).booleanValue(); + } + } + + class Row + { + final String [] values; + final boolean isMeta; + private boolean deleted; + private boolean inserted; + private boolean updated; + private int [] sizes; + + Row(int size) + throws SQLException + { + isMeta = true; + values = new String[size]; + sizes = new int[size]; + for (int i = 0; i < size; i++) { + values[i] = rsMeta.getColumnLabel(i + 1); + sizes[i] = (values[i] == null) ? 1 : values[i].length(); + } + + deleted = false; + updated = false; + inserted = false; + } + + Row(int size, ResultSet rs) + throws SQLException + { + isMeta = false; + values = new String[size]; + sizes = new int[size]; + + try { + deleted = rs.rowDeleted(); + } catch (Throwable t) { + } + try { + updated = rs.rowUpdated(); + } catch (Throwable t) { + } + try { + inserted = rs.rowInserted(); + } catch (Throwable t) { + } + + for (int i = 0; i < size; i++) { + if (numberFormat != null) { + Object o = rs.getObject(i + 1); + if (o == null) { + values[i] = null; + } else if (o instanceof Number) { + values[i] = numberFormat.format(o); + } else { + values[i] = o.toString(); + } + } else { + values[i] = String.valueOf(rs.getObject(i + 1)); + } + sizes[i] = (values[i] == null) ? 1 : values[i].length(); + } + } + } + } + + /** + * Rows implementation which buffers all rows in a linked list. + */ + class BufferedRows + extends Rows + { + private final LinkedList list; + + private final Iterator iterator; + + BufferedRows(ResultSet rs) + throws SQLException + { + super(rs); + + list = new LinkedList(); + + int count = rsMeta.getColumnCount(); + + list.add(new Row(count)); + + while (rs.next()) { + list.add(new Row(count, rs)); + } + + iterator = list.iterator(); + } + + public boolean hasNext() + { + return iterator.hasNext(); + } + + public Object next() + { + return iterator.next(); + } + + void normalizeWidths() + { + int [] max = null; + for (int i = 0; i < list.size(); i++) { + Row row = (Row) list.get(i); + if (max == null) { + max = new int[row.values.length]; + } + + for (int j = 0; j < max.length; j++) { + max[j] = Math.max(max[j], row.sizes[j] + 1); + } + } + + for (int i = 0; i < list.size(); i++) { + Row row = (Row) list.get(i); + row.sizes = max; + } + } + } + + /** + * Rows implementation which returns rows incrementally from result set + * without any buffering. + */ + class IncrementalRows + extends Rows + { + private final ResultSet rs; + private Row labelRow; + private Row maxRow; + private Row nextRow; + private boolean endOfResult; + private boolean normalizingWidths; + + IncrementalRows(ResultSet rs) + throws SQLException + { + super(rs); + this.rs = rs; + + labelRow = new Row(rsMeta.getColumnCount()); + maxRow = new Row(rsMeta.getColumnCount()); + + // pre-compute normalization so we don't have to deal + // with SQLExceptions later + for (int i = 0; i < maxRow.sizes.length; ++i) { + // normalized display width is based on maximum of display size + // and label size + maxRow.sizes[i] = + Math.max( + maxRow.sizes[i], + rsMeta.getColumnDisplaySize(i + 1)); + } + + nextRow = labelRow; + endOfResult = false; + } + + public boolean hasNext() + { + if (endOfResult) { + return false; + } + + if (nextRow == null) { + try { + if (rs.next()) { + nextRow = new Row(labelRow.sizes.length, rs); + + if (normalizingWidths) { + // perform incremental normalization + nextRow.sizes = labelRow.sizes; + } + } else { + endOfResult = true; + } + } catch (SQLException ex) { + throw new RuntimeException(ex.toString()); + } + } + + return (nextRow != null); + } + + public Object next() + { + if (!hasNext()) { + throw new NoSuchElementException(); + } + + Object ret = nextRow; + nextRow = null; + return ret; + } + + void normalizeWidths() + { + // normalize label row + labelRow.sizes = maxRow.sizes; + + // and remind ourselves to perform incremental normalization + // for each row as it is produced + normalizingWidths = true; + } + } + + /////////////////////////////// + // Console interaction classes + /////////////////////////////// + + /** + * A buffer that can output segments using ANSI color. + * + * @author Marc Prud'hommeaux + */ + final static class ColorBuffer + implements Comparable + { + private static final ColorAttr BOLD = new ColorAttr("\033[1m"); + private static final ColorAttr NORMAL = new ColorAttr("\033[m"); + private static final ColorAttr REVERS = new ColorAttr("\033[7m"); + private static final ColorAttr LINED = new ColorAttr("\033[4m"); + private static final ColorAttr GREY = new ColorAttr("\033[1;30m"); + private static final ColorAttr RED = new ColorAttr("\033[1;31m"); + private static final ColorAttr GREEN = new ColorAttr("\033[1;32m"); + private static final ColorAttr BLUE = new ColorAttr("\033[1;34m"); + private static final ColorAttr CYAN = new ColorAttr("\033[1;36m"); + private static final ColorAttr YELLOW = new ColorAttr("\033[1;33m"); + private static final ColorAttr MAGENTA = new ColorAttr("\033[1;35m"); + private static final ColorAttr INVISIBLE = new ColorAttr("\033[8m"); + + private final List parts = new LinkedList(); + + private final boolean useColor; + + public ColorBuffer(boolean useColor) + { + this.useColor = useColor; + + append(""); + } + + public ColorBuffer(String str, boolean useColor) + { + this.useColor = useColor; + + append(str); + } + + /** + * Pad the specified String with spaces to the indicated length + * + * @param str the String to pad + * @param len the length we want the return String to be + * + * @return the passed in String with spaces appended until the length + * matches the specified length. + */ + ColorBuffer pad(ColorBuffer str, int len) + { + int n = str.getVisibleLength(); + while (n < len) { + str.append(" "); + n++; + } + + return append(str); + } + + ColorBuffer center(String str, int len) + { + StringBuffer buf = new StringBuffer(str); + + while (buf.length() < len) { + buf.append(" "); + + if (buf.length() < len) { + buf.insert(0, " "); + } + } + + return append(buf.toString()); + } + + ColorBuffer pad(String str, int len) + { + if (str == null) { + str = ""; + } + + return pad(new ColorBuffer(str, false), len); + } + + public String getColor() + { + return getBuffer(useColor); + } + + public String getMono() + { + return getBuffer(false); + } + + String getBuffer(boolean color) + { + StringBuffer buf = new StringBuffer(); + for (Iterator i = parts.iterator(); i.hasNext();) { + Object next = i.next(); + if (!color && (next instanceof ColorAttr)) { + continue; + } + + buf.append(next.toString()); + } + + return buf.toString(); + } + + /** + * Truncate the ColorBuffer to the specified length and return the new + * ColorBuffer. Any open color tags will be closed. + */ + public ColorBuffer truncate(int len) + { + ColorBuffer cbuff = new ColorBuffer(useColor); + ColorAttr lastAttr = null; + for ( + Iterator i = parts.iterator(); + (cbuff.getVisibleLength() < len) && i.hasNext();) + { + Object next = i.next(); + if (next instanceof ColorAttr) { + lastAttr = (ColorAttr) next; + cbuff.append((ColorAttr) next); + continue; + } + + String val = next.toString(); + if ((cbuff.getVisibleLength() + val.length()) > len) { + int partLen = len - cbuff.getVisibleLength(); + val = val.substring(0, partLen); + } + + cbuff.append(val); + } + + // close off the buffer with a normal tag + if ((lastAttr != null) && (lastAttr != NORMAL)) { + cbuff.append(NORMAL); + } + + return cbuff; + } + + public String toString() + { + return getColor(); + } + + public ColorBuffer append(String str) + { + parts.add(str); + return this; + } + + public ColorBuffer append(ColorBuffer buf) + { + parts.addAll(buf.parts); + return this; + } + + public ColorBuffer append(ColorAttr attr) + { + parts.add(attr); + return this; + } + + public int getVisibleLength() + { + return getMono().length(); + } + + public ColorBuffer append(ColorAttr attr, String val) + { + parts.add(attr); + parts.add(val); + parts.add(NORMAL); + return this; + } + + public ColorBuffer bold(String str) + { + return append(BOLD, str); + } + + public ColorBuffer lined(String str) + { + return append(LINED, str); + } + + public ColorBuffer grey(String str) + { + return append(GREY, str); + } + + public ColorBuffer red(String str) + { + return append(RED, str); + } + + public ColorBuffer blue(String str) + { + return append(BLUE, str); + } + + public ColorBuffer green(String str) + { + return append(GREEN, str); + } + + public ColorBuffer cyan(String str) + { + return append(CYAN, str); + } + + public ColorBuffer yellow(String str) + { + return append(YELLOW, str); + } + + public ColorBuffer magenta(String str) + { + return append(MAGENTA, str); + } + + public int compareTo(Object other) + { + return getMono().compareTo(((ColorBuffer) other).getMono()); + } + + private static class ColorAttr + { + private final String attr; + + public ColorAttr(String attr) + { + this.attr = attr; + } + + public String toString() + { + return attr; + } + } + } + + /** + * An abstract implementation of CommandHandler. + * + * @author Marc Prud'hommeaux + */ + public abstract class AbstractCommandHandler + implements CommandHandler + { + private final String name; + private final String [] names; + private final String helpText; + private Completor [] parameterCompletors = new Completor[0]; + + public AbstractCommandHandler( + String [] names, + String helpText, + Completor [] completors) + { + this.name = names[0]; + this.names = names; + this.helpText = helpText; + if ((completors == null) || (completors.length == 0)) { + this.parameterCompletors = + new Completor[] { + new NullCompletor() + }; + } else { + List c = new LinkedList(Arrays.asList(completors)); + c.add(new NullCompletor()); + this.parameterCompletors = + (Completor []) c.toArray(new Completor[0]); + } + } + + public String getHelpText() + { + return helpText; + } + + public String getName() + { + return this.name; + } + + public String [] getNames() + { + return this.names; + } + + public String matches(String line) + { + if ((line == null) || (line.length() == 0)) { + return null; + } + + String [] parts = split(line); + if ((parts == null) || (parts.length == 0)) { + return null; + } + + for (int i = 0; i < names.length; i++) { + if (names[i].startsWith(parts[0])) { + return names[i]; + } + } + + return null; + } + + public void setParameterCompletors(Completor [] parameterCompletors) + { + this.parameterCompletors = parameterCompletors; + } + + public Completor [] getParameterCompletors() + { + return this.parameterCompletors; + } + } + + /** + * A {@link sqlline.SqlLine.CommandHandler} implementation that uses + * reflection to determine the method to dispatch the command. + * + * @author Marc Prud'hommeaux + */ + public class ReflectiveCommandHandler + extends AbstractCommandHandler + { + public ReflectiveCommandHandler(String [] cmds, Completor [] completor) + { + super(cmds, loc("help-" + cmds[0]), completor); + } + + public boolean execute(String line) + { + try { + Object ob = + command.getClass().getMethod( + getName(), + new Class[] { String.class }).invoke( + command, + new Object[] { line }); + return (ob != null) && (ob instanceof Boolean) + && ((Boolean) ob).booleanValue(); + } catch (Throwable e) { + return error(e); + } + } + } + + ////////////////////////// + // Command methods follow + ////////////////////////// + + public class Commands + { + public boolean metadata(String line) + { + debug(line); + + String [] parts = split(line); + List params = new LinkedList(Arrays.asList(parts)); + if ((parts == null) || (parts.length == 0)) { + return dbinfo(""); + } + + params.remove(0); + params.remove(0); + debug(params.toString()); + return metadata(parts[1], params); + } + + public boolean metadata(String cmd, List argList) + { + try { + Method [] m = con().meta.getClass().getMethods(); + Set methodNames = new TreeSet(); + Set methodNamesUpper = new TreeSet(); + for (int i = 0; i < m.length; i++) { + methodNames.add(m[i].getName()); + methodNamesUpper.add(m[i].getName().toUpperCase()); + } + + if (!methodNamesUpper.contains(cmd.toUpperCase())) { + error(loc("no-such-method", cmd)); + error(loc("possible-methods")); + for (Iterator i = methodNames.iterator(); i.hasNext();) { + error(" " + i.next()); + } + return false; + } + + Object res = + Reflector.invoke( + con().meta, + DatabaseMetaData.class, + cmd, + argList); + + if (res instanceof ResultSet) { + ResultSet rs = (ResultSet) res; + + if (rs != null) { + try { + print(rs); + } finally { + rs.close(); + } + } + } else if (res != null) { + output(res.toString()); + } + } catch (Exception e) { + return error(e); + } + + return true; + } + + public boolean history(String line) + { + List hist = reader.getHistory().getHistoryList(); + int index = 1; + for (Iterator i = hist.iterator(); i.hasNext(); index++) { + output(color().pad(index + ".", 6).append(i.next().toString())); + } + + return true; + } + + String arg1(String line, String paramname) + { + return arg1(line, paramname, null); + } + + String arg1(String line, String paramname, String def) + { + String [] ret = split(line); + + if ((ret == null) || (ret.length != 2)) { + if (def != null) { + return def; + } + + throw new IllegalArgumentException( + loc("arg-usage", + new Object[] { + (ret.length == 0) ? "" : ret[0], + paramname + })); + } + + return ret[1]; + } + + /** + * Constructs a list of string parameters for a metadata call. + * + *

    The number of items is equal to the number of items in the + * strings parameter, typically three (catalog, schema, table + * name). + * + *

    Parses the command line, and assumes that the the first word is + * a compound identifier. If the compound identifier has fewer parts + * than required, fills from the right. + * + *

    The result is a mutable list of strings. + * + * @param line Command line + * @param paramname Name of parameter being read from command line + * @param defaultValues Default values for each component of parameter + * @return Mutable list of strings + */ + private List buildMetadataArgs( + String line, + String paramname, + String[] defaultValues) + { + final ArrayList list = new ArrayList(); + final String[][] ret = splitCompound(line); + String[] compound; + if ((ret == null) || (ret.length != 2)) { + if (defaultValues[defaultValues.length - 1] == null) { + throw new IllegalArgumentException( + loc("arg-usage", + new Object[] { + (ret.length == 0) ? "" : ret[0][0], + paramname + })); + } + compound = new String[0]; + } else { + compound = ret[1]; + } + if (compound.length <= defaultValues.length) { + list.addAll( + Arrays.asList(defaultValues).subList( + 0, defaultValues.length - compound.length)); + list.addAll(Arrays.asList(compound)); + } else { + list.addAll( + Arrays.asList(compound).subList(0, defaultValues.length)); + } + return list; + } + + public boolean indexes(String line) + throws Exception + { + String[] strings = {conn().getCatalog(), null, "%"}; + List args = buildMetadataArgs(line, "table name", strings); + args.add(Boolean.FALSE); + args.add(Boolean.TRUE); + return metadata("getIndexInfo", args); + } + + public boolean primarykeys(String line) + throws Exception + { + String[] strings = {conn().getCatalog(), null, "%"}; + List args = buildMetadataArgs(line, "table name", strings); + return metadata("getPrimaryKeys", args); + } + + public boolean exportedkeys(String line) + throws Exception + { + String[] strings = {conn().getCatalog(), null, "%"}; + List args = buildMetadataArgs(line, "table name", strings); + return metadata("getExportedKeys", args); + } + + public boolean importedkeys(String line) + throws Exception + { + String[] strings = {conn().getCatalog(), null, "%"}; + List args = buildMetadataArgs(line, "table name", strings); + return metadata("getImportedKeys", args); + } + + public boolean procedures(String line) + throws Exception + { + String[] strings = {conn().getCatalog(), null, "%"}; + List args = + buildMetadataArgs(line, "procedure name pattern", strings); + return metadata("getProcedures", args); + } + + public boolean tables(String line) + throws SQLException + { + String[] strings = {conn().getCatalog(), null, "%"}; + List args = buildMetadataArgs(line, "table name", strings); + args.add(null); + return metadata("getTables", args); + } + + public boolean typeinfo(String line) + throws Exception + { + return metadata("getTypeInfo", Collections.EMPTY_LIST); + } + + public boolean nativesql(String sql) + throws Exception + { + if (sql.startsWith(COMMAND_PREFIX)) { + sql = sql.substring(1); + } + + if (sql.startsWith("native")) { + sql = sql.substring("native".length() + 1); + } + + String nat = con().getConnection().nativeSQL(sql); + + output(nat); + + return true; + } + + public boolean columns(String line) throws SQLException + { + String[] strings = {conn().getCatalog(), null, "%"}; + List args = buildMetadataArgs(line, "table name", strings); + args.add("%"); + return metadata("getColumns", args); + } + + public boolean dropall(String line) + { + if ((con() == null) || (con().url == null)) { + return error(loc("no-current-connection")); + } + + try { + if (!(reader.readLine(loc("really-drop-all")).equals("y"))) { + return error("abort-drop-all"); + } + + List cmds = new LinkedList(); + ResultSet rs = getTables(); + try { + while (rs.next()) { + cmds.add( + "DROP TABLE " + + rs.getString("TABLE_NAME") + ";"); + } + } finally { + try { + rs.close(); + } catch (Exception e) { + } + } + + // run as a batch + return runCommands(cmds) == cmds.size(); + } catch (Exception e) { + return error(e); + } + } + + public boolean reconnect(String line) + { + if ((con() == null) || (con().url == null)) { + return error(loc("no-current-connection")); + } + + info(loc("reconnecting", con().url)); + try { + con().reconnect(); + } catch (Exception e) { + return error(e); + } + + return true; + } + + public boolean scan(String line) + throws IOException + { + TreeSet names = new TreeSet(); + + if (drivers == null) { + drivers = Arrays.asList(scanDrivers(line)); + } + + info(loc("drivers-found-count", drivers.size())); + + // unique the list + for (Iterator i = drivers.iterator(); i.hasNext();) { + names.add(((Driver) i.next()).getClass().getName()); + } + + output( + color().bold(color().pad(loc("compliant"), 10).getMono()) + .bold(color().pad(loc("jdbc-version"), 8).getMono()) + .bold(color(loc("driver-class")).getMono())); + + for (Iterator i = names.iterator(); i.hasNext();) { + String name = i.next().toString(); + + try { + Driver driver = (Driver) Class.forName(name).newInstance(); + ColorBuffer msg = + color().pad(driver.jdbcCompliant() ? "yes" : "no", 10) + .pad( + driver.getMajorVersion() + "." + + driver.getMinorVersion(), + 8).append(name); + if (driver.jdbcCompliant()) { + output(msg); + } else { + output(color().red(msg.getMono())); + } + } catch (Throwable t) { + output(color().red(name)); // error with driver + } + } + + return true; + } + + public boolean save(String line) + throws IOException + { + info(loc("saving-options", opts.rcFile)); + opts.save(); + return true; + } + + public boolean load(String line) + throws IOException + { + opts.load(); + info(loc("loaded-options", opts.rcFile)); + return true; + } + + public boolean config(String line) + { + try { + Properties props = opts.toProperties(); + Set keys = new TreeSet(props.keySet()); + for (Iterator i = keys.iterator(); i.hasNext();) { + String key = (String) i.next(); + output( + color().green( + color().pad( + key.substring( + opts.PROPERTY_PREFIX.length()), + 20).getMono()).append( + props.getProperty(key))); + } + } catch (Exception e) { + return error(e); + } + + return true; + } + + public boolean set(String line) + { + if ((line == null) + || line.trim().equals("set") + || (line.length() == 0)) + { + return config(null); + } + + String [] parts = split(line, 3, "Usage: set "); + if (parts == null) { + return false; + } + + String key = parts[1]; + String value = parts[2]; + boolean success = opts.set(key, value, false); + + // if we autosave, then save + if (success && opts.getAutosave()) { + try { + opts.save(); + } catch (Exception saveException) { + } + } + + return success; + } + + private void reportResult(String action, long start, long end) + { + if (opts.getShowTime()) { + info( + action + + " " + + loc( + "time-ms", + new Object[] { + new Double((end - start) / 1000d) + })); + } else { + info(action); + } + } + + public boolean commit(String line) + throws SQLException + { + if (!(assertConnection())) { + return false; + } + if (!(assertAutoCommit())) { + return false; + } + + try { + long start = System.currentTimeMillis(); + con().connection.commit(); + long end = System.currentTimeMillis(); + showWarnings(); + reportResult(loc("commit-complete"), start, end); + + return true; + } catch (Exception e) { + return error(e); + } + } + + public boolean rollback(String line) + throws SQLException + { + if (!(assertConnection())) { + return false; + } + if (!(assertAutoCommit())) { + return false; + } + + try { + long start = System.currentTimeMillis(); + con().connection.rollback(); + long end = System.currentTimeMillis(); + showWarnings(); + reportResult(loc("rollback-complete"), start, end); + return true; + } catch (Exception e) { + return error(e); + } + } + + public boolean autocommit(String line) + throws SQLException + { + if (!(assertConnection())) { + return false; + } + + if (line.endsWith("on")) { + con().connection.setAutoCommit(true); + } else if (line.endsWith("off")) { + con().connection.setAutoCommit(false); + } + + showWarnings(); + autocommitStatus(con().connection); + return true; + } + + public boolean dbinfo(String line) + { + if (!(assertConnection())) { + return false; + } + + showWarnings(); + int padlen = 50; + + String [] m = + new String[] { + "allProceduresAreCallable", + "allTablesAreSelectable", + "dataDefinitionCausesTransactionCommit", + "dataDefinitionIgnoredInTransactions", + "doesMaxRowSizeIncludeBlobs", + "getCatalogSeparator", + "getCatalogTerm", + "getDatabaseProductName", + "getDatabaseProductVersion", + "getDefaultTransactionIsolation", + "getDriverMajorVersion", + "getDriverMinorVersion", + "getDriverName", + "getDriverVersion", + "getExtraNameCharacters", + "getIdentifierQuoteString", + "getMaxBinaryLiteralLength", + "getMaxCatalogNameLength", + "getMaxCharLiteralLength", + "getMaxColumnNameLength", + "getMaxColumnsInGroupBy", + "getMaxColumnsInIndex", + "getMaxColumnsInOrderBy", + "getMaxColumnsInSelect", + "getMaxColumnsInTable", + "getMaxConnections", + "getMaxCursorNameLength", + "getMaxIndexLength", + "getMaxProcedureNameLength", + "getMaxRowSize", + "getMaxSchemaNameLength", + "getMaxStatementLength", + "getMaxStatements", + "getMaxTableNameLength", + "getMaxTablesInSelect", + "getMaxUserNameLength", + "getNumericFunctions", + "getProcedureTerm", + "getSchemaTerm", + "getSearchStringEscape", + "getSQLKeywords", + "getStringFunctions", + "getSystemFunctions", + "getTimeDateFunctions", + "getURL", + "getUserName", + "isCatalogAtStart", + "isReadOnly", + "nullPlusNonNullIsNull", + "nullsAreSortedAtEnd", + "nullsAreSortedAtStart", + "nullsAreSortedHigh", + "nullsAreSortedLow", + "storesLowerCaseIdentifiers", + "storesLowerCaseQuotedIdentifiers", + "storesMixedCaseIdentifiers", + "storesMixedCaseQuotedIdentifiers", + "storesUpperCaseIdentifiers", + "storesUpperCaseQuotedIdentifiers", + "supportsAlterTableWithAddColumn", + "supportsAlterTableWithDropColumn", + "supportsANSI92EntryLevelSQL", + "supportsANSI92FullSQL", + "supportsANSI92IntermediateSQL", + "supportsBatchUpdates", + "supportsCatalogsInDataManipulation", + "supportsCatalogsInIndexDefinitions", + "supportsCatalogsInPrivilegeDefinitions", + "supportsCatalogsInProcedureCalls", + "supportsCatalogsInTableDefinitions", + "supportsColumnAliasing", + "supportsConvert", + "supportsCoreSQLGrammar", + "supportsCorrelatedSubqueries", + "supportsDataDefinitionAndDataManipulationTransactions", + "supportsDataManipulationTransactionsOnly", + "supportsDifferentTableCorrelationNames", + "supportsExpressionsInOrderBy", + "supportsExtendedSQLGrammar", + "supportsFullOuterJoins", + "supportsGroupBy", + "supportsGroupByBeyondSelect", + "supportsGroupByUnrelated", + "supportsIntegrityEnhancementFacility", + "supportsLikeEscapeClause", + "supportsLimitedOuterJoins", + "supportsMinimumSQLGrammar", + "supportsMixedCaseIdentifiers", + "supportsMixedCaseQuotedIdentifiers", + "supportsMultipleResultSets", + "supportsMultipleTransactions", + "supportsNonNullableColumns", + "supportsOpenCursorsAcrossCommit", + "supportsOpenCursorsAcrossRollback", + "supportsOpenStatementsAcrossCommit", + "supportsOpenStatementsAcrossRollback", + "supportsOrderByUnrelated", + "supportsOuterJoins", + "supportsPositionedDelete", + "supportsPositionedUpdate", + "supportsSchemasInDataManipulation", + "supportsSchemasInIndexDefinitions", + "supportsSchemasInPrivilegeDefinitions", + "supportsSchemasInProcedureCalls", + "supportsSchemasInTableDefinitions", + "supportsSelectForUpdate", + "supportsStoredProcedures", + "supportsSubqueriesInComparisons", + "supportsSubqueriesInExists", + "supportsSubqueriesInIns", + "supportsSubqueriesInQuantifieds", + "supportsTableCorrelationNames", + "supportsTransactions", + "supportsUnion", + "supportsUnionAll", + "usesLocalFilePerTable", + "usesLocalFiles", + }; + + for (int i = 0; i < m.length; i++) { + try { + output( + color().pad(m[i], padlen).append( + "" + + Reflector.invoke( + con().meta, + m[i], + EMPTY_OBJ_ARRAY))); + } catch (Exception e) { + handleException(e); + } + } + + return true; + } + + public boolean verbose(String line) + { + info("verbose: on"); + return set("set verbose true"); + } + + public boolean outputformat(String line) + { + return set("set " + line); + } + + public boolean brief(String line) + { + info("verbose: off"); + return set("set verbose false"); + } + + public boolean isolation(String line) + throws SQLException + { + if (!(assertConnection())) { + return false; + } + + int i; + + if (line.endsWith("TRANSACTION_NONE")) { + i = Connection.TRANSACTION_NONE; + } else if (line.endsWith("TRANSACTION_READ_COMMITTED")) { + i = Connection.TRANSACTION_READ_COMMITTED; + } else if (line.endsWith("TRANSACTION_READ_UNCOMMITTED")) { + i = Connection.TRANSACTION_READ_UNCOMMITTED; + } else if (line.endsWith("TRANSACTION_REPEATABLE_READ")) { + i = Connection.TRANSACTION_REPEATABLE_READ; + } else if (line.endsWith("TRANSACTION_SERIALIZABLE")) { + i = Connection.TRANSACTION_SERIALIZABLE; + } else { + return error( + "Usage: isolation "); + } + + con().connection.setTransactionIsolation(i); + + int isol = con().connection.getTransactionIsolation(); + final String isoldesc; + switch (i) { + case Connection.TRANSACTION_NONE: + isoldesc = "TRANSACTION_NONE"; + break; + case Connection.TRANSACTION_READ_COMMITTED: + isoldesc = "TRANSACTION_READ_COMMITTED"; + break; + case Connection.TRANSACTION_READ_UNCOMMITTED: + isoldesc = "TRANSACTION_READ_UNCOMMITTED"; + break; + case Connection.TRANSACTION_REPEATABLE_READ: + isoldesc = "TRANSACTION_REPEATABLE_READ"; + break; + case Connection.TRANSACTION_SERIALIZABLE: + isoldesc = "TRANSACTION_SERIALIZABLE"; + break; + default: + isoldesc = "UNKNOWN"; + } + + info(loc("isolation-status", isoldesc)); + return true; + } + + public boolean batch(String line) + { + if (!(assertConnection())) { + return false; + } + + if (batch == null) { + batch = new LinkedList(); + info(loc("batch-start")); + return true; + } else { + info(loc("running-batch")); + try { + runBatch(batch); + return true; + } catch (Exception e) { + return error(e); + } finally { + batch = null; + } + } + } + + public boolean sql(String line) + { + return execute(line, false); + } + + public boolean call(String line) + { + return execute(line, true); + } + + private boolean execute(String line, boolean call) + { + if ((line == null) || (line.length() == 0)) { + return false; // ??? + } + + // ### FIXME: doing the multi-line handling down here means + // higher-level logic never sees the extra lines. So, + // for example, if a script is being saved, it won't include + // the continuation lines! This is logged as sf.net + // bug 879518. + + // use multiple lines for statements not terminated by ";" + try { + while (!(line.trim().endsWith(";"))) { + StringBuffer prompt = new StringBuffer(getPrompt()); + for (int i = 0; i < (prompt.length() - 1); i++) { + if (prompt.charAt(i) != '>') { + prompt.setCharAt(i, ((i % 2) == 0) ? '.' : ' '); + } + } + + String extra = reader.readLine(prompt.toString()); + if (!isComment(extra)) { + line += sep + extra; + } + } + } catch (Exception e) { + handleException(e); + } + + if (line.trim().endsWith(";")) { + line = line.trim(); + line = line.substring(0, line.length() - 1); + } + + if (!(assertConnection())) { + return false; + } + + String sql = line; + + if (sql.startsWith(COMMAND_PREFIX)) { + sql = sql.substring(1); + } + + String prefix = call ? "call" : "sql"; + + if (sql.startsWith(prefix)) { + sql = sql.substring(prefix.length()); + } + + // batch statements? + if (batch != null) { + batch.add(sql); + return true; + } + + try { + Statement stmnt = null; + boolean hasResults; + + try { + long start = System.currentTimeMillis(); + + if (call) { + stmnt = con().connection.prepareCall(sql); + hasResults = ((CallableStatement) stmnt).execute(); + } else { + stmnt = createStatement(); + hasResults = stmnt.execute(sql); + } + + showWarnings(); + showWarnings(stmnt.getWarnings()); + + if (hasResults) { + do { + ResultSet rs = stmnt.getResultSet(); + try { + int count = print(rs); + long end = System.currentTimeMillis(); + + reportResult( + loc("rows-selected", count), + start, + end); + } finally { + rs.close(); + } + } while (getMoreResults(stmnt)); + } else { + int count = stmnt.getUpdateCount(); + long end = System.currentTimeMillis(); + reportResult( + loc("rows-affected", count), + start, + end); + } + } finally { + if (stmnt != null) { + showWarnings(stmnt.getWarnings()); + stmnt.close(); + } + } + } catch (Exception e) { + return error(e); + } + + showWarnings(); + return true; + } + + public boolean quit(String line) + { + exit = true; + close(null); + return true; + } + + /** + * Close all connections. + */ + public boolean closeall(String line) + { + if (close(null)) { + while (close(null)) { + ; + } + return true; + } + + return false; + } + + /** + * Close the current connection. + */ + public boolean close(String line) + { + if (con() == null) { + return false; + } + + try { + if ((con().connection != null) + && !(con().connection.isClosed())) + { + info(loc("closing", + con().connection.getClass().getName())); + con().connection.close(); + } else { + info(loc("already-closed")); + } + } catch (Exception e) { + return error(e); + } + + connections.remove(); + return true; + } + + /** + * Connect to the database defined in the specified properties file. + */ + public boolean properties(String line) + throws Exception + { + String example = ""; + example += "Usage: properties " + sep; + + String [] parts = split(line); + if (parts.length < 2) { + return error(example); + } + + int successes = 0; + + for (int i = 1; i < parts.length; i++) { + Properties props = new Properties(); + props.load(new FileInputStream(parts[i])); + if (connect(props)) { + successes++; + } + } + + if (successes != (parts.length - 1)) { + return false; + } else { + return true; + } + } + + public boolean connect(String line) + throws Exception + { + String example = ""; + example += + "Usage: connect [driver]" + + sep; + + String [] parts = split(line); + if (parts == null) { + return false; + } + + if (parts.length < 2) { + return error(example); + } + + String url = (parts.length < 2) ? null : parts[1]; + String user = (parts.length < 3) ? null : parts[2]; + String pass = (parts.length < 4) ? null : parts[3]; + String driver = (parts.length < 5) ? null : parts[4]; + + Properties props = new Properties(); + if (url != null) { + props.setProperty("url", url); + } + if (driver != null) { + props.setProperty("driver", driver); + } + if (user != null) { + props.setProperty("user", user); + } + if (pass != null) { + props.setProperty("password", pass); + } + + return connect(props); + } + + private String getProperty(Properties props, String [] keys) + { + for (int i = 0; i < keys.length; i++) { + String val = props.getProperty(keys[i]); + if (val != null) { + return val; + } + } + + for (Iterator i = props.keySet().iterator(); i.hasNext();) { + String key = (String) i.next(); + for (int j = 0; j < keys.length; j++) { + if (key.endsWith(keys[j])) { + return props.getProperty(key); + } + } + } + + return null; + } + + public boolean connect(Properties props) + throws IOException + { + String url = + getProperty( + props, + new String[] { + "url", + "javax.jdo.option.ConnectionURL", + "ConnectionURL", + }); + String driver = + getProperty( + props, + new String[] { + "driver", + "javax.jdo.option.ConnectionDriverName", + "ConnectionDriverName", + }); + String username = + getProperty( + props, + new String[] { + "user", + "javax.jdo.option.ConnectionUserName", + "ConnectionUserName", + }); + String password = + getProperty( + props, + new String[] { + "password", + "javax.jdo.option.ConnectionPassword", + "ConnectionPassword", + }); + + if ((url == null) || (url.length() == 0)) { + return error("Property \"url\" is required"); + } + if ((driver == null) || (driver.length() == 0)) { + if (!scanForDriver(url)) { + return error(loc("no-driver", url)); + } + } + + info("Connecting to " + url); + + if (username == null) { + username = reader.readLine("Enter username for " + url + ": "); + } + if (password == null) { + password = + reader.readLine( + "Enter password for " + url + ": ", + new Character('*')); + } + + try { + // clear old completions + completions.clear(); + + connections.setConnection( + new DatabaseConnection(driver, url, username, password)); + con().getConnection(); + + setCompletions(); + return true; + } catch (SQLException sqle) { + return error(sqle); + } catch (IOException ioe) { + return error(ioe); + } + } + + public boolean rehash(String line) + { + try { + if (!(assertConnection())) { + return false; + } + + completions.clear(); + if (con() != null) { + con().setCompletions(false); + } + + return true; + } catch (Exception e) { + return error(e); + } + } + + /** + * List the current connections + */ + public boolean list(String line) + { + int index = 0; + info(loc("active-connections", connections.size())); + + for (Iterator i = connections.iterator(); i.hasNext(); index++) { + DatabaseConnection c = (DatabaseConnection) i.next(); + boolean closed = false; + try { + closed = c.connection.isClosed(); + } catch (Exception e) { + closed = true; + } + + output( + color().pad(" #" + index + "", 5) + .pad(closed ? loc("closed") : loc("open"), 9).append( + c.url)); + } + + return true; + } + + public boolean all(String line) + { + int index = connections.getIndex(); + + boolean success = true; + + for (int i = 0; i < connections.size(); i++) { + connections.setIndex(i); + output(loc("executing-con", con())); + + // ### FIXME: this is broken for multi-line SQL + success = sql(line.substring("all ".length())) && success; + } + + // restore index + connections.setIndex(index); + return success; + } + + public boolean go(String line) + { + String [] parts = split(line, 2, "Usage: go "); + if (parts == null) { + return false; + } + + int index = Integer.parseInt(parts[1]); + if (!(connections.setIndex(index))) { + error(loc("invalid-connection", "" + index)); + list(""); // list the current connections + return false; + } + + return true; + } + + /** + * Save or stop saving a script to a file + */ + public boolean script(String line) + { + if (script == null) { + return startScript(line); + } else { + return stopScript(line); + } + } + + /** + * Stop writing to the script file and close the script. + */ + private boolean stopScript(String line) + { + try { + script.close(); + } catch (Exception e) { + handleException(e); + } + + output(loc("script-closed", script)); + script = null; + return true; + } + + /** + * Start writing to the specified script file. + */ + private boolean startScript(String line) + { + if (script != null) { + return error(loc("script-already-running", script)); + } + + String [] parts = split(line, 2, "Usage: script "); + if (parts == null) { + return false; + } + + try { + script = new OutputFile(parts[1]); + output(loc("script-started", script)); + return true; + } catch (Exception e) { + return error(e); + } + } + + /** + * Run a script from the specified file. + */ + public boolean run(String line) + { + String [] parts = split(line, 2, "Usage: run "); + if (parts == null) { + return false; + } + + List cmds = new LinkedList(); + + try { + BufferedReader reader = + new BufferedReader(new FileReader( + parts[1])); + try { + // ### NOTE: fix for sf.net bug 879427 + StringBuffer cmd = null; + for (;;) { + String scriptLine = reader.readLine(); + + if (scriptLine == null) { + break; + } + + String trimmedLine = scriptLine.trim(); + if (opts.getTrimScripts()) { + scriptLine = trimmedLine; + } + + if (cmd != null) { + // we're continuing an existing command + cmd.append(" \n"); + cmd.append(scriptLine); + if (trimmedLine.endsWith(";")) { + // this command has terminated + cmds.add(cmd.toString()); + cmd = null; + } + } else { + // we're starting a new command + if (needsContinuation(scriptLine)) { + // multi-line + cmd = new StringBuffer(scriptLine); + } else { + // single-line + cmds.add(scriptLine); + } + } + } + + if (cmd != null) { + // ### REVIEW: oops, somebody left the last command + // unterminated; should we fix it for them or complain? + // For now be nice and fix it. + cmd.append(";"); + cmds.add(cmd.toString()); + } + } finally { + reader.close(); + } + + // success only if all the commands were successful + return runCommands(cmds) == cmds.size(); + } catch (Exception e) { + return error(e); + } + } + + /** + * Save or stop saving all output to a file. + */ + public boolean record(String line) + { + if (record == null) { + return startRecording(line); + } else { + return stopRecording(line); + } + } + + /** + * Stop writing output to the record file. + */ + private boolean stopRecording(String line) + { + try { + record.close(); + } catch (Exception e) { + handleException(e); + } + + output(loc("record-closed", record)); + record = null; + return true; + } + + /** + * Start writing to the specified record file. + */ + private boolean startRecording(String line) + { + if (record != null) { + return error(loc("record-already-running", record)); + } + + String [] parts = split(line, 2, "Usage: record "); + if (parts == null) { + return false; + } + + try { + record = new OutputFile(parts[1]); + output(loc("record-started", record)); + return true; + } catch (Exception e) { + return error(e); + } + } + + public boolean describe(String line) + throws SQLException + { + String[][] cmd = splitCompound(line); + if (cmd.length != 2) { + error("Usage: describe "); + return false; + } + + if (cmd[1].length == 1 + && cmd[1][0] != null + && cmd[1][0].equalsIgnoreCase("tables")) + { + return tables("tables"); + } else { + return columns(line); + } + } + + public boolean help(String line) + { + String [] parts = split(line); + String cmd = (parts.length > 1) ? parts[1] : ""; + TreeSet clist = new TreeSet(); + + for (int i = 0; i < commands.length; i++) { + if ((cmd.length() == 0) + || Arrays.asList(commands[i].getNames()).contains(cmd)) + { + clist.add( + color().pad("!" + commands[i].getName(), 20).append( + wrap(commands[i].getHelpText(), 60, 20))); + } + } + + for (Iterator i = clist.iterator(); i.hasNext();) { + output((ColorBuffer) i.next()); + } + + if (cmd.length() == 0) { + output(""); + output(loc("comments", getApplicationContactInformation())); + } + + return true; + } + + public boolean manual(String line) + throws IOException + { + InputStream in = SqlLine.class.getResourceAsStream("manual.txt"); + if (in == null) { + return error(loc("no-manual")); + } + + BufferedReader breader = + new BufferedReader(new InputStreamReader(in)); + String man; + int index = 0; + while ((man = breader.readLine()) != null) { + index++; + output(man); + + // silly little pager + if ((index % (opts.getMaxHeight() - 1)) == 0) { + String ret = reader.readLine(loc("enter-for-more")); + if ((ret != null) && ret.startsWith("q")) { + break; + } + } + } + + breader.close(); + + return true; + } + } + + /** + * Completor for SQLLine. It dispatches to sub-completors based on the + * current arguments. + * + * @author Marc Prud'hommeaux + */ + class SQLLineCompletor + implements Completor + { + public int complete(String buf, int pos, List cand) + { + if ((buf != null) + && buf.startsWith(COMMAND_PREFIX) + && !buf.startsWith(COMMAND_PREFIX + "all") + && !buf.startsWith(COMMAND_PREFIX + "sql")) + { + return sqlLineCommandCompletor.complete(buf, pos, cand); + } else { + if ((con() != null) && (con().sqlLineSQLCompletor != null)) { + return con().sqlLineSQLCompletor.complete(buf, pos, cand); + } else { + return -1; + } + } + } + } + + class SQLLineCommandCompletor + extends MultiCompletor + { + public SQLLineCommandCompletor() + { + List completors = new LinkedList(); + + for (int i = 0; i < commands.length; i++) { + String [] cmds = commands[i].getNames(); + for (int j = 0; (cmds != null) && (j < cmds.length); j++) { + Completor [] comps = commands[i].getParameterCompletors(); + List compl = new LinkedList(); + compl.add(new SimpleCompletor(COMMAND_PREFIX + cmds[j])); + compl.addAll(Arrays.asList(comps)); + compl.add(new NullCompletor()); // last param no complete + + completors.add( + new ArgumentCompletor( + (Completor []) compl.toArray(new Completor[0]))); + } + } + + setCompletors((Completor []) completors.toArray(new Completor[0])); + } + } + + class TableNameCompletor + implements Completor + { + public int complete(String buf, int pos, List cand) + { + if (con() == null) { + return -1; + } + + return new SimpleCompletor(con().getTableNames(true)).complete( + buf, + pos, + cand); + } + } + + class SQLLineSQLCompletor + extends SimpleCompletor + { + public SQLLineSQLCompletor(boolean skipmeta) + throws IOException, SQLException + { + super(new String[0]); + + Set completions = new TreeSet(); + + // add the default SQL completions + String keywords = + new BufferedReader( + new InputStreamReader( + SQLLineSQLCompletor.class.getResourceAsStream( + "sql-keywords.properties"))).readLine(); + + // now add the keywords from the current connection + + try { + keywords += "," + con().meta.getSQLKeywords(); + } catch (Throwable t) { + } + try { + keywords += "," + con().meta.getStringFunctions(); + } catch (Throwable t) { + } + try { + keywords += "," + con().meta.getNumericFunctions(); + } catch (Throwable t) { + } + try { + keywords += "," + con().meta.getSystemFunctions(); + } catch (Throwable t) { + } + try { + keywords += "," + con().meta.getTimeDateFunctions(); + } catch (Throwable t) { + } + + // also allow lower-case versions of all the keywords + keywords += "," + keywords.toLowerCase(); + + for ( + StringTokenizer tok = new StringTokenizer(keywords, ", "); + tok.hasMoreTokens(); + completions.add(tok.nextToken())) + { + ; + } + + // now add the tables and columns from the current connection + if (!(skipmeta)) { + String [] columns = getColumnNames(con().meta); + for ( + int i = 0; + (columns != null) + && (i < columns.length); + i++) + { + completions.add(columns[i++]); + } + } + + // set the Strings that will be completed + setCandidateStrings((String []) completions.toArray(new String[0])); + } + } + + private static class Connections + { + private final List connections = new ArrayList(); + private int index = -1; + + public SqlLine.DatabaseConnection current() + { + if (index != -1) { + return (SqlLine.DatabaseConnection) connections.get(index); + } + + return null; + } + + public int size() + { + return connections.size(); + } + + public Iterator iterator() + { + return connections.iterator(); + } + + public void remove() + { + if (index != -1) { + connections.remove(index); + } + + while (index >= connections.size()) { + index--; + } + } + + public void addConnection(SqlLine.DatabaseConnection connection) + { + connections.add(connection); + } + + public void setConnection(SqlLine.DatabaseConnection connection) + { + if (connections.indexOf(connection) == -1) { + connections.add(connection); + } + + index = connections.indexOf(connection); + } + + public int getIndex() + { + return index; + } + + public boolean setIndex(int index) + { + if ((index < 0) || (index >= connections.size())) { + return false; + } + + this.index = index; + return true; + } + } + + private class DatabaseConnection + { + Connection connection; + DatabaseMetaData meta; + Quoting quoting; + private final String driver; + private final String url; + private final String username; + private final String password; + private Schema schema = null; + private Completor sqlLineSQLCompletor = null; + + public DatabaseConnection( + String driver, + String url, + String username, + String password) + throws SQLException + { + this.driver = driver; + this.url = url; + this.username = username; + this.password = password; + } + + public String toString() + { + return url + ""; + } + + private void setCompletions(boolean skipmeta) + throws SQLException, IOException + { + // Deduce the string used to quote identifiers. For example, Oracle + // uses double-quotes: + // SELECT * FROM "My Schema"."My Table" + String startQuote = meta.getIdentifierQuoteString(); + final boolean upper = meta.storesUpperCaseIdentifiers(); + if (startQuote == null + || startQuote.equals("") + || startQuote.equals(" ")) + { + if (meta.getDatabaseProductName().startsWith("MySQL")) { + // Some version of the MySQL JDBC driver lie. + quoting = new Quoting('`', '`', upper); + } else { + quoting = new Quoting((char) 0, (char) 0, false); + } + } else if (startQuote.equals("[")) { + quoting = new Quoting('[', ']', upper); + } else if (startQuote.length() > 1) { + error( + "Identifier quote string is '" + startQuote + + "'; quote strings longer than 1 char are not supported"); + quoting = Quoting.DEFAULT; + } else { + quoting = + new Quoting( + startQuote.charAt(0), startQuote.charAt(0), upper); + } + + final String extraNameCharacters = + ((meta == null) || (meta.getExtraNameCharacters() == null)) ? "" + : meta.getExtraNameCharacters(); + + // setup the completor for the database + sqlLineSQLCompletor = + new ArgumentCompletor( + new SQLLineSQLCompletor(skipmeta), + new ArgumentCompletor.AbstractArgumentDelimiter() { + // delimiters for SQL statements are any + // non-letter-or-number characters, except + // underscore and characters that are specified + // by the database to be valid name identifiers. + public boolean isDelimiterChar(String buf, int pos) + { + char c = buf.charAt(pos); + if (Character.isWhitespace(c)) { + return true; + } + + return !(Character.isLetterOrDigit(c)) + && (c != '_') + && (extraNameCharacters.indexOf(c) == -1); + } + }); + + // not all argument elements need to hold true + ((ArgumentCompletor) sqlLineSQLCompletor).setStrict(false); + } + + /** + * Connection to the specified data source. + */ + boolean connect() + throws SQLException + { + try { + if ((driver != null) && (driver.length() != 0)) { + Class.forName(driver); + } + } catch (ClassNotFoundException cnfe) { + return error(cnfe); + } + + boolean foundDriver = false; + Driver theDriver = null; + try { + theDriver = DriverManager.getDriver(url); + foundDriver = theDriver != null; + } catch (Exception e) { + } + + if (!(foundDriver)) { + output(loc("autoloading-known-drivers", url)); + registerKnownDrivers(); + } + + try { + close(); + } catch (Exception e) { + return error(e); + } + + // Avoid using DriverManager.getConnection(). It is a synchronized + // method and thus holds the lock while making the connection. + // Deadlock can occur if the driver's connection processing uses any + // synchronized DriverManager methods. One such example is the + // RMI-JDBC driver, whose RJDriverServer.connect() method uses + // DriverManager.getDriver(). Because RJDriverServer.connect runs in + // a different thread (RMI) than the getConnection() caller (here), + // this sequence will hang every time. + + //connection = DriverManager.getConnection (url, username, + //password); + + // Instead, we use the driver instance to make the connection + + final Properties info = new Properties(); + info.put("user", username); + info.put("password", password); + connection = theDriver.connect(url, info); + meta = connection.getMetaData(); + + try { + info( + loc("connected", + new Object[] { + meta.getDatabaseProductName(), + meta.getDatabaseProductVersion() + })); + } catch (Exception e) { + handleException(e); + } + + try { + info( + loc("driver", + new Object[] { + meta.getDriverName(), + meta.getDriverVersion() + })); + } catch (Exception e) { + handleException(e); + } + + try { + connection.setAutoCommit(opts.getAutoCommit()); + autocommitStatus(connection); + } catch (Exception e) { + handleException(e); + } + + try { + command.isolation("isolation: " + opts.getIsolation()); + } catch (Exception e) { + handleException(e); + } + + showWarnings(); + + return true; + } + + public Connection getConnection() + throws SQLException + { + if (connection != null) { + return connection; + } + + connect(); + + return connection; + } + + public void reconnect() + throws Exception + { + close(); + getConnection(); + } + + public void close() + { + try { + try { + if ((connection != null) && !connection.isClosed()) { + output(loc("closing", connection)); + connection.close(); + } + } catch (Exception e) { + handleException(e); + } + } finally { + connection = null; + meta = null; + } + } + + public String [] getTableNames(boolean force) + { + Schema.Table [] t = getSchema().getTables(); + Set names = new TreeSet(); + for (int i = 0; (t != null) && (i < t.length); i++) { + names.add(t[i].getName()); + } + return (String []) names.toArray(new String[names.size()]); + } + + Schema getSchema() + { + if (schema == null) { + schema = new Schema(); + } + + return schema; + } + + class Schema + { + private Table [] tables = null; + + Table [] getTables() + { + if (tables != null) { + return tables; + } + + List tnames = new LinkedList(); + + try { + ResultSet rs = + meta.getTables( + connection.getCatalog(), + null, + "%", + new String[] { "TABLE" }); + try { + while (rs.next()) { + tnames.add(new Table( + rs.getString("TABLE_NAME"))); + } + } finally { + try { + rs.close(); + } catch (Exception e) { + } + } + } catch (Throwable t) { + } + + return tables = (Table []) tnames.toArray(new Table[0]); + } + + Table getTable(String name) + { + Table [] t = getTables(); + for (int i = 0; (t != null) && (i < t.length); i++) { + if (name.equalsIgnoreCase(t[i].getName())) { + return t[i]; + } + } + + return null; + } + + class Table + { + final String name; + Column [] columns; + + public Table(String name) + { + this.name = name; + } + + public String getName() + { + return name; + } + + class Column + { + final String name; + boolean isPrimaryKey; + + public Column(String name) + { + this.name = name; + } + } + } + } + } + + class Opts + implements Completor + { + public static final String PROPERTY_PREFIX = "sqlline."; + public static final String PROPERTY_NAME_EXIT = + PROPERTY_PREFIX + "system.exit"; + private boolean autosave = false; + private boolean silent = false; + private boolean color = false; + private boolean showHeader = true; + private int headerInterval = 100; + private boolean fastConnect = true; + private boolean autoCommit = true; + private boolean verbose = false; + private boolean force = false; + private boolean incremental = false; + private boolean showTime = true; + private boolean showWarnings = true; + private boolean showNestedErrs = false; + private String numberFormat = "default"; + private int maxWidth = Terminal.setupTerminal().getTerminalWidth(); + private int maxHeight = Terminal.setupTerminal().getTerminalHeight(); + private int maxColumnWidth = 15; + private int rowLimit = 0; + private int timeout = -1; + private String isolation = "TRANSACTION_REPEATABLE_READ"; + private String outputFormat = "table"; + private boolean trimScripts = true; + + private File rcFile = new File(saveDir(), "sqlline.properties"); + private String historyFile = + new File(saveDir(), "history").getAbsolutePath(); + + private String runFile; + + public Opts(Properties props) + { + loadProperties(props); + } + + public Completor [] optionCompletors() + { + return new Completor[] { + this, + // new SimpleCompletor (possibleSettingValues ()), + }; + } + + public String [] possibleSettingValues() + { + List vals = new LinkedList(); + vals.addAll(Arrays.asList( + new String[] { + "yes", + "no", + })); + + return (String []) vals.toArray(new String[vals.size()]); + } + + /** + * The save directory if HOME/.sqlline/ on UNIX, and HOME/sqlline/ on + * Windows. + */ + public File saveDir() + { + String dir = System.getProperty("sqlline.rcfile"); + if ((dir != null) && (dir.length() > 0)) { + return new File(dir); + } + + File f = + new File( + System.getProperty("user.home"), + ((System.getProperty("os.name").toLowerCase().indexOf( + "windows") != -1) ? "" : ".") + "sqlline") + .getAbsoluteFile(); + try { + f.mkdirs(); + } catch (Exception e) { + } + + return f; + } + + public int complete(String buf, int pos, List cand) + { + try { + return new SimpleCompletor(propertyNames()).complete( + buf, + pos, + cand); + } catch (Throwable t) { + return -1; + } + } + + public void save() + throws IOException + { + OutputStream out = new FileOutputStream(rcFile); + save(out); + out.close(); + } + + public void save(OutputStream out) + throws IOException + { + try { + Properties props = toProperties(); + + // don't save maxwidth: it is automatically set based on + // the terminal configuration + props.remove(PROPERTY_PREFIX + "maxwidth"); + + props.store(out, getApplicationTitle()); + } catch (Exception e) { + handleException(e); + } + } + + String [] propertyNames() + throws IllegalAccessException, InvocationTargetException + { + TreeSet names = new TreeSet(); + + // get all the values from getXXX methods + Method [] m = getClass().getDeclaredMethods(); + for (int i = 0; (m != null) && (i < m.length); i++) { + if (!(m[i].getName().startsWith("get"))) { + continue; + } + + if (m[i].getParameterTypes().length != 0) { + continue; + } + + String propName = m[i].getName().substring(3).toLowerCase(); + if (propName.equals("run")) { + // Not a real property + continue; + } + names.add(propName); + } + + return (String []) names.toArray(new String[names.size()]); + } + + public Properties toProperties() + throws IllegalAccessException, + InvocationTargetException, + ClassNotFoundException + { + Properties props = new Properties(); + + String [] names = propertyNames(); + for (int i = 0; (names != null) && (i < names.length); i++) { + props.setProperty( + PROPERTY_PREFIX + names[i], + Reflector.invoke(this, "get" + names[i], EMPTY_OBJ_ARRAY) + .toString()); + } + + debug("properties: " + props.toString()); + return props; + } + + public void load() + throws IOException + { + InputStream in = new FileInputStream(rcFile); + load(in); + in.close(); + } + + public void load(InputStream fin) + throws IOException + { + Properties p = new Properties(); + p.load(fin); + loadProperties(p); + } + + public void loadProperties(Properties props) + { + for (Iterator i = props.keySet().iterator(); i.hasNext();) { + String key = i.next().toString(); + if (key.equals(PROPERTY_NAME_EXIT)) { + // fix for sf.net bug 879422 + continue; + } + if (key.startsWith(PROPERTY_PREFIX)) { + set( + key.substring(PROPERTY_PREFIX.length()), + props.getProperty(key)); + } + } + } + + public void set(String key, String value) + { + set(key, value, false); + } + + public boolean set(String key, String value, boolean quiet) + { + try { + Reflector.invoke(this, "set" + key, new Object[] { value }); + return true; + } catch (Exception e) { + if (!quiet) { + error(loc("error-setting", new Object[] { key, e })); + } + return false; + } + } + + public void setFastConnect(boolean fastConnect) + { + this.fastConnect = fastConnect; + } + + public boolean getFastConnect() + { + return this.fastConnect; + } + + public void setAutoCommit(boolean autoCommit) + { + this.autoCommit = autoCommit; + } + + public boolean getAutoCommit() + { + return this.autoCommit; + } + + public void setVerbose(boolean verbose) + { + this.verbose = verbose; + } + + public boolean getVerbose() + { + return this.verbose; + } + + public void setShowTime(boolean showTime) + { + this.showTime = showTime; + } + + public boolean getShowTime() + { + return this.showTime; + } + + public void setShowWarnings(boolean showWarnings) + { + this.showWarnings = showWarnings; + } + + public boolean getShowWarnings() + { + return this.showWarnings; + } + + public void setShowNestedErrs(boolean showNestedErrs) + { + this.showNestedErrs = showNestedErrs; + } + + public boolean getShowNestedErrs() + { + return this.showNestedErrs; + } + + public void setNumberFormat(String numberFormat) + { + this.numberFormat = numberFormat; + } + + public String getNumberFormat() + { + return this.numberFormat; + } + + public void setMaxWidth(int maxWidth) + { + this.maxWidth = maxWidth; + } + + public int getMaxWidth() + { + return this.maxWidth; + } + + public void setMaxColumnWidth(int maxColumnWidth) + { + this.maxColumnWidth = maxColumnWidth; + } + + public int getMaxColumnWidth() + { + return this.maxColumnWidth; + } + + public void setRowLimit(int rowLimit) + { + this.rowLimit = rowLimit; + } + + public int getRowLimit() + { + return this.rowLimit; + } + + public void setTimeout(int timeout) + { + this.timeout = timeout; + } + + public int getTimeout() + { + return this.timeout; + } + + public void setIsolation(String isolation) + { + this.isolation = isolation; + } + + public String getIsolation() + { + return this.isolation; + } + + public void setHistoryFile(String historyFile) + { + this.historyFile = historyFile; + } + + public String getHistoryFile() + { + return this.historyFile; + } + + public void setColor(boolean color) + { + this.color = color; + } + + public boolean getColor() + { + return this.color; + } + + public void setShowHeader(boolean showHeader) + { + this.showHeader = showHeader; + } + + public boolean getShowHeader() + { + return this.showHeader; + } + + public void setHeaderInterval(int headerInterval) + { + this.headerInterval = headerInterval; + } + + public int getHeaderInterval() + { + return this.headerInterval; + } + + public void setForce(boolean force) + { + this.force = force; + } + + public boolean getForce() + { + return this.force; + } + + public void setIncremental(boolean incremental) + { + this.incremental = incremental; + } + + public boolean getIncremental() + { + return this.incremental; + } + + public void setSilent(boolean silent) + { + this.silent = silent; + } + + public boolean getSilent() + { + return this.silent; + } + + public void setAutosave(boolean autosave) + { + this.autosave = autosave; + } + + public boolean getAutosave() + { + return this.autosave; + } + + public void setOutputFormat(String outputFormat) + { + this.outputFormat = outputFormat; + } + + public String getOutputFormat() + { + return this.outputFormat; + } + + public void setTrimScripts(boolean trimScripts) + { + this.trimScripts = trimScripts; + } + + public boolean getTrimScripts() + { + return this.trimScripts; + } + + public void setMaxHeight(int maxHeight) + { + this.maxHeight = maxHeight; + } + + public int getMaxHeight() + { + return this.maxHeight; + } + + public void setRun(String runFile) + { + this.runFile = runFile; + } + + public String getRun() + { + return this.runFile; + } + } + + static class Reflector + { + public static Object invoke(Object on, String method, Object [] args) + throws InvocationTargetException, + IllegalAccessException, + ClassNotFoundException + { + return invoke(on, method, Arrays.asList(args)); + } + + public static Object invoke(Object on, String method, List args) + throws InvocationTargetException, + IllegalAccessException, + ClassNotFoundException + { + return invoke( + on, + (on == null) ? null : on.getClass(), + method, + args); + } + + public static Object invoke( + Object on, + Class defClass, + String method, + List args) + throws InvocationTargetException, + IllegalAccessException, + ClassNotFoundException + { + Class c = (defClass != null) ? defClass : on.getClass(); + List candidateMethods = new LinkedList(); + + Method [] m = c.getMethods(); + for (int i = 0; i < m.length; i++) { + if (m[i].getName().equalsIgnoreCase(method)) { + candidateMethods.add(m[i]); + } + } + + if (candidateMethods.size() == 0) { + throw new IllegalArgumentException( + loc("no-method", new Object[] { method, c.getName() })); + } + + for (Iterator i = candidateMethods.iterator(); i.hasNext();) { + Method meth = (Method) i.next(); + Class [] ptypes = meth.getParameterTypes(); + if (!(ptypes.length == args.size())) { + continue; + } + + Object [] converted = convert(args, ptypes); + if (converted == null) { + continue; + } + + if (!Modifier.isPublic(meth.getModifiers())) { + continue; + } + + return meth.invoke(on, converted); + } + + return null; + } + + public static Object [] convert(List objects, Class [] toTypes) + throws ClassNotFoundException + { + Object [] converted = new Object[objects.size()]; + for (int i = 0; i < converted.length; i++) { + converted[i] = convert(objects.get(i), toTypes[i]); + } + return converted; + } + + public static Object convert(Object ob, Class toType) + throws ClassNotFoundException + { + if ((ob == null) || ob.toString().equals("null")) { + return null; + } + + if (toType == String.class) { + return new String(ob.toString()); + } else if ((toType == Byte.class) || (toType == byte.class)) { + return new Byte(ob.toString()); + } else if ((toType == Character.class) || (toType == char.class)) { + return new Character(ob.toString().charAt(0)); + } else if ((toType == Short.class) || (toType == short.class)) { + return new Short(ob.toString()); + } else if ((toType == Integer.class) || (toType == int.class)) { + return new Integer(ob.toString()); + } else if ((toType == Long.class) || (toType == long.class)) { + return new Long(ob.toString()); + } else if ((toType == Double.class) || (toType == double.class)) { + return new Double(ob.toString()); + } else if ((toType == Float.class) || (toType == float.class)) { + return new Float(ob.toString()); + } else if ((toType == Boolean.class) || (toType == boolean.class)) { + return new Boolean( + ob.toString().equals("true") + || ob.toString().equals(true + "") + || ob.toString().equals("1") + || ob.toString().equals("on") + || ob.toString().equals("yes")); + } else if (toType == Class.class) { + return Class.forName(ob.toString()); + } + + return null; + } + } + + public class OutputFile + { + final File file; + final PrintWriter out; + + public OutputFile(String filename) + throws IOException + { + file = new File(filename); + out = new PrintWriter(new FileWriter(file)); + } + + public String toString() + { + return file.getAbsolutePath(); + } + + public void addLine(String command) + { + out.println(command); + } + + public void close() + throws IOException + { + out.close(); + } + } + + static class DriverInfo + { + public String sampleURL; + + public DriverInfo(String name) + throws IOException + { + Properties props = new Properties(); + props.load(DriverInfo.class.getResourceAsStream(name)); + fromProperties(props); + } + + public DriverInfo(Properties props) + { + fromProperties(props); + } + + public void fromProperties(Properties props) + { + } + } + + /** + * Quoting strategy. + */ + private static class Quoting + { + private final char start; + private final char end; + private final boolean upper; + + Quoting(char start, char end, boolean upper) + { + this.start = start; + this.end = end; + this.upper = upper; + } + + public static final Quoting DEFAULT = new Quoting('"', '"', true); + } +} + +// End SqlLine.java + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired to `historyIn` by call to `FileInputStream(...)` at line 765 is not released after line 774. +**Note**: potential exception at line 768 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +ConsoleReader SqlLine.getConsoleReader(InputStream) + +### Procedure Id: +sqlline.SqlLine.getConsoleReader(java.io.InputStream):jline.ConsoleReader.20fe57b448e0f25f0131ff5c7f40163b + +### File: +src/main/java/sqlline/SqlLine.java + +### Key: +SqlLine.java|getConsoleReader|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +8e11f6f09017362a41f057fe28491953 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8106/instruction.md b/inferredbugs-8106/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b7e43cccb1d8e7abb111b7e77e120f3d96313bdd --- /dev/null +++ b/inferredbugs-8106/instruction.md @@ -0,0 +1,2662 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sqlline +**Bug ID:** 21 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +// Licensed to Julian Hyde under one or more contributor license +// agreements. See the NOTICE file distributed with this work for +// additional information regarding copyright ownership. +// +// Julian Hyde licenses this file to you under the Modified BSD License +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/BSD-3-Clause +*/ +package sqlline; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.h2.util.StringUtils; +import org.hamcrest.BaseMatcher; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hsqldb.jdbc.CustomDatabaseMetadata; +import org.hsqldb.jdbc.JDBCConnection; +import org.hsqldb.jdbc.JDBCDatabaseMetaData; +import org.hsqldb.jdbc.JDBCResultSet; +import org.hsqldb.jdbc.JDBCResultSetMetaData; +import org.jline.builtins.Commands; +import org.jline.terminal.Terminal; +import org.junit.jupiter.api.Test; + +import mockit.Expectations; +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.internal.reflection.FieldReflection; +import net.hydromatic.scott.data.hsqldb.ScottHsqldb; +import sqlline.extensions.CustomApplication; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Executes tests of the command-line arguments to SqlLine. + */ +public class SqlLineArgsTest { + private static final ConnectionSpec CONNECTION_SPEC = ConnectionSpec.HSQLDB; + private ConnectionSpec connectionSpec; + + public SqlLineArgsTest() { + connectionSpec = CONNECTION_SPEC; + } + + static SqlLine.Status begin(SqlLine sqlLine, OutputStream os, + boolean saveHistory, String... args) { + try { + PrintStream beelineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(beelineOutputStream); + sqlLine.setErrorStream(beelineOutputStream); + final InputStream is = new ByteArrayInputStream(new byte[0]); + return sqlLine.begin(args, is, saveHistory); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Execute a script with "beeline -f". + * + * @return The stderr and stdout from running the script + * @param args Script arguments + */ + private static Pair run(String... args) { + try { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = begin(beeLine, os, false, args); + return new Pair(status, os.toString("UTF8")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + private Pair runScript(File scriptFile, boolean flag, String outputFileName) { + return runScript(connectionSpec, scriptFile, flag, outputFileName); + } + + private static Pair runScript(ConnectionSpec connectionSpec, File scriptFile, + boolean flag, String outputFileName) { + List args = new ArrayList<>(); + Collections.addAll(args, + "-d", connectionSpec.driver, + "-u", connectionSpec.url, + "-n", connectionSpec.username, + "-p", connectionSpec.password); + if (flag) { + args.add("-f"); + args.add(scriptFile.getAbsolutePath()); + } else { + args.add("--run=" + scriptFile.getAbsolutePath()); + } + if (outputFileName != null) { + args.add("-log"); + args.add(outputFileName); + } + return run(args.toArray(new String[0])); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * Tests for presence of an expected pattern in the output (stdout or stderr). + * + * @param scriptText Script text + * @param flag Command flag (--run or -f) + * @param statusMatcher Checks whether status is as expected + * @param outputMatcher Checks whether output is as expected + */ + private void checkScriptFile(String scriptText, boolean flag, + Matcher statusMatcher, + Matcher outputMatcher) { + try { + // Put the script content in a temp file + File scriptFile = createTempFile("foo", "temp"); + PrintStream os = + new PrintStream( + new FileOutputStream(scriptFile), + false, + StandardCharsets.UTF_8.name()); + os.print(scriptText); + os.close(); + + Pair pair = runScript(scriptFile, flag, null); + + // Check output before status. It gives a better clue what went wrong. + assertThat(toLinux(pair.output), outputMatcher); + assertThat(pair.status, statusMatcher); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Windows line separators in a string into Linux line separators; + * a Linux string is unchanged. */ + private static String toLinux(String s) { + return s.replaceAll("\r\n", "\n"); + } + + private File createTempFile(String prefix, String suffix) { + return createTempFile(prefix, suffix, null); + } + + private File createTempFile(String prefix, String suffix, Path directory) { + try { + final File file = directory == null + ? Files.createTempFile(prefix, suffix).toFile() + : Files.createTempFile(directory, prefix, suffix).toFile(); + file.deleteOnExit(); + return file; + } catch (IOException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMultilineScriptWithComments() { + final String script1Text = + "!set incremental true\n" + + "-- a comment \n values\n--comment\n (\n1\n, ' ab'\n--comment\n)\n;\n"; + + checkScriptFile(script1Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-------------+-----+\n" + + "| C1 | C2 |\n" + + "+-------------+-----+\n" + + "| 1 | ab |\n" + + "+-------------+-----+")); + + final String script2Text = + "!set incremental true\n" + + "--comment \n --comment2 \nvalues (';\n' /* comment */, '\"'" + + "/*multiline;\n ;\n comment*/)\n -- ; \n; -- comment"; + + checkScriptFile(script2Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-----+----+\n" + + "| C1 | C2 |\n" + + "+-----+----+\n" + + "| ; \n" + + " | \" |\n" + + "+-----+----+")); + } + + /** + * Attempt to execute a simple script file with the -f option to SqlLine. + * Test for presence of an expected pattern + * in the output (stdout or stderr), fail if not found. + */ + @Test + public void testPositiveScriptFile() { + checkScriptFile("call 100 + 23;\n", + true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * As above, but using '-run' rather than '-f'. + */ + @Test + public void testPositiveScriptFileUsingRun() { + checkScriptFile("call 100 + 23;\n", + false, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * Test case for + * [SQLLINE-42], + * Script fails if first line is a comment. + */ + @Test + public void testScriptFileStartsWithComment() { + final String scriptText = "-- a comment\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileStartsWithEmptyLine() { + final String scriptText = "\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileContainsComment() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithComments() { + final String scriptText = "--comment\n\n" + + "values \n10 \n+ \n23;\n\n\n" + + "-- a comment\n" + + "\n\nvalues " + + "--comment inside\n\n" + + "100 --comment inside\n\n" + + "+ \n\n23\n\n\n;\n\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithMultilineQuotedStrings() { + final String scriptText = "--comment\n\n" + + "values '\nmultiline;\n;\n; string\n'" + + ";\n\n\n" + + "values '\nmultiline2;\n;\n; string2\n'" + + ";\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString("multiline2;"), containsString("; string2"))); + } + + @Test + public void testScriptWithMultilineStatementsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment\n\n" + + "values 1;values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 1 |\n" + + "+----+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + + @Test + public void testScriptWithMultilineStatementsAndCommentsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment;;\n\n" + + "select * from (values ';') t (\";\");/*;select 1;*/values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+---+\n" + + "| ; |\n" + + "+---+\n" + + "| ; |\n" + + "+---+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + /** + * Tests sql with H2 specific one-line comment '//' + */ + @Test + public void testMultilineScriptWithH2Comments() { + final SqlLine sqlLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + final File tmpHistoryFile = createTempFile("queryToExecute", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + final String script = "\n" + + "\n" + + "!set incremental true\n" + + "\n" + + "\n" + + "select * from information_schema.tables// ';\n" + + "// \";" + + ";\n" + + "\n" + + "\n"; + bw.write(script); + bw.flush(); + } + SqlLine.Status status = + begin(sqlLine, os, false, + "-u", ConnectionSpec.H2.url, + "-n", ConnectionSpec.H2.username, + "--run=" + tmpHistoryFile.getAbsolutePath()); + assertThat(status, equalTo(SqlLine.Status.OK)); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |" + + " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |"; + assertThat(output, containsString(expected)); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-72] + * Allow quoted file names (including spaces) in !record, + * !run and !script commands. */ + @Test + public void testScriptFilenameWithSpace() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23;\n"; + File scriptFile = createTempFile("Script with Spaces", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + allOf(containsString(" 33 "), containsString(" 123 "))); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScriptWithOutput() { + final String scriptText = "!set maxcolumnwidth 20\n" + + "!set incremental true\n" + + "values 100 + 123;\n" + + "-- a comment\n" + + "values 100 + 253;\n"; + + File scriptFile = createTempFile("Script file name", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + + File outputFile = createTempFile("testScriptWithOutput", ".out"); + runScript(scriptFile, true, outputFile.getAbsolutePath()); + assertFileContains(outputFile, + allOf(containsString("| 223 |"), + containsString("| 353 |"))); + final boolean delete = outputFile.delete(); + assertThat(delete, is(true)); + } + + /** + * Values that contain null. + */ + @Test + public void testNull() { + final String script = "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString( + "+-------------+-------------+-----+\n" + + "| C1 | C2 | C3 |\n" + + "+-------------+-------------+-----+\n" + + "| 1 | null | |\n" + + "+-------------+-------------+-----+\n")); + } + + @Test + public void testScan() { + final String expectedLine0 = "Compliant Version Driver Class"; + final String expectedLine1 = "yes 2.4 org.hsqldb.jdbc.JDBCDriver"; + checkScriptFile("!scan\n", false, + equalTo(SqlLine.Status.OK), + allOf(containsString(expectedLine0), containsString(expectedLine1))); + } + + /** + * Table output without header. + */ + @Test + public void testTableOutputNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("| 1 | null | |\n")); + } + + /** + * Csv output without header. + */ + @Test + public void testCsvNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set outputformat csv\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("'1','null',''\n")); + } + + /** + * Tests the "close" command, + * [HIVE-5768] + * Beeline connection cannot be closed with '!close' command and + * [SQLLINE-139] + * Look for the exact match if there are multiple matches. + */ + @Test + public void testClose() { + final String expected = "!close\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile("!close\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + /** + * Test case for + * [SQLLINE-32] + * !help set' should print documentation for all variables. + */ + @Test + public void testHelpSet() { + final String expected = "1/1 !help set\n" + + "!set List / set a sqlline variable\n" + + "\n" + + "Variables:\n" + + "\n" + + "Variable Value Description\n" + + "=============== ========== " + + "==================================================\n" + + "autoCommit true/false " + + "Enable/disable automatic transaction commit\n" + + "autoSave true/false Automatically save preferences\n"; + checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + + // Make sure that each variable (autoCommit, autoSave, color, etc.) has a + // line in the output of '!help set' + final SqlLine sqlLine = new SqlLine(); + String help = sqlLine.loc("help-set") + + sqlLine.loc("variables"); + + final TreeSet propertyNamesMixed = + Arrays.stream(BuiltInProperty.values()) + .map(BuiltInProperty::propertyName) + .collect(Collectors.toCollection(TreeSet::new)); + for (String p : propertyNamesMixed) { + assertThat(help, containsString("\n" + p + " ")); + } + assertThat(propertyNamesMixed.contains("autoCommit"), + is(true)); + assertThat(propertyNamesMixed.contains("autocommit"), + is(false)); + assertThat(propertyNamesMixed.contains("trimScripts"), + is(true)); + + while (help.length() > 0) { + int i = help.indexOf("\n", 1); + if (i < 0) { + break; + } + if (i > 78) { + fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i)); + } + help = help.substring(i); + } + } + + /** + * Test case for + * [SQLLINE-39] + * 'help set' should not break long lines. + * + *

    But it should break 'help all', which consists of a single long line. + */ + @Test + public void testHelpAll() { + // Note that "connections" has been broken onto a new line. + final String expected = "1/1 !help all\n" + + "!all Execute the specified SQL against all the current\n" + + " connections\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help all\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + + /** + * Tests "!go <non-existent connection indexes>". + */ + @Test + public void testGoFailing() { + final String[] connectionIndexes = {"321", "invalid"}; + for (String connectionIndex : connectionIndexes) { + final String script = "!go " + connectionIndex + "\n"; + final String expected = "Invalid connection: " + connectionIndex; + checkScriptFile(script, false, + // Status.OTHER as checking of fail cases + equalTo(SqlLine.Status.OTHER), containsString(expected)); + } + } + + /** + * Tests "!help go". "go" and "#" are synonyms. + */ + @Test + public void testHelpGo() { + for (String c : new String[] {"go", "#"}) { + final String expected = "1/1 !help " + c + "\n" + + "!go Select the current connection\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help " + c + "\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + } + + /** + * Test case for + * !?, !# + * and other one-symbol length commands stopped working + * + *

    '!?' should work in the same way as '!help'. + */ + @Test + public void testHelpAsQuestionMark() { + final String script = "!?\n"; + final String expected = + "!autocommit Set autocommit mode on or off"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + allOf(not(containsString("Unknown command: ?")), + containsString(expected))); + } + + /** + * Test case for + * [SQLLINE-49] + * !manual command fails. + */ + @Test + public void testManual() { + final String expectedLine = "sqlline version"; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + new MockUp() { + @Mock + void less(Terminal terminal, InputStream in, PrintStream out, + PrintStream err, Path currentDir, String[] argv) { + } + }; + + SqlLine beeLine = new SqlLine(); + SqlLine.Status status = + begin(beeLine, baos, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + beeLine.runCommands(new DispatchCallback(), "!manual"); + String output = baos.toString("UTF8"); + + assertThat(output, containsString(expectedLine)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-38] + * Expand ~ to user's home directory. */ + @Test + public void testRunFromHome() { + try { + Path tmpDir = + Files.createTempDirectory( + Paths.get(System.getProperty("user.home")), + "tmpdir" + System.nanoTime()); + tmpDir.toFile().deleteOnExit(); + + File tmpFile = createTempFile("test", ".sql", tmpDir); + try (Writer fw = new OutputStreamWriter( + new FileOutputStream(tmpFile), StandardCharsets.UTF_8)) { + fw.write("!set outputformat csv\n"); + fw.write("values (1, 2, 3, 4, 5);"); + fw.flush(); + checkScriptFile("!run ~" + File.separatorChar + + tmpDir.getFileName() + + File.separatorChar + tmpFile.getName().toString(), + false, + equalTo(SqlLine.Status.OK), + allOf(containsString("!set outputformat csv"), + containsString("values (1, 2, 3, 4, 5);"))); + } + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-26] + * Flush output for each command when using !record command. + */ + @Test + public void testRecord() { + File file = createTempFile("sqlline", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + /** Test case for + * [SQLLINE-62] + * Expand ~ to user's home directory. */ + @Test + public void testRecordHome() { + File home = new File(System.getProperty("user.home")); + File file; + for (int i = 0;; i++) { + file = new File(home, "sqlline" + i + ".log"); + if (!file.exists()) { + break; + } + } + file.deleteOnExit(); + final String s = "Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "2/4 !set outputformat csv\n" + + "3/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "4/4 !record\n"; + checkScriptFile("!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n", + false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/4 !record .*.log\n" + + s + + "Recording stopped.\n" + + ".*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, RegexMatcher.of(s)); + final boolean delete = file.delete(); + assertThat(delete, is(true)); + } + + /** + * As {@link #testRecord()}, but file name is double-quoted and contains a + * space. + */ + @Test + public void testRecordFilenameWithSpace() { + File file = createTempFile("sqlline file with spaces", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + private static void assertFileContains(File file, Matcher matcher) { + try (BufferedReader br = new BufferedReader( + new InputStreamReader(new FileInputStream(file), + StandardCharsets.UTF_8.name()))) { + final StringWriter stringWriter = new StringWriter(); + for (;;) { + final String line = br.readLine(); + if (line == null) { + break; + } + stringWriter.write(line); + stringWriter.write("\n"); + } + assertThat(toLinux(stringWriter.toString()), matcher); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-61] + * Add !nickname command. + */ + @Test + public void testNickname() { + final String script = "!set outputformat csv\n" + + "values 1;\n" + + "!nickname foo\n" + + "values 2;\n"; + final String expected = "(?s)1/4 !set outputformat csv\n" + + "2/4 values 1;\n" + + "'C1'\n" + + "'1'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/4 !nickname foo\n" + + "4/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * The first command should fail and the second command should not execute. + */ + @Test + public void testBreakOnErrorScriptFile() { + checkScriptFile("select * from abcdefg01;\ncall 100 + 23;\n", + true, + equalTo(SqlLine.Status.OTHER), + not(containsString(" 123 "))); + } + + /** + * Emulation of Apache Hive behavior with throwing exceptions + * while calling {@link DatabaseMetaData#storesUpperCaseIdentifiers()} + * and {@link DatabaseMetaData#supportsTransactionIsolationLevel(int)}. + * + *

    Also please see + * [SQLLINE-183]. + * + * @param meta Mocked JDBCDatabaseMetaData + */ + @Test + public void testExecutionWithNotSupportedMethods( + @Mocked final JDBCDatabaseMetaData meta) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + + // emulate apache hive behavior + meta.supportsTransactionIsolationLevel(4); + result = new SQLException("Method not supported"); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback dc = new DispatchCallback(); + sqlLine.initArgs(args, dc); + os.reset(); + sqlLine.runCommands(dc, + "!set incremental true", + "values 1;"); + final String output = os.toString("UTF8"); + final String line0 = "+-------------+"; + final String line1 = "| C1 |"; + final String line2 = "+-------------+"; + final String line3 = "| 1 |"; + final String line4 = "+-------------+"; + assertThat(output, + CoreMatchers.allOf(containsString(line0), + containsString(line1), + containsString(line2), + containsString(line3), + containsString(line4))); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + @Test + public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta, + @Mocked final JDBCResultSet resultSet) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getSQLKeywords(); + result = ""; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + // Generate an exception on a call to resultSet.next + resultSet.next(); + result = new SQLException("Generated Exception."); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + // If sqlline is not initialized, handleSQLException will print + // the entire stack trace. + // To prevent that, forcibly set init to true. + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "CREATE TABLE rsTest ( a int);", + "insert into rsTest values (1);", + "insert into rsTest values (2);", + "select a from rsTest; "); + String output = os.toString("UTF8"); + assertThat(output, containsString("Generated Exception")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Attempts to execute a missing script file with the -f option to SqlLine. + */ + @Test + public void testNegativeScriptFile() { + // Create and delete a temp file + File scriptFile = createTempFile("sqllinenegative", "temp"); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OTHER)); + assertThat(pair.output, not(containsString(" 123 "))); + } + + /** Displays usage. */ + @Test + public void testUsage() { + Pair pair = run("--help"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + private int countUsage(String output) { + int n = 0; + for (String line : output.split("\n")) { + if (line.contains("Usage")) { + ++n; + } + } + return n; + } + + /** Invalid arguments. */ + @Test + public void testInvalidArguments() { + Pair pair = run("--fuzz"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + /** Result of executing sqlline: status code and output. */ + static class Pair { + final SqlLine.Status status; + final String output; + + Pair(SqlLine.Status status, String output) { + this.status = status; + this.output = output; + } + } + + @Test + public void testIsolationSetting() { + final String script0 = "!isolation TRANSACTION_NONE\n"; + final String expected = "Transaction isolation level TRANSACTION_NONE " + + "is not supported. Default (TRANSACTION_READ_COMMITTED) " + + "will be used instead."; + checkScriptFile(script0, true, equalTo(SqlLine.Status.OTHER), + containsString(expected)); + } + + @Test + public void testDefaultIsolation() { + final String script1 = "!isolation default\n"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + allOf(not(containsString("Transaction isolation level")), + not(containsString("is not supported")))); + } + + /** + * HIVE-4566, "NullPointerException if typeinfo and nativesql commands are + * executed at beeline before a DB connection is established". + */ + @Test + public void testNPE() { + SqlLine sqlLine = new SqlLine(); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + + try { + sqlLine.runCommands(new DispatchCallback(), "!typeinfo"); + String output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + + sqlLine.runCommands(new DispatchCallback(), "!nativesql"); + output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandlerOnStartup() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final String[] args = { + "-e", "!set maxwidth 80", + "-ch", "sqlline.extensions.HelloWorldCommandHandler"}; + begin(sqlLine, os, false, args); + + try { + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!test"); + output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello test")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandler() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + begin(sqlLine, os, false, "-e", "!set maxwidth 80"); + + try { + final String script = "!commandhandler" + + " sqlline.extensions.HelloWorld2CommandHandler" + + " sqlline.extensions.HelloWorldCommandHandler"; + sqlLine.runCommands(new DispatchCallback(), script); + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD2")); + final String expected = "Could not add command handler " + + "sqlline.extensions.HelloWorldCommandHandler as one of commands " + + "[hello, test] is already present"; + assertThat(output, containsString(expected)); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello2")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testTablesCsv() { + final String script = "!set outputformat csv\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("'TABLE_CAT','TABLE_SCHEM','TABLE_NAME',"), + containsString("'PUBLIC','SCOTT','SALGRADE','TABLE','',"))); + } + + /** + * java.lang.NullPointerException test case from + * https://github.com/julianhyde/sqlline/pull/86#issuecomment-410868361 + */ + @Test + public void testCsvDelimiterAndQuoteCharacter() { + final String script = "!set outputformat csv\n" + + "!set csvDelimiter null\n" + + "!set csvQuoteCharacter @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!set csvDelimiter ##\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@null@C2@null@C3@null@C4@null@C5@null@C6@"; + final String line2 = + "@#@null@@@#@@@null@1@null@1969-07-20@null@@null@ 1'2\"3\t4@"; + final String line3 = "@C1@##@C2@##@C3@##@C4@##@C5@##@C6@"; + final String line4 = "@#@##@@@#@@@##@1@##@1969-07-20@##@@##@ 1'2\"3\t4@"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testCsvOneLiner() { + final String script = "!outputformat csv \"'\" @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!outputformat csv & default\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@'@C2@'@C3@'@C4@'@C5@'@C6@"; + final String line2 = + "@#@'@@@#@@@'@1@'@1969-07-20@'@@'@ 1'2\"3\t4@"; + final String line3 = "'C1'&'C2'&'C3'&'C4'&'C5'&'C6'"; + final String line4 = + "'#'&'@#@'&'1'&'1969-07-20'&''&' 1''2\"3\t4'"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testSetForNulls() { + final String script = "!set numberFormat null\n" + + "!set\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("numberFormat null")); + } + + @Test + public void testSetNonIntValuesToIntProperties() { + SqlLine sqlLine = new SqlLine(); + final String headerIntervalScript = "!set headerinterval abc\n"; + checkScriptFile(headerIntervalScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "headerinterval", "abc"))); + + final String rowLimitScript = "!set rowlimit xxx\n"; + checkScriptFile(rowLimitScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "rowlimit", "xxx"))); + } + + @Test + public void testSelectXmlAttributes() { + final String script = "!set outputformat xmlattr\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ']]> 1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString("&4\"/>"))); + } + + @Test + public void testSelectXmlElements() { + final String script = "!set outputformat xmlelements\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' ]]>1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString(""), + containsString("1"), + containsString("-1.5"), + containsString("TRUE"), + containsString("1969-07-20"), + containsString("null"), + containsString(" ]]>1'2\"3\t<>&4"), + containsString(""), + containsString(""))); + } + + @Test + public void testTablesJson() { + final String script = "!set outputformat json\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"TABLE_CAT\":\"PUBLIC\"," + + "\"TABLE_SCHEM\":\"SYSTEM_LOBS\",\"TABLE_NAME\":\"BLOCKS\"," + + "\"TABLE_TYPE\":\"SYSTEM TABLE\",\"REMARKS\":null," + + "\"TYPE_CAT\":null,"))); + } + + @Test + public void testSelectJson() { + final String script = "!set outputformat json\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"C1\":1,\"C2\":-1.5,\"C3\":true," + + "\"C4\":\"1969-07-20\",\"C5\":null," + + "\"C6\":\" 1'2\\\"3\\t4\"}"))); + } + + @Test + public void testNullValue() { + final String script = "!set nullValue %%%\n" + + "!set outputformat csv\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue \"'\"\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue null\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'%%%','-1.5','%%%','1969-07-20','%%%','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'''','-1.5','''','1969-07-20','''','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'null','-1.5','null','1969-07-20','null','null'"))); + } + + @Test + public void testTimeFormat() { + // Use System.err as it is used in sqlline.SqlLineOpts#set + final PrintStream originalErr = System.err; + try { + final ByteArrayOutputStream errBaos = new ByteArrayOutputStream(); + System.setErr( + new PrintStream(errBaos, false, StandardCharsets.UTF_8.name())); + + // successful patterns + final String okTimeFormat = "!set timeFormat HH:mm:ss\n"; + final String defaultTimeFormat = "!set timeFormat default\n"; + final String okDateFormat = "!set dateFormat YYYY-MM-dd\n"; + final String defaultDateFormat = "!set dateFormat default\n"; + final String okTimestampFormat = "!set timestampFormat default\n"; + final String defaultTimestampFormat = "!set timestampFormat default\n"; + + // successful cases + final SqlLine sqlLine = new SqlLine(); + sqlLine.runCommands(new DispatchCallback(), okTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + + // failed patterns + final String wrongTimeFormat = "!set timeFormat qwerty\n"; + final String wrongDateFormat = "!set dateFormat ASD\n"; + final String wrongTimestampFormat = + "!set timestampFormat 'YYYY-MM-ddTHH:MI:ss'\n"; + + // failed cases + sqlLine.runCommands(new DispatchCallback(), wrongTimeFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'q'")); + sqlLine.runCommands(new DispatchCallback(), wrongDateFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'A'")); + sqlLine.runCommands(new DispatchCallback(), wrongTimestampFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'T'")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } finally { + // Set error stream back + System.setErr(originalErr); + } + } + + /** + * Test case for + * [SQLLINE-203] + * !indexes command fails because of Hive bug. + * The bug in question is + * [HIVE-20983] + * HiveResultSetMetaData.getColumnDisplaySize throws for SHORT column. + * + * @param meta Mocked hsqldb {@link JDBCResultSetMetaData} to use in the test + */ + @Test + public void testOutputWithFailingColumnDisplaySize( + @Mocked final JDBCResultSetMetaData meta) { + try { + new Expectations() { + { + meta.getColumnCount(); + result = 3; + + meta.getColumnLabel(1); + result = "TABLE_CAT"; + + meta.getColumnLabel(2); + result = "TABLE_SCHEM"; + + meta.getColumnLabel(3); + result = "TABLE_NAME"; + + meta.getColumnDisplaySize(1); + result = new Exception("getColumnDisplaySize exception"); + } + }; + + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "!set incremental true", + "!set maxwidth 80", + "!set verbose true", + "!indexes"); + assertThat(os.toString("UTF8"), not(containsString("Exception"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests the {@code !connect} command with interactive password submission. + */ + @Test + public void testConnectWithoutPassword() { + new MockUp() { + @Mock + String readPassword(String url) { + return ""; + } + }; + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} property outside of the URL: + * + *

    + * !connect -p PASSWORD_HASH TRUE jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} and {@code ALLOW_LITERALS} properties + * outside of the URL: + * + *
    + * !connect -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE + * jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter2() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!set maxwidth 80"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "select 1;"); + String output = os.toString("UTF8"); + final String expected = "Error:"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing the password in as a hash: + * + *
    + * !connect "jdbc:h2:mem; PASSWORD_HASH=TRUE" sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbProperty() { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + try { + beeLine.runCommands(dc, "!set maxwidth 80"); + + // fail attempt + String fakeNonEmptyPassword = "nonEmptyPasswd"; + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE\" " + + ConnectionSpec.H2.username + + " \"" + fakeNonEmptyPassword + "\""); + String output = os.toString("UTF8"); + final String expected0 = "Error:"; + assertThat(output, containsString(expected0)); + os.reset(); + + // success attempt + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE;ALLOW_LITERALS=NONE\" " + + ConnectionSpec.H2.username + " \"" + + StringUtils.convertBytesToHex(bytes) + + "\""); + beeLine.runCommands(dc, "!set incremental true"); + beeLine.runCommands(dc, "!tables"); + output = os.toString("UTF8"); + final String expected1 = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected1)); + + beeLine.runCommands(dc, "select 5;"); + output = os.toString("UTF8"); + final String expected2 = "Error:"; + assertThat(output, containsString(expected2)); + os.reset(); + + beeLine.runCommands(new DispatchCallback(), "!quit"); + output = os.toString("UTF8"); + assertThat(output, + allOf(not(containsString("Error:")), containsString("!quit"))); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + private static PrintStream getPrintStream(OutputStream os) { + try { + return new PrintStream(os, false, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testReconnect() { + final String script = "!reconnect"; + final String expected = "Reconnecting to \"jdbc:hsqldb:res:scott\"...\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + @Test + public void testTables() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxcolumnwidth 15\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = + "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | |"; + final String line1 = + "| PUBLIC | SYSTEM_LOBS | BLOCKS | SYSTEM TABLE | |"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + @Test + public void testTablesH2() { + connectionSpec = ConnectionSpec.H2; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + /** + * Test case for + * [SQLLINE-107] + * Script fails if the wrong driver is specified with -d option + * and there is a valid registered driver for the specified url. + * + */ + @Test + public void testTablesH2WithErrorDriver() { + connectionSpec = ConnectionSpec.ERROR_H2_DRIVER; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + final String message = "Could not find driver " + + connectionSpec.driver + + "; using registered driver org.h2.Driver instead"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString(message), + not(containsString("NullPointerException")), + containsString(line0), + containsString(line1))); + } + + @Test + public void testH2TablesWithErrorUrl() { + connectionSpec = ConnectionSpec.ERROR_H2_URL; + final String script = "!tables\n"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + CoreMatchers.allOf(containsString("No suitable driver"), + not(containsString("NullPointerException")))); + } + + @Test + public void testEmptyMetadata() { + final String script = "!metadata\n"; + final String line = "Usage: metadata "; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + /** Tests that methods inherited from Object are not included in the list + * of possible metadata methods. */ + @Test + public void testPossibleMetadataValues() { + final String script = "!metadata 1\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString("allProceduresAreCallable"), + containsString("getIndexInfo"), + not(containsString("Exception")), + not(containsString("equals")), + not(containsString("notify")), + not(containsString("wait")), + not(containsString("toString")), + not(containsString("hashCode")), + not(containsString("notifyAll")))); + } + + @Test + public void testMetadataForClassHierarchy() { + final SqlLine beeLine = new SqlLine(); + + new MockUp() { + @Mock + public DatabaseMetaData getMetaData() throws SQLException { + return new CustomDatabaseMetadata( + (JDBCConnection) beeLine.getConnection()); + } + }; + + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.HSQLDB.url + " \"" + + ConnectionSpec.HSQLDB.username + "\" \"" + + ConnectionSpec.HSQLDB.password + "\""); + os.reset(); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + assertThat(output, + allOf(containsString("TABLE_CAT"), + not(containsString("No such method \"getTables\"")))); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testEmptyRecord() { + final String line = "Usage: record "; + checkScriptFile("!record", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyRun() { + final String line = "Usage: run "; + checkScriptFile("!run", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyScript() { + final String line = "Usage: script "; + checkScriptFile("!script", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEscapeSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxColumnWidth 15\n" + + "!set escapeOutput yes\n" + + "values \n" + + "('\n" + + "multiline\n" + + "value') \n" + + ";\n"; + final String line1 = "" + + "+-----------------+\n" + + "| C1 |\n" + + "+-----------------+\n" + + "| \\nmultiline \\nvalue |\n" + + "+-----------------+\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!sql \n" + + "values \n" + + "(1, 2) \n" + + ";\n"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 1 | 2 |\n" + + "+-------------+-------------+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAllMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!all \n" + + "values \n" + + "(1, '2') \n" + + ";\n"; + final String line1 = "" + + "+-------------+----+\n" + + "| C1 | C2 |\n" + + "+-------------+----+\n" + + "| 1 | 2 |\n" + + "+-------------+----+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAppInfoMessage() { + Pair pair = run("-e", "!set maxwidth 80"); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + containsString(Application.DEFAULT_APP_INFO_MESSAGE)); + + String[] args = {"-e", "!set maxwidth 80", "-ac", "INCORRECT_CLASS_NAME"}; + pair = run(args); + assertThat(pair.output, + containsString("Could not initialize INCORRECT_CLASS_NAME")); + assertThat(pair.output, + containsString(CustomApplication.DEFAULT_APP_INFO_MESSAGE)); + + String[] args2 = {"-e", "!set maxwidth 80", + "-ac", "sqlline.extensions.CustomApplication"}; + pair = run(args2); + assertThat(pair.output, + containsString(CustomApplication.CUSTOM_INFO_MESSAGE)); + } + + @Test + public void testCustomOutputFormats() { + // json format was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!set outputformat json\n" + + "values 1;"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("Unknown outputFormat \"json\"")); + } + + @Test + public void testCustomCommands() { + // table command was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Unknown command: tables")); + } + + @Test + public void testAppConfigReset() { + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!appconfig sqlline.Application\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("TABLE_CAT")); + } + + @Test + public void testCustomOpts() { + // nulls are displayed as custom_null + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "values(null)"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("custom_null")); + } + + @Test + public void testScanForEmptyAllowedDrivers() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.emptyList(); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("No driver classes found")); + } + + @Test + public void testScanForOnlyH2Allowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.h2.Driver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 1.4 org.h2.Driver"), + not(containsString("org.hsqldb.jdbc.JDBCDriver")))); + } + + @Test + public void testScanForOnlyHsqldbAllowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.hsqldb.jdbc.JDBCDriver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 2.4 org.hsqldb.jdbc.JDBCDriver"), + not(containsString("org.h2.Driver")))); + } + + @Test + public void testVersion() { + final String script = "!set\n"; + try { + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(new Application().getVersion())); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSetVersion() { + final String script = "!set version test-version\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("version property is read only")); + } + + @Test + public void testSetPropertySuccess() { + final String script = "!set timeout\n" + + "!set timeout 200\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("timeout -1"), + containsString("timeout 200"))); + } + + @Test + public void testSetPropertyFailure() { + final String script = "!set unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testSetUsage() { + final String script = "!set 1 2 3"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: set [all | []]")); + } + + @Test + public void testSetWrongValueToEnumTypeProperties() { + Collection propertiesWithAvailableValues = + Arrays.stream(BuiltInProperty.values()) + .filter(t -> !t.getAvailableValues().isEmpty()) + .collect(Collectors.toSet()); + final String wrongValue = "wrong_value"; + for (BuiltInProperty property: propertiesWithAvailableValues) { + final String script = + "!set " + property.propertyName() + " " + wrongValue + "\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf( + containsString("Unknown " + property.propertyName() + " \"" + + wrongValue + "\""), + not(containsString("Exception")))); + } + } + + @Test + public void testResetSuccess() { + final String script = "!set timeout 200\n" + + "!reset timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("[timeout] was reset to [-1]")); + } + + @Test + public void testResetFailure() { + final String script = "!reset unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testResetAll() { + final String script = "!set timeout 200\n" + + "!reset all\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("All properties were reset to their defaults."), + containsString("timeout -1"))); + } + + @Test + public void testResetUsage() { + final String script = "!reset"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: reset (all | )")); + } + + @Test + public void testRerun() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:!/ 4\n" + + "1536743104551:!/ 5\n" + + "1536743104551:!/ 2\n" + + "1536743104551:!/ 7\n" + + "1536743107526:!history\n" + + "1536743115431:!/ 3\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set incremental true", + "!set maxcolumnwidth 30", + "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + "\"\""); + os.reset(); + + beeLine.runCommands(dc, "!/ 1"); + String output = os.toString("UTF8"); + final String expected0 = "+----------------------------+"; + final String expected1 = "| C1 |"; + final String expected2 = "1 row selected"; + assertThat(output, + allOf(containsString(expected0), + containsString(expected1), + containsString(expected2))); + os.reset(); + + beeLine.runCommands(dc, "!/ 4"); + output = os.toString("UTF8"); + String expectedLine3 = "Cycled rerun of commands from history [2, 4]"; + assertThat(output, containsString(expectedLine3)); + os.reset(); + + beeLine.runCommands(dc, "!/ 3"); + output = os.toString("UTF8"); + String expectedLine4 = "Cycled rerun of commands from history [3, 5, 7]"; + assertThat(output, containsString(expectedLine4)); + os.reset(); + + beeLine.runCommands(dc, "!/ 8"); + output = os.toString("UTF8"); + String expectedLine5 = "Cycled rerun of commands from history [8]"; + assertThat(output, containsString(expectedLine5)); + os.reset(); + + beeLine.runCommands(dc, "!rerun " + Integer.MAX_VALUE); + output = os.toString("UTF8"); + String expectedLine6 = + "Usage: rerun , available range of offset is -7..8"; + assertThat(output, containsString(expectedLine6)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMaxColumnWidthIncremental() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line2 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line3 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testMaxColumnWidthBuffered() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line1 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line2 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line3 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + /** Tests with incrementalBufferRows = -1; query stays in non-incremental + * mode. */ + @Test + public void testIncrementalBufferRows() { + final String script1 = "!set incrementalBufferRows -1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line1 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + /** Tests with incrementalBufferRows = 0; query goes straight into + * incremental mode. */ + @Test + public void testIncrementalBufferRows2() { + final String script2 = "!set incrementalBufferRows 0\n" + + "!set incremental false\n" + + "select * from (values (1, 2), (1, 20), (111, 20), (11, 2222), (1, 22))"; + final String line2 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 1 | 2 |\n" + + "| 1 | 20 |\n" + + "| 111 | 20 |\n" + + "| 11 | 2222 |\n" + + "| 1 | 22 |\n" + + "+----+----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + } + + /** Tests with incrementalBufferRows = 1; query starts in non-incremental mode + * and switches to incremental after 1 row. */ + @Test + public void testIncrementalBufferRows3() { + final String script3 = "!set incrementalBufferRows 1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222), (111, 2222))"; + final String line3 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "| 111 | 2222 |\n" + + "+----+----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + } + + /** Tests with incrementalBufferRows = 4; query starts in non-incremental mode + * and rows run out before the limit is reached. */ + @Test + public void testIncrementalBufferRows4() { + final String script4 = "!set incrementalBufferRows 4\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line4 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testIncrementalBufferRows5() { + // With incrementalBufferRows default (1000), query starts and + // stays in incremental mode. + final String script5 = "!set incrementalBufferRows default\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2))"; + final String line5 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "+----+----+"; + checkScriptFile(script5, true, equalTo(SqlLine.Status.OK), + containsString(line5)); + } + + @Test + public void testMaxHistoryFileRows() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:SELECT \\n 'asd' as \"sdf\", 4 \\n \\n as \\n c2;\\n\n" + + "1536743104551:SELECT \\n 'asd' \\n as \\n c2;\\n\n" + + "1536743104551:!/ 2\n" + + "1536743104551:SELECT \\n 2123 \\n as \\n c2 from dual;\\n\n" + + "1536743107526:!history\n" + + "1536743115431:SELECT \\n 2 \\n as \\n c2;\n" + + "1536743115431:SELECT \\n '213' \\n as \\n c1;\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + bw.close(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + final int maxLines = 3; + beeLine.runCommands(dc, "!set maxHistoryFileRows " + maxLines); + os.reset(); + beeLine.runCommands(dc, "!history"); + assertEquals(maxLines + 1, + os.toString("UTF8").split("\\s+\\d{2}:\\d{2}:\\d{2}\\s+").length); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSave() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + SqlLine.Status status = begin(beeLine, os, false, + "-e", "!save"); + assertThat(status, equalTo(SqlLine.Status.OK)); + final DispatchCallback dc = new DispatchCallback(); + + assertThat(os.toString("UTF8"), + containsString("Saving preferences to")); + os.reset(); + beeLine.runCommands(dc, "!set"); + assertThat(os.toString("UTF8"), + allOf(containsString("autoCommit"), + not(containsString("Unknown property:")))); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScript() { + final File file = createTempFile("sqlline", ".script"); + final String script = "!script " + file.getAbsolutePath() + "\n" + + "values (100, 200);\n" + + "!set maxcolumnwidth -1\n" + + "!script\n" + + "values (1, 2);\n"; + final String expected = "(?s)1/5 !script.*" + + "2/5 values \\(100, 200\\);.*" + + "3/5 !set maxcolumnwidth -1.*" + + "4/5 !script.*" + + "5/5 values \\(1, 2\\);.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + + final String output = "values \\(100, 200\\);\n" + + "!set maxcolumnwidth -1\n"; + assertFileContains(file, RegexMatcher.of(output)); + } + + @Test + public void testStartupArgsWithoutUrl() { + try { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests setting the "confirm" property. + */ + @Test + public void testConfirmFlag() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + begin(line, os, false, "-e", "!set confirm true"); + assertThat(line.getOpts().getConfirm(), is(true)); + begin(line, os, false, "-e", "!set confirm false"); + assertThat(line.getOpts().getConfirm(), is(false)); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests that the "confirm" property works. + */ + @Test + public void testConfirmFlagEffects() { + new MockUp() { + @Mock + int getUserAnswer(String question, int... allowedAnswers) { + return 'n'; + } + }; + + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + assertThat(line.getOpts().getConfirmPattern(), is("default")); + String script = "CREATE TABLE dummy_test(pk int);\n" + + "INSERT INTO dummy_test(pk) VALUES(1);\n" + + "INSERT INTO dummy_test(pk) VALUES(2);\n" + + "INSERT INTO dummy_test(pk) VALUES(3);\n" + + "DELETE FROM dummy_test;\n" + + "DROP TABLE dummy_test;\n"; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OK), + containsString(" ")); + + script = "!set confirm true\n" + script; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OTHER), + containsString(line.loc("abort-action"))); + } + + /** + * Tests that the "confirmPattern" property works. + */ + @Test + public void testConfirmPattern() { + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i:(TRUNCATE|ALTER))\""); + assertThat(line.getOpts().getConfirmPattern(), + is("^(?i:(TRUNCATE|ALTER))")); + + begin(line, os, false, "-e", "!set confirmPattern default"); + assertThat(line.getOpts().getConfirmPattern(), + is(line.loc("default-confirm-pattern"))); + } + + /** + * Test for illegal regex in confirmPattern + */ + @Test + public void testExceptionConfirmPattern() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + SqlLine.Status status = + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i*:(TRUNCATE|ALTER))\""); + assertThat(status, equalTo(SqlLine.Status.OK)); + assertThat(os.toString("UTF8"), containsString("invalid regex")); + os.reset(); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** Information necessary to create a JDBC connection. Specify one to run + * tests against a different database. (hsqldb is the default.) */ + public static class ConnectionSpec { + public final String url; + public final String username; + public final String password; + public final String driver; + + public ConnectionSpec(String url, String username, String password, + String driver) { + this.url = url; + this.username = username; + this.password = password; + this.driver = driver; + } + + public static final ConnectionSpec H2 = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec ERROR_H2_DRIVER = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "ERROR_DRIVER"); + + public static final ConnectionSpec ERROR_H2_URL = + new ConnectionSpec("ERROR_URL", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec HSQLDB = + new ConnectionSpec( + ScottHsqldb.URI, ScottHsqldb.USER, ScottHsqldb.PASSWORD, + "org.hsqldb.jdbcDriver"); + + public static final ConnectionSpec MYSQL = + new ConnectionSpec( + "jdbc:mysql://localhost/scott", "scott", "tiger", + "com.mysql.jdbc.Driver"); + } + + /** Regular expression matcher. */ + private static class RegexMatcher extends BaseMatcher { + private final String pattern; + + RegexMatcher(String pattern) { + super(); + this.pattern = pattern; + } + + public static RegexMatcher of(String pattern) { + return new RegexMatcher(pattern); + } + + public boolean matches(Object o) { + return o instanceof String + && ((String) o).matches(pattern); + } + + public void describeTo(Description description) { + description.appendText("regular expression ").appendText(pattern); + } + } + +} + +// End SqlLineArgsTest.java + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PrintStream` acquired by call to `SqlLine()` at line 1077 is not released after line 1081. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SqlLineArgsTest.testNPE() + +### Procedure Id: +sqlline.SqlLineArgsTest.testNPE():void.f497417622c772629e5984dd5ffe663f + +### File: +src/test/java/sqlline/SqlLineArgsTest.java + +### Key: +SqlLineArgsTest.java|testNPE|RESOURCE_LEAK + +### Node Key: +c1078589414e490a85c608d232f435de + +### Hash: +6dc04971d8f703294b357d0ce1729f7a + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8107/instruction.md b/inferredbugs-8107/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..953a7a6340d10b1b53d31cf67ceff76cfc150228 --- /dev/null +++ b/inferredbugs-8107/instruction.md @@ -0,0 +1,2663 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sqlline +**Bug ID:** 44 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +// Licensed to Julian Hyde under one or more contributor license +// agreements. See the NOTICE file distributed with this work for +// additional information regarding copyright ownership. +// +// Julian Hyde licenses this file to you under the Modified BSD License +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/BSD-3-Clause +*/ +package sqlline; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.h2.util.StringUtils; +import org.hamcrest.BaseMatcher; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hsqldb.jdbc.CustomDatabaseMetadata; +import org.hsqldb.jdbc.JDBCConnection; +import org.hsqldb.jdbc.JDBCDatabaseMetaData; +import org.hsqldb.jdbc.JDBCResultSet; +import org.hsqldb.jdbc.JDBCResultSetMetaData; +import org.jline.builtins.Commands; +import org.jline.terminal.Terminal; +import org.junit.jupiter.api.Test; + +import mockit.Expectations; +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.internal.reflection.FieldReflection; +import net.hydromatic.scott.data.hsqldb.ScottHsqldb; +import sqlline.extensions.CustomApplication; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Executes tests of the command-line arguments to SqlLine. + */ +public class SqlLineArgsTest { + private static final ConnectionSpec CONNECTION_SPEC = ConnectionSpec.HSQLDB; + private ConnectionSpec connectionSpec; + + public SqlLineArgsTest() { + connectionSpec = CONNECTION_SPEC; + } + + static SqlLine.Status begin(SqlLine sqlLine, OutputStream os, + boolean saveHistory, String... args) { + try { + PrintStream beelineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(beelineOutputStream); + sqlLine.setErrorStream(beelineOutputStream); + final InputStream is = new ByteArrayInputStream(new byte[0]); + return sqlLine.begin(args, is, saveHistory); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Execute a script with "beeline -f". + * + * @return The stderr and stdout from running the script + * @param args Script arguments + */ + private static Pair run(String... args) { + try { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = begin(beeLine, os, false, args); + return new Pair(status, os.toString("UTF8")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + private Pair runScript(File scriptFile, boolean flag, String outputFileName) { + return runScript(connectionSpec, scriptFile, flag, outputFileName); + } + + private static Pair runScript(ConnectionSpec connectionSpec, File scriptFile, + boolean flag, String outputFileName) { + List args = new ArrayList<>(); + Collections.addAll(args, + "-d", connectionSpec.driver, + "-u", connectionSpec.url, + "-n", connectionSpec.username, + "-p", connectionSpec.password); + if (flag) { + args.add("-f"); + args.add(scriptFile.getAbsolutePath()); + } else { + args.add("--run=" + scriptFile.getAbsolutePath()); + } + if (outputFileName != null) { + args.add("-log"); + args.add(outputFileName); + } + return run(args.toArray(new String[0])); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * Tests for presence of an expected pattern in the output (stdout or stderr). + * + * @param scriptText Script text + * @param flag Command flag (--run or -f) + * @param statusMatcher Checks whether status is as expected + * @param outputMatcher Checks whether output is as expected + */ + private void checkScriptFile(String scriptText, boolean flag, + Matcher statusMatcher, + Matcher outputMatcher) { + try { + // Put the script content in a temp file + File scriptFile = createTempFile("foo", "temp"); + PrintStream os = + new PrintStream( + new FileOutputStream(scriptFile), + false, + StandardCharsets.UTF_8.name()); + os.print(scriptText); + os.close(); + + Pair pair = runScript(scriptFile, flag, null); + + // Check output before status. It gives a better clue what went wrong. + assertThat(toLinux(pair.output), outputMatcher); + assertThat(pair.status, statusMatcher); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Windows line separators in a string into Linux line separators; + * a Linux string is unchanged. */ + private static String toLinux(String s) { + return s.replaceAll("\r\n", "\n"); + } + + private File createTempFile(String prefix, String suffix) { + return createTempFile(prefix, suffix, null); + } + + private File createTempFile(String prefix, String suffix, Path directory) { + try { + final File file = directory == null + ? Files.createTempFile(prefix, suffix).toFile() + : Files.createTempFile(directory, prefix, suffix).toFile(); + file.deleteOnExit(); + return file; + } catch (IOException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMultilineScriptWithComments() { + final String script1Text = + "!set incremental true\n" + + "-- a comment \n values\n--comment\n (\n1\n, ' ab'\n--comment\n)\n;\n"; + + checkScriptFile(script1Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-------------+-----+\n" + + "| C1 | C2 |\n" + + "+-------------+-----+\n" + + "| 1 | ab |\n" + + "+-------------+-----+")); + + final String script2Text = + "!set incremental true\n" + + "--comment \n --comment2 \nvalues (';\n' /* comment */, '\"'" + + "/*multiline;\n ;\n comment*/)\n -- ; \n; -- comment"; + + checkScriptFile(script2Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-----+----+\n" + + "| C1 | C2 |\n" + + "+-----+----+\n" + + "| ; \n" + + " | \" |\n" + + "+-----+----+")); + } + + /** + * Attempt to execute a simple script file with the -f option to SqlLine. + * Test for presence of an expected pattern + * in the output (stdout or stderr), fail if not found. + */ + @Test + public void testPositiveScriptFile() { + checkScriptFile("call 100 + 23;\n", + true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * As above, but using '-run' rather than '-f'. + */ + @Test + public void testPositiveScriptFileUsingRun() { + checkScriptFile("call 100 + 23;\n", + false, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * Test case for + * [SQLLINE-42], + * Script fails if first line is a comment. + */ + @Test + public void testScriptFileStartsWithComment() { + final String scriptText = "-- a comment\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileStartsWithEmptyLine() { + final String scriptText = "\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileContainsComment() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithComments() { + final String scriptText = "--comment\n\n" + + "values \n10 \n+ \n23;\n\n\n" + + "-- a comment\n" + + "\n\nvalues " + + "--comment inside\n\n" + + "100 --comment inside\n\n" + + "+ \n\n23\n\n\n;\n\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithMultilineQuotedStrings() { + final String scriptText = "--comment\n\n" + + "values '\nmultiline;\n;\n; string\n'" + + ";\n\n\n" + + "values '\nmultiline2;\n;\n; string2\n'" + + ";\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString("multiline2;"), containsString("; string2"))); + } + + @Test + public void testScriptWithMultilineStatementsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment\n\n" + + "values 1;values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 1 |\n" + + "+----+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + + @Test + public void testScriptWithMultilineStatementsAndCommentsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment;;\n\n" + + "select * from (values ';') t (\";\");/*;select 1;*/values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+---+\n" + + "| ; |\n" + + "+---+\n" + + "| ; |\n" + + "+---+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + /** + * Tests sql with H2 specific one-line comment '//' + */ + @Test + public void testMultilineScriptWithH2Comments() { + final SqlLine sqlLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + final File tmpHistoryFile = createTempFile("queryToExecute", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + final String script = "\n" + + "\n" + + "!set incremental true\n" + + "\n" + + "\n" + + "select * from information_schema.tables// ';\n" + + "// \";" + + ";\n" + + "\n" + + "\n"; + bw.write(script); + bw.flush(); + } + SqlLine.Status status = + begin(sqlLine, os, false, + "-u", ConnectionSpec.H2.url, + "-n", ConnectionSpec.H2.username, + "--run=" + tmpHistoryFile.getAbsolutePath()); + assertThat(status, equalTo(SqlLine.Status.OK)); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |" + + " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |"; + assertThat(output, containsString(expected)); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-72] + * Allow quoted file names (including spaces) in !record, + * !run and !script commands. */ + @Test + public void testScriptFilenameWithSpace() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23;\n"; + File scriptFile = createTempFile("Script with Spaces", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + allOf(containsString(" 33 "), containsString(" 123 "))); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScriptWithOutput() { + final String scriptText = "!set maxcolumnwidth 20\n" + + "!set incremental true\n" + + "values 100 + 123;\n" + + "-- a comment\n" + + "values 100 + 253;\n"; + + File scriptFile = createTempFile("Script file name", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + + File outputFile = createTempFile("testScriptWithOutput", ".out"); + runScript(scriptFile, true, outputFile.getAbsolutePath()); + assertFileContains(outputFile, + allOf(containsString("| 223 |"), + containsString("| 353 |"))); + final boolean delete = outputFile.delete(); + assertThat(delete, is(true)); + } + + /** + * Values that contain null. + */ + @Test + public void testNull() { + final String script = "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString( + "+-------------+-------------+-----+\n" + + "| C1 | C2 | C3 |\n" + + "+-------------+-------------+-----+\n" + + "| 1 | null | |\n" + + "+-------------+-------------+-----+\n")); + } + + @Test + public void testScan() { + final String expectedLine0 = "Compliant Version Driver Class"; + final String expectedLine1 = "yes 2.4 org.hsqldb.jdbc.JDBCDriver"; + checkScriptFile("!scan\n", false, + equalTo(SqlLine.Status.OK), + allOf(containsString(expectedLine0), containsString(expectedLine1))); + } + + /** + * Table output without header. + */ + @Test + public void testTableOutputNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("| 1 | null | |\n")); + } + + /** + * Csv output without header. + */ + @Test + public void testCsvNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set outputformat csv\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("'1','null',''\n")); + } + + /** + * Tests the "close" command, + * [HIVE-5768] + * Beeline connection cannot be closed with '!close' command and + * [SQLLINE-139] + * Look for the exact match if there are multiple matches. + */ + @Test + public void testClose() { + final String expected = "!close\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile("!close\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + /** + * Test case for + * [SQLLINE-32] + * !help set' should print documentation for all variables. + */ + @Test + public void testHelpSet() { + final String expected = "1/1 !help set\n" + + "!set List / set a sqlline variable\n" + + "\n" + + "Variables:\n" + + "\n" + + "Variable Value Description\n" + + "=============== ========== " + + "==================================================\n" + + "autoCommit true/false " + + "Enable/disable automatic transaction commit\n" + + "autoSave true/false Automatically save preferences\n"; + checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + + // Make sure that each variable (autoCommit, autoSave, color, etc.) has a + // line in the output of '!help set' + final SqlLine sqlLine = new SqlLine(); + String help = sqlLine.loc("help-set") + + sqlLine.loc("variables"); + + final TreeSet propertyNamesMixed = + Arrays.stream(BuiltInProperty.values()) + .map(BuiltInProperty::propertyName) + .collect(Collectors.toCollection(TreeSet::new)); + for (String p : propertyNamesMixed) { + assertThat(help, containsString("\n" + p + " ")); + } + assertThat(propertyNamesMixed.contains("autoCommit"), + is(true)); + assertThat(propertyNamesMixed.contains("autocommit"), + is(false)); + assertThat(propertyNamesMixed.contains("trimScripts"), + is(true)); + + while (help.length() > 0) { + int i = help.indexOf("\n", 1); + if (i < 0) { + break; + } + if (i > 78) { + fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i)); + } + help = help.substring(i); + } + } + + /** + * Test case for + * [SQLLINE-39] + * 'help set' should not break long lines. + * + *

    But it should break 'help all', which consists of a single long line. + */ + @Test + public void testHelpAll() { + // Note that "connections" has been broken onto a new line. + final String expected = "1/1 !help all\n" + + "!all Execute the specified SQL against all the current\n" + + " connections\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help all\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + + /** + * Tests "!go <non-existent connection indexes>". + */ + @Test + public void testGoFailing() { + final String[] connectionIndexes = {"321", "invalid"}; + for (String connectionIndex : connectionIndexes) { + final String script = "!go " + connectionIndex + "\n"; + final String expected = "Invalid connection: " + connectionIndex; + checkScriptFile(script, false, + // Status.OTHER as checking of fail cases + equalTo(SqlLine.Status.OTHER), containsString(expected)); + } + } + + /** + * Tests "!help go". "go" and "#" are synonyms. + */ + @Test + public void testHelpGo() { + for (String c : new String[] {"go", "#"}) { + final String expected = "1/1 !help " + c + "\n" + + "!go Select the current connection\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help " + c + "\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + } + + /** + * Test case for + * !?, !# + * and other one-symbol length commands stopped working + * + *

    '!?' should work in the same way as '!help'. + */ + @Test + public void testHelpAsQuestionMark() { + final String script = "!?\n"; + final String expected = + "!autocommit Set autocommit mode on or off"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + allOf(not(containsString("Unknown command: ?")), + containsString(expected))); + } + + /** + * Test case for + * [SQLLINE-49] + * !manual command fails. + */ + @Test + public void testManual() { + final String expectedLine = "sqlline version"; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + new MockUp() { + @Mock + void less(Terminal terminal, InputStream in, PrintStream out, + PrintStream err, Path currentDir, String[] argv) { + } + }; + + SqlLine beeLine = new SqlLine(); + SqlLine.Status status = + begin(beeLine, baos, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + beeLine.runCommands(new DispatchCallback(), "!manual"); + String output = baos.toString("UTF8"); + + assertThat(output, containsString(expectedLine)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-38] + * Expand ~ to user's home directory. */ + @Test + public void testRunFromHome() { + try { + Path tmpDir = + Files.createTempDirectory( + Paths.get(System.getProperty("user.home")), + "tmpdir" + System.nanoTime()); + tmpDir.toFile().deleteOnExit(); + + File tmpFile = createTempFile("test", ".sql", tmpDir); + try (Writer fw = new OutputStreamWriter( + new FileOutputStream(tmpFile), StandardCharsets.UTF_8)) { + fw.write("!set outputformat csv\n"); + fw.write("values (1, 2, 3, 4, 5);"); + fw.flush(); + checkScriptFile("!run ~" + File.separatorChar + + tmpDir.getFileName() + + File.separatorChar + tmpFile.getName().toString(), + false, + equalTo(SqlLine.Status.OK), + allOf(containsString("!set outputformat csv"), + containsString("values (1, 2, 3, 4, 5);"))); + } + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-26] + * Flush output for each command when using !record command. + */ + @Test + public void testRecord() { + File file = createTempFile("sqlline", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + /** Test case for + * [SQLLINE-62] + * Expand ~ to user's home directory. */ + @Test + public void testRecordHome() { + File home = new File(System.getProperty("user.home")); + File file; + for (int i = 0;; i++) { + file = new File(home, "sqlline" + i + ".log"); + if (!file.exists()) { + break; + } + } + file.deleteOnExit(); + final String s = "Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "2/4 !set outputformat csv\n" + + "3/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "4/4 !record\n"; + checkScriptFile("!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n", + false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/4 !record .*.log\n" + + s + + "Recording stopped.\n" + + ".*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, RegexMatcher.of(s)); + final boolean delete = file.delete(); + assertThat(delete, is(true)); + } + + /** + * As {@link #testRecord()}, but file name is double-quoted and contains a + * space. + */ + @Test + public void testRecordFilenameWithSpace() { + File file = createTempFile("sqlline file with spaces", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + private static void assertFileContains(File file, Matcher matcher) { + try (BufferedReader br = new BufferedReader( + new InputStreamReader(new FileInputStream(file), + StandardCharsets.UTF_8.name()))) { + final StringWriter stringWriter = new StringWriter(); + for (;;) { + final String line = br.readLine(); + if (line == null) { + break; + } + stringWriter.write(line); + stringWriter.write("\n"); + } + assertThat(toLinux(stringWriter.toString()), matcher); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-61] + * Add !nickname command. + */ + @Test + public void testNickname() { + final String script = "!set outputformat csv\n" + + "values 1;\n" + + "!nickname foo\n" + + "values 2;\n"; + final String expected = "(?s)1/4 !set outputformat csv\n" + + "2/4 values 1;\n" + + "'C1'\n" + + "'1'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/4 !nickname foo\n" + + "4/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * The first command should fail and the second command should not execute. + */ + @Test + public void testBreakOnErrorScriptFile() { + checkScriptFile("select * from abcdefg01;\ncall 100 + 23;\n", + true, + equalTo(SqlLine.Status.OTHER), + not(containsString(" 123 "))); + } + + /** + * Emulation of Apache Hive behavior with throwing exceptions + * while calling {@link DatabaseMetaData#storesUpperCaseIdentifiers()} + * and {@link DatabaseMetaData#supportsTransactionIsolationLevel(int)}. + * + *

    Also please see + * [SQLLINE-183]. + * + * @param meta Mocked JDBCDatabaseMetaData + */ + @Test + public void testExecutionWithNotSupportedMethods( + @Mocked final JDBCDatabaseMetaData meta) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + + // emulate apache hive behavior + meta.supportsTransactionIsolationLevel(4); + result = new SQLException("Method not supported"); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback dc = new DispatchCallback(); + sqlLine.initArgs(args, dc); + os.reset(); + sqlLine.runCommands(dc, + "!set incremental true", + "values 1;"); + final String output = os.toString("UTF8"); + final String line0 = "+-------------+"; + final String line1 = "| C1 |"; + final String line2 = "+-------------+"; + final String line3 = "| 1 |"; + final String line4 = "+-------------+"; + assertThat(output, + CoreMatchers.allOf(containsString(line0), + containsString(line1), + containsString(line2), + containsString(line3), + containsString(line4))); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + @Test + public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta, + @Mocked final JDBCResultSet resultSet) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getSQLKeywords(); + result = ""; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + // Generate an exception on a call to resultSet.next + resultSet.next(); + result = new SQLException("Generated Exception."); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + // If sqlline is not initialized, handleSQLException will print + // the entire stack trace. + // To prevent that, forcibly set init to true. + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "CREATE TABLE rsTest ( a int);", + "insert into rsTest values (1);", + "insert into rsTest values (2);", + "select a from rsTest; "); + String output = os.toString("UTF8"); + assertThat(output, containsString("Generated Exception")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Attempts to execute a missing script file with the -f option to SqlLine. + */ + @Test + public void testNegativeScriptFile() { + // Create and delete a temp file + File scriptFile = createTempFile("sqllinenegative", "temp"); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OTHER)); + assertThat(pair.output, not(containsString(" 123 "))); + } + + /** Displays usage. */ + @Test + public void testUsage() { + Pair pair = run("--help"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + private int countUsage(String output) { + int n = 0; + for (String line : output.split("\n")) { + if (line.contains("Usage")) { + ++n; + } + } + return n; + } + + /** Invalid arguments. */ + @Test + public void testInvalidArguments() { + Pair pair = run("--fuzz"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + /** Result of executing sqlline: status code and output. */ + static class Pair { + final SqlLine.Status status; + final String output; + + Pair(SqlLine.Status status, String output) { + this.status = status; + this.output = output; + } + } + + @Test + public void testIsolationSetting() { + final String script0 = "!isolation TRANSACTION_NONE\n"; + final String expected = "Transaction isolation level TRANSACTION_NONE " + + "is not supported. Default (TRANSACTION_READ_COMMITTED) " + + "will be used instead."; + checkScriptFile(script0, true, equalTo(SqlLine.Status.OTHER), + containsString(expected)); + } + + @Test + public void testDefaultIsolation() { + final String script1 = "!isolation default\n"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + allOf(not(containsString("Transaction isolation level")), + not(containsString("is not supported")))); + } + + /** + * HIVE-4566, "NullPointerException if typeinfo and nativesql commands are + * executed at beeline before a DB connection is established". + */ + @Test + public void testNPE() { + SqlLine sqlLine = new SqlLine(); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + + try { + sqlLine.runCommands(new DispatchCallback(), "!typeinfo"); + String output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + + sqlLine.runCommands(new DispatchCallback(), "!nativesql"); + output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandlerOnStartup() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final String[] args = { + "-e", "!set maxwidth 80", + "-ch", "sqlline.extensions.HelloWorldCommandHandler"}; + begin(sqlLine, os, false, args); + + try { + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!test"); + output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello test")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandler() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + begin(sqlLine, os, false, "-e", "!set maxwidth 80"); + + try { + final String script = "!commandhandler" + + " sqlline.extensions.HelloWorld2CommandHandler" + + " sqlline.extensions.HelloWorldCommandHandler"; + sqlLine.runCommands(new DispatchCallback(), script); + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD2")); + final String expected = "Could not add command handler " + + "sqlline.extensions.HelloWorldCommandHandler as one of commands " + + "[hello, test] is already present"; + assertThat(output, containsString(expected)); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello2")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testTablesCsv() { + final String script = "!set outputformat csv\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("'TABLE_CAT','TABLE_SCHEM','TABLE_NAME',"), + containsString("'PUBLIC','SCOTT','SALGRADE','TABLE','',"))); + } + + /** + * java.lang.NullPointerException test case from + * https://github.com/julianhyde/sqlline/pull/86#issuecomment-410868361 + */ + @Test + public void testCsvDelimiterAndQuoteCharacter() { + final String script = "!set outputformat csv\n" + + "!set csvDelimiter null\n" + + "!set csvQuoteCharacter @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!set csvDelimiter ##\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@null@C2@null@C3@null@C4@null@C5@null@C6@"; + final String line2 = + "@#@null@@@#@@@null@1@null@1969-07-20@null@@null@ 1'2\"3\t4@"; + final String line3 = "@C1@##@C2@##@C3@##@C4@##@C5@##@C6@"; + final String line4 = "@#@##@@@#@@@##@1@##@1969-07-20@##@@##@ 1'2\"3\t4@"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testCsvOneLiner() { + final String script = "!outputformat csv \"'\" @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!outputformat csv & default\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@'@C2@'@C3@'@C4@'@C5@'@C6@"; + final String line2 = + "@#@'@@@#@@@'@1@'@1969-07-20@'@@'@ 1'2\"3\t4@"; + final String line3 = "'C1'&'C2'&'C3'&'C4'&'C5'&'C6'"; + final String line4 = + "'#'&'@#@'&'1'&'1969-07-20'&''&' 1''2\"3\t4'"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testSetForNulls() { + final String script = "!set numberFormat null\n" + + "!set\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("numberFormat null")); + } + + @Test + public void testSetNonIntValuesToIntProperties() { + SqlLine sqlLine = new SqlLine(); + final String headerIntervalScript = "!set headerinterval abc\n"; + checkScriptFile(headerIntervalScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "headerinterval", "abc"))); + + final String rowLimitScript = "!set rowlimit xxx\n"; + checkScriptFile(rowLimitScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "rowlimit", "xxx"))); + } + + @Test + public void testSelectXmlAttributes() { + final String script = "!set outputformat xmlattr\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ']]> 1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString("&4\"/>"))); + } + + @Test + public void testSelectXmlElements() { + final String script = "!set outputformat xmlelements\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' ]]>1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString(""), + containsString("1"), + containsString("-1.5"), + containsString("TRUE"), + containsString("1969-07-20"), + containsString("null"), + containsString(" ]]>1'2\"3\t<>&4"), + containsString(""), + containsString(""))); + } + + @Test + public void testTablesJson() { + final String script = "!set outputformat json\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"TABLE_CAT\":\"PUBLIC\"," + + "\"TABLE_SCHEM\":\"SYSTEM_LOBS\",\"TABLE_NAME\":\"BLOCKS\"," + + "\"TABLE_TYPE\":\"SYSTEM TABLE\",\"REMARKS\":null," + + "\"TYPE_CAT\":null,"))); + } + + @Test + public void testSelectJson() { + final String script = "!set outputformat json\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"C1\":1,\"C2\":-1.5,\"C3\":true," + + "\"C4\":\"1969-07-20\",\"C5\":null," + + "\"C6\":\" 1'2\\\"3\\t4\"}"))); + } + + @Test + public void testNullValue() { + final String script = "!set nullValue %%%\n" + + "!set outputformat csv\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue \"'\"\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue null\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'%%%','-1.5','%%%','1969-07-20','%%%','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'''','-1.5','''','1969-07-20','''','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'null','-1.5','null','1969-07-20','null','null'"))); + } + + @Test + public void testTimeFormat() { + // Use System.err as it is used in sqlline.SqlLineOpts#set + final PrintStream originalErr = System.err; + try { + final ByteArrayOutputStream errBaos = new ByteArrayOutputStream(); + System.setErr( + new PrintStream(errBaos, false, StandardCharsets.UTF_8.name())); + + // successful patterns + final String okTimeFormat = "!set timeFormat HH:mm:ss\n"; + final String defaultTimeFormat = "!set timeFormat default\n"; + final String okDateFormat = "!set dateFormat YYYY-MM-dd\n"; + final String defaultDateFormat = "!set dateFormat default\n"; + final String okTimestampFormat = "!set timestampFormat default\n"; + final String defaultTimestampFormat = "!set timestampFormat default\n"; + + // successful cases + final SqlLine sqlLine = new SqlLine(); + sqlLine.runCommands(new DispatchCallback(), okTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + + // failed patterns + final String wrongTimeFormat = "!set timeFormat qwerty\n"; + final String wrongDateFormat = "!set dateFormat ASD\n"; + final String wrongTimestampFormat = + "!set timestampFormat 'YYYY-MM-ddTHH:MI:ss'\n"; + + // failed cases + sqlLine.runCommands(new DispatchCallback(), wrongTimeFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'q'")); + sqlLine.runCommands(new DispatchCallback(), wrongDateFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'A'")); + sqlLine.runCommands(new DispatchCallback(), wrongTimestampFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'T'")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } finally { + // Set error stream back + System.setErr(originalErr); + } + } + + /** + * Test case for + * [SQLLINE-203] + * !indexes command fails because of Hive bug. + * The bug in question is + * [HIVE-20983] + * HiveResultSetMetaData.getColumnDisplaySize throws for SHORT column. + * + * @param meta Mocked hsqldb {@link JDBCResultSetMetaData} to use in the test + */ + @Test + public void testOutputWithFailingColumnDisplaySize( + @Mocked final JDBCResultSetMetaData meta) { + try { + new Expectations() { + { + meta.getColumnCount(); + result = 3; + + meta.getColumnLabel(1); + result = "TABLE_CAT"; + + meta.getColumnLabel(2); + result = "TABLE_SCHEM"; + + meta.getColumnLabel(3); + result = "TABLE_NAME"; + + meta.getColumnDisplaySize(1); + result = new Exception("getColumnDisplaySize exception"); + } + }; + + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "!set incremental true", + "!set maxwidth 80", + "!set verbose true", + "!indexes"); + assertThat(os.toString("UTF8"), not(containsString("Exception"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests the {@code !connect} command with interactive password submission. + */ + @Test + public void testConnectWithoutPassword() { + new MockUp() { + @Mock + String readPassword(String url) { + return ""; + } + }; + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} property outside of the URL: + * + *

    + * !connect -p PASSWORD_HASH TRUE jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} and {@code ALLOW_LITERALS} properties + * outside of the URL: + * + *
    + * !connect -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE + * jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter2() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!set maxwidth 80"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "select 1;"); + String output = os.toString("UTF8"); + final String expected = "Error:"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing the password in as a hash: + * + *
    + * !connect "jdbc:h2:mem; PASSWORD_HASH=TRUE" sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbProperty() { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + try { + beeLine.runCommands(dc, "!set maxwidth 80"); + + // fail attempt + String fakeNonEmptyPassword = "nonEmptyPasswd"; + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE\" " + + ConnectionSpec.H2.username + + " \"" + fakeNonEmptyPassword + "\""); + String output = os.toString("UTF8"); + final String expected0 = "Error:"; + assertThat(output, containsString(expected0)); + os.reset(); + + // success attempt + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE;ALLOW_LITERALS=NONE\" " + + ConnectionSpec.H2.username + " \"" + + StringUtils.convertBytesToHex(bytes) + + "\""); + beeLine.runCommands(dc, "!set incremental true"); + beeLine.runCommands(dc, "!tables"); + output = os.toString("UTF8"); + final String expected1 = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected1)); + + beeLine.runCommands(dc, "select 5;"); + output = os.toString("UTF8"); + final String expected2 = "Error:"; + assertThat(output, containsString(expected2)); + os.reset(); + + beeLine.runCommands(new DispatchCallback(), "!quit"); + output = os.toString("UTF8"); + assertThat(output, + allOf(not(containsString("Error:")), containsString("!quit"))); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + private static PrintStream getPrintStream(OutputStream os) { + try { + return new PrintStream(os, false, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testReconnect() { + final String script = "!reconnect"; + final String expected = "Reconnecting to \"jdbc:hsqldb:res:scott\"...\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + @Test + public void testTables() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxcolumnwidth 15\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = + "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | |"; + final String line1 = + "| PUBLIC | SYSTEM_LOBS | BLOCKS | SYSTEM TABLE | |"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + @Test + public void testTablesH2() { + connectionSpec = ConnectionSpec.H2; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + /** + * Test case for + * [SQLLINE-107] + * Script fails if the wrong driver is specified with -d option + * and there is a valid registered driver for the specified url. + * + */ + @Test + public void testTablesH2WithErrorDriver() { + connectionSpec = ConnectionSpec.ERROR_H2_DRIVER; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + final String message = "Could not find driver " + + connectionSpec.driver + + "; using registered driver org.h2.Driver instead"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString(message), + not(containsString("NullPointerException")), + containsString(line0), + containsString(line1))); + } + + @Test + public void testH2TablesWithErrorUrl() { + connectionSpec = ConnectionSpec.ERROR_H2_URL; + final String script = "!tables\n"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + CoreMatchers.allOf(containsString("No suitable driver"), + not(containsString("NullPointerException")))); + } + + @Test + public void testEmptyMetadata() { + final String script = "!metadata\n"; + final String line = "Usage: metadata "; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + /** Tests that methods inherited from Object are not included in the list + * of possible metadata methods. */ + @Test + public void testPossibleMetadataValues() { + final String script = "!metadata 1\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString("allProceduresAreCallable"), + containsString("getIndexInfo"), + not(containsString("Exception")), + not(containsString("equals")), + not(containsString("notify")), + not(containsString("wait")), + not(containsString("toString")), + not(containsString("hashCode")), + not(containsString("notifyAll")))); + } + + @Test + public void testMetadataForClassHierarchy() { + final SqlLine beeLine = new SqlLine(); + + new MockUp() { + @Mock + public DatabaseMetaData getMetaData() throws SQLException { + return new CustomDatabaseMetadata( + (JDBCConnection) beeLine.getConnection()); + } + }; + + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.HSQLDB.url + " \"" + + ConnectionSpec.HSQLDB.username + "\" \"" + + ConnectionSpec.HSQLDB.password + "\""); + os.reset(); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + assertThat(output, + allOf(containsString("TABLE_CAT"), + not(containsString("No such method \"getTables\"")))); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testEmptyRecord() { + final String line = "Usage: record "; + checkScriptFile("!record", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyRun() { + final String line = "Usage: run "; + checkScriptFile("!run", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyScript() { + final String line = "Usage: script "; + checkScriptFile("!script", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEscapeSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxColumnWidth 15\n" + + "!set escapeOutput yes\n" + + "values \n" + + "('\n" + + "multiline\n" + + "value') \n" + + ";\n"; + final String line1 = "" + + "+-----------------+\n" + + "| C1 |\n" + + "+-----------------+\n" + + "| \\nmultiline \\nvalue |\n" + + "+-----------------+\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!sql \n" + + "values \n" + + "(1, 2) \n" + + ";\n"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 1 | 2 |\n" + + "+-------------+-------------+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAllMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!all \n" + + "values \n" + + "(1, '2') \n" + + ";\n"; + final String line1 = "" + + "+-------------+----+\n" + + "| C1 | C2 |\n" + + "+-------------+----+\n" + + "| 1 | 2 |\n" + + "+-------------+----+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAppInfoMessage() { + Pair pair = run("-e", "!set maxwidth 80"); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + containsString(Application.DEFAULT_APP_INFO_MESSAGE)); + + String[] args = {"-e", "!set maxwidth 80", "-ac", "INCORRECT_CLASS_NAME"}; + pair = run(args); + assertThat(pair.output, + containsString("Could not initialize INCORRECT_CLASS_NAME")); + assertThat(pair.output, + containsString(CustomApplication.DEFAULT_APP_INFO_MESSAGE)); + + String[] args2 = {"-e", "!set maxwidth 80", + "-ac", "sqlline.extensions.CustomApplication"}; + pair = run(args2); + assertThat(pair.output, + containsString(CustomApplication.CUSTOM_INFO_MESSAGE)); + } + + @Test + public void testCustomOutputFormats() { + // json format was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!set outputformat json\n" + + "values 1;"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("Unknown outputFormat \"json\"")); + } + + @Test + public void testCustomCommands() { + // table command was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Unknown command: tables")); + } + + @Test + public void testAppConfigReset() { + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!appconfig sqlline.Application\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("TABLE_CAT")); + } + + @Test + public void testCustomOpts() { + // nulls are displayed as custom_null + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "values(null)"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("custom_null")); + } + + @Test + public void testScanForEmptyAllowedDrivers() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.emptyList(); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("No driver classes found")); + } + + @Test + public void testScanForOnlyH2Allowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.h2.Driver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 1.4 org.h2.Driver"), + not(containsString("org.hsqldb.jdbc.JDBCDriver")))); + } + + @Test + public void testScanForOnlyHsqldbAllowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.hsqldb.jdbc.JDBCDriver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 2.4 org.hsqldb.jdbc.JDBCDriver"), + not(containsString("org.h2.Driver")))); + } + + @Test + public void testVersion() { + final String script = "!set\n"; + try { + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(new Application().getVersion())); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSetVersion() { + final String script = "!set version test-version\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("version property is read only")); + } + + @Test + public void testSetPropertySuccess() { + final String script = "!set timeout\n" + + "!set timeout 200\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("timeout -1"), + containsString("timeout 200"))); + } + + @Test + public void testSetPropertyFailure() { + final String script = "!set unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testSetUsage() { + final String script = "!set 1 2 3"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: set [all | []]")); + } + + @Test + public void testSetWrongValueToEnumTypeProperties() { + Collection propertiesWithAvailableValues = + Arrays.stream(BuiltInProperty.values()) + .filter(t -> !t.getAvailableValues().isEmpty()) + .collect(Collectors.toSet()); + final String wrongValue = "wrong_value"; + for (BuiltInProperty property: propertiesWithAvailableValues) { + final String script = + "!set " + property.propertyName() + " " + wrongValue + "\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf( + containsString("Unknown " + property.propertyName() + " \"" + + wrongValue + "\""), + not(containsString("Exception")))); + } + } + + @Test + public void testResetSuccess() { + final String script = "!set timeout 200\n" + + "!reset timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("[timeout] was reset to [-1]")); + } + + @Test + public void testResetFailure() { + final String script = "!reset unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testResetAll() { + final String script = "!set timeout 200\n" + + "!reset all\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("All properties were reset to their defaults."), + containsString("timeout -1"))); + } + + @Test + public void testResetUsage() { + final String script = "!reset"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: reset (all | )")); + } + + @Test + public void testRerun() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:!/ 4\n" + + "1536743104551:!/ 5\n" + + "1536743104551:!/ 2\n" + + "1536743104551:!/ 7\n" + + "1536743107526:!history\n" + + "1536743115431:!/ 3\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set incremental true", + "!set maxcolumnwidth 30", + "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + "\"\""); + os.reset(); + + beeLine.runCommands(dc, "!/ 1"); + String output = os.toString("UTF8"); + final String expected0 = "+----------------------------+"; + final String expected1 = "| C1 |"; + final String expected2 = "1 row selected"; + assertThat(output, + allOf(containsString(expected0), + containsString(expected1), + containsString(expected2))); + os.reset(); + + beeLine.runCommands(dc, "!/ 4"); + output = os.toString("UTF8"); + String expectedLine3 = "Cycled rerun of commands from history [2, 4]"; + assertThat(output, containsString(expectedLine3)); + os.reset(); + + beeLine.runCommands(dc, "!/ 3"); + output = os.toString("UTF8"); + String expectedLine4 = "Cycled rerun of commands from history [3, 5, 7]"; + assertThat(output, containsString(expectedLine4)); + os.reset(); + + beeLine.runCommands(dc, "!/ 8"); + output = os.toString("UTF8"); + String expectedLine5 = "Cycled rerun of commands from history [8]"; + assertThat(output, containsString(expectedLine5)); + os.reset(); + + beeLine.runCommands(dc, "!rerun " + Integer.MAX_VALUE); + output = os.toString("UTF8"); + String expectedLine6 = + "Usage: rerun , available range of offset is -7..8"; + assertThat(output, containsString(expectedLine6)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMaxColumnWidthIncremental() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line2 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line3 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testMaxColumnWidthBuffered() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line1 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line2 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line3 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + /** Tests with incrementalBufferRows = -1; query stays in non-incremental + * mode. */ + @Test + public void testIncrementalBufferRows() { + final String script1 = "!set incrementalBufferRows -1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line1 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + /** Tests with incrementalBufferRows = 0; query goes straight into + * incremental mode. */ + @Test + public void testIncrementalBufferRows2() { + final String script2 = "!set incrementalBufferRows 0\n" + + "!set incremental false\n" + + "select * from (values (1, 2), (1, 20), (111, 20), (11, 2222), (1, 22))"; + final String line2 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 1 | 2 |\n" + + "| 1 | 20 |\n" + + "| 111 | 20 |\n" + + "| 11 | 2222 |\n" + + "| 1 | 22 |\n" + + "+----+----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + } + + /** Tests with incrementalBufferRows = 1; query starts in non-incremental mode + * and switches to incremental after 1 row. */ + @Test + public void testIncrementalBufferRows3() { + final String script3 = "!set incrementalBufferRows 1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222), (111, 2222))"; + final String line3 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "| 111 | 2222 |\n" + + "+----+----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + } + + /** Tests with incrementalBufferRows = 4; query starts in non-incremental mode + * and rows run out before the limit is reached. */ + @Test + public void testIncrementalBufferRows4() { + final String script4 = "!set incrementalBufferRows 4\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line4 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testIncrementalBufferRows5() { + // With incrementalBufferRows default (1000), query starts and + // stays in incremental mode. + final String script5 = "!set incrementalBufferRows default\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2))"; + final String line5 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "+----+----+"; + checkScriptFile(script5, true, equalTo(SqlLine.Status.OK), + containsString(line5)); + } + + @Test + public void testMaxHistoryFileRows() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:SELECT \\n 'asd' as \"sdf\", 4 \\n \\n as \\n c2;\\n\n" + + "1536743104551:SELECT \\n 'asd' \\n as \\n c2;\\n\n" + + "1536743104551:!/ 2\n" + + "1536743104551:SELECT \\n 2123 \\n as \\n c2 from dual;\\n\n" + + "1536743107526:!history\n" + + "1536743115431:SELECT \\n 2 \\n as \\n c2;\n" + + "1536743115431:SELECT \\n '213' \\n as \\n c1;\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + bw.close(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + final int maxLines = 3; + beeLine.runCommands(dc, "!set maxHistoryFileRows " + maxLines); + os.reset(); + beeLine.runCommands(dc, "!history"); + assertEquals(maxLines + 1, + os.toString("UTF8").split("\\s+\\d{2}:\\d{2}:\\d{2}\\s+").length); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSave() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + SqlLine.Status status = begin(beeLine, os, false, + "-e", "!save"); + assertThat(status, equalTo(SqlLine.Status.OK)); + final DispatchCallback dc = new DispatchCallback(); + + assertThat(os.toString("UTF8"), + containsString("Saving preferences to")); + os.reset(); + beeLine.runCommands(dc, "!set"); + assertThat(os.toString("UTF8"), + allOf(containsString("autoCommit"), + not(containsString("Unknown property:")))); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScript() { + final File file = createTempFile("sqlline", ".script"); + final String script = "!script " + file.getAbsolutePath() + "\n" + + "values (100, 200);\n" + + "!set maxcolumnwidth -1\n" + + "!script\n" + + "values (1, 2);\n"; + final String expected = "(?s)1/5 !script.*" + + "2/5 values \\(100, 200\\);.*" + + "3/5 !set maxcolumnwidth -1.*" + + "4/5 !script.*" + + "5/5 values \\(1, 2\\);.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + + final String output = "values \\(100, 200\\);\n" + + "!set maxcolumnwidth -1\n"; + assertFileContains(file, RegexMatcher.of(output)); + } + + @Test + public void testStartupArgsWithoutUrl() { + try { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests setting the "confirm" property. + */ + @Test + public void testConfirmFlag() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + begin(line, os, false, "-e", "!set confirm true"); + assertThat(line.getOpts().getConfirm(), is(true)); + begin(line, os, false, "-e", "!set confirm false"); + assertThat(line.getOpts().getConfirm(), is(false)); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests that the "confirm" property works. + */ + @Test + public void testConfirmFlagEffects() { + new MockUp() { + @Mock + int getUserAnswer(String question, int... allowedAnswers) { + return 'n'; + } + }; + + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + assertThat(line.getOpts().getConfirmPattern(), is("default")); + String script = "CREATE TABLE dummy_test(pk int);\n" + + "INSERT INTO dummy_test(pk) VALUES(1);\n" + + "INSERT INTO dummy_test(pk) VALUES(2);\n" + + "INSERT INTO dummy_test(pk) VALUES(3);\n" + + "DELETE FROM dummy_test;\n" + + "DROP TABLE dummy_test;\n"; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OK), + containsString(" ")); + + script = "!set confirm true\n" + script; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OTHER), + containsString(line.loc("abort-action"))); + } + + /** + * Tests that the "confirmPattern" property works. + */ + @Test + public void testConfirmPattern() { + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i:(TRUNCATE|ALTER))\""); + assertThat(line.getOpts().getConfirmPattern(), + is("^(?i:(TRUNCATE|ALTER))")); + + begin(line, os, false, "-e", "!set confirmPattern default"); + assertThat(line.getOpts().getConfirmPattern(), + is(line.loc("default-confirm-pattern"))); + } + + /** + * Test for illegal regex in confirmPattern + */ + @Test + public void testExceptionConfirmPattern() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + SqlLine.Status status = + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i*:(TRUNCATE|ALTER))\""); + assertThat(status, equalTo(SqlLine.Status.OK)); + assertThat(os.toString("UTF8"), containsString("invalid regex")); + os.reset(); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** Information necessary to create a JDBC connection. Specify one to run + * tests against a different database. (hsqldb is the default.) */ + public static class ConnectionSpec { + public final String url; + public final String username; + public final String password; + public final String driver; + + public ConnectionSpec(String url, String username, String password, + String driver) { + this.url = url; + this.username = username; + this.password = password; + this.driver = driver; + } + + public static final ConnectionSpec H2 = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec ERROR_H2_DRIVER = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "ERROR_DRIVER"); + + public static final ConnectionSpec ERROR_H2_URL = + new ConnectionSpec("ERROR_URL", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec HSQLDB = + new ConnectionSpec( + ScottHsqldb.URI, ScottHsqldb.USER, ScottHsqldb.PASSWORD, + "org.hsqldb.jdbcDriver"); + + public static final ConnectionSpec MYSQL = + new ConnectionSpec( + "jdbc:mysql://localhost/scott", "scott", "tiger", + "com.mysql.jdbc.Driver"); + } + + /** Regular expression matcher. */ + private static class RegexMatcher extends BaseMatcher { + private final String pattern; + + RegexMatcher(String pattern) { + super(); + this.pattern = pattern; + } + + public static RegexMatcher of(String pattern) { + return new RegexMatcher(pattern); + } + + public boolean matches(Object o) { + return o instanceof String + && ((String) o).matches(pattern); + } + + public void describeTo(Description description) { + description.appendText("regular expression ").appendText(pattern); + } + } + +} + +// End SqlLineArgsTest.java + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PrintStream` acquired by call to `SqlLine()` at line 2049 is not released after line 2117. +**Note**: potential exception at line 2052 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SqlLineArgsTest.testRerun() + +### Procedure Id: +sqlline.SqlLineArgsTest.testRerun():void.315cd6e259da1b45800b77099eb9fac0 + +### File: +src/test/java/sqlline/SqlLineArgsTest.java + +### Key: +SqlLineArgsTest.java|testRerun|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +5eb12d021c36ca951ee6e95de863a75b + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8130/instruction.md b/inferredbugs-8130/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c454b8ade258a7d5751fe0c8a5396975e542ae4 --- /dev/null +++ b/inferredbugs-8130/instruction.md @@ -0,0 +1,2662 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sqlline +**Bug ID:** 47 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +// Licensed to Julian Hyde under one or more contributor license +// agreements. See the NOTICE file distributed with this work for +// additional information regarding copyright ownership. +// +// Julian Hyde licenses this file to you under the Modified BSD License +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/BSD-3-Clause +*/ +package sqlline; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.h2.util.StringUtils; +import org.hamcrest.BaseMatcher; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hsqldb.jdbc.CustomDatabaseMetadata; +import org.hsqldb.jdbc.JDBCConnection; +import org.hsqldb.jdbc.JDBCDatabaseMetaData; +import org.hsqldb.jdbc.JDBCResultSet; +import org.hsqldb.jdbc.JDBCResultSetMetaData; +import org.jline.builtins.Commands; +import org.jline.terminal.Terminal; +import org.junit.jupiter.api.Test; + +import mockit.Expectations; +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.internal.reflection.FieldReflection; +import net.hydromatic.scott.data.hsqldb.ScottHsqldb; +import sqlline.extensions.CustomApplication; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Executes tests of the command-line arguments to SqlLine. + */ +public class SqlLineArgsTest { + private static final ConnectionSpec CONNECTION_SPEC = ConnectionSpec.HSQLDB; + private ConnectionSpec connectionSpec; + + public SqlLineArgsTest() { + connectionSpec = CONNECTION_SPEC; + } + + static SqlLine.Status begin(SqlLine sqlLine, OutputStream os, + boolean saveHistory, String... args) { + try { + PrintStream beelineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(beelineOutputStream); + sqlLine.setErrorStream(beelineOutputStream); + final InputStream is = new ByteArrayInputStream(new byte[0]); + return sqlLine.begin(args, is, saveHistory); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Execute a script with "beeline -f". + * + * @return The stderr and stdout from running the script + * @param args Script arguments + */ + private static Pair run(String... args) { + try { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = begin(beeLine, os, false, args); + return new Pair(status, os.toString("UTF8")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + private Pair runScript(File scriptFile, boolean flag, String outputFileName) { + return runScript(connectionSpec, scriptFile, flag, outputFileName); + } + + private static Pair runScript(ConnectionSpec connectionSpec, File scriptFile, + boolean flag, String outputFileName) { + List args = new ArrayList<>(); + Collections.addAll(args, + "-d", connectionSpec.driver, + "-u", connectionSpec.url, + "-n", connectionSpec.username, + "-p", connectionSpec.password); + if (flag) { + args.add("-f"); + args.add(scriptFile.getAbsolutePath()); + } else { + args.add("--run=" + scriptFile.getAbsolutePath()); + } + if (outputFileName != null) { + args.add("-log"); + args.add(outputFileName); + } + return run(args.toArray(new String[0])); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * Tests for presence of an expected pattern in the output (stdout or stderr). + * + * @param scriptText Script text + * @param flag Command flag (--run or -f) + * @param statusMatcher Checks whether status is as expected + * @param outputMatcher Checks whether output is as expected + */ + private void checkScriptFile(String scriptText, boolean flag, + Matcher statusMatcher, + Matcher outputMatcher) { + try { + // Put the script content in a temp file + File scriptFile = createTempFile("foo", "temp"); + PrintStream os = + new PrintStream( + new FileOutputStream(scriptFile), + false, + StandardCharsets.UTF_8.name()); + os.print(scriptText); + os.close(); + + Pair pair = runScript(scriptFile, flag, null); + + // Check output before status. It gives a better clue what went wrong. + assertThat(toLinux(pair.output), outputMatcher); + assertThat(pair.status, statusMatcher); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Windows line separators in a string into Linux line separators; + * a Linux string is unchanged. */ + private static String toLinux(String s) { + return s.replaceAll("\r\n", "\n"); + } + + private File createTempFile(String prefix, String suffix) { + return createTempFile(prefix, suffix, null); + } + + private File createTempFile(String prefix, String suffix, Path directory) { + try { + final File file = directory == null + ? Files.createTempFile(prefix, suffix).toFile() + : Files.createTempFile(directory, prefix, suffix).toFile(); + file.deleteOnExit(); + return file; + } catch (IOException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMultilineScriptWithComments() { + final String script1Text = + "!set incremental true\n" + + "-- a comment \n values\n--comment\n (\n1\n, ' ab'\n--comment\n)\n;\n"; + + checkScriptFile(script1Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-------------+-----+\n" + + "| C1 | C2 |\n" + + "+-------------+-----+\n" + + "| 1 | ab |\n" + + "+-------------+-----+")); + + final String script2Text = + "!set incremental true\n" + + "--comment \n --comment2 \nvalues (';\n' /* comment */, '\"'" + + "/*multiline;\n ;\n comment*/)\n -- ; \n; -- comment"; + + checkScriptFile(script2Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-----+----+\n" + + "| C1 | C2 |\n" + + "+-----+----+\n" + + "| ; \n" + + " | \" |\n" + + "+-----+----+")); + } + + /** + * Attempt to execute a simple script file with the -f option to SqlLine. + * Test for presence of an expected pattern + * in the output (stdout or stderr), fail if not found. + */ + @Test + public void testPositiveScriptFile() { + checkScriptFile("call 100 + 23;\n", + true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * As above, but using '-run' rather than '-f'. + */ + @Test + public void testPositiveScriptFileUsingRun() { + checkScriptFile("call 100 + 23;\n", + false, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * Test case for + * [SQLLINE-42], + * Script fails if first line is a comment. + */ + @Test + public void testScriptFileStartsWithComment() { + final String scriptText = "-- a comment\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileStartsWithEmptyLine() { + final String scriptText = "\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileContainsComment() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithComments() { + final String scriptText = "--comment\n\n" + + "values \n10 \n+ \n23;\n\n\n" + + "-- a comment\n" + + "\n\nvalues " + + "--comment inside\n\n" + + "100 --comment inside\n\n" + + "+ \n\n23\n\n\n;\n\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithMultilineQuotedStrings() { + final String scriptText = "--comment\n\n" + + "values '\nmultiline;\n;\n; string\n'" + + ";\n\n\n" + + "values '\nmultiline2;\n;\n; string2\n'" + + ";\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString("multiline2;"), containsString("; string2"))); + } + + @Test + public void testScriptWithMultilineStatementsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment\n\n" + + "values 1;values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 1 |\n" + + "+----+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + + @Test + public void testScriptWithMultilineStatementsAndCommentsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment;;\n\n" + + "select * from (values ';') t (\";\");/*;select 1;*/values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+---+\n" + + "| ; |\n" + + "+---+\n" + + "| ; |\n" + + "+---+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + /** + * Tests sql with H2 specific one-line comment '//' + */ + @Test + public void testMultilineScriptWithH2Comments() { + final SqlLine sqlLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + final File tmpHistoryFile = createTempFile("queryToExecute", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + final String script = "\n" + + "\n" + + "!set incremental true\n" + + "\n" + + "\n" + + "select * from information_schema.tables// ';\n" + + "// \";" + + ";\n" + + "\n" + + "\n"; + bw.write(script); + bw.flush(); + } + SqlLine.Status status = + begin(sqlLine, os, false, + "-u", ConnectionSpec.H2.url, + "-n", ConnectionSpec.H2.username, + "--run=" + tmpHistoryFile.getAbsolutePath()); + assertThat(status, equalTo(SqlLine.Status.OK)); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |" + + " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |"; + assertThat(output, containsString(expected)); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-72] + * Allow quoted file names (including spaces) in !record, + * !run and !script commands. */ + @Test + public void testScriptFilenameWithSpace() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23;\n"; + File scriptFile = createTempFile("Script with Spaces", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + allOf(containsString(" 33 "), containsString(" 123 "))); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScriptWithOutput() { + final String scriptText = "!set maxcolumnwidth 20\n" + + "!set incremental true\n" + + "values 100 + 123;\n" + + "-- a comment\n" + + "values 100 + 253;\n"; + + File scriptFile = createTempFile("Script file name", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + + File outputFile = createTempFile("testScriptWithOutput", ".out"); + runScript(scriptFile, true, outputFile.getAbsolutePath()); + assertFileContains(outputFile, + allOf(containsString("| 223 |"), + containsString("| 353 |"))); + final boolean delete = outputFile.delete(); + assertThat(delete, is(true)); + } + + /** + * Values that contain null. + */ + @Test + public void testNull() { + final String script = "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString( + "+-------------+-------------+-----+\n" + + "| C1 | C2 | C3 |\n" + + "+-------------+-------------+-----+\n" + + "| 1 | null | |\n" + + "+-------------+-------------+-----+\n")); + } + + @Test + public void testScan() { + final String expectedLine0 = "Compliant Version Driver Class"; + final String expectedLine1 = "yes 2.4 org.hsqldb.jdbc.JDBCDriver"; + checkScriptFile("!scan\n", false, + equalTo(SqlLine.Status.OK), + allOf(containsString(expectedLine0), containsString(expectedLine1))); + } + + /** + * Table output without header. + */ + @Test + public void testTableOutputNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("| 1 | null | |\n")); + } + + /** + * Csv output without header. + */ + @Test + public void testCsvNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set outputformat csv\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("'1','null',''\n")); + } + + /** + * Tests the "close" command, + * [HIVE-5768] + * Beeline connection cannot be closed with '!close' command and + * [SQLLINE-139] + * Look for the exact match if there are multiple matches. + */ + @Test + public void testClose() { + final String expected = "!close\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile("!close\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + /** + * Test case for + * [SQLLINE-32] + * !help set' should print documentation for all variables. + */ + @Test + public void testHelpSet() { + final String expected = "1/1 !help set\n" + + "!set List / set a sqlline variable\n" + + "\n" + + "Variables:\n" + + "\n" + + "Variable Value Description\n" + + "=============== ========== " + + "==================================================\n" + + "autoCommit true/false " + + "Enable/disable automatic transaction commit\n" + + "autoSave true/false Automatically save preferences\n"; + checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + + // Make sure that each variable (autoCommit, autoSave, color, etc.) has a + // line in the output of '!help set' + final SqlLine sqlLine = new SqlLine(); + String help = sqlLine.loc("help-set") + + sqlLine.loc("variables"); + + final TreeSet propertyNamesMixed = + Arrays.stream(BuiltInProperty.values()) + .map(BuiltInProperty::propertyName) + .collect(Collectors.toCollection(TreeSet::new)); + for (String p : propertyNamesMixed) { + assertThat(help, containsString("\n" + p + " ")); + } + assertThat(propertyNamesMixed.contains("autoCommit"), + is(true)); + assertThat(propertyNamesMixed.contains("autocommit"), + is(false)); + assertThat(propertyNamesMixed.contains("trimScripts"), + is(true)); + + while (help.length() > 0) { + int i = help.indexOf("\n", 1); + if (i < 0) { + break; + } + if (i > 78) { + fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i)); + } + help = help.substring(i); + } + } + + /** + * Test case for + * [SQLLINE-39] + * 'help set' should not break long lines. + * + *

    But it should break 'help all', which consists of a single long line. + */ + @Test + public void testHelpAll() { + // Note that "connections" has been broken onto a new line. + final String expected = "1/1 !help all\n" + + "!all Execute the specified SQL against all the current\n" + + " connections\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help all\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + + /** + * Tests "!go <non-existent connection indexes>". + */ + @Test + public void testGoFailing() { + final String[] connectionIndexes = {"321", "invalid"}; + for (String connectionIndex : connectionIndexes) { + final String script = "!go " + connectionIndex + "\n"; + final String expected = "Invalid connection: " + connectionIndex; + checkScriptFile(script, false, + // Status.OTHER as checking of fail cases + equalTo(SqlLine.Status.OTHER), containsString(expected)); + } + } + + /** + * Tests "!help go". "go" and "#" are synonyms. + */ + @Test + public void testHelpGo() { + for (String c : new String[] {"go", "#"}) { + final String expected = "1/1 !help " + c + "\n" + + "!go Select the current connection\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help " + c + "\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + } + + /** + * Test case for + * !?, !# + * and other one-symbol length commands stopped working + * + *

    '!?' should work in the same way as '!help'. + */ + @Test + public void testHelpAsQuestionMark() { + final String script = "!?\n"; + final String expected = + "!autocommit Set autocommit mode on or off"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + allOf(not(containsString("Unknown command: ?")), + containsString(expected))); + } + + /** + * Test case for + * [SQLLINE-49] + * !manual command fails. + */ + @Test + public void testManual() { + final String expectedLine = "sqlline version"; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + new MockUp() { + @Mock + void less(Terminal terminal, InputStream in, PrintStream out, + PrintStream err, Path currentDir, String[] argv) { + } + }; + + SqlLine beeLine = new SqlLine(); + SqlLine.Status status = + begin(beeLine, baos, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + beeLine.runCommands(new DispatchCallback(), "!manual"); + String output = baos.toString("UTF8"); + + assertThat(output, containsString(expectedLine)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-38] + * Expand ~ to user's home directory. */ + @Test + public void testRunFromHome() { + try { + Path tmpDir = + Files.createTempDirectory( + Paths.get(System.getProperty("user.home")), + "tmpdir" + System.nanoTime()); + tmpDir.toFile().deleteOnExit(); + + File tmpFile = createTempFile("test", ".sql", tmpDir); + try (Writer fw = new OutputStreamWriter( + new FileOutputStream(tmpFile), StandardCharsets.UTF_8)) { + fw.write("!set outputformat csv\n"); + fw.write("values (1, 2, 3, 4, 5);"); + fw.flush(); + checkScriptFile("!run ~" + File.separatorChar + + tmpDir.getFileName() + + File.separatorChar + tmpFile.getName().toString(), + false, + equalTo(SqlLine.Status.OK), + allOf(containsString("!set outputformat csv"), + containsString("values (1, 2, 3, 4, 5);"))); + } + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-26] + * Flush output for each command when using !record command. + */ + @Test + public void testRecord() { + File file = createTempFile("sqlline", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + /** Test case for + * [SQLLINE-62] + * Expand ~ to user's home directory. */ + @Test + public void testRecordHome() { + File home = new File(System.getProperty("user.home")); + File file; + for (int i = 0;; i++) { + file = new File(home, "sqlline" + i + ".log"); + if (!file.exists()) { + break; + } + } + file.deleteOnExit(); + final String s = "Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "2/4 !set outputformat csv\n" + + "3/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "4/4 !record\n"; + checkScriptFile("!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n", + false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/4 !record .*.log\n" + + s + + "Recording stopped.\n" + + ".*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, RegexMatcher.of(s)); + final boolean delete = file.delete(); + assertThat(delete, is(true)); + } + + /** + * As {@link #testRecord()}, but file name is double-quoted and contains a + * space. + */ + @Test + public void testRecordFilenameWithSpace() { + File file = createTempFile("sqlline file with spaces", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + private static void assertFileContains(File file, Matcher matcher) { + try (BufferedReader br = new BufferedReader( + new InputStreamReader(new FileInputStream(file), + StandardCharsets.UTF_8.name()))) { + final StringWriter stringWriter = new StringWriter(); + for (;;) { + final String line = br.readLine(); + if (line == null) { + break; + } + stringWriter.write(line); + stringWriter.write("\n"); + } + assertThat(toLinux(stringWriter.toString()), matcher); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-61] + * Add !nickname command. + */ + @Test + public void testNickname() { + final String script = "!set outputformat csv\n" + + "values 1;\n" + + "!nickname foo\n" + + "values 2;\n"; + final String expected = "(?s)1/4 !set outputformat csv\n" + + "2/4 values 1;\n" + + "'C1'\n" + + "'1'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/4 !nickname foo\n" + + "4/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * The first command should fail and the second command should not execute. + */ + @Test + public void testBreakOnErrorScriptFile() { + checkScriptFile("select * from abcdefg01;\ncall 100 + 23;\n", + true, + equalTo(SqlLine.Status.OTHER), + not(containsString(" 123 "))); + } + + /** + * Emulation of Apache Hive behavior with throwing exceptions + * while calling {@link DatabaseMetaData#storesUpperCaseIdentifiers()} + * and {@link DatabaseMetaData#supportsTransactionIsolationLevel(int)}. + * + *

    Also please see + * [SQLLINE-183]. + * + * @param meta Mocked JDBCDatabaseMetaData + */ + @Test + public void testExecutionWithNotSupportedMethods( + @Mocked final JDBCDatabaseMetaData meta) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + + // emulate apache hive behavior + meta.supportsTransactionIsolationLevel(4); + result = new SQLException("Method not supported"); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback dc = new DispatchCallback(); + sqlLine.initArgs(args, dc); + os.reset(); + sqlLine.runCommands(dc, + "!set incremental true", + "values 1;"); + final String output = os.toString("UTF8"); + final String line0 = "+-------------+"; + final String line1 = "| C1 |"; + final String line2 = "+-------------+"; + final String line3 = "| 1 |"; + final String line4 = "+-------------+"; + assertThat(output, + CoreMatchers.allOf(containsString(line0), + containsString(line1), + containsString(line2), + containsString(line3), + containsString(line4))); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + @Test + public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta, + @Mocked final JDBCResultSet resultSet) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getSQLKeywords(); + result = ""; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + // Generate an exception on a call to resultSet.next + resultSet.next(); + result = new SQLException("Generated Exception."); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + // If sqlline is not initialized, handleSQLException will print + // the entire stack trace. + // To prevent that, forcibly set init to true. + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "CREATE TABLE rsTest ( a int);", + "insert into rsTest values (1);", + "insert into rsTest values (2);", + "select a from rsTest; "); + String output = os.toString("UTF8"); + assertThat(output, containsString("Generated Exception")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Attempts to execute a missing script file with the -f option to SqlLine. + */ + @Test + public void testNegativeScriptFile() { + // Create and delete a temp file + File scriptFile = createTempFile("sqllinenegative", "temp"); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OTHER)); + assertThat(pair.output, not(containsString(" 123 "))); + } + + /** Displays usage. */ + @Test + public void testUsage() { + Pair pair = run("--help"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + private int countUsage(String output) { + int n = 0; + for (String line : output.split("\n")) { + if (line.contains("Usage")) { + ++n; + } + } + return n; + } + + /** Invalid arguments. */ + @Test + public void testInvalidArguments() { + Pair pair = run("--fuzz"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + /** Result of executing sqlline: status code and output. */ + static class Pair { + final SqlLine.Status status; + final String output; + + Pair(SqlLine.Status status, String output) { + this.status = status; + this.output = output; + } + } + + @Test + public void testIsolationSetting() { + final String script0 = "!isolation TRANSACTION_NONE\n"; + final String expected = "Transaction isolation level TRANSACTION_NONE " + + "is not supported. Default (TRANSACTION_READ_COMMITTED) " + + "will be used instead."; + checkScriptFile(script0, true, equalTo(SqlLine.Status.OTHER), + containsString(expected)); + } + + @Test + public void testDefaultIsolation() { + final String script1 = "!isolation default\n"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + allOf(not(containsString("Transaction isolation level")), + not(containsString("is not supported")))); + } + + /** + * HIVE-4566, "NullPointerException if typeinfo and nativesql commands are + * executed at beeline before a DB connection is established". + */ + @Test + public void testNPE() { + SqlLine sqlLine = new SqlLine(); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + + try { + sqlLine.runCommands(new DispatchCallback(), "!typeinfo"); + String output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + + sqlLine.runCommands(new DispatchCallback(), "!nativesql"); + output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandlerOnStartup() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final String[] args = { + "-e", "!set maxwidth 80", + "-ch", "sqlline.extensions.HelloWorldCommandHandler"}; + begin(sqlLine, os, false, args); + + try { + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!test"); + output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello test")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandler() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + begin(sqlLine, os, false, "-e", "!set maxwidth 80"); + + try { + final String script = "!commandhandler" + + " sqlline.extensions.HelloWorld2CommandHandler" + + " sqlline.extensions.HelloWorldCommandHandler"; + sqlLine.runCommands(new DispatchCallback(), script); + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD2")); + final String expected = "Could not add command handler " + + "sqlline.extensions.HelloWorldCommandHandler as one of commands " + + "[hello, test] is already present"; + assertThat(output, containsString(expected)); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello2")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testTablesCsv() { + final String script = "!set outputformat csv\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("'TABLE_CAT','TABLE_SCHEM','TABLE_NAME',"), + containsString("'PUBLIC','SCOTT','SALGRADE','TABLE','',"))); + } + + /** + * java.lang.NullPointerException test case from + * https://github.com/julianhyde/sqlline/pull/86#issuecomment-410868361 + */ + @Test + public void testCsvDelimiterAndQuoteCharacter() { + final String script = "!set outputformat csv\n" + + "!set csvDelimiter null\n" + + "!set csvQuoteCharacter @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!set csvDelimiter ##\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@null@C2@null@C3@null@C4@null@C5@null@C6@"; + final String line2 = + "@#@null@@@#@@@null@1@null@1969-07-20@null@@null@ 1'2\"3\t4@"; + final String line3 = "@C1@##@C2@##@C3@##@C4@##@C5@##@C6@"; + final String line4 = "@#@##@@@#@@@##@1@##@1969-07-20@##@@##@ 1'2\"3\t4@"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testCsvOneLiner() { + final String script = "!outputformat csv \"'\" @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!outputformat csv & default\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@'@C2@'@C3@'@C4@'@C5@'@C6@"; + final String line2 = + "@#@'@@@#@@@'@1@'@1969-07-20@'@@'@ 1'2\"3\t4@"; + final String line3 = "'C1'&'C2'&'C3'&'C4'&'C5'&'C6'"; + final String line4 = + "'#'&'@#@'&'1'&'1969-07-20'&''&' 1''2\"3\t4'"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testSetForNulls() { + final String script = "!set numberFormat null\n" + + "!set\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("numberFormat null")); + } + + @Test + public void testSetNonIntValuesToIntProperties() { + SqlLine sqlLine = new SqlLine(); + final String headerIntervalScript = "!set headerinterval abc\n"; + checkScriptFile(headerIntervalScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "headerinterval", "abc"))); + + final String rowLimitScript = "!set rowlimit xxx\n"; + checkScriptFile(rowLimitScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "rowlimit", "xxx"))); + } + + @Test + public void testSelectXmlAttributes() { + final String script = "!set outputformat xmlattr\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ']]> 1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString("&4\"/>"))); + } + + @Test + public void testSelectXmlElements() { + final String script = "!set outputformat xmlelements\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' ]]>1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString(""), + containsString("1"), + containsString("-1.5"), + containsString("TRUE"), + containsString("1969-07-20"), + containsString("null"), + containsString(" ]]>1'2\"3\t<>&4"), + containsString(""), + containsString(""))); + } + + @Test + public void testTablesJson() { + final String script = "!set outputformat json\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"TABLE_CAT\":\"PUBLIC\"," + + "\"TABLE_SCHEM\":\"SYSTEM_LOBS\",\"TABLE_NAME\":\"BLOCKS\"," + + "\"TABLE_TYPE\":\"SYSTEM TABLE\",\"REMARKS\":null," + + "\"TYPE_CAT\":null,"))); + } + + @Test + public void testSelectJson() { + final String script = "!set outputformat json\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"C1\":1,\"C2\":-1.5,\"C3\":true," + + "\"C4\":\"1969-07-20\",\"C5\":null," + + "\"C6\":\" 1'2\\\"3\\t4\"}"))); + } + + @Test + public void testNullValue() { + final String script = "!set nullValue %%%\n" + + "!set outputformat csv\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue \"'\"\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue null\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'%%%','-1.5','%%%','1969-07-20','%%%','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'''','-1.5','''','1969-07-20','''','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'null','-1.5','null','1969-07-20','null','null'"))); + } + + @Test + public void testTimeFormat() { + // Use System.err as it is used in sqlline.SqlLineOpts#set + final PrintStream originalErr = System.err; + try { + final ByteArrayOutputStream errBaos = new ByteArrayOutputStream(); + System.setErr( + new PrintStream(errBaos, false, StandardCharsets.UTF_8.name())); + + // successful patterns + final String okTimeFormat = "!set timeFormat HH:mm:ss\n"; + final String defaultTimeFormat = "!set timeFormat default\n"; + final String okDateFormat = "!set dateFormat YYYY-MM-dd\n"; + final String defaultDateFormat = "!set dateFormat default\n"; + final String okTimestampFormat = "!set timestampFormat default\n"; + final String defaultTimestampFormat = "!set timestampFormat default\n"; + + // successful cases + final SqlLine sqlLine = new SqlLine(); + sqlLine.runCommands(new DispatchCallback(), okTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + + // failed patterns + final String wrongTimeFormat = "!set timeFormat qwerty\n"; + final String wrongDateFormat = "!set dateFormat ASD\n"; + final String wrongTimestampFormat = + "!set timestampFormat 'YYYY-MM-ddTHH:MI:ss'\n"; + + // failed cases + sqlLine.runCommands(new DispatchCallback(), wrongTimeFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'q'")); + sqlLine.runCommands(new DispatchCallback(), wrongDateFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'A'")); + sqlLine.runCommands(new DispatchCallback(), wrongTimestampFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'T'")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } finally { + // Set error stream back + System.setErr(originalErr); + } + } + + /** + * Test case for + * [SQLLINE-203] + * !indexes command fails because of Hive bug. + * The bug in question is + * [HIVE-20983] + * HiveResultSetMetaData.getColumnDisplaySize throws for SHORT column. + * + * @param meta Mocked hsqldb {@link JDBCResultSetMetaData} to use in the test + */ + @Test + public void testOutputWithFailingColumnDisplaySize( + @Mocked final JDBCResultSetMetaData meta) { + try { + new Expectations() { + { + meta.getColumnCount(); + result = 3; + + meta.getColumnLabel(1); + result = "TABLE_CAT"; + + meta.getColumnLabel(2); + result = "TABLE_SCHEM"; + + meta.getColumnLabel(3); + result = "TABLE_NAME"; + + meta.getColumnDisplaySize(1); + result = new Exception("getColumnDisplaySize exception"); + } + }; + + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "!set incremental true", + "!set maxwidth 80", + "!set verbose true", + "!indexes"); + assertThat(os.toString("UTF8"), not(containsString("Exception"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests the {@code !connect} command with interactive password submission. + */ + @Test + public void testConnectWithoutPassword() { + new MockUp() { + @Mock + String readPassword(String url) { + return ""; + } + }; + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} property outside of the URL: + * + *

    + * !connect -p PASSWORD_HASH TRUE jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} and {@code ALLOW_LITERALS} properties + * outside of the URL: + * + *
    + * !connect -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE + * jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter2() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!set maxwidth 80"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "select 1;"); + String output = os.toString("UTF8"); + final String expected = "Error:"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing the password in as a hash: + * + *
    + * !connect "jdbc:h2:mem; PASSWORD_HASH=TRUE" sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbProperty() { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + try { + beeLine.runCommands(dc, "!set maxwidth 80"); + + // fail attempt + String fakeNonEmptyPassword = "nonEmptyPasswd"; + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE\" " + + ConnectionSpec.H2.username + + " \"" + fakeNonEmptyPassword + "\""); + String output = os.toString("UTF8"); + final String expected0 = "Error:"; + assertThat(output, containsString(expected0)); + os.reset(); + + // success attempt + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE;ALLOW_LITERALS=NONE\" " + + ConnectionSpec.H2.username + " \"" + + StringUtils.convertBytesToHex(bytes) + + "\""); + beeLine.runCommands(dc, "!set incremental true"); + beeLine.runCommands(dc, "!tables"); + output = os.toString("UTF8"); + final String expected1 = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected1)); + + beeLine.runCommands(dc, "select 5;"); + output = os.toString("UTF8"); + final String expected2 = "Error:"; + assertThat(output, containsString(expected2)); + os.reset(); + + beeLine.runCommands(new DispatchCallback(), "!quit"); + output = os.toString("UTF8"); + assertThat(output, + allOf(not(containsString("Error:")), containsString("!quit"))); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + private static PrintStream getPrintStream(OutputStream os) { + try { + return new PrintStream(os, false, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testReconnect() { + final String script = "!reconnect"; + final String expected = "Reconnecting to \"jdbc:hsqldb:res:scott\"...\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + @Test + public void testTables() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxcolumnwidth 15\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = + "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | |"; + final String line1 = + "| PUBLIC | SYSTEM_LOBS | BLOCKS | SYSTEM TABLE | |"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + @Test + public void testTablesH2() { + connectionSpec = ConnectionSpec.H2; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + /** + * Test case for + * [SQLLINE-107] + * Script fails if the wrong driver is specified with -d option + * and there is a valid registered driver for the specified url. + * + */ + @Test + public void testTablesH2WithErrorDriver() { + connectionSpec = ConnectionSpec.ERROR_H2_DRIVER; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + final String message = "Could not find driver " + + connectionSpec.driver + + "; using registered driver org.h2.Driver instead"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString(message), + not(containsString("NullPointerException")), + containsString(line0), + containsString(line1))); + } + + @Test + public void testH2TablesWithErrorUrl() { + connectionSpec = ConnectionSpec.ERROR_H2_URL; + final String script = "!tables\n"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + CoreMatchers.allOf(containsString("No suitable driver"), + not(containsString("NullPointerException")))); + } + + @Test + public void testEmptyMetadata() { + final String script = "!metadata\n"; + final String line = "Usage: metadata "; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + /** Tests that methods inherited from Object are not included in the list + * of possible metadata methods. */ + @Test + public void testPossibleMetadataValues() { + final String script = "!metadata 1\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString("allProceduresAreCallable"), + containsString("getIndexInfo"), + not(containsString("Exception")), + not(containsString("equals")), + not(containsString("notify")), + not(containsString("wait")), + not(containsString("toString")), + not(containsString("hashCode")), + not(containsString("notifyAll")))); + } + + @Test + public void testMetadataForClassHierarchy() { + final SqlLine beeLine = new SqlLine(); + + new MockUp() { + @Mock + public DatabaseMetaData getMetaData() throws SQLException { + return new CustomDatabaseMetadata( + (JDBCConnection) beeLine.getConnection()); + } + }; + + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.HSQLDB.url + " \"" + + ConnectionSpec.HSQLDB.username + "\" \"" + + ConnectionSpec.HSQLDB.password + "\""); + os.reset(); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + assertThat(output, + allOf(containsString("TABLE_CAT"), + not(containsString("No such method \"getTables\"")))); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testEmptyRecord() { + final String line = "Usage: record "; + checkScriptFile("!record", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyRun() { + final String line = "Usage: run "; + checkScriptFile("!run", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyScript() { + final String line = "Usage: script "; + checkScriptFile("!script", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEscapeSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxColumnWidth 15\n" + + "!set escapeOutput yes\n" + + "values \n" + + "('\n" + + "multiline\n" + + "value') \n" + + ";\n"; + final String line1 = "" + + "+-----------------+\n" + + "| C1 |\n" + + "+-----------------+\n" + + "| \\nmultiline \\nvalue |\n" + + "+-----------------+\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!sql \n" + + "values \n" + + "(1, 2) \n" + + ";\n"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 1 | 2 |\n" + + "+-------------+-------------+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAllMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!all \n" + + "values \n" + + "(1, '2') \n" + + ";\n"; + final String line1 = "" + + "+-------------+----+\n" + + "| C1 | C2 |\n" + + "+-------------+----+\n" + + "| 1 | 2 |\n" + + "+-------------+----+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAppInfoMessage() { + Pair pair = run("-e", "!set maxwidth 80"); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + containsString(Application.DEFAULT_APP_INFO_MESSAGE)); + + String[] args = {"-e", "!set maxwidth 80", "-ac", "INCORRECT_CLASS_NAME"}; + pair = run(args); + assertThat(pair.output, + containsString("Could not initialize INCORRECT_CLASS_NAME")); + assertThat(pair.output, + containsString(CustomApplication.DEFAULT_APP_INFO_MESSAGE)); + + String[] args2 = {"-e", "!set maxwidth 80", + "-ac", "sqlline.extensions.CustomApplication"}; + pair = run(args2); + assertThat(pair.output, + containsString(CustomApplication.CUSTOM_INFO_MESSAGE)); + } + + @Test + public void testCustomOutputFormats() { + // json format was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!set outputformat json\n" + + "values 1;"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("Unknown outputFormat \"json\"")); + } + + @Test + public void testCustomCommands() { + // table command was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Unknown command: tables")); + } + + @Test + public void testAppConfigReset() { + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!appconfig sqlline.Application\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("TABLE_CAT")); + } + + @Test + public void testCustomOpts() { + // nulls are displayed as custom_null + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "values(null)"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("custom_null")); + } + + @Test + public void testScanForEmptyAllowedDrivers() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.emptyList(); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("No driver classes found")); + } + + @Test + public void testScanForOnlyH2Allowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.h2.Driver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 1.4 org.h2.Driver"), + not(containsString("org.hsqldb.jdbc.JDBCDriver")))); + } + + @Test + public void testScanForOnlyHsqldbAllowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.hsqldb.jdbc.JDBCDriver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 2.4 org.hsqldb.jdbc.JDBCDriver"), + not(containsString("org.h2.Driver")))); + } + + @Test + public void testVersion() { + final String script = "!set\n"; + try { + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(new Application().getVersion())); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSetVersion() { + final String script = "!set version test-version\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("version property is read only")); + } + + @Test + public void testSetPropertySuccess() { + final String script = "!set timeout\n" + + "!set timeout 200\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("timeout -1"), + containsString("timeout 200"))); + } + + @Test + public void testSetPropertyFailure() { + final String script = "!set unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testSetUsage() { + final String script = "!set 1 2 3"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: set [all | []]")); + } + + @Test + public void testSetWrongValueToEnumTypeProperties() { + Collection propertiesWithAvailableValues = + Arrays.stream(BuiltInProperty.values()) + .filter(t -> !t.getAvailableValues().isEmpty()) + .collect(Collectors.toSet()); + final String wrongValue = "wrong_value"; + for (BuiltInProperty property: propertiesWithAvailableValues) { + final String script = + "!set " + property.propertyName() + " " + wrongValue + "\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf( + containsString("Unknown " + property.propertyName() + " \"" + + wrongValue + "\""), + not(containsString("Exception")))); + } + } + + @Test + public void testResetSuccess() { + final String script = "!set timeout 200\n" + + "!reset timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("[timeout] was reset to [-1]")); + } + + @Test + public void testResetFailure() { + final String script = "!reset unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testResetAll() { + final String script = "!set timeout 200\n" + + "!reset all\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("All properties were reset to their defaults."), + containsString("timeout -1"))); + } + + @Test + public void testResetUsage() { + final String script = "!reset"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: reset (all | )")); + } + + @Test + public void testRerun() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:!/ 4\n" + + "1536743104551:!/ 5\n" + + "1536743104551:!/ 2\n" + + "1536743104551:!/ 7\n" + + "1536743107526:!history\n" + + "1536743115431:!/ 3\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set incremental true", + "!set maxcolumnwidth 30", + "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + "\"\""); + os.reset(); + + beeLine.runCommands(dc, "!/ 1"); + String output = os.toString("UTF8"); + final String expected0 = "+----------------------------+"; + final String expected1 = "| C1 |"; + final String expected2 = "1 row selected"; + assertThat(output, + allOf(containsString(expected0), + containsString(expected1), + containsString(expected2))); + os.reset(); + + beeLine.runCommands(dc, "!/ 4"); + output = os.toString("UTF8"); + String expectedLine3 = "Cycled rerun of commands from history [2, 4]"; + assertThat(output, containsString(expectedLine3)); + os.reset(); + + beeLine.runCommands(dc, "!/ 3"); + output = os.toString("UTF8"); + String expectedLine4 = "Cycled rerun of commands from history [3, 5, 7]"; + assertThat(output, containsString(expectedLine4)); + os.reset(); + + beeLine.runCommands(dc, "!/ 8"); + output = os.toString("UTF8"); + String expectedLine5 = "Cycled rerun of commands from history [8]"; + assertThat(output, containsString(expectedLine5)); + os.reset(); + + beeLine.runCommands(dc, "!rerun " + Integer.MAX_VALUE); + output = os.toString("UTF8"); + String expectedLine6 = + "Usage: rerun , available range of offset is -7..8"; + assertThat(output, containsString(expectedLine6)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMaxColumnWidthIncremental() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line2 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line3 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testMaxColumnWidthBuffered() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line1 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line2 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line3 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + /** Tests with incrementalBufferRows = -1; query stays in non-incremental + * mode. */ + @Test + public void testIncrementalBufferRows() { + final String script1 = "!set incrementalBufferRows -1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line1 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + /** Tests with incrementalBufferRows = 0; query goes straight into + * incremental mode. */ + @Test + public void testIncrementalBufferRows2() { + final String script2 = "!set incrementalBufferRows 0\n" + + "!set incremental false\n" + + "select * from (values (1, 2), (1, 20), (111, 20), (11, 2222), (1, 22))"; + final String line2 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 1 | 2 |\n" + + "| 1 | 20 |\n" + + "| 111 | 20 |\n" + + "| 11 | 2222 |\n" + + "| 1 | 22 |\n" + + "+----+----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + } + + /** Tests with incrementalBufferRows = 1; query starts in non-incremental mode + * and switches to incremental after 1 row. */ + @Test + public void testIncrementalBufferRows3() { + final String script3 = "!set incrementalBufferRows 1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222), (111, 2222))"; + final String line3 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "| 111 | 2222 |\n" + + "+----+----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + } + + /** Tests with incrementalBufferRows = 4; query starts in non-incremental mode + * and rows run out before the limit is reached. */ + @Test + public void testIncrementalBufferRows4() { + final String script4 = "!set incrementalBufferRows 4\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line4 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testIncrementalBufferRows5() { + // With incrementalBufferRows default (1000), query starts and + // stays in incremental mode. + final String script5 = "!set incrementalBufferRows default\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2))"; + final String line5 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "+----+----+"; + checkScriptFile(script5, true, equalTo(SqlLine.Status.OK), + containsString(line5)); + } + + @Test + public void testMaxHistoryFileRows() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:SELECT \\n 'asd' as \"sdf\", 4 \\n \\n as \\n c2;\\n\n" + + "1536743104551:SELECT \\n 'asd' \\n as \\n c2;\\n\n" + + "1536743104551:!/ 2\n" + + "1536743104551:SELECT \\n 2123 \\n as \\n c2 from dual;\\n\n" + + "1536743107526:!history\n" + + "1536743115431:SELECT \\n 2 \\n as \\n c2;\n" + + "1536743115431:SELECT \\n '213' \\n as \\n c1;\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + bw.close(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + final int maxLines = 3; + beeLine.runCommands(dc, "!set maxHistoryFileRows " + maxLines); + os.reset(); + beeLine.runCommands(dc, "!history"); + assertEquals(maxLines + 1, + os.toString("UTF8").split("\\s+\\d{2}:\\d{2}:\\d{2}\\s+").length); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSave() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + SqlLine.Status status = begin(beeLine, os, false, + "-e", "!save"); + assertThat(status, equalTo(SqlLine.Status.OK)); + final DispatchCallback dc = new DispatchCallback(); + + assertThat(os.toString("UTF8"), + containsString("Saving preferences to")); + os.reset(); + beeLine.runCommands(dc, "!set"); + assertThat(os.toString("UTF8"), + allOf(containsString("autoCommit"), + not(containsString("Unknown property:")))); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScript() { + final File file = createTempFile("sqlline", ".script"); + final String script = "!script " + file.getAbsolutePath() + "\n" + + "values (100, 200);\n" + + "!set maxcolumnwidth -1\n" + + "!script\n" + + "values (1, 2);\n"; + final String expected = "(?s)1/5 !script.*" + + "2/5 values \\(100, 200\\);.*" + + "3/5 !set maxcolumnwidth -1.*" + + "4/5 !script.*" + + "5/5 values \\(1, 2\\);.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + + final String output = "values \\(100, 200\\);\n" + + "!set maxcolumnwidth -1\n"; + assertFileContains(file, RegexMatcher.of(output)); + } + + @Test + public void testStartupArgsWithoutUrl() { + try { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests setting the "confirm" property. + */ + @Test + public void testConfirmFlag() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + begin(line, os, false, "-e", "!set confirm true"); + assertThat(line.getOpts().getConfirm(), is(true)); + begin(line, os, false, "-e", "!set confirm false"); + assertThat(line.getOpts().getConfirm(), is(false)); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests that the "confirm" property works. + */ + @Test + public void testConfirmFlagEffects() { + new MockUp() { + @Mock + int getUserAnswer(String question, int... allowedAnswers) { + return 'n'; + } + }; + + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + assertThat(line.getOpts().getConfirmPattern(), is("default")); + String script = "CREATE TABLE dummy_test(pk int);\n" + + "INSERT INTO dummy_test(pk) VALUES(1);\n" + + "INSERT INTO dummy_test(pk) VALUES(2);\n" + + "INSERT INTO dummy_test(pk) VALUES(3);\n" + + "DELETE FROM dummy_test;\n" + + "DROP TABLE dummy_test;\n"; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OK), + containsString(" ")); + + script = "!set confirm true\n" + script; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OTHER), + containsString(line.loc("abort-action"))); + } + + /** + * Tests that the "confirmPattern" property works. + */ + @Test + public void testConfirmPattern() { + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i:(TRUNCATE|ALTER))\""); + assertThat(line.getOpts().getConfirmPattern(), + is("^(?i:(TRUNCATE|ALTER))")); + + begin(line, os, false, "-e", "!set confirmPattern default"); + assertThat(line.getOpts().getConfirmPattern(), + is(line.loc("default-confirm-pattern"))); + } + + /** + * Test for illegal regex in confirmPattern + */ + @Test + public void testExceptionConfirmPattern() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + SqlLine.Status status = + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i*:(TRUNCATE|ALTER))\""); + assertThat(status, equalTo(SqlLine.Status.OK)); + assertThat(os.toString("UTF8"), containsString("invalid regex")); + os.reset(); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** Information necessary to create a JDBC connection. Specify one to run + * tests against a different database. (hsqldb is the default.) */ + public static class ConnectionSpec { + public final String url; + public final String username; + public final String password; + public final String driver; + + public ConnectionSpec(String url, String username, String password, + String driver) { + this.url = url; + this.username = username; + this.password = password; + this.driver = driver; + } + + public static final ConnectionSpec H2 = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec ERROR_H2_DRIVER = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "ERROR_DRIVER"); + + public static final ConnectionSpec ERROR_H2_URL = + new ConnectionSpec("ERROR_URL", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec HSQLDB = + new ConnectionSpec( + ScottHsqldb.URI, ScottHsqldb.USER, ScottHsqldb.PASSWORD, + "org.hsqldb.jdbcDriver"); + + public static final ConnectionSpec MYSQL = + new ConnectionSpec( + "jdbc:mysql://localhost/scott", "scott", "tiger", + "com.mysql.jdbc.Driver"); + } + + /** Regular expression matcher. */ + private static class RegexMatcher extends BaseMatcher { + private final String pattern; + + RegexMatcher(String pattern) { + super(); + this.pattern = pattern; + } + + public static RegexMatcher of(String pattern) { + return new RegexMatcher(pattern); + } + + public boolean matches(Object o) { + return o instanceof String + && ((String) o).matches(pattern); + } + + public void describeTo(Description description) { + description.appendText("regular expression ").appendText(pattern); + } + } + +} + +// End SqlLineArgsTest.java + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PrintStream` acquired by call to `SqlLine()` at line 2368 is not released after line 2371. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SqlLineArgsTest.testSave() + +### Procedure Id: +sqlline.SqlLineArgsTest.testSave():void.64455dd1733e93cc05009ea7dae2936c + +### File: +src/test/java/sqlline/SqlLineArgsTest.java + +### Key: +SqlLineArgsTest.java|testSave|RESOURCE_LEAK + +### Node Key: +b2d15307b6382364ce2ba477b6f118cb + +### Hash: +f4a13cec89a3da9ff6410f4512462276 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8136/instruction.md b/inferredbugs-8136/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..81590d12cf9fe6b266cf6e79dd64bf21d3333753 --- /dev/null +++ b/inferredbugs-8136/instruction.md @@ -0,0 +1,2662 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sqlline +**Bug ID:** 25 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +// Licensed to Julian Hyde under one or more contributor license +// agreements. See the NOTICE file distributed with this work for +// additional information regarding copyright ownership. +// +// Julian Hyde licenses this file to you under the Modified BSD License +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/BSD-3-Clause +*/ +package sqlline; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.h2.util.StringUtils; +import org.hamcrest.BaseMatcher; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hsqldb.jdbc.CustomDatabaseMetadata; +import org.hsqldb.jdbc.JDBCConnection; +import org.hsqldb.jdbc.JDBCDatabaseMetaData; +import org.hsqldb.jdbc.JDBCResultSet; +import org.hsqldb.jdbc.JDBCResultSetMetaData; +import org.jline.builtins.Commands; +import org.jline.terminal.Terminal; +import org.junit.jupiter.api.Test; + +import mockit.Expectations; +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.internal.reflection.FieldReflection; +import net.hydromatic.scott.data.hsqldb.ScottHsqldb; +import sqlline.extensions.CustomApplication; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Executes tests of the command-line arguments to SqlLine. + */ +public class SqlLineArgsTest { + private static final ConnectionSpec CONNECTION_SPEC = ConnectionSpec.HSQLDB; + private ConnectionSpec connectionSpec; + + public SqlLineArgsTest() { + connectionSpec = CONNECTION_SPEC; + } + + static SqlLine.Status begin(SqlLine sqlLine, OutputStream os, + boolean saveHistory, String... args) { + try { + PrintStream beelineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(beelineOutputStream); + sqlLine.setErrorStream(beelineOutputStream); + final InputStream is = new ByteArrayInputStream(new byte[0]); + return sqlLine.begin(args, is, saveHistory); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Execute a script with "beeline -f". + * + * @return The stderr and stdout from running the script + * @param args Script arguments + */ + private static Pair run(String... args) { + try { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = begin(beeLine, os, false, args); + return new Pair(status, os.toString("UTF8")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + private Pair runScript(File scriptFile, boolean flag, String outputFileName) { + return runScript(connectionSpec, scriptFile, flag, outputFileName); + } + + private static Pair runScript(ConnectionSpec connectionSpec, File scriptFile, + boolean flag, String outputFileName) { + List args = new ArrayList<>(); + Collections.addAll(args, + "-d", connectionSpec.driver, + "-u", connectionSpec.url, + "-n", connectionSpec.username, + "-p", connectionSpec.password); + if (flag) { + args.add("-f"); + args.add(scriptFile.getAbsolutePath()); + } else { + args.add("--run=" + scriptFile.getAbsolutePath()); + } + if (outputFileName != null) { + args.add("-log"); + args.add(outputFileName); + } + return run(args.toArray(new String[0])); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * Tests for presence of an expected pattern in the output (stdout or stderr). + * + * @param scriptText Script text + * @param flag Command flag (--run or -f) + * @param statusMatcher Checks whether status is as expected + * @param outputMatcher Checks whether output is as expected + */ + private void checkScriptFile(String scriptText, boolean flag, + Matcher statusMatcher, + Matcher outputMatcher) { + try { + // Put the script content in a temp file + File scriptFile = createTempFile("foo", "temp"); + PrintStream os = + new PrintStream( + new FileOutputStream(scriptFile), + false, + StandardCharsets.UTF_8.name()); + os.print(scriptText); + os.close(); + + Pair pair = runScript(scriptFile, flag, null); + + // Check output before status. It gives a better clue what went wrong. + assertThat(toLinux(pair.output), outputMatcher); + assertThat(pair.status, statusMatcher); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Windows line separators in a string into Linux line separators; + * a Linux string is unchanged. */ + private static String toLinux(String s) { + return s.replaceAll("\r\n", "\n"); + } + + private File createTempFile(String prefix, String suffix) { + return createTempFile(prefix, suffix, null); + } + + private File createTempFile(String prefix, String suffix, Path directory) { + try { + final File file = directory == null + ? Files.createTempFile(prefix, suffix).toFile() + : Files.createTempFile(directory, prefix, suffix).toFile(); + file.deleteOnExit(); + return file; + } catch (IOException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMultilineScriptWithComments() { + final String script1Text = + "!set incremental true\n" + + "-- a comment \n values\n--comment\n (\n1\n, ' ab'\n--comment\n)\n;\n"; + + checkScriptFile(script1Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-------------+-----+\n" + + "| C1 | C2 |\n" + + "+-------------+-----+\n" + + "| 1 | ab |\n" + + "+-------------+-----+")); + + final String script2Text = + "!set incremental true\n" + + "--comment \n --comment2 \nvalues (';\n' /* comment */, '\"'" + + "/*multiline;\n ;\n comment*/)\n -- ; \n; -- comment"; + + checkScriptFile(script2Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-----+----+\n" + + "| C1 | C2 |\n" + + "+-----+----+\n" + + "| ; \n" + + " | \" |\n" + + "+-----+----+")); + } + + /** + * Attempt to execute a simple script file with the -f option to SqlLine. + * Test for presence of an expected pattern + * in the output (stdout or stderr), fail if not found. + */ + @Test + public void testPositiveScriptFile() { + checkScriptFile("call 100 + 23;\n", + true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * As above, but using '-run' rather than '-f'. + */ + @Test + public void testPositiveScriptFileUsingRun() { + checkScriptFile("call 100 + 23;\n", + false, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * Test case for + * [SQLLINE-42], + * Script fails if first line is a comment. + */ + @Test + public void testScriptFileStartsWithComment() { + final String scriptText = "-- a comment\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileStartsWithEmptyLine() { + final String scriptText = "\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileContainsComment() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithComments() { + final String scriptText = "--comment\n\n" + + "values \n10 \n+ \n23;\n\n\n" + + "-- a comment\n" + + "\n\nvalues " + + "--comment inside\n\n" + + "100 --comment inside\n\n" + + "+ \n\n23\n\n\n;\n\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithMultilineQuotedStrings() { + final String scriptText = "--comment\n\n" + + "values '\nmultiline;\n;\n; string\n'" + + ";\n\n\n" + + "values '\nmultiline2;\n;\n; string2\n'" + + ";\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString("multiline2;"), containsString("; string2"))); + } + + @Test + public void testScriptWithMultilineStatementsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment\n\n" + + "values 1;values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 1 |\n" + + "+----+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + + @Test + public void testScriptWithMultilineStatementsAndCommentsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment;;\n\n" + + "select * from (values ';') t (\";\");/*;select 1;*/values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+---+\n" + + "| ; |\n" + + "+---+\n" + + "| ; |\n" + + "+---+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + /** + * Tests sql with H2 specific one-line comment '//' + */ + @Test + public void testMultilineScriptWithH2Comments() { + final SqlLine sqlLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + final File tmpHistoryFile = createTempFile("queryToExecute", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + final String script = "\n" + + "\n" + + "!set incremental true\n" + + "\n" + + "\n" + + "select * from information_schema.tables// ';\n" + + "// \";" + + ";\n" + + "\n" + + "\n"; + bw.write(script); + bw.flush(); + } + SqlLine.Status status = + begin(sqlLine, os, false, + "-u", ConnectionSpec.H2.url, + "-n", ConnectionSpec.H2.username, + "--run=" + tmpHistoryFile.getAbsolutePath()); + assertThat(status, equalTo(SqlLine.Status.OK)); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |" + + " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |"; + assertThat(output, containsString(expected)); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-72] + * Allow quoted file names (including spaces) in !record, + * !run and !script commands. */ + @Test + public void testScriptFilenameWithSpace() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23;\n"; + File scriptFile = createTempFile("Script with Spaces", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + allOf(containsString(" 33 "), containsString(" 123 "))); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScriptWithOutput() { + final String scriptText = "!set maxcolumnwidth 20\n" + + "!set incremental true\n" + + "values 100 + 123;\n" + + "-- a comment\n" + + "values 100 + 253;\n"; + + File scriptFile = createTempFile("Script file name", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + + File outputFile = createTempFile("testScriptWithOutput", ".out"); + runScript(scriptFile, true, outputFile.getAbsolutePath()); + assertFileContains(outputFile, + allOf(containsString("| 223 |"), + containsString("| 353 |"))); + final boolean delete = outputFile.delete(); + assertThat(delete, is(true)); + } + + /** + * Values that contain null. + */ + @Test + public void testNull() { + final String script = "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString( + "+-------------+-------------+-----+\n" + + "| C1 | C2 | C3 |\n" + + "+-------------+-------------+-----+\n" + + "| 1 | null | |\n" + + "+-------------+-------------+-----+\n")); + } + + @Test + public void testScan() { + final String expectedLine0 = "Compliant Version Driver Class"; + final String expectedLine1 = "yes 2.4 org.hsqldb.jdbc.JDBCDriver"; + checkScriptFile("!scan\n", false, + equalTo(SqlLine.Status.OK), + allOf(containsString(expectedLine0), containsString(expectedLine1))); + } + + /** + * Table output without header. + */ + @Test + public void testTableOutputNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("| 1 | null | |\n")); + } + + /** + * Csv output without header. + */ + @Test + public void testCsvNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set outputformat csv\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("'1','null',''\n")); + } + + /** + * Tests the "close" command, + * [HIVE-5768] + * Beeline connection cannot be closed with '!close' command and + * [SQLLINE-139] + * Look for the exact match if there are multiple matches. + */ + @Test + public void testClose() { + final String expected = "!close\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile("!close\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + /** + * Test case for + * [SQLLINE-32] + * !help set' should print documentation for all variables. + */ + @Test + public void testHelpSet() { + final String expected = "1/1 !help set\n" + + "!set List / set a sqlline variable\n" + + "\n" + + "Variables:\n" + + "\n" + + "Variable Value Description\n" + + "=============== ========== " + + "==================================================\n" + + "autoCommit true/false " + + "Enable/disable automatic transaction commit\n" + + "autoSave true/false Automatically save preferences\n"; + checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + + // Make sure that each variable (autoCommit, autoSave, color, etc.) has a + // line in the output of '!help set' + final SqlLine sqlLine = new SqlLine(); + String help = sqlLine.loc("help-set") + + sqlLine.loc("variables"); + + final TreeSet propertyNamesMixed = + Arrays.stream(BuiltInProperty.values()) + .map(BuiltInProperty::propertyName) + .collect(Collectors.toCollection(TreeSet::new)); + for (String p : propertyNamesMixed) { + assertThat(help, containsString("\n" + p + " ")); + } + assertThat(propertyNamesMixed.contains("autoCommit"), + is(true)); + assertThat(propertyNamesMixed.contains("autocommit"), + is(false)); + assertThat(propertyNamesMixed.contains("trimScripts"), + is(true)); + + while (help.length() > 0) { + int i = help.indexOf("\n", 1); + if (i < 0) { + break; + } + if (i > 78) { + fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i)); + } + help = help.substring(i); + } + } + + /** + * Test case for + * [SQLLINE-39] + * 'help set' should not break long lines. + * + *

    But it should break 'help all', which consists of a single long line. + */ + @Test + public void testHelpAll() { + // Note that "connections" has been broken onto a new line. + final String expected = "1/1 !help all\n" + + "!all Execute the specified SQL against all the current\n" + + " connections\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help all\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + + /** + * Tests "!go <non-existent connection indexes>". + */ + @Test + public void testGoFailing() { + final String[] connectionIndexes = {"321", "invalid"}; + for (String connectionIndex : connectionIndexes) { + final String script = "!go " + connectionIndex + "\n"; + final String expected = "Invalid connection: " + connectionIndex; + checkScriptFile(script, false, + // Status.OTHER as checking of fail cases + equalTo(SqlLine.Status.OTHER), containsString(expected)); + } + } + + /** + * Tests "!help go". "go" and "#" are synonyms. + */ + @Test + public void testHelpGo() { + for (String c : new String[] {"go", "#"}) { + final String expected = "1/1 !help " + c + "\n" + + "!go Select the current connection\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help " + c + "\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + } + + /** + * Test case for + * !?, !# + * and other one-symbol length commands stopped working + * + *

    '!?' should work in the same way as '!help'. + */ + @Test + public void testHelpAsQuestionMark() { + final String script = "!?\n"; + final String expected = + "!autocommit Set autocommit mode on or off"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + allOf(not(containsString("Unknown command: ?")), + containsString(expected))); + } + + /** + * Test case for + * [SQLLINE-49] + * !manual command fails. + */ + @Test + public void testManual() { + final String expectedLine = "sqlline version"; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + new MockUp() { + @Mock + void less(Terminal terminal, InputStream in, PrintStream out, + PrintStream err, Path currentDir, String[] argv) { + } + }; + + SqlLine beeLine = new SqlLine(); + SqlLine.Status status = + begin(beeLine, baos, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + beeLine.runCommands(new DispatchCallback(), "!manual"); + String output = baos.toString("UTF8"); + + assertThat(output, containsString(expectedLine)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-38] + * Expand ~ to user's home directory. */ + @Test + public void testRunFromHome() { + try { + Path tmpDir = + Files.createTempDirectory( + Paths.get(System.getProperty("user.home")), + "tmpdir" + System.nanoTime()); + tmpDir.toFile().deleteOnExit(); + + File tmpFile = createTempFile("test", ".sql", tmpDir); + try (Writer fw = new OutputStreamWriter( + new FileOutputStream(tmpFile), StandardCharsets.UTF_8)) { + fw.write("!set outputformat csv\n"); + fw.write("values (1, 2, 3, 4, 5);"); + fw.flush(); + checkScriptFile("!run ~" + File.separatorChar + + tmpDir.getFileName() + + File.separatorChar + tmpFile.getName().toString(), + false, + equalTo(SqlLine.Status.OK), + allOf(containsString("!set outputformat csv"), + containsString("values (1, 2, 3, 4, 5);"))); + } + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-26] + * Flush output for each command when using !record command. + */ + @Test + public void testRecord() { + File file = createTempFile("sqlline", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + /** Test case for + * [SQLLINE-62] + * Expand ~ to user's home directory. */ + @Test + public void testRecordHome() { + File home = new File(System.getProperty("user.home")); + File file; + for (int i = 0;; i++) { + file = new File(home, "sqlline" + i + ".log"); + if (!file.exists()) { + break; + } + } + file.deleteOnExit(); + final String s = "Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "2/4 !set outputformat csv\n" + + "3/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "4/4 !record\n"; + checkScriptFile("!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n", + false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/4 !record .*.log\n" + + s + + "Recording stopped.\n" + + ".*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, RegexMatcher.of(s)); + final boolean delete = file.delete(); + assertThat(delete, is(true)); + } + + /** + * As {@link #testRecord()}, but file name is double-quoted and contains a + * space. + */ + @Test + public void testRecordFilenameWithSpace() { + File file = createTempFile("sqlline file with spaces", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + private static void assertFileContains(File file, Matcher matcher) { + try (BufferedReader br = new BufferedReader( + new InputStreamReader(new FileInputStream(file), + StandardCharsets.UTF_8.name()))) { + final StringWriter stringWriter = new StringWriter(); + for (;;) { + final String line = br.readLine(); + if (line == null) { + break; + } + stringWriter.write(line); + stringWriter.write("\n"); + } + assertThat(toLinux(stringWriter.toString()), matcher); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-61] + * Add !nickname command. + */ + @Test + public void testNickname() { + final String script = "!set outputformat csv\n" + + "values 1;\n" + + "!nickname foo\n" + + "values 2;\n"; + final String expected = "(?s)1/4 !set outputformat csv\n" + + "2/4 values 1;\n" + + "'C1'\n" + + "'1'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/4 !nickname foo\n" + + "4/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * The first command should fail and the second command should not execute. + */ + @Test + public void testBreakOnErrorScriptFile() { + checkScriptFile("select * from abcdefg01;\ncall 100 + 23;\n", + true, + equalTo(SqlLine.Status.OTHER), + not(containsString(" 123 "))); + } + + /** + * Emulation of Apache Hive behavior with throwing exceptions + * while calling {@link DatabaseMetaData#storesUpperCaseIdentifiers()} + * and {@link DatabaseMetaData#supportsTransactionIsolationLevel(int)}. + * + *

    Also please see + * [SQLLINE-183]. + * + * @param meta Mocked JDBCDatabaseMetaData + */ + @Test + public void testExecutionWithNotSupportedMethods( + @Mocked final JDBCDatabaseMetaData meta) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + + // emulate apache hive behavior + meta.supportsTransactionIsolationLevel(4); + result = new SQLException("Method not supported"); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback dc = new DispatchCallback(); + sqlLine.initArgs(args, dc); + os.reset(); + sqlLine.runCommands(dc, + "!set incremental true", + "values 1;"); + final String output = os.toString("UTF8"); + final String line0 = "+-------------+"; + final String line1 = "| C1 |"; + final String line2 = "+-------------+"; + final String line3 = "| 1 |"; + final String line4 = "+-------------+"; + assertThat(output, + CoreMatchers.allOf(containsString(line0), + containsString(line1), + containsString(line2), + containsString(line3), + containsString(line4))); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + @Test + public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta, + @Mocked final JDBCResultSet resultSet) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getSQLKeywords(); + result = ""; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + // Generate an exception on a call to resultSet.next + resultSet.next(); + result = new SQLException("Generated Exception."); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + // If sqlline is not initialized, handleSQLException will print + // the entire stack trace. + // To prevent that, forcibly set init to true. + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "CREATE TABLE rsTest ( a int);", + "insert into rsTest values (1);", + "insert into rsTest values (2);", + "select a from rsTest; "); + String output = os.toString("UTF8"); + assertThat(output, containsString("Generated Exception")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Attempts to execute a missing script file with the -f option to SqlLine. + */ + @Test + public void testNegativeScriptFile() { + // Create and delete a temp file + File scriptFile = createTempFile("sqllinenegative", "temp"); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OTHER)); + assertThat(pair.output, not(containsString(" 123 "))); + } + + /** Displays usage. */ + @Test + public void testUsage() { + Pair pair = run("--help"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + private int countUsage(String output) { + int n = 0; + for (String line : output.split("\n")) { + if (line.contains("Usage")) { + ++n; + } + } + return n; + } + + /** Invalid arguments. */ + @Test + public void testInvalidArguments() { + Pair pair = run("--fuzz"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + /** Result of executing sqlline: status code and output. */ + static class Pair { + final SqlLine.Status status; + final String output; + + Pair(SqlLine.Status status, String output) { + this.status = status; + this.output = output; + } + } + + @Test + public void testIsolationSetting() { + final String script0 = "!isolation TRANSACTION_NONE\n"; + final String expected = "Transaction isolation level TRANSACTION_NONE " + + "is not supported. Default (TRANSACTION_READ_COMMITTED) " + + "will be used instead."; + checkScriptFile(script0, true, equalTo(SqlLine.Status.OTHER), + containsString(expected)); + } + + @Test + public void testDefaultIsolation() { + final String script1 = "!isolation default\n"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + allOf(not(containsString("Transaction isolation level")), + not(containsString("is not supported")))); + } + + /** + * HIVE-4566, "NullPointerException if typeinfo and nativesql commands are + * executed at beeline before a DB connection is established". + */ + @Test + public void testNPE() { + SqlLine sqlLine = new SqlLine(); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + + try { + sqlLine.runCommands(new DispatchCallback(), "!typeinfo"); + String output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + + sqlLine.runCommands(new DispatchCallback(), "!nativesql"); + output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandlerOnStartup() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final String[] args = { + "-e", "!set maxwidth 80", + "-ch", "sqlline.extensions.HelloWorldCommandHandler"}; + begin(sqlLine, os, false, args); + + try { + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!test"); + output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello test")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandler() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + begin(sqlLine, os, false, "-e", "!set maxwidth 80"); + + try { + final String script = "!commandhandler" + + " sqlline.extensions.HelloWorld2CommandHandler" + + " sqlline.extensions.HelloWorldCommandHandler"; + sqlLine.runCommands(new DispatchCallback(), script); + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD2")); + final String expected = "Could not add command handler " + + "sqlline.extensions.HelloWorldCommandHandler as one of commands " + + "[hello, test] is already present"; + assertThat(output, containsString(expected)); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello2")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testTablesCsv() { + final String script = "!set outputformat csv\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("'TABLE_CAT','TABLE_SCHEM','TABLE_NAME',"), + containsString("'PUBLIC','SCOTT','SALGRADE','TABLE','',"))); + } + + /** + * java.lang.NullPointerException test case from + * https://github.com/julianhyde/sqlline/pull/86#issuecomment-410868361 + */ + @Test + public void testCsvDelimiterAndQuoteCharacter() { + final String script = "!set outputformat csv\n" + + "!set csvDelimiter null\n" + + "!set csvQuoteCharacter @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!set csvDelimiter ##\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@null@C2@null@C3@null@C4@null@C5@null@C6@"; + final String line2 = + "@#@null@@@#@@@null@1@null@1969-07-20@null@@null@ 1'2\"3\t4@"; + final String line3 = "@C1@##@C2@##@C3@##@C4@##@C5@##@C6@"; + final String line4 = "@#@##@@@#@@@##@1@##@1969-07-20@##@@##@ 1'2\"3\t4@"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testCsvOneLiner() { + final String script = "!outputformat csv \"'\" @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!outputformat csv & default\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@'@C2@'@C3@'@C4@'@C5@'@C6@"; + final String line2 = + "@#@'@@@#@@@'@1@'@1969-07-20@'@@'@ 1'2\"3\t4@"; + final String line3 = "'C1'&'C2'&'C3'&'C4'&'C5'&'C6'"; + final String line4 = + "'#'&'@#@'&'1'&'1969-07-20'&''&' 1''2\"3\t4'"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testSetForNulls() { + final String script = "!set numberFormat null\n" + + "!set\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("numberFormat null")); + } + + @Test + public void testSetNonIntValuesToIntProperties() { + SqlLine sqlLine = new SqlLine(); + final String headerIntervalScript = "!set headerinterval abc\n"; + checkScriptFile(headerIntervalScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "headerinterval", "abc"))); + + final String rowLimitScript = "!set rowlimit xxx\n"; + checkScriptFile(rowLimitScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "rowlimit", "xxx"))); + } + + @Test + public void testSelectXmlAttributes() { + final String script = "!set outputformat xmlattr\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ']]> 1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString("&4\"/>"))); + } + + @Test + public void testSelectXmlElements() { + final String script = "!set outputformat xmlelements\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' ]]>1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString(""), + containsString("1"), + containsString("-1.5"), + containsString("TRUE"), + containsString("1969-07-20"), + containsString("null"), + containsString(" ]]>1'2\"3\t<>&4"), + containsString(""), + containsString(""))); + } + + @Test + public void testTablesJson() { + final String script = "!set outputformat json\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"TABLE_CAT\":\"PUBLIC\"," + + "\"TABLE_SCHEM\":\"SYSTEM_LOBS\",\"TABLE_NAME\":\"BLOCKS\"," + + "\"TABLE_TYPE\":\"SYSTEM TABLE\",\"REMARKS\":null," + + "\"TYPE_CAT\":null,"))); + } + + @Test + public void testSelectJson() { + final String script = "!set outputformat json\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"C1\":1,\"C2\":-1.5,\"C3\":true," + + "\"C4\":\"1969-07-20\",\"C5\":null," + + "\"C6\":\" 1'2\\\"3\\t4\"}"))); + } + + @Test + public void testNullValue() { + final String script = "!set nullValue %%%\n" + + "!set outputformat csv\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue \"'\"\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue null\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'%%%','-1.5','%%%','1969-07-20','%%%','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'''','-1.5','''','1969-07-20','''','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'null','-1.5','null','1969-07-20','null','null'"))); + } + + @Test + public void testTimeFormat() { + // Use System.err as it is used in sqlline.SqlLineOpts#set + final PrintStream originalErr = System.err; + try { + final ByteArrayOutputStream errBaos = new ByteArrayOutputStream(); + System.setErr( + new PrintStream(errBaos, false, StandardCharsets.UTF_8.name())); + + // successful patterns + final String okTimeFormat = "!set timeFormat HH:mm:ss\n"; + final String defaultTimeFormat = "!set timeFormat default\n"; + final String okDateFormat = "!set dateFormat YYYY-MM-dd\n"; + final String defaultDateFormat = "!set dateFormat default\n"; + final String okTimestampFormat = "!set timestampFormat default\n"; + final String defaultTimestampFormat = "!set timestampFormat default\n"; + + // successful cases + final SqlLine sqlLine = new SqlLine(); + sqlLine.runCommands(new DispatchCallback(), okTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + + // failed patterns + final String wrongTimeFormat = "!set timeFormat qwerty\n"; + final String wrongDateFormat = "!set dateFormat ASD\n"; + final String wrongTimestampFormat = + "!set timestampFormat 'YYYY-MM-ddTHH:MI:ss'\n"; + + // failed cases + sqlLine.runCommands(new DispatchCallback(), wrongTimeFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'q'")); + sqlLine.runCommands(new DispatchCallback(), wrongDateFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'A'")); + sqlLine.runCommands(new DispatchCallback(), wrongTimestampFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'T'")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } finally { + // Set error stream back + System.setErr(originalErr); + } + } + + /** + * Test case for + * [SQLLINE-203] + * !indexes command fails because of Hive bug. + * The bug in question is + * [HIVE-20983] + * HiveResultSetMetaData.getColumnDisplaySize throws for SHORT column. + * + * @param meta Mocked hsqldb {@link JDBCResultSetMetaData} to use in the test + */ + @Test + public void testOutputWithFailingColumnDisplaySize( + @Mocked final JDBCResultSetMetaData meta) { + try { + new Expectations() { + { + meta.getColumnCount(); + result = 3; + + meta.getColumnLabel(1); + result = "TABLE_CAT"; + + meta.getColumnLabel(2); + result = "TABLE_SCHEM"; + + meta.getColumnLabel(3); + result = "TABLE_NAME"; + + meta.getColumnDisplaySize(1); + result = new Exception("getColumnDisplaySize exception"); + } + }; + + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "!set incremental true", + "!set maxwidth 80", + "!set verbose true", + "!indexes"); + assertThat(os.toString("UTF8"), not(containsString("Exception"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests the {@code !connect} command with interactive password submission. + */ + @Test + public void testConnectWithoutPassword() { + new MockUp() { + @Mock + String readPassword(String url) { + return ""; + } + }; + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} property outside of the URL: + * + *

    + * !connect -p PASSWORD_HASH TRUE jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} and {@code ALLOW_LITERALS} properties + * outside of the URL: + * + *
    + * !connect -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE + * jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter2() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!set maxwidth 80"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "select 1;"); + String output = os.toString("UTF8"); + final String expected = "Error:"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing the password in as a hash: + * + *
    + * !connect "jdbc:h2:mem; PASSWORD_HASH=TRUE" sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbProperty() { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + try { + beeLine.runCommands(dc, "!set maxwidth 80"); + + // fail attempt + String fakeNonEmptyPassword = "nonEmptyPasswd"; + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE\" " + + ConnectionSpec.H2.username + + " \"" + fakeNonEmptyPassword + "\""); + String output = os.toString("UTF8"); + final String expected0 = "Error:"; + assertThat(output, containsString(expected0)); + os.reset(); + + // success attempt + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE;ALLOW_LITERALS=NONE\" " + + ConnectionSpec.H2.username + " \"" + + StringUtils.convertBytesToHex(bytes) + + "\""); + beeLine.runCommands(dc, "!set incremental true"); + beeLine.runCommands(dc, "!tables"); + output = os.toString("UTF8"); + final String expected1 = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected1)); + + beeLine.runCommands(dc, "select 5;"); + output = os.toString("UTF8"); + final String expected2 = "Error:"; + assertThat(output, containsString(expected2)); + os.reset(); + + beeLine.runCommands(new DispatchCallback(), "!quit"); + output = os.toString("UTF8"); + assertThat(output, + allOf(not(containsString("Error:")), containsString("!quit"))); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + private static PrintStream getPrintStream(OutputStream os) { + try { + return new PrintStream(os, false, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testReconnect() { + final String script = "!reconnect"; + final String expected = "Reconnecting to \"jdbc:hsqldb:res:scott\"...\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + @Test + public void testTables() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxcolumnwidth 15\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = + "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | |"; + final String line1 = + "| PUBLIC | SYSTEM_LOBS | BLOCKS | SYSTEM TABLE | |"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + @Test + public void testTablesH2() { + connectionSpec = ConnectionSpec.H2; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + /** + * Test case for + * [SQLLINE-107] + * Script fails if the wrong driver is specified with -d option + * and there is a valid registered driver for the specified url. + * + */ + @Test + public void testTablesH2WithErrorDriver() { + connectionSpec = ConnectionSpec.ERROR_H2_DRIVER; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + final String message = "Could not find driver " + + connectionSpec.driver + + "; using registered driver org.h2.Driver instead"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString(message), + not(containsString("NullPointerException")), + containsString(line0), + containsString(line1))); + } + + @Test + public void testH2TablesWithErrorUrl() { + connectionSpec = ConnectionSpec.ERROR_H2_URL; + final String script = "!tables\n"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + CoreMatchers.allOf(containsString("No suitable driver"), + not(containsString("NullPointerException")))); + } + + @Test + public void testEmptyMetadata() { + final String script = "!metadata\n"; + final String line = "Usage: metadata "; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + /** Tests that methods inherited from Object are not included in the list + * of possible metadata methods. */ + @Test + public void testPossibleMetadataValues() { + final String script = "!metadata 1\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString("allProceduresAreCallable"), + containsString("getIndexInfo"), + not(containsString("Exception")), + not(containsString("equals")), + not(containsString("notify")), + not(containsString("wait")), + not(containsString("toString")), + not(containsString("hashCode")), + not(containsString("notifyAll")))); + } + + @Test + public void testMetadataForClassHierarchy() { + final SqlLine beeLine = new SqlLine(); + + new MockUp() { + @Mock + public DatabaseMetaData getMetaData() throws SQLException { + return new CustomDatabaseMetadata( + (JDBCConnection) beeLine.getConnection()); + } + }; + + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.HSQLDB.url + " \"" + + ConnectionSpec.HSQLDB.username + "\" \"" + + ConnectionSpec.HSQLDB.password + "\""); + os.reset(); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + assertThat(output, + allOf(containsString("TABLE_CAT"), + not(containsString("No such method \"getTables\"")))); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testEmptyRecord() { + final String line = "Usage: record "; + checkScriptFile("!record", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyRun() { + final String line = "Usage: run "; + checkScriptFile("!run", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyScript() { + final String line = "Usage: script "; + checkScriptFile("!script", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEscapeSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxColumnWidth 15\n" + + "!set escapeOutput yes\n" + + "values \n" + + "('\n" + + "multiline\n" + + "value') \n" + + ";\n"; + final String line1 = "" + + "+-----------------+\n" + + "| C1 |\n" + + "+-----------------+\n" + + "| \\nmultiline \\nvalue |\n" + + "+-----------------+\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!sql \n" + + "values \n" + + "(1, 2) \n" + + ";\n"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 1 | 2 |\n" + + "+-------------+-------------+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAllMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!all \n" + + "values \n" + + "(1, '2') \n" + + ";\n"; + final String line1 = "" + + "+-------------+----+\n" + + "| C1 | C2 |\n" + + "+-------------+----+\n" + + "| 1 | 2 |\n" + + "+-------------+----+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAppInfoMessage() { + Pair pair = run("-e", "!set maxwidth 80"); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + containsString(Application.DEFAULT_APP_INFO_MESSAGE)); + + String[] args = {"-e", "!set maxwidth 80", "-ac", "INCORRECT_CLASS_NAME"}; + pair = run(args); + assertThat(pair.output, + containsString("Could not initialize INCORRECT_CLASS_NAME")); + assertThat(pair.output, + containsString(CustomApplication.DEFAULT_APP_INFO_MESSAGE)); + + String[] args2 = {"-e", "!set maxwidth 80", + "-ac", "sqlline.extensions.CustomApplication"}; + pair = run(args2); + assertThat(pair.output, + containsString(CustomApplication.CUSTOM_INFO_MESSAGE)); + } + + @Test + public void testCustomOutputFormats() { + // json format was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!set outputformat json\n" + + "values 1;"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("Unknown outputFormat \"json\"")); + } + + @Test + public void testCustomCommands() { + // table command was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Unknown command: tables")); + } + + @Test + public void testAppConfigReset() { + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!appconfig sqlline.Application\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("TABLE_CAT")); + } + + @Test + public void testCustomOpts() { + // nulls are displayed as custom_null + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "values(null)"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("custom_null")); + } + + @Test + public void testScanForEmptyAllowedDrivers() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.emptyList(); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("No driver classes found")); + } + + @Test + public void testScanForOnlyH2Allowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.h2.Driver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 1.4 org.h2.Driver"), + not(containsString("org.hsqldb.jdbc.JDBCDriver")))); + } + + @Test + public void testScanForOnlyHsqldbAllowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.hsqldb.jdbc.JDBCDriver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 2.4 org.hsqldb.jdbc.JDBCDriver"), + not(containsString("org.h2.Driver")))); + } + + @Test + public void testVersion() { + final String script = "!set\n"; + try { + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(new Application().getVersion())); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSetVersion() { + final String script = "!set version test-version\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("version property is read only")); + } + + @Test + public void testSetPropertySuccess() { + final String script = "!set timeout\n" + + "!set timeout 200\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("timeout -1"), + containsString("timeout 200"))); + } + + @Test + public void testSetPropertyFailure() { + final String script = "!set unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testSetUsage() { + final String script = "!set 1 2 3"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: set [all | []]")); + } + + @Test + public void testSetWrongValueToEnumTypeProperties() { + Collection propertiesWithAvailableValues = + Arrays.stream(BuiltInProperty.values()) + .filter(t -> !t.getAvailableValues().isEmpty()) + .collect(Collectors.toSet()); + final String wrongValue = "wrong_value"; + for (BuiltInProperty property: propertiesWithAvailableValues) { + final String script = + "!set " + property.propertyName() + " " + wrongValue + "\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf( + containsString("Unknown " + property.propertyName() + " \"" + + wrongValue + "\""), + not(containsString("Exception")))); + } + } + + @Test + public void testResetSuccess() { + final String script = "!set timeout 200\n" + + "!reset timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("[timeout] was reset to [-1]")); + } + + @Test + public void testResetFailure() { + final String script = "!reset unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testResetAll() { + final String script = "!set timeout 200\n" + + "!reset all\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("All properties were reset to their defaults."), + containsString("timeout -1"))); + } + + @Test + public void testResetUsage() { + final String script = "!reset"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: reset (all | )")); + } + + @Test + public void testRerun() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:!/ 4\n" + + "1536743104551:!/ 5\n" + + "1536743104551:!/ 2\n" + + "1536743104551:!/ 7\n" + + "1536743107526:!history\n" + + "1536743115431:!/ 3\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set incremental true", + "!set maxcolumnwidth 30", + "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + "\"\""); + os.reset(); + + beeLine.runCommands(dc, "!/ 1"); + String output = os.toString("UTF8"); + final String expected0 = "+----------------------------+"; + final String expected1 = "| C1 |"; + final String expected2 = "1 row selected"; + assertThat(output, + allOf(containsString(expected0), + containsString(expected1), + containsString(expected2))); + os.reset(); + + beeLine.runCommands(dc, "!/ 4"); + output = os.toString("UTF8"); + String expectedLine3 = "Cycled rerun of commands from history [2, 4]"; + assertThat(output, containsString(expectedLine3)); + os.reset(); + + beeLine.runCommands(dc, "!/ 3"); + output = os.toString("UTF8"); + String expectedLine4 = "Cycled rerun of commands from history [3, 5, 7]"; + assertThat(output, containsString(expectedLine4)); + os.reset(); + + beeLine.runCommands(dc, "!/ 8"); + output = os.toString("UTF8"); + String expectedLine5 = "Cycled rerun of commands from history [8]"; + assertThat(output, containsString(expectedLine5)); + os.reset(); + + beeLine.runCommands(dc, "!rerun " + Integer.MAX_VALUE); + output = os.toString("UTF8"); + String expectedLine6 = + "Usage: rerun , available range of offset is -7..8"; + assertThat(output, containsString(expectedLine6)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMaxColumnWidthIncremental() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line2 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line3 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testMaxColumnWidthBuffered() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line1 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line2 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line3 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + /** Tests with incrementalBufferRows = -1; query stays in non-incremental + * mode. */ + @Test + public void testIncrementalBufferRows() { + final String script1 = "!set incrementalBufferRows -1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line1 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + /** Tests with incrementalBufferRows = 0; query goes straight into + * incremental mode. */ + @Test + public void testIncrementalBufferRows2() { + final String script2 = "!set incrementalBufferRows 0\n" + + "!set incremental false\n" + + "select * from (values (1, 2), (1, 20), (111, 20), (11, 2222), (1, 22))"; + final String line2 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 1 | 2 |\n" + + "| 1 | 20 |\n" + + "| 111 | 20 |\n" + + "| 11 | 2222 |\n" + + "| 1 | 22 |\n" + + "+----+----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + } + + /** Tests with incrementalBufferRows = 1; query starts in non-incremental mode + * and switches to incremental after 1 row. */ + @Test + public void testIncrementalBufferRows3() { + final String script3 = "!set incrementalBufferRows 1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222), (111, 2222))"; + final String line3 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "| 111 | 2222 |\n" + + "+----+----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + } + + /** Tests with incrementalBufferRows = 4; query starts in non-incremental mode + * and rows run out before the limit is reached. */ + @Test + public void testIncrementalBufferRows4() { + final String script4 = "!set incrementalBufferRows 4\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line4 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testIncrementalBufferRows5() { + // With incrementalBufferRows default (1000), query starts and + // stays in incremental mode. + final String script5 = "!set incrementalBufferRows default\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2))"; + final String line5 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "+----+----+"; + checkScriptFile(script5, true, equalTo(SqlLine.Status.OK), + containsString(line5)); + } + + @Test + public void testMaxHistoryFileRows() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:SELECT \\n 'asd' as \"sdf\", 4 \\n \\n as \\n c2;\\n\n" + + "1536743104551:SELECT \\n 'asd' \\n as \\n c2;\\n\n" + + "1536743104551:!/ 2\n" + + "1536743104551:SELECT \\n 2123 \\n as \\n c2 from dual;\\n\n" + + "1536743107526:!history\n" + + "1536743115431:SELECT \\n 2 \\n as \\n c2;\n" + + "1536743115431:SELECT \\n '213' \\n as \\n c1;\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + bw.close(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + final int maxLines = 3; + beeLine.runCommands(dc, "!set maxHistoryFileRows " + maxLines); + os.reset(); + beeLine.runCommands(dc, "!history"); + assertEquals(maxLines + 1, + os.toString("UTF8").split("\\s+\\d{2}:\\d{2}:\\d{2}\\s+").length); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSave() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + SqlLine.Status status = begin(beeLine, os, false, + "-e", "!save"); + assertThat(status, equalTo(SqlLine.Status.OK)); + final DispatchCallback dc = new DispatchCallback(); + + assertThat(os.toString("UTF8"), + containsString("Saving preferences to")); + os.reset(); + beeLine.runCommands(dc, "!set"); + assertThat(os.toString("UTF8"), + allOf(containsString("autoCommit"), + not(containsString("Unknown property:")))); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScript() { + final File file = createTempFile("sqlline", ".script"); + final String script = "!script " + file.getAbsolutePath() + "\n" + + "values (100, 200);\n" + + "!set maxcolumnwidth -1\n" + + "!script\n" + + "values (1, 2);\n"; + final String expected = "(?s)1/5 !script.*" + + "2/5 values \\(100, 200\\);.*" + + "3/5 !set maxcolumnwidth -1.*" + + "4/5 !script.*" + + "5/5 values \\(1, 2\\);.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + + final String output = "values \\(100, 200\\);\n" + + "!set maxcolumnwidth -1\n"; + assertFileContains(file, RegexMatcher.of(output)); + } + + @Test + public void testStartupArgsWithoutUrl() { + try { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests setting the "confirm" property. + */ + @Test + public void testConfirmFlag() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + begin(line, os, false, "-e", "!set confirm true"); + assertThat(line.getOpts().getConfirm(), is(true)); + begin(line, os, false, "-e", "!set confirm false"); + assertThat(line.getOpts().getConfirm(), is(false)); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests that the "confirm" property works. + */ + @Test + public void testConfirmFlagEffects() { + new MockUp() { + @Mock + int getUserAnswer(String question, int... allowedAnswers) { + return 'n'; + } + }; + + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + assertThat(line.getOpts().getConfirmPattern(), is("default")); + String script = "CREATE TABLE dummy_test(pk int);\n" + + "INSERT INTO dummy_test(pk) VALUES(1);\n" + + "INSERT INTO dummy_test(pk) VALUES(2);\n" + + "INSERT INTO dummy_test(pk) VALUES(3);\n" + + "DELETE FROM dummy_test;\n" + + "DROP TABLE dummy_test;\n"; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OK), + containsString(" ")); + + script = "!set confirm true\n" + script; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OTHER), + containsString(line.loc("abort-action"))); + } + + /** + * Tests that the "confirmPattern" property works. + */ + @Test + public void testConfirmPattern() { + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i:(TRUNCATE|ALTER))\""); + assertThat(line.getOpts().getConfirmPattern(), + is("^(?i:(TRUNCATE|ALTER))")); + + begin(line, os, false, "-e", "!set confirmPattern default"); + assertThat(line.getOpts().getConfirmPattern(), + is(line.loc("default-confirm-pattern"))); + } + + /** + * Test for illegal regex in confirmPattern + */ + @Test + public void testExceptionConfirmPattern() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + SqlLine.Status status = + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i*:(TRUNCATE|ALTER))\""); + assertThat(status, equalTo(SqlLine.Status.OK)); + assertThat(os.toString("UTF8"), containsString("invalid regex")); + os.reset(); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** Information necessary to create a JDBC connection. Specify one to run + * tests against a different database. (hsqldb is the default.) */ + public static class ConnectionSpec { + public final String url; + public final String username; + public final String password; + public final String driver; + + public ConnectionSpec(String url, String username, String password, + String driver) { + this.url = url; + this.username = username; + this.password = password; + this.driver = driver; + } + + public static final ConnectionSpec H2 = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec ERROR_H2_DRIVER = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "ERROR_DRIVER"); + + public static final ConnectionSpec ERROR_H2_URL = + new ConnectionSpec("ERROR_URL", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec HSQLDB = + new ConnectionSpec( + ScottHsqldb.URI, ScottHsqldb.USER, ScottHsqldb.PASSWORD, + "org.hsqldb.jdbcDriver"); + + public static final ConnectionSpec MYSQL = + new ConnectionSpec( + "jdbc:mysql://localhost/scott", "scott", "tiger", + "com.mysql.jdbc.Driver"); + } + + /** Regular expression matcher. */ + private static class RegexMatcher extends BaseMatcher { + private final String pattern; + + RegexMatcher(String pattern) { + super(); + this.pattern = pattern; + } + + public static RegexMatcher of(String pattern) { + return new RegexMatcher(pattern); + } + + public boolean matches(Object o) { + return o instanceof String + && ((String) o).matches(pattern); + } + + public void describeTo(Description description) { + description.appendText("regular expression ").appendText(pattern); + } + } + +} + +// End SqlLineArgsTest.java + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PrintStream` acquired by call to `begin(...)` at line 1109 is not released after line 1124. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SqlLineArgsTest.testCommandHandlerOnStartup() + +### Procedure Id: +sqlline.SqlLineArgsTest.testCommandHandlerOnStartup():void.d8337191ffbfe899975ebebaa654f38a + +### File: +src/test/java/sqlline/SqlLineArgsTest.java + +### Key: +SqlLineArgsTest.java|testCommandHandlerOnStartup|RESOURCE_LEAK + +### Node Key: +c9c172f117ebe9d8a98ace40e0eeb16f + +### Hash: +403598aa38f56cfe3891ca54fb31ea3c + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8137/instruction.md b/inferredbugs-8137/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..65e469ecc53614c2708584b5eb755768611c9f94 --- /dev/null +++ b/inferredbugs-8137/instruction.md @@ -0,0 +1,184 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** openkeepass +**Bug ID:** 20 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.slackspace.openkeepass.api; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.zip.GZIPInputStream; + +import de.slackspace.openkeepass.crypto.CryptoInformation; +import de.slackspace.openkeepass.crypto.Decrypter; +import de.slackspace.openkeepass.crypto.ProtectedStringCrypto; +import de.slackspace.openkeepass.crypto.Salsa20; +import de.slackspace.openkeepass.domain.CompressionAlgorithm; +import de.slackspace.openkeepass.domain.CrsAlgorithm; +import de.slackspace.openkeepass.domain.KeePassFile; +import de.slackspace.openkeepass.domain.KeePassHeader; +import de.slackspace.openkeepass.exception.KeePassDatabaseUnreadableException; +import de.slackspace.openkeepass.processor.DecryptionStrategy; +import de.slackspace.openkeepass.processor.IconEnricher; +import de.slackspace.openkeepass.processor.ProtectedValueProcessor; +import de.slackspace.openkeepass.stream.HashedBlockInputStream; +import de.slackspace.openkeepass.util.SafeInputStream; +import de.slackspace.openkeepass.util.StreamUtils; +import de.slackspace.openkeepass.xml.KeePassDatabaseXmlParser; + +public class KeePassDatabaseReader { + + protected Decrypter decrypter = new Decrypter(); + protected KeePassDatabaseXmlParser keePassDatabaseXmlParser = new KeePassDatabaseXmlParser(); + + private KeePassHeader keepassHeader; + + public KeePassDatabaseReader(KeePassHeader keepassHeader) { + this.keepassHeader = keepassHeader; + } + + public KeePassFile decryptAndParseDatabase(byte[] key, byte[] keepassFile) { + try { + byte[] aesDecryptedDbFile = decryptStream(key, keepassFile); + SafeInputStream decryptedStream = skipMetadata(aesDecryptedDbFile); + byte[] hashedBlockBytes = unHashBlockStream(decryptedStream); + + byte[] decompressed = decompressStream(hashedBlockBytes); + ProtectedStringCrypto protectedStringCrypto = getProtectedStringCrypto(); + + return parseDatabase(decompressed, protectedStringCrypto); + } catch (IOException e) { + throw new KeePassDatabaseUnreadableException("Could not open database file", e); + } + } + + private byte[] unHashBlockStream(SafeInputStream decryptedStream) throws IOException { + HashedBlockInputStream hashedBlockInputStream = new HashedBlockInputStream(decryptedStream); + byte[] hashedBlockBytes = StreamUtils.toByteArray(hashedBlockInputStream); + return hashedBlockBytes; + } + + private KeePassFile parseDatabase(byte[] decompressed, ProtectedStringCrypto protectedStringCrypto) { + KeePassFile unprocessedKeepassFile = keePassDatabaseXmlParser.fromXml(new ByteArrayInputStream(decompressed)); + new ProtectedValueProcessor().processProtectedValues(new DecryptionStrategy(protectedStringCrypto), unprocessedKeepassFile); + + return new IconEnricher().enrichNodesWithIconData(unprocessedKeepassFile); + } + + private ProtectedStringCrypto getProtectedStringCrypto() { + ProtectedStringCrypto protectedStringCrypto; + if (keepassHeader.getCrsAlgorithm().equals(CrsAlgorithm.Salsa20)) { + protectedStringCrypto = Salsa20.createInstance(keepassHeader.getProtectedStreamKey()); + } else { + throw new UnsupportedOperationException("Only Salsa20 is supported as CrsAlgorithm at the moment!"); + } + return protectedStringCrypto; + } + + private byte[] decompressStream(byte[] hashedBlockBytes) throws IOException { + byte[] decompressed = hashedBlockBytes; + + // Unzip if necessary + if (keepassHeader.getCompression().equals(CompressionAlgorithm.Gzip)) { + GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(hashedBlockBytes)); + decompressed = StreamUtils.toByteArray(gzipInputStream); + } + + return decompressed; + } + + private SafeInputStream skipMetadata(byte[] aesDecryptedDbFile) throws IOException { + SafeInputStream decryptedStream = new SafeInputStream(new ByteArrayInputStream(aesDecryptedDbFile)); + + byte[] startBytes = new byte[32]; + + // Metadata must be skipped here + decryptedStream.skipSafe(KeePassHeader.VERSION_SIGNATURE_LENGTH + keepassHeader.getHeaderSize()); + decryptedStream.readSafe(startBytes); + + // Compare startBytes + if (!Arrays.equals(keepassHeader.getStreamStartBytes(), startBytes)) { + throw new KeePassDatabaseUnreadableException( + "The keepass database file seems to be corrupt or cannot be decrypted."); + } + + return decryptedStream; + } + + private byte[] decryptStream(byte[] key, byte[] keepassFile) throws IOException { + CryptoInformation cryptoInformation = new CryptoInformation(KeePassHeader.VERSION_SIGNATURE_LENGTH, keepassHeader.getMasterSeed(), + keepassHeader.getTransformSeed(), keepassHeader.getEncryptionIV(), keepassHeader.getTransformRounds(), keepassHeader.getHeaderSize()); + return decrypter.decryptDatabase(key, cryptoInformation, keepassFile); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `de.slackspace.openkeepass.stream.HashedBlockInputStream` acquired to `hashedBlockInputStream` by call to `new()` at line 52 is not released after line 53. +**Note**: potential exception at line 53 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +byte[] KeePassDatabaseReader.unHashBlockStream(SafeInputStream) + +### Procedure Id: +de.slackspace.openkeepass.api.KeePassDatabaseReader.unHashBlockStream(de.slackspace.openkeepass.util.1471d9d64d1dc2b770d80fde22d4c98b + +### File: +src/main/java/de/slackspace/openkeepass/api/KeePassDatabaseReader.java + +### Key: +KeePassDatabaseReader.java|unHashBlockStream|RESOURCE_LEAK + +### Node Key: +f09f436fb0f5a58e4eb6c6bcc0fb6b8e + +### Hash: +7e79e76d4ff1d57b73760634eab9f99b + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8138/instruction.md b/inferredbugs-8138/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..28cd06986122e17107f77cba490954c12b5717b7 --- /dev/null +++ b/inferredbugs-8138/instruction.md @@ -0,0 +1,267 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** openkeepass +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.slackspace.openkeepass.reader; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.util.UUID; + +import javax.xml.bind.DatatypeConverter; + +import org.junit.Assert; +import org.junit.Test; + +import de.slackspace.openkeepass.KeePassDatabase; +import de.slackspace.openkeepass.crypto.Salsa20; +import de.slackspace.openkeepass.domain.CompressionAlgorithm; +import de.slackspace.openkeepass.domain.CrsAlgorithm; +import de.slackspace.openkeepass.domain.CustomIcon; +import de.slackspace.openkeepass.domain.CustomIconBuilder; +import de.slackspace.openkeepass.domain.CustomIcons; +import de.slackspace.openkeepass.domain.CustomIconsBuilder; +import de.slackspace.openkeepass.domain.Entry; +import de.slackspace.openkeepass.domain.EntryBuilder; +import de.slackspace.openkeepass.domain.Group; +import de.slackspace.openkeepass.domain.GroupBuilder; +import de.slackspace.openkeepass.domain.KeePassFile; +import de.slackspace.openkeepass.domain.KeePassFileBuilder; +import de.slackspace.openkeepass.domain.KeePassHeader; +import de.slackspace.openkeepass.domain.Meta; +import de.slackspace.openkeepass.domain.MetaBuilder; +import de.slackspace.openkeepass.domain.zipper.GroupZipper; +import de.slackspace.openkeepass.processor.DecryptionStrategy; +import de.slackspace.openkeepass.processor.ProtectedValueProcessor; +import de.slackspace.openkeepass.util.ByteUtils; +import de.slackspace.openkeepass.xml.KeePassDatabaseXmlParser; + +public class KeepassDatabaseWriterTest { + + private byte[] protectedStreamKey = ByteUtils + .hexStringToByteArray("ec77a2169769734c5d26e5341401f8d7b11052058f8455d314879075d0b7e257"); + + @Test + public void whenWritingDatabaseFileShouldBeAbleToReadItAlso() throws FileNotFoundException { + FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); + KeePassFile keePassFile = new KeePassDatabaseXmlParser().fromXml(fileInputStream, + Salsa20.createInstance(protectedStreamKey)); + new ProtectedValueProcessor().processProtectedValues(new DecryptionStrategy(Salsa20.createInstance(protectedStreamKey)), keePassFile); + + FileOutputStream file = new FileOutputStream("target/test-classes/writeDatabase.kdbx"); + KeePassDatabase.write(keePassFile, "abcdefg", file); + + KeePassDatabase database = KeePassDatabase.getInstance("target/test-classes/writeDatabase.kdbx"); + KeePassHeader header = database.getHeader(); + + Assert.assertEquals(CompressionAlgorithm.Gzip, header.getCompression()); + Assert.assertEquals(CrsAlgorithm.Salsa20, header.getCrsAlgorithm()); + Assert.assertEquals(8000, header.getTransformRounds()); + + KeePassFile openDatabase = database.openDatabase("abcdefg"); + + Entry sampleEntry = openDatabase.getEntryByTitle("Sample Entry"); + Assert.assertEquals("User Name", sampleEntry.getUsername()); + Assert.assertEquals("Password", sampleEntry.getPassword()); + + Entry sampleEntryTwo = openDatabase.getEntryByTitle("Sample Entry #2"); + Assert.assertEquals("Michael321", sampleEntryTwo.getUsername()); + Assert.assertEquals("12345", sampleEntryTwo.getPassword()); + } + + @Test + public void shouldCreateNewDatabaseFile() throws FileNotFoundException { + Entry entryOne = new EntryBuilder("First entry").username("Carl").password("Carls secret").build(); + + KeePassFile keePassFile = new KeePassFileBuilder("testDB").addTopEntries(entryOne).build(); + + String dbFilename = "target/test-classes/writeNewDatabase.kdbx"; + KeePassDatabase.write(keePassFile, "abc", new FileOutputStream(dbFilename)); + + KeePassDatabase keePassDb = KeePassDatabase.getInstance(dbFilename); + KeePassFile database = keePassDb.openDatabase("abc"); + Entry entryByTitle = database.getEntryByTitle("First entry"); + + Assert.assertEquals(entryOne.getTitle(), entryByTitle.getTitle()); + } + + @Test + public void shouldBuildKeePassFileWithTreeStructure() throws FileNotFoundException { + /* + * Should create the following structure: + * + * Root | |-- First entry (E) |-- Banking (G) | |-- Internet (G) | |-- + * Shopping (G) |-- Second entry (E) + * + */ + Group root = new GroupBuilder().addEntry(new EntryBuilder("First entry").build()) + .addGroup(new GroupBuilder("Banking").build()) + .addGroup(new GroupBuilder("Internet") + .addGroup( + new GroupBuilder("Shopping").addEntry(new EntryBuilder("Second entry").build()).build()) + .build()) + .build(); + + KeePassFile keePassFile = new KeePassFileBuilder("writeTreeDB").addTopGroups(root).build(); + + String dbFilename = "target/test-classes/writeTreeDB.kdbx"; + KeePassDatabase.write(keePassFile, "abc", new FileOutputStream(dbFilename)); + + KeePassDatabase keePassDb = KeePassDatabase.getInstance(dbFilename); + KeePassFile database = keePassDb.openDatabase("abc"); + + Assert.assertEquals("Banking", database.getTopGroups().get(0).getName()); + Assert.assertEquals("Internet", database.getTopGroups().get(1).getName()); + Assert.assertEquals("First entry", database.getTopEntries().get(0).getTitle()); + Assert.assertEquals("Shopping", database.getTopGroups().get(1).getGroups().get(0).getName()); + Assert.assertEquals("Second entry", + database.getTopGroups().get(1).getGroups().get(0).getEntries().get(0).getTitle()); + } + + @Test + public void shouldModifiyGroupInKeePassFile() throws FileNotFoundException { + String password = "123456"; + KeePassDatabase keePassDb = KeePassDatabase.getInstance("target/test-classes/fullBlownDatabase.kdbx"); + KeePassFile database = keePassDb.openDatabase(password); + + Group group = database.getGroupByName("test"); + Group modifiedGroup = new GroupBuilder(group).name("test2").build(); + + GroupZipper zipper = new KeePassFileBuilder(database).getZipper().down().right().right().right().right().down(); + KeePassFile modifiedDatabase = zipper.replace(modifiedGroup).close(); + + String dbFilename = "target/test-classes/fullBlownDatabaseModified.kdbx"; + KeePassDatabase.write(modifiedDatabase, password, new FileOutputStream(dbFilename)); + KeePassFile databaseReadFromHdd = KeePassDatabase.getInstance(dbFilename).openDatabase(password); + + Assert.assertNotNull("Banking", databaseReadFromHdd.getGroupByName("test2")); + Assert.assertEquals(2, databaseReadFromHdd.getGroupByName("test2").getEntries().size()); + } + + @Test + public void shouldModifyMetadataAndRenameGeneralNodeThenWriteAndReadDatabase() throws FileNotFoundException { + String password = "abcdefg"; + String originalDbFile = "target/test-classes/testDatabase.kdbx"; + String modifiedDbFile = "target/test-classes/modifiedtestDatabase2.kdbx"; + + KeePassFile database = KeePassDatabase.getInstance(originalDbFile).openDatabase(password); + + // change db name + Meta meta = new MetaBuilder(database.getMeta()).databaseName("differentName").build(); + + // change general node + GroupZipper zipper = new GroupZipper(database).down(); + Group renamedNode = new GroupBuilder(zipper.getNode()).name("Misc").build(); + KeePassFile modifiedKeepassFile = zipper.replace(renamedNode).replaceMeta(meta).close(); + + // write + KeePassDatabase.write(modifiedKeepassFile, password, modifiedDbFile); + + // read and assert + KeePassFile readModifiedDb = KeePassDatabase.getInstance(modifiedDbFile).openDatabase(password); + Assert.assertEquals("differentName", readModifiedDb.getMeta().getDatabaseName()); + Assert.assertEquals("Misc", readModifiedDb.getTopGroups().get(0).getName()); + } + + @Test + public void shouldWriteDatabaseWithCustomIcon() throws FileNotFoundException { + String base64Icon = "iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAADXqc3KAAAB+FBMVEUAAAA/mUPidDHiLi5Cn0XkNTPmeUrkdUg/m0Q0pEfcpSbwaVdKskg+lUP4zA/iLi3msSHkOjVAmETdJSjtYFE/lkPnRj3sWUs8kkLeqCVIq0fxvhXqUkbVmSjwa1n1yBLepyX1xxP0xRXqUkboST9KukpHpUbuvRrzrhF/ljbwaljuZFM4jELaoSdLtElJrUj1xxP6zwzfqSU4i0HYnydMtUlIqUfywxb60AxZqEXaoifgMCXptR9MtklHpEY2iUHWnSjvvRr70QujkC+pUC/90glMuEnlOjVMt0j70QriLS1LtEnnRj3qUUXfIidOjsxAhcZFo0bjNDH0xxNLr0dIrUdmntVTkMoyfL8jcLBRuErhJyrgKyb4zA/5zg3tYFBBmUTmQTnhMinruBzvvhnxwxZ/st+Ktt5zp9hqota2vtK6y9FemNBblc9HiMiTtMbFtsM6gcPV2r6dwroseLrMrbQrdLGdyKoobKbo3Zh+ynrgVllZulTsXE3rV0pIqUf42UVUo0JyjEHoS0HmsiHRGR/lmRz/1hjqnxjvpRWfwtOhusaz0LRGf7FEfbDVmqHXlJeW0pbXq5bec3fX0nTnzmuJuWvhoFFhm0FtrziBsjaAaDCYWC+uSi6jQS3FsSfLJiTirCOkuCG1KiG+wSC+GBvgyhTszQ64Z77KAAAARXRSTlMAIQRDLyUgCwsE6ebm5ubg2dLR0byXl4FDQzU1NDEuLSUgC+vr6urq6ubb29vb2tra2tG8vLu7u7uXl5eXgYGBgYGBLiUALabIAAABsElEQVQoz12S9VPjQBxHt8VaOA6HE+AOzv1wd7pJk5I2adpCC7RUcHd3d3fXf5PvLkxheD++z+yb7GSRlwD/+Hj/APQCZWxM5M+goF+RMbHK594v+tPoiN1uHxkt+xzt9+R9wnRTZZQpXQ0T5uP1IQxToyOAZiQu5HEpjeA4SWIoksRxNiGC1tRZJ4LNxgHgnU5nJZBDvuDdl8lzQRBsQ+s9PZt7s7Pz8wsL39/DkIfZ4xlB2Gqsq62ta9oxVlVrNZpihFRpGO9fzQw1ms0NDWZz07iGkJmIFH8xxkc3a/WWlubmFkv9AB2SEpDvKxbjidN2faseaNV3zoHXvv7wMODJdkOHAegweAfFPx4G67KluxzottCU9n8CUqXzcIQdXOytAHqXxomvykhEKN9EFutG22p//0rbNvHVxiJywa8yS2KDfV1dfbu31H8jF1RHiTKtWYeHxUvq3bn0pyjCRaiRU6aDO+gb3aEfEeVNsDgm8zzLy9egPa7Qt8TSJdwhjplk06HH43ZNJ3s91KKCHQ5x4sw1fRGYDZ0n1L4FKb9/BP5JLYxToheoFCVxz57PPS8UhhEpLBVeAAAAAElFTkSuQmCC"; + + UUID iconUuid = UUID.randomUUID(); + byte[] customPng = DatatypeConverter.parseBase64Binary(base64Icon); + + // build database + CustomIcon customIcon = new CustomIconBuilder().uuid(iconUuid).data(customPng).build(); + CustomIcons customIcons = new CustomIconsBuilder().addIcon(customIcon).build(); + + Meta meta = new MetaBuilder("iconTest").customIcons(customIcons).build(); + Entry entry1 = new EntryBuilder("1").customIconUuid(iconUuid).build(); + Group groupA = new GroupBuilder("A").customIconUuid(iconUuid).addEntry(entry1).build(); + + KeePassFile keePassFile = new KeePassFileBuilder(meta).addTopGroups(groupA).build(); + + // write + String dbFilename = "target/test-classes/databaseWithCustomIcon.kdbx"; + KeePassDatabase.write(keePassFile, "abcdefg", dbFilename); + + // read and assert + KeePassFile readDb = KeePassDatabase.getInstance(dbFilename).openDatabase("abcdefg"); + Assert.assertEquals("iconTest", readDb.getMeta().getDatabaseName()); + Assert.assertEquals(iconUuid, readDb.getGroupByName("A").getCustomIconUuid()); + Assert.assertEquals(base64Icon, DatatypeConverter.printBase64Binary(readDb.getGroupByName("A").getIconData())); + Assert.assertEquals(iconUuid, readDb.getEntryByTitle("1").getCustomIconUuid()); + Assert.assertEquals(base64Icon, DatatypeConverter.printBase64Binary(readDb.getEntryByTitle("1").getIconData())); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired to `fileInputStream` by call to `FileInputStream(...)` at line 43 is not released after line 67. +**Note**: potential exception at line 45 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void KeepassDatabaseWriterTest.whenWritingDatabaseFileShouldBeAbleToReadItAlso() + +### Procedure Id: +de.slackspace.openkeepass.reader.KeepassDatabaseWriterTest.whenWritingDatabaseFileShouldBeAbleToRead.a8a5e671b3a4c3c7bcffca56e2f597d5 + +### File: +src/test/java/de/slackspace/openkeepass/reader/KeepassDatabaseWriterTest.java + +### Key: +KeepassDatabaseWriterTest.java|whenWritingDatabaseFileShouldBeAbleToReadItAlso|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +fe21d39523b13c23c676aff25147f423 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8139/instruction.md b/inferredbugs-8139/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f08a4e6fc572c4ef42be01d667cea2a54a62e515 --- /dev/null +++ b/inferredbugs-8139/instruction.md @@ -0,0 +1,233 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** openkeepass +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.slackspace.openkeepass; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Arrays; +import java.util.zip.GZIPInputStream; + +import de.slackspace.openkeepass.crypto.Decrypter; +import de.slackspace.openkeepass.crypto.ProtectedStringCrypto; +import de.slackspace.openkeepass.crypto.Salsa20; +import de.slackspace.openkeepass.domain.CompressionAlgorithm; +import de.slackspace.openkeepass.domain.CrsAlgorithm; +import de.slackspace.openkeepass.domain.KeePassFile; +import de.slackspace.openkeepass.domain.KeePassHeader; +import de.slackspace.openkeepass.exception.KeepassDatabaseUnreadable; +import de.slackspace.openkeepass.parser.XmlParser; +import de.slackspace.openkeepass.stream.HashedBlockInputStream; +import de.slackspace.openkeepass.util.ByteUtils; +import de.slackspace.openkeepass.util.StreamUtils; + +public class KeePassDatabase { + + // KeePass 2.x signature + private static final int DATABASE_V2_FILE_SIGNATURE_1 = 0x9AA2D903 & 0xFF; + private static final int DATABASE_V2_FILE_SIGNATURE_2 = 0xB54BFB67 & 0xFF; + + // KeePass 1.x signature + private static final int OLD_DATABASE_V1_FILE_SIGNATURE_1 = 0x9AA2D903 & 0xFF; + private static final int OLD_DATABASE_V1_FILE_SIGNATURE_2 = 0xB54BFB65 & 0xFF; + + // KeePass version signature length in bytes + public static final int VERSION_SIGNATURE_LENGTH = 12; + + private KeePassHeader keepassHeader = new KeePassHeader(); + private Decrypter decrypter = new Decrypter(); + private XmlParser xmlParser = new XmlParser(); + private byte[] keepassFile; + + private KeePassDatabase(InputStream inputStream) { + try { + keepassFile = StreamUtils.toByteArray(inputStream); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static KeePassDatabase getInstance(InputStream inputStream) { + KeePassDatabase reader = new KeePassDatabase(inputStream); + + try { + reader.checkVersionSupport(); + reader.readHeader(); + return reader; + } + catch(IOException e) { + throw new RuntimeException("Could not read input stream", e); + } + } + + private void checkVersionSupport() throws IOException { + BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(keepassFile)); + + byte[] signature = new byte[VERSION_SIGNATURE_LENGTH]; + bufferedInputStream.read(signature); + ByteBuffer signatureBuffer = ByteBuffer.wrap(signature); + signatureBuffer.order(ByteOrder.LITTLE_ENDIAN); + + int signaturePart1 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); + int signaturePart2 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); + + if(signaturePart1 == DATABASE_V2_FILE_SIGNATURE_1 && signaturePart2 == DATABASE_V2_FILE_SIGNATURE_2) { + return; + } + else if(signaturePart1 == OLD_DATABASE_V1_FILE_SIGNATURE_1 && signaturePart2 == OLD_DATABASE_V1_FILE_SIGNATURE_2) { + throw new UnsupportedOperationException("The provided KeePass database file seems to be from KeePass 1.x which is not supported!"); + } + else { + throw new UnsupportedOperationException("The provided file seems to be no KeePass database file!"); + } + } + + private void readHeader() throws IOException { + BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(keepassFile)); + bufferedInputStream.skip(VERSION_SIGNATURE_LENGTH); // skip version + + while(true) { + try { + int fieldId = bufferedInputStream.read(); + byte[] fieldLength = new byte[2]; + bufferedInputStream.read(fieldLength); + + ByteBuffer fieldLengthBuffer = ByteBuffer.wrap(fieldLength); + fieldLengthBuffer.order(ByteOrder.LITTLE_ENDIAN); + int fieldLengthInt = ByteUtils.toUnsignedInt(fieldLengthBuffer.getShort()); + + if(fieldLengthInt > 0) { + byte[] data = new byte[fieldLengthInt]; + bufferedInputStream.read(data); + keepassHeader.setValue(fieldId, data); + keepassHeader.increaseHeaderSize(fieldLengthInt + 3); + } + + if(fieldId == 0) { + break; + } + } catch (IOException e) { + throw new RuntimeException("Could not read header input", e); + } + } + } + + public KeePassFile openDatabase(String password) { + try { + byte[] aesDecryptedDbFile = decrypter.decryptDatabase(password, keepassHeader, keepassFile); + + byte[] startBytes = new byte[32]; + ByteArrayInputStream decryptedStream = new ByteArrayInputStream(aesDecryptedDbFile); + decryptedStream.read(startBytes); + + // compare startBytes + if(!Arrays.equals(keepassHeader.getStreamStartBytes(), startBytes)) { + throw new KeepassDatabaseUnreadable("The keepass database file seems to be corrupt or cannot be decrypted."); + } + + HashedBlockInputStream hashedBlockInputStream = new HashedBlockInputStream(decryptedStream); + byte[] hashedBlockBytes = StreamUtils.toByteArray(hashedBlockInputStream); + + byte[] decompressed = hashedBlockBytes; + + // unzip if necessary + if(keepassHeader.getCompression().equals(CompressionAlgorithm.Gzip)) { + GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(hashedBlockBytes)); + decompressed = StreamUtils.toByteArray(gzipInputStream); + } + + ProtectedStringCrypto protectedStringCrypto; + if(keepassHeader.getCrsAlgorithm().equals(CrsAlgorithm.Salsa20)) { + protectedStringCrypto = Salsa20.createInstance(keepassHeader.getProtectedStreamKey()); + } + else { + throw new UnsupportedOperationException("Only Salsa20 is supported as CrsAlgorithm at the moment!"); + } + + return xmlParser.parse(new ByteArrayInputStream(decompressed), protectedStringCrypto); + } catch (IOException e) { + throw new RuntimeException("Could not open database file", e); + } + } + + public KeePassHeader getHeader() { + return keepassHeader; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.util.zip.GZIPInputStream` acquired to `gzipInputStream` by call to `GZIPInputStream(...)` at line 136 is not released after line 137. +**Note**: potential exception at line 137 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +KeePassFile KeePassDatabase.openDatabase(String) + +### Procedure Id: +de.slackspace.openkeepass.KeePassDatabase.openDatabase(java.lang.String):de.slackspace.openkeepass.d.5783df28b5bb358f9264a2505b13bf0d + +### File: +src/main/java/de/slackspace/openkeepass/KeePassDatabase.java + +### Key: +KeePassDatabase.java|openDatabase|RESOURCE_LEAK + +### Node Key: +0602ef43d0c7ae4dbd6715cdf02c324e + +### Hash: +1f7dfca310b30679dab97f3fff95a85d + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8153/instruction.md b/inferredbugs-8153/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c945126f32305bff926661dede78e4e8a1a73f40 --- /dev/null +++ b/inferredbugs-8153/instruction.md @@ -0,0 +1,380 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** openkeepass +**Bug ID:** 12 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.slackspace.openkeepass; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Arrays; +import java.util.zip.GZIPInputStream; + +import org.bouncycastle.util.encoders.Base64; + +import de.slackspace.openkeepass.crypto.Decrypter; +import de.slackspace.openkeepass.crypto.ProtectedStringCrypto; +import de.slackspace.openkeepass.crypto.Salsa20; +import de.slackspace.openkeepass.crypto.Sha256; +import de.slackspace.openkeepass.domain.CompressionAlgorithm; +import de.slackspace.openkeepass.domain.CrsAlgorithm; +import de.slackspace.openkeepass.domain.KeePassFile; +import de.slackspace.openkeepass.domain.KeePassHeader; +import de.slackspace.openkeepass.domain.KeyFile; +import de.slackspace.openkeepass.exception.KeePassDatabaseUnreadable; +import de.slackspace.openkeepass.parser.KeePassDatabaseXmlParser; +import de.slackspace.openkeepass.parser.KeyFileXmlParser; +import de.slackspace.openkeepass.stream.HashedBlockInputStream; +import de.slackspace.openkeepass.util.ByteUtils; +import de.slackspace.openkeepass.util.StreamUtils; + +/** + * A KeePassDatabase is the central API class to read a KeePass database file. + *

    + * Currently the following KeePass files are supported: + * + *

      + *
    • KeePass Database V2 with password
    • + *
    • KeePass Database V2 with keyfile
    • + *
    + * + * A typical use-case should use the following idiom: + *
    + * // open database 
    + * KeePassFile database = KeePassDatabase.getInstance("keePassDatabasePath").openDatabase("secret");
    + * 
    + * // get password entries 
    + * List<Entry> entries = database.getEntries();
    + * ...
    + * 
    + * + * If the database could not be opened a RuntimeException will be thrown. + * + * @see KeePassFile + * + */ +public class KeePassDatabase { + + // KeePass 2.x signature + private static final int DATABASE_V2_FILE_SIGNATURE_1 = 0x9AA2D903 & 0xFF; + private static final int DATABASE_V2_FILE_SIGNATURE_2 = 0xB54BFB67 & 0xFF; + + // KeePass 1.x signature + private static final int OLD_DATABASE_V1_FILE_SIGNATURE_1 = 0x9AA2D903 & 0xFF; + private static final int OLD_DATABASE_V1_FILE_SIGNATURE_2 = 0xB54BFB65 & 0xFF; + + // KeePass version signature length in bytes + public static final int VERSION_SIGNATURE_LENGTH = 12; + + private KeePassHeader keepassHeader = new KeePassHeader(); + private byte[] keepassFile; + + protected Decrypter decrypter = new Decrypter(); + protected KeePassDatabaseXmlParser keePassDatabaseXmlParser = new KeePassDatabaseXmlParser(); + protected KeyFileXmlParser keyFileXmlParser = new KeyFileXmlParser(); + + private KeePassDatabase(InputStream inputStream) { + try { + keepassFile = StreamUtils.toByteArray(inputStream); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Retrieves a KeePassDatabase instance. The instance returned is based on the given database filename and tries to parse the database header of it. + * + * @param keePassDatabaseFile a KeePass database filename, must not be NULL + * @return a KeePassDatabase + */ + public static KeePassDatabase getInstance(String keePassDatabaseFile) { + return getInstance(new File(keePassDatabaseFile)); + } + + /** + * Retrieves a KeePassDatabase instance. The instance returned is based on the given database file and tries to parse the database header of it. + * + * @param keePassDatabaseFile a KeePass database file, must not be NULL + * @return a KeePassDatabase + */ + public static KeePassDatabase getInstance(File keePassDatabaseFile) { + if(keePassDatabaseFile == null) { + throw new IllegalArgumentException("You must provide a valid KeePass database file."); + } + + try { + return getInstance(new FileInputStream(keePassDatabaseFile)); + } catch (FileNotFoundException e) { + throw new IllegalArgumentException("The KeePass database file could not be found. You must provide a valid KeePass database file."); + } + } + + /** + * Retrieves a KeePassDatabase instance. The instance returned is based on the given input stream and tries to parse the database header of it. + * + * @param keePassDatabaseStream an input stream of a KeePass database, must not be NULL + * @return a KeePassDatabase + */ + public static KeePassDatabase getInstance(InputStream keePassDatabaseStream) { + if(keePassDatabaseStream == null) { + throw new IllegalArgumentException("You must provide a non-empty KeePass database stream."); + } + + KeePassDatabase reader = new KeePassDatabase(keePassDatabaseStream); + + try { + reader.checkVersionSupport(); + reader.readHeader(); + return reader; + } + catch(IOException e) { + throw new RuntimeException("Could not read input stream", e); + } + } + + private void checkVersionSupport() throws IOException { + BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(keepassFile)); + + byte[] signature = new byte[VERSION_SIGNATURE_LENGTH]; + bufferedInputStream.read(signature); + ByteBuffer signatureBuffer = ByteBuffer.wrap(signature); + signatureBuffer.order(ByteOrder.LITTLE_ENDIAN); + + int signaturePart1 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); + int signaturePart2 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); + + if(signaturePart1 == DATABASE_V2_FILE_SIGNATURE_1 && signaturePart2 == DATABASE_V2_FILE_SIGNATURE_2) { + return; + } + else if(signaturePart1 == OLD_DATABASE_V1_FILE_SIGNATURE_1 && signaturePart2 == OLD_DATABASE_V1_FILE_SIGNATURE_2) { + throw new UnsupportedOperationException("The provided KeePass database file seems to be from KeePass 1.x which is not supported!"); + } + else { + throw new UnsupportedOperationException("The provided file seems to be no KeePass database file!"); + } + } + + private void readHeader() throws IOException { + BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(keepassFile)); + bufferedInputStream.skip(VERSION_SIGNATURE_LENGTH); // skip version + + while(true) { + try { + int fieldId = bufferedInputStream.read(); + byte[] fieldLength = new byte[2]; + bufferedInputStream.read(fieldLength); + + ByteBuffer fieldLengthBuffer = ByteBuffer.wrap(fieldLength); + fieldLengthBuffer.order(ByteOrder.LITTLE_ENDIAN); + int fieldLengthInt = ByteUtils.toUnsignedInt(fieldLengthBuffer.getShort()); + + if(fieldLengthInt > 0) { + byte[] data = new byte[fieldLengthInt]; + bufferedInputStream.read(data); + keepassHeader.setValue(fieldId, data); + keepassHeader.increaseHeaderSize(fieldLengthInt + 3); + } + + if(fieldId == 0) { + break; + } + } catch (IOException e) { + throw new RuntimeException("Could not read header input", e); + } + } + } + + /** + * Opens a KeePass database with the given password and returns the KeePassFile for further processing. + *

    + * If the database cannot be decrypted with the provided password an exception will be thrown. + * + * @param password the password to open the database + * @return a KeePassFile + * @see KeePassFile + */ + public KeePassFile openDatabase(String password) { + if(password == null) { + throw new IllegalArgumentException("The password for the database must not be null. Please provide a valid password."); + } + + try { + byte[] passwordBytes = password.getBytes("UTF-8"); + byte[] hashedPassword = Sha256.hash(passwordBytes); + + return decryptAndParseDatabase(hashedPassword); + } catch (UnsupportedEncodingException e) { + throw new UnsupportedOperationException("The encoding UTF-8 is not supported"); + } + } + + /** + * Opens a KeePass database with the given password and returns the KeePassFile for further processing. + *

    + * If the database cannot be decrypted with the provided password an exception will be thrown. + * + * @param keyFile the password to open the database + * @return a KeePassFile the keyfile to open the database + * @see KeePassFile + */ + public KeePassFile openDatabase(File keyFile) { + if(keyFile == null) { + throw new IllegalArgumentException("You must provide a valid KeePass keyfile."); + } + + try { + return openDatabase(new FileInputStream(keyFile)); + } catch (FileNotFoundException e) { + throw new IllegalArgumentException("The KeePass keyfile could not be found. You must provide a valid KeePass keyfile."); + } + } + + /** + * Opens a KeePass database with the given keyfile stream and returns the KeePassFile for further processing. + *

    + * If the database cannot be decrypted with the provided keyfile an exception will be thrown. + * + * @param keyFileStream the keyfile to open the database as stream + * @return a KeePassFile + * @see KeePassFile + */ + public KeePassFile openDatabase(InputStream keyFileStream) { + if(keyFileStream == null) { + throw new IllegalArgumentException("You must provide a non-empty KeePass keyfile stream."); + } + + try { + KeyFile keyFile = keyFileXmlParser.parse(keyFileStream); + byte[] protectedBuffer = Base64.decode(keyFile.getKey().getData().getBytes("UTF-8")); + + return decryptAndParseDatabase(protectedBuffer); + } catch (UnsupportedEncodingException e) { + throw new UnsupportedOperationException("The encoding UTF-8 is not supported"); + } + } + + private KeePassFile decryptAndParseDatabase(byte[] key) { + try { + byte[] aesDecryptedDbFile = decrypter.decryptDatabase(key, keepassHeader, keepassFile); + + byte[] startBytes = new byte[32]; + ByteArrayInputStream decryptedStream = new ByteArrayInputStream(aesDecryptedDbFile); + decryptedStream.read(startBytes); + + // compare startBytes + if(!Arrays.equals(keepassHeader.getStreamStartBytes(), startBytes)) { + throw new KeePassDatabaseUnreadable("The keepass database file seems to be corrupt or cannot be decrypted."); + } + + HashedBlockInputStream hashedBlockInputStream = new HashedBlockInputStream(decryptedStream); + byte[] hashedBlockBytes = StreamUtils.toByteArray(hashedBlockInputStream); + + byte[] decompressed = hashedBlockBytes; + + // unzip if necessary + if(keepassHeader.getCompression().equals(CompressionAlgorithm.Gzip)) { + GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(hashedBlockBytes)); + decompressed = StreamUtils.toByteArray(gzipInputStream); + } + + ProtectedStringCrypto protectedStringCrypto; + if(keepassHeader.getCrsAlgorithm().equals(CrsAlgorithm.Salsa20)) { + protectedStringCrypto = Salsa20.createInstance(keepassHeader.getProtectedStreamKey()); + } + else { + throw new UnsupportedOperationException("Only Salsa20 is supported as CrsAlgorithm at the moment!"); + } + + return keePassDatabaseXmlParser.parse(new ByteArrayInputStream(decompressed), protectedStringCrypto); + } catch (IOException e) { + throw new RuntimeException("Could not open database file", e); + } + } + + /** + * Gets the KeePassDatabase header. + * + * @return the database header + */ + public KeePassHeader getHeader() { + return keepassHeader; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired by call to `FileInputStream(...)` at line 109 is not released after line 109. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +KeePassDatabase KeePassDatabase.getInstance(File) + +### Procedure Id: +de.slackspace.openkeepass.KeePassDatabase.getInstance(java.io.File):de.slackspace.openkeepass.KeePas.93b288e08440fd2a9be189da708fea92 + +### File: +src/main/java/de/slackspace/openkeepass/KeePassDatabase.java + +### Key: +KeePassDatabase.java|getInstance|RESOURCE_LEAK + +### Node Key: +8268b871e46a685172ca651b0023a4f1 + +### Hash: +1d089489483e403cc8d3e10420886603 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8154/instruction.md b/inferredbugs-8154/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b4f2c5e1c477da9cad38500a9a2442d8775b1811 --- /dev/null +++ b/inferredbugs-8154/instruction.md @@ -0,0 +1,169 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** openkeepass +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.slackspace.openkeepass.parser; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.TimeZone; + +import junit.framework.Assert; + +import org.junit.BeforeClass; +import org.junit.Test; + +import de.slackspace.openkeepass.crypto.Salsa20; +import de.slackspace.openkeepass.domain.Entry; +import de.slackspace.openkeepass.domain.Group; +import de.slackspace.openkeepass.domain.KeePassFile; +import de.slackspace.openkeepass.util.ByteUtils; + +public class XmlParserTest { + + private byte[] protectedStreamKey = ByteUtils.hexStringToByteArray("ec77a2169769734c5d26e5341401f8d7b11052058f8455d314879075d0b7e257"); + private static SimpleDateFormat dateFormatter; + + @BeforeClass + public static void init() { + // make sure we use UTC time + dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT")); + } + + @Test + public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectMetadata() throws FileNotFoundException { + FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); + KeePassFile keePassFile = new XmlParser().parse(fileInputStream, Salsa20.createInstance(protectedStreamKey)); + Assert.assertEquals("KeePass", keePassFile.getMeta().getGenerator()); + Assert.assertEquals("TestDatabase", keePassFile.getMeta().getDatabaseName()); + Assert.assertEquals("Just a sample db", keePassFile.getMeta().getDatabaseDescription()); + Assert.assertEquals("2014-11-22 18:59:39", dateFormatter.format(keePassFile.getMeta().getDatabaseNameChanged().getTime())); + Assert.assertEquals("2014-11-22 18:59:39", dateFormatter.format(keePassFile.getMeta().getDatabaseDescriptionChanged().getTime())); + Assert.assertEquals(365, keePassFile.getMeta().getMaintenanceHistoryDays()); + Assert.assertEquals(true, keePassFile.getMeta().getRecycleBinEnabled()); + Assert.assertEquals("AAAAAAAAAAAAAAAAAAAAAA==", keePassFile.getMeta().getRecycleBinUuid()); + Assert.assertEquals("2014-11-22 18:58:56", dateFormatter.format(keePassFile.getMeta().getRecycleBinChanged().getTime())); + Assert.assertEquals(10, keePassFile.getMeta().getHistoryMaxItems()); + Assert.assertEquals(6291456, keePassFile.getMeta().getHistoryMaxSize()); + } + + @Test + public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectGroups() throws FileNotFoundException { + FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); + KeePassFile keePassFile = new XmlParser().parse(fileInputStream, Salsa20.createInstance(protectedStreamKey)); + + List groups = keePassFile.getTopGroups(); + Assert.assertNotNull(groups); + + Assert.assertEquals(6, groups.size()); + Assert.assertEquals("General", groups.get(0).getName()); + Assert.assertEquals("FqvMJ8yjlUSAEt9OmNSj2A==", groups.get(0).getUuid()); + + Assert.assertEquals("Windows", groups.get(1).getName()); + Assert.assertEquals("rXt7D+EM/0qW1rgPB4g5nw==", groups.get(1).getUuid()); + + Assert.assertEquals("Network", groups.get(2).getName()); + Assert.assertEquals("DwdAaKn4tEyXFlU56/2UBQ==", groups.get(2).getUuid()); + + Assert.assertEquals("Internet", groups.get(3).getName()); + Assert.assertEquals("COgUrPt5P0676DeyZn/auQ==", groups.get(3).getUuid()); + + Assert.assertEquals("eMail", groups.get(4).getName()); + Assert.assertEquals("/xWfOfnC6ki76sNhrZR7rw==", groups.get(4).getUuid()); + + Assert.assertEquals("Homebanking", groups.get(5).getName()); + Assert.assertEquals("Rdjt21Jla0+E5Q9ElJHw1g==", groups.get(5).getUuid()); + } + + @Test + public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectEntries() throws FileNotFoundException { + FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); + KeePassFile keePassFile = new XmlParser().parse(fileInputStream, Salsa20.createInstance(protectedStreamKey)); + + List entries = keePassFile.getTopEntries(); + Assert.assertNotNull(entries); + + Assert.assertEquals(2, entries.size()); + Assert.assertEquals("libdLW88cU6BvrPQlvKqMA==", entries.get(0).getUuid()); + Assert.assertEquals(5, entries.get(0).getProperties().size()); + Assert.assertEquals("Sample Entry", entries.get(0).getTitle()); + Assert.assertEquals("http://keepass.info/", entries.get(0).getUrl()); + Assert.assertEquals("User Name", entries.get(0).getUsername()); + Assert.assertEquals("Notes", entries.get(0).getNotes()); + Assert.assertEquals("Password", entries.get(0).getPassword()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired to `fileInputStream` by call to `FileInputStream(...)` at line 34 is not released after line 47. +**Note**: potential exception at line 35 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void XmlParserTest.whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectMetadata() + +### Procedure Id: +de.slackspace.openkeepass.parser.XmlParserTest.whenInputIsValidKeePassXmlShouldParseFileAndReturnCor.84d28090343d47ba5ee594aba536e9fa + +### File: +src/test/java/de/slackspace/openkeepass/parser/XmlParserTest.java + +### Key: +XmlParserTest.java|whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectMetadata|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +8099f897033099f1b3cc1aec93f43f98 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8162/instruction.md b/inferredbugs-8162/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a65f200a67512703380b7c7690f6507d279cffb7 --- /dev/null +++ b/inferredbugs-8162/instruction.md @@ -0,0 +1,589 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** acme4j +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * acme4j - Java ACME client + * + * Copyright (C) 2015 Richard "Shred" Körber + * http://acme4j.shredzone.org + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * 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. + */ +package org.shredzone.acme4j.connector; + +import static java.util.stream.Collectors.toList; +import static org.shredzone.acme4j.util.AcmeUtils.keyAlgorithm; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.security.KeyPair; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.OptionalInt; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.jose4j.base64url.Base64Url; +import org.jose4j.jwk.PublicJsonWebKey; +import org.jose4j.jws.JsonWebSignature; +import org.jose4j.lang.JoseException; +import org.shredzone.acme4j.Problem; +import org.shredzone.acme4j.Session; +import org.shredzone.acme4j.exception.AcmeException; +import org.shredzone.acme4j.exception.AcmeNetworkException; +import org.shredzone.acme4j.exception.AcmeProtocolException; +import org.shredzone.acme4j.exception.AcmeRateLimitExceededException; +import org.shredzone.acme4j.exception.AcmeRetryAfterException; +import org.shredzone.acme4j.exception.AcmeServerException; +import org.shredzone.acme4j.exception.AcmeUnauthorizedException; +import org.shredzone.acme4j.exception.AcmeUserActionRequiredException; +import org.shredzone.acme4j.provider.pebble.Pebble; +import org.shredzone.acme4j.util.AcmeUtils; +import org.shredzone.acme4j.util.JSON; +import org.shredzone.acme4j.util.JSONBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Default implementation of {@link Connection}. + */ +public class DefaultConnection implements Connection { + private static final Logger LOG = LoggerFactory.getLogger(DefaultConnection.class); + + private static final String ACCEPT_HEADER = "Accept"; + private static final String ACCEPT_CHARSET_HEADER = "Accept-Charset"; + private static final String ACCEPT_LANGUAGE_HEADER = "Accept-Language"; + private static final String CONTENT_TYPE_HEADER = "Content-Type"; + private static final String DATE_HEADER = "Date"; + private static final String LINK_HEADER = "Link"; + private static final String LOCATION_HEADER = "Location"; + private static final String REPLAY_NONCE_HEADER = "Replay-Nonce"; + private static final String RETRY_AFTER_HEADER = "Retry-After"; + private static final String DEFAULT_CHARSET = "utf-8"; + + private static final Pattern BASE64URL_PATTERN = Pattern.compile("[0-9A-Za-z_-]+"); + + protected final HttpConnector httpConnector; + protected HttpURLConnection conn; + + /** + * Creates a new {@link DefaultConnection}. + * + * @param httpConnector + * {@link HttpConnector} to be used for HTTP connections + */ + public DefaultConnection(HttpConnector httpConnector) { + this.httpConnector = Objects.requireNonNull(httpConnector, "httpConnector"); + } + + @Override + public void resetNonce(Session session) throws AcmeException { + assertConnectionIsClosed(); + + try { + session.setNonce(null); + + URL newNonceUrl = session.resourceUrl(Resource.NEW_NONCE); + + conn = httpConnector.openConnection(newNonceUrl); + conn.setRequestMethod("HEAD"); + conn.setRequestProperty(ACCEPT_LANGUAGE_HEADER, session.getLocale().toLanguageTag()); + conn.connect(); + + int rc = conn.getResponseCode(); + if (rc != HttpURLConnection.HTTP_OK && rc != HttpURLConnection.HTTP_NO_CONTENT) { + throw new AcmeProtocolException("Fetching a nonce returned " + rc + " " + + conn.getResponseMessage()); + } + + updateSession(session); + + if (session.getNonce() == null) { + throw new AcmeProtocolException("Server did not provide a nonce"); + } + } catch (IOException ex) { + throw new AcmeNetworkException(ex); + } finally { + conn = null; + } + } + + @Override + public void sendRequest(URL url, Session session) throws AcmeException { + Objects.requireNonNull(url, "url"); + Objects.requireNonNull(session, "session"); + assertConnectionIsClosed(); + + LOG.debug("GET {}", url); + + try { + conn = httpConnector.openConnection(url); + conn.setRequestMethod("GET"); + conn.setRequestProperty(ACCEPT_CHARSET_HEADER, DEFAULT_CHARSET); + conn.setRequestProperty(ACCEPT_LANGUAGE_HEADER, session.getLocale().toLanguageTag()); + conn.setDoOutput(false); + + conn.connect(); + + logHeaders(); + } catch (IOException ex) { + throw new AcmeNetworkException(ex); + } + } + + @Override + public void sendSignedRequest(URL url, JSONBuilder claims, Session session) throws AcmeException { + if (session.getKeyIdentifier() == null) { + throw new IllegalStateException("session has no KeyIdentifier set"); + } + + sendJwkSignedRequest(url, claims, session); + } + + @Override + public void sendJwkSignedRequest(URL url, JSONBuilder claims, Session session) throws AcmeException { + Objects.requireNonNull(url, "url"); + Objects.requireNonNull(claims, "claims"); + Objects.requireNonNull(session, "session"); + assertConnectionIsClosed(); + + try { + KeyPair keypair = session.getKeyPair(); + + if (session.getNonce() == null) { + resetNonce(session); + } + + conn = httpConnector.openConnection(url); + conn.setRequestMethod("POST"); + conn.setRequestProperty(ACCEPT_HEADER, "application/json"); + conn.setRequestProperty(ACCEPT_CHARSET_HEADER, DEFAULT_CHARSET); + conn.setRequestProperty(ACCEPT_LANGUAGE_HEADER, session.getLocale().toLanguageTag()); + conn.setRequestProperty(CONTENT_TYPE_HEADER, "application/jose+json"); + conn.setDoOutput(true); + + final PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(keypair.getPublic()); + JsonWebSignature jws = new JsonWebSignature(); + jws.setPayload(claims.toString()); + jws.getHeaders().setObjectHeaderValue("nonce", Base64Url.encode(session.getNonce())); + jws.getHeaders().setObjectHeaderValue("url", url); + if (session.getKeyIdentifier() != null) { + // TODO PEBBLE: cannot process "kid" yet, send "jwk" instead + // https://github.com/letsencrypt/pebble/issues/23 + if (Pebble.workaround()) { + jws.getHeaders().setJwkHeaderValue("jwk", jwk); + } else { + jws.getHeaders().setObjectHeaderValue("kid", session.getKeyIdentifier()); + } + } else { + jws.getHeaders().setJwkHeaderValue("jwk", jwk); + } + + jws.setAlgorithmHeaderValue(keyAlgorithm(jwk)); + jws.setKey(keypair.getPrivate()); + + if (LOG.isDebugEnabled()) { + LOG.debug("POST {}", url); + LOG.debug(" Payload: {}", claims.toString()); + LOG.debug(" JWS Header: {}", jws.getHeaders().getFullHeaderAsJsonString()); + } + + byte[] outputData = jws.getCompactSerialization().getBytes(DEFAULT_CHARSET); + + conn.setFixedLengthStreamingMode(outputData.length); + conn.connect(); + + try (OutputStream out = conn.getOutputStream()) { + out.write(outputData); + } + + logHeaders(); + + updateSession(session); + } catch (IOException ex) { + throw new AcmeNetworkException(ex); + } catch (JoseException ex) { + throw new AcmeProtocolException("Failed to generate a JSON request", ex); + } + } + + @Override + public int accept(int... httpStatus) throws AcmeException { + assertConnectionIsOpen(); + + try { + int rc = conn.getResponseCode(); + OptionalInt match = Arrays.stream(httpStatus).filter(s -> s == rc).findFirst(); + if (match.isPresent()) { + return match.getAsInt(); + } + + if (!"application/problem+json".equals(conn.getHeaderField(CONTENT_TYPE_HEADER))) { + throw new AcmeException("HTTP " + rc + ": " + conn.getResponseMessage()); + } + + Problem problem = new Problem(readJsonResponse(), conn.getURL().toURI()); + throw createAcmeException(problem); + } catch (URISyntaxException ex) { + throw new AcmeProtocolException("Bad request URI: " + conn.getURL(), ex); + } catch (IOException ex) { + throw new AcmeNetworkException(ex); + } + } + + @Override + public JSON readJsonResponse() throws AcmeException { + assertConnectionIsOpen(); + + String contentType = conn.getHeaderField(CONTENT_TYPE_HEADER); + if (!("application/json".equals(contentType) + || "application/problem+json".equals(contentType))) { + throw new AcmeProtocolException("Unexpected content type: " + contentType); + } + + JSON result = null; + + try { + InputStream in = + conn.getResponseCode() < 400 ? conn.getInputStream() : conn.getErrorStream(); + if (in != null) { + result = JSON.parse(in); + LOG.debug("Result JSON: {}", result.toString()); + } + } catch (IOException ex) { + throw new AcmeNetworkException(ex); + } + + return result; + } + + @Override + public List readCertificates() throws AcmeException { + assertConnectionIsOpen(); + + String contentType = conn.getHeaderField(CONTENT_TYPE_HEADER); + if (!("application/pem-certificate-chain".equals(contentType))) { + throw new AcmeProtocolException("Unexpected content type: " + contentType); + } + + try (InputStream in = conn.getInputStream()) { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + return cf.generateCertificates(in).stream() + .map(c -> (X509Certificate) c) + .collect(toList()); + } catch (IOException ex) { + throw new AcmeNetworkException(ex); + } catch (CertificateException ex) { + throw new AcmeProtocolException("Failed to read certificate", ex); + } + } + + @Override + public void handleRetryAfter(String message) throws AcmeException { + assertConnectionIsOpen(); + + try { + if (conn.getResponseCode() == HttpURLConnection.HTTP_ACCEPTED) { + Optional retryAfter = getRetryAfterHeader(); + if (retryAfter.isPresent()) { + throw new AcmeRetryAfterException(message, retryAfter.get()); + } + } + } catch (IOException ex) { + throw new AcmeNetworkException(ex); + } + } + + @Override + public void updateSession(Session session) { + assertConnectionIsOpen(); + + String nonceHeader = conn.getHeaderField(REPLAY_NONCE_HEADER); + if (nonceHeader == null || nonceHeader.trim().isEmpty()) { + return; + } + + if (!BASE64URL_PATTERN.matcher(nonceHeader).matches()) { + throw new AcmeProtocolException("Invalid replay nonce: " + nonceHeader); + } + + LOG.debug("Replay Nonce: {}", nonceHeader); + + session.setNonce(Base64Url.decode(nonceHeader)); + } + + @Override + public URL getLocation() { + assertConnectionIsOpen(); + + String location = conn.getHeaderField(LOCATION_HEADER); + if (location == null) { + return null; + } + + LOG.debug("Location: {}", location); + return toURL(resolveRelative(location)); + } + + @Override + public URL getLink(String relation) { + Collection links = getLinks(relation); + if (links == null) { + return null; + } + + if (links.size() > 1) { + LOG.debug("Link: {} - using the first of {}", relation, links.size()); + } + + return toURL(links.iterator().next()); + } + + @Override + public Collection getLinks(String relation) { + assertConnectionIsOpen(); + + List result = new ArrayList<>(); + + List links = conn.getHeaderFields().get(LINK_HEADER); + if (links != null) { + Pattern p = Pattern.compile("<(.*?)>\\s*;\\s*rel=\"?"+ Pattern.quote(relation) + "\"?"); + for (String link : links) { + Matcher m = p.matcher(link); + if (m.matches()) { + String location = m.group(1); + LOG.debug("Link: {} -> {}", relation, location); + result.add(resolveRelative(location)); + } + } + } + + return !result.isEmpty() ? result : null; + } + + @Override + public void close() { + conn = null; + } + + /** + * Gets the instant sent with the Retry-After header. + */ + private Optional getRetryAfterHeader() { + // See RFC 2616 section 14.37 + String header = conn.getHeaderField(RETRY_AFTER_HEADER); + if (header != null) { + try { + // delta-seconds + if (header.matches("^\\d+$")) { + int delta = Integer.parseInt(header); + long date = conn.getHeaderFieldDate(DATE_HEADER, System.currentTimeMillis()); + return Optional.of(Instant.ofEpochMilli(date).plusSeconds(delta)); + } + + // HTTP-date + long date = conn.getHeaderFieldDate(RETRY_AFTER_HEADER, 0L); + if (date != 0) { + return Optional.of(Instant.ofEpochMilli(date)); + } + } catch (Exception ex) { + throw new AcmeProtocolException("Bad retry-after header value: " + header, ex); + } + } + + return Optional.empty(); + } + + /** + * Handles a problem by throwing an exception. If a JSON problem was returned, an + * {@link AcmeServerException} or subtype will be thrown. Otherwise a generic + * {@link AcmeException} is thrown. + */ + private AcmeException createAcmeException(Problem problem) { + if (problem.getType() == null) { + return new AcmeException(problem.getDetail()); + } + + String error = AcmeUtils.stripErrorPrefix(problem.getType().toString()); + + if ("unauthorized".equals(error)) { + return new AcmeUnauthorizedException(problem); + } + + if ("userActionRequired".equals(error)) { + URI tos = getLinks("terms-of-service").stream().findFirst().orElse(null); + return new AcmeUserActionRequiredException(problem, tos); + } + + if ("rateLimited".equals(error)) { + Optional retryAfter = getRetryAfterHeader(); + Collection rateLimits = getLinks("urn:ietf:params:acme:documentation"); + return new AcmeRateLimitExceededException(problem, retryAfter.orElse(null), rateLimits); + } + + return new AcmeServerException(problem); + } + + /** + * Asserts that the connection is currently open. Throws an exception if not. + */ + private void assertConnectionIsOpen() { + if (conn == null) { + throw new IllegalStateException("Not connected."); + } + } + + /** + * Asserts that the connection is currently closed. Throws an exception if not. + */ + private void assertConnectionIsClosed() { + if (conn != null) { + throw new IllegalStateException("Previous connection is not closed."); + } + } + + /** + * Log all HTTP headers in debug mode. + */ + private void logHeaders() { + if (!LOG.isDebugEnabled()) { + return; + } + + conn.getHeaderFields().forEach((key, headers) -> + headers.forEach(value -> + LOG.debug("HEADER {}: {}", key, value) + ) + ); + } + + /** + * Resolves a relative link against the connection's last URL. + * + * @param link + * Link to resolve. Absolute links are just converted to an URI. May be + * {@code null}. + * @return Absolute URI of the given link, or {@code null} if the link was + * {@code null}. + */ + private URI resolveRelative(String link) { + if (link == null) { + return null; + } + + assertConnectionIsOpen(); + try { + return conn.getURL().toURI().resolve(link); + } catch (URISyntaxException ex) { + throw new AcmeProtocolException("Cannot resolve relative link: " + link, ex); + } + } + + /** + * Converts {@link URI} to {@link URL}. + * + * @param uri + * {@link URI} to convert + * @return {@link URL} + * @throws AcmeProtocolException + * if the URI could not be converted to URL + */ + private static URL toURL(URI uri) { + try { + return uri != null ? uri.toURL() : null; + } catch (MalformedURLException ex) { + throw new AcmeProtocolException("Invalid URL: " + uri, ex); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getLinks("terms-of-service")` could be null and is dereferenced at line 430. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +AcmeException DefaultConnection.createAcmeException(Problem) + +### Procedure Id: +org.shredzone.acme4j.connector.DefaultConnection.createAcmeException(org.shredzone.acme4j.Problem):o.8ba68bce0d929e3e1352f559f426b465 + +### File: +acme4j-client/src/main/java/org/shredzone/acme4j/connector/DefaultConnection.java + +### Key: +DefaultConnection.java|createAcmeException|NULL_DEREFERENCE + +### Node Key: +42f56fda1ad408e362508b93a175bb0c + +### Hash: +00b6efb00bfc3647014db395768078fd + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8165/instruction.md b/inferredbugs-8165/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f2578d0239766c4531ae749089c18523513acd1f --- /dev/null +++ b/inferredbugs-8165/instruction.md @@ -0,0 +1,1014 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** acme4j +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * acme4j - Java ACME client + * + * Copyright (C) 2015 Richard "Shred" Körber + * http://acme4j.shredzone.org + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * 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. + */ +package org.shredzone.acme4j.connector; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; +import static org.shredzone.acme4j.toolbox.TestUtils.url; +import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.Proxy; +import java.net.URI; +import java.net.URL; +import java.security.KeyPair; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.jose4j.base64url.Base64Url; +import org.jose4j.jws.JsonWebSignature; +import org.jose4j.jwx.CompactSerializer; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentMatchers; +import org.shredzone.acme4j.Login; +import org.shredzone.acme4j.Session; +import org.shredzone.acme4j.exception.AcmeException; +import org.shredzone.acme4j.exception.AcmeProtocolException; +import org.shredzone.acme4j.exception.AcmeRateLimitedException; +import org.shredzone.acme4j.exception.AcmeRetryAfterException; +import org.shredzone.acme4j.exception.AcmeServerException; +import org.shredzone.acme4j.exception.AcmeUnauthorizedException; +import org.shredzone.acme4j.exception.AcmeUserActionRequiredException; +import org.shredzone.acme4j.provider.AcmeProvider; +import org.shredzone.acme4j.toolbox.AcmeUtils; +import org.shredzone.acme4j.toolbox.JSON; +import org.shredzone.acme4j.toolbox.JSONBuilder; +import org.shredzone.acme4j.toolbox.TestUtils; + +/** + * Unit tests for {@link DefaultConnection}. + */ +public class DefaultConnectionTest { + + private URL requestUrl = TestUtils.url("http://example.com/acme/"); + private URL accountUrl = TestUtils.url(TestUtils.ACCOUNT_URL); + private HttpURLConnection mockUrlConnection; + private HttpConnector mockHttpConnection; + private Session session; + private Login login; + private KeyPair keyPair; + + @Before + public void setup() throws AcmeException, IOException { + mockUrlConnection = mock(HttpURLConnection.class); + + mockHttpConnection = mock(HttpConnector.class); + when(mockHttpConnection.openConnection(requestUrl, Proxy.NO_PROXY)).thenReturn(mockUrlConnection); + + final AcmeProvider mockProvider = mock(AcmeProvider.class); + when(mockProvider.directory( + ArgumentMatchers.any(Session.class), + ArgumentMatchers.eq(URI.create(TestUtils.ACME_SERVER_URI)))) + .thenReturn(TestUtils.getJSON("directory")); + + session = TestUtils.session(mockProvider); + session.setLocale(Locale.JAPAN); + + keyPair = TestUtils.createKeyPair(); + + login = session.login(accountUrl, keyPair); + } + + /** + * Test that {@link DefaultConnection#getNonce()} returns {@code null} if there is no + * {@code Replay-Nonce} header. + */ + @Test + public void testNoNonceFromHeader() { + when(mockUrlConnection.getHeaderField("Replay-Nonce")).thenReturn(null); + + assertThat(session.getNonce(), is(nullValue())); + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getNonce(), is(nullValue())); + } + + verify(mockUrlConnection).getHeaderField("Replay-Nonce"); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that {@link DefaultConnection#getNonce()} extracts a {@code Replay-Nonce} + * header correctly. + */ + @Test + public void testGetNonceFromHeader() { + when(mockUrlConnection.getHeaderField("Replay-Nonce")) + .thenReturn(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getNonce(), is(TestUtils.DUMMY_NONCE)); + } + + verify(mockUrlConnection).getHeaderField("Replay-Nonce"); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that {@link DefaultConnection#getNonce()} fails on an invalid + * {@code Replay-Nonce} header. + */ + @Test + public void testInvalidNonceFromHeader() { + String badNonce = "#$%&/*+*#'"; + + when(mockUrlConnection.getHeaderField("Replay-Nonce")).thenReturn(badNonce); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.getNonce(); + fail("Expected to fail"); + } catch (AcmeProtocolException ex) { + assertThat(ex.getMessage(), org.hamcrest.Matchers.startsWith("Invalid replay nonce")); + } + + verify(mockUrlConnection).getHeaderField("Replay-Nonce"); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that {@link DefaultConnection#resetNonce(Session)} fetches a new nonce via + * new-nonce resource and a HEAD request. + */ + @Test + public void testResetNonce() throws AcmeException, IOException { + when(mockHttpConnection.openConnection(new URL("https://example.com/acme/new-nonce"), Proxy.NO_PROXY)) + .thenReturn(mockUrlConnection); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_NO_CONTENT); + + assertThat(session.getNonce(), is(nullValue())); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.resetNonce(session); + fail("missing Replay-Nonce header not detected"); + } catch (AcmeProtocolException ex) { + // expected + } + + assertThat(session.getNonce(), is(nullValue())); + + when(mockUrlConnection.getHeaderField("Replay-Nonce")) + .thenReturn(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.resetNonce(session); + } + + assertThat(session.getNonce(), is(TestUtils.DUMMY_NONCE)); + + verify(mockUrlConnection, atLeastOnce()).setRequestMethod("HEAD"); + verify(mockUrlConnection, atLeastOnce()).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection, atLeastOnce()).connect(); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Replay-Nonce"); + verify(mockUrlConnection, atLeastOnce()).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that an absolute Location header is evaluated. + */ + @Test + public void testGetAbsoluteLocation() throws Exception { + when(mockUrlConnection.getHeaderField("Location")).thenReturn("https://example.com/otherlocation"); + when(mockUrlConnection.getURL()).thenReturn(new URL("https://example.org/acme")); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + URL location = conn.getLocation(); + assertThat(location, is(new URL("https://example.com/otherlocation"))); + } + + verify(mockUrlConnection).getHeaderField("Location"); + verify(mockUrlConnection).getURL(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that a relative Location header is evaluated. + */ + @Test + public void testGetRelativeLocation() throws Exception { + when(mockUrlConnection.getHeaderField("Location")).thenReturn("/otherlocation"); + when(mockUrlConnection.getURL()).thenReturn(new URL("https://example.org/acme")); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + URL location = conn.getLocation(); + assertThat(location, is(new URL("https://example.org/otherlocation"))); + } + + verify(mockUrlConnection).getHeaderField("Location"); + verify(mockUrlConnection).getURL(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that absolute and relative Link headers are evaluated. + */ + @Test + public void testGetLink() throws Exception { + Map> headers = new HashMap<>(); + headers.put("Content-Type", Arrays.asList("application/json")); + headers.put("Location", Arrays.asList("https://example.com/acme/acct/asdf")); + headers.put("Link", Arrays.asList( + ";rel=\"next\"", + ";rel=recover", + "; rel=\"terms-of-service\"" + )); + + when(mockUrlConnection.getHeaderFields()).thenReturn(headers); + when(mockUrlConnection.getURL()).thenReturn(new URL("https://example.org/acme")); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getLinks("next"), containsInAnyOrder(new URL("https://example.com/acme/new-authz"))); + assertThat(conn.getLinks("recover"), containsInAnyOrder(new URL("https://example.org/recover-acct"))); + assertThat(conn.getLinks("terms-of-service"), containsInAnyOrder(new URL("https://example.com/acme/terms"))); + assertThat(conn.getLinks("secret-stuff"), is(empty())); + } + } + + /** + * Test that multiple link headers are evaluated. + */ + @Test + public void testGetMultiLink() { + URL baseUrl = url("https://example.com/acme/request/1234"); + + Map> headers = new HashMap<>(); + headers.put("Link", Arrays.asList( + "; rel=\"terms-of-service\"", + "; rel=\"terms-of-service\"", + "<../terms3>; rel=\"terms-of-service\"" + )); + + when(mockUrlConnection.getHeaderFields()).thenReturn(headers); + when(mockUrlConnection.getURL()).thenReturn(baseUrl); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getLinks("terms-of-service"), containsInAnyOrder( + url("https://example.com/acme/terms1"), + url("https://example.com/acme/terms2"), + url("https://example.com/acme/terms3") + )); + } + } + + /** + * Test that no link headers are properly handled. + */ + @Test + public void testGetNoLink() { + Map> headers = Collections.emptyMap(); + when(mockUrlConnection.getHeaderFields()).thenReturn(headers); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getLinks("something"), is(empty())); + } + } + + /** + * Test that no Location header returns {@code null}. + */ + @Test + public void testNoLocation() { + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + URL location = conn.getLocation(); + assertThat(location, is(nullValue())); + } + + verify(mockUrlConnection).getHeaderField("Location"); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test if Retry-After header with absolute date is correctly parsed. + */ + @Test + public void testHandleRetryAfterHeaderDate() throws AcmeException, IOException { + Instant retryDate = Instant.now().plus(Duration.ofHours(10)).truncatedTo(ChronoUnit.MILLIS); + String retryMsg = "absolute date"; + + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getHeaderField("Retry-After")).thenReturn(retryDate.toString()); + when(mockUrlConnection.getHeaderFieldDate("Retry-After", 0L)).thenReturn(retryDate.toEpochMilli()); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.handleRetryAfter(retryMsg); + fail("no AcmeRetryAfterException was thrown"); + } catch (AcmeRetryAfterException ex) { + assertThat(ex.getRetryAfter(), is(retryDate)); + assertThat(ex.getMessage(), is(retryMsg)); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); + } + + /** + * Test if Retry-After header with relative timespan is correctly parsed. + */ + @Test + public void testHandleRetryAfterHeaderDelta() throws AcmeException, IOException { + int delta = 10 * 60 * 60; + long now = System.currentTimeMillis(); + String retryMsg = "relative time"; + + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getHeaderField("Retry-After")) + .thenReturn(String.valueOf(delta)); + when(mockUrlConnection.getHeaderFieldDate( + ArgumentMatchers.eq("Date"), + ArgumentMatchers.anyLong())) + .thenReturn(now); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.handleRetryAfter(retryMsg); + fail("no AcmeRetryAfterException was thrown"); + } catch (AcmeRetryAfterException ex) { + assertThat(ex.getRetryAfter(), is(Instant.ofEpochMilli(now).plusSeconds(delta))); + assertThat(ex.getMessage(), is(retryMsg)); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); + } + + /** + * Test if no Retry-After header is correctly handled. + */ + @Test + public void testHandleRetryAfterHeaderNull() throws AcmeException, IOException { + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getHeaderField("Retry-After")) + .thenReturn(null); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.handleRetryAfter("no header"); + } catch (AcmeRetryAfterException ex) { + fail("an AcmeRetryAfterException was thrown"); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); + } + + /** + * Test if missing retry-after header is correctly handled. + */ + @Test + public void testHandleRetryAfterNotAccepted() throws AcmeException, IOException { + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.handleRetryAfter("http ok"); + } catch (AcmeRetryAfterException ex) { + fail("an AcmeRetryAfterException was thrown"); + } + } + + /** + * Test if an {@link AcmeServerException} is thrown on an acme problem. + */ + @Test + public void testAccept() throws Exception { + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + int rc = conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + assertThat(rc, is(HttpURLConnection.HTTP_OK)); + } + + verify(mockUrlConnection).getResponseCode(); + } + + /** + * Test if an {@link AcmeServerException} is thrown on an acme problem. + */ + @Test + public void testAcceptThrowsException() throws Exception { + String jsonData = "{\"type\":\"urn:ietf:params:acme:error:unauthorized\",\"detail\":\"Invalid response: 404\"}"; + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/problem+json"); + when(mockUrlConnection.getContentLength()).thenReturn(jsonData.length()); + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_FORBIDDEN); + when(mockUrlConnection.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + when(mockUrlConnection.getErrorStream()).thenReturn(new ByteArrayInputStream(jsonData.getBytes("utf-8"))); + when(mockUrlConnection.getURL()).thenReturn(url("https://example.com/acme/1")); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeUnauthorizedException ex) { + assertThat(ex.getType(), is(URI.create("urn:ietf:params:acme:error:unauthorized"))); + assertThat(ex.getMessage(), is("Invalid response: 404")); + } catch (AcmeException ex) { + fail("Expected an AcmeUnauthorizedException"); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getContentLength(); + verify(mockUrlConnection).getErrorStream(); + verify(mockUrlConnection).getURL(); + } + + /** + * Test if an {@link AcmeUserActionRequiredException} is thrown on an acme problem. + */ + @Test + public void testAcceptThrowsUserActionRequiredException() throws Exception { + String jsonData = "{\"type\":\"urn:ietf:params:acme:error:userActionRequired\",\"detail\":\"Accept the TOS\"}"; + + Map> linkHeader = new HashMap<>(); + linkHeader.put("Link", Arrays.asList("; rel=\"terms-of-service\"")); + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/problem+json"); + when(mockUrlConnection.getContentLength()).thenReturn(jsonData.length()); + when(mockUrlConnection.getHeaderFields()).thenReturn(linkHeader); + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_FORBIDDEN); + when(mockUrlConnection.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + when(mockUrlConnection.getErrorStream()).thenReturn(new ByteArrayInputStream(jsonData.getBytes("utf-8"))); + when(mockUrlConnection.getURL()).thenReturn(url("https://example.com/acme/1")); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeUserActionRequiredException ex) { + assertThat(ex.getType(), is(URI.create("urn:ietf:params:acme:error:userActionRequired"))); + assertThat(ex.getMessage(), is("Accept the TOS")); + assertThat(ex.getTermsOfServiceUri(), is(URI.create("https://example.com/tos.pdf"))); + } catch (AcmeException ex) { + fail("Expected an AcmeUserActionRequiredException"); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getHeaderFields(); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getErrorStream(); + verify(mockUrlConnection).getContentLength(); + verify(mockUrlConnection, atLeastOnce()).getURL(); + } + + /** + * Test if an {@link AcmeRateLimitedException} is thrown on an acme problem. + */ + @Test + public void testAcceptThrowsRateLimitedException() throws Exception { + String jsonData = "{\"type\":\"urn:ietf:params:acme:error:rateLimited\",\"detail\":\"Too many invocations\"}"; + + Map> linkHeader = new HashMap<>(); + linkHeader.put("Link", Arrays.asList("; rel=\"urn:ietf:params:acme:documentation\"")); + + Instant retryAfter = Instant.now().plusSeconds(30L).truncatedTo(ChronoUnit.MILLIS); + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/problem+json"); + when(mockUrlConnection.getContentLength()).thenReturn(jsonData.length()); + when(mockUrlConnection.getHeaderField("Retry-After")).thenReturn(retryAfter.toString()); + when(mockUrlConnection.getHeaderFieldDate("Retry-After", 0L)).thenReturn(retryAfter.toEpochMilli()); + when(mockUrlConnection.getHeaderFields()).thenReturn(linkHeader); + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_FORBIDDEN); + when(mockUrlConnection.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + when(mockUrlConnection.getErrorStream()).thenReturn(new ByteArrayInputStream(jsonData.getBytes("utf-8"))); + when(mockUrlConnection.getURL()).thenReturn(url("https://example.com/acme/1")); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeRateLimitedException ex) { + assertThat(ex.getType(), is(URI.create("urn:ietf:params:acme:error:rateLimited"))); + assertThat(ex.getMessage(), is("Too many invocations")); + assertThat(ex.getRetryAfter(), is(retryAfter)); + assertThat(ex.getDocuments(), is(notNullValue())); + assertThat(ex.getDocuments().size(), is(1)); + assertThat(ex.getDocuments().iterator().next(), is(url("https://example.com/rates.pdf"))); + } catch (AcmeException ex) { + fail("Expected an AcmeRateLimitedException"); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); + verify(mockUrlConnection).getHeaderFieldDate("Retry-After", 0L); + verify(mockUrlConnection, atLeastOnce()).getHeaderFields(); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getContentLength(); + verify(mockUrlConnection).getErrorStream(); + verify(mockUrlConnection, atLeastOnce()).getURL(); + } + + /** + * Test if an {@link AcmeServerException} is thrown on another problem. + */ + @Test + public void testAcceptThrowsOtherException() throws IOException { + when(mockUrlConnection.getHeaderField("Content-Type")) + .thenReturn("application/problem+json"); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_INTERNAL_ERROR); + when(mockUrlConnection.getURL()) + .thenReturn(url("https://example.com/acme/1")); + when(mockUrlConnection.getOutputStream()) + .thenReturn(new ByteArrayOutputStream()); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public JSON readJsonResponse() { + JSONBuilder result = new JSONBuilder(); + result.put("type", "urn:zombie:error:apocalypse"); + result.put("detail", "Zombie apocalypse in progress"); + return result.toJSON(); + } + }) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeServerException ex) { + assertThat(ex.getType(), is(URI.create("urn:zombie:error:apocalypse"))); + assertThat(ex.getMessage(), is("Zombie apocalypse in progress")); + } catch (AcmeException ex) { + fail("Expected an AcmeServerException"); + } + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getURL(); + } + + /** + * Test if an {@link AcmeException} is thrown if there is no error type. + */ + @Test + public void testAcceptThrowsNoTypeException() throws IOException { + when(mockUrlConnection.getHeaderField("Content-Type")) + .thenReturn("application/problem+json"); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_INTERNAL_ERROR); + when(mockUrlConnection.getURL()) + .thenReturn(url("https://example.com/acme/1")); + when(mockUrlConnection.getOutputStream()) + .thenReturn(new ByteArrayOutputStream()); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public JSON readJsonResponse() { + return JSON.empty(); + } + }) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeProtocolException ex) { + assertThat(ex.getMessage(), not(isEmptyOrNullString())); + } catch (AcmeException ex) { + fail("Did not expect an AcmeException"); + } + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getURL(); + } + + /** + * Test if an {@link AcmeException} is thrown if there is a generic error. + */ + @Test + public void testAcceptThrowsServerException() throws IOException { + when(mockUrlConnection.getHeaderField("Content-Type")) + .thenReturn("text/html"); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_INTERNAL_ERROR); + when(mockUrlConnection.getResponseMessage()) + .thenReturn("Infernal Server Error"); + when(mockUrlConnection.getOutputStream()) + .thenReturn(new ByteArrayOutputStream()); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeException ex) { + assertThat(ex.getMessage(), is("HTTP 500: Infernal Server Error")); + } + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection, atLeastOnce()).getResponseMessage(); + } + + /** + * Test GET requests. + */ + @Test + public void testSendRequest() throws Exception { + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendRequest(requestUrl, session); + } + + verify(mockUrlConnection).setRequestMethod("GET"); + verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); + verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); + verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection).setDoOutput(false); + verify(mockUrlConnection).connect(); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection, atLeast(0)).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test certificate GET requests. + */ + @Test + public void testSendCertificateRequest() throws Exception { + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendCertificateRequest(requestUrl, session); + } + + verify(mockUrlConnection).setRequestMethod("GET"); + verify(mockUrlConnection).setRequestProperty("Accept", "application/pem-certificate-chain"); + verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); + verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection).setDoOutput(false); + verify(mockUrlConnection).connect(); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection, atLeast(0)).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test signed POST requests. + */ + @Test + public void testSendSignedRequest() throws Exception { + final String nonce1 = Base64Url.encode("foo-nonce-1-foo".getBytes()); + final String nonce2 = Base64Url.encode("foo-nonce-2-foo".getBytes()); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getOutputStream()).thenReturn(outputStream); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public void resetNonce(Session session) { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == null) { + session.setNonce(nonce1); + } else { + fail("unknown nonce"); + } + } + + @Override + public String getNonce() { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == nonce1) { + return nonce2; + } else { + fail("unknown nonce"); + return null; + } + } + }) { + JSONBuilder cb = new JSONBuilder(); + cb.put("foo", 123).put("bar", "a-string"); + conn.sendSignedRequest(requestUrl, cb, login); + } + + verify(mockUrlConnection).setRequestMethod("POST"); + verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); + verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); + verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection).setRequestProperty("Content-Type", "application/jose+json"); + verify(mockUrlConnection).connect(); + verify(mockUrlConnection).setDoOutput(true); + verify(mockUrlConnection).setFixedLengthStreamingMode(outputStream.toByteArray().length); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection).getOutputStream(); + verify(mockUrlConnection, atLeast(0)).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + + JSON data = JSON.parse(new String(outputStream.toByteArray(), "utf-8")); + String encodedHeader = data.get("protected").asString(); + String encodedSignature = data.get("signature").asString(); + String encodedPayload = data.get("payload").asString(); + + StringBuilder expectedHeader = new StringBuilder(); + expectedHeader.append('{'); + expectedHeader.append("\"nonce\":\"").append(nonce1).append("\","); + expectedHeader.append("\"url\":\"").append(requestUrl).append("\","); + expectedHeader.append("\"alg\":\"RS256\","); + expectedHeader.append("\"kid\":\"").append(accountUrl).append('"'); + expectedHeader.append('}'); + + assertThat(Base64Url.decodeToUtf8String(encodedHeader), sameJSONAs(expectedHeader.toString())); + assertThat(Base64Url.decodeToUtf8String(encodedPayload), sameJSONAs("{\"foo\":123,\"bar\":\"a-string\"}")); + assertThat(encodedSignature, not(isEmptyOrNullString())); + + JsonWebSignature jws = new JsonWebSignature(); + jws.setCompactSerialization(CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature)); + jws.setKey(login.getKeyPair().getPublic()); + assertThat(jws.verifySignature(), is(true)); + } + + /** + * Test signed POST requests without KeyIdentifier. + */ + @Test + public void testSendSignedRequestNoKid() throws Exception { + final String nonce1 = Base64Url.encode("foo-nonce-1-foo".getBytes()); + final String nonce2 = Base64Url.encode("foo-nonce-2-foo".getBytes()); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getOutputStream()).thenReturn(outputStream); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public void resetNonce(Session session) { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == null) { + session.setNonce(nonce1); + } else { + fail("unknown nonce"); + } + } + + @Override + public String getNonce() { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == nonce1) { + return nonce2; + } else { + fail("unknown nonce"); + return null; + } + } + }) { + JSONBuilder cb = new JSONBuilder(); + cb.put("foo", 123).put("bar", "a-string"); + conn.sendSignedRequest(requestUrl, cb, session, keyPair); + } + + verify(mockUrlConnection).setRequestMethod("POST"); + verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); + verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); + verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection).setRequestProperty("Content-Type", "application/jose+json"); + verify(mockUrlConnection).connect(); + verify(mockUrlConnection).setDoOutput(true); + verify(mockUrlConnection).setFixedLengthStreamingMode(outputStream.toByteArray().length); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection).getOutputStream(); + verify(mockUrlConnection, atLeast(0)).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + + JSON data = JSON.parse(new String(outputStream.toByteArray(), "utf-8")); + String encodedHeader = data.get("protected").asString(); + String encodedSignature = data.get("signature").asString(); + String encodedPayload = data.get("payload").asString(); + + StringBuilder expectedHeader = new StringBuilder(); + expectedHeader.append('{'); + expectedHeader.append("\"nonce\":\"").append(nonce1).append("\","); + expectedHeader.append("\"url\":\"").append(requestUrl).append("\","); + expectedHeader.append("\"alg\":\"RS256\","); + expectedHeader.append("\"jwk\":{"); + expectedHeader.append("\"kty\":\"").append(TestUtils.KTY).append("\","); + expectedHeader.append("\"e\":\"").append(TestUtils.E).append("\","); + expectedHeader.append("\"n\":\"").append(TestUtils.N).append("\""); + expectedHeader.append("}}"); + + assertThat(Base64Url.decodeToUtf8String(encodedHeader), sameJSONAs(expectedHeader.toString())); + assertThat(Base64Url.decodeToUtf8String(encodedPayload), sameJSONAs("{\"foo\":123,\"bar\":\"a-string\"}")); + assertThat(encodedSignature, not(isEmptyOrNullString())); + + JsonWebSignature jws = new JsonWebSignature(); + jws.setCompactSerialization(CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature)); + jws.setKey(login.getKeyPair().getPublic()); + assertThat(jws.verifySignature(), is(true)); + } + + /** + * Test signed POST requests if there is no nonce. + */ + @Test(expected = AcmeException.class) + public void testSendSignedRequestNoNonce() throws Exception { + when(mockHttpConnection.openConnection(new URL("https://example.com/acme/new-nonce"), Proxy.NO_PROXY)) + .thenReturn(mockUrlConnection); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_NOT_FOUND); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + JSONBuilder cb = new JSONBuilder(); + conn.sendSignedRequest(requestUrl, cb, DefaultConnectionTest.this.session, DefaultConnectionTest.this.keyPair); + } + } + + /** + * Test getting a JSON response. + */ + @Test + public void testReadJsonResponse() throws Exception { + String jsonData = "{\n\"foo\":123,\n\"bar\":\"a-string\"\n}\n"; + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/json"); + when(mockUrlConnection.getContentLength()).thenReturn(jsonData.length()); + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getInputStream()).thenReturn(new ByteArrayInputStream(jsonData.getBytes("utf-8"))); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + JSON result = conn.readJsonResponse(); + assertThat(result, is(notNullValue())); + assertThat(result.keySet(), hasSize(2)); + assertThat(result.get("foo").asInt(), is(123)); + assertThat(result.get("bar").asString(), is("a-string")); + } + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection).getContentLength(); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection).getInputStream(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that a certificate is downloaded correctly. + */ + @Test + public void testReadCertificate() throws Exception { + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/pem-certificate-chain"); + when(mockUrlConnection.getInputStream()).thenReturn(getClass().getResourceAsStream("/cert.pem")); + + List downloaded; + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + downloaded = conn.readCertificates(); + } + + List original = TestUtils.createCertificate(); + assertThat(original.size(), is(2)); + + assertThat(downloaded, not(nullValue())); + assertThat(downloaded.size(), is(original.size())); + for (int ix = 0; ix < downloaded.size(); ix++) { + assertThat(downloaded.get(ix).getEncoded(), is(original.get(ix).getEncoded())); + }; + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection).getInputStream(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that a bad certificate throws an exception. + */ + @Test(expected = AcmeProtocolException.class) + public void testReadBadCertificate() throws Exception { + // Build a broken certificate chain PEM file + byte[] brokenPem; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); + OutputStreamWriter w = new OutputStreamWriter(baos)) { + for (X509Certificate cert : TestUtils.createCertificate()) { + byte[] badCert = cert.getEncoded(); + Arrays.sort(badCert); // break it + AcmeUtils.writeToPem(badCert, AcmeUtils.PemLabel.CERTIFICATE, w); + } + w.flush(); + brokenPem = baos.toByteArray(); + } + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/pem-certificate-chain"); + when(mockUrlConnection.getInputStream()).thenReturn(new ByteArrayInputStream(brokenPem)); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.readCertificates(); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `javax.net.ssl.HttpsURLConnection` acquired by call to `sendCertificateRequest(...)` at line 674 is not released after line 675. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DefaultConnectionTest.testSendCertificateRequest() + +### Procedure Id: +org.shredzone.acme4j.connector.DefaultConnectionTest.testSendCertificateRequest():void.dbd677766527acb4193adf935e967520 + +### File: +acme4j-client/src/test/java/org/shredzone/acme4j/connector/DefaultConnectionTest.java + +### Key: +DefaultConnectionTest.java|testSendCertificateRequest|RESOURCE_LEAK + +### Node Key: +be34d01a97ade44aabeb9969f5c22e18 + +### Hash: +ba4f0d4e85f574cbc90f02a8390fe205 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8191/instruction.md b/inferredbugs-8191/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a84a37aed979b14a806b4e03922c83b4f37e3db4 --- /dev/null +++ b/inferredbugs-8191/instruction.md @@ -0,0 +1,248 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** SmartIM +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package io.github.biezhi.wechat.model; + +import java.io.File; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import cn.ieclipse.smartim.model.impl.AbstractMessage; +import cn.ieclipse.util.StringUtils; +import io.github.biezhi.wechat.api.WechatClient; +import io.github.biezhi.wechat.handler.msg.AppMsgXmlHandler; +import io.github.biezhi.wechat.handler.msg.EmojiMsgXmlHandler; +import io.github.biezhi.wechat.handler.msg.ImageMsgXmlHandler; + +public class WechatMessage extends AbstractMessage { + + public static final int MSGTYPE_TEXT = 1; + public static final int MSGTYPE_IMAGE = 3; + /** + * 慎用,并不确定 + */ + public static final int MSGTYPE_FILE = 6; + public static final int MSGTYPE_VOICE = 34; + public static final int MSGTYPE_VERIFYMSG = 37; + public static final int MSGTYPE_POSSIBLEFRIEND_MSG = 40; + public static final int MSGTYPE_SHARECARD = 42; + public static final int MSGTYPE_VIDEO = 43; + public static final int MSGTYPE_EMOTICON = 47; + public static final int MSGTYPE_LOCATION = 48; + public static final int MSGTYPE_APP = 49; + public static final int MSGTYPE_VOIPMSG = 50; + public static final int MSGTYPE_STATUSNOTIFY = 51; + public static final int MSGTYPE_VOIPNOTIFY = 52; + public static final int MSGTYPE_VOIPINVITE = 53; + public static final int MSGTYPE_MICROVIDEO = 62; + public static final int MSGTYPE_SYSNOTICE = 9999; + public static final int MSGTYPE_SYS = 10000; + public static final int MSGTYPE_RECALLED = 10002; + + public static final int APPMSGTYPE_TEXT = 1; + public static final int APPMSGTYPE_IMG = 2; + public static final int APPMSGTYPE_AUDIO = 3; + public static final int APPMSGTYPE_VIDEO = 4; + public static final int APPMSGTYPE_URL = 5; + public static final int APPMSGTYPE_ATTACH = 6; + public static final int APPMSGTYPE_OPEN = 7; + public static final int APPMSGTYPE_EMOJI = 8; + public static final int APPMSGTYPE_VOICE_REMIND = 9; + public static final int APPMSGTYPE_SCAN_GOOD = 10; + public static final int APPMSGTYPE_GOOD = 13; + public static final int APPMSGTYPE_EMOTION = 15; + public static final int APPMSGTYPE_CARD_TICKET = 16; + public static final int APPMSGTYPE_REALTIME_SHARE_LOCATION = 17; + public static final String APPMSGTYPE_TRANSFERS = "2e3"; + public static final int APPMSGTYPE_RED_ENVELOPES = 2001; + public static final int APPMSGTYPE_READER_TYPE = 100001; + public static final int UPLOAD_MEDIA_TYPE_IMAGE = 1; + public static final int UPLOAD_MEDIA_TYPE_VIDEO = 2; + public static final int UPLOAD_MEDIA_TYPE_AUDIO = 3; + public static final int UPLOAD_MEDIA_TYPE_ATTACHMENT = 4; + + public static final String CONTENT_DELIMITER = ":
    "; + + @SerializedName("MsgType") + public int MsgType; + @SerializedName("FromUserName") + public String FromUserName; + @SerializedName("ToUserName") + public String ToUserName; + @SerializedName("Content") + public String Content; + + @SerializedName("MsgId") + public String MsgId; + + @SerializedName("CreateTime") + public long CreateTime; + + @SerializedName("StatusNotifyCode") + public int StatusNotifyCode; + + @SerializedName("StatusNotifyUserName") + public String StatusNotifyUserName; + + @Expose(serialize = false, deserialize = false) + public String text; + public String src; + public String groupId; + public String MediaId; + public int AppMsgType; + public String FileName; + public String EncryFileName; + public int ImgHeight; + public int ImgWidth; + + @Override + public CharSequence getText() { + if (text == null) { + parseContent(); + } + return text; + } + + public void parseContent() { + String temp = StringUtils.decodeXml(Content); + if (MsgType == WechatMessage.MSGTYPE_EMOTICON) { + text = new EmojiMsgXmlHandler(temp).getHtml(getMediaLink(), this); + } + else if (MsgType == WechatMessage.MSGTYPE_IMAGE) { + text = new ImageMsgXmlHandler(temp).getHtml(getMediaLink(), this); + } + else if (MsgType == WechatMessage.MSGTYPE_APP) { + text = new AppMsgXmlHandler(temp).getHtml(getMediaLink(), this); + } + // else if (MsgType == WechatMessage.MSGTYPE_FILE) { + // text = new FileMsgXmlHandler(temp).getHtml(getMediaLink()); + // } + else if (MsgType == WechatMessage.MSGTYPE_VIDEO) { + text = "视频消息(请在手机上查看)"; + } + else if (MsgType == WechatMessage.MSGTYPE_VOICE) { + text = "语音消息(请在手机上查看)"; + } + else if (MsgType == WechatMessage.MSGTYPE_MICROVIDEO) { + text = "小视频(请在手机上查看)"; + } + else if (MsgType == WechatMessage.MSGTYPE_VERIFYMSG) { + text = "验证消息(请在手机上查看)"; + } + else if (MsgType == WechatMessage.MSGTYPE_VOIPINVITE) { + text = "视频邀请消息(请在手机上查看)"; + } + else { + text = temp; + } + } + + public String getMediaLink() { + if (WechatClient.getInstance() != null) { + File dir = WechatClient.getInstance().getWorkDir("media"); + File f = null; + if (MsgType == WechatMessage.MSGTYPE_IMAGE) { + f = new File(dir, "image_" + MsgId + ".jpg"); + } + else if (MsgType == WechatMessage.MSGTYPE_EMOTICON) { + f = new File(dir, "emotion_" + MsgId + ".gif"); + } + else if (MsgType == WechatMessage.MSGTYPE_APP) { + if (WechatMessage.MSGTYPE_FILE == AppMsgType + && !StringUtils.isEmpty(FileName)) { + f = new File( + WechatClient.getInstance().getWorkDir("attach"), + FileName); + } + } + + String link = WechatClient.getInstance().getMediaLink(this, f); + return link; + } + return null; + } + + @Override + public long getTime() { + // fix #2 wechat timeline error refer to + // https://github.com/Jamling/SmartQQ4IntelliJ/issues/30 + return CreateTime * 1000; + } + + @Override + public String toString() { + return String.format("type:%d, msg:%s", MsgType, text); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `temp` last assigned on line 105 could be null and is dereferenced by call to `ImageMsgXmlHandler(...)` at line 110. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void WechatMessage.parseContent() + +### Procedure Id: +io.github.biezhi.wechat.model.WechatMessage.parseContent():void.3fe963b408dde7ba19ff1177d8df6510 + +### File: +wechat/src/main/java/io/github/biezhi/wechat/model/WechatMessage.java + +### Key: +WechatMessage.java|parseContent|NULL_DEREFERENCE + +### Node Key: +784c4b183b3d42c8e49c891ead93a47b + +### Hash: +24abd001d3fb49fae0d687ba5059ef74 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8196/instruction.md b/inferredbugs-8196/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9a27731b0e88fe69fbf80e283840da50217a6cf1 --- /dev/null +++ b/inferredbugs-8196/instruction.md @@ -0,0 +1,209 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jqf +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2017-2018 The Regents of the University of California + * + * 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 COPYRIGHT HOLDERS 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 COPYRIGHT + * HOLDER 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. + */ + + +package edu.berkeley.cs.jqf.fuzz.ei; + +import edu.berkeley.cs.jqf.fuzz.junit.GuidedFuzzing; +import edu.berkeley.cs.jqf.instrument.InstrumentingClassLoader; +import org.junit.runner.Result; +import picocli.CommandLine; +import picocli.CommandLine.Option; +import picocli.CommandLine.Parameters; + +import java.io.File; +import java.util.ArrayList; + +/** + * CLI for Zest based guidance. + * + * @author Yevgeny Pats + */ +@CommandLine.Command(name = "ZestCLI", mixinStandardHelpOptions = true, version = "1.3") +public class ZestCLI implements Runnable{ + @Option(names = { "-e", "--exit-on-crash" }, + description = "Exit fuzzer on first crash (default: false)") + private boolean exitOnCrash = false; + + @Option(names = { "-l", "--libfuzzer-compat-output" }, + description = "Use libFuzzer compat output instead of AFL like stats screen (default: false)") + private boolean libFuzzerCompatOutput = false; + + @Option(names = { "-i", "--input" }, + description = "Input directory containing seed test cases (default: none)") + private File inputDirectory; + + @Option(names = { "-o", "--output" }, + description = "Output Directory containing results (default: fuzz_results)") + private File outputDirectory = new File("fuzz-results"); + + @Parameters(index="0", paramLabel = "PACKAGE", description = "package containing the fuzzer and all dependencies") + private String testPackageName; + + @Parameters(index="1", paramLabel = "TEST_CLASS", description = "full class name where the fuzz function is located") + private String testClassName; + + @Parameters(index="2", paramLabel = "TEST_METHOD", description = "fuzz function name") + private String testMethodName; + + + private File[] readSeedFiles() { + if (this.inputDirectory == null) { + return new File[0]; + } + + ArrayList seedFilesArray = new ArrayList<>(); + File[] allFiles = this.inputDirectory.listFiles(); + for (int i = 0; i < allFiles.length; i++) { + if (allFiles[i].isFile()) { + seedFilesArray.add(allFiles[i]); + } + } + File[] seedFiles = seedFilesArray.toArray(new File[seedFilesArray.size()]); + return seedFiles; + } + + public void run() { + + File[] seedFiles = readSeedFiles(); + + if (this.exitOnCrash) { + System.setProperty("jqf.ei.EXIT_ON_CRASH", "true"); + } + + if (this.libFuzzerCompatOutput) { + System.setProperty("jqf.ei.LIBFUZZER_COMPAT_OUTPUT", "true"); + } + + try { + ClassLoader loader = new InstrumentingClassLoader( + new String[]{System.getProperty("java.class.path"), this.testPackageName}, + ZestCLI.class.getClassLoader()); + + // Load the guidance + String title = this.testClassName+"#"+this.testMethodName; + ZestGuidance guidance = seedFiles.length > 0 ? + new ZestGuidance(title, null, this.outputDirectory, seedFiles) : + new ZestGuidance(title, null, this.outputDirectory); + + // Run the Junit test + Result res = GuidedFuzzing.run(testClassName, testMethodName, loader, guidance, System.out); + if (Boolean.getBoolean("jqf.logCoverage")) { + System.out.println(String.format("Covered %d edges.", + guidance.getTotalCoverage().getNonZeroCount())); + } + if (Boolean.getBoolean("jqf.ei.EXIT_ON_CRASH") && !res.wasSuccessful()) { + System.exit(3); + } + + } catch (Exception e) { + e.printStackTrace(); + System.exit(2); + } + + } + public static void main(String[] args) { + int exitCode = new CommandLine(new ZestCLI()).execute(args); + System.exit(exitCode); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `allFiles` last assigned on line 82 could be null and is dereferenced at line 83. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +java.io.File[] ZestCLI.readSeedFiles() + +### Procedure Id: +edu.berkeley.cs.jqf.fuzz.ei.ZestCLI.readSeedFiles():java.io.File[].06e4f02c05725c3fa8eb760dc9479ca1 + +### File: +fuzz/src/main/java/edu/berkeley/cs/jqf/fuzz/ei/ZestCLI.java + +### Key: +ZestCLI.java|readSeedFiles|NULL_DEREFERENCE + +### Node Key: +57a86cabad769b98ba4bb221beb4a196 + +### Hash: +0c1afb0b45a2d91c68345e9f5da4eb7f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8198/instruction.md b/inferredbugs-8198/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a66be7207029b72f0dcf95fb25cc8c09ea0d65ee --- /dev/null +++ b/inferredbugs-8198/instruction.md @@ -0,0 +1,242 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jqf +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + The MIT License + + Copyright (c) 2017 University of California, Berkeley + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +package edu.berkeley.cs.jqf.fuzz.junit; + +import java.io.PrintStream; + +import edu.berkeley.cs.jqf.fuzz.guidance.Guidance; +import edu.berkeley.cs.jqf.fuzz.guidance.NoGuidance; +import edu.berkeley.cs.jqf.fuzz.junit.quickcheck.JQF; +import edu.berkeley.cs.jqf.instrument.tracing.SingleSnoop; +import org.junit.internal.TextListener; +import org.junit.internal.runners.ErrorReportingRunner; +import org.junit.runner.JUnitCore; +import org.junit.runner.Request; +import org.junit.runner.RunWith; +import org.junit.runner.Runner; + +public class GuidedFuzzing { + + private static Guidance guidance; + + private static long DEFAULT_MAX_TRIALS = 100; + + private static void setGuidance(Guidance g) { + if (guidance != null) { + throw new IllegalStateException("Can only set guided once."); + } + guidance = g; + } + + /** + * Returns the currently registered Guidance instance. + * + *

    If no guidance is set, this method creates a new + * instance of {@link NoGuidance}, registers it, and returns + * a reference to it.

    + * + * @return the currently registered Guidance instance + */ + public static Guidance getCurrentGuidance() { + if (guidance == null) { + System.err.println(String.format("Warning: No guidance set. " + + " Falling back to default %d trials with no feedback", DEFAULT_MAX_TRIALS)); + setGuidance(new NoGuidance(DEFAULT_MAX_TRIALS, System.err)); + } + + return guidance; + } + + private static void unsetGuidance() { + guidance = null; + } + + + /** + * Runs the guided fuzzing loop. + * + *

    The test class must be annotated with @RunWith(JQF.class) + * and the test method must be annotated with @Fuzz.

    + * + *

    Once this method is invoked, the guided fuzzing loop runs continuously + * until the guidance instance decides to stop by returning false + * for {@link Guidance#hasInput()}. Until the fuzzing stops, this method + * cannot be invoked again (i.e. at most one guided fuzzing can be running + * at any time in a single JVM instance).

    + * + * @param testClassName the test class containing the test method + * @param testMethod the test method to execute in the fuzzing loop + * @param guidance the fuzzing guidance + * @param out an output stream to log Junit messages + * @throws ClassNotFoundException if testClassName cannot be loaded + * @throws IllegalStateException if a guided fuzzing run is currently executing + */ + public synchronized static void run(String testClassName, String testMethod, + Guidance guidance, PrintStream out) throws ClassNotFoundException, IllegalStateException { + Class testClass = + java.lang.Class.forName(testClassName, true, ClassLoader.getSystemClassLoader()); + + run(testClass, testMethod, guidance, out); + + } + + + /** + * Runs the guided fuzzing loop. + * + *

    The test class must be annotated with @RunWith(JQF.class) + * and the test method must be annotated with @Fuzz.

    + * + *

    Once this method is invoked, the guided fuzzing loop runs continuously + * until the guidance instance decides to stop by returning false + * for {@link Guidance#hasInput()}. Until the fuzzing stops, this method + * cannot be invoked again (i.e. at most one guided fuzzing can be running + * at any time in a single JVM instance).

    + * + * @param testClass the test class containing the test method + * @param testMethod the test method to execute in the fuzzing loop + * @param guidance the fuzzing guidance + * @param out an output stream to log Junit messages + * @throws IllegalStateException if a guided fuzzing run is currently executing + */ + public synchronized static void run(Class testClass, String testMethod, + Guidance guidance, PrintStream out) throws IllegalStateException { + + // Ensure that the class uses the right test runner + RunWith annotation = testClass.getAnnotation(RunWith.class); + if (annotation == null || !annotation.value().equals(JQF.class)) { + throw new IllegalArgumentException(testClass.getName() + " is not annotated with @RunWith(JQF.class)"); + } + + + // Set the static guided instance + setGuidance(guidance); + + // Register callback + SingleSnoop.setCallbackGenerator(guidance::generateCallBack); + + // Create a JUnit Request + Request testRequest = Request.method(testClass, testMethod); + + // Instantiate a runner (throws exception if testMethod is not a proper test method) + Runner testRunner = testRequest.getRunner(); + + // Start tracing for the test method + SingleSnoop.startSnooping(testClass.getName() + "#" + testMethod); + + // Run the test and make sure to de-register the guidance before returning + try { + JUnitCore junit = new JUnitCore(); + if (out != null) { + junit.addListener(new TextListener(out)); + } + junit.run(testRunner); + } finally { + unsetGuidance(); + } + + + if (testRunner instanceof ErrorReportingRunner) { + throw new IllegalArgumentException(String.format("Could not instantiate a Junit runner for method %s#%s.", testClass, testMethod)); + } + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `edu.berkeley.cs.jqf.fuzz.junit.GuidedFuzzing.getCurrentGuidance` indirectly writes to field `junit.GuidedFuzzing.edu.berkeley.cs.jqf.fuzz.junit.GuidedFuzzing.guidance` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Guidance GuidedFuzzing.getCurrentGuidance() + +### Procedure Id: +edu.berkeley.cs.jqf.fuzz.junit.GuidedFuzzing.getCurrentGuidance():edu.berkeley.cs.jqf.fuzz.guidance..04ca1cd9521d9d3b2524037f54c7f5c9 + +### File: +fuzz/src/main/java/edu/berkeley/cs/jqf/fuzz/junit/GuidedFuzzing.java + +### Key: +GuidedFuzzing.java|getCurrentGuidance|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +e26e33494eeb955cf61c260a2dbe7164 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8249/instruction.md b/inferredbugs-8249/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3d4af3e82ad27394fbd21da266a3476b13bf7595 --- /dev/null +++ b/inferredbugs-8249/instruction.md @@ -0,0 +1,226 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** Chronicle-Queue +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2013 Peter Lawrey + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.openhft.chronicle.sandbox; + +import net.openhft.lang.io.NativeBytes; + +import java.io.Closeable; +import java.io.File; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; + +public class VanillaDataCache implements Closeable { + private static final int MAX_SIZE = 32; + + private final String basePath; + private final DataKey key = new DataKey(); + private final int blockBits; + private final DateCache dateCache; + private final Map dataKeyVanillaFileMap = new LinkedHashMap(MAX_SIZE, 1.0f, true) { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() >= MAX_SIZE; + } + }; + + public VanillaDataCache(String basePath, int blockBits, DateCache dateCache) { + this.basePath = basePath; + this.blockBits = blockBits; + this.dateCache = dateCache; + } + + public synchronized VanillaFile dataFor(int cycle, int threadId, int dataCount, boolean forWrite) throws IOException { + key.cycle = cycle; + key.threadId = threadId; + key.dataCount = dataCount; + VanillaFile vanillaFile = dataKeyVanillaFileMap.get(key); + if (vanillaFile == null) { + String cycleStr = dateCache.formatFor(cycle); + dataKeyVanillaFileMap.put(key.clone(), vanillaFile = new VanillaFile(basePath, cycleStr, "data-" + threadId + "-" + dataCount, dataCount, 1L << blockBits, forWrite)); + findEndOfData(vanillaFile); + } + vanillaFile.incrementUsage(); + return vanillaFile; + } + + private void findEndOfData(VanillaFile vanillaFile) { + NativeBytes bytes = vanillaFile.bytes(); + for (int i = 0, max = 1 << blockBits; i < max; i += 4) { + int len = bytes.readInt(bytes.position()); + if (len == 0) { + return; + } + int len2 = nextWordAlignment(~len); + if (len2 < 0) { + throw new IllegalStateException("Corrupted length in " + vanillaFile.file() + " " + Integer.toHexString(len)); + } + bytes.position(bytes.position() + len2 + 4); + } + throw new AssertionError(); + } + + int nextWordAlignment(int len) { + return (len + 3) & ~3; + } + + @Override + public synchronized void close() { + for (VanillaFile vanillaFile : dataKeyVanillaFileMap.values()) { + vanillaFile.close(); + } + dataKeyVanillaFileMap.clear(); + } + + private int lastCycle = -1; + private int lastCount = -1; + + public VanillaFile dataForLast(int cycle, int threadId) throws IOException { + String cycleStr = dateCache.formatFor(cycle); + String dataPrefix = basePath + "/" + cycleStr + "/data-" + threadId + "-"; + if (lastCycle != cycle) { + int maxCount = 0; + File[] files = new File(dataPrefix).listFiles(); + if (files != null) + for (File file : files) { + if (file.getName().startsWith(dataPrefix)) { + int count = Integer.parseInt(file.getName().substring(dataPrefix.length())); + if (maxCount < count) + maxCount = count; + } + } + lastCycle = cycle; + lastCount = maxCount; + } + + return dataFor(cycle, threadId, lastCount, true); + } + + public void incrementLastCount() { + lastCount++; + } + + public synchronized void checkCounts(int min, int max) { + for (VanillaFile file : dataKeyVanillaFileMap.values()) { + if (file.usage() < min || file.usage() > max) + throw new IllegalStateException(file.file() + " has a count of " + file.usage()); + } + } + + + static class DataKey implements Cloneable { + int cycle; + int threadId; + int dataCount; + + @Override + public int hashCode() { + return threadId * 10191 + cycle * 17 + dataCount; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof DataKey)) return false; + DataKey key = (DataKey) obj; + return dataCount == key.dataCount && threadId == key.threadId && cycle == key.cycle; + } + + @Override + protected DataKey clone() { + try { + return (DataKey) super.clone(); + } catch (CloneNotSupportedException e) { + throw new AssertionError(e); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `net.openhft.chronicle.sandbox.VanillaDataCache.dataForLast` indirectly reads without synchronization from `this.net.openhft.chronicle.sandbox.VanillaDataCache.dateCache.net.openhft.chronicle.sandbox.DateCache.values.[_]`. Potentially races with write in method `VanillaDataCache.dataFor(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +VanillaFile VanillaDataCache.dataForLast(int,int) + +### Procedure Id: +net.openhft.chronicle.sandbox.VanillaDataCache.dataForLast(int,int):net.openhft.chronicle.sandbox.Va.9db58d5806f03b789c74aaccc4b63778 + +### File: +chronicle-sandbox/src/main/java/net/openhft/chronicle/sandbox/VanillaDataCache.java + +### Key: +VanillaDataCache.java|dataForLast|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +0cf6dacdfa70fc4178c47cb6e7874de1 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8271/instruction.md b/inferredbugs-8271/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e03be1e8fa917b0ba8b6e58fda8207fdcf1a7475 --- /dev/null +++ b/inferredbugs-8271/instruction.md @@ -0,0 +1,143 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** tika +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.tika.parser.asm; + +import java.io.InputStream; + +import org.apache.tika.metadata.Metadata; +import org.apache.tika.parser.AutoDetectParser; +import org.apache.tika.parser.Parser; +import org.apache.tika.sax.BodyContentHandler; +import org.xml.sax.ContentHandler; + +import junit.framework.TestCase; + +/** + * Test case for parsing Java class files. + */ +public class ClassParserTest extends TestCase { + + public void testClassParsing() throws Exception { + Parser parser = new AutoDetectParser(); // Should auto-detect! + ContentHandler handler = new BodyContentHandler(); + Metadata metadata = new Metadata(); + + InputStream stream = ClassParserTest.class.getResourceAsStream( + "/test-documents/AutoDetectParser.class"); + try { + parser.parse(stream, handler, metadata); + } finally { + stream.close(); + } + + assertEquals("AutoDetectParser", metadata.get(Metadata.TITLE)); + assertEquals( + "AutoDetectParser.class", + metadata.get(Metadata.RESOURCE_NAME_KEY)); + + String content = handler.toString(); + assertTrue(content.contains("package org.apache.tika.parser;")); + assertTrue(content.contains( + "class AutoDetectParser extends CompositeParser")); + assertTrue(content.contains( + "private org.apache.tika.mime.MimeTypes types")); + assertTrue(content.contains( + "public void parse(" + + "java.io.InputStream, org.xml.sax.ContentHandler," + + " org.apache.tika.metadata.Metadata) throws" + + " java.io.IOException, org.xml.sax.SAXException," + + " org.apache.tika.exception.TikaException;")); + assertTrue(content.contains( + "private byte[] getPrefix(java.io.InputStream, int)" + + " throws java.io.IOException;")); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `parser.parsers` last assigned on line 35 could be null and is dereferenced by call to `parse(...)` at line 42. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ClassParserTest.testClassParsing() + +### Procedure Id: +org.apache.tika.parser.asm.ClassParserTest.testClassParsing():void.93a3df8cbc5630636b4d4b4e7e3c74b1 + +### File: +tika-parsers/src/test/java/org/apache/tika/parser/asm/ClassParserTest.java + +### Key: +ClassParserTest.java|testClassParsing|NULL_DEREFERENCE + +### Node Key: +80164e1767c4ff0172216db8631d9e39 + +### Hash: +10401d62265654810d73298d6f9baead + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8276/instruction.md b/inferredbugs-8276/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..594a2fd5762ead047911480d38e7fceb8af607a8 --- /dev/null +++ b/inferredbugs-8276/instruction.md @@ -0,0 +1,161 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** tika +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.tika.parser; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.io.input.CountingInputStream; +import org.apache.tika.config.TikaConfig; +import org.apache.tika.exception.TikaException; +import org.apache.tika.metadata.Metadata; +import org.apache.tika.mime.MediaType; +import org.apache.tika.mime.MimeTypes; +import org.apache.tika.sax.SecureContentHandler; +import org.xml.sax.ContentHandler; +import org.xml.sax.SAXException; + +public class AutoDetectParser extends CompositeParser { + + private MimeTypes types; + + /** + * Creates an auto-detecting parser instance using the default Tika + * configuration. + */ + public AutoDetectParser() { + try { + setConfig(TikaConfig.getDefaultConfig()); + } catch (TikaException e) { + // FIXME: This should never happen + throw new RuntimeException(e); + } + } + + public AutoDetectParser(TikaConfig config) { + setConfig(config); + } + + public void setConfig(TikaConfig config) { + setParsers(config.getParsers()); + setMimeTypes(config.getMimeRepository()); + } + + public MimeTypes getMimeTypes() { + return types; + } + + public void setMimeTypes(MimeTypes types) { + this.types = types; + } + + public void parse( + InputStream stream, ContentHandler handler, Metadata metadata) + throws IOException, SAXException, TikaException { + // We need buffering to enable MIME magic detection before parsing + if (!stream.markSupported()) { + stream = new BufferedInputStream(stream); + } + + // Automatically detect the MIME type of the document + MediaType type = types.detect(stream, metadata); + metadata.set(Metadata.CONTENT_TYPE, type.toString()); + + // TIKA-216: Zip bomb prevention + CountingInputStream count = new CountingInputStream(stream); + SecureContentHandler secure = new SecureContentHandler(handler, count); + + // Parse the document + super.parse(count, secure, metadata); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.io.input.CountingInputStream` acquired to `count` by call to `new()` at line 80 is not released after line 84. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AutoDetectParser.parse(InputStream,BodyContentHandler,Metadata) + +### Procedure Id: +org.apache.tika.parser.AutoDetectParser.parse(java.io.InputStream,org.apache.tika.sax.BodyContentHan.f6dfa771fd5afb98e68617d62cb0ada9 + +### File: +src/main/java/org/apache/tika/parser/AutoDetectParser.java + +### Key: +AutoDetectParser.java|parse|RESOURCE_LEAK + +### Node Key: +08134dd5715af8c52e3e8f4128c07ccd + +### Hash: +4412765daf8e3cd1b2b02f76316d811b + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8282/instruction.md b/inferredbugs-8282/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1d0e02fd4db02d75ddca1f8bafd55662f1515a99 --- /dev/null +++ b/inferredbugs-8282/instruction.md @@ -0,0 +1,234 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** GMavenPlus +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.codehaus.gmavenplus.mojo; + +import com.google.common.io.Closer; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.codehaus.gmavenplus.util.NoExitSecurityManager; +import org.codehaus.gmavenplus.util.ReflectionUtils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.InvocationTargetException; +import java.net.MalformedURLException; +import java.net.URL; + + +/** + * Executes Groovy scripts (in the pom or external), bound to the current project. + * Note that this mojo requires Groovy >= 1.5.0. + * Note that it references the plugin classloader to pull in dependencies + * Groovy didn't include (for things like Ant for AntBuilder, Ivy for @grab, + * and Jansi for Groovysh)). + * + * @author Keegan Witt + * @since 1.0-beta-1 + * + * @goal execute + * @configurator include-project-test-dependencies + * @requiresDependencyResolution test + * @threadSafe + */ +public class ExecuteMojo extends AbstractToolsMojo { + + /** + * Groovy scripts to run (in order). Can be an actual Groovy script or a + * {@link java.net.URL URL} to a Groovy script (local or remote). + * + * @parameter + * @required + */ + protected String[] scripts; + + /** + * Whether to continue executing remaining scripts when a script fails. + * + * @parameter default-value="false" + */ + protected boolean continueExecuting; + + /** + * The encoding of script files. + * @since 1.0-beta-2 + * + * @parameter default-value="${project.build.sourceEncoding}" + */ + protected String sourceEncoding; + + /** + * Executes this mojo. + * + * @throws MojoExecutionException If an unexpected problem occurs. Throwing this exception causes a "BUILD ERROR" message to be displayed + * @throws MojoFailureException If an expected problem (such as a compilation failure) occurs. Throwing this exception causes a "BUILD FAILURE" message to be displayed + */ + public void execute() throws MojoExecutionException, MojoFailureException { + usePluginClassLoader = true; + if (groovyVersionSupportsAction()) { + logGroovyVersion("execute"); + + if (scripts == null || scripts.length == 0) { + getLog().info("No scripts specified for execution. Skipping."); + return; + } + + final SecurityManager sm = System.getSecurityManager(); + try { + System.setSecurityManager(new NoExitSecurityManager()); + // get classes we need with reflection + Class groovyShellClass = Class.forName("groovy.lang.GroovyShell"); + + // create a GroovyShell to run scripts in + Object shell = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyShellClass)); + initializeProperties(); + for (Object k : properties.keySet()) { + String key = (String) k; + ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, key, properties.get(key)); + } + + // run the scripts + int scriptNum = 1; + for (String script : scripts) { + Closer closer = Closer.create(); + try { + try { + URL url = new URL(script); + // it's a URL to a script + getLog().info("Fetching Groovy script from " + url.toString() + "."); + BufferedReader reader; + if (sourceEncoding != null) { + reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream(), sourceEncoding))); + } else { + reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream()))); + } + StringBuilder scriptSource = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + scriptSource.append(line).append("\n"); + } + if (!scriptSource.toString().isEmpty()) { + ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, scriptSource.toString()); + } + } catch (MalformedURLException e) { + // it's not a URL to a script, treat as a script body + ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, script); + } catch (Throwable throwable) { + throw closer.rethrow(throwable); + } finally { + closer.close(); + } + } catch (IOException ioe) { + if (continueExecuting) { + getLog().error("An Exception occurred while executing script " + scriptNum + ". Continuing to execute remaining scripts.", ioe); + } else { + throw new MojoExecutionException("An Exception occurred while executing script " + scriptNum + ".", ioe); + } + } + scriptNum++; + } + } catch (ClassNotFoundException e) { + throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project or the plugin?", e); + } catch (InvocationTargetException e) { + throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e); + } catch (InstantiationException e) { + throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e); + } catch (IllegalAccessException e) { + throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e); + } finally { + System.setSecurityManager(sm); + } + } else { + getLog().error("Your Groovy version (" + getGroovyVersion() + ") doesn't support script execution. The minimum version of Groovy required is " + minGroovyVersion + ". Skipping script execution."); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 117 is not released after line 117. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExecuteMojo.execute() + +### Procedure Id: +org.codehaus.gmavenplus.mojo.ExecuteMojo.execute():void.51159157ec9223d202942c21bc93f3d2 + +### File: +src/main/java/org/codehaus/gmavenplus/mojo/ExecuteMojo.java + +### Key: +ExecuteMojo.java|execute|RESOURCE_LEAK + +### Node Key: +f29a0b5fbb21603d796e3f4e7ba77dde + +### Hash: +f7925e9d2b668f97b10597d0553e62de + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8285/instruction.md b/inferredbugs-8285/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..11c0251b96ea9b73e69d4378406658c35ad271bf --- /dev/null +++ b/inferredbugs-8285/instruction.md @@ -0,0 +1,412 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** GMavenPlus +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.codehaus.gmavenplus.mojo; + +import com.google.common.io.Closer; +import com.google.common.io.Files; +import org.apache.maven.shared.model.fileset.FileSet; +import org.apache.maven.shared.model.fileset.util.FileSetManager; +import org.codehaus.gmavenplus.groovyworkarounds.GroovyDocTemplateInfo; +import org.codehaus.gmavenplus.model.Scopes; +import org.codehaus.gmavenplus.model.Version; +import org.codehaus.gmavenplus.util.ReflectionUtils; + +import java.io.*; +import java.lang.reflect.InvocationTargetException; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; + + +/** + * The base groovydoc mojo, which all groovydoc mojos extend. + * + * @author Keegan Witt + * @since 1.0-beta-1 + */ +public abstract class AbstractGroovydocMojo extends AbstractGroovySourcesMojo { + + /** + * The location for the generated API docs. + * + * @parameter default-value="${project.build.directory}/gapidocs" + */ + protected File groovydocOutputDirectory; + + /** + * The location for the generated test API docs. + * + * @parameter default-value="${project.build.directory}/testgapidocs" + */ + protected File testGroovydocOutputDirectory; + + /** + * The window title. + * + * @parameter default-value="Groovy Documentation" + */ + protected String windowTitle; + + /** + * The page title. + * + * @parameter default-value="Groovy Documentation" + */ + protected String docTitle; + + /** + * The page footer. + * + * @parameter default-value="Groovy Documentation" + */ + protected String footer; + + /** + * The page header. + * + * @parameter default-value="Groovy Documentation" + */ + protected String header; + + /** + * Whether to display the author in the generated Groovydoc. + * + * @parameter default-value="true" + */ + protected boolean displayAuthor; + + /** + * The HTML file to be used for overview documentation. + * + * @parameter + */ + protected File overviewFile; + + /** + * The stylesheet file (absolute path) to copy to output directory (will overwrite default stylesheet.css). + * + * @parameter + */ + protected File stylesheetFile; + + /** + * The encoding of stylesheetFile. + * + * @parameter default-value="UTF-8" + */ + protected String stylesheetEncoding; + + /** + * The scope to generate Groovydoc for. Should be one of: + *
      + *
    • "public"
    • + *
    • "protected"
    • + *
    • "package"
    • + *
    • "private"
    • + *
    + * + * @parameter default-value="private" + */ + protected String scope; + + /** + * Links to include in the generated groovydoc (key is link href, value is comma-separated packages to use that link). + * @since 1.0-beta-2 + * + * @parameter + */ + protected List links; + + /** + * Whether to include Java sources in groovydoc generation. + * @since 1.0-beta-2 + * + * @parameter default-value="true" + */ + protected boolean groovydocJavaSources; + + /** + * Generates the groovydoc for the specified sources. + * + * @param sourceDirectories The source directories to generate groovydoc for + * @param classpath The classpath to use for compilation + * @param outputDirectory The directory to save the generated groovydoc in + * @throws ClassNotFoundException When a class needed for groovydoc generation cannot be found + * @throws InstantiationException When a class needed for groovydoc generation cannot be instantiated + * @throws IllegalAccessException When a method needed for groovydoc generation cannot be accessed + * @throws InvocationTargetException When a reflection invocation needed for groovydoc generation cannot be completed + * @throws java.net.MalformedURLException When a classpath element provides a malformed URL + */ + @SuppressWarnings("unchecked") + protected void generateGroovydoc(final FileSet[] sourceDirectories, final List classpath, final File outputDirectory) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException, MalformedURLException { + if (sourceDirectories == null || sourceDirectories.length == 0) { + getLog().info("No source directories specified for Groovydoc generation. Skipping."); + return; + } + if (getGroovyVersion().compareTo(new Version(1, 6, 0, "RC-1")) == 0) { + // Groovy 1.6-RC-1 is excluded because of its dependency on org.apache.tools.ant.types.Path for constructing GroovyDocTool + getLog().warn("Groovy 1.6-RC-1 is blacklisted from the supported Groovydoc versions because of its dependency on Ant. Skipping Groovydoc generation."); + return; + } + + // create an isolated ClassLoader with all the appropriate project dependencies in it + ClassLoader isolatedClassLoader = createNewClassLoader(classpath); + + + // get classes we need with reflection + Class groovyDocToolClass = Class.forName("org.codehaus.groovy.tools.groovydoc.GroovyDocTool", true, isolatedClassLoader); + Class outputToolClass = Class.forName("org.codehaus.groovy.tools.groovydoc.OutputTool", true, isolatedClassLoader); + Class fileOutputToolClass = Class.forName("org.codehaus.groovy.tools.groovydoc.FileOutputTool", true, isolatedClassLoader); + Class resourceManagerClass = Class.forName("org.codehaus.groovy.tools.groovydoc.ResourceManager", true, isolatedClassLoader); + Class classpathResourceManagerClass = Class.forName("org.codehaus.groovy.tools.groovydoc.ClasspathResourceManager", true, isolatedClassLoader); + + // set up Groovydoc options + Properties properties = new Properties(); + properties.setProperty("windowTitle", windowTitle); + properties.setProperty("docTitle", docTitle); + properties.setProperty("footer", footer); + properties.setProperty("header", header); + properties.setProperty("author", Boolean.toString(displayAuthor)); + properties.setProperty("overviewFile", overviewFile != null ? overviewFile.getAbsolutePath() : ""); + try { + Scopes scopeVal = Scopes.valueOf(scope.toUpperCase()); + if (scopeVal.equals(Scopes.PUBLIC)) { + properties.setProperty("publicScope", "true"); + } else if (scopeVal.equals(Scopes.PROTECTED)) { + properties.setProperty("protectedScope", "true"); + } else if (scopeVal.equals(Scopes.PACKAGE)) { + properties.setProperty("packageScope", "true"); + } else if (scopeVal.equals(Scopes.PRIVATE)) { + properties.setProperty("privateScope", "true"); + } + } catch (IllegalArgumentException e) { + getLog().warn("Scope (" + scope + ") was not recognized. Skipping argument."); + } + Object fileOutputTool = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(fileOutputToolClass)); + Object classpathResourceManager = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(classpathResourceManagerClass)); + FileSetManager fileSetManager = new FileSetManager(getLog()); + List sourceDirectoriesStrings = new ArrayList(); + for (FileSet sourceDirectory : sourceDirectories) { + sourceDirectoriesStrings.add(sourceDirectory.getDirectory()); + } + GroovyDocTemplateInfo groovyDocTemplateInfo = new GroovyDocTemplateInfo(getGroovyVersion()); + Object groovyDocTool; + List linksList = new ArrayList(); + if (links != null && links.size() > 0) { + Class linkArgumentClass = null; + if (getGroovyVersion().compareTo(new Version(1, 6, 0, "RC-2")) >= 0) { + linkArgumentClass = Class.forName("org.codehaus.groovy.tools.groovydoc.LinkArgument", true, isolatedClassLoader); + } else if (getGroovyVersion().compareTo(new Version(1, 5, 2)) >= 0) { + linkArgumentClass = Class.forName("org.codehaus.groovy.ant.Groovydoc$LinkArgument", true, isolatedClassLoader); + } + if (linkArgumentClass != null) { + for (Link link : links) { + Object linkArgument = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(linkArgumentClass)); + ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(linkArgumentClass, "setHref", String.class), linkArgument, link.getHref()); + ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(linkArgumentClass, "setPackages", String.class), linkArgument, link.getPackages()); + linksList.add(linkArgument); + } + } else { + getLog().warn("Requested to use Groovydoc links, but your Groovy version doesn't support it (must be 1.5.2 or newer). Ignoring links parameter."); + } + } + if (getGroovyVersion().compareTo(new Version(1, 6, 0, "RC-2")) < 0) { + getLog().warn("Your Groovy version doesn't support Groovydoc documentation properties (docTitle, footer, header, displayAuthor, overviewFile, and scope). You need Groovy 1.6-RC-2 or newer to support this. Ignoring properties."); + } + if (getGroovyVersion().compareTo(new Version(1, 6, 0, "RC-2")) >= 0) { + groovyDocTool = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyDocToolClass, resourceManagerClass, String[].class, String[].class, String[].class, String[].class, List.class, Properties.class), + classpathResourceManager, + sourceDirectoriesStrings.toArray(new String[sourceDirectoriesStrings.size()]), + groovyDocTemplateInfo.defaultDocTemplates(), + groovyDocTemplateInfo.defaultPackageTemplates(), + groovyDocTemplateInfo.defaultClassTemplates(), + linksList, + properties + ); + } else if (getGroovyVersion().compareTo(new Version(1, 5, 2)) >= 0) { + groovyDocTool = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyDocToolClass, resourceManagerClass, String.class, String[].class, String[].class, String[].class, List.class), + classpathResourceManager, + sourceDirectoriesStrings.get(0), + groovyDocTemplateInfo.defaultDocTemplates(), + groovyDocTemplateInfo.defaultPackageTemplates(), + groovyDocTemplateInfo.defaultClassTemplates(), + linksList + ); + if (sourceDirectoriesStrings.size() > 1) { + getLog().warn("Your Groovy version doesn't support more than one Groovydoc source directory (must be 1.6-RC-2 or newer). Only using first source directory (" + sourceDirectoriesStrings.get(0) + ")."); + } + } else { + groovyDocTool = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyDocToolClass, resourceManagerClass, String.class, String[].class, String[].class, String[].class), + classpathResourceManager, + sourceDirectoriesStrings.get(0), + groovyDocTemplateInfo.defaultDocTemplates(), + groovyDocTemplateInfo.defaultPackageTemplates(), + groovyDocTemplateInfo.defaultClassTemplates() + ); + if (sourceDirectoriesStrings.size() > 1) { + getLog().warn("Your Groovy version doesn't support more than one Groovydoc source directory (must be 1.6-RC-2 or newer). Only using first source directory (" + sourceDirectoriesStrings.get(0) + ")."); + } + } + + // prevent Java stubs (which lack Javadoc) from overwriting Groovydoc by removing Java sources + List javaSources = new ArrayList(); + List groovySources = new ArrayList(); + List possibleGroovyStubs = new ArrayList(); + for (FileSet sourceDirectory : sourceDirectories) { + List sources = Arrays.asList(fileSetManager.getIncludedFiles(sourceDirectory)); + for (String source : sources) { + if (source.endsWith(".java") && !javaSources.contains(source)) { + javaSources.add(source); + } else if (!groovySources.contains(source)) { + groovySources.add(source); + possibleGroovyStubs.add(source.replaceFirst("\\." + Files.getFileExtension(source), ".java")); + } + } + } + javaSources.removeAll(possibleGroovyStubs); + List groovydocSources = new ArrayList(); + groovydocSources.addAll(javaSources); + groovydocSources.addAll(groovySources); + + // add the Groovydoc sources + getLog().debug("Adding sources to generate Groovydoc for:"); + if (getLog().isDebugEnabled()) { + getLog().debug(" " + groovydocSources); + } + + // generate Groovydoc + if (getGroovyVersion().compareTo(new Version(1, 6, 0, "RC-2")) >= 0) { + ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyDocToolClass, "add", List.class), groovyDocTool, groovydocSources); + } else { + for (String groovydocSource : groovydocSources) { + ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyDocToolClass, "add", String.class), groovyDocTool, groovydocSource); + } + } + ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyDocToolClass, "renderToOutput", outputToolClass, String.class), groovyDocTool, fileOutputTool, outputDirectory.getAbsolutePath()); + + // overwrite stylesheet.css with provided stylesheet (if configured) + if (stylesheetFile != null) { + copyStylesheet(outputDirectory); + } + } + + /** + * Copies the stylesheet to the specified output directory. + * + * @param outputDirectory The output directory to copy the stylesheet to + */ + private void copyStylesheet(final File outputDirectory) { + getLog().info("Using stylesheet from " + stylesheetFile.getAbsolutePath() + "."); + Closer closer = Closer.create(); + try { + try { + BufferedReader bufferedReader = closer.register(new BufferedReader(new InputStreamReader(new FileInputStream(stylesheetFile), stylesheetEncoding))); + StringBuilder css = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + css.append(line).append("\n"); + } + File outfile = new File(outputDirectory, "stylesheet.css"); + BufferedWriter bufferedWriter = closer.register(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), stylesheetEncoding))); + bufferedWriter.write(css.toString()); + } catch (Throwable throwable) { + throw closer.rethrow(throwable); + } finally { + closer.close(); + } + } catch (IOException e) { + getLog().warn("Unable to copy specified stylesheet (" + stylesheetFile.getAbsolutePath() + ")."); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `InputStreamReader(...)` at line 319 is not released after line 319. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AbstractGroovydocMojo.copyStylesheet(File) + +### Procedure Id: +org.codehaus.gmavenplus.mojo.AbstractGroovydocMojo.copyStylesheet(java.io.File):void.60ea8cd86b90b925233b1fde5f86c200 + +### File: +src/main/java/org/codehaus/gmavenplus/mojo/AbstractGroovydocMojo.java + +### Key: +AbstractGroovydocMojo.java|copyStylesheet|RESOURCE_LEAK + +### Node Key: +f29a0b5fbb21603d796e3f4e7ba77dde + +### Hash: +ac329123156da69ace7b45a0db1f3a9a + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8302/instruction.md b/inferredbugs-8302/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c1a96f258de0606f0ad49b832b1c9d251989815a --- /dev/null +++ b/inferredbugs-8302/instruction.md @@ -0,0 +1,545 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jvm-tools +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright 2014 Alexey Ragozin + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.gridkit.jvmtool.heapdump; + +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +import org.gridkit.jvmtool.heapdump.PathStep.Move; +import org.netbeans.lib.profiler.heap.Field; +import org.netbeans.lib.profiler.heap.FieldValue; +import org.netbeans.lib.profiler.heap.Instance; +import org.netbeans.lib.profiler.heap.JavaClass; +import org.netbeans.lib.profiler.heap.ObjectFieldValue; +import org.netbeans.lib.profiler.heap.PrimitiveArrayInstance; + +public class HeapWalker { + + private static final Set BOX_TYPES = new HashSet(); + + static { + BOX_TYPES.add(Boolean.class.getName()); + BOX_TYPES.add(Byte.class.getName()); + BOX_TYPES.add(Short.class.getName()); + BOX_TYPES.add(Character.class.getName()); + BOX_TYPES.add(Integer.class.getName()); + BOX_TYPES.add(Long.class.getName()); + BOX_TYPES.add(Float.class.getName()); + BOX_TYPES.add(Double.class.getName()); + } + + private static final Map CONVERTERS = new HashMap(); + + static { + CONVERTERS.put(String.class.getName(), new InstanceConverter() { + @Override + public Object convert(Instance instance) { + return stringValue(instance); + } + }); + InstanceConverter primitiveConverter = new InstanceConverter() { + @Override + public Object convert(Instance instance) { + return primitiveValue(instance); + } + }; + InstanceConverter primitiveArrayConverter = new InstanceConverter() { + @Override + public Object convert(Instance instance) { + return primitiveArrayValue(instance); + } + }; + for(String ptype: BOX_TYPES) { + CONVERTERS.put(ptype, primitiveConverter); + } + CONVERTERS.put("boolean[]", primitiveArrayConverter); + CONVERTERS.put("byte[]", primitiveArrayConverter); + CONVERTERS.put("char[]", primitiveArrayConverter); + CONVERTERS.put("short[]", primitiveArrayConverter); + CONVERTERS.put("int[]", primitiveArrayConverter); + CONVERTERS.put("long[]", primitiveArrayConverter); + CONVERTERS.put("float[]", primitiveArrayConverter); + CONVERTERS.put("double[]", primitiveArrayConverter); + } + + private static PrimitiveParser BOOL_PARSER = new PrimitiveParser() { + @Override + public Object toValue(String x) { + return Boolean.valueOf(x); + } + }; + + private static PrimitiveParser BYTE_PARSER = new PrimitiveParser() { + @Override + public Object toValue(String x) { + return Byte.valueOf(x); + } + }; + + private static PrimitiveParser SHORT_PARSER = new PrimitiveParser() { + @Override + public Object toValue(String x) { + return Short.valueOf(x); + } + }; + + private static PrimitiveParser CHAR_PARSER = new PrimitiveParser() { + @Override + public Object toValue(String x) { + return x.charAt(0); + } + }; + + private static PrimitiveParser INT_PARSER = new PrimitiveParser() { + @Override + public Object toValue(String x) { + return Integer.valueOf(x); + } + }; + + private static PrimitiveParser LONG_PARSER = new PrimitiveParser() { + @Override + public Object toValue(String x) { + return Long.valueOf(x); + } + }; + + private static PrimitiveParser FLOAT_PARSER = new PrimitiveParser() { + @Override + public Object toValue(String x) { + return Float.valueOf(x); + } + }; + + private static PrimitiveParser DOUBLE_PARSER = new PrimitiveParser() { + @Override + public Object toValue(String x) { + return Double.valueOf(x); + } + }; + + /** + * Converts instances of few well know Java classes from + * dump to normal java objects. + *
    + * Following are supported classes + *
  • {@link String}
  • + *
  • {@link Boolean}
  • + *
  • {@link Byte}
  • + *
  • {@link Short}
  • + *
  • {@link Character}
  • + *
  • {@link Integer}
  • + *
  • {@link Long}
  • + *
  • {@link Float}
  • + *
  • {@link Double}
  • + *
  • primitive arrays
  • + *
  • object arrays
  • + */ + /* TBD + *
  • {@link Arrays#asList(Object...)}
  • + *
  • {@link ArrayList} (subclasses would be reduced to {@link ArrayList})
  • + *
  • {@link HashMap} (subclasses including {@link LinkedHashMap} would be reduced to {@link ArrayList})
  • + *
  • {@link HashSet} (subclasses including {@link LinkedHashSet} would be reduced to {@link ArrayList})
  • + */ + @SuppressWarnings("unchecked") + public static T valueOf(Instance obj) { + if (obj == null) { + return null; + } + JavaClass t = obj.getJavaClass(); + InstanceConverter c = CONVERTERS.get(obj.getJavaClass().getName()); + while(c == null && t.getSuperClass() != null) { + t = t.getSuperClass(); + c = CONVERTERS.get(obj.getJavaClass().getName()); + } + if (c == null) { + // return instance as is + return (T) obj; + } + else { + return (T)c.convert(obj); + } + } + + /** + * Converts value referenced for path from dump to normal java objects. + * Few well known Java classes as long as primitive types are supported. + *
    + * Following are supported classes + *
  • {@link String}
  • + *
  • {@link Boolean}
  • + *
  • {@link Byte}
  • + *
  • {@link Short}
  • + *
  • {@link Character}
  • + *
  • {@link Integer}
  • + *
  • {@link Long}
  • + *
  • {@link Float}
  • + *
  • {@link Double}
  • + *
  • primitive arrays
  • + *
  • object arrays
  • + */ + /* TBD + *
  • {@link Arrays#asList(Object...)}
  • + *
  • {@link ArrayList} (subclasses would be reduced to {@link ArrayList})
  • + *
  • {@link HashMap} (subclasses including {@link LinkedHashMap} would be reduced to {@link ArrayList})
  • + *
  • {@link HashSet} (subclasses including {@link LinkedHashSet} would be reduced to {@link ArrayList})
  • + */ + @SuppressWarnings("unchecked") + public static T valueOf(Instance obj, String pathSpec) { + PathStep[] steps = HeapPath.parsePath(pathSpec, true); + if (steps.length > 0 && steps[steps.length - 1] instanceof FieldStep) { + PathStep[] shortPath = Arrays.copyOf(steps, steps.length - 1); + FieldStep lastStep = (FieldStep) steps[steps.length - 1]; + String fieldName = lastStep.getFieldName(); + for(Instance i: HeapPath.collect(obj, shortPath)) { + for(FieldValue fv: i.getFieldValues()) { + if ((fieldName == null && (!fv.getField().isStatic())) + || (fv.getField().getName().equals(fieldName))) { + if (fv instanceof ObjectFieldValue) { + return valueOf(((ObjectFieldValue) fv).getInstance()); + } + else { + // have to use this as private package API is used behind scene + return (T) i.getValueOfField(fv.getField().getName()); + } + } + } + } + return null; + } + else if (steps.length > 0 && steps[steps.length - 1] instanceof ArrayIndexStep) { + PathStep[] shortPath = Arrays.copyOf(steps, steps.length - 1); + ArrayIndexStep lastStep = (ArrayIndexStep) steps[steps.length - 1]; + for(Instance i: HeapPath.collect(obj, shortPath)) { + if (i instanceof PrimitiveArrayInstance) { + Object array = valueOf(i); + if (array != null) { + int len = Array.getLength(array); + int n = lastStep.getIndex(); + if (n < 0) { + n = 0; + } + if (n < len) { + return (T) Array.get(array, n); + } + else { + return null; + } + } + } + else { + for(Instance x: HeapPath.collect(i, new PathStep[]{lastStep})) { + return valueOf(x); + } + } + } + return null; + + } else { + for(Instance i: HeapPath.collect(obj, steps)) { + return valueOf(i); + } + return null; + } + } + + public static String stringValue(Instance obj) { + if (obj == null) { + return null; + } + if (!"java.lang.String".equals(obj.getJavaClass().getName())) { + throw new IllegalArgumentException("Is not a string: " + obj.getInstanceId() + " (" + obj.getJavaClass().getName() + ")"); + } + char[] text = null; + int offset = 0; + int len = -1; + for(FieldValue f: obj.getFieldValues()) { + Field ff = f.getField(); + if ("value".equals(ff.getName())) { + PrimitiveArrayInstance chars = (PrimitiveArrayInstance) ((ObjectFieldValue)f).getInstance(); + text = new char[chars.getLength()]; + for(int i = 0; i != text.length; ++i) { + text[i] = ((String)chars.getValues().get(i)).charAt(0); + } + } + // fields below were removed in Java 7 + else if ("offset".equals(ff.getName())) { + offset = Integer.valueOf(f.getValue()); + } + else if ("count".equals(ff.getName())) { + len = Integer.valueOf(f.getValue()); + } + } + + if (len < 0) { + len = text.length; + } + + return new String(text, offset, len); + } + + @SuppressWarnings("unchecked") + public static T primitiveValue(Instance obj) { + if (obj == null) { + return null; + } + String className = obj.getJavaClass().getName(); + if (BOX_TYPES.contains(className)) { + return (T)obj.getValueOfField("value"); + } + else { + throw new IllegalArgumentException("Is not a primitive wrapper: " + obj.getInstanceId() + " (" + obj.getJavaClass().getName() + ")"); + } + } + + @SuppressWarnings("unchecked") + public static T primitiveArrayValue(Instance obj) { + if (obj == null) { + return null; + } + if (obj instanceof PrimitiveArrayInstance) { + PrimitiveArrayInstance pa = (PrimitiveArrayInstance) obj; + String type = pa.getJavaClass().getName(); + PrimitiveParser parser; + Object array; + int len = pa.getLength(); + if ("boolean[]".equals(type)) { + array = new boolean[len]; + parser = BOOL_PARSER; + } + else if ("byte[]".equals(type)) { + array = new byte[len]; + parser = BYTE_PARSER; + } + else if ("char[]".equals(type)) { + array = new char[len]; + parser = CHAR_PARSER; + } + else if ("short[]".equals(type)) { + array = new short[len]; + parser = SHORT_PARSER; + } + else if ("int[]".equals(type)) { + array = new int[len]; + parser = INT_PARSER; + } + else if ("long[]".equals(type)) { + array = new long[len]; + parser = LONG_PARSER; + } + else if ("float[]".equals(type)) { + array = new float[len]; + parser = FLOAT_PARSER; + } + else if ("double[]".equals(type)) { + array = new double[len]; + parser = DOUBLE_PARSER; + } + else { + throw new IllegalArgumentException("Is not a primitive array: " + obj.getInstanceId() + " (" + obj.getJavaClass().getName() + ")"); + } + + List values = pa.getValues(); + for(int i = 0; i != values.size(); ++i) { + Object val = values.get(i); + if (val instanceof String) { + val = parser.toValue((String) val); + } + Array.set(array, i, val); + } + + return (T)array; + } + else { + throw new IllegalArgumentException("Is not a primitive array: " + obj.getInstanceId() + " (" + obj.getJavaClass().getName() + ")"); + } + } + + public static Iterable walk(Instance root, String path) { + return HeapPath.collect(root, HeapPath.parsePath(path, true)); + } + + public static Instance walkFirst(Instance root, String path) { + Iterator it = walk(root, path).iterator(); + if (it.hasNext()) { + return it.next(); + } + else { + return null; + } + } + + public static String explainPath(Instance root, String path) { + PathStep[] chain = HeapPath.parsePath(path, true); + StringBuilder sb = new StringBuilder(); + Instance o = root; + for(int i = 0; i != chain.length; ++i) { + if (chain[i] instanceof TypeFilterStep) { + continue; + } + + try { + Move m = chain[i].track(o).next(); +// JavaClass hostType = hostType(o.getJavaClass(), m.pathSpec); +// hostType = hostType == null ? o.getJavaClass() : hostType; + +// sb.append("(" + shortName(hostType.getName()) + ")"); + sb.append("(" + shortName(o.getJavaClass().getName()) + ")"); + sb.append(m.pathSpec); + o = m.instance; + } + catch(NoSuchElementException e) { + sb.append("{failed: " + chain[i] + "}"); + break; + } + } + return sb.toString(); + } + + @SuppressWarnings("unused") + private static JavaClass hostType(JavaClass type, String pathSpec) { + if (pathSpec.startsWith(".")) { + pathSpec = pathSpec.substring(1); + } + for(Field f: type.getFields()) { + if (!f.isStatic() && f.getName().equals(pathSpec)) { + return f.getDeclaringClass(); + } + } + if (type.getSuperClass() != null) { + return hostType(type.getSuperClass(), pathSpec); + } + return null; + } + + + public static Set filterTypes(String filter, Iterable types) { + PathStep[] steps = HeapPath.parsePath("(" + filter + ")", true); + if (steps.length != 1 || !(steps[0] instanceof TypeFilterStep)) { + throw new IllegalArgumentException("Bad type filter: " + filter); + } + TypeFilterStep f = (TypeFilterStep) steps[0]; + Set result = new LinkedHashSet(); + for(JavaClass jc: types) { + if (f.evaluate(jc)) { + result.add(jc); + } + } + + return result; + } + + private static final String shortName(String name) { + int c = name.lastIndexOf('.'); + if (c >= 0) { + return "**." + name.substring(c + 1); + } + else { + return name; + } + } + + private interface InstanceConverter { + + public Object convert(Instance instance); + } + + private interface PrimitiveParser { + + public Object toValue(String x); + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `text` last assigned on line 274 could be null and is dereferenced at line 296. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String HeapWalker.stringValue(Instance) + +### Procedure Id: +org.gridkit.jvmtool.heapdump.HeapWalker.stringValue(org.netbeans.lib.profiler.heap.Instance):java.la.8d4ccf4b3acb9f8a860649c01d8eaadf + +### File: +hprof-heap/src/main/java/org/gridkit/jvmtool/heapdump/HeapWalker.java + +### Key: +HeapWalker.java|stringValue|NULL_DEREFERENCE + +### Node Key: +66a0c6023764b6c68c1765dac75c2ff0 + +### Hash: +39e1ecb13fa4dff47045303105d9aa7a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8304/instruction.md b/inferredbugs-8304/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a6236f9967bf543aa66292eb7340fa58dad86a11 --- /dev/null +++ b/inferredbugs-8304/instruction.md @@ -0,0 +1,183 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jReddit +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.jreddit.submissions; + +import com.github.jreddit.user.User; +import com.github.jreddit.utils.restclient.RestClient; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.ParseException; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import com.github.jreddit.utils.ApiEndpointUtils; + +/** + * This class offers some submission utilities. + * + * @author Omer Elnour + */ +public class Submissions { + + private final RestClient restClient; + + public enum Popularity { + HOT, NEW + } + + public enum Page { + FRONTPAGE + } + + public Submissions(RestClient restClient) { + this.restClient = restClient; + } + + /** + * This function returns a linked list containing the submissions on a given + * subreddit and page. (in progress) + * + * @param redditName The subreddit's name + * @param type HOT or NEW and some others to come + * @param frontpage TODO this + * @param user The user + * @return The linked list containing submissions + * @throws IOException If connection fails + * @throws ParseException If JSON parsing fails + */ + public LinkedList getSubmissions(String redditName, + Popularity type, Page frontpage, User user) throws IOException, ParseException { + + LinkedList submissions = new LinkedList(); + String urlString = "/r/" + redditName; + + switch (type) { + case NEW: + urlString += "/new"; + break; + default: + break; + } + + //TODO Implement Pages + + urlString += ".json"; + + JSONObject object = (JSONObject) restClient.get(urlString, user.getCookie()).getResponseObject(); + JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); + + JSONObject data; + for (Object anArray : array) { + data = (JSONObject) anArray; + data = ((JSONObject) data.get("data")); + submissions.add(new Submission(user, data.get("id").toString(), (data.get("permalink").toString()))); + } + + return submissions; + } + + /** + * Returns a list of submissions from a subreddit. + * + * @param subreddit The subreddit at which submissions you want to retrieve submissions. + * @return List of submissions on the subreddit. + */ + public List getSubmissions(String subreddit) { + // List of submissions made by this user + List submissions = new ArrayList(500); + try { + // Send GET request to get the account overview + JSONObject object = (JSONObject) restClient.get(String.format(ApiEndpointUtils.SUBMISSIONS, subreddit), null); + JSONObject data = (JSONObject) object.get("data"); + JSONArray children = (JSONArray) data.get("children"); + + JSONObject obj; + + for (Object aChildren : children) { + // Get the object containing the comment + obj = (JSONObject) aChildren; + obj = (JSONObject) obj.get("data"); + //add a new Submission to the list + submissions.add(new Submission(obj)); + } + } catch (Exception e) { + e.printStackTrace(); + } + + // Return the submissions + return submissions; + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `data.get("id")` could be null and is dereferenced at line 73. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +LinkedList Submissions.getSubmissions(String,Submissions$Popularity,Submissions$Page,User) + +### Procedure Id: +com.github.jreddit.submissions.Submissions.getSubmissions(java.lang.String,com.github.jreddit.submis.6248a7610cba7d83701562c3e9f51848 + +### File: +src/main/java/com/github/jreddit/submissions/Submissions.java + +### Key: +Submissions.java|getSubmissions|NULL_DEREFERENCE + +### Node Key: +42f56fda1ad408e362508b93a175bb0c + +### Hash: +e65e5175062069d8a957d34c3259eaf6 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8305/instruction.md b/inferredbugs-8305/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e92f2bd3e8db96e0bd3632d58c8ab16fdd1c8437 --- /dev/null +++ b/inferredbugs-8305/instruction.md @@ -0,0 +1,304 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jReddit +**Bug ID:** 27 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.jreddit.retrieval; + + +import static com.github.jreddit.utils.restclient.JsonUtils.safeJsonToString; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.LinkedList; +import java.util.List; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +import com.github.jreddit.entity.Kind; +import com.github.jreddit.entity.Subreddit; +import com.github.jreddit.entity.User; +import com.github.jreddit.exception.RedditError; +import com.github.jreddit.exception.RetrievalFailedException; +import com.github.jreddit.retrieval.params.SubredditsView; +import com.github.jreddit.utils.ApiEndpointUtils; +import com.github.jreddit.utils.ParamFormatter; +import com.github.jreddit.utils.restclient.RestClient; + +/** + * This class offers the following functionality: + * 1) Parsing the results of a request into Subreddit objects (see Subreddits.parse()). + * 2) The ability to get listings of subreddits (see Subreddits.get()). + * 3) The ability to search the subreddits (for subreddits) on Reddit (see Subreddits.search()). + * + * @author Benjamin Jakobus + * @author Raul Rene Lepsa + * @author Andrei Sfat + * @author Simon Kassing + */ +public class Subreddits implements ActorDriven { + + /** + * Handle to the REST client instance. + */ + private final RestClient restClient; + private User user; + + /** + * Constructor. + * + * @param restClient REST client instance + */ + public Subreddits(RestClient restClient) { + this.restClient = restClient; + } + + /** + * Constructor. + * @param restClient REST Client instance + * @param actor User instance + */ + public Subreddits(RestClient restClient, User actor) { + this.restClient = restClient; + this.user = actor; + } + + /** + * Switch the current user for the new user who will + * be used when invoking retrieval requests. + * + * @param new_actor New user + */ + public void switchActor(User new_actor) { + this.user = new_actor; + } + + /** + * Parses a JSON feed from the Reddit (URL) into a nice list of Subreddit objects. + * + * @param user User + * @param url URL + * @return Listing of submissions + */ + public List parse(String url) throws RetrievalFailedException, RedditError { + + // Determine cookie + String cookie = (user == null) ? null : user.getCookie(); + + // List of subreddits + List subreddits = new LinkedList(); + + // Send request to reddit server via REST client + Object response = restClient.get(url, cookie).getResponseObject(); + + if (response instanceof JSONObject) { + + JSONObject object = (JSONObject) response; + JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); + + // Iterate over the subreddit results + JSONObject data; + for (Object anArray : array) { + data = (JSONObject) anArray; + + // Make sure it is of the correct kind + String kind = safeJsonToString(data.get("kind")); + if (kind.equals(Kind.SUBREDDIT.value())) { + + // Create and add subreddit + data = ((JSONObject) data.get("data")); + subreddits.add(new Subreddit(data)); + + } + + } + + } else { + System.err.println("Cannot cast to JSON Object: '" + response.toString() + "'"); + } + + // Finally return list of subreddits + return subreddits; + + } + + /** + * Searches all subreddits with the given query using the given parameters. + * The parameters here are in Strings instead of wrapper objects, which allows users + * to manually adjust the parameters (if the API changes and jReddit is not updated + * in time yet). + * + * @param query Search query + * @param count Count at which the subreddits are started being numbered + * @param limit Maximum amount of subreddits that can be returned (0-100, 25 default (see Reddit API)) + * @param after The subreddit after which needs to be retrieved + * @param before The subreddit after which needs to be retrieved + * + * @return List of subreddits that satisfy the given parameters. + */ + public List search(String query, String count, String limit, String after, String before) throws RetrievalFailedException, RedditError { + + // Format parameters + String params = ""; + try { + params = ParamFormatter.addParameter(params, "q", URLEncoder.encode(query, "ISO-8859-1")); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + params = ParamFormatter.addParameter(params, "count", count); + params = ParamFormatter.addParameter(params, "limit", limit); + params = ParamFormatter.addParameter(params, "after", after); + params = ParamFormatter.addParameter(params, "before", before); + + // Retrieve submissions from the given URL + return parse(String.format(ApiEndpointUtils.SUBREDDITS_SEARCH, params)); + + } + + /** + * Searches all subreddits with the given query using the given parameters. + * + * @param query Search query + * @param count Count at which the subreddits are started being numbered + * @param limit Maximum amount of subreddits that can be returned (0-100, 25 default (see Reddit API)) + * @param after The subreddit after which needs to be retrieved + * @param before The subreddit after which needs to be retrieved + * + * @return List of subreddits that satisfy the given parameters. + */ + public List search(String query, int count, int limit, Subreddit after, Subreddit before) throws RetrievalFailedException, RedditError { + + if (query == null || query.isEmpty()) { + throw new IllegalArgumentException("The query must be defined."); + } + + return search( + query, + String.valueOf(count), + String.valueOf(limit), + (after != null) ? after.getFullName() : "", + (before != null) ? before.getFullName() : "" + ); + + } + + /** + * Gets all subreddits using the given parameters. + * The parameters here are in Strings instead of wrapper objects, which allows users + * to manually adjust the parameters (if the API changes and jReddit is not updated + * in time yet). + * + * @param type Type of subreddit, this determines the ordering (e.g. new or mine) + * @param count Count at which the subreddits are started being numbered + * @param limit Maximum amount of subreddits that can be returned (0-100, 25 default (see Reddit API)) + * @param after The subreddit after which needs to be retrieved + * @param before The subreddit after which needs to be retrieved + * + * @return List of subreddits that satisfy the given parameters. + */ + public List get(String type, String count, String limit, String after, String before) throws RetrievalFailedException, RedditError { + + // Format parameters + String params = ""; + params = ParamFormatter.addParameter(params, "count", count); + params = ParamFormatter.addParameter(params, "limit", limit); + params = ParamFormatter.addParameter(params, "after", after); + params = ParamFormatter.addParameter(params, "before", before); + + // Retrieve submissions from the given URL + return parse(String.format(ApiEndpointUtils.SUBREDDITS_GET, type, params)); + + } + + /** + * Gets all subreddits using the given parameters. + * + * @param type Type of subreddit, this determines the ordering (e.g. new or mine) + * @param count Count at which the subreddits are started being numbered + * @param limit Maximum amount of subreddits that can be returned (0-100, 25 default (see Reddit API)) + * @param after The subreddit after which needs to be retrieved + * @param before The subreddit after which needs to be retrieved + * + * @return List of subreddits that satisfy the given parameters. + */ + public List get(SubredditsView type, int count, int limit, Subreddit after, Subreddit before) throws RetrievalFailedException, RedditError { + return get( + (type != null) ? type.value() : "", + String.valueOf(count), + String.valueOf(limit), + (after != null) ? after.getFullName() : "", + (before != null) ? before.getFullName() : "" + ); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `kind` last assigned on line 101 could be null and is dereferenced at line 102. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List Subreddits.parse(String) + +### Procedure Id: +com.github.jreddit.retrieval.Subreddits.parse(java.lang.String):java.util.List.b3b9c46ebb35bed179a36902199dd8a9 + +### File: +src/main/java/com/github/jreddit/retrieval/Subreddits.java + +### Key: +Subreddits.java|parse|NULL_DEREFERENCE + +### Node Key: +7e9fc31bc469440d6384630f8b346526 + +### Hash: +98816e729c371350d5b052c23ba2f325 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8332/instruction.md b/inferredbugs-8332/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5d8d4c0c1f512a1e772e6346d094defa9d9d33a2 --- /dev/null +++ b/inferredbugs-8332/instruction.md @@ -0,0 +1,111 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** whatsmars +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.itlong.whatsmars.base.tmp; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Map; + +/** + * Created by shenhongxi on 2015/11/9. + * javahongxi + */ +public class T { + public static void main(String[] args) throws Exception { + String path = "E:/btdata/bt_cumulation.txt"; + BufferedReader br = new BufferedReader(new FileReader(path)); + String line = null; + br.readLine(); + + PrintWriter pw = new PrintWriter("E:/btdata/bt_cumulation2.txt"); + int i = 0; + while ((line = br.readLine()) != null) { + //System.out.println("'" + line + "',"); + String[] ss = line.split(","); + String pin = ss[1]; + pw.println(pin); + if (i++ % 10 == 0) { + pw.flush(); + System.out.println(i); + } + } + + br.close(); + pw.close(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileReader` acquired by call to `new()` at line 16 is not released after line 35. +**Note**: potential exception at line 18 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void T.main(java.lang.String[]) + +### Procedure Id: +com.itlong.whatsmars.base.tmp.T.main(java.lang.String[]):void.c286bdaacde6c15963f456a77fb89512 + +### File: +whatsmars-javase-example/src/main/java/com/itlong/whatsmars/base/tmp/T.java + +### Key: +T.java|main|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +60d22891ac06b1e6887c73d7e8f09813 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8333/instruction.md b/inferredbugs-8333/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e101dfd956138d04effe2004f9b406c5cf35eb15 --- /dev/null +++ b/inferredbugs-8333/instruction.md @@ -0,0 +1,111 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** whatsmars +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.itlong.whatsmars.base.tmp; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Map; + +/** + * Created by shenhongxi on 2015/11/9. + * javahongxi + */ +public class T { + public static void main(String[] args) throws Exception { + String path = "E:/btdata/bt_cumulation.txt"; + BufferedReader br = new BufferedReader(new FileReader(path)); + String line = null; + br.readLine(); + + PrintWriter pw = new PrintWriter("E:/btdata/bt_cumulation2.txt"); + int i = 0; + while ((line = br.readLine()) != null) { + //System.out.println("'" + line + "',"); + String[] ss = line.split(","); + String pin = ss[1]; + pw.println(pin); + if (i++ % 10 == 0) { + pw.flush(); + System.out.println(i); + } + } + + br.close(); + pw.close(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PrintWriter` acquired to `pw` by call to `new()` at line 20 is not released after line 35. +**Note**: potential exception at line 22 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void T.main(java.lang.String[]) + +### Procedure Id: +com.itlong.whatsmars.base.tmp.T.main(java.lang.String[]):void.c286bdaacde6c15963f456a77fb89512 + +### File: +whatsmars-javase-example/src/main/java/com/itlong/whatsmars/base/tmp/T.java + +### Key: +T.java|main|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +524c565bf33e2083ef671109a59b0901 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8334/instruction.md b/inferredbugs-8334/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d41abc45c232bd44b4184d9c6716e6ad34466d9e --- /dev/null +++ b/inferredbugs-8334/instruction.md @@ -0,0 +1,83 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** whatsmars +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.hongxi.whatsmars.mq.rocketmq.spring.demo; + +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class Consumer { + public static void main(String[] args) { + new ClassPathXmlApplicationContext("spring/rocketmq-consumer.xml"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.springframework.context.support.ClassPathXmlApplicationContext` acquired by call to `new()` at line 7 is not released after line 7. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Consumer.main(java.lang.String[]) + +### Procedure Id: +org.hongxi.whatsmars.mq.rocketmq.spring.demo.Consumer.main(java.lang.String[]):void.df887389baed9cbc4852e0e569f9d69c + +### File: +whatsmars-mq/src/main/java/org/hongxi/whatsmars/mq/rocketmq/spring/demo/Consumer.java + +### Key: +Consumer.java|main|RESOURCE_LEAK + +### Node Key: +a389af274a9b8bd4479f2eb273323f0e + +### Hash: +df21878f46ed570f016e09ba3944fb3f + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8335/instruction.md b/inferredbugs-8335/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..491ab8b67fcf9bd92ba454318cd155b8867894fa --- /dev/null +++ b/inferredbugs-8335/instruction.md @@ -0,0 +1,163 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** apollo +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package io.logz.apollo.status; + +import io.logz.apollo.dao.DeployableVersionDao; +import io.logz.apollo.dao.DeploymentDao; +import io.logz.apollo.dao.EnvironmentDao; +import io.logz.apollo.dao.ServiceDao; +import io.logz.apollo.models.DeployableVersion; +import io.logz.apollo.models.Deployment; +import io.logz.apollo.models.Service; +import javax.inject.Inject; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static java.util.Objects.requireNonNull; + +public class ServiceStatusHandler { + private final DeploymentDao deploymentDao; + private final DeployableVersionDao deployableVersionDao; + private final EnvironmentDao environmentDao; + private final ServiceDao serviceDao; + private static final int MIN_DAYS_OF_UNDEPLOYED_SERVICES = 21; + + @Inject + public ServiceStatusHandler(DeploymentDao deploymentDao, DeployableVersionDao deployableVersionDao, EnvironmentDao environmentDao, ServiceDao serviceDao) { + this.deploymentDao = requireNonNull(deploymentDao); + this.deployableVersionDao = requireNonNull(deployableVersionDao); + this.environmentDao = requireNonNull(environmentDao); + this.serviceDao = requireNonNull(serviceDao); + } + + public List getUndeployedServices() { + List productionEnvironmentsIds = getProductionEnvironmentsIds(); + List undeployedServices = new ArrayList<>(); + productionEnvironmentsIds.forEach(environmentId -> undeployedServices.addAll(getUndeployedServicesByEnvironmentId(environmentId))); + return undeployedServices; + } + + private List getUndeployedServicesByEnvironmentId(int environmentId) { + List services = serviceDao.getAllServices(); + List undeployedServicesIds = new ArrayList<>(); + services.forEach(service -> { + if(isServiceUndeployed(environmentId, service.getId())) { + undeployedServicesIds.add(service.getId()); + } + }); + return undeployedServicesIds; + } + + private List getProductionEnvironmentsIds() { + return environmentDao.getProductionEnvironmentsIds(); + } + + private boolean isServiceUndeployed(int environmentId, int serviceId){ + Date latestDeploymentDate = getLatestDeploymentDateByServiceIdInEnvironment(environmentId, serviceId); + Date latestUpdatedDate = getLatestDeployableVersionDateByServiceId(serviceId); + + if(latestDeploymentDate != null) { + long diffBetweenDatesInDays = TimeUnit.DAYS.convert(Math.abs(latestDeploymentDate.getTime() - latestUpdatedDate.getTime()), TimeUnit.MILLISECONDS); + return diffBetweenDatesInDays > MIN_DAYS_OF_UNDEPLOYED_SERVICES ? true : false; + } + if(latestUpdatedDate != null) { + Date durationSinceLatestUpdate = Date.from(LocalDate.now().minusDays((long) MIN_DAYS_OF_UNDEPLOYED_SERVICES).atStartOfDay(ZoneId.systemDefault()).toInstant()); + if(latestUpdatedDate.compareTo(durationSinceLatestUpdate) < 0) { + return true; + } + } + return false; + } + + private Date getLatestDeploymentDateByServiceIdInEnvironment(int environmentId, int serviceId) { + Deployment deployment = deploymentDao.getLatestDeploymentOfServiceInEnvironment(serviceId, environmentId); + if(deployment != null){ + return deployment.getLastUpdate(); + } + return null; + } + + private Date getLatestDeployableVersionDateByServiceId(int serviceId) { + DeployableVersion latestDeployableVersion = deployableVersionDao.getLatestDeployableVersionByServiceId(serviceId); + if(latestDeployableVersion != null) { + return latestDeployableVersion.getCommitDate(); + } + return null; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `latestUpdatedDate` last assigned on line 59 could be null and is dereferenced at line 62. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean ServiceStatusHandler.isServiceUndeployed(int,int) + +### Procedure Id: +io.logz.apollo.status.ServiceStatusHandler.isServiceUndeployed(int,int):boolean.dc86429149443c80629e6ca134e7b863 + +### File: +apollo-backend/src/main/java/io/logz/apollo/status/ServiceStatusHandler.java + +### Key: +ServiceStatusHandler.java|isServiceUndeployed|NULL_DEREFERENCE + +### Node Key: +42f56fda1ad408e362508b93a175bb0c + +### Hash: +3a50d6218e99d28b4431f87712bea506 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8357/instruction.md b/inferredbugs-8357/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..60e1631977c8e995070dedb7668f9b40f3dcf859 --- /dev/null +++ b/inferredbugs-8357/instruction.md @@ -0,0 +1,375 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riot-api-java +**Bug ID:** 27 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2016 Taylor Caldwell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.rithms.riot.api.request; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.logging.Level; + +import net.rithms.riot.api.ApiConfig; +import net.rithms.riot.api.ApiMethod; +import net.rithms.riot.api.RiotApi; +import net.rithms.riot.api.RiotApiAsync; +import net.rithms.riot.api.RiotApiException; + +/** + * This class is used to fire asynchronous call at the Riot Api. You should not construct these requests manually. To fire asynchronous + * requests, use a {@link RiotApiAsync} object. + * + * @author Daniel 'Linnun' Figge + * @see RiotApiAsync + */ +public class AsyncRequest extends Request implements Runnable { + + protected final Object signal = new Object(); + + protected List listeners = new ArrayList(); + protected Thread executionThread = null; + private boolean sent = false; + + /** + * Constructs an asynchronous request + * + * @param config + * Configuration to use + * @param method + * Api method to call + * @see ApiConfig + * @see ApiMethod + */ + public AsyncRequest(ApiConfig config, ApiMethod method) { + super(); + init(config, method); + setTimeout(); + } + + /** + * Adds a {@link RequestListener} to this request + * + * @param listener + * A request listener + * @see RequestListener + */ + public void addListener(RequestListener listener) { + if (!listeners.contains(listener)) { + listeners.add(listener); + } + } + + /** + * Adds a given collection of {@link RequestListener} to this request + * + * @param listeners + * A collection of request listeners + * @see RequestListener + */ + public void addListeners(Collection listeners) { + for (RequestListener listener : listeners) { + if (!this.listeners.contains(listener)) { + this.listeners.add(listener); + } + } + } + + /** + * Waits indefinitely until the request completes. + *

    + * If the thread is interrupted while waiting for the request to complete, this method will throw an {@code InterruptedException} and + * the thread's interrupt flag will be cleared. + *

    + *

    + * Please note that this method is blocking and thus negates the advantage of the asynchronous nature of this class. Consider using a + * {@link RequestListener} instead. + *

    + * + * @throws InterruptedException + * If the method is interrupted by calling {@link Thread#interrupt()}. The interrupt flag will be cleared + */ + public void await() throws InterruptedException { + while (!isDone()) { + synchronized (signal) { + signal.wait(); + } + } + } + + /** + * Waits for at most the given time until the request completes. + *

    + * If the thread is interrupted while waiting for the request to complete, this method will throw an {@code InterruptedException} and + * the thread's interrupt flag will be cleared. + *

    + *

    + * Please note that this method is blocking and thus negates the advantage of the asynchronous nature of this class. Consider using a + * {@link RequestListener} instead. + *

    + * + * @param timeout + * The maximum amount of the given time unit to wait + * @param unit + * The time unit of the {@code timeout} argument + * @throws InterruptedException + * If the method is interrupted by calling {@link Thread#interrupt()}. The interrupt flag will be cleared + * @throws TimeoutException + * If the given time elapsed without the request completing + */ + public void await(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { + await(timeout, unit, false); + } + + /** + * Waits for at most the given time until the request completes. + *

    + * If the thread is interrupted while waiting for the request to complete, this method will throw an {@code InterruptedException} and + * the thread's interrupt flag will be cleared. + *

    + *

    + * Please note that this method is blocking and thus negates the advantage of the asynchronous nature of this class. Consider using a + * {@link RequestListener} instead. + *

    + * + * @param timeout + * The maximum amount of the given time unit to wait + * @param unit + * The time unit of the {@code timeout} argument + * @param cancelOnTimeout + * Whether or not the request should be cancelled, if the given {@code timeout} is elapsed without the request completing + * @throws InterruptedException + * If the method is interrupted by calling {@link Thread#interrupt()}. The interrupt flag will be cleared + * @throws TimeoutException + * If the given time elapsed without the request completing + */ + public void await(long timeout, TimeUnit unit, boolean cancelOnTimeout) throws InterruptedException, TimeoutException { + final long end = System.currentTimeMillis() + unit.toMillis(timeout); + while (!isDone() && System.currentTimeMillis() < end) { + synchronized (signal) { + signal.wait(end - System.currentTimeMillis()); + } + } + if (!isDone()) { + if (cancelOnTimeout) { + cancel(); + } + throw new TimeoutException(); + } + } + + @Override + public boolean cancel() { + boolean cancelled = super.cancel(); + if (!cancelled) { + return false; + } + synchronized (signal) { + signal.notifyAll(); + } + // Try to force-quit the connection + if (connection != null) { + setTimeout(1); + connection.disconnect(); + } + return true; + } + + @Override + public synchronized void execute() { + if (isSent()) { + return; + } + sent = true; + executionThread = new Thread(this); + executionThread.start(); + } + + /** + * Retrieves the request's result. If an exception would be thrown, it is swallowed, since you should only call this method, if the + * request succeeded. + * + *

    + * If you want this method to throw exceptions, please use {@link #getDtoAndThrowException()} instead. + *

    + * + * @return The object returned by the api call, or {@code null} if the request did not finish yet + */ + @Override + public T getDto() { + try { + return super.getDto(true); + } catch (RiotApiException e) { + RiotApi.log.log(Level.FINE, "Retrieving Dto Failed", e); + } + return null; + } + + /** + * Retrieves the request's result. If an exception occures, it is thrown. + * + *

    + * If you do not want this method to throw exceptions, please use {@link #getDto()} instead. + *

    + * + * @return The object returned by the api call, or {@code null} if the request did not finish yet + * @throws RiotApiException + * If an exception occurs while parsing the Riot Api's response + */ + public T getDtoAndThrowException() throws RiotApiException { + return super.getDto(true); + } + + /** + * Returns {@code true} if this request has started execution + * + * @return {@code true} if this request has started execution + */ + public boolean isSent() { + return sent; + } + + /** + * Removes all listeners from this request + * + * @see RequestListener + */ + public void removeAllListeners() { + listeners.clear(); + } + + /** + * Removes a listener from this request + * + * @param listener + * Listener to remove + * @see RequestListener + */ + public void removeListener(RequestListener listener) { + listeners.remove(listener); + } + + @Override + public void run() { + try { + super.execute(); + } catch (RiotApiException e) { + setException(e); + } + } + + @Override + protected boolean setState(RequestState state) { + if (isDone()) { + return false; + } + for (RequestListener listener : listeners) { + if (state == RequestState.Succeeded) { + listener.onRequestSucceeded(this); + } else if (state == RequestState.Failed) { + listener.onRequestFailed(getException()); + } else if (state == RequestState.TimeOut) { + listener.onRequestTimeout(this); + } + } + super.setState(state); + if (state == RequestState.Cancelled || state == RequestState.Succeeded || state == RequestState.Failed || state == RequestState.TimeOut) { + synchronized (signal) { + signal.notifyAll(); + } + } + return true; + } + + @Override + protected void setTimeout() { + setTimeout(config.getAsyncRequestTimeout()); + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `net.rithms.riot.api.request.AsyncRequest.setState` indirectly reads without synchronization from `this.net.rithms.riot.api.request.Request.exception`. Potentially races with write in method `AsyncRequest.getDtoAndThrowException()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean AsyncRequest.setState(RequestState) + +### Procedure Id: +net.rithms.riot.api.request.AsyncRequest.setState(net.rithms.riot.api.request.RequestState):boolean.f5ca4d1641cd17fd9b62774730f70490 + +### File: +src/net/rithms/riot/api/request/AsyncRequest.java + +### Key: +AsyncRequest.java|setState|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +48039c47fab267b25acbf7b76a8b728b + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8359/instruction.md b/inferredbugs-8359/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..60922ddf406e37c57c6ff12044c1e34c9f482706 --- /dev/null +++ b/inferredbugs-8359/instruction.md @@ -0,0 +1,1906 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riot-api-java +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package main.java.riotapi; + +/** + * Riot Games API Java Library + * riot-api-java + * by Taylor Caldwell - @rithms + * http://rithms.im + */ + +/* + * Copyright 2014 Taylor Caldwell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.util.List; +import java.util.Map; + +import constant.PlatformId; +import constant.QueueType; +import constant.Region; +import constant.Season; +import constant.staticdata.ChampData; +import constant.staticdata.ItemData; +import constant.staticdata.ItemListData; +import constant.staticdata.MasteryData; +import constant.staticdata.MasteryListData; +import constant.staticdata.RuneData; +import constant.staticdata.RuneListData; +import constant.staticdata.SpellData; +import dto.Champion.*; +import dto.CurrentGame.CurrentGameInfo; +import dto.FeaturedGames.FeaturedGames; +import dto.Game.RecentGames; +import dto.League.League; +import dto.Match.MatchDetail; +import dto.MatchHistory.PlayerHistory; +import dto.Team.Team; +import dto.Static.ChampionList; +import dto.Static.GameMapList; +import dto.Static.Item; +import dto.Static.ItemList; +import dto.Static.LanguageStrings; +import dto.Static.Mastery; +import dto.Static.MasteryList; +import dto.Static.Realm; +import dto.Static.Rune; +import dto.Static.RuneList; +import dto.Static.SummonerSpell; +import dto.Static.SummonerSpellList; +import dto.Stats.PlayerStatsSummaryList; +import dto.Stats.RankedStats; +import dto.Status.Shard; +import dto.Status.ShardStatus; +import dto.Summoner.MasteryPages; +import dto.Summoner.RunePages; +import dto.Summoner.Summoner; +import method.*; + +public class RiotApi { + + /** + * The base URL for all API requests + */ + private String endpoint = Region.GLOBAL.getEndpoint(); + + private Region region = Region.NA; // North American region default + private Season season = null; + private String key; + + public RiotApi() { + } + + public RiotApi(String key) { + this.setKey(key); + } + + public RiotApi(String key, Region region) { + this.setKey(key); + this.setRegion(region); + } + + /** + * Get all the champions for a set region + * + * @return A list of all the champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions() throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey()); + } + + /** + * Get all the champions for a given region + * + * @param region The desired region + * @return A list of all the champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(Region region) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey()); + } + + /** + * Get all the champions for a set region + * + * @param freeToPlay Only free to play + * @return A list of all the free to play champions for the set region when + * freeToPlay is true A list of all the champions for the set region when + * freeToPlay is false + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(boolean freeToPlay) throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey(), freeToPlay); + } + + /** + * Get all champions for a given region + * + * @param region The desired region + * @param freeToPlay Only free to play + * @return A list of all the free to play champions for the given region + * when freeToPlay is true A list of all the champions for the given region + * when freeToPlay is false + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(Region region, boolean freeToPlay) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey(), freeToPlay); + } + + /** + * Get all free to play champions for a given region + * + * @param region The desired region + * @return A list of all the free to play champions for the given region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getFreeToPlayChampions(Region region) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey(), true); + } + + /** + * Get all free to play champions for a set region + * + * @return A list of all the free to play champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getFreeToPlayChampions() throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey(), true); + } + + /** + * Get a champion by id for a given region + * + * @param region The desired region + * @param champId The ID of the desired champion + * @return The champion of the given ID + * @see ChampionList + * @throws RiotApiException + */ + public Champion getChampionById(Region region, int champId) throws RiotApiException { + + return ChampionMethod.getChampionById(region.getEndpoint(), region.getName(), getKey(), champId); + } + + /** + * Get a champion by id for a set region + * + * @param champId The ID of the desired champion + * @return The champion of the given ID + * @see ChampionList + * @throws RiotApiException + */ + public Champion getChampionById(int champId) throws RiotApiException { + + return ChampionMethod.getChampionById(getEndpoint(), getRegion(), getKey(), champId); + } + + /** + * Get recent games for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return Recent games of the given summoner + * @see RecentGames + * @throws RiotApiException + */ + public RecentGames getRecentGames(Region region, long summonerId) throws RiotApiException { + + return GameMethod.getRecentGames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get recent games for a given summoner + * + * @param summonerId The ID of the desired summoner + * @return Recent games of the given summoner + * @see RecentGames + * @throws RiotApiException + */ + public RecentGames getRecentGames(long summonerId) throws RiotApiException { + + return GameMethod.getRecentGames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(Region region, long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(Region region, long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(Region region, String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(String summonerIds) throws RiotApiException { + return LeagueMethod.getLeagueBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(Region region, String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(Region region, long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(Region region, long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(Region region, String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(Region region, String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @throws RiotApiException + */ + public League getChallengerLeagues(Region region) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(region.getEndpoint(), region.getName(), getKey()); + } + + /** + * + * @throws RiotApiException + */ + public League getChallengerLeagues() throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(getEndpoint(), getRegion(), getKey()); + } + + /** + * + * @param region + * @param queueType + * @throws RiotApiException + */ + public League getChallengerLeagues(Region region, QueueType queueType) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(region.getEndpoint(), region.getName(), getKey(), queueType); + } + + /** + * + * @param queueType + * @throws RiotApiException + * @return League + */ + public League getChallengerLeagues(QueueType queueType) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(getEndpoint(), getRegion(), getKey(), queueType); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Region region, Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(region.getEndpoint(), region.getName(), season.getName(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(getEndpoint(), getRegion(), season.getName(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Region region, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(region.getEndpoint(), region.getName(), getSeason(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param summonerId The ID of the desired summoner + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(getEndpoint(), getRegion(), getSeason(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Region region, Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(region.getEndpoint(), region.getName(), season.getName(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(getEndpoint(), getRegion(), season.getName(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Region region, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(region.getEndpoint(), region.getName(), getSeason(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param summonerId The ID of the desired summoner + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(getEndpoint(), getRegion(), getSeason(), getKey(), summonerId); + } + + /** + * Get the mastery pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(String summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(String summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerNames The names of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersByName(Region region, String summonerNames) throws RiotApiException { + + return SummonerMethod.getSummonersByName(region.getEndpoint(), region.getName(), getKey(), summonerNames); + } + + /** + * Get summoners by names + * + * @param summonerNames The names of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersByName(String summonerNames) throws RiotApiException { + + return SummonerMethod.getSummonersByName(getEndpoint(), getRegion(), getKey(), summonerNames); + } + + /** + * Get summoner by name + * + * @param region The desired region + * @param summonerName The name of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerByName(Region region, String summonerName) throws RiotApiException { + + return SummonerMethod.getSummonersByName(region.getEndpoint(), region.getName(), getKey(), summonerName); + } + + /** + * Get summoner by name + * + * @param summonerName The name of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerByName(String summonerName) throws RiotApiException { + + return SummonerMethod.getSummonersByName(getEndpoint(), getRegion(), getKey(), summonerName); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(Region region, long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(Region region, String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerIds A comma separated list of IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param summonerIds A comma separated list of IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerId The IDs of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(Region region, long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param summonerId The IDs of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(Region region, String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param summonerId The ID of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get teams by summonerIDs + * + * @param region The desired region + * @param summonerIds A list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(Region region, long... summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param summonerIds A list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(long... summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param region The desired region + * @param summonerIds Comma-separated list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(Region region, String summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param summonerIds Comma-separated list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(String summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get match by ID + * + * @param region The desired region + * @param matchId The ID of the match + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(Region region, long matchId) throws RiotApiException { + + return MatchMethod.getMatch(region.getEndpoint(), region.getName(), getKey(), matchId); + } + + /** + * Get match by ID + * + * @param matchId The ID of the match + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(long matchId) throws RiotApiException { + + return MatchMethod.getMatch(getEndpoint(), getRegion(), getKey(), matchId); + } + + /** + * Get match by ID + * + * @param region The desired region + * @param matchId The ID of the match + * @param includeTimeline Flag indicating whether or not to include match timeline data + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(Region region, long matchId, boolean includeTimeline) throws RiotApiException { + + return MatchMethod.getMatch(region.getEndpoint(), region.getName(), getKey(), matchId, includeTimeline); + } + + /** + * Get match by ID + * + * @param matchId The ID of the match + * @param includeTimeline Flag indicating whether or not to include match timeline data + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(long matchId, boolean includeTimeline) throws RiotApiException { + + return MatchMethod.getMatch(getEndpoint(), getRegion(), getKey(), matchId, includeTimeline); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, -1, -1); + } + + /** + * + */ + public ChampionList getDataChampionList(Region region, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(region.getName(), getKey(), locale, version, dataById, champData); + } + + /** + * + */ + public ChampionList getDataChampionList(String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(getRegion(), getKey(), locale, version, dataById, champData); + } + + /** + * + */ + public ChampionList getDataChampionList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(region.getName(), getKey(), null, null, false, null); + } + + /** + * + */ + public ChampionList getDataChampionList() throws RiotApiException { + + return StaticDataMethod.getDataChampionList(getRegion(), getKey(), null, null, false, null); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(Region region, int id, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, locale, version, dataById, champData); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(int id, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, locale, version, dataById, champData); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, null, null, false, null); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(int id) throws RiotApiException { + + return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, null, null, false, null); + } + + /** + * + */ + public ItemList getDataItemList(Region region, String locale, String version, ItemListData itemListData) throws RiotApiException { + + return StaticDataMethod.getDataItemList(region.getName(), getKey(), locale, version, itemListData); + } + + /** + * + */ + public ItemList getDataItemList(String locale, String version, ItemListData itemListData) throws RiotApiException { + + return StaticDataMethod.getDataItemList(getRegion(), getKey(), locale, version, itemListData); + } + + /** + * + */ + public ItemList getDataItemList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataItemList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public ItemList getDataItemList() throws RiotApiException { + + return StaticDataMethod.getDataItemList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Item getDataItem(Region region, int id, String locale, String version, ItemData itemData) throws RiotApiException { + + return StaticDataMethod.getDataItem(region.getName(), getKey(), id, locale, version, itemData); + } + + /** + * + */ + public Item getDataItem(int id, String locale, String version, ItemData itemData) throws RiotApiException { + + return StaticDataMethod.getDataItem(getRegion(), getKey(), id, locale, version, itemData); + } + + /** + * + */ + public Item getDataItem(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataItem(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Item getDataItem(int id) throws RiotApiException { + + return StaticDataMethod.getDataItem(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public Realm getDataRealm(Region region) throws RiotApiException { + + return StaticDataMethod.getDataRealm(region.getName(), getKey()); + } + + /** + * + */ + public Realm getDataRealm() throws RiotApiException { + + return StaticDataMethod.getDataRealm(getRegion(), getKey()); + } + + /** + * + */ + public RuneList getDataRuneList(Region region, String locale, String version, RuneListData runeListData) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(region.getName(), getKey(), locale, version, runeListData); + } + + /** + * + */ + public RuneList getDataRuneList(String locale, String version, RuneListData runeListData) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(getRegion(), getKey(), locale, version, runeListData); + } + + /** + * + */ + public RuneList getDataRuneList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public RuneList getDataRuneList() throws RiotApiException { + + return StaticDataMethod.getDataRuneList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Rune getDataRune(Region region, int id, String locale, String version, RuneData runeData) throws RiotApiException { + + return StaticDataMethod.getDataRune(region.getName(), getKey(), id, locale, version, runeData); + } + + /** + * + */ + public Rune getDataRune(int id, String locale, String version, RuneData runeData) throws RiotApiException { + + return StaticDataMethod.getDataRune(getRegion(), getKey(), id, locale, version, runeData); + } + + /** + * + */ + public Rune getDataRune(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataRune(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Rune getDataRune(int id) throws RiotApiException { + + return StaticDataMethod.getDataRune(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public MasteryList getDataMasteryList(Region region, String locale, String version, MasteryListData masteryListData) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), locale, version, masteryListData); + } + + /** + * + */ + public MasteryList getDataMasteryList(String locale, String version, MasteryListData masteryListData) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), locale, version, masteryListData); + } + + /** + * + */ + public MasteryList getDataMasteryList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public MasteryList getDataMasteryList() throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Mastery getDataMastery(Region region, int id, String locale, String version, MasteryData masteryData) throws RiotApiException { + + return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, locale, version, masteryData); + } + + /** + * + */ + public Mastery getDataMastery(int id, String locale, String version, MasteryData masteryData) throws RiotApiException { + + return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, locale, version, masteryData); + } + + /** + * + */ + public Mastery getDataMastery(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Mastery getDataMastery(int id) throws RiotApiException { + + return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(Region region, String locale, String version, boolean dataById, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), locale, version, dataById, spellData); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(String locale, String version, boolean dataById, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), locale, version, dataById, spellData); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), null, null, false, null); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList() throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), null, null, false, null); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(Region region, int id, String locale, String version, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, locale, version, spellData); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(int id, String locale, String version, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, locale, version, spellData); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(int id) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public List getDataVersions(Region region) throws RiotApiException { + + return StaticDataMethod.getDataVersions(region.getName(), getKey()); + } + + /** + * + */ + public List getDataVersions() throws RiotApiException { + + return StaticDataMethod.getDataVersions(getRegion(), getKey()); + } + + /** + * + */ + public List getDataLanguages(Region region) throws RiotApiException { + + return StaticDataMethod.getDataLanguages(region.getName(), getKey()); + } + + /** + * + */ + public List getDataLanguages() throws RiotApiException { + + return StaticDataMethod.getDataLanguages(getRegion(), getKey()); + } + + /** + * + */ + public List getShards() throws RiotApiException { + + return StatusMethod.getShards(); + } + + /** + * + */ + public ShardStatus getShardStatus(Region region) throws RiotApiException { + + return StatusMethod.getShardStatus(region.getName()); + } + + /** + * + */ + public ShardStatus getShardStatus() throws RiotApiException { + + return StatusMethod.getShardStatus(getRegion()); + } + + /** + * + */ + public GameMapList getDataGameMapList(Region region, String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(region.getName(), getKey(), locale, version); + } + + /** + * + */ + public GameMapList getDataGameMapList(String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(getRegion(), getKey(), locale, version); + } + + /** + * + */ + public GameMapList getDataGameMapList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(region.getName(), getKey(), null, null); + } + + /** + * + */ + public GameMapList getDataGameMapList() throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(getRegion(), getKey(), null, null); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(Region region, String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(region.getName(), getKey(), locale, version); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(getRegion(), getKey(), locale, version); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(Region region) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(region.getName(), getKey(), null, null); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings() throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(getRegion(), getKey(), null, null); + } + + /** + * + */ + public FeaturedGames getFeaturedGames(Region region) throws RiotApiException { + + return FeaturedGamesMethod.getFeaturedGames(region.getName(), getKey()); + } + + /** + * + */ + public FeaturedGames getFeaturedGames() throws RiotApiException { + + return FeaturedGamesMethod.getFeaturedGames(getRegion(), getKey()); + } + + /** + * + */ + public CurrentGameInfo getCurrentGameInfo(PlatformId platformId, long summonerId) throws RiotApiException { + + return CurrentGameMethod.getCurrentGameInfo(platformId, getKey(), summonerId); + } + + /** + * Get the currently set season + * + * @return The currently set season + */ + public String getSeason() { + if(season == null){ + return null; + } + return season.getName(); + } + + /** + * Get the currently set API key + * + * @return The currently set API key + */ + public String getKey() { + return key; + } + + /** + * Get the currently set region + * + * @return The currently set region + * @throws + */ + public String getRegion() { + return region.getName(); + } + + /** + * Set the season + * + * @param season The season to set + */ + public void setSeason(Season season) { + this.season = season; + } + + /** + * Set the API key + * + * @param key The API key to set + */ + public void setKey(String key) { + this.key = key; + } + + /** + * Set the region + * + * @param region The region to set + */ + public void setRegion(Region region) { + this.region = region; + setEndpoint(); + } + + /** + * Get the base URL for all API requests + * + * @return The base URL for all API requests + */ + public String getEndpoint() { + return endpoint; + } + + private void setEndpoint() { + this.endpoint = region.getEndpoint(); + } + + public RiotApi clone() { + return new RiotApi(this.key, this.region); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `getDataRune(...)` at line 1473. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Rune RiotApi.getDataRune(Region,int) + +### Procedure Id: +main.java.riotapi.RiotApi.getDataRune(constant.Region,int):dto.Static.Rune.0d042e63f7b0cf5f529432257971e628 + +### File: +src/main/java/riotapi/RiotApi.java + +### Key: +RiotApi.java|getDataRune|NULL_DEREFERENCE + +### Node Key: +71bbd039293bbda847a7c7191bb8b301 + +### Hash: +2545d2461ab658588eed7737b20b31fc + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8361/instruction.md b/inferredbugs-8361/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b41d54ee0633950ff042cdfdd0b9306e80cde200 --- /dev/null +++ b/inferredbugs-8361/instruction.md @@ -0,0 +1,148 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riot-api-java +**Bug ID:** 29 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2016 Taylor Caldwell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.rithms.test; + +import static org.junit.Assert.assertEquals; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import net.rithms.riot.api.RiotApiException; +import net.rithms.util.Convert; + +/** + * Tests all the utility features provided by the classes in the package {@code net.rithms.util}. + */ +public class UtilTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testLongToString() throws RiotApiException { + // Valid Usage + assertEquals("1", Convert.longToString(1)); + assertEquals("1,2,3", Convert.longToString(1, 2, 3)); + // NullPointerException + thrown.expect(NullPointerException.class); + Convert.longToString(null); + } + + @Test + public void testNormalizeSummonerName() throws RiotApiException { + // Valid Usage + assertEquals("abc", Convert.normalizeSummonerName("A b C")); + // NullPointerException + thrown.expect(NullPointerException.class); + Convert.normalizeSummonerName(null); + } + + @Test + public void testNormalizeSummonerNames() throws RiotApiException { + // Valid Usage + String[] s = Convert.normalizeSummonerNames("ab c", "D E F"); + assertEquals("abc", s[0]); + assertEquals("def", s[1]); + // NullPointerException + thrown.expect(NullPointerException.class); + Convert.normalizeSummonerNames((String[]) null); + } + + @Test + public void testJoinString() throws RiotApiException { + // Valid Usage + assertEquals("abc", Convert.joinString(",", "abc")); + assertEquals("abc,def,ghi", Convert.joinString(",", "abc", "def", "ghi")); + // NullPointerException + thrown.expect(NullPointerException.class); + Convert.joinString(null, (CharSequence[]) null); + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `joinString(...)` at line 73. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void UtilTest.testJoinString() + +### Procedure Id: +net.rithms.test.UtilTest.testJoinString():void.1aee850439c4ed9210bc75f39bd8c3a8 + +### File: +src/test/java/net/rithms/test/UtilTest.java + +### Key: +UtilTest.java|testJoinString|NULL_DEREFERENCE + +### Node Key: +3922f2e7d938afbbdd7d21ea17c4b644 + +### Hash: +3c6ad7a969c57222a804d74cb45822a6 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8366/instruction.md b/inferredbugs-8366/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7541b4cff9b235d2f9b2dbb78e8ea37ba98c4cc5 --- /dev/null +++ b/inferredbugs-8366/instruction.md @@ -0,0 +1,1906 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riot-api-java +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package main.java.riotapi; + +/** + * Riot Games API Java Library + * riot-api-java + * by Taylor Caldwell - @rithms + * http://rithms.im + */ + +/* + * Copyright 2014 Taylor Caldwell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.util.List; +import java.util.Map; + +import constant.PlatformId; +import constant.QueueType; +import constant.Region; +import constant.Season; +import constant.staticdata.ChampData; +import constant.staticdata.ItemData; +import constant.staticdata.ItemListData; +import constant.staticdata.MasteryData; +import constant.staticdata.MasteryListData; +import constant.staticdata.RuneData; +import constant.staticdata.RuneListData; +import constant.staticdata.SpellData; +import dto.Champion.*; +import dto.CurrentGame.CurrentGameInfo; +import dto.FeaturedGames.FeaturedGames; +import dto.Game.RecentGames; +import dto.League.League; +import dto.Match.MatchDetail; +import dto.MatchHistory.PlayerHistory; +import dto.Team.Team; +import dto.Static.ChampionList; +import dto.Static.GameMapList; +import dto.Static.Item; +import dto.Static.ItemList; +import dto.Static.LanguageStrings; +import dto.Static.Mastery; +import dto.Static.MasteryList; +import dto.Static.Realm; +import dto.Static.Rune; +import dto.Static.RuneList; +import dto.Static.SummonerSpell; +import dto.Static.SummonerSpellList; +import dto.Stats.PlayerStatsSummaryList; +import dto.Stats.RankedStats; +import dto.Status.Shard; +import dto.Status.ShardStatus; +import dto.Summoner.MasteryPages; +import dto.Summoner.RunePages; +import dto.Summoner.Summoner; +import method.*; + +public class RiotApi { + + /** + * The base URL for all API requests + */ + private String endpoint = Region.GLOBAL.getEndpoint(); + + private Region region = Region.NA; // North American region default + private Season season = null; + private String key; + + public RiotApi() { + } + + public RiotApi(String key) { + this.setKey(key); + } + + public RiotApi(String key, Region region) { + this.setKey(key); + this.setRegion(region); + } + + /** + * Get all the champions for a set region + * + * @return A list of all the champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions() throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey()); + } + + /** + * Get all the champions for a given region + * + * @param region The desired region + * @return A list of all the champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(Region region) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey()); + } + + /** + * Get all the champions for a set region + * + * @param freeToPlay Only free to play + * @return A list of all the free to play champions for the set region when + * freeToPlay is true A list of all the champions for the set region when + * freeToPlay is false + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(boolean freeToPlay) throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey(), freeToPlay); + } + + /** + * Get all champions for a given region + * + * @param region The desired region + * @param freeToPlay Only free to play + * @return A list of all the free to play champions for the given region + * when freeToPlay is true A list of all the champions for the given region + * when freeToPlay is false + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(Region region, boolean freeToPlay) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey(), freeToPlay); + } + + /** + * Get all free to play champions for a given region + * + * @param region The desired region + * @return A list of all the free to play champions for the given region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getFreeToPlayChampions(Region region) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey(), true); + } + + /** + * Get all free to play champions for a set region + * + * @return A list of all the free to play champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getFreeToPlayChampions() throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey(), true); + } + + /** + * Get a champion by id for a given region + * + * @param region The desired region + * @param champId The ID of the desired champion + * @return The champion of the given ID + * @see ChampionList + * @throws RiotApiException + */ + public Champion getChampionById(Region region, int champId) throws RiotApiException { + + return ChampionMethod.getChampionById(region.getEndpoint(), region.getName(), getKey(), champId); + } + + /** + * Get a champion by id for a set region + * + * @param champId The ID of the desired champion + * @return The champion of the given ID + * @see ChampionList + * @throws RiotApiException + */ + public Champion getChampionById(int champId) throws RiotApiException { + + return ChampionMethod.getChampionById(getEndpoint(), getRegion(), getKey(), champId); + } + + /** + * Get recent games for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return Recent games of the given summoner + * @see RecentGames + * @throws RiotApiException + */ + public RecentGames getRecentGames(Region region, long summonerId) throws RiotApiException { + + return GameMethod.getRecentGames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get recent games for a given summoner + * + * @param summonerId The ID of the desired summoner + * @return Recent games of the given summoner + * @see RecentGames + * @throws RiotApiException + */ + public RecentGames getRecentGames(long summonerId) throws RiotApiException { + + return GameMethod.getRecentGames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(Region region, long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(Region region, long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(Region region, String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(String summonerIds) throws RiotApiException { + return LeagueMethod.getLeagueBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(Region region, String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(Region region, long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(Region region, long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(Region region, String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(Region region, String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @throws RiotApiException + */ + public League getChallengerLeagues(Region region) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(region.getEndpoint(), region.getName(), getKey()); + } + + /** + * + * @throws RiotApiException + */ + public League getChallengerLeagues() throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(getEndpoint(), getRegion(), getKey()); + } + + /** + * + * @param region + * @param queueType + * @throws RiotApiException + */ + public League getChallengerLeagues(Region region, QueueType queueType) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(region.getEndpoint(), region.getName(), getKey(), queueType); + } + + /** + * + * @param queueType + * @throws RiotApiException + * @return League + */ + public League getChallengerLeagues(QueueType queueType) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(getEndpoint(), getRegion(), getKey(), queueType); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Region region, Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(region.getEndpoint(), region.getName(), season.getName(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(getEndpoint(), getRegion(), season.getName(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Region region, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(region.getEndpoint(), region.getName(), getSeason(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param summonerId The ID of the desired summoner + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(getEndpoint(), getRegion(), getSeason(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Region region, Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(region.getEndpoint(), region.getName(), season.getName(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(getEndpoint(), getRegion(), season.getName(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Region region, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(region.getEndpoint(), region.getName(), getSeason(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param summonerId The ID of the desired summoner + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(getEndpoint(), getRegion(), getSeason(), getKey(), summonerId); + } + + /** + * Get the mastery pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(String summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(String summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerNames The names of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersByName(Region region, String summonerNames) throws RiotApiException { + + return SummonerMethod.getSummonersByName(region.getEndpoint(), region.getName(), getKey(), summonerNames); + } + + /** + * Get summoners by names + * + * @param summonerNames The names of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersByName(String summonerNames) throws RiotApiException { + + return SummonerMethod.getSummonersByName(getEndpoint(), getRegion(), getKey(), summonerNames); + } + + /** + * Get summoner by name + * + * @param region The desired region + * @param summonerName The name of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerByName(Region region, String summonerName) throws RiotApiException { + + return SummonerMethod.getSummonersByName(region.getEndpoint(), region.getName(), getKey(), summonerName); + } + + /** + * Get summoner by name + * + * @param summonerName The name of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerByName(String summonerName) throws RiotApiException { + + return SummonerMethod.getSummonersByName(getEndpoint(), getRegion(), getKey(), summonerName); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(Region region, long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(Region region, String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerIds A comma separated list of IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param summonerIds A comma separated list of IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerId The IDs of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(Region region, long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param summonerId The IDs of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(Region region, String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param summonerId The ID of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get teams by summonerIDs + * + * @param region The desired region + * @param summonerIds A list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(Region region, long... summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param summonerIds A list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(long... summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param region The desired region + * @param summonerIds Comma-separated list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(Region region, String summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param summonerIds Comma-separated list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(String summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get match by ID + * + * @param region The desired region + * @param matchId The ID of the match + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(Region region, long matchId) throws RiotApiException { + + return MatchMethod.getMatch(region.getEndpoint(), region.getName(), getKey(), matchId); + } + + /** + * Get match by ID + * + * @param matchId The ID of the match + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(long matchId) throws RiotApiException { + + return MatchMethod.getMatch(getEndpoint(), getRegion(), getKey(), matchId); + } + + /** + * Get match by ID + * + * @param region The desired region + * @param matchId The ID of the match + * @param includeTimeline Flag indicating whether or not to include match timeline data + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(Region region, long matchId, boolean includeTimeline) throws RiotApiException { + + return MatchMethod.getMatch(region.getEndpoint(), region.getName(), getKey(), matchId, includeTimeline); + } + + /** + * Get match by ID + * + * @param matchId The ID of the match + * @param includeTimeline Flag indicating whether or not to include match timeline data + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(long matchId, boolean includeTimeline) throws RiotApiException { + + return MatchMethod.getMatch(getEndpoint(), getRegion(), getKey(), matchId, includeTimeline); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, -1, -1); + } + + /** + * + */ + public ChampionList getDataChampionList(Region region, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(region.getName(), getKey(), locale, version, dataById, champData); + } + + /** + * + */ + public ChampionList getDataChampionList(String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(getRegion(), getKey(), locale, version, dataById, champData); + } + + /** + * + */ + public ChampionList getDataChampionList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(region.getName(), getKey(), null, null, false, null); + } + + /** + * + */ + public ChampionList getDataChampionList() throws RiotApiException { + + return StaticDataMethod.getDataChampionList(getRegion(), getKey(), null, null, false, null); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(Region region, int id, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, locale, version, dataById, champData); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(int id, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, locale, version, dataById, champData); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, null, null, false, null); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(int id) throws RiotApiException { + + return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, null, null, false, null); + } + + /** + * + */ + public ItemList getDataItemList(Region region, String locale, String version, ItemListData itemListData) throws RiotApiException { + + return StaticDataMethod.getDataItemList(region.getName(), getKey(), locale, version, itemListData); + } + + /** + * + */ + public ItemList getDataItemList(String locale, String version, ItemListData itemListData) throws RiotApiException { + + return StaticDataMethod.getDataItemList(getRegion(), getKey(), locale, version, itemListData); + } + + /** + * + */ + public ItemList getDataItemList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataItemList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public ItemList getDataItemList() throws RiotApiException { + + return StaticDataMethod.getDataItemList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Item getDataItem(Region region, int id, String locale, String version, ItemData itemData) throws RiotApiException { + + return StaticDataMethod.getDataItem(region.getName(), getKey(), id, locale, version, itemData); + } + + /** + * + */ + public Item getDataItem(int id, String locale, String version, ItemData itemData) throws RiotApiException { + + return StaticDataMethod.getDataItem(getRegion(), getKey(), id, locale, version, itemData); + } + + /** + * + */ + public Item getDataItem(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataItem(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Item getDataItem(int id) throws RiotApiException { + + return StaticDataMethod.getDataItem(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public Realm getDataRealm(Region region) throws RiotApiException { + + return StaticDataMethod.getDataRealm(region.getName(), getKey()); + } + + /** + * + */ + public Realm getDataRealm() throws RiotApiException { + + return StaticDataMethod.getDataRealm(getRegion(), getKey()); + } + + /** + * + */ + public RuneList getDataRuneList(Region region, String locale, String version, RuneListData runeListData) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(region.getName(), getKey(), locale, version, runeListData); + } + + /** + * + */ + public RuneList getDataRuneList(String locale, String version, RuneListData runeListData) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(getRegion(), getKey(), locale, version, runeListData); + } + + /** + * + */ + public RuneList getDataRuneList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public RuneList getDataRuneList() throws RiotApiException { + + return StaticDataMethod.getDataRuneList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Rune getDataRune(Region region, int id, String locale, String version, RuneData runeData) throws RiotApiException { + + return StaticDataMethod.getDataRune(region.getName(), getKey(), id, locale, version, runeData); + } + + /** + * + */ + public Rune getDataRune(int id, String locale, String version, RuneData runeData) throws RiotApiException { + + return StaticDataMethod.getDataRune(getRegion(), getKey(), id, locale, version, runeData); + } + + /** + * + */ + public Rune getDataRune(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataRune(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Rune getDataRune(int id) throws RiotApiException { + + return StaticDataMethod.getDataRune(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public MasteryList getDataMasteryList(Region region, String locale, String version, MasteryListData masteryListData) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), locale, version, masteryListData); + } + + /** + * + */ + public MasteryList getDataMasteryList(String locale, String version, MasteryListData masteryListData) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), locale, version, masteryListData); + } + + /** + * + */ + public MasteryList getDataMasteryList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public MasteryList getDataMasteryList() throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Mastery getDataMastery(Region region, int id, String locale, String version, MasteryData masteryData) throws RiotApiException { + + return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, locale, version, masteryData); + } + + /** + * + */ + public Mastery getDataMastery(int id, String locale, String version, MasteryData masteryData) throws RiotApiException { + + return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, locale, version, masteryData); + } + + /** + * + */ + public Mastery getDataMastery(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Mastery getDataMastery(int id) throws RiotApiException { + + return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(Region region, String locale, String version, boolean dataById, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), locale, version, dataById, spellData); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(String locale, String version, boolean dataById, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), locale, version, dataById, spellData); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), null, null, false, null); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList() throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), null, null, false, null); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(Region region, int id, String locale, String version, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, locale, version, spellData); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(int id, String locale, String version, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, locale, version, spellData); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(int id) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public List getDataVersions(Region region) throws RiotApiException { + + return StaticDataMethod.getDataVersions(region.getName(), getKey()); + } + + /** + * + */ + public List getDataVersions() throws RiotApiException { + + return StaticDataMethod.getDataVersions(getRegion(), getKey()); + } + + /** + * + */ + public List getDataLanguages(Region region) throws RiotApiException { + + return StaticDataMethod.getDataLanguages(region.getName(), getKey()); + } + + /** + * + */ + public List getDataLanguages() throws RiotApiException { + + return StaticDataMethod.getDataLanguages(getRegion(), getKey()); + } + + /** + * + */ + public List getShards() throws RiotApiException { + + return StatusMethod.getShards(); + } + + /** + * + */ + public ShardStatus getShardStatus(Region region) throws RiotApiException { + + return StatusMethod.getShardStatus(region.getName()); + } + + /** + * + */ + public ShardStatus getShardStatus() throws RiotApiException { + + return StatusMethod.getShardStatus(getRegion()); + } + + /** + * + */ + public GameMapList getDataGameMapList(Region region, String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(region.getName(), getKey(), locale, version); + } + + /** + * + */ + public GameMapList getDataGameMapList(String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(getRegion(), getKey(), locale, version); + } + + /** + * + */ + public GameMapList getDataGameMapList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(region.getName(), getKey(), null, null); + } + + /** + * + */ + public GameMapList getDataGameMapList() throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(getRegion(), getKey(), null, null); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(Region region, String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(region.getName(), getKey(), locale, version); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(getRegion(), getKey(), locale, version); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(Region region) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(region.getName(), getKey(), null, null); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings() throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(getRegion(), getKey(), null, null); + } + + /** + * + */ + public FeaturedGames getFeaturedGames(Region region) throws RiotApiException { + + return FeaturedGamesMethod.getFeaturedGames(region.getName(), getKey()); + } + + /** + * + */ + public FeaturedGames getFeaturedGames() throws RiotApiException { + + return FeaturedGamesMethod.getFeaturedGames(getRegion(), getKey()); + } + + /** + * + */ + public CurrentGameInfo getCurrentGameInfo(PlatformId platformId, long summonerId) throws RiotApiException { + + return CurrentGameMethod.getCurrentGameInfo(platformId, getKey(), summonerId); + } + + /** + * Get the currently set season + * + * @return The currently set season + */ + public String getSeason() { + if(season == null){ + return null; + } + return season.getName(); + } + + /** + * Get the currently set API key + * + * @return The currently set API key + */ + public String getKey() { + return key; + } + + /** + * Get the currently set region + * + * @return The currently set region + * @throws + */ + public String getRegion() { + return region.getName(); + } + + /** + * Set the season + * + * @param season The season to set + */ + public void setSeason(Season season) { + this.season = season; + } + + /** + * Set the API key + * + * @param key The API key to set + */ + public void setKey(String key) { + this.key = key; + } + + /** + * Set the region + * + * @param region The region to set + */ + public void setRegion(Region region) { + this.region = region; + setEndpoint(); + } + + /** + * Get the base URL for all API requests + * + * @return The base URL for all API requests + */ + public String getEndpoint() { + return endpoint; + } + + private void setEndpoint() { + this.endpoint = region.getEndpoint(); + } + + public RiotApi clone() { + return new RiotApi(this.key, this.region); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `getDataChampionList(...)` at line 1297. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +ChampionList RiotApi.getDataChampionList(Region) + +### Procedure Id: +main.java.riotapi.RiotApi.getDataChampionList(constant.Region):dto.Static.ChampionList.f782223f0f684e9e63d89df9db3185ee + +### File: +src/main/java/riotapi/RiotApi.java + +### Key: +RiotApi.java|getDataChampionList|NULL_DEREFERENCE + +### Node Key: +d46e1684de2ca326ba231ad8a5b48143 + +### Hash: +d0a122eb6ecd94f839cb665ac9962e42 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8368/instruction.md b/inferredbugs-8368/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..88b6174e5166e03c5d913209ea26e8a4898e8b1b --- /dev/null +++ b/inferredbugs-8368/instruction.md @@ -0,0 +1,1906 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riot-api-java +**Bug ID:** 19 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package main.java.riotapi; + +/** + * Riot Games API Java Library + * riot-api-java + * by Taylor Caldwell - @rithms + * http://rithms.im + */ + +/* + * Copyright 2014 Taylor Caldwell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.util.List; +import java.util.Map; + +import constant.PlatformId; +import constant.QueueType; +import constant.Region; +import constant.Season; +import constant.staticdata.ChampData; +import constant.staticdata.ItemData; +import constant.staticdata.ItemListData; +import constant.staticdata.MasteryData; +import constant.staticdata.MasteryListData; +import constant.staticdata.RuneData; +import constant.staticdata.RuneListData; +import constant.staticdata.SpellData; +import dto.Champion.*; +import dto.CurrentGame.CurrentGameInfo; +import dto.FeaturedGames.FeaturedGames; +import dto.Game.RecentGames; +import dto.League.League; +import dto.Match.MatchDetail; +import dto.MatchHistory.PlayerHistory; +import dto.Team.Team; +import dto.Static.ChampionList; +import dto.Static.GameMapList; +import dto.Static.Item; +import dto.Static.ItemList; +import dto.Static.LanguageStrings; +import dto.Static.Mastery; +import dto.Static.MasteryList; +import dto.Static.Realm; +import dto.Static.Rune; +import dto.Static.RuneList; +import dto.Static.SummonerSpell; +import dto.Static.SummonerSpellList; +import dto.Stats.PlayerStatsSummaryList; +import dto.Stats.RankedStats; +import dto.Status.Shard; +import dto.Status.ShardStatus; +import dto.Summoner.MasteryPages; +import dto.Summoner.RunePages; +import dto.Summoner.Summoner; +import method.*; + +public class RiotApi { + + /** + * The base URL for all API requests + */ + private String endpoint = Region.GLOBAL.getEndpoint(); + + private Region region = Region.NA; // North American region default + private Season season = null; + private String key; + + public RiotApi() { + } + + public RiotApi(String key) { + this.setKey(key); + } + + public RiotApi(String key, Region region) { + this.setKey(key); + this.setRegion(region); + } + + /** + * Get all the champions for a set region + * + * @return A list of all the champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions() throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey()); + } + + /** + * Get all the champions for a given region + * + * @param region The desired region + * @return A list of all the champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(Region region) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey()); + } + + /** + * Get all the champions for a set region + * + * @param freeToPlay Only free to play + * @return A list of all the free to play champions for the set region when + * freeToPlay is true A list of all the champions for the set region when + * freeToPlay is false + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(boolean freeToPlay) throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey(), freeToPlay); + } + + /** + * Get all champions for a given region + * + * @param region The desired region + * @param freeToPlay Only free to play + * @return A list of all the free to play champions for the given region + * when freeToPlay is true A list of all the champions for the given region + * when freeToPlay is false + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(Region region, boolean freeToPlay) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey(), freeToPlay); + } + + /** + * Get all free to play champions for a given region + * + * @param region The desired region + * @return A list of all the free to play champions for the given region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getFreeToPlayChampions(Region region) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey(), true); + } + + /** + * Get all free to play champions for a set region + * + * @return A list of all the free to play champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getFreeToPlayChampions() throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey(), true); + } + + /** + * Get a champion by id for a given region + * + * @param region The desired region + * @param champId The ID of the desired champion + * @return The champion of the given ID + * @see ChampionList + * @throws RiotApiException + */ + public Champion getChampionById(Region region, int champId) throws RiotApiException { + + return ChampionMethod.getChampionById(region.getEndpoint(), region.getName(), getKey(), champId); + } + + /** + * Get a champion by id for a set region + * + * @param champId The ID of the desired champion + * @return The champion of the given ID + * @see ChampionList + * @throws RiotApiException + */ + public Champion getChampionById(int champId) throws RiotApiException { + + return ChampionMethod.getChampionById(getEndpoint(), getRegion(), getKey(), champId); + } + + /** + * Get recent games for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return Recent games of the given summoner + * @see RecentGames + * @throws RiotApiException + */ + public RecentGames getRecentGames(Region region, long summonerId) throws RiotApiException { + + return GameMethod.getRecentGames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get recent games for a given summoner + * + * @param summonerId The ID of the desired summoner + * @return Recent games of the given summoner + * @see RecentGames + * @throws RiotApiException + */ + public RecentGames getRecentGames(long summonerId) throws RiotApiException { + + return GameMethod.getRecentGames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(Region region, long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(Region region, long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(Region region, String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(String summonerIds) throws RiotApiException { + return LeagueMethod.getLeagueBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(Region region, String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(Region region, long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(Region region, long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(Region region, String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(Region region, String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @throws RiotApiException + */ + public League getChallengerLeagues(Region region) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(region.getEndpoint(), region.getName(), getKey()); + } + + /** + * + * @throws RiotApiException + */ + public League getChallengerLeagues() throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(getEndpoint(), getRegion(), getKey()); + } + + /** + * + * @param region + * @param queueType + * @throws RiotApiException + */ + public League getChallengerLeagues(Region region, QueueType queueType) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(region.getEndpoint(), region.getName(), getKey(), queueType); + } + + /** + * + * @param queueType + * @throws RiotApiException + * @return League + */ + public League getChallengerLeagues(QueueType queueType) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(getEndpoint(), getRegion(), getKey(), queueType); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Region region, Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(region.getEndpoint(), region.getName(), season.getName(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(getEndpoint(), getRegion(), season.getName(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Region region, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(region.getEndpoint(), region.getName(), getSeason(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param summonerId The ID of the desired summoner + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(getEndpoint(), getRegion(), getSeason(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Region region, Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(region.getEndpoint(), region.getName(), season.getName(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(getEndpoint(), getRegion(), season.getName(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Region region, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(region.getEndpoint(), region.getName(), getSeason(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param summonerId The ID of the desired summoner + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(getEndpoint(), getRegion(), getSeason(), getKey(), summonerId); + } + + /** + * Get the mastery pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(String summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(String summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerNames The names of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersByName(Region region, String summonerNames) throws RiotApiException { + + return SummonerMethod.getSummonersByName(region.getEndpoint(), region.getName(), getKey(), summonerNames); + } + + /** + * Get summoners by names + * + * @param summonerNames The names of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersByName(String summonerNames) throws RiotApiException { + + return SummonerMethod.getSummonersByName(getEndpoint(), getRegion(), getKey(), summonerNames); + } + + /** + * Get summoner by name + * + * @param region The desired region + * @param summonerName The name of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerByName(Region region, String summonerName) throws RiotApiException { + + return SummonerMethod.getSummonersByName(region.getEndpoint(), region.getName(), getKey(), summonerName); + } + + /** + * Get summoner by name + * + * @param summonerName The name of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerByName(String summonerName) throws RiotApiException { + + return SummonerMethod.getSummonersByName(getEndpoint(), getRegion(), getKey(), summonerName); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(Region region, long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(Region region, String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerIds A comma separated list of IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param summonerIds A comma separated list of IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerId The IDs of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(Region region, long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param summonerId The IDs of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(Region region, String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param summonerId The ID of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get teams by summonerIDs + * + * @param region The desired region + * @param summonerIds A list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(Region region, long... summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param summonerIds A list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(long... summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param region The desired region + * @param summonerIds Comma-separated list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(Region region, String summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param summonerIds Comma-separated list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(String summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get match by ID + * + * @param region The desired region + * @param matchId The ID of the match + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(Region region, long matchId) throws RiotApiException { + + return MatchMethod.getMatch(region.getEndpoint(), region.getName(), getKey(), matchId); + } + + /** + * Get match by ID + * + * @param matchId The ID of the match + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(long matchId) throws RiotApiException { + + return MatchMethod.getMatch(getEndpoint(), getRegion(), getKey(), matchId); + } + + /** + * Get match by ID + * + * @param region The desired region + * @param matchId The ID of the match + * @param includeTimeline Flag indicating whether or not to include match timeline data + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(Region region, long matchId, boolean includeTimeline) throws RiotApiException { + + return MatchMethod.getMatch(region.getEndpoint(), region.getName(), getKey(), matchId, includeTimeline); + } + + /** + * Get match by ID + * + * @param matchId The ID of the match + * @param includeTimeline Flag indicating whether or not to include match timeline data + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(long matchId, boolean includeTimeline) throws RiotApiException { + + return MatchMethod.getMatch(getEndpoint(), getRegion(), getKey(), matchId, includeTimeline); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, -1, -1); + } + + /** + * + */ + public ChampionList getDataChampionList(Region region, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(region.getName(), getKey(), locale, version, dataById, champData); + } + + /** + * + */ + public ChampionList getDataChampionList(String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(getRegion(), getKey(), locale, version, dataById, champData); + } + + /** + * + */ + public ChampionList getDataChampionList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(region.getName(), getKey(), null, null, false, null); + } + + /** + * + */ + public ChampionList getDataChampionList() throws RiotApiException { + + return StaticDataMethod.getDataChampionList(getRegion(), getKey(), null, null, false, null); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(Region region, int id, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, locale, version, dataById, champData); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(int id, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, locale, version, dataById, champData); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, null, null, false, null); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(int id) throws RiotApiException { + + return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, null, null, false, null); + } + + /** + * + */ + public ItemList getDataItemList(Region region, String locale, String version, ItemListData itemListData) throws RiotApiException { + + return StaticDataMethod.getDataItemList(region.getName(), getKey(), locale, version, itemListData); + } + + /** + * + */ + public ItemList getDataItemList(String locale, String version, ItemListData itemListData) throws RiotApiException { + + return StaticDataMethod.getDataItemList(getRegion(), getKey(), locale, version, itemListData); + } + + /** + * + */ + public ItemList getDataItemList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataItemList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public ItemList getDataItemList() throws RiotApiException { + + return StaticDataMethod.getDataItemList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Item getDataItem(Region region, int id, String locale, String version, ItemData itemData) throws RiotApiException { + + return StaticDataMethod.getDataItem(region.getName(), getKey(), id, locale, version, itemData); + } + + /** + * + */ + public Item getDataItem(int id, String locale, String version, ItemData itemData) throws RiotApiException { + + return StaticDataMethod.getDataItem(getRegion(), getKey(), id, locale, version, itemData); + } + + /** + * + */ + public Item getDataItem(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataItem(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Item getDataItem(int id) throws RiotApiException { + + return StaticDataMethod.getDataItem(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public Realm getDataRealm(Region region) throws RiotApiException { + + return StaticDataMethod.getDataRealm(region.getName(), getKey()); + } + + /** + * + */ + public Realm getDataRealm() throws RiotApiException { + + return StaticDataMethod.getDataRealm(getRegion(), getKey()); + } + + /** + * + */ + public RuneList getDataRuneList(Region region, String locale, String version, RuneListData runeListData) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(region.getName(), getKey(), locale, version, runeListData); + } + + /** + * + */ + public RuneList getDataRuneList(String locale, String version, RuneListData runeListData) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(getRegion(), getKey(), locale, version, runeListData); + } + + /** + * + */ + public RuneList getDataRuneList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public RuneList getDataRuneList() throws RiotApiException { + + return StaticDataMethod.getDataRuneList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Rune getDataRune(Region region, int id, String locale, String version, RuneData runeData) throws RiotApiException { + + return StaticDataMethod.getDataRune(region.getName(), getKey(), id, locale, version, runeData); + } + + /** + * + */ + public Rune getDataRune(int id, String locale, String version, RuneData runeData) throws RiotApiException { + + return StaticDataMethod.getDataRune(getRegion(), getKey(), id, locale, version, runeData); + } + + /** + * + */ + public Rune getDataRune(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataRune(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Rune getDataRune(int id) throws RiotApiException { + + return StaticDataMethod.getDataRune(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public MasteryList getDataMasteryList(Region region, String locale, String version, MasteryListData masteryListData) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), locale, version, masteryListData); + } + + /** + * + */ + public MasteryList getDataMasteryList(String locale, String version, MasteryListData masteryListData) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), locale, version, masteryListData); + } + + /** + * + */ + public MasteryList getDataMasteryList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public MasteryList getDataMasteryList() throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Mastery getDataMastery(Region region, int id, String locale, String version, MasteryData masteryData) throws RiotApiException { + + return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, locale, version, masteryData); + } + + /** + * + */ + public Mastery getDataMastery(int id, String locale, String version, MasteryData masteryData) throws RiotApiException { + + return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, locale, version, masteryData); + } + + /** + * + */ + public Mastery getDataMastery(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Mastery getDataMastery(int id) throws RiotApiException { + + return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(Region region, String locale, String version, boolean dataById, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), locale, version, dataById, spellData); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(String locale, String version, boolean dataById, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), locale, version, dataById, spellData); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), null, null, false, null); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList() throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), null, null, false, null); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(Region region, int id, String locale, String version, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, locale, version, spellData); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(int id, String locale, String version, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, locale, version, spellData); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(int id) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public List getDataVersions(Region region) throws RiotApiException { + + return StaticDataMethod.getDataVersions(region.getName(), getKey()); + } + + /** + * + */ + public List getDataVersions() throws RiotApiException { + + return StaticDataMethod.getDataVersions(getRegion(), getKey()); + } + + /** + * + */ + public List getDataLanguages(Region region) throws RiotApiException { + + return StaticDataMethod.getDataLanguages(region.getName(), getKey()); + } + + /** + * + */ + public List getDataLanguages() throws RiotApiException { + + return StaticDataMethod.getDataLanguages(getRegion(), getKey()); + } + + /** + * + */ + public List getShards() throws RiotApiException { + + return StatusMethod.getShards(); + } + + /** + * + */ + public ShardStatus getShardStatus(Region region) throws RiotApiException { + + return StatusMethod.getShardStatus(region.getName()); + } + + /** + * + */ + public ShardStatus getShardStatus() throws RiotApiException { + + return StatusMethod.getShardStatus(getRegion()); + } + + /** + * + */ + public GameMapList getDataGameMapList(Region region, String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(region.getName(), getKey(), locale, version); + } + + /** + * + */ + public GameMapList getDataGameMapList(String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(getRegion(), getKey(), locale, version); + } + + /** + * + */ + public GameMapList getDataGameMapList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(region.getName(), getKey(), null, null); + } + + /** + * + */ + public GameMapList getDataGameMapList() throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(getRegion(), getKey(), null, null); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(Region region, String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(region.getName(), getKey(), locale, version); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(getRegion(), getKey(), locale, version); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(Region region) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(region.getName(), getKey(), null, null); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings() throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(getRegion(), getKey(), null, null); + } + + /** + * + */ + public FeaturedGames getFeaturedGames(Region region) throws RiotApiException { + + return FeaturedGamesMethod.getFeaturedGames(region.getName(), getKey()); + } + + /** + * + */ + public FeaturedGames getFeaturedGames() throws RiotApiException { + + return FeaturedGamesMethod.getFeaturedGames(getRegion(), getKey()); + } + + /** + * + */ + public CurrentGameInfo getCurrentGameInfo(PlatformId platformId, long summonerId) throws RiotApiException { + + return CurrentGameMethod.getCurrentGameInfo(platformId, getKey(), summonerId); + } + + /** + * Get the currently set season + * + * @return The currently set season + */ + public String getSeason() { + if(season == null){ + return null; + } + return season.getName(); + } + + /** + * Get the currently set API key + * + * @return The currently set API key + */ + public String getKey() { + return key; + } + + /** + * Get the currently set region + * + * @return The currently set region + * @throws + */ + public String getRegion() { + return region.getName(); + } + + /** + * Set the season + * + * @param season The season to set + */ + public void setSeason(Season season) { + this.season = season; + } + + /** + * Set the API key + * + * @param key The API key to set + */ + public void setKey(String key) { + this.key = key; + } + + /** + * Set the region + * + * @param region The region to set + */ + public void setRegion(Region region) { + this.region = region; + setEndpoint(); + } + + /** + * Get the base URL for all API requests + * + * @return The base URL for all API requests + */ + public String getEndpoint() { + return endpoint; + } + + private void setEndpoint() { + this.endpoint = region.getEndpoint(); + } + + public RiotApi clone() { + return new RiotApi(this.key, this.region); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `getDataSummonerSpell(...)` at line 1601. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +SummonerSpell RiotApi.getDataSummonerSpell(Region,int) + +### Procedure Id: +main.java.riotapi.RiotApi.getDataSummonerSpell(constant.Region,int):dto.Static.SummonerSpell.190808eaffec4b717377b7594ba51207 + +### File: +src/main/java/riotapi/RiotApi.java + +### Key: +RiotApi.java|getDataSummonerSpell|NULL_DEREFERENCE + +### Node Key: +71bbd039293bbda847a7c7191bb8b301 + +### Hash: +083142b1ebc3b31fdf96b3e2369526b7 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8392/instruction.md b/inferredbugs-8392/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..74eb8ca227740a6e69aefd1824c18fd3080073d7 --- /dev/null +++ b/inferredbugs-8392/instruction.md @@ -0,0 +1,142 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fim +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * This file is part of Fim - File Integrity Manager + * + * Copyright (C) 2015 Etienne Vrignaud + * + * Fim 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 of the License, or + * (at your option) any later version. + * + * Fim 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 Fim. If not, see . + */ +package org.fim.internal; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.fim.model.DuplicateResult; +import org.fim.model.FileHash; +import org.fim.model.FileState; +import org.fim.model.Parameters; +import org.fim.model.State; + +public class DuplicateFinder +{ + private final Parameters parameters; + private final List duplicatedFiles; + private final Comparator fullHashComparator; + + public DuplicateFinder(Parameters parameters) + { + this.parameters = parameters; + this.duplicatedFiles = new ArrayList<>(); + this.fullHashComparator = new FileState.HashComparator(); + } + + public DuplicateResult findDuplicates(State state) + { + DuplicateResult result = new DuplicateResult(parameters); + + List fileStates = new ArrayList<>(state.getFileStates()); + Collections.sort(fileStates, fullHashComparator); + + FileHash previousHash = new FileHash(FileState.NO_HASH, FileState.NO_HASH, FileState.NO_HASH); + for (FileState fileState : fileStates) + { + if (!previousHash.equals(fileState.getFileHash())) + { + result.addDuplicatedFiles(duplicatedFiles); + duplicatedFiles.clear(); + } + + previousHash = fileState.getFileHash(); + duplicatedFiles.add(fileState); + } + result.addDuplicatedFiles(duplicatedFiles); + + return result; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `previousHash` last assigned on line 61 could be null and is dereferenced at line 55. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +DuplicateResult DuplicateFinder.findDuplicates(State) + +### Procedure Id: +org.fim.internal.DuplicateFinder.findDuplicates(org.fim.model.State):org.fim.model.DuplicateResult.bd61d9397138f834529fb510401da569 + +### File: +src/main/java/org/fim/internal/DuplicateFinder.java + +### Key: +DuplicateFinder.java|findDuplicates|NULL_DEREFERENCE + +### Node Key: +7e9fc31bc469440d6384630f8b346526 + +### Hash: +4eb0365e7150ff107d911b63194f15ee + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8395/instruction.md b/inferredbugs-8395/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a80d482166fc94cf2f681bbf50221d336f555736 --- /dev/null +++ b/inferredbugs-8395/instruction.md @@ -0,0 +1,268 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fim +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * This file is part of Fim - File Integrity Manager + * + * Copyright (C) 2015 Etienne Vrignaud + * + * Fim 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 of the License, or + * (at your option) any later version. + * + * Fim 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 Fim. If not, see . + */ +package org.fim.internal; + +import static java.nio.file.StandardOpenOption.CREATE; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.util.List; + +import org.fim.model.FileState; +import org.fim.model.Parameters; +import org.fim.model.State; + +public class StateManager +{ + public static final String STATE_EXTENSION = ".json.gz"; + + public static final String LAST_STATE_FILE_NAME = "lastState"; + + private final Parameters parameters; + private final Charset utf8 = Charset.forName("UTF-8"); + private final File stateDir; + protected int lastStateNumber = -1; + + public StateManager(Parameters parameters) + { + this(parameters, parameters.getDefaultStateDir()); + } + + public StateManager(Parameters parameters, File stateDir) + { + this.parameters = parameters; + this.stateDir = stateDir; + } + + public void createNewState(State state) throws IOException + { + state.saveToGZipFile(getNextStateFile()); + writeLastStateNumber(); + } + + public File getNextStateFile() + { + findLastStateNumber(); + lastStateNumber++; + File statFile = getStateFile(lastStateNumber); + return statFile; + } + + public State loadLastState() throws IOException + { + findLastStateNumber(); + return loadState(lastStateNumber); + } + + public State loadState(int stateNumber) throws IOException + { + File stateFile = getStateFile(stateNumber); + if (!stateFile.exists()) + { + throw new IllegalStateException(String.format("Unable to load State file %d from directory %s", stateNumber, stateDir)); + } + + State state = new State(); + state.loadFromGZipFile(stateFile); + + // Replace by 'no_hash' accurately to be able to compare the FileState entry + switch (parameters.getHashMode()) + { + case DONT_HASH_FILES: + for (FileState fileState : state.getFileStates()) + { + fileState.getFileHash().setFirstFourKiloHash(FileState.NO_HASH); + fileState.getFileHash().setFirstMegaHash(FileState.NO_HASH); + fileState.getFileHash().setFullHash(FileState.NO_HASH); + } + break; + + case HASH_ONLY_FIRST_FOUR_KILO: + for (FileState fileState : state.getFileStates()) + { + fileState.getFileHash().setFirstMegaHash(FileState.NO_HASH); + fileState.getFileHash().setFullHash(FileState.NO_HASH); + } + break; + + case HASH_ONLY_FIRST_MEGA: + for (FileState fileState : state.getFileStates()) + { + fileState.getFileHash().setFirstFourKiloHash(FileState.NO_HASH); + fileState.getFileHash().setFullHash(FileState.NO_HASH); + } + break; + + case COMPUTE_ALL_HASH: + // Nothing to do + break; + } + + return state; + } + + /** + * @return the State file formatted like this: /state_.json.gz + */ + public File getStateFile(int stateNumber) + { + StringBuilder builder = new StringBuilder(); + builder.append("state_").append(stateNumber).append(STATE_EXTENSION); + return new File(stateDir, builder.toString()); + } + + protected void findLastStateNumber() + { + readLastStateNumber(); + if (lastStateNumber != -1) + { + return; + } + + for (int index = 1; ; index++) + { + File statFile = getStateFile(index); + if (!statFile.exists()) + { + lastStateNumber = index - 1; + return; + } + } + } + + public void readLastStateNumber() + { + lastStateNumber = -1; + + File lastStateFile = new File(stateDir, LAST_STATE_FILE_NAME); + if (lastStateFile.exists()) + { + try + { + List strings = Files.readAllLines(lastStateFile.toPath(), utf8); + if (strings.size() > 0) + { + lastStateNumber = Integer.parseInt(strings.get(0)); + } + } + catch (IOException ex) + { + ex.printStackTrace(); + } + } + } + + private void writeLastStateNumber() + { + if (lastStateNumber != -1) + { + File lastStateFile = new File(stateDir, LAST_STATE_FILE_NAME); + String content = Integer.toString(lastStateNumber); + try + { + Files.write(lastStateFile.toPath(), content.getBytes(), CREATE); + } + catch (IOException ex) + { + ex.printStackTrace(); + } + } + } + + public int getLastStateNumber() + { + return lastStateNumber; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `state.getFileStates()` could be null and is dereferenced at line 99. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +State StateManager.loadState(int) + +### Procedure Id: +org.fim.internal.StateManager.loadState(int):org.fim.model.State.814e6eef6c52f2ed5d5977dc1d6ff532 + +### File: +src/main/java/org/fim/internal/StateManager.java + +### Key: +StateManager.java|loadState|NULL_DEREFERENCE + +### Node Key: +42f56fda1ad408e362508b93a175bb0c + +### Hash: +ace2cfc5deaffe4d5af465222a8296c6 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8420/instruction.md b/inferredbugs-8420/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..977a1ebbfe1810d4a5388cc7747bd7fc399ea8d5 --- /dev/null +++ b/inferredbugs-8420/instruction.md @@ -0,0 +1,694 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** raft-java +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.wenweihu86.raft; + +import com.github.wenweihu86.raft.proto.Raft; +import com.github.wenweihu86.raft.storage.SegmentedLog; +import com.google.protobuf.ByteString; +import com.github.wenweihu86.raft.storage.Snapshot; +import com.github.wenweihu86.rpc.client.RPCCallback; +import org.apache.commons.io.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.locks.*; + +/** + * Created by wenweihu86 on 2017/5/2. + */ +public class RaftNode { + + public enum NodeState { + STATE_FOLLOWER, + STATE_CANDIDATE, + STATE_LEADER + } + + private static final Logger LOG = LoggerFactory.getLogger(RaftNode.class); + + private NodeState state = NodeState.STATE_FOLLOWER; + // 服务器最后一次知道的任期号(初始化为 0,持续递增) + private long currentTerm; + // 在当前获得选票的候选人的Id + private int votedFor; + private List entries; + // 已知的最大的已经被提交的日志条目的索引值 + private long commitIndex; + // The index of the last log entry that has been flushed to disk. + // Valid for leaders only. + private long lastSyncedIndex; + // 最后被应用到状态机的日志条目索引值(初始化为 0,持续递增) + private volatile long lastAppliedIndex; + + private List peers; + private ServerAddress localServer; + private int leaderId; // leader节点id + private SegmentedLog raftLog; + private StateMachine stateMachine; + + private Snapshot snapshot; + private long lastSnapshotIndex; + private long lastSnapshotTerm; + private boolean isSnapshoting; + private ReadWriteLock snapshotLock = new ReentrantReadWriteLock(); + + private Lock lock = new ReentrantLock(); + private Condition commitIndexCondition = lock.newCondition(); + + private ExecutorService executorService; + private ScheduledExecutorService scheduledExecutorService; + private ScheduledFuture electionScheduledFuture; + private ScheduledFuture heartbeatScheduledFuture; + + public RaftNode(int localServerId, List servers) { + raftLog = new SegmentedLog(); + snapshot = new Snapshot(); + for (ServerAddress server : servers) { + if (server.getServerId() == localServerId) { + this.localServer = server; + } else { + Peer peer = new Peer(server); + peers.add(peer); + } + } + executorService = Executors.newFixedThreadPool(peers.size() * 2); + scheduledExecutorService = Executors.newScheduledThreadPool(2); + // election timer + resetElectionTimer(); + this.currentTerm = raftLog.getMetaData().getCurrentTerm(); + this.votedFor = raftLog.getMetaData().getVotedFor(); + this.commitIndex = Math.max(snapshot.getMetaData().getLastIncludedIndex(), commitIndex); + stepDown(1); + scheduledExecutorService.schedule(new Runnable() { + @Override + public void run() { + takeSnapshot(); + } + }, RaftOption.snapshotPeriodSeconds, TimeUnit.SECONDS); + } + + public void resetElectionTimer() { + if (electionScheduledFuture != null && !electionScheduledFuture.isDone()) { + electionScheduledFuture.cancel(true); + } + electionScheduledFuture = scheduledExecutorService.schedule(new Runnable() { + @Override + public void run() { + startNewElection(); + } + }, getElectionTimeoutMs(), TimeUnit.MILLISECONDS); + } + + // 开始新的选举,对candidate有效 + public void startNewElection() { + currentTerm++; + LOG.info("Running for election in term {}", currentTerm); + state = NodeState.STATE_CANDIDATE; + leaderId = 0; + votedFor = localServer.getServerId(); + for (final Peer peer : peers) { + Future electionFuture = executorService.submit(new Runnable() { + @Override + public void run() { + requestVote(peer); + } + }); + peer.setElectionFuture(electionFuture); + } + resetElectionTimer(); + } + + public void resetHeartbeatTimer() { + if (heartbeatScheduledFuture != null && !heartbeatScheduledFuture.isDone()) { + heartbeatScheduledFuture.cancel(true); + } + heartbeatScheduledFuture = scheduledExecutorService.schedule(new Runnable() { + @Override + public void run() { + startNewHeartbeat(); + } + }, RaftOption.heartbeatPeriodMilliseconds, TimeUnit.MILLISECONDS); + } + + // 开始心跳,对leader有效 + public void startNewHeartbeat() { + LOG.info("start new heartbeat"); + for (final Peer peer : peers) { + Future heartbeatFuture = executorService.submit(new Runnable() { + @Override + public void run() { + appendEntries(peer); + } + }); + peer.setHeartbeatFuture(heartbeatFuture); + } + resetHeartbeatTimer(); + } + + public void requestVote(Peer peer) { + peer.setVoteGranted(false); + Raft.VoteRequest request = Raft.VoteRequest.newBuilder() + .setServerId(localServer.getServerId()) + .setTerm(currentTerm) + .setLastLogIndex(raftLog.getLastLogIndex()) + .setLastLogTerm(raftLog.getLastLogTerm()).build(); + peer.getRpcClient().asyncCall( + "RaftConsensusService.requestVote", request, + new VoteResponseCallback(peer)); + } + + private class VoteResponseCallback implements RPCCallback { + private Peer peer; + + public VoteResponseCallback(Peer peer) { + this.peer = peer; + } + + @Override + public void success(Raft.VoteResponse response) { + if (response.getTerm() > currentTerm) { + LOG.info("Received RequestVote response from server {} " + + "in term {} (this server's term was {})", + peer.getServerAddress().getServerId(), + response.getTerm(), + currentTerm); + stepDown(response.getTerm()); + } else { + if (response.getGranted()) { + LOG.info("Got vote from server {} for term {}", + peer.getServerAddress().getServerId(), currentTerm); + int voteGrantedNum = 1; + for (Peer peer1 : peers) { + if (peer1.isVoteGranted()) { + voteGrantedNum += 1; + } + } + if (voteGrantedNum > (peers.size() + 1) / 2) { + LOG.info("Got majority vote"); + becomeLeader(); + } + } else { + LOG.info("Vote denied by server {} for term {}", + peer.getServerAddress().getServerId(), currentTerm); + } + } + } + + @Override + public void fail(Throwable e) { + LOG.warn("requestVote with peer[{}:{}] failed", + peer.getServerAddress().getHost(), + peer.getServerAddress().getPort()); + } + + } + + public void appendEntries(Peer peer) { + long startLogIndex = raftLog.getStartLogIndex(); + if (peer.getNextIndex() < startLogIndex) { + this.installSnapshot(peer); + return; + } + + long lastLogIndex = this.raftLog.getLastLogIndex(); + long prevLogIndex = peer.getNextIndex() - 1; + long prevLogTerm = 0; + if (prevLogIndex >= startLogIndex) { + prevLogTerm = raftLog.getEntry(prevLogIndex).getTerm(); + } else if (prevLogIndex == 0) { + prevLogTerm = 0; + } else if (prevLogIndex == lastSnapshotIndex) { + prevLogTerm = lastSnapshotTerm; + } else { + installSnapshot(peer); + return; + } + + Raft.AppendEntriesRequest.Builder requestBuilder = Raft.AppendEntriesRequest.newBuilder(); + requestBuilder.setServerId(localServer.getServerId()); + requestBuilder.setTerm(currentTerm); + requestBuilder.setPrevLogTerm(prevLogTerm); + requestBuilder.setPrevLogIndex(prevLogIndex); + long numEntries = packEntries(peer.getNextIndex(), requestBuilder); + requestBuilder.setCommitIndex(Math.min(commitIndex, prevLogIndex + numEntries)); + Raft.AppendEntriesRequest request = requestBuilder.build(); + + Raft.AppendEntriesResponse response = peer.getRaftConsensusService().appendEntries(request); + if (response == null) { + LOG.warn("appendEntries with peer[{}:{}] failed", + peer.getServerAddress().getHost(), + peer.getServerAddress().getPort()); + return; + } + if (response.getTerm() > currentTerm) { + LOG.info("Received AppendEntries response from server {} " + + "in term {} (this server's term was {})", + peer.getServerAddress().getServerId(), + response.getTerm(), currentTerm); + stepDown(response.getTerm()); + } else { + if (response.getSuccess()) { + peer.setMatchIndex(prevLogIndex + numEntries); + advanceCommitIndex(); + peer.setNextIndex(peer.getMatchIndex() + 1); + } else { + if (peer.getNextIndex() > 1) { + peer.setNextIndex(peer.getNextIndex() - 1); + } + if (response.getLastLogIndex() != 0 + && peer.getNextIndex() > response.getLastLogIndex() + 1) { + peer.setNextIndex(response.getLastLogIndex() + 1); + } + } + } + } + + public void advanceCommitIndex() { + // 获取quorum matchIndex + int peerNum = peers.size(); + long[] matchIndexes = new long[peerNum + 1]; + for (int i = 0; i < peerNum - 1; i++) { + matchIndexes[i] = peers.get(i).getMatchIndex(); + } + matchIndexes[peerNum] = lastSyncedIndex; + Arrays.sort(matchIndexes); + long newCommitIndex = matchIndexes[(peerNum + 1 + 1) / 2]; + if (raftLog.getEntry(newCommitIndex).getTerm() != currentTerm) { + return; + } + + lock.lock(); + if (commitIndex >= newCommitIndex) { + return; + } + long oldCommitIndex = commitIndex; + commitIndex = newCommitIndex; + // 同步到状态机 + for (long index = oldCommitIndex + 1; index <= newCommitIndex; index++) { + Raft.LogEntry entry = raftLog.getEntry(index); + stateMachine.apply(entry.getData().toByteArray()); + } + lastAppliedIndex = commitIndex; + commitIndexCondition.signalAll(); + lock.unlock(); + } + + public long packEntries(long nextIndex, Raft.AppendEntriesRequest.Builder requestBuilder) { + long lastIndex = Math.min(raftLog.getLastLogIndex(), + nextIndex + RaftOption.maxLogEntriesPerRequest - 1); + for (long index = nextIndex; index <= lastIndex; index++) { + Raft.LogEntry entry = raftLog.getEntry(index); + requestBuilder.addEntries(entry); + } + return lastIndex - nextIndex + 1; + } + + public void installSnapshot(Peer peer) { + Raft.InstallSnapshotRequest.Builder requestBuilder = Raft.InstallSnapshotRequest.newBuilder(); + requestBuilder.setServerId(localServer.getServerId()); + requestBuilder.setTerm(currentTerm); + // send snapshot + try { + snapshotLock.readLock().lock(); + Raft.InstallSnapshotRequest request = this.buildInstallSnapshotRequest( + null, 0, 0); + peer.getRpcClient().asyncCall("RaftConsensusService.installSnapshot", + request, new InstallSnapshotResponseCallback(peer, request)); + isSnapshoting = true; + } finally { + snapshotLock.readLock().unlock(); + } + + } + + private class InstallSnapshotResponseCallback implements RPCCallback { + private Peer peer; + private Raft.InstallSnapshotRequest request; + + public InstallSnapshotResponseCallback(Peer peer, Raft.InstallSnapshotRequest request) { + this.peer = peer; + this.request = request; + } + + @Override + public void success(Raft.InstallSnapshotResponse response) { + TreeMap snapshotDataFileMap = snapshot.getSnapshotDataFileMap(); + Snapshot.SnapshotDataFile lastDataFile = snapshotDataFileMap.get(request.getFileName()); + try { + snapshotLock.readLock().lock(); + if (request.getIsLast() == true) { + isSnapshoting = false; + } else { + Raft.InstallSnapshotRequest currentRequest = buildInstallSnapshotRequest( + this.request.getFileName(), + this.request.getOffset(), + this.request.getData().toByteArray().length); + peer.getRpcClient().asyncCall("RaftConsensusService.installSnapshot", + currentRequest, new InstallSnapshotResponseCallback(peer, currentRequest)); + } + } finally { + snapshotLock.readLock().unlock(); + } + } + + @Override + public void fail(Throwable e) { + LOG.warn("install snapshot failed, msg={}", e.getMessage()); + snapshotLock.readLock().lock(); + isSnapshoting = false; + snapshotLock.readLock().unlock(); + } + } + + private Raft.InstallSnapshotRequest buildInstallSnapshotRequest( + String lastFileName, long lastOffset, long lastLength) { + Raft.InstallSnapshotRequest.Builder requestBuilder = Raft.InstallSnapshotRequest.newBuilder(); + try { + TreeMap snapshotDataFileMap = snapshot.getSnapshotDataFileMap(); + if (lastFileName == null) { + lastFileName = snapshotDataFileMap.firstKey(); + lastOffset = 0; + lastLength = 0; + } + Snapshot.SnapshotDataFile lastFile = snapshotDataFileMap.get(lastFileName); + long lastFileLength = lastFile.randomAccessFile.length(); + String currentFileName = lastFileName; + long currentOffset = lastOffset + lastLength; + int currentDataSize = RaftOption.maxSnapshotBytesPerRequest; + Snapshot.SnapshotDataFile currentDataFile = lastFile; + if (lastOffset + lastLength < lastFileLength) { + if (lastOffset + lastLength + RaftOption.maxSnapshotBytesPerRequest > lastFileLength) { + currentDataSize = (int) (lastFileLength - (lastOffset + lastLength)); + } + } else { + Map.Entry currentEntry + = snapshotDataFileMap.higherEntry(lastFileName); + if (currentEntry == null) { + return null; + } + currentDataFile = currentEntry.getValue(); + currentFileName = currentEntry.getKey(); + currentOffset = 0; + int currentFileLenght = (int) currentEntry.getValue().randomAccessFile.length(); + if (currentFileLenght < RaftOption.maxSnapshotBytesPerRequest) { + currentDataSize = currentFileLenght; + } + } + byte[] currentData = new byte[currentDataSize]; + currentDataFile.randomAccessFile.read(currentData); + requestBuilder.setData(ByteString.copyFrom(currentData)); + requestBuilder.setFileName(currentFileName); + requestBuilder.setOffset(currentOffset); + requestBuilder.setTerm(currentTerm); + requestBuilder.setServerId(localServer.getServerId()); + requestBuilder.setIsFirst(false); + if (currentFileName.equals(snapshotDataFileMap.lastKey()) + && currentOffset + currentDataSize >= currentDataFile.randomAccessFile.length()) { + requestBuilder.setIsLast(true); + } else { + requestBuilder.setIsLast(false); + } + if (currentFileName.equals(snapshotDataFileMap.firstKey()) && currentOffset == 0) { + requestBuilder.setIsFirst(true); + } else { + requestBuilder.setIsFirst(false); + } + return requestBuilder.build(); + } catch (IOException ex) { + return null; + } + } + + public void becomeLeader() { + state = NodeState.STATE_LEADER; + leaderId = localServer.getServerId(); + // start heartbeat timer + resetHeartbeatTimer(); + } + + public void stepDown(long newTerm) { + if (currentTerm > newTerm) { + LOG.error("can't be happened"); + return; + } + if (currentTerm < newTerm) { + currentTerm = newTerm; + leaderId = 0; + votedFor = 0; + raftLog.updateMetaData(currentTerm, votedFor, null); + } + state = NodeState.STATE_FOLLOWER; + resetElectionTimer(); + } + + public void updateMetaData() { + raftLog.updateMetaData(currentTerm, votedFor, null); + } + + public int getElectionTimeoutMs() { + ThreadLocalRandom random = ThreadLocalRandom.current(); + int randomElectionTimeout = RaftOption.electionTimeoutMilliseconds + + random.nextInt(0, RaftOption.electionTimeoutMilliseconds); + return randomElectionTimeout; + } + + // client set command + public void replicate(byte[] data) { + Raft.LogEntry logEntry = Raft.LogEntry.newBuilder() + .setTerm(currentTerm) + .setType(Raft.EntryType.ENTRY_TYPE_DATA) + .setData(ByteString.copyFrom(data)).build(); + List entries = new ArrayList<>(); + entries.add(logEntry); + long newLastLogIndex = raftLog.append(entries); + for (final Peer peer : peers) { + executorService.submit(new Runnable() { + @Override + public void run() { + appendEntries(peer); + } + }); + } + // sync wait condition commitIndex >= newLastLogIndex + // TODO: add timeout + lock.lock(); + try { + while (commitIndex < newLastLogIndex) { + try { + commitIndexCondition.await(); + } catch (InterruptedException ex) { + LOG.warn(ex.getMessage()); + } + } + } finally { + lock.unlock(); + } + } + + public void takeSnapshot() { + if (raftLog.getTotalSize() < RaftOption.snapshotMinLogSize) { + return; + } + if (lastAppliedIndex <= lastSnapshotIndex) { + return; + } + long lastAppliedTerm = 0; + if (lastAppliedIndex >= raftLog.getStartLogIndex() + && lastAppliedIndex <= raftLog.getLastLogIndex()) { + lastAppliedTerm = raftLog.getEntry(lastAppliedIndex).getTerm(); + } + + snapshotLock.writeLock().lock(); + // take snapshot + String tmpSnapshotDir = snapshot.getSnapshotDir() + ".tmp"; + snapshot.updateMetaData(tmpSnapshotDir, lastAppliedIndex, lastAppliedTerm); + String tmpSnapshotDataDir = tmpSnapshotDir + File.pathSeparator + "data"; + stateMachine.writeSnapshot(tmpSnapshotDataDir); + try { + FileUtils.moveDirectory(new File(tmpSnapshotDir), new File(snapshot.getSnapshotDir())); + lastSnapshotIndex = lastAppliedIndex; + lastSnapshotTerm = lastAppliedTerm; + } catch (IOException ex) { + LOG.warn("move direct failed, msg={}", ex.getMessage()); + } + snapshotLock.writeLock().unlock(); + } + + public Lock getLock() { + return lock; + } + + public void setLock(Lock lock) { + this.lock = lock; + } + + public NodeState getState() { + return state; + } + + public void setState(NodeState state) { + this.state = state; + } + + public long getCurrentTerm() { + return currentTerm; + } + + public void setCurrentTerm(int currentTerm) { + this.currentTerm = currentTerm; + } + + public int getVotedFor() { + return votedFor; + } + + public void setVotedFor(int votedFor) { + this.votedFor = votedFor; + } + + public List getEntries() { + return entries; + } + + public void setEntries(List entries) { + this.entries = entries; + } + + public long getCommitIndex() { + return commitIndex; + } + + public void setCommitIndex(long commitIndex) { + this.commitIndex = commitIndex; + } + + + public long getLastAppliedIndex() { + return lastAppliedIndex; + } + + public void setLastAppliedIndex(long lastAppliedIndex) { + this.lastAppliedIndex = lastAppliedIndex; + } + + public ServerAddress getLocalServer() { + return localServer; + } + + public void setLocalServer(ServerAddress localServer) { + this.localServer = localServer; + } + + public SegmentedLog getRaftLog() { + return raftLog; + } + + public int getLeaderId() { + return leaderId; + } + + public void setLeaderId(int leaderId) { + this.leaderId = leaderId; + } + + public Snapshot getSnapshot() { + return snapshot; + } + + public void setSnapshot(Snapshot snapshot) { + this.snapshot = snapshot; + } + + public ExecutorService getExecutorService() { + return executorService; + } + + public ScheduledExecutorService getScheduledExecutorService() { + return scheduledExecutorService; + } + + public ReadWriteLock getSnapshotLock() { + return snapshotLock; + } + + public StateMachine getStateMachine() { + return stateMachine; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.github.wenweihu86.raft.RaftNode.installSnapshot` reads without synchronization from `this.com.github.wenweihu86.raft.RaftNode.currentTerm`. Potentially races with write in method `RaftNode.stepDown(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RaftNode.installSnapshot(Peer) + +### Procedure Id: +com.github.wenweihu86.raft.RaftNode.installSnapshot(com.github.wenweihu86.raft.Peer):void.259a658f0cd631041109cdf19df614a7 + +### File: +raft-java-core/src/main/java/com/github/wenweihu86/raft/RaftNode.java + +### Key: +RaftNode.java|installSnapshot|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +713b0af483701aeb2e4000e192937365 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8427/instruction.md b/inferredbugs-8427/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..60a4ed689f6076ae9a74bf377b8380332f6b6f0d --- /dev/null +++ b/inferredbugs-8427/instruction.md @@ -0,0 +1,273 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** raft-java +**Bug ID:** 21 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.wenweihu86.raft.service.impl; + +import com.github.wenweihu86.raft.RaftNode; +import com.github.wenweihu86.raft.proto.Raft; +import com.github.wenweihu86.raft.service.RaftConsensusService; +import com.github.wenweihu86.raft.util.RaftFileUtils; +import org.apache.commons.io.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by wenweihu86 on 2017/5/2. + */ +public class RaftConsensusServiceImpl implements RaftConsensusService { + + private static final Logger LOG = LoggerFactory.getLogger(RaftConsensusServiceImpl.class); + private RaftNode raftNode; + + public RaftConsensusServiceImpl(RaftNode node) { + this.raftNode = node; + } + + @Override + public Raft.VoteResponse requestVote(Raft.VoteRequest request) { + raftNode.getLock().lock(); + Raft.VoteResponse.Builder responseBuilder = Raft.VoteResponse.newBuilder(); + responseBuilder.setGranted(false); + responseBuilder.setTerm(raftNode.getCurrentTerm()); + if (request.getTerm() < raftNode.getCurrentTerm()) { + raftNode.getLock().unlock(); + return responseBuilder.build(); + } + if (request.getTerm() > raftNode.getCurrentTerm()) { + LOG.info("Received RequestVote request from server {} " + + "in term {} (this server's term was {})", + request.getServerId(), request.getTerm(), + raftNode.getCurrentTerm()); + raftNode.stepDown(request.getTerm()); + } + boolean logIsOk = request.getLastLogTerm() > raftNode.getRaftLog().getLastLogTerm() + || (request.getLastLogTerm() == raftNode.getRaftLog().getLastLogTerm() + && request.getLastLogIndex() >= raftNode.getRaftLog().getLastLogIndex()); + if (raftNode.getVotedFor() == 0 || logIsOk) { + raftNode.stepDown(request.getTerm()); + raftNode.setVotedFor(request.getServerId()); + raftNode.getRaftLog().updateMetaData(raftNode.getCurrentTerm(), raftNode.getVotedFor(), null); + responseBuilder.setGranted(true); + responseBuilder.setTerm(raftNode.getCurrentTerm()); + } + raftNode.getLock().unlock(); + return responseBuilder.build(); + } + + @Override + public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { + raftNode.getLock().lock(); + Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); + responseBuilder.setTerm(raftNode.getCurrentTerm()); + responseBuilder.setSuccess(false); + responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); + if (request.getTerm() < raftNode.getCurrentTerm()) { + raftNode.getLock().unlock(); + return responseBuilder.build(); + } + if (request.getTerm() > raftNode.getCurrentTerm()) { + LOG.info("Received AppendEntries request from server {} " + + "in term {} (this server's term was {})", + request.getServerId(), request.getTerm(), + raftNode.getCurrentTerm()); + raftNode.stepDown(request.getTerm()); + } + if (raftNode.getLeaderId() == 0) { + raftNode.setLeaderId(request.getServerId()); + } + + if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) { + LOG.debug("Rejecting AppendEntries RPC: would leave gap"); + raftNode.getLock().unlock(); + return responseBuilder.build(); + } + if (request.getPrevLogIndex() >= raftNode.getRaftLog().getFirstLogIndex() + && raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm() + != request.getPrevLogTerm()) { + LOG.debug("Rejecting AppendEntries RPC: terms don't agree"); + raftNode.getLock().unlock(); + return responseBuilder.build(); + } + + responseBuilder.setSuccess(true); + List entries = new ArrayList<>(); + long index = request.getPrevLogIndex(); + for (Raft.LogEntry entry : request.getEntriesList()) { + index++; + if (index < raftNode.getRaftLog().getFirstLogIndex()) { + continue; + } + if (raftNode.getRaftLog().getLastLogIndex() >= index) { + if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) { + continue; + } + // truncate segment log from index + long lastIndexKept = index - 1; + raftNode.getRaftLog().truncateSuffix(lastIndexKept); + } + entries.add(entry); + } + raftNode.getRaftLog().append(entries); + responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex()); + + if (raftNode.getCommitIndex() < request.getCommitIndex()) { + raftNode.setCommitIndex(request.getCommitIndex()); + // apply state machine + for (index = raftNode.getLastAppliedIndex() + 1; index <= raftNode.getCommitIndex(); index++) { + raftNode.getStateMachine().apply( + raftNode.getRaftLog().getEntry(index).getData().toByteArray()); + } + } + + raftNode.getLock().unlock(); + return responseBuilder.build(); + } + + @Override + public Raft.InstallSnapshotResponse installSnapshot(Raft.InstallSnapshotRequest request) { + Raft.InstallSnapshotResponse.Builder responseBuilder = Raft.InstallSnapshotResponse.newBuilder(); + responseBuilder.setTerm(raftNode.getCurrentTerm()); + + raftNode.getLock().lock(); + if (request.getTerm() < raftNode.getCurrentTerm()) { + LOG.info("Caller({}) is stale. Our term is {}, theirs is {}", + request.getServerId(), raftNode.getCurrentTerm(), request.getTerm()); + raftNode.getLock().unlock(); + return responseBuilder.build(); + } + raftNode.stepDown(request.getTerm()); + if (raftNode.getLeaderId() == 0) { + raftNode.setLeaderId(request.getServerId()); + } + raftNode.getLock().unlock(); + + // write snapshot data to local + String tmpSnapshotDir = raftNode.getSnapshot().getSnapshotDir() + ".tmp"; + File file = new File(tmpSnapshotDir); + if (file.exists() && request.getIsFirst()) { + file.delete(); + file.mkdir(); + } + if (request.getIsFirst()) { + raftNode.getSnapshot().updateMetaData(tmpSnapshotDir, + request.getSnapshotMetaData().getLastIncludedIndex(), + request.getSnapshotMetaData().getLastIncludedTerm()); + } + // write to file + RandomAccessFile randomAccessFile = null; + try { + String currentDataFileName = tmpSnapshotDir + File.pathSeparator + + "data" + File.pathSeparator + request.getFileName(); + File currentDataFile = new File(currentDataFileName); + if (!currentDataFile.exists()) { + currentDataFile.createNewFile(); + } + randomAccessFile = RaftFileUtils.openFile( + tmpSnapshotDir + File.pathSeparator + "data", + request.getFileName(), "rw"); + randomAccessFile.skipBytes((int) request.getOffset()); + randomAccessFile.write(request.getData().toByteArray()); + if (randomAccessFile != null) { + try { + randomAccessFile.close(); + randomAccessFile = null; + } catch (Exception ex2) { + LOG.warn("close failed"); + } + } + // move tmp dir to snapshot dir if this is the last package + File snapshotDirFile = new File(raftNode.getSnapshot().getSnapshotDir()); + if (snapshotDirFile.exists()) { + snapshotDirFile.delete(); + } + FileUtils.moveDirectory(new File(tmpSnapshotDir), snapshotDirFile); + responseBuilder.setSuccess(true); + } catch (IOException ex) { + LOG.warn("io exception, msg={}", ex.getMessage()); + } finally { + RaftFileUtils.closeFile(randomAccessFile); + } + return responseBuilder.build(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.github.wenweihu86.raft.service.impl.RaftConsensusServiceImpl.installSnapshot` indirectly writes to field `n$129.com.github.wenweihu86.raft.storage.Snapshot.metaData` outside of synchronization. + Reporting because this access may occur on a background thread. + +Note that the prefix path n$129 has been contaminated during the execution, so the reported race on n$129.com.github.wenweihu86.raft.storage.Snapshot.metaData might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Raft$InstallSnapshotResponse RaftConsensusServiceImpl.installSnapshot(Raft$InstallSnapshotRequest) + +### Procedure Id: +com.github.wenweihu86.raft.service.impl.RaftConsensusServiceImpl.installSnapshot(com.github.wenweihu.536237e5108950ab8ea8dd2417bbe35a + +### File: +raft-java-core/src/main/java/com/github/wenweihu86/raft/service/impl/RaftConsensusServiceImpl.java + +### Key: +RaftConsensusServiceImpl.java|installSnapshot|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +adcd71b729219a493a3fed53dfa6f97b + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8501/instruction.md b/inferredbugs-8501/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..955de8ff66c76cde963ead27d4c27df908fd2bf6 --- /dev/null +++ b/inferredbugs-8501/instruction.md @@ -0,0 +1,377 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** passay +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* See LICENSE for licensing and NOTICE for copyright. */ +package org.passay.dictionary; + +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CoderResult; +import java.util.TreeMap; + +/** + * Common implementation for file based word lists. + * + * @author Middleware Services + */ +public abstract class AbstractFileWordList extends AbstractWordList +{ + + /** Default cache size. */ + public static final int DEFAULT_CACHE_SIZE = 5; + + /** File containing words. */ + protected final RandomAccessFile file; + + /** Number of words in the file. */ + protected int size; + + /** Cache of indexes to file positions. */ + // CheckStyle:IllegalType OFF + // uses the firstKey and floorKey implementations + protected TreeMap cache = new TreeMap<>(); + // CheckStyle:IllegalType ON + + /** Character decoder. */ + private final CharsetDecoder charDecoder; + + /** Buffer to hold word read from file. */ + private final ByteBuffer wordBuf = ByteBuffer.allocate(256); + + /** Buffer to hold decoded word read from file. */ + private final CharBuffer charBuf = CharBuffer.allocate(wordBuf.capacity() * 4); + + /** Current position into backing file. */ + private long position; + + + /** + * Creates a new abstract file word list from the supplied file. + * + * @param raf File containing words, one per line. + * @param caseSensitive Set to true to create case-sensitive word list, false otherwise. + * @param cachePercent Percent (0-100) of file to cache in memory for improved read performance. + * @param decoder Charset decoder for converting file bytes to characters + * + * @throws IllegalArgumentException if cache percent is out of range. + * @throws IOException if an error occurs reading the supplied file + */ + public AbstractFileWordList( + final RandomAccessFile raf, + final boolean caseSensitive, + final int cachePercent, + final CharsetDecoder decoder) + throws IOException + { + if (cachePercent < 0 || cachePercent > 100) { + throw new IllegalArgumentException("cachePercent must be between 0 and 100 inclusive"); + } + file = raf; + if (caseSensitive) { + comparator = WordLists.CASE_SENSITIVE_COMPARATOR; + } else { + comparator = WordLists.CASE_INSENSITIVE_COMPARATOR; + } + charDecoder = decoder; + } + + + @Override + public String get(final int index) + { + checkRange(index); + try { + return readWord(index); + } catch (IOException e) { + throw new RuntimeException("Error reading from file backing word list", e); + } + } + + + @Override + public int size() + { + return size; + } + + + /** + * Returns the file backing this list. + * + * @return random access file that is backing this list + */ + public RandomAccessFile getFile() + { + return file; + } + + + /** + * Closes the underlying file and make the cache available for garbage collection. + * + * @throws IOException if an error occurs closing the file + */ + public void close() + throws IOException + { + synchronized (cache) { + file.close(); + } + cache = null; + } + + + /** + * Reads words from the backing file to initialize the word list. + * + * @param cachePercent Percent of file in bytes to use for cache. + * + * @throws IOException on I/O errors reading file data. + */ + protected void initialize(final int cachePercent) + throws IOException + { + final long fileBytes = file.length(); + final long cacheSize = (fileBytes / 100) * cachePercent; + final long cacheModulus = cacheSize == 0 ? fileBytes : cacheSize > fileBytes ? 1 : fileBytes / cacheSize; + + if (cache == null) { + throw new IllegalStateException("Cannot initialize after close has been called."); + } + + FileWord a; + FileWord b = null; + synchronized (cache) { + position = 0; + seek(0); + cache.clear(); + while ((a = nextWord()) != null) { + if (b != null && comparator.compare(a.word, b.word) < 0) { + throw new IllegalArgumentException("File is not sorted correctly for this comparator"); + } + b = a; + if (cacheSize > 0 && size % cacheModulus == 0) { + cache.put(size, a.offset); + } + size++; + } + } + } + + + /** + * Reads the word from the file at the given index of the word list. + * + * @param index ith word in the word list + * + * @return word at the supplied index + * + * @throws IOException on I/O errors + */ + protected String readWord(final int index) + throws IOException + { + int i = 0; + if (!cache.isEmpty() && cache.firstKey() <= index) { + i = cache.floorKey(index); + } + FileWord w; + synchronized (cache) { + position = i > 0 ? cache.get(i) : 0L; + seek(position); + do { + w = nextWord(); + } while (i++ < index && w != null); + return w != null ? w.word : null; + } + } + + + /** + * Positions the read head of the backing file at the given byte offset. + * + * @param offset byte offset into file. + * + * @throws IOException on I/O errors seeking. + */ + protected abstract void seek(long offset) + throws IOException; + + + /** + * @return Buffer around backing file. + */ + protected abstract ByteBuffer buffer(); + + + /** + * Fills the buffer from the backing file. This method may be a no-op if the buffer contains all file contents. + * + * @throws IOException on I/O errors filling buffer. + */ + protected abstract void fill() + throws IOException; + + + /** + * Reads the next word from the current position in the backing file. + * + * @return Data structure containing word and byte offset into file where word begins. + * + * @throws IOException on I/O errors reading file data. + */ + private FileWord nextWord() + throws IOException + { + byte b; + long start = position; + wordBuf.clear(); + while (hasRemaining()) { + b = buffer().get(); + position++; + if ((char) b == '\n' || (char) b == '\r') { + // Ignore leading line termination characters + if (wordBuf.position() == 0) { + start++; + continue; + } + break; + } + wordBuf.put(b); + } + if (wordBuf.position() == 0) { + return null; + } + + charBuf.clear(); + wordBuf.flip(); + final CoderResult result = charDecoder.decode(wordBuf, charBuf, true); + if (result.isError()) { + result.throwException(); + } + return new FileWord(charBuf.flip().toString(), start); + } + + + /** + * Determines whether the backing buffer has any more data to read. If the buffer is empty, it attempts + * to read from the underlying file and then checks the buffer again. + * + * @return True if there is any more data to read from the buffer, false otherwise. + * + * @throws IOException on I/O errors reading file data. + */ + private boolean hasRemaining() + throws IOException + { + if (buffer().hasRemaining()) { + return true; + } + fill(); + return buffer().hasRemaining(); + } + + + /** + * Data structure containing word and byte offset into file where word begins in backing file. + */ + static class FileWord + { + + // CheckStyle:VisibilityModifier OFF + /** Word read from backing file. */ + String word; + + /** Byte offset into file where word begins. */ + long offset; + // CheckStyle:VisibilityModifier ON + + + /** + * Creates a new instance with a word and offset. + * + * @param s word. + * @param position byte offset into file. + */ + FileWord(final String s, final long position) + { + word = s; + offset = position; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.passay.dictionary.AbstractFileWordList.readWord` reads with synchronization from `this.org.passay.dictionary.AbstractFileWordList.cache`. Potentially races with unsynchronized write in method `AbstractFileWordList.close()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String AbstractFileWordList.readWord(int) + +### Procedure Id: +org.passay.dictionary.AbstractFileWordList.readWord(int):java.lang.String.504e278e3e1028c410da225088302dd4 + +### File: +src/main/java/org/passay/dictionary/AbstractFileWordList.java + +### Key: +AbstractFileWordList.java|readWord|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +b08960449ef401de5946b452134970db + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8506/instruction.md b/inferredbugs-8506/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14ca994ccfb39bab8bda28fe14521d3011efb6bb --- /dev/null +++ b/inferredbugs-8506/instruction.md @@ -0,0 +1,148 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** GCViewer +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.tagtraum.perf.gcviewer.imp; + +import static com.tagtraum.perf.gcviewer.UnittestHelper.toKiloBytes; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.number.IsCloseTo.closeTo; +import static org.junit.Assert.assertThat; + +import java.io.InputStream; +import java.util.logging.Level; +import java.util.logging.Logger; + +import com.tagtraum.perf.gcviewer.UnittestHelper; +import com.tagtraum.perf.gcviewer.model.GCEvent; +import com.tagtraum.perf.gcviewer.model.GCModel; +import org.junit.Test; + +/** + * Tests some J9_R26 sample files against the IBM J9 parser. + */ +public class TestDataReaderIBM_J9_R26 { + private static final Logger IMP_LOGGER = Logger.getLogger("com.tagtraum.perf.gcviewer.imp"); + private static final Logger DATA_READER_FACTORY_LOGGER = Logger.getLogger("com.tagtraum.perf.gcviewer.DataReaderFactory"); + + @Test + public void testFullHeaderWithAfGcs() throws Exception { + TestLogHandler handler = new TestLogHandler(); + handler.setLevel(Level.WARNING); + IMP_LOGGER.addHandler(handler); + DATA_READER_FACTORY_LOGGER.addHandler(handler); + + InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R26_GAFP1_full_header.txt"); + DataReader reader = new DataReaderIBM_J9_R28(in); + GCModel model = reader.read(); + + assertThat("model size", model.size(), is(1)); + + GCEvent event = (GCEvent) model.get(0); + assertThat("pause", event.getPause(), closeTo(0.00529, 0.0000001)); + + assertThat("number of errors", handler.getCount(), is(1)); + } + + @Test + public void testSystemGc() throws Exception { + TestLogHandler handler = new TestLogHandler(); + handler.setLevel(Level.WARNING); + IMP_LOGGER.addHandler(handler); + DATA_READER_FACTORY_LOGGER.addHandler(handler); + + InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R26_GAFP1_global.txt"); + DataReader reader = new DataReaderIBM_J9_R28(in); + GCModel model = reader.read(); + + assertThat("model size", model.size(), is(1)); + + GCEvent event = (GCEvent) model.get(0); + assertThat("pause", event.getPause(), closeTo(0.036392, 0.0000001)); + + assertThat("total before", event.getTotal(), is(toKiloBytes(514064384))); + assertThat("free before", event.getPreUsed(), is(toKiloBytes(514064384 - 428417552))); + assertThat("free after", event.getPostUsed(), is(toKiloBytes(514064384 - 479900360))); + + assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(111411200))); + assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(111411200 - 29431656))); + assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(111411200 - 80831520))); + + assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(402653184))); + assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(402653184 - 398985896))); + assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(402653184 - 399068840))); + + assertThat("number of errors", handler.getCount(), is(0)); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.LineNumberReader` acquired by call to `DataReaderIBM_J9_R28(...)` at line 32 is not released after line 33. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestDataReaderIBM_J9_R26.testFullHeaderWithAfGcs() + +### Procedure Id: +com.tagtraum.perf.gcviewer.imp.TestDataReaderIBM_J9_R26.testFullHeaderWithAfGcs():void.4320c3a7f517835eacb3dfffa0ecb351 + +### File: +src/test/java/com/tagtraum/perf/gcviewer/imp/TestDataReaderIBM_J9_R26.java + +### Key: +TestDataReaderIBM_J9_R26.java|testFullHeaderWithAfGcs|RESOURCE_LEAK + +### Node Key: +c9deda297ca620e1c62c0c1ea8763701 + +### Hash: +356fa4b2b2cfff0e5c0309f41188e115 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8508/instruction.md b/inferredbugs-8508/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2278264e6fda5f3ee3e14b2a5db0ca35d461b74e --- /dev/null +++ b/inferredbugs-8508/instruction.md @@ -0,0 +1,307 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** GCViewer +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.tagtraum.perf.gcviewer.imp; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.LineNumberReader; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.events.Attribute; +import javax.xml.stream.events.EndElement; +import javax.xml.stream.events.StartElement; +import javax.xml.stream.events.XMLEvent; + +import com.tagtraum.perf.gcviewer.model.AbstractGCEvent.Type; +import com.tagtraum.perf.gcviewer.model.GCEvent; +import com.tagtraum.perf.gcviewer.model.GCModel; +import com.tagtraum.perf.gcviewer.util.NumberParser; + +/** + * Parser for IBM gc logs R26_Java6 + R27_Java7 + R28_Java8 + */ +public class DataReaderIBM_J9_R28 implements DataReader { + // TODO IBM_J9: support system gcs + + private static final String VERBOSEGC = "verbosegc"; + private static final String INITIALIZED = "initialized"; + private static final String EXCLUSIVE_START = "exclusive-start"; + private static final String GC_START = "gc-start"; + private static final String GC_END = "gc-end"; + private static final String EXCLUSIVE_END = "exclusive-end"; + + private static Logger LOG = Logger.getLogger(DataReaderIBM_J9_R28.class.getName()); + private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; + + private LineNumberReader in; + + public DataReaderIBM_J9_R28(InputStream in) { + this.in = new LineNumberReader(new InputStreamReader(in)); + } + + @Override + public GCModel read() throws IOException { + GCModel model = new GCModel(); + try { + XMLInputFactory factory = XMLInputFactory.newInstance(); + XMLEventReader eventReader = factory.createXMLEventReader(in); + GCEvent currentGcEvent = null; + while (eventReader.hasNext()) { + XMLEvent event = eventReader.nextEvent(); + if (event.isStartElement()) { + StartElement startElement = event.asStartElement(); + switch (startElement.getName().getLocalPart()) { + case VERBOSEGC: + handleVerboseGC(startElement); + break; + case INITIALIZED: + handleInitialized(eventReader); + break; + case EXCLUSIVE_START: + currentGcEvent = handleExclusiveStart(startElement); + break; + case GC_START: + handleGcStart(eventReader, startElement, currentGcEvent); + break; + case GC_END: + handleGcEnd(eventReader, currentGcEvent); + break; + case EXCLUSIVE_END: + handleExclusiveEnd(startElement, currentGcEvent); + model.add(currentGcEvent); + currentGcEvent = null; + break; + } + } + + } + } + catch (XMLStreamException e) { + if (LOG.isLoggable(Level.WARNING)) LOG.warning("line " + in.getLineNumber() + ": " + e.toString()); + if (LOG.isLoggable(Level.FINE)) LOG.log(Level.FINE, "line " + in.getLineNumber() + ": " + e.getMessage(), e); + } + + return model; + } + + private void handleVerboseGC(StartElement startElement) { + assert startElement.getName().getLocalPart().equals(VERBOSEGC) : "expected name of startElement: " + VERBOSEGC + ", but got " + startElement.getName(); + LOG.info("gc log version = " + getAttributeValue(startElement, "version")); + } + + private void handleInitialized(XMLEventReader eventReader) throws XMLStreamException { + String currentElementName = ""; + while (eventReader.hasNext() && !currentElementName.equals(INITIALIZED)) { + XMLEvent event = eventReader.nextEvent(); + if (event.isStartElement()) { + StartElement startElement = event.asStartElement(); + if (startElement.getName().getLocalPart().equals("attribute")) { + String name = getAttributeValue(startElement, "name"); + if (name != null && name.equals("gcPolicy")) { + LOG.info("gcPolicy = " + getAttributeValue(startElement, "value")); + } + } + } + else if (event.isEndElement()) { + EndElement endElement = event.asEndElement(); + currentElementName = endElement.getName().getLocalPart(); + } + } + } + + private GCEvent handleExclusiveStart(StartElement startElement) { + GCEvent event = new GCEvent(); + try { + event.setDateStamp(ZonedDateTime.of( + LocalDateTime.parse(getAttributeValue(startElement, "timestamp"), dateTimeFormatter), + ZoneId.systemDefault())); + } + catch (DateTimeParseException e) { + if (LOG.isLoggable(Level.WARNING)) LOG.warning("line " + in.getLineNumber() + ": " + e.toString()); + if (LOG.isLoggable(Level.FINE)) LOG.log(Level.FINE, "line " + in.getLineNumber() + ": " + e.getMessage(), e); + } + + return event; + } + + private void handleExclusiveEnd(StartElement startElement, GCEvent event) { + event.setPause(NumberParser.parseDouble(getAttributeValue(startElement, "durationms")) / 1000); + } + + private void handleGcStart(XMLEventReader eventReader, StartElement startElement, GCEvent event) throws XMLStreamException { + event.setType(Type.lookup(getAttributeValue(startElement, "type"))); + if (event.getExtendedType() == null) { + LOG.warning("could not determine type of event " + startElement.toString()); + return; + } + + String currentElementName = ""; + while (eventReader.hasNext() && !currentElementName.equals(GC_START)) { + + XMLEvent xmlEvent = eventReader.nextEvent(); + if (xmlEvent.isStartElement()) { + StartElement startEl = xmlEvent.asStartElement(); + if (startEl.getName().getLocalPart().equals("mem-info")) { + setTotalAndPreUsed(event, startEl); + } + else if (startEl.getName().getLocalPart().equals("mem")) { + switch (getAttributeValue(startEl, "type")) { + case "nursery": + GCEvent young = new GCEvent(); + young.setType(Type.lookup("nursery")); + setTotalAndPreUsed(young, startEl); + event.add(young); + break; + case "tenure": + GCEvent tenured = new GCEvent(); + tenured.setType(Type.lookup("tenure")); + setTotalAndPreUsed(tenured, startEl); + event.add(tenured); + break; + // all other are ignored + } + } + } + else if (xmlEvent.isEndElement()) { + EndElement endElement = xmlEvent.asEndElement(); + currentElementName = endElement.getName().getLocalPart(); + } + } + } + + private void handleGcEnd(XMLEventReader eventReader, GCEvent event) throws XMLStreamException { + String currentElementName = ""; + while (eventReader.hasNext() && !currentElementName.equals(GC_END)) { + + XMLEvent xmlEvent = eventReader.nextEvent(); + if (xmlEvent.isStartElement()) { + StartElement startEl = xmlEvent.asStartElement(); + if (startEl.getName().getLocalPart().equals("mem-info")) { + setPostUsed(event, startEl); + } + else if (startEl.getName().getLocalPart().equals("mem")) { + switch (getAttributeValue(startEl, "type")) { + case "nursery": + setPostUsed(event.getYoung(), startEl); + break; + case "tenure": + setPostUsed(event.getTenured(), startEl); + break; + // all other are ignored + } + } + } + else if (xmlEvent.isEndElement()) { + EndElement endElement = xmlEvent.asEndElement(); + currentElementName = endElement.getName().getLocalPart(); + } + } + } + + private void setTotalAndPreUsed(GCEvent event, StartElement startEl) { + long total = NumberParser.parseInt(getAttributeValue(startEl, "total")); + event.setTotal(toKiloBytes(total)); + event.setPreUsed(toKiloBytes(total - NumberParser.parseInt(getAttributeValue(startEl, "free")))); + } + + private void setPostUsed(GCEvent event, StartElement startEl) { + long total = NumberParser.parseInt(getAttributeValue(startEl, "total")); + event.setPostUsed(toKiloBytes(total - NumberParser.parseInt(getAttributeValue(startEl, "free")))); + } + + private String getAttributeValue(StartElement event, String name) { + String value = null; + Attribute attr = event.getAttributeByName(new QName(name)); + if (attr != null) { + value = attr.getValue(); + } + + return value; + } + + private int toKiloBytes(long bytes) { + return (int)Math.rint(bytes / (double)1024); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getAttributeValue(this,startEl,"total")` could be null and is dereferenced by call to `parseInt(...)` at line 216. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DataReaderIBM_J9_R28.setPostUsed(GCEvent,StartElement) + +### Procedure Id: +com.tagtraum.perf.gcviewer.imp.DataReaderIBM_J9_R28.setPostUsed(com.tagtraum.perf.gcviewer.model.GCE.d215c3509ac5f0a02c5e180d9a4bd8e3 + +### File: +src/main/java/com/tagtraum/perf/gcviewer/imp/DataReaderIBM_J9_R28.java + +### Key: +DataReaderIBM_J9_R28.java|setPostUsed|NULL_DEREFERENCE + +### Node Key: +265ba86214678cae77b0c9ab2eedcb6d + +### Hash: +d129ce442d02857374a15eb10d2a6ffb + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8530/instruction.md b/inferredbugs-8530/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cbeb6dda55418f8fa077b4be905d51ee0c6b50fe --- /dev/null +++ b/inferredbugs-8530/instruction.md @@ -0,0 +1,583 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** smartqq +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.scienjus.smartqq.client; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.scienjus.smartqq.callback.MessageCallback; +import com.scienjus.smartqq.model.*; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.cookie.Cookie; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.params.CoreConnectionPNames; +import org.apache.log4j.Logger; + +import java.io.*; +import java.util.*; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * Api客户端 + * @author ScienJus + * @date 2015/12/18. + */ +public class SmartQQClient { + + //日志 + private static final Logger LOGGER = Logger.getLogger(SmartQQClient.class); + + //执行拉取消息的线程池 + private static final ScheduledThreadPoolExecutor POOL = new ScheduledThreadPoolExecutor(20); + + //消息id,这个好像可以随便设置,所以设成全局的 + private static long MESSAGE_ID = 43690001; + + //发送请求的客户端 + private CloseableHttpClient client = HttpClients.createDefault(); + + //保存cookie信息 + private HttpClientContext context = HttpClientContext.create(); + + //鉴权参数 + private String ptwebqq; + + private String vfwebqq; + + private long uin; + + private String psessionid; + + //拉取消息的线程 + private ScheduledFuture pollMessageFuture; + + /** + * 登录 + */ + public void login() { + getQRCode(); + String url = verifyQRCode(); + getPtwebqq(url); + getVfwebqq(); + getUinAndPsessionid(); + } + + //登录流程1:获取二维码 + private void getQRCode() { + LOGGER.info("开始获取二维码"); + String filePath = getClass().getResource("/").getPath().concat("qrcode.png"); + HttpGet get = defaultHttpGet("https://ssl.ptlogin2.qq.com/ptqrshow?appid=501004106&e=0&l=M&s=5&d=72&v=4&t=0.1", null); + try (CloseableHttpResponse response = client.execute(get, context); + FileOutputStream out = new FileOutputStream(filePath)) { + int len; + byte[] buffer = new byte[1024]; + while ((len = response.getEntity().getContent().read(buffer)) != -1) { + out.write(buffer, 0, len); + } + out.close(); + LOGGER.info("二维码已保存在 " + filePath + " 文件中,请打开手机QQ并扫描二维码"); + } catch (IOException e) { + LOGGER.error("获取二维码失败"); + } + } + + //登录流程2:校验二维码 + private String verifyQRCode() { + LOGGER.info("等待扫描二维码"); + HttpGet get = defaultHttpGet( + "https://ssl.ptlogin2.qq.com/ptqrlogin?webqq_type=10&remember_uin=1&login2qq=1&aid=501004106&u1=h" + + "ttp%3A%2F%2Fw.qq.com%2Fproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&ptredirect=0&ptlang=2052&daid=164&from_ui=1&ptty" + + "pe=1&dumy=&fp=loginerroralert&action=0-0-157510&mibao_css=m_webqq&t=1&g=1&js_type=0&js_ver=10143&login_sig=&pt_randsalt=0", + + "https://ui.ptlogin2.qq.com/cgi-bin/login?daid=164&target=self&style=16&mibao_css=m_webqq&appid=501004106&enable_q" + + "login=0&no_verifyimg=1&s_url=http%3A%2F%2Fw.qq.com%2Fproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t=20131024001"); + + //阻塞直到确认二维码认证成功 + while (true) { + sleep(1); + try (CloseableHttpResponse response = client.execute(get, context)) { + String responseText = getResponseText(response); + if (responseText.contains("成功")) { + for (String content : responseText.split("','")) { + if (content.startsWith("http")) { + return content; + } + } + } else if (responseText.contains("已失效")) { + LOGGER.info("二维码已失效,尝试重新获取二维码"); + getQRCode(); + } + } catch (IOException e) { + LOGGER.error("校验二维码失败"); + } + } + + } + + //登录流程3:获取ptwebqq + private void getPtwebqq(String url) { + LOGGER.info("开始获取ptwebqq"); + HttpGet get = defaultHttpGet(url, null); + try { + client.execute(get, context); + for (Cookie cookie : context.getCookieStore().getCookies()) { + if (cookie.getName().equals("ptwebqq")) { + this.ptwebqq = cookie.getValue(); + } + } + } catch (IOException e) { + LOGGER.error("获取ptwebqq失败"); + } + } + + //登录流程4:获取vfwebqq + private void getVfwebqq() { + LOGGER.info("开始获取vfwebqq"); + HttpGet get = defaultHttpGet( + "http://s.web2.qq.com/api/getvfwebqq?ptwebqq=" + ptwebqq + "&clientid=53999199&psessionid=&t=0.1", + "http://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1"); + try (CloseableHttpResponse response = client.execute(get, context)) { + JSONObject responseJson = JSON.parseObject(getResponseText(response)); + this.vfwebqq = responseJson.getJSONObject("result").getString("vfwebqq"); + } catch (IOException e) { + LOGGER.error("获取vfwebqq失败"); + } + } + + //登录流程5:获取uin和psessionid + private void getUinAndPsessionid() { + LOGGER.info("开始获取uin和psessionid"); + HttpPost post = defaultHttpPost( + "http://d1.web2.qq.com/channel/login2", + "http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2"); + JSONObject r = new JSONObject(); + r.put("ptwebqq", ptwebqq); + r.put("clientid", 53999199); + r.put("psessionid", ""); + r.put("status", "online"); + try { + post.setEntity(new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("r", r.toJSONString())))); + try (CloseableHttpResponse response = client.execute(post, context)) { + JSONObject responseJson = JSON.parseObject(getResponseText(response)); + this.psessionid = responseJson.getJSONObject("result").getString("psessionid"); + this.uin = responseJson.getJSONObject("result").getLongValue("uin"); + } catch (IOException e) { + LOGGER.error("获取uin和psessionid失败"); + } + } catch (UnsupportedEncodingException e) { + LOGGER.error("获取uin和psessionid失败"); + } + + } + + /** + * 获取群列表 + * @return + */ + public List getGroupList() { + LOGGER.info("开始获取群列表"); + HttpPost post = defaultHttpPost( + "http://s.web2.qq.com/api/get_group_name_list_mask2", + "http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2"); + JSONObject r = new JSONObject(); + r.put("vfwebqq", vfwebqq); + r.put("hash", hash()); + try { + post.setEntity(new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("r", r.toJSONString())))); + try (CloseableHttpResponse response = client.execute(post, context)) { + JSONObject responseJson = JSON.parseObject(getResponseText(response)); + return JSON.parseArray(responseJson.getJSONObject("result").getJSONArray("gnamelist").toJSONString(), Group.class); + } catch (IOException e) { + LOGGER.error("获取群列表失败"); + } + } catch (UnsupportedEncodingException e) { + LOGGER.error("获取群列表失败"); + } + return Collections.emptyList(); + } + + /** + * 拉取消息 + * @param callback 获取消息后的回调 + */ + public void pollMessage(MessageCallback callback) { + LOGGER.info("开始接受消息"); + HttpPost post = defaultHttpPost( + "http://d1.web2.qq.com/channel/poll2", + "http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2"); + JSONObject r = new JSONObject(); + r.put("ptwebqq", ptwebqq); + r.put("clientid", 53999199); + r.put("psessionid", psessionid); + r.put("key", ""); + try { + post.setEntity(new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("r", r.toJSONString())))); + if (pollMessageFuture != null) { + pollMessageFuture.cancel(false); + } + pollMessageFuture = POOL.scheduleWithFixedDelay(new PollMessageTask(post, callback), 1, 1, TimeUnit.SECONDS); + } catch (UnsupportedEncodingException e) { + LOGGER.error("获取接受消息失败"); + } + } + + /** + * 停止拉取消息 + */ + public void stopPoll() { + if (pollMessageFuture != null) { + pollMessageFuture.cancel(false); + } + pollMessageFuture = null; + } + + /** + * 发送群消息 + * @param groupId + * @param msg + */ + public void sendMessageToGroup(long groupId, String msg) { + LOGGER.info("开始发送群消息"); + HttpPost post = defaultHttpPost( + "http://d1.web2.qq.com/channel/send_qun_msg2", + "http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2"); + JSONObject r = new JSONObject(); + r.put("group_uin", groupId); + r.put("content", JSON.toJSONString(Arrays.asList(msg, Arrays.asList("font", Font.DEFAULT_FONT)))); //注意这里虽然格式是Json,但是实际是String + r.put("face", 573); + r.put("clientid", 53999199); + r.put("msg_id", MESSAGE_ID++); + r.put("psessionid", psessionid); + try { + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("r", r.toJSONString())), "UTF-8"); + post.setEntity(entity); + try (CloseableHttpResponse response = client.execute(post, context)) { + JSONObject responseJson = JSON.parseObject(getResponseText(response)); + if (0 == responseJson.getIntValue("errCode")) { + LOGGER.error("发送群消息成功"); + } else { + LOGGER.error("发送群消息失败"); + } + } catch (IOException e) { + LOGGER.error("发送群消息失败"); + } + } catch (UnsupportedEncodingException e) { + LOGGER.error("发送群消息失败"); + } + } + + /** + * 发送消息 + * @param friendId + * @param msg + */ + public void sendMessageToFriend(long friendId, String msg) { + LOGGER.info("开始发送消息"); + HttpPost post = defaultHttpPost( + "http://d1.web2.qq.com/channel/send_buddy_msg2", + "http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2"); + JSONObject r = new JSONObject(); + r.put("to", friendId); + r.put("content", JSON.toJSONString(Arrays.asList(msg, Arrays.asList("font", Font.DEFAULT_FONT)))); //注意这里虽然格式是Json,但是实际是String + r.put("face", 573); + r.put("clientid", 53999199); + r.put("msg_id", MESSAGE_ID++); + r.put("psessionid", psessionid); + try { + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("r", r.toJSONString())), "UTF-8"); + post.setEntity(entity); + try (CloseableHttpResponse response = client.execute(post, context)) { + JSONObject responseJson = JSON.parseObject(getResponseText(response)); + if (0 == responseJson.getIntValue("errCode")) { + LOGGER.error("发送消息成功"); + } else { + LOGGER.error("发送消息失败"); + } + } catch (IOException e) { + LOGGER.error("发送消息失败"); + } + } catch (UnsupportedEncodingException e) { + LOGGER.error("发送消息失败"); + } + } + + /** + * 获取好友列表 + * @return + */ + public List getFriendList() { + LOGGER.info("开始获取好友列表"); + HttpPost post = defaultHttpPost( + "http://s.web2.qq.com/api/get_user_friends2", + "http://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1"); + JSONObject r = new JSONObject(); + r.put("vfwebqq", vfwebqq); + r.put("hash", hash()); + try { + post.setEntity(new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("r", r.toJSONString())))); + try (CloseableHttpResponse response = client.execute(post, context)) { + JSONObject responseJson = JSON.parseObject(getResponseText(response)); + if (0 == responseJson.getIntValue("retcode")) { + JSONObject result = responseJson.getJSONObject("result"); + //获得分组 + JSONArray categories = result.getJSONArray("categories"); + Map categoryMap = new HashMap<>(); + categoryMap.put(0, Category.defaultCategory()); + for (int i = 0; categories != null && i < categories.size(); i++) { + Category category = categories.getObject(i, Category.class); + categoryMap.put(category.getIndex(), category); + } + //获得好友信息 + Map friendMap = new HashMap<>(); + JSONArray friends = result.getJSONArray("friends"); + for (int i = 0; friends != null && i < friends.size(); i++) { + JSONObject item = friends.getJSONObject(i); + Friend friend = new Friend(); + friend.setUserId(item.getLongValue("uin")); + friendMap.put(friend.getUserId(), friend); + categoryMap.get(item.getIntValue("categories")).addFriend(friend); + } + JSONArray marknames = result.getJSONArray("marknames"); + for (int i = 0; marknames != null && i < marknames.size(); i++) { + JSONObject item = marknames.getJSONObject(i); + friendMap.get(item.getLongValue("uin")).setMarkname(item.getString("markname")); + } + JSONArray info = result.getJSONArray("info"); + for (int i = 0; info != null && i < info.size(); i++) { + JSONObject item = info.getJSONObject(i); + friendMap.get(item.getLongValue("uin")).setNickname(item.getString("nick")); + } + JSONArray vipinfo = result.getJSONArray("vipinfo"); + for (int i = 0; vipinfo != null && i < vipinfo.size(); i++) { + JSONObject item = vipinfo.getJSONObject(i); + Friend friend = friendMap.get(item.getLongValue("u")); + friend.setVip(item.getIntValue("is_vip") == 1); + friend.setVipLevel(item.getIntValue("vip_level")); + } + return new ArrayList<>(categoryMap.values()); + } else { + LOGGER.error("获取好友列表失败"); + } + } catch (IOException e) { + LOGGER.error("获取好友列表失败"); + } + } catch (UnsupportedEncodingException e) { + LOGGER.error("获取好友列表失败"); + } + return Collections.EMPTY_LIST; + } + + //hash加密方法 + private String hash() { + return hash(uin, ptwebqq); + } + + //线程暂停 + private static void sleep(long seconds) { + try { + Thread.sleep(seconds * 1000); + } catch (InterruptedException e) {} + } + + //hash加密方法 + private static String hash(long x, String K) { + int[] N = new int[4]; + for (int T = 0; T < K.length(); T++) { + N[T % 4] ^= K.charAt(T); + } + String[] U = {"EC", "OK"}; + long[] V = new long[4]; + V[0] = x >> 24 & 255 ^ U[0].charAt(0); + V[1] = x >> 16 & 255 ^ U[0].charAt(1); + V[2] = x >> 8 & 255 ^ U[1].charAt(0); + V[3] = x & 255 ^ U[1].charAt(1); + + long[] U1 = new long[8]; + + for (int T = 0; T < 8; T++) { + U1[T] = T % 2 == 0 ? N[T >> 1] : V[T >> 1]; + } + + String[] N1 = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}; + String V1 = ""; + for (long aU1 : U1) { + V1 += N1[(int) ((aU1 >> 4) & 15)]; + V1 += N1[(int) (aU1 & 15)]; + } + return V1; + } + + //得到返回的数据 + private static String getResponseText(CloseableHttpResponse response) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { + StringBuilder buffer = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + buffer.append(line); + } + return buffer.toString(); + } catch (IOException e) { + LOGGER.error("获取返回数据失败"); + } + return ""; + } + + //默认的http get + private static HttpGet defaultHttpGet(String url, String referer) { + HttpGet get = new HttpGet(url); + if (referer != null) { + get.setHeader("Referer", referer); + } + RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(120 * 1000) + .setConnectionRequestTimeout(120 * 1000) + .setSocketTimeout(120 * 1000) + .build(); + get.setConfig(requestConfig); + get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"); + return get; + } + + //默认的http post + private static HttpPost defaultHttpPost(String url, String referer) { + HttpPost post = new HttpPost(url); + if (referer != null) { + post.setHeader("Referer", referer); + } + RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(120 * 1000) + .setConnectionRequestTimeout(120 * 1000) + .setSocketTimeout(120 * 1000) + .build(); + post.setConfig(requestConfig); + post.setHeader("Origin", getOrigin(url)); + post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"); + return post; + } + + //截取url得到origin + private static String getOrigin(String url) { + return url.substring(0, url.lastIndexOf("/")); + } + + + //拉取消息的线程 + private class PollMessageTask implements Runnable { + + //请求的post方法 + private HttpPost post; + + //拉取到消息的回调 + private MessageCallback callback; + + public PollMessageTask(HttpPost post, MessageCallback callback) { + this.post = post; + this.callback = callback; + } + + @Override + public void run() { + try (CloseableHttpResponse response = client.execute(post, context)) { + JSONObject responseJson = JSON.parseObject(getResponseText(response)); + + if (responseJson.getIntValue("retcode") == 0) { + JSONArray array = responseJson.getJSONArray("result"); + for (int i = 0; array != null && i < array.size(); i++) { + JSONObject message = array.getJSONObject(i); + String type = message.getString("poll_type"); + if ("message".equals(type)) { + callback.onMessage(new Message(message.getJSONObject("value"))); + } else if ("group_message".equals(type)) { + callback.onGroupMessage(new GroupMessage(message.getJSONObject("value"))); + } + } + } else { + LOGGER.error("接受消息失败 retcode: " + responseJson.getIntValue("retcode")); + } + } catch (IOException e) { + LOGGER.error("获取接受消息失败"); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `categoryMap.get(valueOf(item.getIntValue("categories")))` could be null and is dereferenced at line 345. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List SmartQQClient.getFriendList() + +### Procedure Id: +com.scienjus.smartqq.client.SmartQQClient.getFriendList():java.util.List.234c7cbd59dd160d17640196a061a06f + +### File: +src/main/java/com/scienjus/smartqq/client/SmartQQClient.java + +### Key: +SmartQQClient.java|getFriendList|NULL_DEREFERENCE + +### Node Key: +667f766f56f9a333b07e78646d5e69c3 + +### Hash: +920aedb35b5bd9bf8efb930868d49b2c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8537/instruction.md b/inferredbugs-8537/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c31b6d65e4a775f911b801176b0afc888c4d120 --- /dev/null +++ b/inferredbugs-8537/instruction.md @@ -0,0 +1,472 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** cointrader +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.cryptocoinpartners.util; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.persistence.EntityManager; +import javax.persistence.NoResultException; +import javax.persistence.Query; +import javax.persistence.TypedQuery; + +import org.cryptocoinpartners.schema.Currencies; +import org.cryptocoinpartners.schema.EntityBase; +import org.cryptocoinpartners.schema.Exchanges; +import org.cryptocoinpartners.schema.Prompts; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Tim Olson + */ +public class PersistUtil { + + private static Logger log = LoggerFactory.getLogger("org.cryptocoinpartners.persist"); + private static Object lock = new Object(); + + public static void insert(EntityBase... entities) { + synchronized (lock) { + EntityManager em = null; + boolean persited = true; + try { + em = createEntityManager(); + PersistUtilHelper.beginTransaction(); + + try { + for (EntityBase entity : entities) { + // em.refresh(entity); + // if (em.contains(entity)) + /// em.merge(entity); + // else + em.persist(entity); + PersistUtilHelper.commit(); + } + + } catch (Exception | Error e) { + persited = false; + e.printStackTrace(); + if (PersistUtilHelper.isActive()) + PersistUtilHelper.rollback(); + } + } finally { + if (persited) + for (EntityBase entity : entities) + log.debug(entity.getClass().getSimpleName() + ": " + entity.getId().toString() + " saved to database"); + else + for (EntityBase entity : entities) + log.error(entity.getClass().getSimpleName() + ": " + entity.getId().toString() + " not saved to database"); + if (em != null && em.isOpen()) + PersistUtilHelper.closeEntityManager(); + + } + } + } + + public static void merge(EntityBase... entities) { + synchronized (lock) { + EntityManager em = null; + boolean persited = true; + try { + em = createEntityManager(); + PersistUtilHelper.beginTransaction(); + + try { + for (EntityBase entity : entities) { + // em.find(entity.getClass(), entity.getId()); + // em. + // em.refresh(entity); + //if (em.contains(entity)) + // em.merge(entity); + //else + em.merge(entity); + PersistUtilHelper.commit(); + } + + } catch (Exception | Error e) { + persited = false; + e.printStackTrace(); + if (PersistUtilHelper.isActive()) + PersistUtilHelper.rollback(); + } + } finally { + if (persited) + for (EntityBase entity : entities) + log.debug(entity.getClass().getSimpleName() + ": " + entity.getId().toString() + " saved to database"); + else + for (EntityBase entity : entities) + log.error(entity.getClass().getSimpleName() + ": " + entity.getId().toString() + " not saved to database"); + if (em != null && em.isOpen()) + PersistUtilHelper.closeEntityManager(); + + } + } + } + + /** + * Use this method if you do not know the number of columns or rows in the result set. The visitor will be called + * once for each row with an Object[] of column values + */ + public static void queryEach(Visitor handler, String queryStr, Object... params) { + queryEach(handler, defaultBatchSize, queryStr, params); + } + + /** + * Use this method if you do not know the number of columns or rows in the result set. The visitor will be called + * once for each row with an Object[] of column values + */ + @SuppressWarnings("ConstantConditions") + public static void queryEach(Visitor handler, int batchSize, String queryStr, Object... params) { + EntityManager em = null; + try { + em = createEntityManager(); + final Query query = em.createQuery(queryStr); + if (params != null) { + for (int i = 0; i < params.length; i++) { + Object param = params[i]; + query.setParameter(i + 1, param); // JPA uses 1-based indexes + } + } + query.setMaxResults(batchSize); + for (int start = 0;; start += batchSize) { + query.setFirstResult(start); + List list = query.getResultList(); + if (list.isEmpty()) + return; + for (Object row : list) { + if (row.getClass().isArray() && !handler.handleItem((Object[]) row) || !row.getClass().isArray() + && !handler.handleItem(new Object[] { row })) + return; + } + } + } finally { + if (em != null) + PersistUtilHelper.closeEntityManager(); + } + } + + public static void queryEach(Class resultType, Visitor handler, String queryStr, Object... params) { + queryEach(resultType, handler, defaultBatchSize, queryStr, params); + } + + public static void queryEach(Class resultType, Visitor handler, int batchSize, String queryStr, Object... params) { + EntityManager em = null; + try { + em = createEntityManager(); + final TypedQuery query = em.createQuery(queryStr, resultType); + if (params != null) { + for (int i = 0; i < params.length; i++) { + Object param = params[i]; + query.setParameter(i + 1, param); // JPA uses 1-based indexes + } + } + query.setMaxResults(batchSize); + for (int start = 0;; start += batchSize) { + query.setFirstResult(start); + final List list = query.getResultList(); + if (list.isEmpty()) + return; + for (T row : list) { + if (!handler.handleItem(row)) + return; + } + } + } finally { + if (em != null) + PersistUtilHelper.closeEntityManager(); + + } + } + + public static List queryList(Class resultType, String queryStr, Object... params) { + EntityManager em = null; + try { + em = createEntityManager(); + final TypedQuery query = em.createQuery(queryStr, resultType); + if (params != null) { + for (int i = 0; i < params.length; i++) { + Object param = params[i]; + query.setParameter(i + 1, param); // JPA uses 1-based indexes + } + } + return query.getResultList(); + } finally { + if (em != null) + PersistUtilHelper.closeEntityManager(); + } + } + + @SuppressWarnings("unchecked") + public static List queryNativeList(Class resultType, String queryStr, Object... params) { + EntityManager em = null; + try { + em = createEntityManager(); + final Query query = em.createNativeQuery(queryStr, resultType); + if (params != null) { + for (int i = 0; i < params.length; i++) { + Object param = params[i]; + query.setParameter(i + 1, param); // JPA uses 1-based indexes + } + } + return query.getResultList(); + } finally { + if (em != null) + PersistUtilHelper.closeEntityManager(); + } + } + + /** + returns a single result entity. if none found, a javax.persistence.NoResultException is thrown. + */ + public static T queryOne(Class resultType, String queryStr, Object... params) throws NoResultException { + EntityManager em = null; + try { + em = createEntityManager(); + final TypedQuery query = em.createQuery(queryStr, resultType); + if (params != null) { + for (int i = 0; i < params.length; i++) { + Object param = params[i]; + query.setParameter(i + 1, param); // JPA uses 1-based indexes + } + } + return query.getSingleResult(); + } finally { + if (em != null) + PersistUtilHelper.closeEntityManager(); + } + } + + public static T namedQueryOne(Class resultType, String namedQuery, Object... params) throws NoResultException { + EntityManager em = null; + try { + em = createEntityManager(); + final TypedQuery query = em.createNamedQuery(namedQuery, resultType); + if (params != null) { + for (int i = 0; i < params.length; i++) { + Object param = params[i]; + query.setParameter(i + 1, param); // JPA uses 1-based indexes + } + } + return query.getSingleResult(); + } finally { + if (em != null) + PersistUtilHelper.closeEntityManager(); + } + } + + /** + returns a single result entity or null if not found + */ + public static T queryZeroOne(Class resultType, String queryStr, Object... params) { + EntityManager em = null; + try { + em = createEntityManager(); + final TypedQuery query = em.createQuery(queryStr, resultType); + if (params != null) { + for (int i = 0; i < params.length; i++) { + Object param = params[i]; + query.setParameter(i + 1, param); // JPA uses 1-based indexes + } + } + try { + return query.getSingleResult(); + } catch (NoResultException x) { + return null; + } + } finally { + if (em != null) + PersistUtilHelper.closeEntityManager(); + } + } + + public static T namedQueryZeroOne(Class resultType, String namedQuery, Object... params) { + EntityManager em = null; + try { + em = createEntityManager(); + final TypedQuery query = em.createNamedQuery(namedQuery, resultType); + if (params != null) { + for (int i = 0; i < params.length; i++) { + Object param = params[i]; + query.setParameter(i + 1, param); // JPA uses 1-based indexes + } + } + try { + return query.getSingleResult(); + } catch (NoResultException x) { + return null; + } + } finally { + if (em != null) + PersistUtilHelper.closeEntityManager(); + } + } + + public static T findById(Class resultType, UUID id) throws NoResultException { + return queryOne(resultType, "select x from " + resultType.getSimpleName() + " x where x.id = ?1", id); + } + + public static EntityManager createEntityManager() { + init(false); + return PersistUtilHelper.getEntityManager(); + // return entityManagerFactory.createEntityManager(); + } + + public static void resetDatabase() { + init(true); + } + + public static void init() { + init(false); + } + + public static void shutdown() { + if (PersistUtilHelper.getEntityManagerFactory() != null) + PersistUtilHelper.closeEntityManagerFactory(); + } + + private static void init(boolean resetDatabase) { + if (PersistUtilHelper.getEntityManagerFactory() != null) { + if (!PersistUtilHelper.isOpen()) { + log.warn("entityManagerFactory was closed. Re-initializing"); + PersistUtilHelper.reset(); + } else if (!resetDatabase) { + // entityManagerFactory exists, is open, and a reset is not requested. continue to use existing EMF + return; + } + } + + if (resetDatabase) { + log.info("resetting database"); + } else + log.info("initializing persistence"); + Map properties = new HashMap<>(); + String createMode; + if (resetDatabase) + createMode = "create"; + else + createMode = "update"; + properties.put("hibernate.hbm2ddl.auto", createMode); + properties.put("hibernate.connection.driver_class", ConfigUtil.combined().getString("db.driver")); + properties.put("hibernate.dialect", ConfigUtil.combined().getString("db.dialect")); + properties.put("hibernate.connection.url", ConfigUtil.combined().getString("db.url")); + properties.put("hibernate.connection.username", ConfigUtil.combined().getString("db.username")); + properties.put("hibernate.connection.password", ConfigUtil.combined().getString("db.password")); + properties.put("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy"); + properties.put("hibernate.connection.autocommit", "true"); + properties.put("hibernate.connection.provider_class", "org.hibernate.connection.C3P0ConnectionProvider"); + properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"); + properties.put("hibernate.cache.use_second_level_cache", "true"); + properties.put("hibernate.cache.use_query_cache", "true"); + properties.put("hibernate.c3p0.min_size", "1"); + properties.put("hibernate.c3p0.max_size", ConfigUtil.combined().getString("db.pool.size")); + properties.put("hibernate.c3p0.acquire_increment", ConfigUtil.combined().getString("db.pool.growth")); + properties.put("hibernate.c3p0.idle_test_period", ConfigUtil.combined().getString("db.idle.test.period")); + properties.put("hibernate.c3p0.max_statements", "0"); + properties.put("hibernate.c3p0.timeout", "0"); + properties.put("hibernate.c3p0.preferredTestQuery", "SELECT 1 from exchange"); + properties.put("hibernate.c3p0.maxConnectionAge", ConfigUtil.combined().getString("db.max.connection.age")); + final String testConnection = resetDatabase ? "false" : ConfigUtil.combined().getString("db.test.connection"); + properties.put("hibernate.c3p0.testConnectionOnCheckout", testConnection); + properties.put("hibernate.c3p0.acquireRetryDelay", "1000"); + properties.put("hibernate.c3p0.acquireRetryAttempts", "0"); + properties.put("hibernate.c3p0.breakAfterAcquireFailure", "false"); + properties.put("javax.persistence.sharedCache.mode", "ENABLE_SELECTIVE"); + + try { + PersistUtilHelper emh = new PersistUtilHelper(properties); + ensureSingletonsExist(); + + } catch (Throwable t) { + if (PersistUtilHelper.getEntityManagerFactory() != null) { + PersistUtilHelper.closeEntityManagerFactory(); + + } + throw new Error("Could not initialize db", t); + } + } + + private static void ensureSingletonsExist() { + // Touch the singleton holders + Currencies.BTC.getSymbol(); // this should load all the singletons in Currencies + Exchanges.BITFINEX.getSymbol(); // this should load all the singletons in Exchanges + Prompts.THIS_WEEK.getSymbol(); + } + + //private static EntityManagerFactory entityManagerFactory; + private static final int defaultBatchSize = 20; +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.cryptocoinpartners.util.PersistUtil.createEntityManager` indirectly reads without synchronization from `util.PersistUtilHelper.org.cryptocoinpartners.util.PersistUtilHelper.emf`. Potentially races with write in method `PersistUtil.insert(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +EntityManager PersistUtil.createEntityManager() + +### Procedure Id: +org.cryptocoinpartners.util.PersistUtil.createEntityManager():javax.persistence.EntityManager.30784cb16e6154675f2593fe1cffe967 + +### File: +src/main/java/org/cryptocoinpartners/util/PersistUtil.java + +### Key: +PersistUtil.java|createEntityManager|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +dc9172b9372f7e6fd6091daffa1f3719 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8539/instruction.md b/inferredbugs-8539/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0d7183e186d4b6135dda14c4efaad577eb34a012 --- /dev/null +++ b/inferredbugs-8539/instruction.md @@ -0,0 +1,595 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** xnio +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * JBoss, Home of Professional Open Source. + * Copyright 2012 Red Hat, Inc., and individual contributors + * as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.xnio.nio; + +import static org.xnio.IoUtils.safeClose; +import static org.xnio.nio.Log.log; +import static org.xnio.nio.Log.tcpServerLog; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; +import java.nio.channels.SelectionKey; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.atomic.AtomicLongFieldUpdater; + +import org.jboss.logging.Logger; +import org.xnio.ChannelListener; +import org.xnio.ManagementRegistration; +import org.xnio.IoUtils; +import org.xnio.LocalSocketAddress; +import org.xnio.Option; +import org.xnio.OptionMap; +import org.xnio.Options; +import org.xnio.StreamConnection; +import org.xnio.XnioExecutor; +import org.xnio.channels.AcceptListenerSettable; +import org.xnio.channels.AcceptingChannel; +import org.xnio.channels.UnsupportedOptionException; +import org.xnio.management.XnioServerMXBean; + +final class NioTcpServer extends AbstractNioChannel implements AcceptingChannel, AcceptListenerSettable { + private static final String FQCN = NioTcpServer.class.getName(); + + private volatile ChannelListener acceptListener; + + private final NioTcpServerHandle[] handles; + + private final ServerSocketChannel channel; + private final ServerSocket socket; + private final ManagementRegistration mbeanHandle; + + private static final Set> options = Option.setBuilder() + .add(Options.REUSE_ADDRESSES) + .add(Options.RECEIVE_BUFFER) + .add(Options.SEND_BUFFER) + .add(Options.KEEP_ALIVE) + .add(Options.TCP_OOB_INLINE) + .add(Options.TCP_NODELAY) + .add(Options.CONNECTION_HIGH_WATER) + .add(Options.CONNECTION_LOW_WATER) + .add(Options.READ_TIMEOUT) + .add(Options.WRITE_TIMEOUT) + .create(); + + @SuppressWarnings("unused") + private volatile int keepAlive; + @SuppressWarnings("unused") + private volatile int oobInline; + @SuppressWarnings("unused") + private volatile int tcpNoDelay; + @SuppressWarnings("unused") + private volatile int sendBuffer = -1; + @SuppressWarnings("unused") + private volatile long connectionStatus = CONN_LOW_MASK | CONN_HIGH_MASK; + @SuppressWarnings("unused") + private volatile int readTimeout; + @SuppressWarnings("unused") + private volatile int writeTimeout; + private volatile int tokenConnectionCount; + volatile boolean resumed; + + private static final long CONN_LOW_MASK = 0x000000007FFFFFFFL; + private static final long CONN_LOW_BIT = 0L; + @SuppressWarnings("unused") + private static final long CONN_LOW_ONE = 1L; + private static final long CONN_HIGH_MASK = 0x3FFFFFFF80000000L; + private static final long CONN_HIGH_BIT = 31L; + @SuppressWarnings("unused") + private static final long CONN_HIGH_ONE = 1L << CONN_HIGH_BIT; + + private static final AtomicIntegerFieldUpdater keepAliveUpdater = AtomicIntegerFieldUpdater.newUpdater(NioTcpServer.class, "keepAlive"); + private static final AtomicIntegerFieldUpdater oobInlineUpdater = AtomicIntegerFieldUpdater.newUpdater(NioTcpServer.class, "oobInline"); + private static final AtomicIntegerFieldUpdater tcpNoDelayUpdater = AtomicIntegerFieldUpdater.newUpdater(NioTcpServer.class, "tcpNoDelay"); + private static final AtomicIntegerFieldUpdater sendBufferUpdater = AtomicIntegerFieldUpdater.newUpdater(NioTcpServer.class, "sendBuffer"); + private static final AtomicIntegerFieldUpdater readTimeoutUpdater = AtomicIntegerFieldUpdater.newUpdater(NioTcpServer.class, "readTimeout"); + private static final AtomicIntegerFieldUpdater writeTimeoutUpdater = AtomicIntegerFieldUpdater.newUpdater(NioTcpServer.class, "writeTimeout"); + + private static final AtomicLongFieldUpdater connectionStatusUpdater = AtomicLongFieldUpdater.newUpdater(NioTcpServer.class, "connectionStatus"); + + NioTcpServer(final NioXnioWorker worker, final ServerSocketChannel channel, final OptionMap optionMap) throws IOException { + super(worker); + this.channel = channel; + final WorkerThread[] threads = worker.getAll(); + final int threadCount = threads.length; + if (threadCount == 0) { + throw log.noThreads(); + } + final int tokens = optionMap.get(Options.BALANCING_TOKENS, -1); + final int connections = optionMap.get(Options.BALANCING_CONNECTIONS, 16); + if (tokens != -1) { + if (tokens < 1 || tokens >= threadCount) { + throw log.balancingTokens(); + } + if (connections < 1) { + throw log.balancingConnectionCount(); + } + tokenConnectionCount = connections; + } + socket = channel.socket(); + if (optionMap.contains(Options.SEND_BUFFER)) { + final int sendBufferSize = optionMap.get(Options.SEND_BUFFER, DEFAULT_BUFFER_SIZE); + if (sendBufferSize < 1) { + throw log.parameterOutOfRange("sendBufferSize"); + } + sendBufferUpdater.set(this, sendBufferSize); + } + if (optionMap.contains(Options.KEEP_ALIVE)) { + keepAliveUpdater.lazySet(this, optionMap.get(Options.KEEP_ALIVE, false) ? 1 : 0); + } + if (optionMap.contains(Options.TCP_OOB_INLINE)) { + oobInlineUpdater.lazySet(this, optionMap.get(Options.TCP_OOB_INLINE, false) ? 1 : 0); + } + if (optionMap.contains(Options.TCP_NODELAY)) { + tcpNoDelayUpdater.lazySet(this, optionMap.get(Options.TCP_NODELAY, false) ? 1 : 0); + } + if (optionMap.contains(Options.READ_TIMEOUT)) { + readTimeoutUpdater.lazySet(this, optionMap.get(Options.READ_TIMEOUT, 0)); + } + if (optionMap.contains(Options.WRITE_TIMEOUT)) { + writeTimeoutUpdater.lazySet(this, optionMap.get(Options.WRITE_TIMEOUT, 0)); + } + int perThreadLow, perThreadLowRem; + int perThreadHigh, perThreadHighRem; + if (optionMap.contains(Options.CONNECTION_HIGH_WATER) || optionMap.contains(Options.CONNECTION_LOW_WATER)) { + final int highWater = optionMap.get(Options.CONNECTION_HIGH_WATER, Integer.MAX_VALUE); + final int lowWater = optionMap.get(Options.CONNECTION_LOW_WATER, highWater); + if (highWater <= 0) { + throw badHighWater(); + } + if (lowWater <= 0 || lowWater > highWater) { + throw badLowWater(highWater); + } + final long highLowWater = (long) highWater << CONN_HIGH_BIT | (long) lowWater << CONN_LOW_BIT; + connectionStatusUpdater.lazySet(this, highLowWater); + perThreadLow = lowWater / threadCount; + perThreadLowRem = lowWater % threadCount; + perThreadHigh = highWater / threadCount; + perThreadHighRem = highWater % threadCount; + } else { + perThreadLow = Integer.MAX_VALUE; + perThreadLowRem = 0; + perThreadHigh = Integer.MAX_VALUE; + perThreadHighRem = 0; + connectionStatusUpdater.lazySet(this, CONN_LOW_MASK | CONN_HIGH_MASK); + } + final NioTcpServerHandle[] handles = new NioTcpServerHandle[threadCount]; + for (int i = 0, length = threadCount; i < length; i++) { + final SelectionKey key = threads[i].registerChannel(channel); + handles[i] = new NioTcpServerHandle(this, key, threads[i], i < perThreadHighRem ? perThreadHigh + 1 : perThreadHigh, i < perThreadLowRem ? perThreadLow + 1 : perThreadLow); + key.attach(handles[i]); + } + this.handles = handles; + if (tokens > 0) { + for (int i = 0; i < threadCount; i ++) { + handles[i].initializeTokenCount(i < tokens ? connections : 0); + } + } + mbeanHandle = worker.registerServerMXBean( + new XnioServerMXBean() { + public String getProviderName() { + return "nio"; + } + + public String getWorkerName() { + return worker.getName(); + } + + public String getBindAddress() { + return String.valueOf(getLocalAddress()); + } + + public int getConnectionCount() { + final AtomicInteger counter = new AtomicInteger(); + final CountDownLatch latch = new CountDownLatch(handles.length); + for (final NioTcpServerHandle handle : handles) { + handle.getWorkerThread().execute(() -> { + counter.getAndAdd(handle.getConnectionCount()); + latch.countDown(); + }); + } + try { + latch.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return counter.get(); + } + + public int getConnectionLimitHighWater() { + return getHighWater(connectionStatus); + } + + public int getConnectionLimitLowWater() { + return getLowWater(connectionStatus); + } + } + ); + + } + + private static IllegalArgumentException badLowWater(final int highWater) { + return new IllegalArgumentException("Low water must be greater than 0 and less than or equal to high water (" + highWater + ")"); + } + + private static IllegalArgumentException badHighWater() { + return new IllegalArgumentException("High water must be greater than 0"); + } + + public void close() throws IOException { + try { + channel.close(); + } finally { + for (NioTcpServerHandle handle : handles) { + handle.cancelKey(false); + } + safeClose(mbeanHandle); + } + } + + public boolean supportsOption(final Option option) { + return options.contains(option); + } + + public T getOption(final Option option) throws UnsupportedOptionException, IOException { + if (option == Options.REUSE_ADDRESSES) { + return option.cast(Boolean.valueOf(socket.getReuseAddress())); + } else if (option == Options.RECEIVE_BUFFER) { + return option.cast(Integer.valueOf(socket.getReceiveBufferSize())); + } else if (option == Options.SEND_BUFFER) { + final int value = sendBuffer; + return value == -1 ? null : option.cast(Integer.valueOf(value)); + } else if (option == Options.KEEP_ALIVE) { + return option.cast(Boolean.valueOf(keepAlive != 0)); + } else if (option == Options.TCP_OOB_INLINE) { + return option.cast(Boolean.valueOf(oobInline != 0)); + } else if (option == Options.TCP_NODELAY) { + return option.cast(Boolean.valueOf(tcpNoDelay != 0)); + } else if (option == Options.READ_TIMEOUT) { + return option.cast(Integer.valueOf(readTimeout)); + } else if (option == Options.WRITE_TIMEOUT) { + return option.cast(Integer.valueOf(writeTimeout)); + } else if (option == Options.CONNECTION_HIGH_WATER) { + return option.cast(Integer.valueOf(getHighWater(connectionStatus))); + } else if (option == Options.CONNECTION_LOW_WATER) { + return option.cast(Integer.valueOf(getLowWater(connectionStatus))); + } else { + return null; + } + } + + public T setOption(final Option option, final T value) throws IllegalArgumentException, IOException { + final Object old; + if (option == Options.REUSE_ADDRESSES) { + old = Boolean.valueOf(socket.getReuseAddress()); + socket.setReuseAddress(Options.REUSE_ADDRESSES.cast(value, Boolean.FALSE).booleanValue()); + } else if (option == Options.RECEIVE_BUFFER) { + old = Integer.valueOf(socket.getReceiveBufferSize()); + final int newValue = Options.RECEIVE_BUFFER.cast(value, Integer.valueOf(DEFAULT_BUFFER_SIZE)).intValue(); + if (newValue < 1) { + throw log.optionOutOfRange("RECEIVE_BUFFER"); + } + socket.setReceiveBufferSize(newValue); + } else if (option == Options.SEND_BUFFER) { + final int newValue = Options.SEND_BUFFER.cast(value, Integer.valueOf(DEFAULT_BUFFER_SIZE)).intValue(); + if (newValue < 1) { + throw log.optionOutOfRange("SEND_BUFFER"); + } + final int oldValue = sendBufferUpdater.getAndSet(this, newValue); + old = oldValue == -1 ? null : Integer.valueOf(oldValue); + } else if (option == Options.KEEP_ALIVE) { + old = Boolean.valueOf(keepAliveUpdater.getAndSet(this, Options.KEEP_ALIVE.cast(value, Boolean.FALSE).booleanValue() ? 1 : 0) != 0); + } else if (option == Options.TCP_OOB_INLINE) { + old = Boolean.valueOf(oobInlineUpdater.getAndSet(this, Options.TCP_OOB_INLINE.cast(value, Boolean.FALSE).booleanValue() ? 1 : 0) != 0); + } else if (option == Options.TCP_NODELAY) { + old = Boolean.valueOf(tcpNoDelayUpdater.getAndSet(this, Options.TCP_NODELAY.cast(value, Boolean.FALSE).booleanValue() ? 1 : 0) != 0); + } else if (option == Options.READ_TIMEOUT) { + old = Integer.valueOf(readTimeoutUpdater.getAndSet(this, Options.READ_TIMEOUT.cast(value, Integer.valueOf(0)).intValue())); + } else if (option == Options.WRITE_TIMEOUT) { + old = Integer.valueOf(writeTimeoutUpdater.getAndSet(this, Options.WRITE_TIMEOUT.cast(value, Integer.valueOf(0)).intValue())); + } else if (option == Options.CONNECTION_HIGH_WATER) { + old = Integer.valueOf(getHighWater(updateWaterMark(-1, Options.CONNECTION_HIGH_WATER.cast(value, Integer.valueOf(Integer.MAX_VALUE)).intValue()))); + } else if (option == Options.CONNECTION_LOW_WATER) { + old = Integer.valueOf(getLowWater(updateWaterMark(Options.CONNECTION_LOW_WATER.cast(value, Integer.valueOf(Integer.MAX_VALUE)).intValue(), -1))); + } else { + return null; + } + return option.cast(old); + } + + private long updateWaterMark(int reqNewLowWater, int reqNewHighWater) { + // at least one must be specified + assert reqNewLowWater != -1 || reqNewHighWater != -1; + // if both given, low must be less than high + assert reqNewLowWater == -1 || reqNewHighWater == -1 || reqNewLowWater <= reqNewHighWater; + + long oldVal, newVal; + int oldHighWater, oldLowWater; + int newLowWater, newHighWater; + + do { + oldVal = connectionStatus; + oldLowWater = getLowWater(oldVal); + oldHighWater = getHighWater(oldVal); + newLowWater = reqNewLowWater == -1 ? oldLowWater : reqNewLowWater; + newHighWater = reqNewHighWater == -1 ? oldHighWater : reqNewHighWater; + // Make sure the new values make sense + if (reqNewLowWater != -1 && newLowWater > newHighWater) { + newHighWater = newLowWater; + } else if (reqNewHighWater != -1 && newHighWater < newLowWater) { + newLowWater = newHighWater; + } + // See if the change would be redundant + if (oldLowWater == newLowWater && oldHighWater == newHighWater) { + return oldVal; + } + newVal = (long)newLowWater << CONN_LOW_BIT | (long)newHighWater << CONN_HIGH_BIT; + } while (! connectionStatusUpdater.compareAndSet(this, oldVal, newVal)); + + final NioTcpServerHandle[] conduits = handles; + final int threadCount = conduits.length; + + int perThreadLow, perThreadLowRem; + int perThreadHigh, perThreadHighRem; + + perThreadLow = newLowWater / threadCount; + perThreadLowRem = newLowWater % threadCount; + perThreadHigh = newHighWater / threadCount; + perThreadHighRem = newHighWater % threadCount; + + for (int i = 0; i < conduits.length; i++) { + NioTcpServerHandle conduit = conduits[i]; + conduit.executeSetTask(i < perThreadHighRem ? perThreadHigh + 1 : perThreadHigh, i < perThreadLowRem ? perThreadLow + 1 : perThreadLow); + } + + return oldVal; + } + + private static int getHighWater(final long value) { + return (int) ((value & CONN_HIGH_MASK) >> CONN_HIGH_BIT); + } + + private static int getLowWater(final long value) { + return (int) ((value & CONN_LOW_MASK) >> CONN_LOW_BIT); + } + + public NioSocketStreamConnection accept() throws IOException { + final WorkerThread current = WorkerThread.getCurrent(); + final NioTcpServerHandle handle = handles[current.getNumber()]; + if (! handle.getConnection()) { + return null; + } + final SocketChannel accepted; + boolean ok = false; + try { + accepted = channel.accept(); + if (accepted != null) try { + final SocketAddress localAddress = accepted.getLocalAddress(); + int hash; + if (localAddress instanceof InetSocketAddress) { + final InetSocketAddress address = (InetSocketAddress) localAddress; + hash = address.getAddress().hashCode() * 23 + address.getPort(); + } else if (localAddress instanceof LocalSocketAddress) { + hash = ((LocalSocketAddress) localAddress).getName().hashCode(); + } else { + hash = localAddress.hashCode(); + } + final SocketAddress remoteAddress = accepted.getRemoteAddress(); + if (remoteAddress instanceof InetSocketAddress) { + final InetSocketAddress address = (InetSocketAddress) remoteAddress; + hash = (address.getAddress().hashCode() * 23 + address.getPort()) * 23 + hash; + } else if (remoteAddress instanceof LocalSocketAddress) { + hash = ((LocalSocketAddress) remoteAddress).getName().hashCode() * 23 + hash; + } else { + hash = localAddress.hashCode() * 23 + hash; + } + accepted.configureBlocking(false); + final Socket socket = accepted.socket(); + socket.setKeepAlive(keepAlive != 0); + socket.setOOBInline(oobInline != 0); + socket.setTcpNoDelay(tcpNoDelay != 0); + final int sendBuffer = this.sendBuffer; + if (sendBuffer > 0) socket.setSendBufferSize(sendBuffer); + final WorkerThread ioThread = worker.getIoThread(hash); + final SelectionKey selectionKey = ioThread.registerChannel(accepted); + final NioSocketStreamConnection newConnection = new NioSocketStreamConnection(ioThread, selectionKey, handle); + newConnection.setOption(Options.READ_TIMEOUT, Integer.valueOf(readTimeout)); + newConnection.setOption(Options.WRITE_TIMEOUT, Integer.valueOf(writeTimeout)); + ok = true; + return newConnection; + } finally { + if (! ok) safeClose(accepted); + } + } catch (IOException e) { + return null; + } finally { + if (! ok) { + handle.freeConnection(); + } + } + // by contract, only a resume will do + return null; + } + + public String toString() { + return String.format("TCP server (NIO) <%s>", Integer.toHexString(hashCode())); + } + + public ChannelListener getAcceptListener() { + return acceptListener; + } + + public void setAcceptListener(final ChannelListener acceptListener) { + this.acceptListener = acceptListener; + } + + public ChannelListener.Setter getAcceptSetter() { + return new AcceptListenerSettable.Setter(this); + } + + public boolean isOpen() { + return channel.isOpen(); + } + + public SocketAddress getLocalAddress() { + return socket.getLocalSocketAddress(); + } + + public A getLocalAddress(final Class type) { + final SocketAddress address = getLocalAddress(); + return type.isInstance(address) ? type.cast(address) : null; + } + + public void suspendAccepts() { + resumed = false; + doResume(0); + } + + public void resumeAccepts() { + resumed = true; + doResume(SelectionKey.OP_ACCEPT); + } + + public boolean isAcceptResumed() { + return resumed; + } + + private void doResume(final int op) { + if (op == 0) { + for (NioTcpServerHandle handle : handles) { + handle.suspend(); + } + } else { + for (NioTcpServerHandle handle : handles) { + handle.resume(); + } + } + } + + public void wakeupAccepts() { + tcpServerLog.logf(FQCN, Logger.Level.TRACE, null, "Wake up accepts on %s", this); + resumeAccepts(); + final NioTcpServerHandle[] handles = this.handles; + final int idx = IoUtils.getThreadLocalRandom().nextInt(handles.length); + handles[idx].wakeup(SelectionKey.OP_ACCEPT); + } + + public void awaitAcceptable() throws IOException { + throw log.unsupported("awaitAcceptable"); + } + + public void awaitAcceptable(final long time, final TimeUnit timeUnit) throws IOException { + throw log.unsupported("awaitAcceptable"); + } + + @Deprecated + public XnioExecutor getAcceptThread() { + return getIoThread(); + } + + NioTcpServerHandle getHandle(final int number) { + return handles[number]; + } + + int getTokenConnectionCount() { + return tokenConnectionCount; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `current` last assigned on line 381 could be null and is dereferenced at line 382. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +NioSocketStreamConnection NioTcpServer.accept() + +### Procedure Id: +org.xnio.nio.NioTcpServer.accept():org.xnio.nio.NioSocketStreamConnection.a76f8b6c69f1e95ab044588a79d986e6 + +### File: +nio-impl/src/main/java/org/xnio/nio/NioTcpServer.java + +### Key: +NioTcpServer.java|accept|NULL_DEREFERENCE + +### Node Key: +c50e57c2d19d70f0757cbfc3768d2a96 + +### Hash: +16686e339500400d141e723c216ce2f8 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8552/instruction.md b/inferredbugs-8552/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b29ae738f41520423488df8020f37a911d6beb62 --- /dev/null +++ b/inferredbugs-8552/instruction.md @@ -0,0 +1,414 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** moshi +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2017 Square, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.squareup.moshi; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; + +/** + * This class reads a JSON document by traversing a Java object comprising maps, lists, and JSON + * primitives. It does depth-first traversal keeping a stack starting with the root object. During + * traversal a stack tracks the current position in the document: + * + *
      + *
    • The next element to act upon is on the top of the stack. + *
    • When the top of the stack is a {@link List}, calling {@link #beginArray()} replaces the + * list with a {@link ListIterator}. The first element of the iterator is pushed on top of the + * iterator. + *
    • Similarly, when the top of the stack is a {@link Map}, calling {@link #beginObject()} + * replaces the map with an {@link Iterator} of its entries. The first element of the iterator + * is pushed on top of the iterator. + *
    • When the top of the stack is a {@link Map.Entry}, calling {@link #nextName()} returns the + * entry's key and replaces the entry with its value on the stack. + *
    • When an element is consumed it is popped. If the new top of the stack has a non-exhausted + * iterator, the next element of that iterator is pushed. + *
    • If the top of the stack is an exhausted iterator, calling {@link #endArray} or {@link + * #endObject} will pop it. + *
    + */ +final class ObjectJsonReader extends JsonReader { + /** Sentinel object pushed on {@link #stack} when the reader is closed. */ + private static final Object JSON_READER_CLOSED = new Object(); + + private final Object[] stack = new Object[32]; + + public ObjectJsonReader(Object root) { + scopes[stackSize] = JsonScope.NONEMPTY_DOCUMENT; + stack[stackSize++] = root; + } + + @Override public void beginArray() throws IOException { + List peeked = require(List.class, Token.BEGIN_ARRAY); + + ListIterator iterator = peeked.listIterator(); + stack[stackSize - 1] = iterator; + scopes[stackSize - 1] = JsonScope.EMPTY_ARRAY; + pathIndices[stackSize - 1] = 0; + + // If the iterator isn't empty push its first value onto the stack. + if (iterator.hasNext()) { + push(iterator.next()); + } + } + + @Override public void endArray() throws IOException { + ListIterator peeked = require(ListIterator.class, Token.END_ARRAY); + if (peeked.hasNext()) { + throw typeMismatch(peeked, Token.END_ARRAY); + } + remove(); + } + + @Override public void beginObject() throws IOException { + Map peeked = require(Map.class, Token.BEGIN_OBJECT); + + Iterator iterator = peeked.entrySet().iterator(); + stack[stackSize - 1] = iterator; + scopes[stackSize - 1] = JsonScope.EMPTY_OBJECT; + + // If the iterator isn't empty push its first value onto the stack. + if (iterator.hasNext()) { + push(iterator.next()); + } + } + + @Override public void endObject() throws IOException { + Iterator peeked = require(Iterator.class, Token.END_OBJECT); + if (peeked instanceof ListIterator || peeked.hasNext()) { + throw typeMismatch(peeked, Token.END_OBJECT); + } + pathNames[stackSize - 1] = null; + remove(); + } + + @Override public boolean hasNext() throws IOException { + // TODO(jwilson): this is consistent with BufferedSourceJsonReader but it doesn't make sense. + if (stackSize == 0) return true; + + Object peeked = stack[stackSize - 1]; + return !(peeked instanceof Iterator) || ((Iterator) peeked).hasNext(); + } + + @Override public Token peek() throws IOException { + if (stackSize == 0) return Token.END_DOCUMENT; + + // If the top of the stack is an iterator, take its first element and push it on the stack. + Object peeked = stack[stackSize - 1]; + if (peeked instanceof ListIterator) return Token.END_ARRAY; + if (peeked instanceof Iterator) return Token.END_OBJECT; + if (peeked instanceof List) return Token.BEGIN_ARRAY; + if (peeked instanceof Map) return Token.BEGIN_OBJECT; + if (peeked instanceof Map.Entry) return Token.NAME; + if (peeked instanceof String) return Token.STRING; + if (peeked instanceof Boolean) return Token.BOOLEAN; + if (peeked instanceof Number) return Token.NUMBER; + if (peeked == null) return Token.NULL; + if (peeked == JSON_READER_CLOSED) throw new IllegalStateException("JsonReader is closed"); + + throw typeMismatch(peeked, "a JSON value"); + } + + @Override public String nextName() throws IOException { + Map.Entry peeked = require(Map.Entry.class, Token.NAME); + + // Swap the Map.Entry for its value on the stack and return its key. + String result = stringKey(peeked); + stack[stackSize - 1] = peeked.getValue(); + pathNames[stackSize - 2] = result; + return result; + } + + @Override public int selectName(Options options) throws IOException { + Map.Entry peeked = require(Map.Entry.class, Token.NAME); + String name = stringKey(peeked); + for (int i = 0, length = options.strings.length; i < length; i++) { + // Swap the Map.Entry for its value on the stack and return its key. + if (options.strings[i].equals(name)) { + stack[stackSize - 1] = peeked.getValue(); + pathNames[stackSize - 2] = name; + return i; + } + } + return -1; + } + + @Override public String nextString() throws IOException { + String peeked = require(String.class, Token.STRING); + remove(); + return peeked; + } + + @Override public int selectString(Options options) throws IOException { + String peeked = require(String.class, Token.STRING); + for (int i = 0, length = options.strings.length; i < length; i++) { + if (options.strings[i].equals(peeked)) { + remove(); + return i; + } + } + return -1; + } + + @Override public boolean nextBoolean() throws IOException { + Boolean peeked = require(Boolean.class, Token.BOOLEAN); + remove(); + return peeked; + } + + @Override public T nextNull() throws IOException { + require(Void.class, Token.NULL); + remove(); + return null; + } + + @Override public double nextDouble() throws IOException { + Object peeked = require(Object.class, Token.NUMBER); + + double result; + if (peeked instanceof Number) { + result = ((Number) peeked).doubleValue(); + } else if (peeked instanceof String) { + try { + result = Double.parseDouble((String) peeked); + } catch (NumberFormatException e) { + throw typeMismatch(peeked, Token.NUMBER); + } + } else { + throw typeMismatch(peeked, Token.NUMBER); + } + if (!lenient && (Double.isNaN(result) || Double.isInfinite(result))) { + throw new JsonEncodingException("JSON forbids NaN and infinities: " + result + + " at path " + getPath()); + } + remove(); + return result; + } + + @Override public long nextLong() throws IOException { + Object peeked = require(Object.class, Token.NUMBER); + + long result; + if (peeked instanceof Number) { + result = ((Number) peeked).longValue(); + } else if (peeked instanceof String) { + try { + result = Long.parseLong((String) peeked); + } catch (NumberFormatException e) { + try { + BigDecimal asDecimal = new BigDecimal((String) peeked); + result = asDecimal.longValueExact(); + } catch (NumberFormatException e2) { + throw typeMismatch(peeked, Token.NUMBER); + } + } + } else { + throw typeMismatch(peeked, Token.NUMBER); + } + remove(); + return result; + } + + @Override public int nextInt() throws IOException { + Object peeked = require(Object.class, Token.NUMBER); + + int result; + if (peeked instanceof Number) { + result = ((Number) peeked).intValue(); + } else if (peeked instanceof String) { + try { + result = Integer.parseInt((String) peeked); + } catch (NumberFormatException e) { + try { + BigDecimal asDecimal = new BigDecimal((String) peeked); + result = asDecimal.intValueExact(); + } catch (NumberFormatException e2) { + throw typeMismatch(peeked, Token.NUMBER); + } + } + } else { + throw typeMismatch(peeked, Token.NUMBER); + } + remove(); + return result; + } + + @Override public void skipValue() throws IOException { + if (failOnUnknown) { + throw new JsonDataException("Cannot skip unexpected " + peek() + " at " + getPath()); + } + + // If this element is in an object clear out the key. + if (stackSize > 1) { + pathNames[stackSize - 2] = "null"; + } + + Object skipped = stackSize != 0 ? stack[stackSize - 1] : null; + + if (skipped instanceof Map.Entry) { + // We're skipping a name. Promote the map entry's value. + Map.Entry entry = (Map.Entry) stack[stackSize - 1]; + stack[stackSize - 1] = entry.getValue(); + } else if (stackSize > 0) { + // We're skipping a value. + remove(); + } + } + + @Override void promoteNameToValue() throws IOException { + Map.Entry peeked = require(Map.Entry.class, Token.NAME); + + push(peeked.getKey()); + stack[stackSize - 2] = peeked.getValue(); + } + + @Override public void close() throws IOException { + Arrays.fill(stack, 0, stackSize, null); + stack[0] = JSON_READER_CLOSED; + scopes[0] = JsonScope.CLOSED; + stackSize = 1; + } + + private void push(Object newTop) { + if (stackSize == stack.length) { + throw new JsonDataException("Nesting too deep at " + getPath()); + } + stack[stackSize++] = newTop; + } + + /** + * Returns the top of the stack which is required to be a {@code type}. Throws if this reader is + * closed, or if the type isn't what was expected. + */ + private T require(Class type, Token expected) throws IOException { + Object peeked = (stackSize != 0 ? stack[stackSize - 1] : null); + + if (type.isInstance(peeked)) { + return type.cast(peeked); + } + if (peeked == null && expected == Token.NULL) { + return null; + } + if (peeked == JSON_READER_CLOSED) { + throw new IllegalStateException("JsonReader is closed"); + } + throw typeMismatch(peeked, expected); + } + + private String stringKey(Map.Entry entry) { + Object name = entry.getKey(); + if (name instanceof String) return (String) name; + throw typeMismatch(name, Token.NAME); + } + + /** + * Removes a value and prepares for the next. If we're iterating a map or list this advances the + * iterator. + */ + private void remove() { + stackSize--; + stack[stackSize] = null; + scopes[stackSize] = 0; + + // If we're iterating an array or an object push its next element on to the stack. + if (stackSize > 0) { + pathIndices[stackSize - 1]++; + + Object parent = stack[stackSize - 1]; + if (parent instanceof Iterator && ((Iterator) parent).hasNext()) { + push(((Iterator) parent).next()); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `peeked` last assigned on line 276 could be null and is dereferenced at line 278. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ObjectJsonReader.promoteNameToValue() + +### Procedure Id: +com.squareup.moshi.ObjectJsonReader.promoteNameToValue():void.88297f4309a3953cd801ae9f57a627ef + +### File: +moshi/src/main/java/com/squareup/moshi/ObjectJsonReader.java + +### Key: +ObjectJsonReader.java|promoteNameToValue|NULL_DEREFERENCE + +### Node Key: +93644ec69cbfe39e33422caaa4675eaa + +### Hash: +83d41154322e3afe61b06a1052e2492c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8553/instruction.md b/inferredbugs-8553/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09086c31126797785536e69d916f27afb9c70eef --- /dev/null +++ b/inferredbugs-8553/instruction.md @@ -0,0 +1,408 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** moshi +**Bug ID:** 17 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2015 Square, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.squareup.moshi; + +import okio.Buffer; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + +public final class PromoteNameToValueTest { + @Test public void readerStringValue() throws Exception { + JsonReader reader = newReader("{\"a\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.a"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo("a"); + assertThat(reader.getPath()).isEqualTo("$.a"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.a"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerIntegerValue() throws Exception { + JsonReader reader = newReader("{\"5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextInt()).isEqualTo(5); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerDoubleValue() throws Exception { + JsonReader reader = newReader("{\"5.5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextDouble()).isEqualTo(5.5d); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerBooleanValue() throws Exception { + JsonReader reader = newReader("{\"true\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextBoolean(); + fail(); + } catch (JsonDataException e) { + assertThat(e).hasMessage("Expected a boolean but was STRING at path $.true"); + } + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.nextString()).isEqualTo("true"); + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerLongValue() throws Exception { + JsonReader reader = newReader("{\"5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextLong()).isEqualTo(5L); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerNullValue() throws Exception { + JsonReader reader = newReader("{\"null\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.null"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextNull(); + fail(); + } catch (JsonDataException e) { + assertThat(e).hasMessage("Expected null but was STRING at path $.null"); + } + assertThat(reader.nextString()).isEqualTo("null"); + assertThat(reader.getPath()).isEqualTo("$.null"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.null"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerMultipleValueObject() throws Exception { + JsonReader reader = newReader("{\"a\":1,\"b\":2}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextInt()).isEqualTo(1); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.b"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo("b"); + assertThat(reader.getPath()).isEqualTo("$.b"); + assertThat(reader.nextInt()).isEqualTo(2); + assertThat(reader.getPath()).isEqualTo("$.b"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerEmptyValueObject() throws Exception { + JsonReader reader = newReader("{}"); + reader.beginObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_OBJECT); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$."); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerUnusedPromotionDoesntPersist() throws Exception { + JsonReader reader = newReader("[{},{\"a\":5}]"); + reader.beginArray(); + reader.beginObject(); + reader.promoteNameToValue(); + reader.endObject(); + reader.beginObject(); + try { + reader.nextString(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextName()).isEqualTo("a"); + } + + @Test public void readerUnquotedIntegerValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextInt()).isEqualTo(5); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + @Test public void readerUnquotedLongValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextLong()).isEqualTo(5L); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + @Test public void readerUnquotedDoubleValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextDouble()).isEqualTo(5d); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + private JsonReader newReader(String s) { + return JsonReader.of(new Buffer().writeUtf8(s)); + } + + @Test public void writerStringValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value("a"); + assertThat(writer.getPath()).isEqualTo("$.a"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.a"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"a\":1}"); + } + + @Test public void writerIntegerValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5\":1}"); + } + + @Test public void writerDoubleValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5.5d); + assertThat(writer.getPath()).isEqualTo("$.5.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5.5\":1}"); + } + + @Test public void writerBooleanValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + try { + writer.value(true); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Nesting problem."); + } + writer.value("true"); + assertThat(writer.getPath()).isEqualTo("$.true"); + writer.value(1); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"true\":1}"); + } + + @Test public void writerLongValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5L); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5\":1}"); + } + + @Test public void writerNullValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + try { + writer.nullValue(); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Nesting problem."); + } + writer.value("null"); + assertThat(writer.getPath()).isEqualTo("$.null"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.null"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"null\":1}"); + } + + @Test public void writerMultipleValueObject() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.name("a"); + writer.value(1); + writer.promoteNameToValue(); + writer.value("b"); + assertThat(writer.getPath()).isEqualTo("$.b"); + writer.value(2); + assertThat(writer.getPath()).isEqualTo("$.b"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"a\":1,\"b\":2}"); + } + + @Test public void writerEmptyValueObject() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + assertThat(writer.getPath()).isEqualTo("$."); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{}"); + } + + @Test public void writerUnusedPromotionDoesntPersist() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginArray(); + writer.beginObject(); + writer.promoteNameToValue(); + writer.endObject(); + writer.beginObject(); + try { + writer.value("a"); + fail(); + } catch (IllegalStateException expected) { + } + writer.name("a"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.squareup.moshi.BufferedSourceJsonReader` acquired by call to `newReader(...)` at line 173 is not released after line 180. +**Note**: potential exception at line 175 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PromoteNameToValueTest.readerUnquotedLongValue() + +### Procedure Id: +com.squareup.moshi.PromoteNameToValueTest.readerUnquotedLongValue():void.1737723cad14a79ca8cb0e7df9a42fe0 + +### File: +moshi/src/test/java/com/squareup/moshi/PromoteNameToValueTest.java + +### Key: +PromoteNameToValueTest.java|readerUnquotedLongValue|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +448f6acb9b06f5f237e7ba5da96c4d1f + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8554/instruction.md b/inferredbugs-8554/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..38501d2ffaaae5c8f24f82e9f430e82a13f48fbe --- /dev/null +++ b/inferredbugs-8554/instruction.md @@ -0,0 +1,377 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** moshi +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2015 Square, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.squareup.moshi; + +import okio.Buffer; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + +public final class PromoteNameToValueTest { + @Test public void readerStringValue() throws Exception { + JsonReader reader = newReader("{\"a\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.a"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo("a"); + assertThat(reader.getPath()).isEqualTo("$.a"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.a"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerIntegerValue() throws Exception { + JsonReader reader = newReader("{\"5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextInt()).isEqualTo(5); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerDoubleValue() throws Exception { + JsonReader reader = newReader("{\"5.5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextDouble()).isEqualTo(5.5d); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerBooleanValue() throws Exception { + JsonReader reader = newReader("{\"true\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextBoolean(); + fail(); + } catch (JsonDataException e) { + assertThat(e).hasMessage("Expected a boolean but was STRING at path $.true"); + } + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.nextString()).isEqualTo("true"); + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerLongValue() throws Exception { + JsonReader reader = newReader("{\"5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextLong()).isEqualTo(5L); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerNullValue() throws Exception { + JsonReader reader = newReader("{\"null\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.null"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextNull(); + fail(); + } catch (JsonDataException e) { + assertThat(e).hasMessage("Expected null but was STRING at path $.null"); + } + assertThat(reader.nextString()).isEqualTo("null"); + assertThat(reader.getPath()).isEqualTo("$.null"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.null"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerMultipleValueObject() throws Exception { + JsonReader reader = newReader("{\"a\":1,\"b\":2}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextInt()).isEqualTo(1); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.b"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo("b"); + assertThat(reader.getPath()).isEqualTo("$.b"); + assertThat(reader.nextInt()).isEqualTo(2); + assertThat(reader.getPath()).isEqualTo("$.b"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerEmptyValueObject() throws Exception { + JsonReader reader = newReader("{}"); + reader.beginObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_OBJECT); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$."); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerUnusedPromotionDoesntPersist() throws Exception { + JsonReader reader = new JsonReader(new Buffer().writeUtf8("[{},{\"a\":5}]")); + reader.beginArray(); + reader.beginObject(); + reader.promoteNameToValue(); + reader.endObject(); + reader.beginObject(); + try { + reader.nextString(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextName()).isEqualTo("a"); + } + + private JsonReader newReader(String s) { + return new JsonReader(new Buffer().writeUtf8(s)); + } + + @Test public void writerStringValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value("a"); + assertThat(writer.getPath()).isEqualTo("$.a"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.a"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"a\":1}"); + } + + @Test public void writerIntegerValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5\":1}"); + } + + @Test public void writerDoubleValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5.5d); + assertThat(writer.getPath()).isEqualTo("$.5.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5.5\":1}"); + } + + @Test public void writerBooleanValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + try { + writer.value(true); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Nesting problem."); + } + writer.value("true"); + assertThat(writer.getPath()).isEqualTo("$.true"); + writer.value(1); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"true\":1}"); + } + + @Test public void writerLongValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5L); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5\":1}"); + } + + @Test public void writerNullValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + try { + writer.nullValue(); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Nesting problem."); + } + writer.value("null"); + assertThat(writer.getPath()).isEqualTo("$.null"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.null"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"null\":1}"); + } + + @Test public void writerMultipleValueObject() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.name("a"); + writer.value(1); + writer.promoteNameToValue(); + writer.value("b"); + assertThat(writer.getPath()).isEqualTo("$.b"); + writer.value(2); + assertThat(writer.getPath()).isEqualTo("$.b"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"a\":1,\"b\":2}"); + } + + @Test public void writerEmptyValueObject() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + assertThat(writer.getPath()).isEqualTo("$."); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{}"); + } + + @Test public void writerUnusedPromotionDoesntPersist() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginArray(); + writer.beginObject(); + writer.promoteNameToValue(); + writer.endObject(); + writer.beginObject(); + try { + writer.value("a"); + fail(); + } catch (IllegalStateException expected) { + } + writer.name("a"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `okio.Buffer` acquired by call to `new()` at line 148 is not released after line 148. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PromoteNameToValueTest.readerUnusedPromotionDoesntPersist() + +### Procedure Id: +com.squareup.moshi.PromoteNameToValueTest.readerUnusedPromotionDoesntPersist():void.ff9fbfdc887aa33c33d792718d5dbda4 + +### File: +moshi/src/test/java/com/squareup/moshi/PromoteNameToValueTest.java + +### Key: +PromoteNameToValueTest.java|readerUnusedPromotionDoesntPersist|RESOURCE_LEAK + +### Node Key: +9794f75d6e6f05ee83cf48ce4076a7f0 + +### Hash: +9e695d40288c225900d27002360cff77 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8562/instruction.md b/inferredbugs-8562/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c07bc5ab3e95eae4d012d520242a926b2d02fd4a --- /dev/null +++ b/inferredbugs-8562/instruction.md @@ -0,0 +1,408 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** moshi +**Bug ID:** 12 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2015 Square, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.squareup.moshi; + +import okio.Buffer; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + +public final class PromoteNameToValueTest { + @Test public void readerStringValue() throws Exception { + JsonReader reader = newReader("{\"a\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.a"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo("a"); + assertThat(reader.getPath()).isEqualTo("$.a"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.a"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerIntegerValue() throws Exception { + JsonReader reader = newReader("{\"5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextInt()).isEqualTo(5); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerDoubleValue() throws Exception { + JsonReader reader = newReader("{\"5.5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextDouble()).isEqualTo(5.5d); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerBooleanValue() throws Exception { + JsonReader reader = newReader("{\"true\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextBoolean(); + fail(); + } catch (JsonDataException e) { + assertThat(e).hasMessage("Expected a boolean but was STRING at path $.true"); + } + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.nextString()).isEqualTo("true"); + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerLongValue() throws Exception { + JsonReader reader = newReader("{\"5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextLong()).isEqualTo(5L); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerNullValue() throws Exception { + JsonReader reader = newReader("{\"null\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.null"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextNull(); + fail(); + } catch (JsonDataException e) { + assertThat(e).hasMessage("Expected null but was STRING at path $.null"); + } + assertThat(reader.nextString()).isEqualTo("null"); + assertThat(reader.getPath()).isEqualTo("$.null"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.null"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerMultipleValueObject() throws Exception { + JsonReader reader = newReader("{\"a\":1,\"b\":2}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextInt()).isEqualTo(1); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.b"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo("b"); + assertThat(reader.getPath()).isEqualTo("$.b"); + assertThat(reader.nextInt()).isEqualTo(2); + assertThat(reader.getPath()).isEqualTo("$.b"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerEmptyValueObject() throws Exception { + JsonReader reader = newReader("{}"); + reader.beginObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_OBJECT); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$."); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerUnusedPromotionDoesntPersist() throws Exception { + JsonReader reader = newReader("[{},{\"a\":5}]"); + reader.beginArray(); + reader.beginObject(); + reader.promoteNameToValue(); + reader.endObject(); + reader.beginObject(); + try { + reader.nextString(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextName()).isEqualTo("a"); + } + + @Test public void readerUnquotedIntegerValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextInt()).isEqualTo(5); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + @Test public void readerUnquotedLongValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextLong()).isEqualTo(5L); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + @Test public void readerUnquotedDoubleValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextDouble()).isEqualTo(5d); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + private JsonReader newReader(String s) { + return JsonReader.of(new Buffer().writeUtf8(s)); + } + + @Test public void writerStringValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value("a"); + assertThat(writer.getPath()).isEqualTo("$.a"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.a"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"a\":1}"); + } + + @Test public void writerIntegerValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5\":1}"); + } + + @Test public void writerDoubleValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5.5d); + assertThat(writer.getPath()).isEqualTo("$.5.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5.5\":1}"); + } + + @Test public void writerBooleanValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + try { + writer.value(true); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Nesting problem."); + } + writer.value("true"); + assertThat(writer.getPath()).isEqualTo("$.true"); + writer.value(1); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"true\":1}"); + } + + @Test public void writerLongValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5L); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5\":1}"); + } + + @Test public void writerNullValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + try { + writer.nullValue(); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Nesting problem."); + } + writer.value("null"); + assertThat(writer.getPath()).isEqualTo("$.null"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.null"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"null\":1}"); + } + + @Test public void writerMultipleValueObject() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.name("a"); + writer.value(1); + writer.promoteNameToValue(); + writer.value("b"); + assertThat(writer.getPath()).isEqualTo("$.b"); + writer.value(2); + assertThat(writer.getPath()).isEqualTo("$.b"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"a\":1,\"b\":2}"); + } + + @Test public void writerEmptyValueObject() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + assertThat(writer.getPath()).isEqualTo("$."); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{}"); + } + + @Test public void writerUnusedPromotionDoesntPersist() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginArray(); + writer.beginObject(); + writer.promoteNameToValue(); + writer.endObject(); + writer.beginObject(); + try { + writer.value("a"); + fail(); + } catch (IllegalStateException expected) { + } + writer.name("a"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.squareup.moshi.BufferedSourceJsonReader` acquired by call to `newReader(...)` at line 102 is not released after line 119. +**Note**: potential exception at line 103 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PromoteNameToValueTest.readerNullValue() + +### Procedure Id: +com.squareup.moshi.PromoteNameToValueTest.readerNullValue():void.e5f371e0fceb3c63b025fc1d81da103d + +### File: +moshi/src/test/java/com/squareup/moshi/PromoteNameToValueTest.java + +### Key: +PromoteNameToValueTest.java|readerNullValue|RESOURCE_LEAK + +### Node Key: +95ced91ca0473a6646194f1eb482b307 + +### Hash: +d62b67d8e84efda462cab4ad56145104 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8563/instruction.md b/inferredbugs-8563/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f825c96ec10af9ec76e49bce1cb1a05a979fce36 --- /dev/null +++ b/inferredbugs-8563/instruction.md @@ -0,0 +1,378 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** moshi +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2015 Square, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.squareup.moshi; + +import okio.Buffer; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + +public final class PromoteNameToValueTest { + @Test public void readerStringValue() throws Exception { + JsonReader reader = newReader("{\"a\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.a"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo("a"); + assertThat(reader.getPath()).isEqualTo("$.a"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.a"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerIntegerValue() throws Exception { + JsonReader reader = newReader("{\"5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextInt()).isEqualTo(5); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerDoubleValue() throws Exception { + JsonReader reader = newReader("{\"5.5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextDouble()).isEqualTo(5.5d); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerBooleanValue() throws Exception { + JsonReader reader = newReader("{\"true\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextBoolean(); + fail(); + } catch (JsonDataException e) { + assertThat(e).hasMessage("Expected a boolean but was STRING at path $.true"); + } + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.nextString()).isEqualTo("true"); + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerLongValue() throws Exception { + JsonReader reader = newReader("{\"5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextLong()).isEqualTo(5L); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerNullValue() throws Exception { + JsonReader reader = newReader("{\"null\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.null"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextNull(); + fail(); + } catch (JsonDataException e) { + assertThat(e).hasMessage("Expected null but was STRING at path $.null"); + } + assertThat(reader.nextString()).isEqualTo("null"); + assertThat(reader.getPath()).isEqualTo("$.null"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.null"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerMultipleValueObject() throws Exception { + JsonReader reader = newReader("{\"a\":1,\"b\":2}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextInt()).isEqualTo(1); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.b"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo("b"); + assertThat(reader.getPath()).isEqualTo("$.b"); + assertThat(reader.nextInt()).isEqualTo(2); + assertThat(reader.getPath()).isEqualTo("$.b"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerEmptyValueObject() throws Exception { + JsonReader reader = newReader("{}"); + reader.beginObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_OBJECT); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$."); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerUnusedPromotionDoesntPersist() throws Exception { + JsonReader reader = new JsonReader(new Buffer().writeUtf8("[{},{\"a\":5}]")); + reader.beginArray(); + reader.beginObject(); + reader.promoteNameToValue(); + reader.endObject(); + reader.beginObject(); + try { + reader.nextString(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextName()).isEqualTo("a"); + } + + private JsonReader newReader(String s) { + return new JsonReader(new Buffer().writeUtf8(s)); + } + + @Test public void writerStringValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value("a"); + assertThat(writer.getPath()).isEqualTo("$.a"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.a"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"a\":1}"); + } + + @Test public void writerIntegerValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5\":1}"); + } + + @Test public void writerDoubleValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5.5d); + assertThat(writer.getPath()).isEqualTo("$.5.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5.5\":1}"); + } + + @Test public void writerBooleanValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + try { + writer.value(true); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Nesting problem."); + } + writer.value("true"); + assertThat(writer.getPath()).isEqualTo("$.true"); + writer.value(1); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"true\":1}"); + } + + @Test public void writerLongValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5L); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5\":1}"); + } + + @Test public void writerNullValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + try { + writer.nullValue(); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Nesting problem."); + } + writer.value("null"); + assertThat(writer.getPath()).isEqualTo("$.null"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.null"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"null\":1}"); + } + + @Test public void writerMultipleValueObject() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.name("a"); + writer.value(1); + writer.promoteNameToValue(); + writer.value("b"); + assertThat(writer.getPath()).isEqualTo("$.b"); + writer.value(2); + assertThat(writer.getPath()).isEqualTo("$.b"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"a\":1,\"b\":2}"); + } + + @Test public void writerEmptyValueObject() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + assertThat(writer.getPath()).isEqualTo("$."); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{}"); + } + + @Test public void writerUnusedPromotionDoesntPersist() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = new JsonWriter(buffer); + writer.beginArray(); + writer.beginObject(); + writer.promoteNameToValue(); + writer.endObject(); + writer.beginObject(); + try { + writer.value("a"); + fail(); + } catch (IllegalStateException expected) { + } + writer.name("a"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.squareup.moshi.JsonReader` acquired to `reader` by call to `new()` at line 148 is not released after line 160. +**Note**: potential exception at line 149 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PromoteNameToValueTest.readerUnusedPromotionDoesntPersist() + +### Procedure Id: +com.squareup.moshi.PromoteNameToValueTest.readerUnusedPromotionDoesntPersist():void.ff9fbfdc887aa33c33d792718d5dbda4 + +### File: +moshi/src/test/java/com/squareup/moshi/PromoteNameToValueTest.java + +### Key: +PromoteNameToValueTest.java|readerUnusedPromotionDoesntPersist|RESOURCE_LEAK + +### Node Key: +95ced91ca0473a6646194f1eb482b307 + +### Hash: +51aacd2287280afdd1ce353f8a7ba677 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8564/instruction.md b/inferredbugs-8564/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a6d5770682ada159776b6cdd1f18a4e572896827 --- /dev/null +++ b/inferredbugs-8564/instruction.md @@ -0,0 +1,408 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** moshi +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2015 Square, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.squareup.moshi; + +import okio.Buffer; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + +public final class PromoteNameToValueTest { + @Test public void readerStringValue() throws Exception { + JsonReader reader = newReader("{\"a\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.a"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo("a"); + assertThat(reader.getPath()).isEqualTo("$.a"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.a"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerIntegerValue() throws Exception { + JsonReader reader = newReader("{\"5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextInt()).isEqualTo(5); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerDoubleValue() throws Exception { + JsonReader reader = newReader("{\"5.5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextDouble()).isEqualTo(5.5d); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerBooleanValue() throws Exception { + JsonReader reader = newReader("{\"true\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextBoolean(); + fail(); + } catch (JsonDataException e) { + assertThat(e).hasMessage("Expected a boolean but was STRING at path $.true"); + } + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.nextString()).isEqualTo("true"); + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerLongValue() throws Exception { + JsonReader reader = newReader("{\"5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextLong()).isEqualTo(5L); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerNullValue() throws Exception { + JsonReader reader = newReader("{\"null\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.null"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextNull(); + fail(); + } catch (JsonDataException e) { + assertThat(e).hasMessage("Expected null but was STRING at path $.null"); + } + assertThat(reader.nextString()).isEqualTo("null"); + assertThat(reader.getPath()).isEqualTo("$.null"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.null"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerMultipleValueObject() throws Exception { + JsonReader reader = newReader("{\"a\":1,\"b\":2}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextInt()).isEqualTo(1); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.b"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo("b"); + assertThat(reader.getPath()).isEqualTo("$.b"); + assertThat(reader.nextInt()).isEqualTo(2); + assertThat(reader.getPath()).isEqualTo("$.b"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerEmptyValueObject() throws Exception { + JsonReader reader = newReader("{}"); + reader.beginObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_OBJECT); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$."); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerUnusedPromotionDoesntPersist() throws Exception { + JsonReader reader = newReader("[{},{\"a\":5}]"); + reader.beginArray(); + reader.beginObject(); + reader.promoteNameToValue(); + reader.endObject(); + reader.beginObject(); + try { + reader.nextString(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextName()).isEqualTo("a"); + } + + @Test public void readerUnquotedIntegerValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextInt()).isEqualTo(5); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + @Test public void readerUnquotedLongValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextLong()).isEqualTo(5L); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + @Test public void readerUnquotedDoubleValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextDouble()).isEqualTo(5d); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + private JsonReader newReader(String s) { + return JsonReader.of(new Buffer().writeUtf8(s)); + } + + @Test public void writerStringValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value("a"); + assertThat(writer.getPath()).isEqualTo("$.a"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.a"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"a\":1}"); + } + + @Test public void writerIntegerValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5\":1}"); + } + + @Test public void writerDoubleValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5.5d); + assertThat(writer.getPath()).isEqualTo("$.5.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5.5\":1}"); + } + + @Test public void writerBooleanValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + try { + writer.value(true); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Nesting problem."); + } + writer.value("true"); + assertThat(writer.getPath()).isEqualTo("$.true"); + writer.value(1); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"true\":1}"); + } + + @Test public void writerLongValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5L); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5\":1}"); + } + + @Test public void writerNullValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + try { + writer.nullValue(); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Nesting problem."); + } + writer.value("null"); + assertThat(writer.getPath()).isEqualTo("$.null"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.null"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"null\":1}"); + } + + @Test public void writerMultipleValueObject() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.name("a"); + writer.value(1); + writer.promoteNameToValue(); + writer.value("b"); + assertThat(writer.getPath()).isEqualTo("$.b"); + writer.value(2); + assertThat(writer.getPath()).isEqualTo("$.b"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"a\":1,\"b\":2}"); + } + + @Test public void writerEmptyValueObject() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + assertThat(writer.getPath()).isEqualTo("$."); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{}"); + } + + @Test public void writerUnusedPromotionDoesntPersist() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginArray(); + writer.beginObject(); + writer.promoteNameToValue(); + writer.endObject(); + writer.beginObject(); + try { + writer.value("a"); + fail(); + } catch (IllegalStateException expected) { + } + writer.name("a"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.squareup.moshi.BufferedSourceJsonReader` acquired by call to `newReader(...)` at line 122 is not released after line 135. +**Note**: potential exception at line 123 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PromoteNameToValueTest.readerMultipleValueObject() + +### Procedure Id: +com.squareup.moshi.PromoteNameToValueTest.readerMultipleValueObject():void.bd3ddae489b3902c7ea4e01016183072 + +### File: +moshi/src/test/java/com/squareup/moshi/PromoteNameToValueTest.java + +### Key: +PromoteNameToValueTest.java|readerMultipleValueObject|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +a91e90fb79826b5f18d7a044875de055 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8590/instruction.md b/inferredbugs-8590/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6d0bc609dd72e157c931fe952dcb184cc5c374e8 --- /dev/null +++ b/inferredbugs-8590/instruction.md @@ -0,0 +1,193 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bt +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package bt.bencoding; + +import org.junit.Test; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +public class BEParserTest { + + @Test + public void testParse_String1() { + BEParser parser = new BEParser("1:s"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("s", parser.readString()); + } + + @Test + public void testParse_String2() { + BEParser parser = new BEParser("11:!@#$%^&*()_"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("!@#$%^&*()_", parser.readString()); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_EmptyString() { + new BEParser(""); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_LengthStartsWithZero() { + new BEParser("0:").readString(); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_InsufficientContent() { + new BEParser("7:abcdef").readString(); + } + + @Test + public void testParse_Integer1() { + BEParser parser = new BEParser("i1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE, parser.readInteger()); + } + + @Test + public void testParse_Integer_Negative() { + BEParser parser = new BEParser("i-1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_ZeroLength() { + BEParser parser = new BEParser("ie"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test//(expected = Exception.class) + public void testParse_Integer_Exception_NegativeZero() { + // not sure why the protocol spec forbids negative zeroes, + // so let it be for now + BEParser parser = new BEParser("i-0e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ZERO.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_NotTerminated() { + BEParser parser = new BEParser("i1"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_UnexpectedTokens() { + BEParser parser = new BEParser("i-1-e"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test + public void testParse_List1() { + BEParser parser = new BEParser("l4:spam4:eggsi1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", "eggs", BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_List_ListOfLists() { + BEParser parser = new BEParser("l4:spaml4:spam4:eggsi1eei1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", Arrays.asList("spam", "eggs", BigInteger.ONE), BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_Map1() { + BEParser parser = new BEParser("d4:spaml1:a1:bee"); + assertEquals(BEType.MAP, parser.readType()); + + Map expected = new HashMap<>(); + expected.put("spam", Arrays.asList("a", "b")); + + assertEquals(expected, parser.readMap()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PushbackReader` acquired by call to `BEParser(...)` at line 46 is not released after line 48. +**Note**: potential exception at line 48 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BEParserTest.testParse_Integer1() + +### Procedure Id: +bt.bencoding.BEParserTest.testParse_Integer1():void.cdfb51eebf39cb89ad886f196bc50785 + +### File: +src/test/java/bt/bencoding/BEParserTest.java + +### Key: +BEParserTest.java|testParse_Integer1|RESOURCE_LEAK + +### Node Key: +0c3ef2102c9a4eccc579e7c5e6a2b9c8 + +### Hash: +7594c380c7491ae8542daecfd1c6fcc9 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8591/instruction.md b/inferredbugs-8591/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..39d35357ab471b67acab3aa430e3f4f8d207810f --- /dev/null +++ b/inferredbugs-8591/instruction.md @@ -0,0 +1,193 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bt +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package bt.bencoding; + +import org.junit.Test; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +public class BEParserTest { + + @Test + public void testParse_String1() { + BEParser parser = new BEParser("1:s"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("s", parser.readString()); + } + + @Test + public void testParse_String2() { + BEParser parser = new BEParser("11:!@#$%^&*()_"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("!@#$%^&*()_", parser.readString()); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_EmptyString() { + new BEParser(""); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_LengthStartsWithZero() { + new BEParser("0:").readString(); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_InsufficientContent() { + new BEParser("7:abcdef").readString(); + } + + @Test + public void testParse_Integer1() { + BEParser parser = new BEParser("i1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE, parser.readInteger()); + } + + @Test + public void testParse_Integer_Negative() { + BEParser parser = new BEParser("i-1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_ZeroLength() { + BEParser parser = new BEParser("ie"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test//(expected = Exception.class) + public void testParse_Integer_Exception_NegativeZero() { + // not sure why the protocol spec forbids negative zeroes, + // so let it be for now + BEParser parser = new BEParser("i-0e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ZERO.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_NotTerminated() { + BEParser parser = new BEParser("i1"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_UnexpectedTokens() { + BEParser parser = new BEParser("i-1-e"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test + public void testParse_List1() { + BEParser parser = new BEParser("l4:spam4:eggsi1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", "eggs", BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_List_ListOfLists() { + BEParser parser = new BEParser("l4:spaml4:spam4:eggsi1eei1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", Arrays.asList("spam", "eggs", BigInteger.ONE), BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_Map1() { + BEParser parser = new BEParser("d4:spaml1:a1:bee"); + assertEquals(BEType.MAP, parser.readType()); + + Map expected = new HashMap<>(); + expected.put("spam", Arrays.asList("a", "b")); + + assertEquals(expected, parser.readMap()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PushbackReader` acquired by call to `BEParser(...)` at line 53 is not released after line 55. +**Note**: potential exception at line 55 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BEParserTest.testParse_Integer_Negative() + +### Procedure Id: +bt.bencoding.BEParserTest.testParse_Integer_Negative():void.0779a8b89418abe83968f6fb705d5e8e + +### File: +src/test/java/bt/bencoding/BEParserTest.java + +### Key: +BEParserTest.java|testParse_Integer_Negative|RESOURCE_LEAK + +### Node Key: +20a35cb35a7b0d8f02a62e464233ebb8 + +### Hash: +9c7aa6fa9ac8fdf2f8433d0d4540eb0f + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8596/instruction.md b/inferredbugs-8596/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6bae1a1f1f766253409d7ee6540d40c06dabd1f9 --- /dev/null +++ b/inferredbugs-8596/instruction.md @@ -0,0 +1,193 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bt +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package bt.bencoding; + +import org.junit.Test; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +public class BEParserTest { + + @Test + public void testParse_String1() { + BEParser parser = new BEParser("1:s"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("s", parser.readString()); + } + + @Test + public void testParse_String2() { + BEParser parser = new BEParser("11:!@#$%^&*()_"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("!@#$%^&*()_", parser.readString()); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_EmptyString() { + new BEParser(""); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_LengthStartsWithZero() { + new BEParser("0:").readString(); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_InsufficientContent() { + new BEParser("7:abcdef").readString(); + } + + @Test + public void testParse_Integer1() { + BEParser parser = new BEParser("i1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE, parser.readInteger()); + } + + @Test + public void testParse_Integer_Negative() { + BEParser parser = new BEParser("i-1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_ZeroLength() { + BEParser parser = new BEParser("ie"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test//(expected = Exception.class) + public void testParse_Integer_Exception_NegativeZero() { + // not sure why the protocol spec forbids negative zeroes, + // so let it be for now + BEParser parser = new BEParser("i-0e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ZERO.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_NotTerminated() { + BEParser parser = new BEParser("i1"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_UnexpectedTokens() { + BEParser parser = new BEParser("i-1-e"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test + public void testParse_List1() { + BEParser parser = new BEParser("l4:spam4:eggsi1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", "eggs", BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_List_ListOfLists() { + BEParser parser = new BEParser("l4:spaml4:spam4:eggsi1eei1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", Arrays.asList("spam", "eggs", BigInteger.ONE), BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_Map1() { + BEParser parser = new BEParser("d4:spaml1:a1:bee"); + assertEquals(BEType.MAP, parser.readType()); + + Map expected = new HashMap<>(); + expected.put("spam", Arrays.asList("a", "b")); + + assertEquals(expected, parser.readMap()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PushbackReader` acquired by call to `BEParser(...)` at line 17 is not released after line 17. +**Note**: potential exception at line 17 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BEParserTest.testParse_String1() + +### Procedure Id: +bt.bencoding.BEParserTest.testParse_String1():void.bff10264ef0ce425b6838cacf27cf398 + +### File: +src/test/java/bt/bencoding/BEParserTest.java + +### Key: +BEParserTest.java|testParse_String1|RESOURCE_LEAK + +### Node Key: +f5c23f66aa0be60f5260b2bec3c2ccc6 + +### Hash: +59f655b3cf1beebcab3bc04efecf9b99 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8597/instruction.md b/inferredbugs-8597/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fc7b24c37ff724bed3eb313060e651f2f80d15dd --- /dev/null +++ b/inferredbugs-8597/instruction.md @@ -0,0 +1,193 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bt +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package bt.bencoding; + +import org.junit.Test; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +public class BEParserTest { + + @Test + public void testParse_String1() { + BEParser parser = new BEParser("1:s"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("s", parser.readString()); + } + + @Test + public void testParse_String2() { + BEParser parser = new BEParser("11:!@#$%^&*()_"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("!@#$%^&*()_", parser.readString()); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_EmptyString() { + new BEParser(""); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_LengthStartsWithZero() { + new BEParser("0:").readString(); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_InsufficientContent() { + new BEParser("7:abcdef").readString(); + } + + @Test + public void testParse_Integer1() { + BEParser parser = new BEParser("i1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE, parser.readInteger()); + } + + @Test + public void testParse_Integer_Negative() { + BEParser parser = new BEParser("i-1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_ZeroLength() { + BEParser parser = new BEParser("ie"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test//(expected = Exception.class) + public void testParse_Integer_Exception_NegativeZero() { + // not sure why the protocol spec forbids negative zeroes, + // so let it be for now + BEParser parser = new BEParser("i-0e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ZERO.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_NotTerminated() { + BEParser parser = new BEParser("i1"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_UnexpectedTokens() { + BEParser parser = new BEParser("i-1-e"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test + public void testParse_List1() { + BEParser parser = new BEParser("l4:spam4:eggsi1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", "eggs", BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_List_ListOfLists() { + BEParser parser = new BEParser("l4:spaml4:spam4:eggsi1eei1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", Arrays.asList("spam", "eggs", BigInteger.ONE), BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_Map1() { + BEParser parser = new BEParser("d4:spaml1:a1:bee"); + assertEquals(BEType.MAP, parser.readType()); + + Map expected = new HashMap<>(); + expected.put("spam", Arrays.asList("a", "b")); + + assertEquals(expected, parser.readMap()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PushbackReader` acquired by call to `BEParser(...)` at line 53 is not released after line 53. +**Note**: potential exception at line 53 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BEParserTest.testParse_Integer_Negative() + +### Procedure Id: +bt.bencoding.BEParserTest.testParse_Integer_Negative():void.0779a8b89418abe83968f6fb705d5e8e + +### File: +src/test/java/bt/bencoding/BEParserTest.java + +### Key: +BEParserTest.java|testParse_Integer_Negative|RESOURCE_LEAK + +### Node Key: +f5c23f66aa0be60f5260b2bec3c2ccc6 + +### Hash: +9c7aa6fa9ac8fdf2f8433d0d4540eb0f + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8598/instruction.md b/inferredbugs-8598/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f35b4109df95d165ddc9d20ac7a8d032dc696d48 --- /dev/null +++ b/inferredbugs-8598/instruction.md @@ -0,0 +1,193 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bt +**Bug ID:** 19 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package bt.bencoding; + +import org.junit.Test; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +public class BEParserTest { + + @Test + public void testParse_String1() { + BEParser parser = new BEParser("1:s"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("s", parser.readString()); + } + + @Test + public void testParse_String2() { + BEParser parser = new BEParser("11:!@#$%^&*()_"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("!@#$%^&*()_", parser.readString()); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_EmptyString() { + new BEParser(""); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_LengthStartsWithZero() { + new BEParser("0:").readString(); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_InsufficientContent() { + new BEParser("7:abcdef").readString(); + } + + @Test + public void testParse_Integer1() { + BEParser parser = new BEParser("i1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE, parser.readInteger()); + } + + @Test + public void testParse_Integer_Negative() { + BEParser parser = new BEParser("i-1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_ZeroLength() { + BEParser parser = new BEParser("ie"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test//(expected = Exception.class) + public void testParse_Integer_Exception_NegativeZero() { + // not sure why the protocol spec forbids negative zeroes, + // so let it be for now + BEParser parser = new BEParser("i-0e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ZERO.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_NotTerminated() { + BEParser parser = new BEParser("i1"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_UnexpectedTokens() { + BEParser parser = new BEParser("i-1-e"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test + public void testParse_List1() { + BEParser parser = new BEParser("l4:spam4:eggsi1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", "eggs", BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_List_ListOfLists() { + BEParser parser = new BEParser("l4:spaml4:spam4:eggsi1eei1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", Arrays.asList("spam", "eggs", BigInteger.ONE), BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_Map1() { + BEParser parser = new BEParser("d4:spaml1:a1:bee"); + assertEquals(BEType.MAP, parser.readType()); + + Map expected = new HashMap<>(); + expected.put("spam", Arrays.asList("a", "b")); + + assertEquals(expected, parser.readMap()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PushbackReader` acquired by call to `BEParser(...)` at line 83 is not released after line 85. +**Note**: potential exception at line 85 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BEParserTest.testParse_Integer_Exception_UnexpectedTokens() + +### Procedure Id: +bt.bencoding.BEParserTest.testParse_Integer_Exception_UnexpectedTokens():void.e9d1ab40554db73c7abcd107f262af27 + +### File: +src/test/java/bt/bencoding/BEParserTest.java + +### Key: +BEParserTest.java|testParse_Integer_Exception_UnexpectedTokens|RESOURCE_LEAK + +### Node Key: +0131fec294bdeca06e2199ba6a6be717 + +### Hash: +8ebea885ee3b466a13a4711cd21585b6 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8612/instruction.md b/inferredbugs-8612/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d1692dd30614f8cd019dcaad66f7b706863ad722 --- /dev/null +++ b/inferredbugs-8612/instruction.md @@ -0,0 +1,193 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bt +**Bug ID:** 22 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package bt.bencoding; + +import org.junit.Test; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +public class BEParserTest { + + @Test + public void testParse_String1() { + BEParser parser = new BEParser("1:s"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("s", parser.readString()); + } + + @Test + public void testParse_String2() { + BEParser parser = new BEParser("11:!@#$%^&*()_"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("!@#$%^&*()_", parser.readString()); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_EmptyString() { + new BEParser(""); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_LengthStartsWithZero() { + new BEParser("0:").readString(); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_InsufficientContent() { + new BEParser("7:abcdef").readString(); + } + + @Test + public void testParse_Integer1() { + BEParser parser = new BEParser("i1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE, parser.readInteger()); + } + + @Test + public void testParse_Integer_Negative() { + BEParser parser = new BEParser("i-1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_ZeroLength() { + BEParser parser = new BEParser("ie"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test//(expected = Exception.class) + public void testParse_Integer_Exception_NegativeZero() { + // not sure why the protocol spec forbids negative zeroes, + // so let it be for now + BEParser parser = new BEParser("i-0e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ZERO.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_NotTerminated() { + BEParser parser = new BEParser("i1"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_UnexpectedTokens() { + BEParser parser = new BEParser("i-1-e"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test + public void testParse_List1() { + BEParser parser = new BEParser("l4:spam4:eggsi1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", "eggs", BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_List_ListOfLists() { + BEParser parser = new BEParser("l4:spaml4:spam4:eggsi1eei1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", Arrays.asList("spam", "eggs", BigInteger.ONE), BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_Map1() { + BEParser parser = new BEParser("d4:spaml1:a1:bee"); + assertEquals(BEType.MAP, parser.readType()); + + Map expected = new HashMap<>(); + expected.put("spam", Arrays.asList("a", "b")); + + assertEquals(expected, parser.readMap()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PushbackReader` acquired by call to `BEParser(...)` at line 110 is not released after line 110. +**Note**: potential exception at line 110 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BEParserTest.testParse_Map1() + +### Procedure Id: +bt.bencoding.BEParserTest.testParse_Map1():void.899f0d3aa82d7862b7596d952d12d16e + +### File: +src/test/java/bt/bencoding/BEParserTest.java + +### Key: +BEParserTest.java|testParse_Map1|RESOURCE_LEAK + +### Node Key: +f5c23f66aa0be60f5260b2bec3c2ccc6 + +### Hash: +278ff5e1c14a04f0a39f1620b9126580 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8615/instruction.md b/inferredbugs-8615/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..510ef3521c945fa9f1f67c1259ddd1113c133c90 --- /dev/null +++ b/inferredbugs-8615/instruction.md @@ -0,0 +1,632 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** httl +**Bug ID:** 20 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2011-2013 HTTL Team. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package httl.spi.translators; + +import httl.Engine; +import httl.Node; +import httl.Resource; +import httl.Template; +import httl.internal.util.ClassUtils; +import httl.internal.util.StringSequence; +import httl.internal.util.StringUtils; +import httl.spi.Compiler; +import httl.spi.Converter; +import httl.spi.Filter; +import httl.spi.Formatter; +import httl.spi.Interceptor; +import httl.spi.Logger; +import httl.spi.Parser; +import httl.spi.Switcher; +import httl.spi.Translator; +import httl.spi.translators.templates.AdaptiveTemplate; +import httl.spi.translators.templates.CompiledTemplate; +import httl.spi.translators.templates.CompiledVisitor; + +import java.io.IOException; +import java.io.Reader; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * CompiledTranslator. (SPI, Singleton, ThreadSafe) + * + * @see httl.spi.engines.DefaultEngine#setTranslator(Translator) + * + * @author @author Liang Fei (liangfei0201 AT gmail DOT com) + */ +public class CompiledTranslator implements Translator { + + private String[] forVariable = new String[] { "for" }; + + private String filterVariable = "filter"; + + private String formatterVariable = "formatter"; + + private String defaultFilterVariable; + + private String defaultFormatterVariable; + + private Engine engine; + + private Parser templateParser; + + private Compiler compiler; + + private Interceptor interceptor; + + private Logger logger; + + public void setLogger(Logger logger) { + this.logger = logger; + } + + private Switcher textFilterSwitcher; + + private Switcher valueFilterSwitcher; + + private Switcher> formatterSwitcher; + + private Filter templateFilter; + + private Filter textFilter; + + private Filter valueFilter; + + private Converter mapConverter; + + private Converter outConverter; + + private Formatter formatter; + + private String[] importMacros; + + private final Map importMacroTemplates = new ConcurrentHashMap(); + + private String[] importPackages; + + private Set importPackageSet; + + private String[] importVariables; + + private Map> importTypes; + + private String[] importMethods; + + private final Map, Object> functions = new ConcurrentHashMap, Object>(); + + private final List sequences = new CopyOnWriteArrayList(); + + private static final String TEMPLATE_CLASS_PREFIX = CompiledTemplate.class.getPackage().getName() + ".Template_"; + + private boolean isOutputStream; + + private boolean isOutputWriter; + + private boolean sourceInClass; + + private boolean textInClass; + + private String outputEncoding; + + private Class defaultVariableType; + + private String engineName; + + private String[] importSizers; + + private String[] importGetters; + + /** + * httl.properties: template.parser=httl.spi.parsers.TemplateParser + */ + public void setTemplateParser(Parser parser) { + this.templateParser = parser; + } + + /** + * httl.properties: import.sizers=size,length,getSize,getLength + */ + public void setImportSizers(String[] importSizers) { + this.importSizers = importSizers; + } + + /** + * httl.properties: import.getters=get,getProperty,getAttribute + */ + public void setImportGetters(String[] importGetters) { + this.importGetters = importGetters; + } + + /** + * httl.properties: default.variable.type=java.lang.Object + */ + public void setDefaultVariableType(String defaultVariableType) { + this.defaultVariableType = ClassUtils.forName(defaultVariableType); + } + + /** + * httl.properties: import.macros=common.httl + */ + public void setImportMacros(String[] importMacros) { + this.importMacros = importMacros; + } + + /** + * httl.properties: output.encoding=UTF-8 + */ + public void setOutputEncoding(String outputEncoding) { + this.outputEncoding = outputEncoding; + } + + private static final String HTTL_DEFAULT = "httl.properties"; + + private static final String HTTL_PREFIX = "httl-"; + + private static final String PROPERTIES_SUFFIX = ".properties"; + + /** + * httl.properties: engine=httl.spi.engines.DefaultEngine + */ + public void setEngine(Engine engine) { + this.engine = engine; + } + + /** + * httl.properties: engine.name=httl.properties + */ + public void setEngineName(String name) { + if (HTTL_DEFAULT.equals(name)) { + name = ""; + } else { + if (name.startsWith(HTTL_PREFIX)) { + name = name.substring(HTTL_PREFIX.length()); + } + if (name.endsWith(PROPERTIES_SUFFIX)) { + name = name.substring(0, name.length() - PROPERTIES_SUFFIX.length()); + } + } + this.engineName = name; + } + + /** + * httl.properties: compiler=httl.spi.compilers.JdkCompiler + */ + public void setCompiler(Compiler compiler) { + this.compiler = compiler; + } + + /** + * httl.properties: interceptors=httl.spi.interceptors.ExtendsInterceptor + */ + public void setInterceptor(Interceptor interceptor) { + this.interceptor = interceptor; + } + + /** + * httl.properties: text.filter.switchers=httl.spi.switchers.JavaScriptFilterSwitcher + */ + public void setTextFilterSwitcher(Switcher textFilterSwitcher) { + this.textFilterSwitcher = textFilterSwitcher; + } + + /** + * httl.properties: value.filter.switchers=httl.spi.switchers.JavaScriptFilterSwitcher + */ + public void setValueFilterSwitcher(Switcher valueFilterSwitcher) { + this.valueFilterSwitcher = valueFilterSwitcher; + } + + /** + * httl.properties: formatter.switchers=httl.spi.switchers.NumberFormatterSwitcher + */ + public void setFormatterSwitcher(Switcher> formatterSwitcher) { + this.formatterSwitcher = formatterSwitcher; + } + + /** + * httl.properties: template.filters=httl.spi.filters.CleanBlankLineFilter + */ + public void setTemplateFilter(Filter templateFilter) { + this.templateFilter = templateFilter; + } + + /** + * httl.properties: text.filters=httl.spi.filters.CompressBlankFilter + */ + public void setTextFilter(Filter filter) { + this.textFilter = filter; + } + + /** + * httl.properties: value.filters=httl.spi.filters.EscapeXmlFilter + */ + public void setValueFilter(Filter filter) { + this.valueFilter = filter; + } + + /** + * httl.properties: map.converters=httl.spi.converters.BeanMapConverter + */ + public void setMapConverter(Converter mapConverter) { + this.mapConverter = mapConverter; + } + + /** + * httl.properties: out.converters=httl.spi.converters.ResponseOutConverter + */ + public void setOutConverter(Converter outConverter) { + this.outConverter = outConverter; + } + + /** + * httl.properties: formatters=httl.spi.formatters.DateFormatter + */ + public void setFormatter(Formatter formatter) { + this.formatter = formatter; + } + + /** + * httl.properties: output.stream=true + */ + public void setOutputStream(boolean outputStream) { + this.isOutputStream = outputStream; + } + + /** + * httl.properties: output.writer=true + */ + public void setOutputWriter(boolean outputWriter) { + this.isOutputWriter = outputWriter; + } + + /** + * httl.properties: source.in.class=false + */ + public void setSourceInClass(boolean sourceInClass) { + this.sourceInClass = sourceInClass; + } + + /** + * httl.properties: text.in.class=false + */ + public void setTextInClass(boolean textInClass) { + this.textInClass = textInClass; + } + + /** + * httl.properties: for.variable=for + */ + public void setForVariable(String[] forVariable) { + this.forVariable = forVariable; + } + + /** + * httl.properties: filter.variable=filter + */ + public void setFilterVariable(String filterVariable) { + this.filterVariable = filterVariable; + } + + /** + * httl.properties: formatter.variable=formatter + */ + public void setFormatterVariable(String formatterVariable) { + this.formatterVariable = formatterVariable; + } + + /** + * httl.properties: import.packages=java.util + */ + public void setImportPackages(String[] importPackages) { + this.importPackages = importPackages; + this.importPackageSet = new HashSet(Arrays.asList(importPackages)); + } + + /** + * httl.properties: import.setVariables=javax.servlet.http.HttpServletRequest request + */ + public void setImportVariables(String[] importVariables) { + this.importVariables = importVariables; + } + + /** + * httl.properties: import.methods=java.lang.Math + */ + public void setImportMethods(String[] importMethods) { + this.importMethods = importMethods; + } + + /** + * httl.properties: import.sequences=Mon Tue Wed Thu Fri Sat Sun Mon + */ + public void setImportSequences(String[] sequences) { + for (String s : sequences) { + s = s.trim(); + if (s.length() > 0) { + String[] ts = s.split("\\s+"); + List sequence = new ArrayList(); + for (String t : ts) { + t = t.trim(); + if (t.length() > 0) { + sequence.add(t); + } + } + this.sequences.add(new StringSequence(sequence)); + } + } + } + + /** + * init. + */ + public void init() { + defaultFilterVariable = "$" + filterVariable; + defaultFormatterVariable = "$" + formatterVariable; + if (importVariables != null && importVariables.length > 0) { + this.importTypes = new HashMap>(); + for (String var : importVariables) { + int i = var.lastIndexOf(' '); + if (i < 0) { + throw new IllegalArgumentException("Illegal config import.setVariables"); + } + this.importTypes.put(var.substring(i + 1), ClassUtils.forName(importPackages, var.substring(0, i))); + } + } + if (importMethods != null && importMethods.length > 0) { + for (String method : importMethods) { + Class cls = ClassUtils.forName(importPackages, method); + Object ins; + try { + ins = cls.newInstance(); + } catch (Exception e) { + ins = cls; + } + this.functions.put(cls, ins); + } + } + } + + /** + * inited. + */ + public void inited() { + if (importMacros != null && importMacros.length > 0) { + for (String importMacro : importMacros) { + try { + Template importMacroTemplate = engine.getTemplate(importMacro); + importMacroTemplates.putAll(importMacroTemplate.getMacros()); + } catch (Exception e) { + throw new IllegalStateException(e.getMessage(), e); + } + } + } + } + + public Template translate(Resource resource, Map> defVariableTypes) throws IOException, ParseException { + if (logger != null && logger.isDebugEnabled()) { + logger.debug("Compile template " + resource.getName()); + } + try { + Template writerTemplate = null; + Template streamTemplate = null; + String source = resource.getSource(); + if (templateFilter != null) { + source = templateFilter.filter(resource.getName(), source); + } + Node root = templateParser.parse(source, 0); + if (isOutputWriter || ! isOutputStream) { + Class clazz = parseClass(resource, root, defVariableTypes, false, 0); + writerTemplate = (Template) clazz.getConstructor(Engine.class, Interceptor.class, Compiler.class, Switcher.class, Switcher.class, Filter.class, Formatter.class, Converter.class, Converter.class, Map.class, Map.class, Resource.class, Template.class, Node.class) + .newInstance(engine, interceptor, compiler, valueFilterSwitcher, formatterSwitcher, valueFilter, formatter, mapConverter, outConverter, functions, importMacroTemplates, resource, null, root); + } + if (isOutputStream) { + Class clazz = parseClass(resource, root, defVariableTypes, true, 0); + streamTemplate = (Template) clazz.getConstructor(Engine.class, Interceptor.class, Compiler.class, Switcher.class, Switcher.class, Filter.class, Formatter.class, Converter.class, Converter.class, Map.class, Map.class, Resource.class, Template.class, Node.class) + .newInstance(engine, interceptor, compiler, valueFilterSwitcher, formatterSwitcher, valueFilter, formatter, mapConverter, outConverter, functions, importMacroTemplates, resource, null, root); + } + if (writerTemplate != null && streamTemplate != null) { + return new AdaptiveTemplate(writerTemplate, streamTemplate, outConverter); + } else if (streamTemplate != null) { + return streamTemplate; + } else { + return writerTemplate; + } + } catch (IOException e) { + throw e; + } catch (Exception e) { + ParseException pe; + if (e instanceof ParseException) + pe = (ParseException) e; + else + pe = new ParseException("Failed to parse template: " + resource.getName() + ", cause: " + ClassUtils.toString(e), 0); + if (e.getMessage() != null + && e.getMessage().contains("Occur to offset:")) { + throw pe; + } + int offset = pe.getErrorOffset(); + if (offset <= 0) { + throw pe; + } + String location = null; + try { + Reader reader = resource.getReader(); + try { + location = StringUtils.getLocationMessage(resource.getName(), reader, offset); + } finally { + reader.close(); + } + } catch (Throwable t) { + } + throw new ParseException(e.getMessage() + "\nOccur to offset: " + offset + + (StringUtils.isEmpty(location) ? "" : ", " + location) + + ", stack: " + ClassUtils.toString(e), offset); + } + } + + private String getTemplateClassName(Resource resource, boolean stream) { + String name = resource.getName(); + String encoding = resource.getEncoding(); + Locale locale = resource.getLocale(); + long lastModified = resource.getLastModified(); + StringBuilder buf = new StringBuilder(name.length() + 40); + buf.append(name); + if (engineName != null) { + buf.append("_"); + buf.append(engineName); + } + if (encoding != null) { + buf.append("_"); + buf.append(encoding); + } + if (locale != null) { + buf.append("_"); + buf.append(locale); + } + if (lastModified > 0) { + buf.append("_"); + buf.append(lastModified); + } + buf.append(stream ? "_stream" : "_writer"); + return TEMPLATE_CLASS_PREFIX + StringUtils.getVaildName(buf.toString()); + } + + private Class parseClass(Resource resource, Node root, Map> types, boolean stream, int offset) throws IOException, ParseException { + String name = getTemplateClassName(resource, stream); + try { + return Class.forName(name, true, Thread.currentThread().getContextClassLoader()); + } catch (ClassNotFoundException e) { + if (types == null) { + types = new HashMap>(); + } + CompiledVisitor visitor = new CompiledVisitor(); + visitor.setResource(resource); + visitor.setNode(root); + visitor.setTypes(types); + visitor.setStream(stream); + visitor.setOffset(offset); + visitor.setDefaultFilterVariable(defaultFilterVariable); + visitor.setDefaultFormatterVariable(defaultFormatterVariable); + visitor.setDefaultVariableType(defaultVariableType); + visitor.setEngineName(engineName); + visitor.setFilterVariable(filterVariable); + visitor.setFormatterSwitcher(formatterSwitcher); + visitor.setFormatterVariable(formatterVariable); + visitor.setForVariable(forVariable); + visitor.setImportMacroTemplates(importMacroTemplates); + visitor.setImportPackages(importPackages); + visitor.setImportPackageSet(importPackageSet); + visitor.setImportSizers(importSizers); + visitor.setImportGetters(importGetters); + visitor.setImportTypes(importTypes); + visitor.setImportMethods(functions); + visitor.setImportSequences(sequences); + visitor.setOutputEncoding(outputEncoding); + visitor.setSourceInClass(sourceInClass); + visitor.setTemplateFilter(templateFilter); + visitor.setTextFilter(textFilter); + visitor.setTextFilterSwitcher(textFilterSwitcher); + visitor.setTextInClass(textInClass); + visitor.setValueFilterSwitcher(valueFilterSwitcher); + visitor.setCompiler(compiler); + visitor.init(); + root.accept(visitor); + return visitor.compile(); + } + } + +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `cls` last assigned on line 399 could be null and is dereferenced at line 402. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CompiledTranslator.init() + +### Procedure Id: +httl.spi.translators.CompiledTranslator.init():void.c98e8fdf2e2c5e959d933eab26067073 + +### File: +src/main/java/httl/spi/translators/CompiledTranslator.java + +### Key: +CompiledTranslator.java|init|NULL_DEREFERENCE + +### Node Key: +b74cb9740a7cfd4491509f25814fcf35 + +### Hash: +696949a7e8ed88b882c0a55cb6a90f3c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8702/instruction.md b/inferredbugs-8702/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..190ca3d722610389fb87026063c355700b8ed722 --- /dev/null +++ b/inferredbugs-8702/instruction.md @@ -0,0 +1,302 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** spatial-framework-for-hadoop +**Bug ID:** 43 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.esri.json.hadoop; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; + +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.io.LongWritable; +import org.apache.hadoop.io.Text; +import org.apache.hadoop.mapred.FileSplit; +import org.apache.hadoop.mapred.JobConf; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +public class TestUnenclosedJsonRecordReader { + private UnenclosedJsonRecordReader getReaderFor(String resource, int start, int end) throws IOException { + Path path = new Path(this.getClass().getResource(resource).getFile()); + + JobConf conf = new JobConf(); + + FileSplit split = new FileSplit(path, start, end - start, new String[0]); + + return new UnenclosedJsonRecordReader(split, conf); + } + + int [] getRecordIndexesInReader(UnenclosedJsonRecordReader reader) throws IOException { + return getRecordIndexesInReader(reader, false); + } + + int [] getRecordIndexesInReader(UnenclosedJsonRecordReader reader, boolean flag) throws IOException { + List linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;iThese should not be run under j2cl, because the descriptions don't include the expected stack + * traces there. + * + * @author Pete Gillin + */ +@RunWith(JUnit4.class) +public final class CorrespondenceExceptionStoreTest extends BaseSubjectTestCase { + + @Test + public void hasCompareException_empty() { + Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable(); + assertThat(exceptions.hasCompareException()).isFalse(); + } + + @Test + public void hasCompareException_hasCompareException() { + Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable(); + addCompareException(exceptions); + assertThat(exceptions.hasCompareException()).isTrue(); + } + + @Test + public void describeAsMainCause_empty() { + Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable(); + try { + exceptions.describeAsMainCause(); + fail("Expected IllegalStateException"); + } catch (IllegalStateException expected) { + } + } + + @Test + public void describeAsMainCause_notEmpty() { + Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable(); + addCompareException(exceptions); + assertExpectedFacts( + exceptions.describeAsMainCause().asIterable(), + "one or more exceptions were thrown while comparing elements"); + } + + @Test + public void describeAsAdditionalInfo_empty() { + Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable(); + assertThat(exceptions.describeAsAdditionalInfo().asIterable()).isEmpty(); + } + + @Test + public void describeAsAdditionalInfo_notEmpty() { + Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable(); + addCompareException(exceptions); + assertExpectedFacts( + exceptions.describeAsAdditionalInfo().asIterable(), + "additionally, one or more exceptions were thrown while comparing elements"); + } + + /** Adds a somewhat realistic exception from {@link Correspondence#compare} to the given store. */ + private static void addCompareException(Correspondence.ExceptionStore exceptions) { + try { + boolean unused = TestCorrespondences.WITHIN_10_OF.compare(null, 123); + } catch (RuntimeException e) { + exceptions.addCompareException(CorrespondenceExceptionStoreTest.class, e, null, 123); + } + } + + /** + * Asserts that the given iterable has two facts, the first with the given key and no value, the + * second with a key of {@code "first exception"} and a value describing the exception added by + * {@link #addCompareException}. + */ + private static void assertExpectedFacts(Iterable facts, String expectedFirstKey) { + assertThat(facts).hasSize(2); + Fact first = Iterables.get(facts, 0); + Fact second = Iterables.get(facts, 1); + assertThat(first.key).isEqualTo(expectedFirstKey); + assertThat(first.value).isNull(); + assertThat(second.key).isEqualTo("first exception"); + assertThat(second.value) + .matches( // an initial statement of the method that threw and the exception type: + "compare\\(null, 123\\) threw java.lang.NullPointerException" + // some whitespace: + + "\\s+" + // the start of a stack trace, with the correct class: + + "at com\\.google\\.common\\.truth\\.TestCorrespondences" + // the rest of the stack trace, which we don't validate (and may contain newlines): + + "(.|\\n)*" + // the expected separator + + "\\n---"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `exceptions.firstFormatDiffException` last assigned on line 77 could be null and is dereferenced by call to `describeAsAdditionalInfo()` at line 80. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CorrespondenceExceptionStoreTest.describeAsAdditionalInfo_notEmpty() + +### Procedure Id: +com.google.common.truth.CorrespondenceExceptionStoreTest.describeAsAdditionalInfo_notEmpty():void.6c99077399023d281ea90dc4e6f39606 + +### File: +core/src/test/java/com/google/common/truth/CorrespondenceExceptionStoreTest.java + +### Key: +CorrespondenceExceptionStoreTest.java|describeAsAdditionalInfo_notEmpty|NULL_DEREFERENCE + +### Node Key: +dd4a74aeaaf0a6c2a3a8877464bb9a91 + +### Hash: +3ce9ff125856565dd9dfcb6f8533d40b + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8756/instruction.md b/inferredbugs-8756/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9aee682d634814fa90e62d4568ec41dbc3d59d9b --- /dev/null +++ b/inferredbugs-8756/instruction.md @@ -0,0 +1,373 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** litemall +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.linlinjava.litemall.admin.web; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.linlinjava.litemall.admin.annotation.LoginAdmin; +import org.linlinjava.litemall.admin.dao.GoodsAllinone; +import org.linlinjava.litemall.admin.util.CatVo; +import org.linlinjava.litemall.core.qcode.QCodeService; +import org.linlinjava.litemall.db.domain.*; +import org.linlinjava.litemall.db.service.*; +import org.linlinjava.litemall.core.util.ResponseUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.DefaultTransactionDefinition; +import org.springframework.web.bind.annotation.*; + +import java.time.LocalDateTime; +import java.util.*; + +@RestController +@RequestMapping("/admin/goods") +public class AdminGoodsController { + private final Log logger = LogFactory.getLog(AdminGoodsController.class); + + @Autowired + private PlatformTransactionManager txManager; + + @Autowired + private LitemallGoodsService goodsService; + @Autowired + private LitemallGoodsSpecificationService specificationService; + @Autowired + private LitemallGoodsAttributeService attributeService; + @Autowired + private LitemallProductService productService; + @Autowired + private LitemallCategoryService categoryService; + @Autowired + private LitemallBrandService brandService; + + @Autowired + private QCodeService qCodeService; + + @GetMapping("/list") + public Object list(@LoginAdmin Integer adminId, + String goodsSn, String name, + @RequestParam(value = "page", defaultValue = "1") Integer page, + @RequestParam(value = "limit", defaultValue = "10") Integer limit, + String sort, String order) { + if (adminId == null) { + return ResponseUtil.unlogin(); + } + + List goodsList = goodsService.querySelective(goodsSn, name, page, limit, sort, order); + int total = goodsService.countSelective(goodsSn, name, page, limit, sort, order); + Map data = new HashMap<>(); + data.put("total", total); + data.put("items", goodsList); + + return ResponseUtil.ok(data); + } + + /* + * TODO + * 目前商品修改的逻辑是 + * 1. 更新litemall_goods表 + * 2. 逻辑删除litemall_goods_specification、litemall_goods_attribute、litemall_product + * 3. 添加litemall_goods_specification、litemall_goods_attribute、litemall_product + * + * 这里商品三个表的数据采用删除再跟新的策略是因为 + * 商品编辑页面,管理员可以添加删除商品规格、添加删除商品属性,因此这里仅仅更新表是不可能的, + * 因此这里只能删除所有旧的数据,然后添加新的数据 + */ + @PostMapping("/update") + public Object update(@LoginAdmin Integer adminId, @RequestBody GoodsAllinone goodsAllinone) { + if (adminId == null) { + return ResponseUtil.unlogin(); + } + + LitemallGoods goods = goodsAllinone.getGoods(); + LitemallGoodsAttribute[] attributes = goodsAllinone.getAttributes(); + LitemallGoodsSpecification[] specifications = goodsAllinone.getSpecifications(); + LitemallProduct[] products = goodsAllinone.getProducts(); + + // 开启事务管理 + DefaultTransactionDefinition def = new DefaultTransactionDefinition(); + def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + TransactionStatus status = txManager.getTransaction(def); + try { + + // 商品基本信息表litemall_goods + goodsService.updateById(goods); + + Integer gid = goods.getId(); + specificationService.deleteByGid(gid); + attributeService.deleteByGid(gid); + productService.deleteByGid(gid); + + // 商品规格表litemall_goods_specification + Map specIds = new HashMap<>(); + for (LitemallGoodsSpecification specification : specifications) { + specification.setGoodsId(goods.getId()); + specification.setAddTime(LocalDateTime.now()); + specificationService.add(specification); + specIds.put(specification.getValue(), specification.getId()); + } + + // 商品参数表litemall_goods_attribute + for (LitemallGoodsAttribute attribute : attributes) { + attribute.setGoodsId(goods.getId()); + attribute.setAddTime(LocalDateTime.now()); + attributeService.add(attribute); + } + + // 商品货品表litemall_product + for (LitemallProduct product : products) { + product.setGoodsId(goods.getId()); + product.setAddTime(LocalDateTime.now()); + productService.add(product); + } + } catch (Exception ex) { + txManager.rollback(status); + logger.error("系统内部错误", ex); + } + txManager.commit(status); + + qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName()); + + return ResponseUtil.ok(); + } + + @PostMapping("/delete") + public Object delete(@LoginAdmin Integer adminId, @RequestBody LitemallGoods goods) { + if (adminId == null) { + return ResponseUtil.unlogin(); + } + + // 开启事务管理 + DefaultTransactionDefinition def = new DefaultTransactionDefinition(); + def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + TransactionStatus status = txManager.getTransaction(def); + try { + + Integer gid = goods.getId(); + goodsService.deleteById(gid); + specificationService.deleteByGid(gid); + attributeService.deleteByGid(gid); + productService.deleteByGid(gid); + } catch (Exception ex) { + txManager.rollback(status); + logger.error("系统内部错误", ex); + } + txManager.commit(status); + return ResponseUtil.ok(); + } + + @PostMapping("/create") + public Object create(@LoginAdmin Integer adminId, @RequestBody GoodsAllinone goodsAllinone) { + if (adminId == null) { + return ResponseUtil.unlogin(); + } + + LitemallGoods goods = goodsAllinone.getGoods(); + LitemallGoodsAttribute[] attributes = goodsAllinone.getAttributes(); + LitemallGoodsSpecification[] specifications = goodsAllinone.getSpecifications(); + LitemallProduct[] products = goodsAllinone.getProducts(); + + String name = goods.getName(); + if (goodsService.checkExistByName(name)) { + return ResponseUtil.fail(403, "商品名已经存在"); + } + + // 开启事务管理 + DefaultTransactionDefinition def = new DefaultTransactionDefinition(); + def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + TransactionStatus status = txManager.getTransaction(def); + try { + + // 商品基本信息表litemall_goods + goods.setAddTime(LocalDateTime.now()); + goodsService.add(goods); + + // 商品规格表litemall_goods_specification + Map specIds = new HashMap<>(); + for (LitemallGoodsSpecification specification : specifications) { + specification.setGoodsId(goods.getId()); + specification.setAddTime(LocalDateTime.now()); + specificationService.add(specification); + specIds.put(specification.getValue(), specification.getId()); + } + + // 商品参数表litemall_goods_attribute + for (LitemallGoodsAttribute attribute : attributes) { + attribute.setGoodsId(goods.getId()); + attribute.setAddTime(LocalDateTime.now()); + attributeService.add(attribute); + } + + // 商品货品表litemall_product + for (LitemallProduct product : products) { + product.setGoodsId(goods.getId()); + product.setAddTime(LocalDateTime.now()); + productService.add(product); + } + } catch (Exception ex) { + txManager.rollback(status); + logger.error("系统内部错误", ex); + } + txManager.commit(status); + + + qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName()); + + return ResponseUtil.ok(); + } + + + @GetMapping("/catAndBrand") + public Object list2(@LoginAdmin Integer adminId) { + if (adminId == null) { + return ResponseUtil.unlogin(); + } + + // http://element-cn.eleme.io/#/zh-CN/component/cascader + // 管理员设置“所属分类” + List l1CatList = categoryService.queryL1(); + List categoryList = new ArrayList<>(l1CatList.size()); + + for (LitemallCategory l1 : l1CatList) { + CatVo l1CatVo = new CatVo(); + l1CatVo.setValue(l1.getId()); + l1CatVo.setLabel(l1.getName()); + + List l2CatList = categoryService.queryByPid(l1.getId()); + List children = new ArrayList<>(l2CatList.size()); + for (LitemallCategory l2 : l2CatList) { + CatVo l2CatVo = new CatVo(); + l2CatVo.setValue(l2.getId()); + l2CatVo.setLabel(l2.getName()); + children.add(l2CatVo); + } + l1CatVo.setChildren(children); + + categoryList.add(l1CatVo); + } + + // http://element-cn.eleme.io/#/zh-CN/component/select + // 管理员设置“所属品牌商” + List list = brandService.all(); + List> brandList = new ArrayList<>(l1CatList.size()); + for (LitemallBrand brand : list) { + Map b = new HashMap<>(2); + b.put("value", brand.getId()); + b.put("label", brand.getName()); + brandList.add(b); + } + + Map data = new HashMap<>(); + data.put("categoryList", categoryList); + data.put("brandList", brandList); + return ResponseUtil.ok(data); + } + + @GetMapping("/detail") + public Object detail(@LoginAdmin Integer adminId, Integer id) { + if (adminId == null) { + return ResponseUtil.unlogin(); + } + + if (id == null) { + return ResponseUtil.badArgument(); + } + + LitemallGoods goods = goodsService.findById(id); + List products = productService.queryByGid(id); + List specifications = specificationService.queryByGid(id); + List attributes = attributeService.queryByGid(id); + + Integer categoryId = goods.getCategoryId(); + LitemallCategory category = categoryService.findById(categoryId); + Integer[] categoryIds = new Integer[]{}; + if (category != null) { + Integer parentCategoryId = category.getPid(); + categoryIds = new Integer[]{parentCategoryId, categoryId}; + } + + Map data = new HashMap<>(); + data.put("goods", goods); + data.put("specifications", specifications); + data.put("products", products); + data.put("attributes", attributes); + data.put("categoryIds", categoryIds); + + return ResponseUtil.ok(data); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `goods.getId()` could be null and is dereferenced at line 129. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object AdminGoodsController.update(Integer,GoodsAllinone) + +### Procedure Id: +org.linlinjava.litemall.admin.web.AdminGoodsController.update(java.lang.Integer,org.linlinjava.litem.b6b11888faa7c5109f3f2e7c6ca2d623 + +### File: +litemall-admin-api/src/main/java/org/linlinjava/litemall/admin/web/AdminGoodsController.java + +### Key: +AdminGoodsController.java|update|NULL_DEREFERENCE + +### Node Key: +42f56fda1ad408e362508b93a175bb0c + +### Hash: +4495b7cad7c5703d28ae69fec5cc3cc7 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8757/instruction.md b/inferredbugs-8757/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f51416d23980654795636c2496d730a24fcd4ceb --- /dev/null +++ b/inferredbugs-8757/instruction.md @@ -0,0 +1,157 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** google-auth-library-java +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2015, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * 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. + * + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT + * OWNER 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. + */ + +package com.google.auth.oauth2; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.lang.Runnable; +import java.lang.Thread; +import java.net.ServerSocket; +import java.net.Socket; + +/** + * Unit tests for CloudShellCredentials + */ +@RunWith(JUnit4.class) +public class CloudShellCredentialsTest { + + @Test + public void refreshAccessToken() throws IOException{ + final ServerSocket authSocket = new ServerSocket(0); + Runnable serverTask = new Runnable() { + @Override + public void run() { + try { + Socket clientSocket = authSocket.accept(); + BufferedReader input = + new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + String lines = input.readLine(); + lines += '\n' + input.readLine(); + assertEquals(lines, CloudShellCredentials.GET_AUTH_TOKEN_REQUEST); + + PrintWriter out = + new PrintWriter(clientSocket.getOutputStream(), true); + out.println("32\n[\"email\", \"project-id\", \"token\"]"); + } catch (Exception reThrown) { + throw new RuntimeException(reThrown); + } + } + }; + Thread serverThread = new Thread(serverTask); + serverThread.start(); + + GoogleCredentials creds = new CloudShellCredentials(authSocket.getLocalPort()); + assertEquals("token", creds.refreshAccessToken().getTokenValue()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.net.ServerSocket` acquired to `authSocket` by call to `new()` at line 57 is not released after line 80. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CloudShellCredentialsTest.refreshAccessToken() + +### Procedure Id: +com.google.auth.oauth2.CloudShellCredentialsTest.refreshAccessToken():void.fab4023266b7d8f6b2c1ca327f8f6e4c + +### File: +oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java + +### Key: +CloudShellCredentialsTest.java|refreshAccessToken|RESOURCE_LEAK + +### Node Key: +e5141fc1d7885ecafc62b960d3352f3f + +### Hash: +fffb65afe41023e9693888c311efe19d + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8758/instruction.md b/inferredbugs-8758/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ba03769b5fee23149195548a79a084b15504b119 --- /dev/null +++ b/inferredbugs-8758/instruction.md @@ -0,0 +1,240 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** google-auth-library-java +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2015, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * 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. + * + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT + * OWNER 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. + */ + +package com.google.auth.oauth2; + +import com.google.api.client.json.JsonParser; +import com.google.common.base.MoreObjects; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.Socket; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * OAuth2 credentials representing the built-in service account for Google Cloud Shell. + */ +public class CloudShellCredentials extends GoogleCredentials { + + private static final long serialVersionUID = -2133257318957488451L; + private static final int ACCESS_TOKEN_INDEX = 2; + private static final int READ_TIMEOUT_MS = 5000; + + /** + * The Cloud Shell back authorization channel uses serialized + * Javascript Protobufers, preceeded by the message length and a + * new line character. However, the request message has no content, + * so a token request consists of an empty JsPb, and its 2 character + * lenth prefix. + */ + protected final static String GET_AUTH_TOKEN_REQUEST = "2\n[]"; + + private final int authPort; + + /** + * @param authPort Authentication port. + * @return The CloudShellCredentials. + * @deprecated Use {@link #create(int)} instead. This method will be deleted in a later version. + */ + @Deprecated + public static CloudShellCredentials of(int authPort) { + return create(authPort); + } + + public static CloudShellCredentials create(int authPort) { + return CloudShellCredentials.newBuilder().setAuthPort(authPort).build(); + } + + /** + * @param authPort Authentication port. + * @deprecated Use {@link #create(int)} instead. This constructor will either be deleted or + * made private in a later version. + */ + @Deprecated + public CloudShellCredentials(int authPort) { + this.authPort = authPort; + } + + protected int getAuthPort() { + return this.authPort; + } + + @Override + public AccessToken refreshAccessToken() throws IOException { + Socket socket = new Socket("localhost", this.getAuthPort()); + socket.setSoTimeout(READ_TIMEOUT_MS); + AccessToken token; + try { + PrintWriter out = + new PrintWriter(socket.getOutputStream(), true); + out.println(GET_AUTH_TOKEN_REQUEST); + + BufferedReader input = + new BufferedReader(new InputStreamReader(socket.getInputStream())); + input.readLine(); // Skip over the first line + JsonParser parser = OAuth2Utils.JSON_FACTORY.createJsonParser(input); + List messageArray = (List) parser.parseArray(ArrayList.class, Object.class); + String accessToken = messageArray.get(ACCESS_TOKEN_INDEX).toString(); + token = new AccessToken(accessToken, null); + } finally { + socket.close(); + } + return token; + } + + @Override + public int hashCode() { + return Objects.hash(authPort); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this).add("authPort", authPort).toString(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof CloudShellCredentials)) { + return false; + } + CloudShellCredentials other = (CloudShellCredentials) obj; + return this.authPort == other.authPort; + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static Builder newBuilder() { + return new Builder(); + } + + public static class Builder extends GoogleCredentials.Builder { + private int authPort; + + protected Builder() {} + + protected Builder(CloudShellCredentials credentials) { + this.authPort = credentials.authPort; + } + + public Builder setAuthPort(int authPort) { + this.authPort = authPort; + return this; + } + + public int getAuthPort() { + return authPort; + } + + public CloudShellCredentials build() { + return new CloudShellCredentials(authPort); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 105 is not released after line 107. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +AccessToken CloudShellCredentials.refreshAccessToken() + +### Procedure Id: +com.google.auth.oauth2.CloudShellCredentials.refreshAccessToken():com.google.auth.oauth2.AccessToken.4cab98e0690f877901699d2f21d20d53 + +### File: +oauth2_http/java/com/google/auth/oauth2/CloudShellCredentials.java + +### Key: +CloudShellCredentials.java|refreshAccessToken|RESOURCE_LEAK + +### Node Key: +241d42dae50053d7648ace8f5b7dfc3f + +### Hash: +00341b14514a72be1fa67072274ea8d6 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8759/instruction.md b/inferredbugs-8759/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ebe040ba697899634c26c63d60ae7317834123bf --- /dev/null +++ b/inferredbugs-8759/instruction.md @@ -0,0 +1,400 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** google-auth-library-java +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2015, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * 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. + * + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT + * OWNER 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. + */ + +package com.google.auth.oauth2; + +import com.google.api.client.util.Clock; +import com.google.auth.Credentials; +import com.google.auth.RequestMetadataCallback; +import com.google.auth.http.AuthHttpConstants; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.MoreObjects; +import com.google.common.base.MoreObjects.ToStringHelper; +import com.google.common.base.Preconditions; +import com.google.common.collect.Iterables; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.ServiceLoader; +import java.util.concurrent.Executor; + +/** + * Base type for Credentials using OAuth2. + */ +public class OAuth2Credentials extends Credentials { + + private static final long serialVersionUID = 4556936364828217687L; + private static final long MINIMUM_TOKEN_MILLISECONDS = 60000L * 5L; + + // byte[] is serializable, so the lock variable can be final + private final Object lock = new byte[0]; + private Map> requestMetadata; + private AccessToken temporaryAccess; + + // Change listeners are not serialized + private transient List changeListeners; + // Until we expose this to the users it can remain transient and non-serializable + @VisibleForTesting + transient Clock clock = Clock.SYSTEM; + + /** + * Returns the credentials instance from the given access token. + * + * @param accessToken the access token + * @return the credentials instance + */ + public static OAuth2Credentials of(AccessToken accessToken) { + return OAuth2Credentials.newBuilder().setAccessToken(accessToken).build(); + } + + /** + * Default constructor. + **/ + protected OAuth2Credentials() { + this(null); + } + + /** + * Constructor with explicit access token. + * + * @param accessToken Initial or temporary access token. + **/ + @Deprecated + public OAuth2Credentials(AccessToken accessToken) { + if (accessToken != null) { + useAccessToken(accessToken); + } + } + + @Override + public String getAuthenticationType() { + return "OAuth2"; + } + + @Override + public boolean hasRequestMetadata() { + return true; + } + + @Override + public boolean hasRequestMetadataOnly() { + return true; + } + + public final AccessToken getAccessToken() { + return temporaryAccess; + } + + @Override + public void getRequestMetadata(final URI uri, Executor executor, + final RequestMetadataCallback callback) { + Map> metadata; + synchronized(lock) { + if (shouldRefresh()) { + // The base class implementation will do a blocking get in the executor. + super.getRequestMetadata(uri, executor, callback); + return; + } + metadata = Preconditions.checkNotNull(requestMetadata, "cached requestMetadata"); + } + callback.onSuccess(metadata); + } + + /** + * Provide the request metadata by ensuring there is a current access token and providing it + * as an authorization bearer token. + */ + @Override + public Map> getRequestMetadata(URI uri) throws IOException { + synchronized(lock) { + if (shouldRefresh()) { + refresh(); + } + return Preconditions.checkNotNull(requestMetadata, "requestMetadata"); + } + } + + /** + * Refresh the token by discarding the cached token and metadata and requesting the new ones. + */ + @Override + public void refresh() throws IOException { + synchronized(lock) { + requestMetadata = null; + temporaryAccess = null; + useAccessToken(Preconditions.checkNotNull(refreshAccessToken(), "new access token")); + if (changeListeners != null) { + for (CredentialsChangedListener listener : changeListeners) { + listener.onChanged(this); + } + } + } + } + + // Must be called under lock + private void useAccessToken(AccessToken token) { + this.temporaryAccess = token; + this.requestMetadata = Collections.singletonMap( + AuthHttpConstants.AUTHORIZATION, + Collections.singletonList(OAuth2Utils.BEARER_PREFIX + token.getTokenValue())); + } + + // Must be called under lock + // requestMetadata will never be null if false is returned. + private boolean shouldRefresh() { + Long expiresIn = getExpiresInMilliseconds(); + return requestMetadata == null || expiresIn != null && expiresIn <= MINIMUM_TOKEN_MILLISECONDS; + } + + /** + * Method to refresh the access token according to the specific type of credentials. + * + * Throws IllegalStateException if not overridden since direct use of OAuth2Credentials is only + * for temporary or non-refreshing access tokens. + * + * @throws IOException from derived implementations + */ + public AccessToken refreshAccessToken() throws IOException { + throw new IllegalStateException("OAuth2Credentials instance does not support refreshing the" + + " access token. An instance with a new access token should be used, or a derived type" + + " that supports refreshing."); + } + + /** + * Adds a listener that is notified when the Credentials data changes. + * + *

    This is called when token content changes, such as when the access token is refreshed. This + * is typically used by code caching the access token. + * + * @param listener The listener to be added. + */ + public final void addChangeListener(CredentialsChangedListener listener) { + synchronized(lock) { + if (changeListeners == null) { + changeListeners = new ArrayList<>(); + } + changeListeners.add(listener); + } + } + + /** + * Return the remaining time the current access token will be valid, or null if there is no + * token or expiry information. Must be called under lock. + */ + private Long getExpiresInMilliseconds() { + if (temporaryAccess == null) { + return null; + } + Date expirationTime = temporaryAccess.getExpirationTime(); + if (expirationTime == null) { + return null; + } + return (expirationTime.getTime() - clock.currentTimeMillis()); + } + + /** + * Listener for changes to credentials. + * + *

    This is called when token content changes, such as when the access token is refreshed. This + * is typically used by code caching the access token. + */ + public interface CredentialsChangedListener { + + /** + * Notifies that the credentials have changed. + * + *

    This is called when token content changes, such as when the access token is refreshed. + * This is typically used by code caching the access token. + * + * @param credentials The updated credentials instance + * @throws IOException My be thrown by listeners if saving credentials fails. + */ + void onChanged(OAuth2Credentials credentials) throws IOException; + } + + @Override + public int hashCode() { + return Objects.hash(requestMetadata, temporaryAccess); + } + + protected ToStringHelper toStringHelper() { + return MoreObjects.toStringHelper(this) + .add("requestMetadata", requestMetadata) + .add("temporaryAccess", temporaryAccess); + } + + @Override + public String toString() { + return toStringHelper().toString(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof OAuth2Credentials)) { + return false; + } + OAuth2Credentials other = (OAuth2Credentials) obj; + return Objects.equals(this.requestMetadata, other.requestMetadata) + && Objects.equals(this.temporaryAccess, other.temporaryAccess); + } + + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + clock = Clock.SYSTEM; + } + + @SuppressWarnings("unchecked") + protected static T newInstance(String className) throws IOException, ClassNotFoundException { + try { + return (T) Class.forName(className).newInstance(); + } catch (InstantiationException | IllegalAccessException e) { + throw new IOException(e); + } + } + + protected static T getFromServiceLoader(Class clazz, T defaultInstance) { + return Iterables.getFirst(ServiceLoader.load(clazz), defaultInstance); + } + + public static Builder newBuilder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static class Builder { + + private AccessToken accessToken; + + protected Builder() {} + + protected Builder(OAuth2Credentials credentials) { + this.accessToken = credentials.getAccessToken(); + } + + public Builder setAccessToken(AccessToken token) { + this.accessToken = token; + return this; + } + + public AccessToken getAccessToken() { + return accessToken; + } + + public OAuth2Credentials build() { + return new OAuth2Credentials(accessToken); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.google.auth.oauth2.OAuth2Credentials.toString` indirectly reads without synchronization from `this.com.google.auth.oauth2.OAuth2Credentials.requestMetadata`. Potentially races with write in method `OAuth2Credentials.refresh()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String OAuth2Credentials.toString() + +### Procedure Id: +com.google.auth.oauth2.OAuth2Credentials.toString():java.lang.String.810672b8384d4bacb6295d751bd8f56e + +### File: +oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java + +### Key: +OAuth2Credentials.java|toString|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +a5796060fefac47b0ab5ee26998b092e + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8760/instruction.md b/inferredbugs-8760/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..963dff53c0346b000d79352eda130bf35de3635f --- /dev/null +++ b/inferredbugs-8760/instruction.md @@ -0,0 +1,245 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** google-auth-library-java +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.google.auth.oauth2; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; + +import com.google.auth.TestClock; +import com.google.auth.TestUtils; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; +import java.net.URI; +import java.util.Map; +import java.util.List; + +/** + * Test case for {@link OAuth2Credentials}. + */ +@RunWith(JUnit4.class) +public class OAuth2CredentialsTest { + + private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; + private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; + private static final String REFRESH_TOKEN = "1/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; + private static final String ACCESS_TOKEN = "aashpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; + private static final URI CALL_URI = URI.create("http://googleapis.com/testapi/v1/foo"); + + @Test + public void constructor_storesAccessToken() { + OAuth2Credentials credentials = new OAuth2Credentials(new AccessToken(ACCESS_TOKEN, null)); + + assertEquals(credentials.getAccessToken().getTokenValue(), ACCESS_TOKEN); + } + + @Test + public void getAuthenticationType_returnsOAuth2() { + OAuth2Credentials credentials = new UserCredentials(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN); + assertEquals(credentials.getAuthenticationType(), "OAuth2"); + } + + @Test + public void hasRequestMetadata_returnsTrue() { + OAuth2Credentials credentials = new UserCredentials(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN); + assertTrue(credentials.hasRequestMetadata()); + } + + @Test + public void hasRequestMetadataOnly_returnsTrue() { + OAuth2Credentials credentials = new UserCredentials(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN); + assertTrue(credentials.hasRequestMetadata()); + } + + @Test + public void addaddChangeListener_notifiesOnRefresh() throws IOException { + final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; + final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; + MockTokenServerTransport transport = new MockTokenServerTransport(); + transport.addClient(CLIENT_ID, CLIENT_SECRET); + transport.addRefreshToken(REFRESH_TOKEN, accessToken1); + OAuth2Credentials userCredentials = new UserCredentials( + CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, transport, null); + // Use a fixed clock so tokens don't expire + userCredentials.clock = new TestClock(); + TestChangeListener listener = new TestChangeListener(); + userCredentials.addChangeListener(listener); + Map> metadata; + assertEquals(0, listener.callCount); + + // Get a first token + metadata = userCredentials.getRequestMetadata(CALL_URI); + TestUtils.assertContainsBearerToken(metadata, accessToken1); + assertEquals(accessToken1, listener.accessToken.getTokenValue()); + assertEquals(1, listener.callCount); + + // Change server to a different token and refresh + transport.addRefreshToken(REFRESH_TOKEN, accessToken2); + // Refresh to force getting next token + userCredentials.refresh(); + + metadata = userCredentials.getRequestMetadata(CALL_URI); + TestUtils.assertContainsBearerToken(metadata, accessToken2); + assertEquals(accessToken2, listener.accessToken.getTokenValue()); + assertEquals(2, listener.callCount); + } + + @Test + public void getRequestMetadata_cachesExpiringToken() throws IOException { + final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; + final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; + MockTokenServerTransport transport = new MockTokenServerTransport(); + transport.addClient(CLIENT_ID, CLIENT_SECRET); + transport.addRefreshToken(REFRESH_TOKEN, accessToken1); + TestClock clock = new TestClock(); + OAuth2Credentials credentials = new UserCredentials( + CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, transport, null); + credentials.clock = clock; + + // Verify getting the first token + Map> metadata = credentials.getRequestMetadata(CALL_URI); + TestUtils.assertContainsBearerToken(metadata, accessToken1); + + // Change server to a different token + transport.addRefreshToken(REFRESH_TOKEN, accessToken2); + + // Advance 5 minutes and verify original token + clock.addToCurrentTime(5 * 60 * 1000); + metadata = credentials.getRequestMetadata(CALL_URI); + TestUtils.assertContainsBearerToken(metadata, accessToken1); + + // Advance 60 minutes and verify revised token + clock.addToCurrentTime(60 * 60 * 1000); + metadata = credentials.getRequestMetadata(CALL_URI); + TestUtils.assertContainsBearerToken(metadata, accessToken2); + } + + @Test + public void getRequestMetadata_temporaryToken_hasToken() throws IOException { + OAuth2Credentials credentials = new OAuth2Credentials(new AccessToken(ACCESS_TOKEN, null)); + + // Verify getting the first token + Map> metadata = credentials.getRequestMetadata(CALL_URI); + TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); + } + + @Test + public void refresh_refreshesToken() throws IOException { + final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; + final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; + MockTokenServerTransport transport = new MockTokenServerTransport(); + transport.addClient(CLIENT_ID, CLIENT_SECRET); + transport.addRefreshToken(REFRESH_TOKEN, accessToken1); + OAuth2Credentials userCredentials = new UserCredentials( + CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, transport, null); + // Use a fixed clock so tokens don't exire + userCredentials.clock = new TestClock(); + + // Get a first token + Map> metadata = userCredentials.getRequestMetadata(CALL_URI); + TestUtils.assertContainsBearerToken(metadata, accessToken1); + + // Change server to a different token + transport.addRefreshToken(REFRESH_TOKEN, accessToken2); + + // Confirm token being cached + TestUtils.assertContainsBearerToken(metadata, accessToken1); + + // Refresh to force getting next token + userCredentials.refresh(); + metadata = userCredentials.getRequestMetadata(CALL_URI); + TestUtils.assertContainsBearerToken(metadata, accessToken2); + } + + @Test(expected = IllegalStateException.class) + public void refresh_temporaryToken_throws() throws IOException { + OAuth2Credentials credentials = new OAuth2Credentials(new AccessToken(ACCESS_TOKEN, null)); + credentials.refresh(); + } + + private static class TestChangeListener implements OAuth2Credentials.CredentialsChangedListener { + + public AccessToken accessToken = null; + public int callCount = 0; + @Override + public void onChanged(OAuth2Credentials credentials) throws IOException { + accessToken = credentials.getAccessToken(); + callCount++; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `userCredentials.temporaryAccess` last assigned on line 134 could be null and is dereferenced by call to `getRequestMetadata(...)` at line 140. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void OAuth2CredentialsTest.refresh_refreshesToken() + +### Procedure Id: +com.google.auth.oauth2.OAuth2CredentialsTest.refresh_refreshesToken():void.ac0764c6189a974b1053d7d92c19ba21 + +### File: +oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java + +### Key: +OAuth2CredentialsTest.java|refresh_refreshesToken|NULL_DEREFERENCE + +### Node Key: +6f964b7de486c86cfccf06970ed8431d + +### Hash: +9418471a81138710ef0b5c4fa6a959f3 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8761/instruction.md b/inferredbugs-8761/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f054674ce192f208f33b3a8ad63c9c50d0121bdd --- /dev/null +++ b/inferredbugs-8761/instruction.md @@ -0,0 +1,241 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** google-auth-library-java +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2015, Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * 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. + * + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT + * OWNER 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. + */ + +package com.google.auth.oauth2; + +import com.google.api.client.json.JsonParser; +import com.google.common.base.MoreObjects; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.Socket; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * OAuth2 credentials representing the built-in service account for Google Cloud Shell. + */ +public class CloudShellCredentials extends GoogleCredentials { + + private static final long serialVersionUID = -2133257318957488451L; + private static final int ACCESS_TOKEN_INDEX = 2; + private static final int READ_TIMEOUT_MS = 5000; + + /** + * The Cloud Shell back authorization channel uses serialized + * Javascript Protobufers, preceeded by the message length and a + * new line character. However, the request message has no content, + * so a token request consists of an empty JsPb, and its 2 character + * lenth prefix. + */ + protected final static String GET_AUTH_TOKEN_REQUEST = "2\n[]"; + + private final int authPort; + + /** + * @param authPort Authentication port. + * @return The CloudShellCredentials. + * @deprecated Use {@link #create(int)} instead. This method will be deleted in a later version. + */ + @Deprecated + public static CloudShellCredentials of(int authPort) { + return create(authPort); + } + + public static CloudShellCredentials create(int authPort) { + return CloudShellCredentials.newBuilder().setAuthPort(authPort).build(); + } + + /** + * @param authPort Authentication port. + * @deprecated Use {@link #create(int)} instead. This constructor will either be deleted or + * made private in a later version. + */ + @Deprecated + public CloudShellCredentials(int authPort) { + this.authPort = authPort; + } + + protected int getAuthPort() { + return this.authPort; + } + + @Override + public AccessToken refreshAccessToken() throws IOException { + Socket socket = new Socket("localhost", this.getAuthPort()); + socket.setSoTimeout(READ_TIMEOUT_MS); + AccessToken token; + try { + PrintWriter out = + new PrintWriter(socket.getOutputStream(), true); + out.println(GET_AUTH_TOKEN_REQUEST); + + BufferedReader input = + new BufferedReader(new InputStreamReader(socket.getInputStream())); + input.readLine(); // Skip over the first line + JsonParser parser = OAuth2Utils.JSON_FACTORY.createJsonParser(input); + List messageArray = (List) parser.parseArray(ArrayList.class, Object.class); + String accessToken = messageArray.get(ACCESS_TOKEN_INDEX).toString(); + token = new AccessToken(accessToken, null); + } finally { + socket.close(); + } + return token; + } + + @Override + public int hashCode() { + return Objects.hash(authPort); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this).add("authPort", authPort).toString(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof CloudShellCredentials)) { + return false; + } + CloudShellCredentials other = (CloudShellCredentials) obj; + return this.authPort == other.authPort; + } + + public Builder toBuilder() { + return new Builder(this); + } + + public static Builder newBuilder() { + return new Builder(); + } + + public static class Builder extends GoogleCredentials.Builder { + private int authPort; + + protected Builder() {} + + protected Builder(CloudShellCredentials credentials) { + this.authPort = credentials.authPort; + } + + public Builder setAuthPort(int authPort) { + this.authPort = authPort; + return this; + } + + public int getAuthPort() { + return authPort; + } + + public CloudShellCredentials build() { + return new CloudShellCredentials(authPort); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 105 is not released after line 112. +**Note**: potential exception at line 106 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +AccessToken CloudShellCredentials.refreshAccessToken() + +### Procedure Id: +com.google.auth.oauth2.CloudShellCredentials.refreshAccessToken():com.google.auth.oauth2.AccessToken.4cab98e0690f877901699d2f21d20d53 + +### File: +oauth2_http/java/com/google/auth/oauth2/CloudShellCredentials.java + +### Key: +CloudShellCredentials.java|refreshAccessToken|RESOURCE_LEAK + +### Node Key: +6d15c9608e0b7a140ecfdba5dce92676 + +### Hash: +4edc398a1c1ceb9e019e5f5f7007a60f + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8766/instruction.md b/inferredbugs-8766/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b81ebae3b25618f570edff79526e828625e6d21f --- /dev/null +++ b/inferredbugs-8766/instruction.md @@ -0,0 +1,180 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** blockchain-java +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package one.wangwei.blockchain.util; + +import one.wangwei.blockchain.block.Block; +import org.rocksdb.Options; +import org.rocksdb.RocksDB; +import org.rocksdb.RocksDBException; + +/** + * RocksDB 工具类 + * + * @author wangwei + * @date 2018/02/27 + */ +public class RocksDBUtils { + + /** + * 区块链数据文件 + */ + private static final String DB_FILE = "blockchain.db"; + /** + * 区块桶前缀 + */ + private static final String BLOCKS_BUCKET_PREFIX = "blocks_"; + + private volatile static RocksDBUtils instance; + + public static RocksDBUtils getInstance() { + if (instance == null) { + synchronized (RocksDBUtils.class) { + if (instance == null) { + instance = new RocksDBUtils(); + } + } + } + return instance; + } + + private RocksDB rocksDB; + + private RocksDBUtils() { + initRocksDB(); + } + + /** + * 初始化RocksDB + */ + private void initRocksDB() { + try { + rocksDB = RocksDB.open(new Options().setCreateIfMissing(true), DB_FILE); + } catch (RocksDBException e) { + e.printStackTrace(); + } + } + + /** + * 保存最新一个区块的Hash值 + * + * @param tipBlockHash + */ + public void putLastBlockHash(String tipBlockHash) throws Exception { + rocksDB.put(SerializeUtils.serialize(BLOCKS_BUCKET_PREFIX + "l"), SerializeUtils.serialize(tipBlockHash)); + } + + /** + * 查询最新一个区块的Hash值 + * + * @return + */ + public String getLastBlockHash() throws Exception { + byte[] lastBlockHashBytes = rocksDB.get(SerializeUtils.serialize(BLOCKS_BUCKET_PREFIX + "l")); + if (lastBlockHashBytes != null) { + return (String) SerializeUtils.deserialize(lastBlockHashBytes); + } + return ""; + } + + /** + * 保存区块 + * + * @param block + */ + public void putBlock(Block block) throws Exception { + byte[] key = SerializeUtils.serialize(BLOCKS_BUCKET_PREFIX + block.getHash()); + rocksDB.put(key, SerializeUtils.serialize(block)); + } + + /** + * 查询区块 + * + * @param blockHash + * @return + */ + public Block getBlock(String blockHash) throws Exception { + byte[] key = SerializeUtils.serialize(BLOCKS_BUCKET_PREFIX + blockHash); + return (Block) SerializeUtils.deserialize(rocksDB.get(key)); + } + + /** + * 关闭数据库 + */ + public void closeDB() { + if (rocksDB != null) { + rocksDB.close(); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.rocksdb.Options` acquired by call to `new()` at line 49 is not released after line 49. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RocksDBUtils.initRocksDB() + +### Procedure Id: +one.wangwei.blockchain.util.RocksDBUtils.initRocksDB():void.05be2c50f9b454e376f030fe8db25605 + +### File: +src/main/java/one/wangwei/blockchain/util/RocksDBUtils.java + +### Key: +RocksDBUtils.java|initRocksDB|RESOURCE_LEAK + +### Node Key: +64fcabe8c0d600fd6678fb1fef09d9a3 + +### Hash: +bada7f790c0e13c3f9f0ebdb9c32e071 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8768/instruction.md b/inferredbugs-8768/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..23dcc99778a6f8f024f3c662644f85af5fd3ed87 --- /dev/null +++ b/inferredbugs-8768/instruction.md @@ -0,0 +1,475 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** datumbox-framework +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2013-2016 Vasilis Vryniotis + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datumbox.framework.machinelearning.classification; + +import com.datumbox.common.dataobjects.AssociativeArray; +import com.datumbox.common.dataobjects.Dataframe; +import com.datumbox.common.dataobjects.Record; +import com.datumbox.common.persistentstorage.interfaces.DatabaseConnector; +import com.datumbox.framework.machinelearning.common.abstracts.modelers.AbstractClassifier; +import com.datumbox.common.persistentstorage.interfaces.BigMap; +import com.datumbox.common.persistentstorage.interfaces.DatabaseConfiguration; +import com.datumbox.common.dataobjects.TypeInference; +import com.datumbox.common.persistentstorage.interfaces.DatabaseConnector.MapType; +import com.datumbox.common.persistentstorage.interfaces.DatabaseConnector.StorageHint; +import com.datumbox.framework.machinelearning.common.interfaces.PredictParallelizable; +import com.datumbox.framework.machinelearning.common.validators.SoftMaxRegressionValidator; +import com.datumbox.framework.statistics.descriptivestatistics.Descriptives; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; + + +/** + * The SoftMaxRegression implements the Multinomial Logistic Regression classifier. + * + * References: + * http://blog.datumbox.com/machine-learning-tutorial-the-multinomial-logistic-regression-softmax-regression/ + * http://blog.datumbox.com/tuning-the-learning-rate-in-gradient-descent/ + * http://www.cs.cmu.edu/afs/cs/user/aberger/www/html/tutorial/node3.html + * http://acl.ldc.upenn.edu/P/P02/P02-1002.pdf + * + * @author Vasilis Vryniotis + */ +public class SoftMaxRegression extends AbstractClassifier implements PredictParallelizable { + + /** {@inheritDoc} */ + public static class ModelParameters extends AbstractClassifier.AbstractModelParameters { + private static final long serialVersionUID = 1L; + + @BigMap(mapType=MapType.HASHMAP, storageHint=StorageHint.IN_MEMORY, concurrent=false) + private Map, Double> thitas; //the thita parameters of the model + + /** + * @param dbc + * @see com.datumbox.framework.machinelearning.common.abstracts.AbstractTrainer.AbstractModelParameters#AbstractModelParameters(com.datumbox.common.persistentstorage.interfaces.DatabaseConnector) + */ + protected ModelParameters(DatabaseConnector dbc) { + super(dbc); + } + + /** + * Getter for the Thita coefficients of the model. + * + * @return + */ + public Map, Double> getThitas() { + return thitas; + } + + /** + * Setter for the Thita coefficients of the model. + * + * @param thitas + */ + protected void setThitas(Map, Double> thitas) { + this.thitas = thitas; + } + } + + /** {@inheritDoc} */ + public static class TrainingParameters extends AbstractClassifier.AbstractTrainingParameters { + private static final long serialVersionUID = 1L; + + private int totalIterations=100; + private double learningRate=0.1; + + /** + * Getter for the total iterations of the training process. + * + * @return + */ + public int getTotalIterations() { + return totalIterations; + } + + /** + * Setter for the total iterations of the training process. + * + * @param totalIterations + */ + public void setTotalIterations(int totalIterations) { + this.totalIterations = totalIterations; + } + + /** + * Getter for the initial value of the Learning Rate. + * + * @return + */ + public double getLearningRate() { + return learningRate; + } + + /** + * Setter for the initial value of the Learning Rate. This value will be + * adapted during the iterations. + * + * @param learningRate + */ + public void setLearningRate(double learningRate) { + this.learningRate = learningRate; + } + + } + + /** {@inheritDoc} */ + public static class ValidationMetrics extends AbstractClassifier.AbstractValidationMetrics { + private static final long serialVersionUID = 1L; + + private double SSE = 0.0; + private double CountRSquare = 0.0; // http://www.ats.ucla.edu/stat/mult_pkg/faq/general/Psuedo_RSquareds.htm + + /** + * Getter for the SSE metric. + * + * @return + */ + public double getSSE() { + return SSE; + } + + /** + * Setter for the SSE metric. + * + * @param SSE + */ + public void setSSE(double SSE) { + this.SSE = SSE; + } + + /** + * Getter for the Count R^2 metric. + * + * @return + */ + public double getCountRSquare() { + return CountRSquare; + } + + /** + * Setter for the Count R^2 metric. + * + * @param CountRSquare + */ + public void setCountRSquare(double CountRSquare) { + this.CountRSquare = CountRSquare; + } + + } + + /** + * Public constructor of the algorithm. + * + * @param dbName + * @param dbConf + */ + public SoftMaxRegression(String dbName, DatabaseConfiguration dbConf) { + super(dbName, dbConf, SoftMaxRegression.ModelParameters.class, SoftMaxRegression.TrainingParameters.class, SoftMaxRegression.ValidationMetrics.class, new SoftMaxRegressionValidator()); + } + + private boolean parallelized = true; + + /** {@inheritDoc} */ + @Override + public boolean isParallelized() { + return parallelized; + } + + /** {@inheritDoc} */ + @Override + public void setParallelized(boolean parallelized) { + this.parallelized = parallelized; + } + + /** {@inheritDoc} */ + @Override + protected void _predictDataset(Dataframe newData) { + DatabaseConnector dbc = kb().getDbc(); + Map resultsBuffer = dbc.getBigMap("tmp_resultsBuffer", MapType.HASHMAP, StorageHint.IN_DISK, true, true); + _predictDatasetParallel(newData, resultsBuffer); + dbc.dropBigMap("tmp_resultsBuffer", resultsBuffer); + } + + /** {@inheritDoc} */ + @Override + public Prediction _predictRecord(Record r) { + ModelParameters modelParameters = kb().getModelParameters(); + + Set classesSet = modelParameters.getClasses(); + Map, Double> thitas = modelParameters.getThitas(); + + AssociativeArray predictionScores = new AssociativeArray(); + for(Object theClass : classesSet) { + predictionScores.put(theClass, calculateClassScore(r.getX(), theClass, thitas)); + } + + Object predictedClass=getSelectedClassFromClassScores(predictionScores); + + Descriptives.normalizeExp(predictionScores); + + return new Prediction(predictedClass, predictionScores); + } + + /** {@inheritDoc} */ + @Override + protected void _fit(Dataframe trainingData) { + ModelParameters modelParameters = kb().getModelParameters(); + TrainingParameters trainingParameters = kb().getTrainingParameters(); + + + Map, Double> thitas = modelParameters.getThitas(); + Set classesSet = modelParameters.getClasses(); + + //first we need to find all the classes + for(Record r : trainingData) { + Object theClass=r.getY(); + + classesSet.add(theClass); + } + + //we initialize the thitas to zero for all features and all classes compinations + for(Object theClass : classesSet) { + thitas.put(Arrays.asList(Dataframe.COLUMN_NAME_CONSTANT, theClass), 0.0); + + for(Record r : trainingData) { + for(Object feature : r.getX().keySet()) { + thitas.put(Arrays.asList(feature, theClass), 0.0); + } + } + } + + double minError = Double.POSITIVE_INFINITY; + + double learningRate = trainingParameters.getLearningRate(); + int totalIterations = trainingParameters.getTotalIterations(); + DatabaseConnector dbc = kb().getDbc(); + for(int iteration=0;iteration, Double> tmp_newThitas = dbc.getBigMap("tmp_newThitas", MapType.HASHMAP, StorageHint.IN_MEMORY, false, true); + + tmp_newThitas.putAll(thitas); + batchGradientDescent(trainingData, tmp_newThitas, learningRate); + + double newError = calculateError(trainingData,tmp_newThitas); + + //bold driver + if(newError>minError) { + learningRate/=2.0; + } + else { + learningRate*=1.05; + minError=newError; + + //keep the new thitas + thitas.clear(); + thitas.putAll(tmp_newThitas); + } + + //Drop the temporary Collection + dbc.dropBigMap("tmp_newThitas", tmp_newThitas); + } + } + + /** {@inheritDoc} */ + @Override + protected SoftMaxRegression.ValidationMetrics validateModel(Dataframe validationData) { + SoftMaxRegression.ValidationMetrics validationMetrics = super.validateModel(validationData); + + validationMetrics.setCountRSquare(validationMetrics.getAccuracy()); //CountRSquare is equal to Accuracy + + double SSE = calculateError(validationData,kb().getModelParameters().getThitas()); + validationMetrics.setSSE(SSE); + + return validationMetrics; + } + + private void batchGradientDescent(Dataframe trainingData, Map, Double> newThitas, double learningRate) { + //NOTE! This is not the stochastic gradient descent. It is the batch gradient descent optimized for speed (despite it looks more than the stochastic). + //Despite the fact that the loops are inverse, the function still changes the values of Thitas at the end of the function. We use the previous thitas + //to estimate the costs and only at the end we update the new thitas. + ModelParameters modelParameters = kb().getModelParameters(); + + double multiplier = learningRate/modelParameters.getN(); + Map, Double> thitas = modelParameters.getThitas(); + Set classesSet = modelParameters.getClasses(); + + for(Record r : trainingData) { + //mind the fact that we use the previous thitas to estimate the new ones! this is because the thitas must be updated simultaniously + AssociativeArray classProbabilities = hypothesisFunction(r.getX(), thitas); + for(Object theClass : classesSet) { + + double error; + double score = classProbabilities.getDouble(theClass); + if(r.getY().equals(theClass)) { + error = 1 - score; + } + else { + error = - score; + } + + double errorMultiplier = multiplier*error; + + + //update the weight of constant + List featureClassTuple = Arrays.asList(Dataframe.COLUMN_NAME_CONSTANT, theClass); + newThitas.put(featureClassTuple, newThitas.get(featureClassTuple)+errorMultiplier); + + //update the rest of the weights + + for(Map.Entry entry : r.getX().entrySet()) { + Double value = TypeInference.toDouble(entry.getValue()); + + Object feature = entry.getKey(); + featureClassTuple = Arrays.asList(feature, theClass); + + Double thitaWeight = newThitas.get(featureClassTuple); + if(thitaWeight!=null) {//ensure that the feature is in the dictionary + newThitas.put(featureClassTuple, thitaWeight+errorMultiplier*value); + } + } + } + } + + } + + private Double calculateClassScore(AssociativeArray x, Object theClass, Map, Double> thitas) { + double score = thitas.get(Arrays.asList(Dataframe.COLUMN_NAME_CONSTANT, theClass)); + + for(Map.Entry entry : x.entrySet()) { + Double value = TypeInference.toDouble(entry.getValue()); + + Object feature = entry.getKey(); + List featureClassTuple = Arrays.asList(feature, theClass); + + Double thitaWeight = thitas.get(featureClassTuple); + if(thitaWeight!=null) {//ensure that the feature is in the dictionary + score+=thitaWeight*value; + } + } + + return score; + } + + private double calculateError(Dataframe trainingData, Map, Double> thitas) { + //The cost function as described on http://ufldl.stanford.edu/wiki/index.php/Softmax_Regression + //It is optimized for speed to reduce the amount of loops + double error=0.0; + + for(Record r : trainingData) { + AssociativeArray classProbabilities = hypothesisFunction(r.getX(), thitas); + Double score = classProbabilities.getDouble(r.getY()); + error+=Math.log(score); //no need to loop through the categories. Just grab the one that we are interested in + } + + return -error/kb().getModelParameters().getN(); + } + + private AssociativeArray hypothesisFunction(AssociativeArray x, Map, Double> thitas) { + Set classesSet = kb().getModelParameters().getClasses(); + AssociativeArray predictionProbabilities = new AssociativeArray(); + + for(Object theClass : classesSet) { + double score=calculateClassScore(x, theClass, thitas); + if(score<=0) { + score=1e-8; + } + predictionProbabilities.put(theClass, score); + } + + Descriptives.normalize(predictionProbabilities); + + return predictionProbabilities; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `score` last assigned on line 377 could be null and is dereferenced at line 378. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +double SoftMaxRegression.calculateError(Dataframe,Map) + +### Procedure Id: +com.datumbox.framework.machinelearning.classification.SoftMaxRegression.calculateError(com.datumbox..bcdf219bb42638e0e7d986d3c0ac0819 + +### File: +src/main/java/com/datumbox/framework/machinelearning/classification/SoftMaxRegression.java + +### Key: +SoftMaxRegression.java|calculateError|NULL_DEREFERENCE + +### Node Key: +9140dff8bf7cd03886d368c0c0c52aa5 + +### Hash: +7fb98664edd20ced21551e3023e9cfd5 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8769/instruction.md b/inferredbugs-8769/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c6b98a107800590b6b913ad50ff42f3b99e62c2b --- /dev/null +++ b/inferredbugs-8769/instruction.md @@ -0,0 +1,399 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** datumbox-framework +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2013-2015 Vasilis Vryniotis + * + * 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 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, see . + */ +package com.datumbox.framework.machinelearning.common.bases.datatransformation; + +import com.datumbox.common.dataobjects.AssociativeArray; +import com.datumbox.common.dataobjects.Dataset; +import com.datumbox.common.dataobjects.FlatDataList; +import com.datumbox.common.dataobjects.Record; +import com.datumbox.common.persistentstorage.interfaces.DatabaseConnector; +import com.datumbox.common.persistentstorage.interfaces.BigMap; +import com.datumbox.common.persistentstorage.interfaces.DatabaseConfiguration; +import com.datumbox.common.utilities.TypeConversions; +import com.datumbox.framework.statistics.descriptivestatistics.Descriptives; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + + +/** + * + * @author Vasilis Vryniotis + */ +public abstract class BaseDummyMinMaxTransformer extends DataTransformer { + + public static class ModelParameters extends DataTransformer.ModelParameters { + + @BigMap + protected Map referenceLevels; + + @BigMap + protected Map minColumnValues; + + @BigMap + protected Map maxColumnValues; + + public ModelParameters(DatabaseConnector dbc) { + super(dbc); + } + + public Map getReferenceLevels() { + return referenceLevels; + } + + public void setReferenceLevels(Map referenceLevels) { + this.referenceLevels = referenceLevels; + } + + public Map getMinColumnValues() { + return minColumnValues; + } + + public void setMinColumnValues(Map minColumnValues) { + this.minColumnValues = minColumnValues; + } + + public Map getMaxColumnValues() { + return maxColumnValues; + } + + public void setMaxColumnValues(Map maxColumnValues) { + this.maxColumnValues = maxColumnValues; + } + + + } + + public static class TrainingParameters extends DataTransformer.TrainingParameters { + + } + + protected BaseDummyMinMaxTransformer(String dbName, DatabaseConfiguration dbConf) { + super(dbName, dbConf, BaseDummyMinMaxTransformer.ModelParameters.class, BaseDummyMinMaxTransformer.TrainingParameters.class); + } + + protected static void fitX(Dataset data, Map minColumnValues, Map maxColumnValues) { + + for(Map.Entry entry : data.getColumns().entrySet()) { + Object column = entry.getKey(); + Dataset.ColumnType columnType = entry.getValue(); + + if(columnType==Dataset.ColumnType.NUMERICAL) { + FlatDataList columnValues = data.extractColumnValues(column); + Double max = Descriptives.max(columnValues.toFlatDataCollection()); + Double min = Descriptives.min(columnValues.toFlatDataCollection()); + + minColumnValues.put(column, min); + maxColumnValues.put(column, max); + } + else { + //do nothing for non-numeric columns + } + } + + //do nothing for the response variable Y + } + + protected static void normalizeX(Dataset data, Map minColumnValues, Map maxColumnValues) { + for(Integer rId : data) { + Record r = data.get(rId); + for(Object column : minColumnValues.keySet()) { + Double value = r.getX().getDouble(column); + if(value==null) { //if we have a missing value don't perform any normalization + continue; + } + + Double min = minColumnValues.get(column); + Double max = maxColumnValues.get(column); + + //it is important how we will handle 0 normalized values because + //0-valued features are considered inactive. + double normalizedValue; + if(min.equals(max)) { + normalizedValue = (min>0.0)?1.0:0.0; //set it 0.0 ONLY if the feature is always inactive and 1.0 if it has a non-zero value + } + else { + normalizedValue = (value-min)/(max-min); + } + + r.getX().put(column, normalizedValue); + } + + //do nothing for the response variable Y + } + } + + protected static void denormalizeX(Dataset data, Map minColumnValues, Map maxColumnValues) { + for(Integer rId : data) { + Record r = data.get(rId); + for(Object column : minColumnValues.keySet()) { + Double value = r.getX().getDouble(column); + if(value==null) { //if we have a missing value don't perform any denormalization + continue; + } + + Double min = minColumnValues.get(column); + Double max = maxColumnValues.get(column); + + if(min.equals(max)) { + r.getX().put(column, min); + } + else { + r.getX().put(column, value*(max-min) + min); + } + } + + //do nothing for the response variable Y + } + } + + protected static void fitY(Dataset data, Map minColumnValues, Map maxColumnValues) { + if(data.isEmpty()) { + return; + } + + //check if the first record has numeric value on response variable Y + Dataset.ColumnType columnType = Dataset.value2ColumnType(data.get(data.iterator().next()).getY()); + + if(columnType==Dataset.ColumnType.NUMERICAL) { + //if this is numeric normalize it + + FlatDataList columnValues = data.extractYValues(); + Double max = Descriptives.max(columnValues.toFlatDataCollection()); + Double min = Descriptives.min(columnValues.toFlatDataCollection()); + + minColumnValues.put(Dataset.YColumnName, min); + maxColumnValues.put(Dataset.YColumnName, max); + } + } + + protected static void normalizeY(Dataset data, Map minColumnValues, Map maxColumnValues) { + if(data.isEmpty()) { + return; + } + + Dataset.ColumnType columnType = Dataset.value2ColumnType(data.get(data.iterator().next()).getY()); + + if(columnType==Dataset.ColumnType.NUMERICAL) { + + for(Integer rId : data) { + Record r = data.get(rId); + Double value = TypeConversions.toDouble(r.getY()); + if(value==null) { //if we have a missing value don't perform any normalization + continue; + } + + //do the same for the response variable Y + Double min = minColumnValues.get(Dataset.YColumnName); + Double max = maxColumnValues.get(Dataset.YColumnName); + + //it is important how we will handle 0 normalized values because + //0-valued features are considered inactive. + double normalizedValue; + if(min.equals(max)) { + normalizedValue = (min!=0.0)?1.0:0.0; //set it 0.0 ONLY if the feature is always inactive and 1.0 if it has a non-zero value + } + else { + normalizedValue = (value-min)/(max-min); + } + + data.set(rId, new Record(r.getX(), normalizedValue, r.getYPredicted(), r.getYPredictedProbabilities())); + } + } + } + + protected static void denormalizeY(Dataset data, Map minColumnValues, Map maxColumnValues) { + + if(data.isEmpty()) { + return; + } + + Dataset.ColumnType columnType = Dataset.value2ColumnType(data.get(data.iterator().next()).getY()); + + if(columnType==Dataset.ColumnType.NUMERICAL) { + + for(Integer rId : data) { + Record r = data.get(rId); + + //do the same for the response variable Y + Double min = minColumnValues.get(Dataset.YColumnName); + Double max = maxColumnValues.get(Dataset.YColumnName); + + Object denormalizedY = null; + Object denormalizedYPredicted = null; + if(min.equals(max)) { + denormalizedY = min; + if(r.getYPredicted()!=null) { + denormalizedYPredicted = min; + } + } + else { + denormalizedY = TypeConversions.toDouble(r.getY())*(max-min) + min; + + Double YPredicted = TypeConversions.toDouble(r.getYPredicted()); + if(YPredicted!=null) { + denormalizedYPredicted = YPredicted*(max-min) + min; + } + } + + data.set(rId, new Record(r.getX(), denormalizedY, denormalizedYPredicted, r.getYPredictedProbabilities())); + } + } + } + + private static boolean covert2dummy(Dataset.ColumnType columnType) { + return columnType==Dataset.ColumnType.CATEGORICAL || columnType==Dataset.ColumnType.ORDINAL; + } + + protected static void extractDummies(Dataset data, Map referenceLevels) { + + Map columnTypes = data.getColumns(); + if(referenceLevels.isEmpty()) { + //Training Mode + + //find the referenceLevels for each categorical variable + for(Integer rId: data) { + Record r = data.get(rId); + for(Map.Entry entry: r.getX().entrySet()) { + Object column = entry.getKey(); + if(referenceLevels.containsKey(column)==false) { //already set? + if(covert2dummy(columnTypes.get(column))==false) { + continue; //only ordinal and categorical are converted into dummyvars + } + Object value = entry.getValue(); + referenceLevels.put(column, value); + } + } + } + } + + //Replace variables with dummy versions + for(Integer rId: data) { + Record r = data.get(rId); + + AssociativeArray xData = new AssociativeArray(r.getX()); + + boolean modified = false; + for(Object column : r.getX().keySet()) { + if(covert2dummy(columnTypes.get(column))==false) { + continue; + } + Object value = xData.get(column); + + xData.remove(column); //remove the original column + modified = true; + + Object referenceLevel= referenceLevels.get(column); + + if(referenceLevel != null && //not unknown variable + !referenceLevel.equals(value)) { //not equal to reference level + + //create a new column + List newColumn = Arrays.asList(column,value); + + //add a new dummy variable for this column-value combination + xData.put(newColumn, true); + } + } + + if(modified) { + r = new Record(xData, r.getY(), r.getYPredicted(), r.getYPredictedProbabilities()); + data.set(rId, r); + } + } + + //Reset Meta info + data.resetMeta(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `r.getX()` could be null and is dereferenced at line 146. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BaseDummyMinMaxTransformer.denormalizeX(Dataset,Map,Map) + +### Procedure Id: +com.datumbox.framework.machinelearning.common.bases.datatransformation.BaseDummyMinMaxTransformer.de.213d16c6cb196552e6bfa95b7e0c3a45 + +### File: +src/main/java/com/datumbox/framework/machinelearning/common/bases/datatransformation/BaseDummyMinMaxTransformer.java + +### Key: +BaseDummyMinMaxTransformer.java|denormalizeX|NULL_DEREFERENCE + +### Node Key: +7e9fc31bc469440d6384630f8b346526 + +### Hash: +0db3bf600a9167fc32fd53dc5544b080 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8792/instruction.md b/inferredbugs-8792/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..776f50f5a3cb20ba0e4061b0edc613b63d29d5cd --- /dev/null +++ b/inferredbugs-8792/instruction.md @@ -0,0 +1,180 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** dns-java +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2012-2014 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.spotify.dns.examples; + +import com.google.common.base.Function; +import com.google.common.collect.Sets; + +import com.spotify.dns.ChangeNotifier; +import com.spotify.dns.DnsException; +import com.spotify.dns.DnsSrvResolver; +import com.spotify.dns.DnsSrvResolvers; +import com.spotify.dns.DnsSrvWatcher; +import com.spotify.dns.LookupResult; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.concurrent.TimeUnit; + +import javax.annotation.Nullable; + +public final class PollingUsage { + + public static void main(String[] args) throws IOException { + Function resultTransformer = new Function() { + @Nullable + @Override + public Integer apply(@Nullable LookupResult input) { + return input.weight(); + } + }; + + DnsSrvResolver resolver = DnsSrvResolvers.newBuilder() + .cachingLookups(true) + .retainingDataOnFailures(true) + .dnsLookupTimeoutMillis(1000) + .build(); + + + DnsSrvWatcher watcher = DnsSrvResolvers.newWatcherBuilder(resolver) + .polling(1, TimeUnit.SECONDS) + .build(); + + boolean quit = false; + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + while (!quit) { + System.out.print("Enter a SRV name (empty to quit): "); + String line = in.readLine(); + + if (line == null || line.isEmpty()) { + quit = true; + } else { + try { + ChangeNotifier notifier = watcher.watch(line); + notifier.setListener(new ChangeListener(line), false); + } + catch (DnsException e) { + e.printStackTrace(System.out); + } + } + } + } + + static class ChangeListener implements ChangeNotifier.Listener { + + final String name; + + ChangeListener(String name) { + this.name = name; + } + + @Override + public void endpointsChanged(ChangeNotifier.ChangeNotification changeNotification) { + System.out.println("\nEndpoints changed for " + name); + for (LookupResult endpoint : changeNotification.previous()) { + System.out.println(" prev: " + endpoint); + } + + for (LookupResult endpoint : changeNotification.current()) { + System.out.println(" curr: " + endpoint); + } + + final Sets.SetView unchanged = + Sets.intersection(changeNotification.current(), changeNotification.previous()); + + for (LookupResult endpoint : unchanged) { + System.out.println(" noch: " + endpoint); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.spotify.dns.PollingDnsSrvWatcher` acquired by call to `build()` at line 56 is not released after line 77. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PollingUsage.main(java.lang.String[]) + +### Procedure Id: +com.spotify.dns.examples.PollingUsage.main(java.lang.String[]):void.0d2fe7f4bb8f8a02006f7c3a2fb94c0a + +### File: +src/test/java/com/spotify/dns/examples/PollingUsage.java + +### Key: +PollingUsage.java|main|RESOURCE_LEAK + +### Node Key: +af124b9e4e475ec1dcf4a48bafb14056 + +### Hash: +a4cb1ecaa5229fbe3b8b6efc22c37a97 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8795/instruction.md b/inferredbugs-8795/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..03201359b80cd382efedbd0ce4d3c47c2c007063 --- /dev/null +++ b/inferredbugs-8795/instruction.md @@ -0,0 +1,313 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** failsafe +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package net.jodah.failsafe; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.net.ConnectException; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; + +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import net.jodah.failsafe.util.concurrent.Scheduler; + +@Test +public class AsyncExecutionTest { + ConnectException e = new ConnectException(); + AsyncExecution exec; + FailsafeFuture future; + Callable callable; + Scheduler scheduler; + + @BeforeMethod + @SuppressWarnings("unchecked") + void beforeMethod() { + scheduler = mock(Scheduler.class); + future = mock(FailsafeFuture.class); + callable = mock(Callable.class); + } + + public void testComplete() { + // Given + exec = new AsyncExecution(callable, scheduler, future, configFor(new RetryPolicy())); + + // When + exec.complete(); + + // Then + assertEquals(exec.getExecutions(), 1); + assertTrue(exec.isComplete()); + assertNull(exec.getLastResult()); + assertNull(exec.getLastFailure()); + verify(future).complete(null, null, null); + } + + public void testCompleteForResult() { + // Given + exec = new AsyncExecution(callable, scheduler, future, configFor(new RetryPolicy().retryWhen(null))); + + // When / Then + assertFalse(exec.complete(null)); + exec.before(); + assertTrue(exec.complete(true)); + + // Then + assertEquals(exec.getExecutions(), 2); + assertTrue(exec.isComplete()); + assertEquals(exec.getLastResult(), Boolean.TRUE); + assertNull(exec.getLastFailure()); + verify(future).complete(true, null, null); + } + + public void testGetAttemptCount() { + exec = new AsyncExecution(callable, scheduler, future, configFor(new RetryPolicy())); + exec.retryOn(e); + exec.before(); + exec.retryOn(e); + assertEquals(exec.getExecutions(), 2); + } + + public void testRetryForResult() { + // Given retry for null + exec = new AsyncExecution(callable, scheduler, future, configFor(new RetryPolicy().retryWhen(null))); + + // When / Then + assertFalse(exec.complete(null)); + exec.before(); + assertTrue(exec.retryFor(null)); + exec.before(); + assertFalse(exec.retryFor(1)); + + // Then + assertEquals(exec.getExecutions(), 3); + assertTrue(exec.isComplete()); + assertEquals(exec.getLastResult(), Integer.valueOf(1)); + assertNull(exec.getLastFailure()); + verifyScheduler(1); + verify(future).complete(1, null, null); + + // Given 2 max retries + exec = new AsyncExecution(callable, scheduler, future, + configFor(new RetryPolicy().retryWhen(null).withMaxRetries(2))); + + // When / Then + resetMocks(); + assertFalse(exec.complete(null)); + exec.before(); + assertTrue(exec.retryFor(null)); + exec.before(); + assertFalse(exec.retryFor(null)); + + // Then + assertEquals(exec.getExecutions(), 3); + assertTrue(exec.isComplete()); + assertNull(exec.getLastResult()); + assertNull(exec.getLastFailure()); + verifyScheduler(1); + verify(future).complete(null, null, null); + } + + public void testRetryForResultAndThrowable() { + // Given retry for null + exec = new AsyncExecution(callable, scheduler, future, configFor(new RetryPolicy().retryWhen(null))); + + // When / Then + assertFalse(exec.complete(null)); + exec.before(); + assertTrue(exec.retryFor(null, null)); + exec.before(); + assertTrue(exec.retryFor(1, new IllegalArgumentException())); + exec.before(); + assertFalse(exec.retryFor(1, null)); + + // Then + assertEquals(exec.getExecutions(), 4); + assertTrue(exec.isComplete()); + assertEquals(exec.getLastResult(), Integer.valueOf(1)); + assertNull(exec.getLastFailure()); + verifyScheduler(2); + verify(future).complete(1, null, null); + + // Given 2 max retries + exec = new AsyncExecution(callable, scheduler, future, + configFor(new RetryPolicy().retryWhen(null).withMaxRetries(2))); + + // When / Then + resetMocks(); + assertFalse(exec.complete(null)); + exec.before(); + assertTrue(exec.retryFor(null, e)); + exec.before(); + assertFalse(exec.retryFor(null, e)); + + // Then + assertEquals(exec.getExecutions(), 3); + assertTrue(exec.isComplete()); + assertNull(exec.getLastResult()); + assertEquals(exec.getLastFailure(), e); + verifyScheduler(1); + verify(future).complete(null, e, null); + } + + @SuppressWarnings("unchecked") + public void testRetryOn() { + // Given retry on IllegalArgumentException + exec = new AsyncExecution(callable, scheduler, future, + configFor(new RetryPolicy().retryOn(IllegalArgumentException.class))); + + // When / Then + assertTrue(exec.retryOn(new IllegalArgumentException())); + exec.before(); + assertFalse(exec.retryOn(e)); + + // Then + assertEquals(exec.getExecutions(), 2); + assertTrue(exec.isComplete()); + assertNull(exec.getLastResult()); + assertEquals(exec.getLastFailure(), e); + verifyScheduler(1); + verify(future).complete(null, e, null); + + // Given 2 max retries + exec = new AsyncExecution(callable, scheduler, future, configFor(new RetryPolicy().withMaxRetries(1))); + + // When / Then + resetMocks(); + assertTrue(exec.retryOn(e)); + exec.before(); + assertFalse(exec.retryOn(e)); + + // Then + assertEquals(exec.getExecutions(), 2); + assertTrue(exec.isComplete()); + assertNull(exec.getLastResult()); + assertEquals(exec.getLastFailure(), e); + verifyScheduler(1); + verify(future).complete(null, e, null); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void shouldThrowOnRetryWhenAlreadyComplete() { + exec = new AsyncExecution(callable, scheduler, future, configFor(new RetryPolicy())); + exec.complete(); + exec.before(); + exec.retryOn(e); + } + + public void testCompleteOrRetry() { + // Given retry on IllegalArgumentException + exec = new AsyncExecution(callable, scheduler, future, configFor(new RetryPolicy())); + + // When / Then + exec.completeOrRetry(null, e); + assertFalse(exec.isComplete()); + exec.before(); + exec.completeOrRetry(null, null); + + // Then + assertEquals(exec.getExecutions(), 2); + assertTrue(exec.isComplete()); + assertNull(exec.getLastResult()); + assertNull(exec.getLastFailure()); + verifyScheduler(1); + verify(future).complete(null, null, null); + } + + @SuppressWarnings("unchecked") + private void resetMocks() { + reset(scheduler); + reset(future); + reset(callable); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + static FailsafeConfig> configFor(RetryPolicy retryPolicy) { + return (FailsafeConfig>) new FailsafeConfig().with(retryPolicy); + } + + private void verifyScheduler(int executions) { + verify(scheduler, times(executions)).schedule(any(Callable.class), any(Long.class), any(TimeUnit.class)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `AsyncExecutionTest.exec.circuitBreaker` last assigned on line 207 could be null and is dereferenced by call to `before()` at line 212. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AsyncExecutionTest.testCompleteOrRetry() + +### Procedure Id: +net.jodah.failsafe.AsyncExecutionTest.testCompleteOrRetry():void.495748f3fb4910cda92554fb8837caf7 + +### File: +src/test/java/net/jodah/failsafe/AsyncExecutionTest.java + +### Key: +AsyncExecutionTest.java|testCompleteOrRetry|NULL_DEREFERENCE + +### Node Key: +cd1e023b8fb7f0b3653d3c5ad14bd182 + +### Hash: +613f1ef104339044e9fbf3c910085a49 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8840/instruction.md b/inferredbugs-8840/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..538580a52c301f8b88f079608d3635b1ff7452f1 --- /dev/null +++ b/inferredbugs-8840/instruction.md @@ -0,0 +1,142 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jflex +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.jflex.plugin.maven; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.LineNumberReader; + +public class LexSimpleAnalyzer { + public static final String DEFAULT_NAME = "Yylex"; + + /** + * Guess the package and class name, based on this grammar definition. Does + * not overide the Mojo configuration if it exist. + * + * @return The name of the java code to generate. + * + * Credit goes to the authors of the maven-jlex-plugin + * + * @throws IOException + * @author Rafal Mantiuk (Rafal.Mantiuk@bellstream.pl) + * @author Gerwin Klein (lsf@jflex.de) + * @throws FileNotFoundException + * if the lex file does not exist + * + */ + protected static ClassInfo guessPackageAndClass(File lexFile) + throws FileNotFoundException, IOException { + assert lexFile.isAbsolute() : lexFile; + + LineNumberReader reader = new LineNumberReader(new FileReader(lexFile)); + + ClassInfo classInfo = new ClassInfo(); + while (classInfo.className == null || classInfo.packageName == null) { + String line = reader.readLine(); + if (line == null) + break; + + if (classInfo.packageName == null) { + int index = line.indexOf("package"); + if (index >= 0) { + index += 7; + + int end = line.indexOf(';', index); + if (end >= index) { + classInfo.packageName = line.substring(index, end); + classInfo.packageName = classInfo.packageName.trim(); + } + } + } + + if (classInfo.className == null) { + int index = line.indexOf("%class"); + if (index >= 0) { + index += 6; + + classInfo.className = line.substring(index); + classInfo.className = classInfo.className.trim(); + } + } + } + + if (classInfo.className == null) { + classInfo.className = DEFAULT_NAME; + } + return classInfo; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.LineNumberReader` acquired by call to `new()` at line 31 is not released after line 64. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +ClassInfo LexSimpleAnalyzer.guessPackageAndClass(File) + +### Procedure Id: +de.jflex.plugin.maven.LexSimpleAnalyzer.guessPackageAndClass(java.io.File):de.jflex.plugin.maven.Cla.eafd61a8c8abd1853a5cd4f3ec05eb48 + +### File: +jflex-maven-plugin/src/main/java/de/jflex/plugin/maven/LexSimpleAnalyzer.java + +### Key: +LexSimpleAnalyzer.java|guessPackageAndClass|RESOURCE_LEAK + +### Node Key: +2b80aa5466e54d4bf346e6ecd87af348 + +### Hash: +a72962afeac4b7ee7ea3ae5aad03b855 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8847/instruction.md b/inferredbugs-8847/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..955d7c14b9d6038eb7604daff3175cb42896ab03 --- /dev/null +++ b/inferredbugs-8847/instruction.md @@ -0,0 +1,828 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-imaging +**Bug ID:** 35 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.imaging.common.itu_t4; + +import java.io.ByteArrayInputStream; +import java.io.IOException; + +import org.apache.commons.imaging.ImageReadException; +import org.apache.commons.imaging.ImageWriteException; +import org.apache.commons.imaging.common.itu_t4.T4_T6_Tables.Entry; +import org.apache.commons.imaging.util.IoUtils; + +public final class T4AndT6Compression { + private static final HuffmanTree WHITE_RUN_LENGTHS = new HuffmanTree<>(); + private static final HuffmanTree BLACK_RUN_LENGTHS = new HuffmanTree<>(); + private static final HuffmanTree CONTROL_CODES = new HuffmanTree<>(); + + public static final int WHITE = 0; + public static final int BLACK = 1; + + static { + try { + for (final Entry entry : T4_T6_Tables.WHITE_TERMINATING_CODES) { + WHITE_RUN_LENGTHS.insert(entry.bitString, entry.value); + } + for (final Entry entry : T4_T6_Tables.WHITE_MAKE_UP_CODES) { + WHITE_RUN_LENGTHS.insert(entry.bitString, entry.value); + } + for (final Entry entry : T4_T6_Tables.BLACK_TERMINATING_CODES) { + BLACK_RUN_LENGTHS.insert(entry.bitString, entry.value); + } + for (final Entry entry : T4_T6_Tables.BLACK_MAKE_UP_CODES) { + BLACK_RUN_LENGTHS.insert(entry.bitString, entry.value); + } + for (final Entry entry : T4_T6_Tables.ADDITIONAL_MAKE_UP_CODES) { + WHITE_RUN_LENGTHS.insert(entry.bitString, entry.value); + BLACK_RUN_LENGTHS.insert(entry.bitString, entry.value); + } + CONTROL_CODES.insert(T4_T6_Tables.EOL.bitString, T4_T6_Tables.EOL); + CONTROL_CODES.insert(T4_T6_Tables.EOL13.bitString, T4_T6_Tables.EOL13); + CONTROL_CODES.insert(T4_T6_Tables.EOL14.bitString, T4_T6_Tables.EOL14); + CONTROL_CODES.insert(T4_T6_Tables.EOL15.bitString, T4_T6_Tables.EOL15); + CONTROL_CODES.insert(T4_T6_Tables.EOL16.bitString, T4_T6_Tables.EOL16); + CONTROL_CODES.insert(T4_T6_Tables.EOL17.bitString, T4_T6_Tables.EOL17); + CONTROL_CODES.insert(T4_T6_Tables.EOL18.bitString, T4_T6_Tables.EOL18); + CONTROL_CODES.insert(T4_T6_Tables.EOL19.bitString, T4_T6_Tables.EOL19); + CONTROL_CODES.insert(T4_T6_Tables.P.bitString, T4_T6_Tables.P); + CONTROL_CODES.insert(T4_T6_Tables.H.bitString, T4_T6_Tables.H); + CONTROL_CODES.insert(T4_T6_Tables.V0.bitString, T4_T6_Tables.V0); + CONTROL_CODES.insert(T4_T6_Tables.VL1.bitString, T4_T6_Tables.VL1); + CONTROL_CODES.insert(T4_T6_Tables.VL2.bitString, T4_T6_Tables.VL2); + CONTROL_CODES.insert(T4_T6_Tables.VL3.bitString, T4_T6_Tables.VL3); + CONTROL_CODES.insert(T4_T6_Tables.VR1.bitString, T4_T6_Tables.VR1); + CONTROL_CODES.insert(T4_T6_Tables.VR2.bitString, T4_T6_Tables.VR2); + CONTROL_CODES.insert(T4_T6_Tables.VR3.bitString, T4_T6_Tables.VR3); + } catch (final HuffmanTreeException cannotHappen) { + throw new Error(cannotHappen); + } + } + + private T4AndT6Compression() { + } + + private static void compress1DLine(final BitInputStreamFlexible inputStream, + final BitArrayOutputStream outputStream, final int[] referenceLine, final int width) + throws ImageWriteException { + int color = WHITE; + int runLength = 0; + + for (int x = 0; x < width; x++) { + try { + final int nextColor = inputStream.readBits(1); + if (referenceLine != null) { + referenceLine[x] = nextColor; + } + if (color == nextColor) { + ++runLength; + } else { + writeRunLength(outputStream, runLength, color); + color = nextColor; + runLength = 1; + } + } catch (final IOException ioException) { + throw new ImageWriteException("Error reading image to compress", ioException); + } + } + + writeRunLength(outputStream, runLength, color); + } + + /** + * Compressed with the "Modified Huffman" encoding of section 10 in the + * TIFF6 specification. No EOLs, no RTC, rows are padded to end on a byte + * boundary. + * + * @param uncompressed + * @param width + * @param height + * @return the compressed data + * @throws ImageWriteException + */ + public static byte[] compressModifiedHuffman(final byte[] uncompressed, + final int width, final int height) throws ImageWriteException { + final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(uncompressed)); + final BitArrayOutputStream outputStream = new BitArrayOutputStream(); + for (int y = 0; y < height; y++) { + compress1DLine(inputStream, outputStream, null, width); + inputStream.flushCache(); + outputStream.flush(); + } + return outputStream.toByteArray(); + } + + /** + * Decompresses the "Modified Huffman" encoding of section 10 in the TIFF6 + * specification. No EOLs, no RTC, rows are padded to end on a byte + * boundary. + * + * @param compressed + * @param width + * @param height + * @return the decompressed data + * @throws ImageReadException + */ + public static byte[] decompressModifiedHuffman(final byte[] compressed, + final int width, final int height) throws ImageReadException { + final BitInputStreamFlexible inputStream = new BitInputStreamFlexible( + new ByteArrayInputStream(compressed)); + BitArrayOutputStream outputStream = null; + boolean canThrow = false; + try { + outputStream = new BitArrayOutputStream(); + for (int y = 0; y < height; y++) { + int color = WHITE; + int rowLength; + for (rowLength = 0; rowLength < width;) { + final int runLength = readTotalRunLength(inputStream, color); + for (int i = 0; i < runLength; i++) { + outputStream.writeBit(color); + } + color = 1 - color; + rowLength += runLength; + } + + if (rowLength == width) { + inputStream.flushCache(); + outputStream.flush(); + } else if (rowLength > width) { + throw new ImageReadException("Unrecoverable row length error in image row " + y); + } + } + final byte[] ret = outputStream.toByteArray(); + canThrow = true; + return ret; + } finally { + try { + IoUtils.closeQuietly(canThrow, outputStream); + } catch (final IOException ioException) { + throw new ImageReadException("I/O error", ioException); + } + } + } + + public static byte[] compressT4_1D(final byte[] uncompressed, final int width, + final int height, final boolean hasFill) throws ImageWriteException { + final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(uncompressed)); + final BitArrayOutputStream outputStream = new BitArrayOutputStream(); + if (hasFill) { + T4_T6_Tables.EOL16.writeBits(outputStream); + } else { + T4_T6_Tables.EOL.writeBits(outputStream); + } + + for (int y = 0; y < height; y++) { + compress1DLine(inputStream, outputStream, null, width); + if (hasFill) { + int bitsAvailable = outputStream + .getBitsAvailableInCurrentByte(); + if (bitsAvailable < 4) { + outputStream.flush(); + bitsAvailable = 8; + } + for (; bitsAvailable > 4; bitsAvailable--) { + outputStream.writeBit(0); + } + } + T4_T6_Tables.EOL.writeBits(outputStream); + inputStream.flushCache(); + } + + return outputStream.toByteArray(); + } + + /** + * Decompresses T.4 1D encoded data. EOL at the beginning and after each + * row, can be preceded by fill bits to fit on a byte boundary, no RTC. + * + * @param compressed + * @param width + * @param height + * @return the decompressed data + * @throws ImageReadException + */ + public static byte[] decompressT4_1D(final byte[] compressed, final int width, + final int height, final boolean hasFill) throws ImageReadException { + final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(compressed)); + BitArrayOutputStream outputStream = null; + boolean canThrow = false; + try { + outputStream = new BitArrayOutputStream(); + for (int y = 0; y < height; y++) { + int rowLength; + try { + T4_T6_Tables.Entry entry = CONTROL_CODES.decode(inputStream); + if (!isEOL(entry, hasFill)) { + throw new ImageReadException("Expected EOL not found"); + } + int color = WHITE; + for (rowLength = 0; rowLength < width;) { + final int runLength = readTotalRunLength(inputStream, color); + for (int i = 0; i < runLength; i++) { + outputStream.writeBit(color); + } + color = 1 - color; + rowLength += runLength; + } + } catch (final HuffmanTreeException huffmanException) { + throw new ImageReadException("Decompression error", huffmanException); + } + + if (rowLength == width) { + outputStream.flush(); + } else if (rowLength > width) { + throw new ImageReadException("Unrecoverable row length error in image row " + y); + } + } + final byte[] ret = outputStream.toByteArray(); + canThrow = true; + return ret; + } finally { + try { + IoUtils.closeQuietly(canThrow, outputStream); + } catch (final IOException ioException) { + throw new ImageReadException("I/O error", ioException); + } + } + } + + public static byte[] compressT4_2D(final byte[] uncompressed, final int width, + final int height, final boolean hasFill, final int parameterK) + throws ImageWriteException { + final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(uncompressed)); + final BitArrayOutputStream outputStream = new BitArrayOutputStream(); + int[] referenceLine = new int[width]; + int[] codingLine = new int[width]; + int kCounter = 0; + if (hasFill) { + T4_T6_Tables.EOL16.writeBits(outputStream); + } else { + T4_T6_Tables.EOL.writeBits(outputStream); + } + + for (int y = 0; y < height; y++) { + if (kCounter > 0) { + // 2D + outputStream.writeBit(0); + for (int i = 0; i < width; i++) { + try { + codingLine[i] = inputStream.readBits(1); + } catch (final IOException ioException) { + throw new ImageWriteException("Error reading image to compress", ioException); + } + } + int codingA0Color = WHITE; + int referenceA0Color = WHITE; + int a1 = nextChangingElement(codingLine, codingA0Color, 0); + int b1 = nextChangingElement(referenceLine, referenceA0Color, 0); + int b2 = nextChangingElement(referenceLine, 1 - referenceA0Color, b1 + 1); + for (int a0 = 0; a0 < width;) { + if (b2 < a1) { + T4_T6_Tables.P.writeBits(outputStream); + a0 = b2; + } else { + final int a1b1 = a1 - b1; + if (-3 <= a1b1 && a1b1 <= 3) { + T4_T6_Tables.Entry entry; + if (a1b1 == -3) { + entry = T4_T6_Tables.VL3; + } else if (a1b1 == -2) { + entry = T4_T6_Tables.VL2; + } else if (a1b1 == -1) { + entry = T4_T6_Tables.VL1; + } else if (a1b1 == 0) { + entry = T4_T6_Tables.V0; + } else if (a1b1 == 1) { + entry = T4_T6_Tables.VR1; + } else if (a1b1 == 2) { + entry = T4_T6_Tables.VR2; + } else { + entry = T4_T6_Tables.VR3; + } + entry.writeBits(outputStream); + codingA0Color = 1 - codingA0Color; + a0 = a1; + } else { + final int a2 = nextChangingElement(codingLine, 1 - codingA0Color, a1 + 1); + final int a0a1 = a1 - a0; + final int a1a2 = a2 - a1; + T4_T6_Tables.H.writeBits(outputStream); + writeRunLength(outputStream, a0a1, codingA0Color); + writeRunLength(outputStream, a1a2, 1 - codingA0Color); + a0 = a2; + } + } + referenceA0Color = changingElementAt(referenceLine, a0); + a1 = nextChangingElement(codingLine, codingA0Color, a0 + 1); + if (codingA0Color == referenceA0Color) { + b1 = nextChangingElement(referenceLine, referenceA0Color, a0 + 1); + } else { + b1 = nextChangingElement(referenceLine, referenceA0Color, a0 + 1); + b1 = nextChangingElement(referenceLine, 1 - referenceA0Color, b1 + 1); + } + b2 = nextChangingElement(referenceLine, 1 - codingA0Color, b1 + 1); + } + final int[] swap = referenceLine; + referenceLine = codingLine; + codingLine = swap; + } else { + // 1D + outputStream.writeBit(1); + compress1DLine(inputStream, outputStream, referenceLine, width); + } + if (hasFill) { + int bitsAvailable = outputStream + .getBitsAvailableInCurrentByte(); + if (bitsAvailable < 4) { + outputStream.flush(); + bitsAvailable = 8; + } + for (; bitsAvailable > 4; bitsAvailable--) { + outputStream.writeBit(0); + } + } + T4_T6_Tables.EOL.writeBits(outputStream); + kCounter++; + if (kCounter == parameterK) { + kCounter = 0; + } + inputStream.flushCache(); + } + + return outputStream.toByteArray(); + } + + /** + * Decompressed T.4 2D encoded data. EOL at the beginning and after each + * row, can be preceded by fill bits to fit on a byte boundary, and is + * succeeded by a tag bit determining whether the next line is encoded using + * 1D or 2D. No RTC. + * + * @param compressed + * @param width + * @param height + * @return the decompressed data + * @throws ImageReadException + */ + public static byte[] decompressT4_2D(final byte[] compressed, final int width, + final int height, final boolean hasFill) throws ImageReadException { + final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(compressed)); + final BitArrayOutputStream outputStream = new BitArrayOutputStream(); + final int[] referenceLine = new int[width]; + for (int y = 0; y < height; y++) { + int rowLength = 0; + try { + T4_T6_Tables.Entry entry = CONTROL_CODES.decode(inputStream); + if (!isEOL(entry, hasFill)) { + throw new ImageReadException("Expected EOL not found"); + } + final int tagBit = inputStream.readBits(1); + if (tagBit == 0) { + // 2D + int codingA0Color = WHITE; + int referenceA0Color = WHITE; + int b1 = nextChangingElement(referenceLine, referenceA0Color, 0); + int b2 = nextChangingElement(referenceLine, 1 - referenceA0Color, b1 + 1); + for (int a0 = 0; a0 < width;) { + int a1; + int a2; + entry = CONTROL_CODES.decode(inputStream); + if (entry == T4_T6_Tables.P) { + fillRange(outputStream, referenceLine, a0, b2, codingA0Color); + a0 = b2; + } else if (entry == T4_T6_Tables.H) { + final int a0a1 = readTotalRunLength(inputStream, codingA0Color); + a1 = a0 + a0a1; + fillRange(outputStream, referenceLine, a0, a1, codingA0Color); + final int a1a2 = readTotalRunLength(inputStream, 1 - codingA0Color); + a2 = a1 + a1a2; + fillRange(outputStream, referenceLine, a1, a2, 1 - codingA0Color); + a0 = a2; + } else { + int a1b1; + if (entry == T4_T6_Tables.V0) { + a1b1 = 0; + } else if (entry == T4_T6_Tables.VL1) { + a1b1 = -1; + } else if (entry == T4_T6_Tables.VL2) { + a1b1 = -2; + } else if (entry == T4_T6_Tables.VL3) { + a1b1 = -3; + } else if (entry == T4_T6_Tables.VR1) { + a1b1 = 1; + } else if (entry == T4_T6_Tables.VR2) { + a1b1 = 2; + } else if (entry == T4_T6_Tables.VR3) { + a1b1 = 3; + } else { + throw new ImageReadException("Invalid/unknown T.4 control code " + entry.bitString); + } + a1 = b1 + a1b1; + fillRange(outputStream, referenceLine, a0, a1, codingA0Color); + a0 = a1; + codingA0Color = 1 - codingA0Color; + } + referenceA0Color = changingElementAt(referenceLine, a0); + if (codingA0Color == referenceA0Color) { + b1 = nextChangingElement(referenceLine, referenceA0Color, a0 + 1); + } else { + b1 = nextChangingElement(referenceLine, referenceA0Color, a0 + 1); + b1 = nextChangingElement(referenceLine, 1 - referenceA0Color, b1 + 1); + } + b2 = nextChangingElement(referenceLine, 1 - codingA0Color, b1 + 1); + rowLength = a0; + } + } else { + // 1D + int color = WHITE; + for (rowLength = 0; rowLength < width;) { + final int runLength = readTotalRunLength(inputStream, color); + for (int i = 0; i < runLength; i++) { + outputStream.writeBit(color); + referenceLine[rowLength + i] = color; + } + color = 1 - color; + rowLength += runLength; + } + } + } catch (final IOException ioException) { + throw new ImageReadException("Decompression error", ioException); + } catch (final HuffmanTreeException huffmanException) { + throw new ImageReadException("Decompression error", huffmanException); + } + + if (rowLength == width) { + outputStream.flush(); + } else if (rowLength > width) { + throw new ImageReadException("Unrecoverable row length error in image row " + y); + } + } + + return outputStream.toByteArray(); + } + + public static byte[] compressT6(final byte[] uncompressed, final int width, final int height) + throws ImageWriteException { + BitInputStreamFlexible inputStream = null; + boolean canThrow = false; + try { + inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(uncompressed)); + final BitArrayOutputStream outputStream = new BitArrayOutputStream(); + int[] referenceLine = new int[width]; + int[] codingLine = new int[width]; + for (int y = 0; y < height; y++) { + for (int i = 0; i < width; i++) { + try { + codingLine[i] = inputStream.readBits(1); + } catch (final IOException ioException) { + throw new ImageWriteException("Error reading image to compress", ioException); + } + } + int codingA0Color = WHITE; + int referenceA0Color = WHITE; + int a1 = nextChangingElement(codingLine, codingA0Color, 0); + int b1 = nextChangingElement(referenceLine, referenceA0Color, 0); + int b2 = nextChangingElement(referenceLine, 1 - referenceA0Color, b1 + 1); + for (int a0 = 0; a0 < width;) { + if (b2 < a1) { + T4_T6_Tables.P.writeBits(outputStream); + a0 = b2; + } else { + final int a1b1 = a1 - b1; + if (-3 <= a1b1 && a1b1 <= 3) { + T4_T6_Tables.Entry entry; + if (a1b1 == -3) { + entry = T4_T6_Tables.VL3; + } else if (a1b1 == -2) { + entry = T4_T6_Tables.VL2; + } else if (a1b1 == -1) { + entry = T4_T6_Tables.VL1; + } else if (a1b1 == 0) { + entry = T4_T6_Tables.V0; + } else if (a1b1 == 1) { + entry = T4_T6_Tables.VR1; + } else if (a1b1 == 2) { + entry = T4_T6_Tables.VR2; + } else { + entry = T4_T6_Tables.VR3; + } + entry.writeBits(outputStream); + codingA0Color = 1 - codingA0Color; + a0 = a1; + } else { + final int a2 = nextChangingElement(codingLine, 1 - codingA0Color, a1 + 1); + final int a0a1 = a1 - a0; + final int a1a2 = a2 - a1; + T4_T6_Tables.H.writeBits(outputStream); + writeRunLength(outputStream, a0a1, codingA0Color); + writeRunLength(outputStream, a1a2, 1 - codingA0Color); + a0 = a2; + } + } + referenceA0Color = changingElementAt(referenceLine, a0); + a1 = nextChangingElement(codingLine, codingA0Color, a0 + 1); + if (codingA0Color == referenceA0Color) { + b1 = nextChangingElement(referenceLine, referenceA0Color, a0 + 1); + } else { + b1 = nextChangingElement(referenceLine, referenceA0Color, a0 + 1); + b1 = nextChangingElement(referenceLine, 1 - referenceA0Color, b1 + 1); + } + b2 = nextChangingElement(referenceLine, 1 - codingA0Color, b1 + 1); + } + final int[] swap = referenceLine; + referenceLine = codingLine; + codingLine = swap; + inputStream.flushCache(); + } + // EOFB + T4_T6_Tables.EOL.writeBits(outputStream); + T4_T6_Tables.EOL.writeBits(outputStream); + final byte[] ret = outputStream.toByteArray(); + canThrow = true; + return ret; + } finally { + try { + IoUtils.closeQuietly(canThrow, inputStream); + } catch (final IOException ioException) { + throw new ImageWriteException("I/O error", ioException); + } + } + } + + /** + * Decompress T.6 encoded data. No EOLs, except for 2 consecutive ones at + * the end (the EOFB, end of fax block). No RTC. No fill bits anywhere. All + * data is 2D encoded. + * + * @param compressed + * @param width + * @param height + * @return the decompressed data + * @throws ImageReadException + */ + public static byte[] decompressT6(final byte[] compressed, final int width, final int height) + throws ImageReadException { + final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(compressed)); + final BitArrayOutputStream outputStream = new BitArrayOutputStream(); + final int[] referenceLine = new int[width]; + for (int y = 0; y < height; y++) { + int rowLength = 0; + try { + int codingA0Color = WHITE; + int referenceA0Color = WHITE; + int b1 = nextChangingElement(referenceLine, referenceA0Color, 0); + int b2 = nextChangingElement(referenceLine, 1 - referenceA0Color, b1 + 1); + for (int a0 = 0; a0 < width;) { + int a1; + int a2; + T4_T6_Tables.Entry entry = CONTROL_CODES.decode(inputStream); + if (entry == T4_T6_Tables.P) { + fillRange(outputStream, referenceLine, a0, b2, codingA0Color); + a0 = b2; + } else if (entry == T4_T6_Tables.H) { + final int a0a1 = readTotalRunLength(inputStream, codingA0Color); + a1 = a0 + a0a1; + fillRange(outputStream, referenceLine, a0, a1, codingA0Color); + final int a1a2 = readTotalRunLength(inputStream, 1 - codingA0Color); + a2 = a1 + a1a2; + fillRange(outputStream, referenceLine, a1, a2, 1 - codingA0Color); + a0 = a2; + } else { + int a1b1; + if (entry == T4_T6_Tables.V0) { + a1b1 = 0; + } else if (entry == T4_T6_Tables.VL1) { + a1b1 = -1; + } else if (entry == T4_T6_Tables.VL2) { + a1b1 = -2; + } else if (entry == T4_T6_Tables.VL3) { + a1b1 = -3; + } else if (entry == T4_T6_Tables.VR1) { + a1b1 = 1; + } else if (entry == T4_T6_Tables.VR2) { + a1b1 = 2; + } else if (entry == T4_T6_Tables.VR3) { + a1b1 = 3; + } else { + throw new ImageReadException("Invalid/unknown T.6 control code " + entry.bitString); + } + a1 = b1 + a1b1; + fillRange(outputStream, referenceLine, a0, a1, codingA0Color); + a0 = a1; + codingA0Color = 1 - codingA0Color; + } + referenceA0Color = changingElementAt(referenceLine, a0); + if (codingA0Color == referenceA0Color) { + b1 = nextChangingElement(referenceLine, referenceA0Color, a0 + 1); + } else { + b1 = nextChangingElement(referenceLine, referenceA0Color, a0 + 1); + b1 = nextChangingElement(referenceLine, 1 - referenceA0Color, b1 + 1); + } + b2 = nextChangingElement(referenceLine, 1 - codingA0Color, b1 + 1); + rowLength = a0; + } + } catch (final HuffmanTreeException huffmanException) { + throw new ImageReadException("Decompression error", huffmanException); + } + + if (rowLength == width) { + outputStream.flush(); + } else if (rowLength > width) { + throw new ImageReadException("Unrecoverable row length error in image row " + y); + } + } + + return outputStream.toByteArray(); + } + + private static boolean isEOL(final T4_T6_Tables.Entry entry, final boolean hasFill) { + if (entry == T4_T6_Tables.EOL) { + return true; + } + if (hasFill) { + return entry == T4_T6_Tables.EOL13 || entry == T4_T6_Tables.EOL14 + || entry == T4_T6_Tables.EOL15 + || entry == T4_T6_Tables.EOL16 + || entry == T4_T6_Tables.EOL17 + || entry == T4_T6_Tables.EOL18 + || entry == T4_T6_Tables.EOL19; + } + return false; + } + + private static void writeRunLength(final BitArrayOutputStream bitStream, + int runLength, final int color) { + final T4_T6_Tables.Entry[] makeUpCodes; + final T4_T6_Tables.Entry[] terminatingCodes; + if (color == WHITE) { + makeUpCodes = T4_T6_Tables.WHITE_MAKE_UP_CODES; + terminatingCodes = T4_T6_Tables.WHITE_TERMINATING_CODES; + } else { + makeUpCodes = T4_T6_Tables.BLACK_MAKE_UP_CODES; + terminatingCodes = T4_T6_Tables.BLACK_TERMINATING_CODES; + } + while (runLength >= 1792) { + final T4_T6_Tables.Entry entry = lowerBound( + T4_T6_Tables.ADDITIONAL_MAKE_UP_CODES, runLength); + entry.writeBits(bitStream); + runLength -= entry.value; + } + while (runLength >= 64) { + final T4_T6_Tables.Entry entry = lowerBound(makeUpCodes, runLength); + entry.writeBits(bitStream); + runLength -= entry.value; + } + final T4_T6_Tables.Entry terminatingEntry = terminatingCodes[runLength]; + terminatingEntry.writeBits(bitStream); + } + + private static T4_T6_Tables.Entry lowerBound(final T4_T6_Tables.Entry[] entries, final int value) { + int first = 0; + int last = entries.length - 1; + do { + final int middle = (first + last) >>> 1; + if (entries[middle].value <= value + && ((middle + 1) >= entries.length || value < entries[middle + 1].value)) { + return entries[middle]; + } else if (entries[middle].value > value) { + last = middle - 1; + } else { + first = middle + 1; + } + } while (first < last); + + return entries[first]; + } + + private static int readTotalRunLength(final BitInputStreamFlexible bitStream, + final int color) throws ImageReadException { + try { + int totalLength = 0; + Integer runLength; + do { + if (color == WHITE) { + runLength = WHITE_RUN_LENGTHS.decode(bitStream); + } else { + runLength = BLACK_RUN_LENGTHS.decode(bitStream); + } + totalLength += runLength; + } while (runLength > 63); + return totalLength; + } catch (final HuffmanTreeException huffmanException) { + throw new ImageReadException("Decompression error", huffmanException); + } + } + + private static int changingElementAt(final int[] line, final int position) { + if (position < 0 || position >= line.length) { + return WHITE; + } + return line[position]; + } + + private static int nextChangingElement(final int[] line, final int currentColour, final int start) { + int position; + for (position = start; position < line.length + && line[position] == currentColour; position++) { + // noop + } + + return position < line.length ? position : line.length; + } + + private static void fillRange(final BitArrayOutputStream outputStream, + final int[] referenceRow, final int a0, final int end, final int color) { + for (int i = a0; i < end; i++) { + referenceRow[i] = color; + outputStream.writeBit(color); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.imaging.common.itu_t4.BitArrayOutputStream` acquired by call to `new()` at line 224 is not released after line 256. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +byte[] T4AndT6Compression.decompressT4_1D(byte[],int,int,boolean) + +### Procedure Id: +org.apache.commons.imaging.common.itu_t4.T4AndT6Compression.decompressT4_1D(byte[],int,int,boolean):.120240f8f4b62cd5dfe2a6fd01bb1bce + +### File: +src/main/java/org/apache/commons/imaging/common/itu_t4/T4AndT6Compression.java + +### Key: +T4AndT6Compression.java|decompressT4_1D|RESOURCE_LEAK + +### Node Key: +33103e039a9974e67f967f0461ee6ea2 + +### Hash: +dbeeca76d3a2a82b3222e076861e8c67 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8902/instruction.md b/inferredbugs-8902/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0fb9325dd78df42dd7132e42f292d7e3aa6c1d69 --- /dev/null +++ b/inferredbugs-8902/instruction.md @@ -0,0 +1,360 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** word +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * + * APDPlat - Application Product Development Platform + * Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com + * + * 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 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, see . + * + */ + +package org.apdplat.word.segmentation.impl; + +import java.util.*; +import java.util.Map.Entry; +import java.util.stream.Collectors; + +import org.apdplat.word.recognition.RecognitionTool; +import org.apdplat.word.segmentation.Segmentation; +import org.apdplat.word.segmentation.SegmentationAlgorithm; +import org.apdplat.word.segmentation.SegmentationFactory; +import org.apdplat.word.segmentation.Word; + +/** + * 基于词典的全切分算法 + * Dictionary-based full segmentation algorithm + * 利用ngram给每一种切分结果计算分值 + * 如果多个切分结果分值相同,则选择切分出的词的个数最少的切分结果(最少分词原则) + * @author 杨尚川 + */ +public class FullSegmentation extends AbstractSegmentation{ + private static final AbstractSegmentation RMM = (AbstractSegmentation)SegmentationFactory.getSegmentation(SegmentationAlgorithm.ReverseMaximumMatching); + //在评估采用的测试文本253 3709行2837 4490个字符中,行长度小于等于50的占了99.932465% + //大于50的行长度文本采用逆向最大匹配算法切分文本 + private static final int PROCESS_TEXT_LENGTH_LESS_THAN = 50; + //长度小于等于18的文本单字成词,大于18的文本只有无词时才单字成词 + private static final int CHAR_IS_WORD_LENGTH_LESS_THAN = 18; + + @Override + public SegmentationAlgorithm getSegmentationAlgorithm() { + return SegmentationAlgorithm.FullSegmentation; + } + @Override + public List segImpl(String text) { + if(text.length() > PROCESS_TEXT_LENGTH_LESS_THAN){ + return RMM.segImpl(text); + } + //获取全切分结果 + List[] array = fullSeg(text); + //利用ngram计算分值 + Map, Float> words = ngram(array); + //歧义消解(ngram分值优先、词个数少优先) + List result = disambiguity(words); + return result; + } + private List disambiguity(Map, Float> words){ + //按分值排序 + List, Float>> entrys = words.entrySet().parallelStream().sorted((a,b)->b.getValue().compareTo(a.getValue())).collect(Collectors.toList()); + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("ngram分值:"); + int i=1; + for(Entry, Float> entry : entrys){ + LOGGER.debug("\t"+(i++)+"、"+"词个数="+entry.getKey().size()+"\tngram分值="+entry.getValue()+"\t"+entry.getKey()); + } + } + //移除小于最大分值的切分结果 + float maxScore=entrys.get(0).getValue(); + Iterator, Float>> iter = entrys.iterator(); + while(iter.hasNext()){ + Entry, Float> entry = iter.next(); + if(entry.getValue() < maxScore){ + entry.getKey().clear(); + iter.remove(); + } + } + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("只保留最大分值:"); + int i=1; + for(Entry, Float> entry : entrys){ + LOGGER.debug("\t"+(i++)+"、"+"词个数="+entry.getKey().size()+"\tngram分值="+entry.getValue()+"\t"+entry.getKey()); + } + } + //如果有多个分值一样的切分结果,则选择词个数最少的(最少分词原则) + int minSize=Integer.MAX_VALUE; + List minSizeList = null; + iter = entrys.iterator(); + while(iter.hasNext()){ + Entry, Float> entry = iter.next(); + if(entry.getKey().size() < minSize){ + minSize = entry.getKey().size(); + if(minSizeList != null){ + minSizeList.clear(); + } + minSizeList = entry.getKey(); + }else{ + entry.getKey().clear(); + iter.remove(); + } + } + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("最大分值:"+maxScore+", 消歧结果:"+minSizeList+",词个数:"+minSize); + } + return minSizeList; + } + /** + * 获取文本的所有可能切分结果 + * @param text 文本 + * @return 全切分结果 + */ + private List[] fullSeg(String text){ + //文本长度 + final int textLen = text.length(); + //以每一个字作为词的开始,所能切分的词 + final List[] sequence = new LinkedList[textLen]; + if(isParallelSeg()){ + //并行化 + List list = new ArrayList<>(textLen); + for(int i=0; isequence[i] = fullSeg(text, i)); + }else { + //串行化 + for (int i = 0; i < textLen; i++) { + sequence[i] = fullSeg(text, i); + } + } + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("全切分中间结果:"); + int i=1; + for(List list : sequence){ + LOGGER.debug("\t"+(i++)+"、"+list); + } + } + //树叶 + List leaf = new LinkedList<>(); + for(String word : sequence[0]){ + //树根 + Node node = new Node(word); + //把全切分中间结果(二维数组)转换为合理切分 + buildNode(node, sequence, word.length(), leaf); + } + //清理无用数据 + for(int j=0; j[] res = toWords(leaf); + leaf.clear(); + return res; + } + /** + * 获取以某个字符开始的小于截取长度的所有词 + * @param text 文本 + * @param start 起始字符索引 + * @return 所有符合要求的词 + */ + private List fullSeg(final String text, final int start) { + List result = new LinkedList<>(); + final int textLen = text.length(); + //剩下文本长度 + int len = textLen - start; + //最大截取长度 + int interceptLength = getInterceptLength(); + if(len > interceptLength){ + len = interceptLength; + } + while(len > 1){ + if(getDictionary().contains(text, start, len) || RecognitionTool.recog(text, start, len)){ + result.add(text.substring(start, start + len)); + } + len--; + } + if(textLen <= CHAR_IS_WORD_LENGTH_LESS_THAN || result.isEmpty()){ + //增加单字词 + result.add(text.substring(start, start + 1)); + } + return result; + } + /** + * 根据全切分中间结果构造切分树 + * @param parent 父节点 + * @param sequence 全切分中间结果 + * @param from 全切分中间结果数组下标索引 + * @param leaf 叶子节点集合 + */ + private void buildNode(Node parent, List[] sequence, int from, List leaf){ + //递归退出条件:二维数组遍历完毕 + if(from >= sequence.length){ + //记住叶子节点 + leaf.add(parent); + return; + } + for(String item : sequence[from]){ + Node child = new Node(item, parent); + buildNode(child, sequence, from+item.length(), leaf); + } + } + /** + * 从树叶开始反向遍历生成全切分结果 + * @param leaf 树叶节点集合 + * @return 全切分结果集合 + */ + private List[] toWords(List leaf){ + List[] result = new ArrayList[leaf.size()]; + int i = 0; + if(LOGGER.isDebugEnabled()) { + LOGGER.debug("全切分结果:"); + } + for(Node node : leaf){ + result[i++] = toWords(node); + if(LOGGER.isDebugEnabled()) { + LOGGER.debug("\t" + i + ":" + result[i - 1]); + } + } + return result; + } + /** + * 从树叶开始反向遍历生成全切分结果 + * @param node 树叶节点 + * @return 全切分结果 + */ + private List toWords(Node node){ + Stack stack = new Stack<>(); + while(node != null){ + stack.push(node.getText()); + node = node.getParent(); + } + int len = stack.size(); + List list = new ArrayList<>(len); + for(int i=0; i 0){ + System.out.println(m.seg(Arrays.asList(args).toString())); + return; + } + String text = "蝶舞打扮得漂漂亮亮出现在张公公面前"; + System.out.println(m.seg(text)); + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `words` last assigned on line 60 could be null and is dereferenced by call to `disambiguity(...)` at line 62. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List FullSegmentation.segImpl(String) + +### Procedure Id: +org.apdplat.word.segmentation.impl.FullSegmentation.segImpl(java.lang.String):java.util.List.91392936c7775c5901120795694c621b + +### File: +src/main/java/org/apdplat/word/segmentation/impl/FullSegmentation.java + +### Key: +FullSegmentation.java|segImpl|NULL_DEREFERENCE + +### Node Key: +cd917e0854ab05a03701b589d85cd12c + +### Hash: +416abd8972bec4244a64cced453418c4 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8903/instruction.md b/inferredbugs-8903/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1fa60f728f11cad9a594a6c204eadbdd3e61bed7 --- /dev/null +++ b/inferredbugs-8903/instruction.md @@ -0,0 +1,375 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** word +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * + * APDPlat - Application Product Development Platform + * Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com + * + * 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 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, see . + * + */ + +package org.apdplat.word.segmentation.impl; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Stack; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.apdplat.word.corpus.Bigram; +import org.apdplat.word.corpus.Trigram; +import org.apdplat.word.dictionary.Dictionary; +import org.apdplat.word.dictionary.DictionaryFactory; +import org.apdplat.word.recognition.PersonName; +import org.apdplat.word.segmentation.Segmentation; +import org.apdplat.word.segmentation.Word; +import org.apdplat.word.recognition.Punctuation; +import org.apdplat.word.segmentation.WordRefiner; +import org.apdplat.word.util.WordConfTools; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 分词算法抽象类 + * @author 杨尚川 + */ +public abstract class AbstractSegmentation implements Segmentation{ + protected final Logger LOGGER = LoggerFactory.getLogger(getClass()); + protected static final Dictionary DIC = DictionaryFactory.getDictionary(); + protected static final boolean PERSON_NAME_RECOGNIZE = "true".equals(WordConfTools.get("person.name.recognize", "true")); + protected static final boolean KEEP_WHITESPACE = "true".equals(WordConfTools.get("keep.whitespace", "false")); + protected static final boolean KEEP_PUNCTUATION = "true".equals(WordConfTools.get("keep.punctuation", "false")); + private static final int INTERCEPT_LENGTH = WordConfTools.getInt("intercept.length", 16); + private static final String NGRAM = WordConfTools.get("ngram", "bigram"); + private static final boolean refine = "true".equals(WordConfTools.get("refine", "false").trim()); + private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(WordConfTools.getInt("thread.pool.size", 4)); + public abstract List segImpl(String text); + /** + * 是否启用ngram + * @return 是或否 + */ + public boolean ngramEnabled(){ + return "bigram".equals(NGRAM) || "trigram".equals(NGRAM); + } + /** + * 利用ngram进行评分 + * @param sentences 多个分词结果 + * @return 评分后的结果 + */ + public Map, Float> ngram(List... sentences){ + if("bigram".equals(NGRAM)){ + return Bigram.bigram(sentences); + + } + if("trigram".equals(NGRAM)){ + return Trigram.trigram(sentences); + } + return null; + } + /** + * 分词时截取的字符串的最大长度 + * @return + */ + public int getInterceptLength(){ + if(DIC.getMaxLength() > INTERCEPT_LENGTH){ + return DIC.getMaxLength(); + } + return INTERCEPT_LENGTH; + } + /** + * 默认分词算法实现: + * 1、把要分词的文本根据标点符号进行分割 + * 2、对分割后的文本进行分词 + * 3、组合分词结果 + * @param text 文本 + * @return 分词结果 + */ + @Override + public List seg(String text) { + List result = new ArrayList<>(); + List sentences = Punctuation.seg(text, KEEP_PUNCTUATION); + if(sentences.size() == 1){ + result = segSentence(sentences.get(0)); + }else { + //如果是多个句子,可以利用多线程提升分词速度 + List>> futures = new ArrayList<>(sentences.size()); + for (String sentence : sentences) { + futures.add(submit(sentence)); + } + sentences.clear(); + for (Future> future : futures) { + List words; + try { + words = future.get(); + if (words != null) { + result.addAll(words); + } + } catch (InterruptedException | ExecutionException ex) { + LOGGER.error("获取分词结果失败", ex); + } + } + futures.clear(); + } + if(refine) { + LOGGER.debug("对分词结果进行refine之前:{}", result); + List finalResult = refine(result); + LOGGER.debug("对分词结果进行refine之后:{}", finalResult); + result.clear(); + return finalResult; + }else{ + return result; + } + } + + /** + * 先拆词,再组词 + * @param words + * @return + */ + private List refine(List words){ + List result = new ArrayList<>(words.size()); + //一:拆词 + for(Word word : words){ + List splitWords = WordRefiner.split(word); + if(splitWords==null){ + result.add(word); + }else{ + LOGGER.debug("词: "+word.getText()+" 被拆分为:"+splitWords); + result.addAll(splitWords); + } + } + LOGGER.debug("对分词结果进行refine阶段的拆词之后:{}",result); + //二:组词 + if(result.size()<2){ + return result; + } + int combineMaxLength = WordConfTools.getInt("word.refine.combine.max.length", 3); + if(combineMaxLength < 2){ + combineMaxLength = 2; + } + List finalResult = new ArrayList<>(result.size()); + for(int i=0; i toCombineWords = null; + Word combinedWord = null; + for(int j=2; j<=combineMaxLength; j++){ + int to = i+j; + if(to > result.size()){ + to = result.size(); + } + toCombineWords = result.subList(i, to); + combinedWord = WordRefiner.combine(toCombineWords); + if(combinedWord != null){ + i += j; + i--; + break; + } + } + if(combinedWord == null){ + finalResult.add(result.get(i)); + }else{ + LOGGER.debug("词: "+toCombineWords+" 被合并为:"+combinedWord); + finalResult.add(combinedWord); + } + } + return finalResult; + } + private Future> submit(final String sentence){ + return EXECUTOR_SERVICE.submit(new Callable>(){ + @Override + public List call() { + return segSentence(sentence); + } + }); + } + private List segSentence(final String sentence){ + if(sentence.length() == 1){ + if(KEEP_WHITESPACE){ + List result = new ArrayList<>(1); + result.add(new Word(sentence)); + return result; + }else{ + if(!isWhiteSpace(sentence.charAt(0))){ + List result = new ArrayList<>(1); + result.add(new Word(sentence)); + return result; + } + } + } + if(sentence.length() > 1){ + List list = segImpl(sentence); + if(list != null){ + if(PERSON_NAME_RECOGNIZE){ + list = PersonName.recognize(list); + } + return list; + }else{ + LOGGER.error("文本 "+sentence+" 没有获得分词结果"); + } + } + return null; + } + /** + * 将识别出的词放入队列 + * @param result 队列 + * @param text 文本 + * @param start 词开始索引 + * @param len 词长度 + */ + protected void addWord(List result, String text, int start, int len){ + Word word = getWord(text, start, len); + if(word != null){ + result.add(word); + } + } + /** + * 将识别出的词入栈 + * @param result 栈 + * @param text 文本 + * @param start 词开始索引 + * @param len 词长度 + */ + protected void addWord(Stack result, String text, int start, int len){ + Word word = getWord(text, start, len); + if(word != null){ + result.push(word); + } + } + /** + * 获取一个已经识别的词 + * @param text 文本 + * @param start 词开始索引 + * @param len 词长度 + * @return 词或空 + */ + protected Word getWord(String text, int start, int len){ + Word word = new Word(text.substring(start, start+len).toLowerCase()); + //方便编译器优化 + if(KEEP_WHITESPACE){ + //保留空白字符 + return word; + }else{ + //忽略空白字符,包括:空格、全角空格、\t、\n + if(len > 1){ + //长度大于1,不会是空白字符 + return word; + }else{ + //长度为1,只要非空白字符 + if(!(isWhiteSpace(text, start, len))){ + //不是空白字符,保留 + return word; + } + } + } + return null; + } + /** + * 判断索引下标为start的字符是否为空白字符 + * 这个方法只用在这里 + * 为了速度,不检查索引下标是否越界 + * @param text 文本 + * @param start 索引下标 + * @param len 长度 + * @return 是否 + */ + protected boolean isWhiteSpace(String text, int start, int len){ + return isWhiteSpace(text.charAt(start)); + } + /** + * 判断指定的字符是否是空白字符 + * @param c 字符 + * @return 是否是空白字符 + */ + protected boolean isWhiteSpace(char c){ + return c == ' ' || c == ' ' || c == '\t' || c == '\n'; + } + public static void main(String[] args){ + + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `result` last assigned on line 105 could be null and is dereferenced at line 130. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List AbstractSegmentation.seg(String) + +### Procedure Id: +org.apdplat.word.segmentation.impl.AbstractSegmentation.seg(java.lang.String):java.util.List.997cd5f4cad0e8e2df78bb400e3a3dd1 + +### File: +src/main/java/org/apdplat/word/segmentation/impl/AbstractSegmentation.java + +### Key: +AbstractSegmentation.java|seg|NULL_DEREFERENCE + +### Node Key: +4c63353bc838fe81ed2993cd57a90371 + +### Hash: +2d43ef30c5ef8a0ce4c6d97b395a78f0 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8904/instruction.md b/inferredbugs-8904/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6bcb16e95241fa6ed3ecf9326bce8be5e2bd51a4 --- /dev/null +++ b/inferredbugs-8904/instruction.md @@ -0,0 +1,135 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** word +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * + * APDPlat - Application Product Development Platform + * Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com + * + * 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 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, see . + * + */ + +package org.apdplat.word.util; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * + * @author 杨尚川 + */ +public class GenericTrieTest { + private final GenericTrie trie = new GenericTrie<>(); + @Before + public void setUp() { + trie.put("杨尚川", 100); + trie.put("杨尚喜", 99); + trie.put("杨尚丽", 98); + trie.put("中华人民共和国", 1); + } + @After + public void tearDown() { + trie.clear(); + } + @Test + public void testClear() { + Assert.assertEquals(100, trie.get("杨尚川"), 0); + Assert.assertEquals(1, trie.get("中华人民共和国"), 0); + trie.clear(); + Assert.assertEquals(null, trie.get("杨尚川")); + Assert.assertEquals(null, trie.get("中华人民共和国")); + } + @Test + public void testGet() { + Assert.assertEquals(100, trie.get("杨尚川"), 0); + Assert.assertEquals(99, trie.get("杨尚喜"), 0); + Assert.assertEquals(98, trie.get("杨尚丽"), 0); + Assert.assertEquals(1, trie.get("中华人民共和国"), 0); + Assert.assertEquals(null, trie.get("杨")); + Assert.assertEquals(null, trie.get("杨尚")); + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `GenericTrieTest.trie.get("\\230\\157\\168\\229\\176\\154\\229\\183\\157")` could be null and is dereferenced at line 47. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GenericTrieTest.testClear() + +### Procedure Id: +org.apdplat.word.util.GenericTrieTest.testClear():void.0af7bdc85d06fa3adab24a302842b0d6 + +### File: +src/test/java/org/apdplat/word/util/GenericTrieTest.java + +### Key: +GenericTrieTest.java|testClear|NULL_DEREFERENCE + +### Node Key: +3392ddd9e7af3710d0647e5067e4a3e1 + +### Hash: +136a72b42773586543041e70e3d18dc0 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8905/instruction.md b/inferredbugs-8905/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ab87580494d966c065e6a14d8aa6d841e95be1dd --- /dev/null +++ b/inferredbugs-8905/instruction.md @@ -0,0 +1,348 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** word +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * + * APDPlat - Application Product Development Platform + * Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com + * + * 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 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, see . + * + */ + +package org.apdplat.word.segmentation.impl; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Stack; +import org.apdplat.word.recognition.RecognitionTool; +import org.apdplat.word.segmentation.SegmentationAlgorithm; +import org.apdplat.word.segmentation.SegmentationFactory; +import org.apdplat.word.segmentation.Word; +import org.apdplat.word.util.Utils; + +/** + * 基于词典的全切分算法 + * Dictionary-based full segmentation algorithm + * 利用ngram给每一种切分结果计算分值 + * 如果多个切分结果分值相同,则选择切分出的词的个数最少的切分结果(最少分词原则) + * @author 杨尚川 + */ +public class FullSegmentation extends AbstractSegmentation{ + private static final AbstractSegmentation RMM = (AbstractSegmentation)SegmentationFactory.getSegmentation(SegmentationAlgorithm.ReverseMaximumMatching); + //在评估采用的测试文本253 3709行2837 4490个字符中,行长度小于等于50的占了99.932465% + //大于50的行长度文本采用逆向最大匹配算法切分文本 + private static final int PROCESS_TEXT_LENGTH_LESS_THAN = 50; + //长度小于等于18的文本单字成词,大于18的文本只有无词时才单字成词 + private static final int CHAR_IS_WORD_LENGTH_LESS_THAN = 18; + @Override + public List segImpl(String text) { + if(text.length() > PROCESS_TEXT_LENGTH_LESS_THAN){ + return RMM.segImpl(text); + } + //获取全切分结果 + List[] array = fullSeg(text); + //利用ngram计算分值 + Map, Float> words = ngram(array); + //歧义消解(ngram分值优先、词个数少优先) + List result = disambiguity(words); + return result; + } + private List disambiguity(Map, Float> words){ + //按分值排序 + List, Float>> entrys = Utils.getSortedMapByValue(words); + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("ngram分值:"); + int i=1; + for(Entry, Float> entry : entrys){ + LOGGER.debug("\t"+(i++)+"、"+"词个数="+entry.getKey().size()+"\tngram分值="+entry.getValue()+"\t"+entry.getKey()); + } + } + //移除小于最大分值的切分结果 + float maxScore=entrys.get(0).getValue(); + Iterator, Float>> iter = entrys.iterator(); + while(iter.hasNext()){ + Entry, Float> entry = iter.next(); + if(entry.getValue() < maxScore){ + entry.getKey().clear(); + iter.remove(); + } + } + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("只保留最大分值:"); + int i=1; + for(Entry, Float> entry : entrys){ + LOGGER.debug("\t"+(i++)+"、"+"词个数="+entry.getKey().size()+"\tngram分值="+entry.getValue()+"\t"+entry.getKey()); + } + } + //如果有多个分值一样的切分结果,则选择词个数最少的(最少分词原则) + int minSize=Integer.MAX_VALUE; + List minSizeList = null; + iter = entrys.iterator(); + while(iter.hasNext()){ + Entry, Float> entry = iter.next(); + if(entry.getKey().size() < minSize){ + minSize = entry.getKey().size(); + if(minSizeList != null){ + minSizeList.clear(); + } + minSizeList = entry.getKey(); + }else{ + entry.getKey().clear(); + iter.remove(); + } + } + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("最大分值:"+maxScore+", 消歧结果:"+minSizeList+",词个数:"+minSize); + } + return minSizeList; + } + /** + * 获取文本的所有可能切分结果 + * @param text 文本 + * @return 全切分结果 + */ + private List[] fullSeg(String text){ + //文本长度 + final int textLen = text.length(); + //以每一个字作为词的开始,所能切分的词 + List[] sequence = new LinkedList[textLen]; + for(int start=0; start list : sequence){ + LOGGER.debug("\t"+(i++)+"、"+list); + } + } + //树叶 + List leaf = new LinkedList<>(); + for(String word : sequence[0]){ + //树根 + Node node = new Node(word); + //把全切分中间结果(二维数组)转换为合理切分 + buildNode(node, sequence, word.length(), leaf); + } + //清理无用数据 + for(int j=0; j[] res = toWords(leaf); + leaf.clear(); + return res; + } + /** + * 获取以某个字符开始的小于截取长度的所有词 + * @param text 文本 + * @param start 起始字符索引 + * @return 所有符合要求的词 + */ + private List fullSeg(final String text, final int start) { + List result = new LinkedList<>(); + final int textLen = text.length(); + //剩下文本长度 + int len = textLen - start; + //最大截取长度 + int interceptLength = getInterceptLength(); + if(len > interceptLength){ + len = interceptLength; + } + while(len > 1){ + if(getDictionary().contains(text, start, len) || RecognitionTool.recog(text, start, len)){ + result.add(text.substring(start, start + len)); + } + len--; + } + if(textLen <= CHAR_IS_WORD_LENGTH_LESS_THAN || result.isEmpty()){ + //增加单字词 + result.add(text.substring(start, start + 1)); + } + return result; + } + /** + * 根据全切分中间结果构造切分树 + * @param parent 父节点 + * @param sequence 全切分中间结果 + * @param from 全切分中间结果数组下标索引 + * @param leaf 叶子节点集合 + */ + private void buildNode(Node parent, List[] sequence, int from, List leaf){ + //递归退出条件:二维数组遍历完毕 + if(from >= sequence.length){ + //记住叶子节点 + leaf.add(parent); + return; + } + for(String item : sequence[from]){ + Node child = new Node(item, parent); + buildNode(child, sequence, from+item.length(), leaf); + } + } + /** + * 从树叶开始反向遍历生成全切分结果 + * @param leaf 树叶节点集合 + * @return 全切分结果集合 + */ + private List[] toWords(List leaf){ + List[] result = new ArrayList[leaf.size()]; + int i = 0; + if(LOGGER.isDebugEnabled()) { + LOGGER.debug("全切分结果:"); + } + for(Node node : leaf){ + result[i++] = toWords(node); + if(LOGGER.isDebugEnabled()) { + LOGGER.debug("\t" + i + ":" + result[i - 1]); + } + } + return result; + } + /** + * 从树叶开始反向遍历生成全切分结果 + * @param node 树叶节点 + * @return 全切分结果 + */ + private List toWords(Node node){ + Stack stack = new Stack<>(); + while(node != null){ + stack.push(node.getText()); + node = node.getParent(); + } + int len = stack.size(); + List list = new ArrayList<>(len); + for(int i=0; i. + */ +package mediathek.gui; + +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import javax.swing.AbstractAction; +import javax.swing.ActionMap; +import javax.swing.InputMap; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPopupMenu; +import javax.swing.KeyStroke; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import mediathek.MediathekGui; +import mediathek.controller.filmeLaden.ListenerFilmeLaden; +import mediathek.controller.filmeLaden.ListenerFilmeLadenEvent; +import mediathek.controller.io.starter.Start; +import mediathek.daten.DDaten; +import mediathek.daten.Daten; +import mediathek.daten.DatenDownload; +import mediathek.daten.DatenFilm; +import mediathek.daten.DatenPset; +import mediathek.gui.dialog.DialogDatenFilm; +import mediathek.gui.dialog.DialogEditDownload; +import mediathek.tool.BeobMpanel; +import mediathek.tool.CellRendererDownloads; +import mediathek.tool.Datum; +import mediathek.tool.GuiFunktionen; +import mediathek.tool.GuiKonstanten; +import mediathek.tool.HinweisKeineAuswahl; +import mediathek.tool.JTableMed; +import mediathek.tool.Konstanten; +import mediathek.tool.ListenerMediathekView; +import mediathek.tool.TModelDownload; + +public class GuiDownloads extends PanelVorlage { + + private DialogDatenFilm dialogDatenFilm = null; + private JTableMed tabelle; + + public GuiDownloads(DDaten d) { + super(d); + initComponents(); + tabelle = new JTableMed(JTableMed.TABELLE_TAB_DOWNLOADS); + jScrollPane1.setViewportView(tabelle); + dialogDatenFilm = new DialogDatenFilm(null, false, ddaten); + init(); + load(); + tabelle.initTabelle(); + } + //=================================== + //public + //=================================== + + @Override + public void isShown() { + super.isShown(); + ddaten.mediathekGui.setToolbar(MediathekGui.ButtonDonwload); + ddaten.infoPanel.setIdx(InfoPanel.IDX_GUI_DOWNLOAD); + } + + //toolbar + public void aktualisieren() { + Daten.setGeaendert(); + aufraeumen(); + ddaten.listeDownloads.abosLoschen(); + ddaten.listeDownloads.abosEintragen(); + load(); + } + + public void starten(boolean alle) { + filmStartenWiederholenStoppen(alle, true /* starten */); + } + + public void stoppen(boolean alle) { + filmStartenWiederholenStoppen(alle, false /* starten */); + } + + public void vorziehen() { + downloadVorziehen(); + } + + public void zurueckstellen() { + downloadLoeschen(false); + } + + public void loeschen() { + downloadLoeschen(true); + } + + public void aufraeumen() { + tabelleAufraeumen(); + } + + public void aendern() { + downloadAendern(); + } + + //=================================== + //private + //=================================== + private void init() { + jRadioButtonAbos.setForeground(GuiKonstanten.ABO_FOREGROUND); + jRadioButtonDownloads.setForeground(GuiKonstanten.DOWNLOAD_FOREGROUND); + tabelle.setDefaultRenderer(Object.class, new CellRendererDownloads(ddaten)); + tabelle.setDefaultRenderer(Datum.class, new CellRendererDownloads(ddaten)); + tabelle.setModel(new TModelDownload(new Object[][]{}, DatenDownload.DOWNLOAD_COLUMN_NAMES)); + tabelle.addMouseListener(new BeobMausTabelle()); + tabelle.getSelectionModel().addListSelectionListener(new BeobachterTableSelect1()); + //aendern + ActionMap am = tabelle.getActionMap(); + am.put("aendern", new BeobAbstractAction()); + InputMap im = tabelle.getInputMap(); + KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); + im.put(enter, "aendern"); + // + jRadioButtonAlles.addActionListener(new BeobAnzeige()); + jRadioButtonAbos.addActionListener(new BeobAnzeige()); + jRadioButtonDownloads.addActionListener(new BeobAnzeige()); + jCheckBoxFilter.addActionListener(new BeobMpanel(jCheckBoxFilter, jPanelFilter, "Filter")); + ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_LISTE_DOWNLOADS, GuiDownloads.class.getSimpleName()) { + @Override + public void ping() { + load(); + } + }); + ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_ART_DOWNLOAD_PROZENT, GuiDownloads.class.getSimpleName()) { + @Override + public void ping() { + tabelle.getSelected(); + ((TModelDownload) tabelle.getModel()).fireTableDataChanged(); + tabelle.setSelected(); + setInfo(); + //panelUpdate(); + } + }); + DDaten.filmeLaden.addAdListener(new ListenerFilmeLaden() { + @Override + public void fertig(ListenerFilmeLadenEvent event) { + if (Boolean.parseBoolean(Daten.system[Konstanten.SYSTEM_ABOS_SOFORT_SUCHEN_NR])) { + aktualisieren(); + } + } + }); + ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_LISTE_ABOS, GuiDownloads.class.getSimpleName()) { + @Override + public void ping() { + if (Boolean.parseBoolean(Daten.system[Konstanten.SYSTEM_ABOS_SOFORT_SUCHEN_NR])) { + aktualisieren(); + } + } + }); + ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_START_EVENT, GuiDownloads.class.getSimpleName()) { + @Override + public void ping() { + tabelle.getSelected(); + ((TModelDownload) tabelle.getModel()).fireTableDataChanged(); + tabelle.setSelected(); + setInfo(); + //panelUpdate(); + } + }); + } + + private void load() { + //Filme laden + boolean abo, download; + tabelle.getSpalten(); + if (jRadioButtonAlles.isSelected()) { + abo = true; + download = true; + } else if (jRadioButtonAbos.isSelected()) { + abo = true; + download = false; + } else { + abo = false; + download = true; + } + ddaten.listeDownloads.getModel((TModelDownload) tabelle.getModel(), abo, download); + ((TModelDownload) tabelle.getModel()).fireTableDataChanged(); + tabelle.setSpalten(); + setInfo(); + } + + private void downloadAendern() { + int rows[] = tabelle.getSelectedRows(); + if (rows.length > 0) { + for (int i = rows.length - 1; i >= 0; --i) { + int delRow = tabelle.convertRowIndexToModel(rows[i]); + String url = tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + DatenDownload d = download.getCopy(); + DialogEditDownload dialog = new DialogEditDownload(null, true, d); + dialog.setVisible(true); + if (dialog.ok) { + download.aufMichKopieren(d); + DDaten.setGeaendert(); + load(); + } + } + setInfo(); + } else { + new HinweisKeineAuswahl().zeigen(); + } + } + + private void downloadVorziehen() { + int row = tabelle.getSelectedRow(); + if (row != -1) { + int delRow = tabelle.convertRowIndexToModel(row); + String url = tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + DatenDownload download = ddaten.listeDownloads.downloadVorziehen(url); + if (download != null) { + // hat dann geklappt + load(); + setInfo(); + if (tabelle.getRowCount() > 0) { + tabelle.setRowSelectionInterval(0, 0); + tabelle.scrollRectToVisible(tabelle.getCellRect(0, 0, false)); + } + } + } else { + new HinweisKeineAuswahl().zeigen(); + } + } + + private void downloadLoeschen(boolean dauerhaft) { + int rows[] = tabelle.getSelectedRows(); + if (rows.length > 0) { + for (int i = rows.length - 1; i >= 0; --i) { + int delRow = tabelle.convertRowIndexToModel(rows[i]); + String url = tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + if (dauerhaft) { + if (download.istAbo()) { + // ein Abo wird zusätzlich ins Logfile geschrieben + ddaten.erledigteAbos.zeileSchreiben(download.arr[DatenDownload.DOWNLOAD_THEMA_NR], + download.arr[DatenDownload.DOWNLOAD_TITEL_NR], + url); + } + ddaten.listeDownloads.delDownloadByUrl(url); + } + ddaten.starterClass.filmLoeschen(tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString()); + ((TModelDownload) tabelle.getModel()).removeRow(delRow); + } + setInfo(); + } else { + new HinweisKeineAuswahl().zeigen(); + } + } + + private void filmStartenWiederholenStoppen(boolean alle, boolean starten /* starten/wiederstarten oder stoppen */) { + // bezieht sich immer auf "alle" oder nur die markierten + // Film der noch keinen Starts hat wird gestartet + // Film dessen Starts schon auf fertig/fehler steht wird wieder gestartet + // bei !starten wird der Film gestoppt + String[] urls; + String url; + // erst mal die URLs sammeln + if (alle) { + urls = new String[tabelle.getRowCount()]; + for (int i = 0; i < tabelle.getRowCount(); ++i) { + urls[i] = tabelle.getModel().getValueAt(i, DatenDownload.DOWNLOAD_URL_NR).toString(); + } + } else { + int[] rows = tabelle.getSelectedRows(); + urls = new String[rows.length]; + if (rows.length >= 0) { + for (int i = 0; i < rows.length; i++) { + int row = tabelle.convertRowIndexToModel(rows[i]); + url = tabelle.getModel().getValueAt(row, DatenDownload.DOWNLOAD_URL_NR).toString(); + urls[i] = url; + } + } else { + new HinweisKeineAuswahl().zeigen(); + } + } + // und jetzt abarbeiten + for (int i = 0; i < urls.length; ++i) { + url = urls[i]; + Start s = ddaten.starterClass.getStart(url); + if (s != null) { + // wenn kein s -> dann gibts auch nichts zum stoppen oder wieder-starten + if (!starten && s.status <= Start.STATUS_RUN) { + // löschen -> nur wenn noch läuft, sonst gibts nichts mehr zum löschen + ddaten.starterClass.filmLoeschen(url); + if (s.datenDownload.istAbo()) { + // bei Abos Url auch aus dem Logfile löschen, der Film ist damit wieder auf "Anfang" + ddaten.erledigteAbos.urlAusLogfileLoeschen(url); + } + } + if (starten && s.status > Start.STATUS_RUN) { + // wenn er schon fertig ist, erst mal fragen vor dem erneuten Starten + int a = JOptionPane.showConfirmDialog(null, "Film nochmal starten? ==> " + s.datenDownload.arr[DatenDownload.DOWNLOAD_TITEL_NR], "Fertiger Download", JOptionPane.YES_NO_OPTION); + if (a != JOptionPane.YES_OPTION) { + // weiter mit der nächsten URL + continue; + } + ddaten.starterClass.filmLoeschen(url); + if (s.datenDownload.istAbo()) { + // bei Abos Url auch aus dem Logfile löschen, der Film ist damit wieder auf "Anfang" + ddaten.erledigteAbos.urlAusLogfileLoeschen(url); + + } + } + } + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + if (starten) { + // jetzt noch starten/wiederstarten + // Start erstellen und zur Liste hinzufügen + download.startMelden(DatenDownload.PROGRESS_WARTEN); + ddaten.starterClass.addStarts(new Start(download)); + } else { + download.startMelden(DatenDownload.PROGRESS_NICHT_GESTARTET); + } + } // for() + setInfo(); + } + + private void stopWartende() { + // es werden alle noch nicht gestarteten Downloads gelöscht + for (int i = 0; i < tabelle.getRowCount(); ++i) { + int delRow = tabelle.convertRowIndexToModel(i); + String url = tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + Start s = ddaten.starterClass.getStart(url); + if (s != null) { + if (s.status < Start.STATUS_RUN) { + ddaten.starterClass.filmLoeschen(url); + } + } + setInfo(); + } + } + + private void tabelleAufraeumen() { + for (int i = tabelle.getRowCount() - 1; i >= 0; --i) { + int delRow = tabelle.convertRowIndexToModel(i); + String url = tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + Start s = ddaten.starterClass.getStart(url); + if (s != null) { + if (s.status >= Start.STATUS_FERTIG) { + ddaten.listeDownloads.delDownloadByUrl(url); + ((TModelDownload) tabelle.getModel()).removeRow(delRow); + } + } + } + setInfo(); + ddaten.starterClass.aufraeumen(); + } + +// private void panelUpdate() { +// setInfo(); +// tabelle.repaint(); +// this.validate(); +// } + private void setInfo() { + String textLinks; + // Text links: Zeilen Tabelle + int laufen = ddaten.starterClass.getDownloadsLaufen(); + int warten = ddaten.starterClass.getDownloadsWarten(); + int gesamt = tabelle.getModel().getRowCount(); + if (gesamt == 1) { + textLinks = "1 Download,"; + } else { + textLinks = gesamt + " Downloads,"; + } + textLinks += " ("; + if (laufen == 1) { + textLinks += "1 läuft,"; + } else { + textLinks += laufen + " laufen,"; + } + if (warten == 1) { + textLinks += " 1 wartet"; + } else { + textLinks += " " + warten + " warten"; + } + textLinks += ")"; + // Infopanel setzen + ddaten.infoPanel.setTextLinks(InfoPanel.IDX_GUI_DOWNLOAD, textLinks); + } + + private void table1Select() { + DatenFilm aktFilm = new DatenFilm(); + int selectedTableRow = tabelle.getSelectedRow(); + if (selectedTableRow >= 0) { + int selectedModelRow = tabelle.convertRowIndexToModel(selectedTableRow); + DatenFilm film = Daten.listeFilme.getFilmByUrl(tabelle.getModel().getValueAt(selectedModelRow, DatenDownload.DOWNLOAD_URL_NR).toString()); + if (film != null) { + aktFilm = film; + } + } + dialogDatenFilm.setAktFilm(aktFilm); + } + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroup1 = new javax.swing.ButtonGroup(); + jScrollPane1 = new javax.swing.JScrollPane(); + jTable1 = new javax.swing.JTable(); + jPanelFilter = new javax.swing.JPanel(); + jCheckBoxFilter = new javax.swing.JCheckBox(); + jPanelFilterInnen = new javax.swing.JPanel(); + jRadioButtonAlles = new javax.swing.JRadioButton(); + jRadioButtonDownloads = new javax.swing.JRadioButton(); + jRadioButtonAbos = new javax.swing.JRadioButton(); + + jTable1.setAutoCreateRowSorter(true); + jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); + jScrollPane1.setViewportView(jTable1); + + jPanelFilter.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); + + jCheckBoxFilter.setBackground(new java.awt.Color(217, 217, 217)); + jCheckBoxFilter.setFont(new java.awt.Font("Dialog", 1, 10)); // NOI18N + jCheckBoxFilter.setText("Filter"); + + buttonGroup1.add(jRadioButtonAlles); + jRadioButtonAlles.setSelected(true); + jRadioButtonAlles.setText(" alle"); + jRadioButtonAlles.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); + jRadioButtonAlles.setBorderPainted(true); + + buttonGroup1.add(jRadioButtonDownloads); + jRadioButtonDownloads.setText(" Downloads "); + jRadioButtonDownloads.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); + jRadioButtonDownloads.setBorderPainted(true); + + buttonGroup1.add(jRadioButtonAbos); + jRadioButtonAbos.setText(" Abos "); + jRadioButtonAbos.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); + jRadioButtonAbos.setBorderPainted(true); + + javax.swing.GroupLayout jPanelFilterInnenLayout = new javax.swing.GroupLayout(jPanelFilterInnen); + jPanelFilterInnen.setLayout(jPanelFilterInnenLayout); + jPanelFilterInnenLayout.setHorizontalGroup( + jPanelFilterInnenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanelFilterInnenLayout.createSequentialGroup() + .addContainerGap() + .addComponent(jRadioButtonAlles) + .addGap(18, 18, 18) + .addComponent(jRadioButtonDownloads) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jRadioButtonAbos) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + jPanelFilterInnenLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jRadioButtonAbos, jRadioButtonAlles, jRadioButtonDownloads}); + + jPanelFilterInnenLayout.setVerticalGroup( + jPanelFilterInnenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanelFilterInnenLayout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanelFilterInnenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(jRadioButtonAlles) + .addComponent(jRadioButtonDownloads) + .addComponent(jRadioButtonAbos)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + javax.swing.GroupLayout jPanelFilterLayout = new javax.swing.GroupLayout(jPanelFilter); + jPanelFilter.setLayout(jPanelFilterLayout); + jPanelFilterLayout.setHorizontalGroup( + jPanelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanelFilterInnen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jCheckBoxFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + jPanelFilterLayout.setVerticalGroup( + jPanelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanelFilterLayout.createSequentialGroup() + .addComponent(jCheckBoxFilter) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanelFilterInnen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 670, Short.MAX_VALUE) + .addComponent(jPanelFilter, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(jPanelFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) + .addContainerGap()) + ); + }// //GEN-END:initComponents + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.ButtonGroup buttonGroup1; + private javax.swing.JCheckBox jCheckBoxFilter; + private javax.swing.JPanel jPanelFilter; + private javax.swing.JPanel jPanelFilterInnen; + private javax.swing.JRadioButton jRadioButtonAbos; + private javax.swing.JRadioButton jRadioButtonAlles; + private javax.swing.JRadioButton jRadioButtonDownloads; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JTable jTable1; + // End of variables declaration//GEN-END:variables + + private class BeobachterTableSelect1 implements ListSelectionListener { + + public int selectedModelRow = -1; + + @Override + public void valueChanged(ListSelectionEvent event) { + if (!event.getValueIsAdjusting()) { + table1Select(); + } + } + } + + public class BeobMausTabelle extends MouseAdapter { + + private Point p; + + public BeobMausTabelle() { + } + + @Override + public void mouseClicked(MouseEvent arg0) { + if (arg0.getButton() == MouseEvent.BUTTON1) { + if (arg0.getClickCount() > 1) { + downloadAendern(); + } + } else if (arg0.getButton() == MouseEvent.BUTTON3) { + showMenu(arg0); + } + } + + private void showMenu(MouseEvent evt) { + p = evt.getPoint(); + int nr = tabelle.rowAtPoint(p); + if (nr >= 0) { + tabelle.setRowSelectionInterval(nr, nr); + } + JPopupMenu jPopupMenu = new JPopupMenu(); + //Film vorziehen + int row = tabelle.getSelectedRow(); + boolean wartenOderLaufen = false; + if (row >= 0) { + int delRow = tabelle.convertRowIndexToModel(row); + Start s = ddaten.starterClass.getStart(tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString()); + if (s != null) { + if (s.status <= Start.STATUS_RUN) { + wartenOderLaufen = true; + } + } + } + JMenuItem itemStarten = new JMenuItem("Download starten"); + itemStarten.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/player_play_16.png"))); + itemStarten.setEnabled(!wartenOderLaufen); + jPopupMenu.add(itemStarten); + itemStarten.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + filmStartenWiederholenStoppen(false /* alle */, true /* starten */); + } + }); + JMenuItem itemStoppen = new JMenuItem("Download stoppen"); + itemStoppen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/player_stop_16.png"))); + itemStoppen.setEnabled(wartenOderLaufen); + jPopupMenu.add(itemStoppen); + itemStoppen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + filmStartenWiederholenStoppen(false /* alle */, false /* starten */); + } + }); + + //####################################### + jPopupMenu.addSeparator(); + //####################################### + + JMenuItem itemVorziehen = new JMenuItem("Download vorziehen"); + itemVorziehen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/up_blue_16.png"))); + jPopupMenu.add(itemVorziehen); + itemVorziehen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadVorziehen(); + } + }); + JMenuItem itemLoeschen = new JMenuItem("Download zurückstellen"); + itemLoeschen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/undo_16.png"))); + jPopupMenu.add(itemLoeschen); + itemLoeschen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadLoeschen(false /* dauerhaft */); + } + }); + //dauerhaft löschen + JMenuItem itemDauerhaftLoeschen = new JMenuItem("Download dauerhaft löschen"); + itemDauerhaftLoeschen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/del_16.png"))); + jPopupMenu.add(itemDauerhaftLoeschen); + itemDauerhaftLoeschen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadLoeschen(true /* dauerhaft */); + } + }); + //ändern + JMenuItem itemAendern = new JMenuItem("Download Ändern"); + itemAendern.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/configure_16.png"))); + jPopupMenu.add(itemAendern); + itemAendern.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadAendern(); + } + }); + + //####################################### + jPopupMenu.addSeparator(); + //####################################### + + JMenuItem itemAlleStarten = new JMenuItem("alle Downloads starten"); + itemAlleStarten.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/next_16.png"))); + jPopupMenu.add(itemAlleStarten); + itemAlleStarten.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + filmStartenWiederholenStoppen(true /* alle */, true /* starten */); + } + }); + JMenuItem itemAlleStoppen = new JMenuItem("alle Downloads stoppen"); + itemAlleStoppen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/player_stop_16.png"))); + jPopupMenu.add(itemAlleStoppen); + itemAlleStoppen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + filmStartenWiederholenStoppen(true /* alle */, false /* starten */); + } + }); + JMenuItem itemWartendeStoppen = new JMenuItem("wartende Downloads stoppen"); + itemWartendeStoppen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/player_stop_16.png"))); + jPopupMenu.add(itemWartendeStoppen); + itemWartendeStoppen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + stopWartende(); + } + }); + JMenuItem itemAktualisieren = new JMenuItem("Liste der Downloads aktualisieren"); + itemAktualisieren.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/view-refresh_16.png"))); + jPopupMenu.add(itemAktualisieren); + itemAktualisieren.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + aktualisieren(); + } + }); + JMenuItem itemAufraeumen = new JMenuItem("Liste Aufräumen"); + itemAufraeumen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/edit-clear_16.png"))); + jPopupMenu.add(itemAufraeumen); + itemAufraeumen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + aufraeumen(); + } + }); + + //####################################### + jPopupMenu.addSeparator(); + //####################################### + + //url + JMenuItem itemUrl = new JMenuItem("URL kopieren"); + itemUrl.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + int nr = tabelle.rowAtPoint(p); + if (nr >= 0) { + GuiFunktionen.copyToClipboard( + tabelle.getModel().getValueAt(tabelle.convertRowIndexToModel(nr), + DatenDownload.DOWNLOAD_URL_NR).toString()); + } + } + }); + jPopupMenu.add(itemUrl); + //Player + JMenuItem itemPlayer = new JMenuItem("Film abspielen"); + itemPlayer.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + int nr = tabelle.rowAtPoint(p); + if (nr >= 0) { + DatenPset gruppe = ddaten.listePset.getPsetAbspielen(); + if (gruppe != null) { + int selectedModelRow = tabelle.convertRowIndexToModel(nr); + DatenFilm film = Daten.listeFilme.getFilmByUrl(tabelle.getModel().getValueAt(selectedModelRow, DatenDownload.DOWNLOAD_URL_NR).toString()); + if (film != null) { + // in die History eintragen + ddaten.history.add(film.getUrlOrg()); + // und starten + ddaten.starterClass.urlStarten(gruppe, film); + } + } else { + JOptionPane.showMessageDialog(null, "Im Menü unter \"Datei->Optionen->Videoplayer\" ein Programm zum Abspielen festlegen.", + "kein Videoplayer!", JOptionPane.INFORMATION_MESSAGE); + } + } + } + }); + jPopupMenu.add(itemPlayer); + //Infos + JMenuItem itemInfo = new JMenuItem("Infos anzeigen"); + itemInfo.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + dialogDatenFilm.setVis(); + } + }); + jPopupMenu.add(itemInfo); + // Tabellenspalten zurücksetzen + JMenuItem item = new JMenuItem("Spalten zurücksetzen"); + item.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + tabelle.resetTabelle(); + } + }); + jPopupMenu.add(item); + //Menü anzeigen + jPopupMenu.show(evt.getComponent(), evt.getX(), evt.getY()); + } + } + + private class BeobAbstractAction extends AbstractAction { + + @Override + public void actionPerformed(ActionEvent e) { + downloadAendern(); + } + } + + private class BeobAnzeige implements ActionListener { + + @Override + public void actionPerformed(ActionEvent e) { + load(); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `download` last assigned on line 256 could be null and is dereferenced at line 258. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GuiDownloads.downloadLoeschen(boolean) + +### Procedure Id: +mediathek.gui.GuiDownloads.downloadLoeschen(boolean):void.a71a3ec3efbdf0818498ea192700462e + +### File: +src/mediathek/gui/GuiDownloads.java + +### Key: +GuiDownloads.java|downloadLoeschen|NULL_DEREFERENCE + +### Node Key: +6cccac43c00eba65da104b6f3239cef0 + +### Hash: +6aa010171a0157b9869d3a8490d0266d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8933/instruction.md b/inferredbugs-8933/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..35558d49d3b8d46a77408a7ade70c8fcf7dbb547 --- /dev/null +++ b/inferredbugs-8933/instruction.md @@ -0,0 +1,408 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 27 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * 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 of the License, or + * 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, see . + */ +package mediathek.tool; + +import java.io.File; +import java.io.InputStream; +import java.util.Iterator; +import javax.swing.JOptionPane; +import mediathek.controller.io.IoXmlLesen; +import mediathek.daten.DDaten; +import mediathek.daten.Daten; +import mediathek.daten.DatenProg; +import mediathek.daten.DatenPset; +import mediathek.daten.ListePset; +import mediathek.file.GetFile; +import mediathek.gui.dialog.DialogHilfe; +import mediathek.gui.dialog.DialogOk; +import mediathek.gui.dialogEinstellungen.DialogImportPset; +import mediathek.gui.dialogEinstellungen.PanelProgrammPfade; + +public class GuiFunktionenProgramme { + + private static String getWindowsMplayerPath() { + //Für Windows den Pfad des VLC ermitteln + //sonst den deutschen Defaultpfad für Programme verwenden verwenden + final String PFAD_WIN_DEFAULT = "C:\\Program Files\\SMPlayer\\mplayer\\mplayer.exe"; + final String PFAD_WIN = "\\SMPlayer\\mplayer\\mplayer.exe"; + String vlcPfad; + try { + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + if (System.getenv("ProgramFiles") != null) { + vlcPfad = System.getenv("ProgramFiles") + PFAD_WIN; + if (new File(vlcPfad).exists()) { + return vlcPfad; + } + } + } + if (System.getenv("ProgramFiles(x86)") != null) { + vlcPfad = System.getenv("ProgramFiles(x86)") + PFAD_WIN; + if (new File(vlcPfad).exists()) { + return vlcPfad; + } + } + } catch (Exception ex) { + } + return PFAD_WIN_DEFAULT; + } + + private static String getWindowsVlcPath() { + //Für Windows den Pfad des VLC ermitteln + //sonst den deutschen Defaultpfad für Programme verwenden verwenden + final String PFAD_WIN_DEFAULT = "C:\\Programme\\VideoLAN\\VLC\\vlc.exe"; + final String PFAD_WIN = "\\VideoLAN\\VLC\\vlc.exe"; + String vlcPfad; + try { + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + if (System.getenv("ProgramFiles") != null) { + vlcPfad = System.getenv("ProgramFiles") + PFAD_WIN; + if (new File(vlcPfad).exists()) { + return vlcPfad; + } + } + } + if (System.getenv("ProgramFiles(x86)") != null) { + vlcPfad = System.getenv("ProgramFiles(x86)") + PFAD_WIN; + if (new File(vlcPfad).exists()) { + return vlcPfad; + } + } + } catch (Exception ex) { + } + return PFAD_WIN_DEFAULT; + } + + public static String getMusterPfadMplayer() { + final String PFAD_LINUX = "/usr/bin/mplayer"; + final String PFAD_MAC = "/opt/local/bin/mplayer"; + String pfad = ""; + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + pfad = getWindowsMplayerPath(); + } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { + pfad = PFAD_LINUX; + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + pfad = PFAD_MAC; + } + if (new File(pfad).exists()) { + return pfad; + } else { + return ""; + } + } + + public static String getMusterPfadVlc() { + final String PFAD_LINUX_VLC = "/usr/bin/vlc"; + final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC"; + String pfad = ""; + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + pfad = getWindowsVlcPath(); + } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { + pfad = PFAD_LINUX_VLC; + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + pfad = PFAD_MAC_VLC; + } + if (new File(pfad).exists()) { + return pfad; + } else { + return ""; + } + } + + public static String getMusterPfadFlv() { + final String PFAD_LINUX_FLV = "/usr/bin/flvstreamer"; + final String PFAD_WINDOWS_FLV = "bin\\flvstreamer_win32_latest.exe"; + final String PFAD_MAC_FLV = "bin\\flvstreamer_macosx_intel_32bit_latest"; + String pfad = ""; + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + pfad = Funktionen.getPathJar() + PFAD_WINDOWS_FLV; + } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { + pfad = PFAD_LINUX_FLV; + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + pfad = Funktionen.getPathJar() + PFAD_MAC_FLV; + } + if (new File(pfad).exists()) { + return pfad; + } else { + return ""; + } + } + + public static String getPfadMplayer() { + if (Daten.system[Konstanten.SYSTEM_PFAD_MPLAYER_NR].equals("")) { + new DialogOk(null, true, new PanelProgrammPfade(false /* vlc */, false /* flvstreamer */, true /* mplayer */), "Pfade Standardprogramme").setVisible(true); + } + return Daten.system[Konstanten.SYSTEM_PFAD_MPLAYER_NR]; + } + + public static String getPfadVlc() { + if (Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR].equals("")) { + new DialogOk(null, true, new PanelProgrammPfade(true /* vlc */, false /* flvstreamer */, false /* mplayer */), "Pfade Standardprogramme").setVisible(true); + } + return Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR]; + } + + public static String getPfadFlv() { + if (Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR].equals("")) { + new DialogOk(null, true, new PanelProgrammPfade(false /* vlc */, true /* flvstreamer */, false /* mplayer */), "Pfade Standardprogramme").setVisible(true); + } + return Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR]; + } + + public static String getPfadScript() { + String pfadScript; + final String PFAD_LINUX_SCRIPT = "bin/flv.sh"; + final String PFAD_WINDOWS_SCRIPT = "bin\\flv.bat"; + if (System.getProperty("os.name").toLowerCase().contains("linux")) { + pfadScript = Funktionen.getPathJar() + PFAD_LINUX_SCRIPT; + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + pfadScript = Funktionen.getPathJar() + PFAD_LINUX_SCRIPT; + } else { + pfadScript = Funktionen.getPathJar() + PFAD_WINDOWS_SCRIPT; + } + return pfadScript; + } + + public static ListePset getStandardprogramme(DDaten ddaten) { + ListePset pSet; + InputStream datei; + if (System.getProperty("os.name").toLowerCase().contains("linux")) { + datei = new GetFile().getPsetVorlageLinux(); + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + datei = new GetFile().getPsetVorlageMac(); + } else { + datei = new GetFile().getPsetVorlageWindows(); + } + // Standardgruppen laden + pSet = IoXmlLesen.importPset(datei, true); + return pSet; + } + + public static boolean addVorlagen(DDaten ddaten, ListePset pSet, boolean auto) { + // Standardgruppen laden + if (pSet != null) { + if (!auto) { + DialogImportPset dialog = new DialogImportPset(null, true, ddaten, pSet); + dialog.setVisible(true); + if (!dialog.ok) { + return false; + } + } + if (ddaten.listePset.addPset(pSet)) { + ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_LISTE_PSET, GuiFunktionenProgramme.class.getSimpleName()); + JOptionPane.showMessageDialog(null, pSet.size() + " Programmset importiert!", + "Ok", JOptionPane.INFORMATION_MESSAGE); + } + return true; + } else { + JOptionPane.showMessageDialog(null, "Die Datei wurde nicht importiert!", + "Fehler", JOptionPane.ERROR_MESSAGE); + return false; + } + } + + public static boolean praefixTesten(String str, String uurl, boolean praefix) { + //prüfen ob url beginnt/endet mit einem Argument in str + //wenn str leer dann true + boolean ret = false; + String url = uurl.toLowerCase(); + String s1 = ""; + if (str.equals("")) { + ret = true; + } else { + for (int i = 0; i < str.length(); ++i) { + if (str.charAt(i) != ',') { + s1 += str.charAt(i); + } + if (str.charAt(i) == ',' || i >= str.length() - 1) { + if (praefix) { + //Präfix prüfen + if (url.startsWith(s1.toLowerCase())) { + ret = true; + break; + } + } else { + //Suffix prüfen + if (url.endsWith(s1.toLowerCase())) { + ret = true; + break; + } + } + s1 = ""; + } + } + } + return ret; + } + + public static boolean checkPfadBeschreibbar(String pfad) { + boolean ret = false; + File testPfad = new File(pfad); + try { + if (!testPfad.exists()) { + testPfad.mkdirs(); + } + if (pfad.equals("")) { + } else if (!testPfad.isDirectory()) { + } else { + if (testPfad.canWrite()) { + File tmpFile = File.createTempFile("mediathek", "tmp", testPfad); + tmpFile.delete(); + ret = true; + } + } + } catch (Exception ex) { + } + return ret; + } + + public static boolean programmePruefen(DDaten daten) { + final String PIPE = "| "; + final String LEER = " "; + final String PFEIL = " -> "; + boolean ret = true; + String text = ""; + Iterator itPset = daten.listePset.iterator(); + DatenPset datenPset; + DatenProg datenProg; + while (itPset.hasNext()) { + datenPset = itPset.next(); + ret = true; + if (!datenPset.isFreeLine() && !datenPset.isLable()) { + // nur wenn kein Lable oder freeline + text += "++++++++++++++++++++++++++++++++++++++++++++" + "\n"; + text += PIPE + "Programmgruppe: " + datenPset.arr[DatenPset.PROGRAMMSET_NAME_NR] + "\n"; + String zielPfad = datenPset.arr[DatenPset.PROGRAMMSET_ZIEL_PFAD_NR]; + if (datenPset.progsContainPath()) { + // beim nur Abspielen wird er nicht gebraucht + if (zielPfad.equals("")) { + ret = false; + text += PIPE + LEER + "Zielpfad fehlt!\n"; + } else { + // Pfad beschreibbar? + if (!checkPfadBeschreibbar(zielPfad)) { + //da Pfad-leer und "kein" Pfad schon abgeprüft + ret = false; + text += PIPE + LEER + "Falscher Zielpfad!\n"; + text += PIPE + LEER + PFEIL + "Zielpfad \"" + zielPfad + "\" nicht beschreibbar!" + "\n"; + } + } + } + Iterator itProg = datenPset.getListeProg().iterator(); + while (itProg.hasNext()) { + datenProg = itProg.next(); + // Programmpfad prüfen + //if (!new File(datenProg.arr[Konstanten.PROGRAMM_PROGRAMMPFAD_NR]).exists()) { + if (!new File(datenProg.arr[DatenProg.PROGRAMM_PROGRAMMPFAD_NR]).canExecute()) { + // Programme prüfen + ret = false; + text += PIPE + LEER + "Falscher Programmpfad!\n"; + text += PIPE + LEER + PFEIL + "Programmname: " + datenProg.arr[DatenProg.PROGRAMM_NAME_NR] + "\n"; + text += PIPE + LEER + LEER + "Pfad: " + datenProg.arr[DatenProg.PROGRAMM_PROGRAMMPFAD_NR] + "\n"; + if (!datenProg.arr[DatenProg.PROGRAMM_PROGRAMMPFAD_NR].contains(File.separator)) { + text += PIPE + LEER + PFEIL + "Wenn das Programm nicht im Systempfad liegt, " + "\n"; + text += PIPE + LEER + LEER + "wird der Start nicht klappen!" + "\n"; + } + } + } + if (ret) { + //sollte alles passen + text += PIPE + PFEIL + "Ok!" + "\n"; + } + text += "++++++++++++++++++++++++++++++++++++++++++++" + "\n\n\n"; + } + } + new DialogHilfe(null, true, text).setVisible(true); + return ret; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getProperty("os.name")` could be null and is dereferenced at line 174. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String GuiFunktionenProgramme.getPfadScript() + +### Procedure Id: +mediathek.tool.GuiFunktionenProgramme.getPfadScript():java.lang.String.f4e3fc847474d1e03d713239d4dbdcd7 + +### File: +src/mediathek/tool/GuiFunktionenProgramme.java + +### Key: +GuiFunktionenProgramme.java|getPfadScript|NULL_DEREFERENCE + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +9243952ee193370e9da244e8b00b3c80 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8950/instruction.md b/inferredbugs-8950/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..088cd53c3bfb2034b3265f99f91fdd65c65722f7 --- /dev/null +++ b/inferredbugs-8950/instruction.md @@ -0,0 +1,1071 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 44 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * 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 of the License, or + * 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, see . + */ +package mediathek.gui; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Desktop; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.File; +import java.util.ArrayList; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPopupMenu; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import mediathek.MVStatusBar_Mac; +import mediathek.MediathekGui; +import mediathek.controller.filmeLaden.ListenerFilmeLaden; +import mediathek.controller.filmeLaden.ListenerFilmeLadenEvent; +import mediathek.controller.io.starter.Start; +import mediathek.daten.DDaten; +import mediathek.daten.Daten; +import mediathek.daten.DatenDownload; +import mediathek.daten.DatenFilm; +import mediathek.daten.DatenPset; +import mediathek.gui.dialog.DialogEditDownload; +import mediathek.gui.dialog.DialogProgrammOrdnerOeffnen; +import mediathek.gui.dialog.MVFilmInformation; +import mediathek.res.GetIcon; +import mediathek.tool.BeobMpanel; +import mediathek.tool.BeobTableHeader; +import mediathek.tool.CellRendererDownloads; +import mediathek.tool.Datum; +import mediathek.tool.GuiFunktionen; +import mediathek.tool.GuiKonstanten; +import mediathek.tool.HinweisKeineAuswahl; +import mediathek.tool.MVJTable; +import mediathek.tool.Konstanten; +import mediathek.tool.ListenerMediathekView; +import mediathek.tool.Log; +import mediathek.tool.MVMessageDialog; +import mediathek.tool.TModelDownload; + +public class GuiDownloads extends PanelVorlage { + + private MVFilmInformation filmInfoHud; + private PanelBeschreibung panelBeschreibung; + + public GuiDownloads(DDaten d, Component parentComponent) { + super(d, parentComponent); + initComponents(); + tabelle = new MVJTable(MVJTable.TABELLE_TAB_DOWNLOADS); + jScrollPane1.setViewportView(tabelle); + filmInfoHud = ddaten.filmInfoHud; + panelBeschreibung = new PanelBeschreibung(ddaten); + jPanelBeschreibung.setLayout(new BorderLayout()); + jPanelBeschreibung.add(panelBeschreibung, BorderLayout.CENTER); + init(); + downloadsAktualisieren(); // die Tabelle wird dabei gleich geladen + tabelle.initTabelle(); + if (tabelle.getRowCount() > 0) { + tabelle.setRowSelectionInterval(0, 0); + } + } + //=================================== + //public + //=================================== + + @Override + public void isShown() { + super.isShown(); + ddaten.mediathekGui.setToolbar(MediathekGui.UIButtonState.DOWNLOAD); + ddaten.mediathekGui.getStatusBar().setIndexForCenterDisplay(MVStatusBar_Mac.StatusbarIndex.DOWNLOAD); + aktFilmSetzen(); + } + + public void aktualisieren() { + downloadsAktualisieren(); + } + + public void starten(boolean alle) { + filmStartenWiederholenStoppen(alle, true /* starten */); + } + + public void stoppen(boolean alle) { + filmStartenWiederholenStoppen(alle, false /* starten */); + } + + public void vorziehen() { + downloadVorziehen(); + } + + public void zurueckstellen() { + downloadLoeschen(false); + } + + public void loeschen() { + downloadLoeschen(true); + } + + public void aufraeumen() { + downloadsAufraeumen(); + } + + public void aendern() { + downloadAendern(); + } + + //=================================== + //private + //=================================== + private void init() { + panelBeschreibungSetzen(); + jRadioButtonAbos.setForeground(GuiKonstanten.ABO_FOREGROUND); + jRadioButtonDownloads.setForeground(GuiKonstanten.DOWNLOAD_FOREGROUND); + tabelle.setDefaultRenderer(Object.class, new CellRendererDownloads(ddaten)); + tabelle.setDefaultRenderer(Datum.class, new CellRendererDownloads(ddaten)); + tabelle.setModel(new TModelDownload(new Object[][]{}, DatenDownload.COLUMN_NAMES)); + tabelle.addMouseListener(new BeobMausTabelle()); + tabelle.getSelectionModel().addListSelectionListener(new BeobachterTableSelect()); + tabelle.getTableHeader().addMouseListener(new BeobTableHeader(tabelle, DatenDownload.COLUMN_NAMES, DatenDownload.spaltenAnzeigen) { + @Override + public void tabelleLaden_() { + tabelleLaden(); + } + }); +// ist jetzt im Menü + //aendern +// ActionMap am = tabelle.getActionMap(); +// InputMap im = tabelle.getInputMap(); +// //aendern +// am.put("aendern", new BeobAbstractActionAendern()); +// KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); +// im.put(enter, "aendern"); +// //löschen +// am.put("loeschen", new BeobAbstractActionLoeschen()); +// KeyStroke del = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0); +// im.put(del, "loeschen"); +// // + jRadioButtonAlles.addActionListener(new BeobAnzeige()); + jRadioButtonAbos.addActionListener(new BeobAnzeige()); + jRadioButtonDownloads.addActionListener(new BeobAnzeige()); + jCheckBoxFilter.addActionListener(new BeobMpanel(jCheckBoxFilter, jPanelFilter, "Filter")); + ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_LISTE_DOWNLOADS, GuiDownloads.class.getSimpleName()) { + @Override + public void ping() { + tabelleLaden(); + } + }); + ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_ART_DOWNLOAD_PROZENT, GuiDownloads.class.getSimpleName()) { + @Override + public void ping() { + tabelleProzentGeaendert(); + } + }); + DDaten.filmeLaden.addAdListener(new ListenerFilmeLaden() { + @Override + public void fertig_(ListenerFilmeLadenEvent event) { + if (Boolean.parseBoolean(Daten.system[Konstanten.SYSTEM_ABOS_SOFORT_SUCHEN_NR])) { + downloadsAktualisieren(); + } + } + }); + ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_BLACKLIST_GEAENDERT, GuiDownloads.class.getSimpleName()) { + @Override + public void ping() { + if (Boolean.parseBoolean(Daten.system[Konstanten.SYSTEM_ABOS_SOFORT_SUCHEN_NR]) + && Boolean.parseBoolean(Daten.system[Konstanten.SYSTEM_BLACKLIST_AUCH_ABO_NR])) { + // nur auf Blacklist reagieren, wenn auch für Abos eingeschaltet + downloadsAktualisieren(); + } + } + }); + ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_LISTE_ABOS, GuiDownloads.class.getSimpleName()) { + @Override + public void ping() { + if (Boolean.parseBoolean(Daten.system[Konstanten.SYSTEM_ABOS_SOFORT_SUCHEN_NR])) { + downloadsAktualisieren(); + } + } + }); + ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_START_EVENT, GuiDownloads.class.getSimpleName()) { + @Override + public void ping() { + tabelle.fireTableDataChanged(true /*setSpalten*/); +// aktFilmSetzen(); + setInfo(); + } + }); + ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_PANEL_BESCHREIBUNG_ANZEIGEN, GuiDownloads.class.getSimpleName()) { + @Override + public void ping() { + panelBeschreibungSetzen(); + } + }); + } + + private void panelBeschreibungSetzen() { + jPanelBeschreibung.setVisible(Boolean.parseBoolean(DDaten.system[Konstanten.SYSTEM_PANEL_BESCHREIBUNG_ANZEIGEN_NR])); + } + + private synchronized void tabelleLaden() { + // nur Downloads die schon in der Liste sind werden geladen + boolean abo, download; + stopBeob = true; + tabelle.getSpalten(); + if (jRadioButtonAlles.isSelected()) { + abo = true; + download = true; + } else if (jRadioButtonAbos.isSelected()) { + abo = true; + download = false; + } else { + abo = false; + download = true; + } + ddaten.listeDownloads.getModel((TModelDownload) tabelle.getModel(), abo, download); + tabelle.setSpalten(); + stopBeob = false; + aktFilmSetzen(); + setInfo(); + } + + private synchronized void downloadsAktualisieren() { + // erledigte entfernen, nicht gestartete Abos entfernen und neu nach Abos suchen + downloadsAufraeumen(); + ddaten.listeDownloads.zurueckgestellteWiederAktivieren(); + ddaten.listeDownloads.abosLoschenWennNochNichtGestartet(); + ddaten.listeDownloads.abosSuchen(); + tabelleLaden(); + } + + private synchronized void downloadsAufraeumen() { + // abgeschlossene Downloads werden aus der Tabelle/Liste entfernt + // die Starts dafür werden auch gelöscht + ddaten.listeDownloads.listePutzen(); + } + + private synchronized void downloadAendern() { + int row = tabelle.getSelectedRow(); + if (row != -1) { + int delRow = tabelle.convertRowIndexToModel(row); + String url = tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + DatenDownload d = download.getCopy(); + DialogEditDownload dialog = new DialogEditDownload(null, true, ddaten, d); + dialog.setVisible(true); + if (dialog.ok) { + download.aufMichKopieren(d); + tabelle.getSelected(); + tabelleLaden(); + tabelle.setSelected(); + } + } else { + new HinweisKeineAuswahl().zeigen(parentComponent); + } + } + + private void downloadVorziehen() { + String[] urls; + ArrayList arrayUrls = new ArrayList(); + ArrayList arrayDownload = new ArrayList(); + // ========================== + // erst mal die URLs sammeln + int[] rows = tabelle.getSelectedRows(); + urls = new String[rows.length]; + if (rows.length >= 0) { + for (int i = 0; i < rows.length; i++) { + int row = tabelle.convertRowIndexToModel(rows[i]); + urls[i] = tabelle.getModel().getValueAt(row, DatenDownload.DOWNLOAD_URL_NR).toString(); + } + for (String url : urls) { + ddaten.listeDownloads.downloadVorziehen(url); + } + tabelleLaden(); + } else { + new HinweisKeineAuswahl().zeigen(parentComponent); + } + } + + private void zielordnerOeffnen() { + boolean gut = false; + File sFile = null; + int row = tabelle.getSelectedRow(); + if (row >= 0) { + String url = tabelle.getModel().getValueAt(tabelle.convertRowIndexToModel(row), DatenDownload.DOWNLOAD_URL_NR).toString(); + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + String s = download.arr[DatenDownload.DOWNLOAD_ZIEL_PFAD_NR]; + if (!s.endsWith(File.separator)) { + s += File.separator; + } + try { + sFile = new File(s); + if (!sFile.exists()) { + sFile = sFile.getParentFile(); + } + if (Desktop.isDesktopSupported()) { + Desktop d = Desktop.getDesktop(); + if (d.isSupported(Desktop.Action.OPEN)) { + d.open(sFile); + gut = true; + } + } + } catch (Exception ex) { + try { + gut = false; + String programm = ""; + if (Daten.system[Konstanten.SYSTEM_ORDNER_OEFFNEN_NR].equals("")) { + String text = "\n Der Dateimanager zum Anzeigen des Speicherordners wird nicht gefunden.\n Dateimanager selbst auswählen."; + DialogProgrammOrdnerOeffnen dialog = new DialogProgrammOrdnerOeffnen(ddaten.mediathekGui, ddaten, true, "", "Dateimanager suchen", text); + dialog.setVisible(true); + if (dialog.ok) { + programm = dialog.ziel; + } + } else { + programm = Daten.system[Konstanten.SYSTEM_ORDNER_OEFFNEN_NR]; + } + if (sFile != null) { + Runtime.getRuntime().exec(programm + " " + sFile.getAbsolutePath()); + Daten.system[Konstanten.SYSTEM_ORDNER_OEFFNEN_NR] = programm; + ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_PROGRAMM_OEFFNEN, GuiDownloads.class.getSimpleName()); + gut = true; + } + } catch (Exception eex) { + Log.fehlerMeldung(306590789, Log.FEHLER_ART_PROG, GuiDownloads.class.getName(), ex, "Ordner öffnen: " + download.arr[DatenDownload.DOWNLOAD_ZIEL_PFAD_NR]); + } + } finally { + if (!gut) { + Daten.system[Konstanten.SYSTEM_ORDNER_OEFFNEN_NR] = ""; + ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_PROGRAMM_OEFFNEN, GuiDownloads.class.getSimpleName()); + MVMessageDialog.showMessageDialog(parentComponent, "Kann den Dateimanager nicht öffnen!", + "Fehler", JOptionPane.ERROR_MESSAGE); + } + } + } else { + new HinweisKeineAuswahl().zeigen(parentComponent); + } + } + + private void downloadLoeschen(boolean dauerhaft) { + int rows[] = tabelle.getSelectedRows(); + if (rows.length > 0) { + ArrayList arrayUrls = new ArrayList(); + ArrayList arrayUrlsAbo = new ArrayList(); + for (int i = 0; i < rows.length; ++i) { + arrayUrls.add(tabelle.getModel().getValueAt(tabelle.convertRowIndexToModel(rows[i]), DatenDownload.DOWNLOAD_URL_NR).toString()); + } + for (String url : arrayUrls) { + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + if (dauerhaft) { + if (download.istAbo()) { + // ein Abo wird zusätzlich ins Logfile geschrieben + arrayUrlsAbo.add(new String[]{download.arr[DatenDownload.DOWNLOAD_THEMA_NR], + download.arr[DatenDownload.DOWNLOAD_TITEL_NR], + download.arr[DatenDownload.DOWNLOAD_FILM_URL_NR]}); + } + ddaten.listeDownloads.delDownloadByUrl(url); + } else { + // wenn nicht dauerhaft + download.zurueckstellen(); + } + } + if (arrayUrlsAbo.size() > 0) { + ddaten.erledigteAbos.zeileSchreiben(arrayUrlsAbo); + } + ddaten.starterClass.filmLoeschen(arrayUrls); + tabelleLaden(); + ersteZeileMarkieren(); + } else { + new HinweisKeineAuswahl().zeigen(parentComponent); + } + } + + private void ersteZeileMarkieren() { + if (tabelle.getRowCount() > 0) { + // sonst ist schon eine Zeile markiert + if (tabelle.getSelectedRow() == -1) { + tabelle.requestFocus(); + tabelle.setRowSelectionInterval(0, 0); + } + } + + } + + private void filmStartenWiederholenStoppen(boolean alle, boolean starten /* starten/wiederstarten oder stoppen */) { + // bezieht sich immer auf "alle" oder nur die markierten + // Film der noch keinen Starts hat wird gestartet + // Film dessen Start schon auf fertig/fehler steht wird wieder gestartet + // bei !starten wird der Film gestoppt + String[] urls; + ArrayList arrayUrls = new ArrayList(); + ArrayList arrayDownload = new ArrayList(); + // ========================== + // erst mal die URLs sammeln + if (alle) { + urls = new String[tabelle.getRowCount()]; + for (int i = 0; i < tabelle.getRowCount(); ++i) { + urls[i] = tabelle.getModel().getValueAt(i, DatenDownload.DOWNLOAD_URL_NR).toString(); + } + } else { + int[] rows = tabelle.getSelectedRows(); + urls = new String[rows.length]; + if (rows.length >= 0) { + for (int i = 0; i < rows.length; i++) { + int row = tabelle.convertRowIndexToModel(rows[i]); + urls[i] = tabelle.getModel().getValueAt(row, DatenDownload.DOWNLOAD_URL_NR).toString(); + } + } else { + new HinweisKeineAuswahl().zeigen(parentComponent); + } + } + if (!starten) { + // dann das Starten von neuen Downloads etwas Pausieren + ddaten.starterClass.pause(); + } + // ======================== + // und jetzt abarbeiten + for (String url : urls) { + Start s = ddaten.starterClass.getStart(url); + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + if (starten) { + // -------------- + // starten + if (s != null) { + if (s.status > Start.STATUS_RUN) { + // wenn er noch läuft gibts nix + // wenn er schon fertig ist, erst mal fragen vor dem erneuten Starten + int a = JOptionPane.showConfirmDialog(parentComponent, "Film nochmal starten? ==> " + s.datenDownload.arr[DatenDownload.DOWNLOAD_TITEL_NR], "Fertiger Download", JOptionPane.YES_NO_OPTION); + if (a != JOptionPane.YES_OPTION) { + // weiter mit der nächsten URL + continue; + } + arrayUrls.add(url); + //ddaten.starterClass.filmLoeschen(url); + if (s.datenDownload.istAbo()) { + // wenn er schon feritg ist und ein Abos ist, Url auch aus dem Logfile löschen, der Film ist damit wieder auf "Anfang" + ddaten.erledigteAbos.urlAusLogfileLoeschen(url); + } + } + } + arrayDownload.add(download); + } else { + // --------------- + // stoppen + if (s != null) { + // wenn kein s -> dann gibts auch nichts zum stoppen oder wieder-starten + if (s.status <= Start.STATUS_RUN) { + // löschen -> nur wenn noch läuft, sonst gibts nichts mehr zum löschen + arrayUrls.add(url); + //ddaten.starterClass.filmLoeschen(url); + } +//// if (s.status > Start.STATUS_RUN) { +//// // wenn er schon feritg ist und ein Abos ist, Url auch aus dem Logfile löschen, der Film ist damit wieder auf "Anfang" +//// if (s.datenDownload.istAbo()) { +//// ddaten.erledigteAbos.urlAusLogfileLoeschen(url); +//// } +//// } + arrayDownload.add(download); + } + } + } + // ======================== + // jetzt noch die Starts stoppen + ddaten.starterClass.filmLoeschen(arrayUrls); + // und die Downloads starten oder stoppen + if (starten) { + //alle Downloads starten/wiederstarten + DatenDownload.starten(ddaten, arrayDownload); + } else { + //oder alle Downloads stoppen +// tabelleProzentGeaendert(); + ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_ART_DOWNLOAD_PROZENT, GuiDownloads.class.getName()); +// DatenDownload.statusMelden(arrayDownload, DatenDownload.PROGRESS_NICHT_GESTARTET); + } + } + + private void stopWartende() { + // es werden alle noch nicht gestarteten Downloads gelöscht + ArrayList urls = new ArrayList(); + for (int i = 0; i < tabelle.getRowCount(); ++i) { + int delRow = tabelle.convertRowIndexToModel(i); + String url = tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + Start s = ddaten.starterClass.getStart(url); + if (s != null) { + if (s.status < Start.STATUS_RUN) { + urls.add(url); + } + } + } + for (String url : urls) { + ddaten.starterClass.filmLoeschen(url); + } + } + + private void tabelleProzentGeaendert() { + stopBeob = true; + tabelle.fireTableDataChanged(true /*setSpalten*/); + stopBeob = false; + setInfo(); + } + + private void setInfo() { + String textLinks; + // Text links: Zeilen Tabelle + int laufen = ddaten.starterClass.getDownloadsLaufen(); + int warten = ddaten.starterClass.getDownloadsWarten(); + int gesamt = tabelle.getModel().getRowCount(); + if (gesamt == 1) { + textLinks = "1 Download,"; + } else { + textLinks = gesamt + " Downloads,"; + } + textLinks += " ("; + if (laufen == 1) { + textLinks += "1 läuft,"; + } else { + textLinks += laufen + " laufen,"; + } + if (warten == 1) { + textLinks += " 1 wartet"; + } else { + textLinks += " " + warten + " warten"; + } + textLinks += ")"; + // Infopanel setzen + ddaten.mediathekGui.getStatusBar().setTextLeft(MVStatusBar_Mac.StatusbarIndex.DOWNLOAD, textLinks); + } + + private void aktFilmSetzen() { + if (this.isShowing()) { + DatenFilm aktFilm = null; + int selectedTableRow = tabelle.getSelectedRow(); + if (selectedTableRow >= 0) { + int selectedModelRow = tabelle.convertRowIndexToModel(selectedTableRow); + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(tabelle.getModel().getValueAt(selectedModelRow, DatenDownload.DOWNLOAD_URL_NR).toString()); + if (download.film == null) { + // geladener Einmaldownload nach Programmstart + download.film = Daten.listeFilme.getFilmByUrl(tabelle.getModel().getValueAt(selectedModelRow, DatenDownload.DOWNLOAD_URL_NR).toString()); + } else { + aktFilm = download.film; + } + } + filmInfoHud.updateCurrentFilm(aktFilm); + // Beschreibung setzen + panelBeschreibung.setAktFilm(aktFilm); + } + } + + /** + * This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // //GEN-BEGIN:initComponents + private void initComponents() { + + javax.swing.ButtonGroup buttonGroup1 = new javax.swing.ButtonGroup(); + jScrollPane1 = new javax.swing.JScrollPane(); + javax.swing.JTable jTable1 = new javax.swing.JTable(); + jPanelFilter = new javax.swing.JPanel(); + jCheckBoxFilter = new javax.swing.JCheckBox(); + javax.swing.JPanel jPanelFilterInnen = new javax.swing.JPanel(); + jRadioButtonAlles = new javax.swing.JRadioButton(); + jRadioButtonDownloads = new javax.swing.JRadioButton(); + jRadioButtonAbos = new javax.swing.JRadioButton(); + jPanelBeschreibung = new javax.swing.JPanel(); + + jTable1.setAutoCreateRowSorter(true); + jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); + jScrollPane1.setViewportView(jTable1); + + jPanelFilter.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); + + jCheckBoxFilter.setBackground(new java.awt.Color(217, 217, 217)); + jCheckBoxFilter.setFont(new java.awt.Font("Dialog", 1, 10)); // NOI18N + jCheckBoxFilter.setText("Filter"); + + buttonGroup1.add(jRadioButtonAlles); + jRadioButtonAlles.setSelected(true); + jRadioButtonAlles.setText(" alle"); + jRadioButtonAlles.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); + jRadioButtonAlles.setBorderPainted(true); + + buttonGroup1.add(jRadioButtonDownloads); + jRadioButtonDownloads.setText(" Downloads "); + jRadioButtonDownloads.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); + jRadioButtonDownloads.setBorderPainted(true); + + buttonGroup1.add(jRadioButtonAbos); + jRadioButtonAbos.setText(" Abos "); + jRadioButtonAbos.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); + jRadioButtonAbos.setBorderPainted(true); + + javax.swing.GroupLayout jPanelFilterInnenLayout = new javax.swing.GroupLayout(jPanelFilterInnen); + jPanelFilterInnen.setLayout(jPanelFilterInnenLayout); + jPanelFilterInnenLayout.setHorizontalGroup( + jPanelFilterInnenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanelFilterInnenLayout.createSequentialGroup() + .addContainerGap() + .addComponent(jRadioButtonAlles) + .addGap(18, 18, 18) + .addComponent(jRadioButtonDownloads) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jRadioButtonAbos) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + jPanelFilterInnenLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jRadioButtonAbos, jRadioButtonAlles, jRadioButtonDownloads}); + + jPanelFilterInnenLayout.setVerticalGroup( + jPanelFilterInnenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanelFilterInnenLayout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanelFilterInnenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(jRadioButtonAlles) + .addComponent(jRadioButtonDownloads) + .addComponent(jRadioButtonAbos)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + javax.swing.GroupLayout jPanelFilterLayout = new javax.swing.GroupLayout(jPanelFilter); + jPanelFilter.setLayout(jPanelFilterLayout); + jPanelFilterLayout.setHorizontalGroup( + jPanelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanelFilterInnen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jCheckBoxFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + jPanelFilterLayout.setVerticalGroup( + jPanelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanelFilterLayout.createSequentialGroup() + .addComponent(jCheckBoxFilter) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanelFilterInnen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + ); + + jPanelBeschreibung.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); + + javax.swing.GroupLayout jPanelBeschreibungLayout = new javax.swing.GroupLayout(jPanelBeschreibung); + jPanelBeschreibung.setLayout(jPanelBeschreibungLayout); + jPanelBeschreibungLayout.setHorizontalGroup( + jPanelBeschreibungLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 668, Short.MAX_VALUE) + ); + jPanelBeschreibungLayout.setVerticalGroup( + jPanelBeschreibungLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 127, Short.MAX_VALUE) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanelFilter, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jPanelBeschreibung, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(jPanelFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanelBeschreibung, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(6, 6, 6)) + ); + }// //GEN-END:initComponents + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JCheckBox jCheckBoxFilter; + private javax.swing.JPanel jPanelBeschreibung; + private javax.swing.JPanel jPanelFilter; + private javax.swing.JRadioButton jRadioButtonAbos; + private javax.swing.JRadioButton jRadioButtonAlles; + private javax.swing.JRadioButton jRadioButtonDownloads; + private javax.swing.JScrollPane jScrollPane1; + // End of variables declaration//GEN-END:variables + + private class BeobachterTableSelect implements ListSelectionListener { + + @Override + public void valueChanged(ListSelectionEvent event) { + if (!event.getValueIsAdjusting()) { + aktFilmSetzen(); + } + } + } + + public class BeobMausTabelle extends MouseAdapter { + + private Point p; + + public BeobMausTabelle() { + } + + @Override + public void mouseClicked(MouseEvent arg0) { + if (arg0.getButton() == MouseEvent.BUTTON1) { +// aktFilmSetzen(); //da gibts keine Schwierigkeiten beim update des JProgressbar + if (arg0.getClickCount() > 1) { + downloadAendern(); + } + } + } + + @Override + public void mousePressed(MouseEvent arg0) { +// aktFilmSetzen(); + if (arg0.isPopupTrigger()) { + showMenu(arg0); + } + } + + @Override + public void mouseReleased(MouseEvent arg0) { +// aktFilmSetzen(); + if (arg0.isPopupTrigger()) { + showMenu(arg0); + } + } + + private void showMenu(MouseEvent evt) { + p = evt.getPoint(); + int nr = tabelle.rowAtPoint(p); + if (nr >= 0) { + tabelle.setRowSelectionInterval(nr, nr); + } + JPopupMenu jPopupMenu = new JPopupMenu(); + + //Film vorziehen + int row = tabelle.getSelectedRow(); + boolean wartenOderLaufen = false; + if (row >= 0) { + int delRow = tabelle.convertRowIndexToModel(row); + Start s = ddaten.starterClass.getStart(tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString()); + if (s != null) { + if (s.status <= Start.STATUS_RUN) { + wartenOderLaufen = true; + } + } + } + + // Download starten + JMenuItem itemStarten = new JMenuItem("Download starten"); + itemStarten.setIcon(GetIcon.getIcon("player_play_16.png")); + itemStarten.setEnabled(!wartenOderLaufen); + jPopupMenu.add(itemStarten); + itemStarten.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + filmStartenWiederholenStoppen(false /* alle */, true /* starten */); + } + }); + + // Download stoppen + JMenuItem itemStoppen = new JMenuItem("Download stoppen"); + itemStoppen.setIcon(GetIcon.getIcon("player_stop_16.png")); + itemStoppen.setEnabled(wartenOderLaufen); + jPopupMenu.add(itemStoppen); + itemStoppen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + filmStartenWiederholenStoppen(false /* alle */, false /* starten */); + } + }); + + // Zielordner öffnen + JMenuItem itemOeffnen = new JMenuItem("Zielordner öffnen"); + itemOeffnen.setIcon(GetIcon.getIcon("fileopen_16.png")); + jPopupMenu.add(itemOeffnen); + itemOeffnen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + zielordnerOeffnen(); + } + }); + + + //####################################### + jPopupMenu.addSeparator(); + //####################################### + + JMenuItem itemVorziehen = new JMenuItem("Download vorziehen"); + itemVorziehen.setIcon(GetIcon.getIcon("move_up_16.png")); + jPopupMenu.add(itemVorziehen); + itemVorziehen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadVorziehen(); + } + }); + JMenuItem itemLoeschen = new JMenuItem("Download zurückstellen"); + itemLoeschen.setIcon(GetIcon.getIcon("undo_16.png")); + jPopupMenu.add(itemLoeschen); + itemLoeschen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadLoeschen(false /* dauerhaft */); + } + }); + //dauerhaft löschen + JMenuItem itemDauerhaftLoeschen = new JMenuItem("Download dauerhaft löschen"); + itemDauerhaftLoeschen.setIcon(GetIcon.getIcon("del_16.png")); + jPopupMenu.add(itemDauerhaftLoeschen); + itemDauerhaftLoeschen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadLoeschen(true /* dauerhaft */); + } + }); + //ändern + JMenuItem itemAendern = new JMenuItem("Download Ändern"); + itemAendern.setIcon(GetIcon.getIcon("configure_16.png")); + jPopupMenu.add(itemAendern); + itemAendern.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadAendern(); + } + }); + + //####################################### + jPopupMenu.addSeparator(); + //####################################### + + JMenuItem itemAlleStarten = new JMenuItem("alle Downloads starten"); + itemAlleStarten.setIcon(GetIcon.getIcon("alle_starten_16.png")); + jPopupMenu.add(itemAlleStarten); + itemAlleStarten.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + filmStartenWiederholenStoppen(true /* alle */, true /* starten */); + } + }); + JMenuItem itemAlleStoppen = new JMenuItem("alle Downloads stoppen"); + itemAlleStoppen.setIcon(GetIcon.getIcon("player_stop_16.png")); + jPopupMenu.add(itemAlleStoppen); + itemAlleStoppen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + filmStartenWiederholenStoppen(true /* alle */, false /* starten */); + } + }); + JMenuItem itemWartendeStoppen = new JMenuItem("wartende Downloads stoppen"); + itemWartendeStoppen.setIcon(GetIcon.getIcon("player_stop_16.png")); + jPopupMenu.add(itemWartendeStoppen); + itemWartendeStoppen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + stopWartende(); + } + }); + JMenuItem itemAktualisieren = new JMenuItem("Liste der Downloads aktualisieren"); + itemAktualisieren.setIcon(GetIcon.getIcon("view-refresh_16.png")); + jPopupMenu.add(itemAktualisieren); + itemAktualisieren.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadsAktualisieren(); + } + }); + JMenuItem itemAufraeumen = new JMenuItem("Liste Aufräumen"); + itemAufraeumen.setIcon(GetIcon.getIcon("clear_16.png")); + jPopupMenu.add(itemAufraeumen); + itemAufraeumen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadsAufraeumen(); + } + }); + + //####################################### + jPopupMenu.addSeparator(); + //####################################### + + // url + JMenuItem itemUrl = new JMenuItem("URL kopieren"); + itemUrl.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + int nr = tabelle.rowAtPoint(p); + if (nr >= 0) { + GuiFunktionen.copyToClipboard( + tabelle.getModel().getValueAt(tabelle.convertRowIndexToModel(nr), + DatenDownload.DOWNLOAD_URL_NR).toString()); + } + } + }); + jPopupMenu.add(itemUrl); + + // Player + JMenuItem itemPlayer = new JMenuItem("Film abspielen"); + itemPlayer.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + int nr = tabelle.rowAtPoint(p); + if (nr >= 0) { + DatenPset gruppe = ddaten.listePset.getPsetAbspielen(); + if (gruppe != null) { + int selectedModelRow = tabelle.convertRowIndexToModel(nr); + String url = tabelle.getModel().getValueAt(selectedModelRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + //String filmNr = tabelle.getModel().getValueAt(selectedModelRow, DatenDownload.DOWNLOAD_FILM_NR_NR).toString(); + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + //DatenFilm film = Daten.listeFilme.getFilmByNr(filmNr); + if (download != null) { + //DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + if (download.film == null) { + // bei Einmaldownload nach Programmstart + download.film = Daten.listeFilme.getFilmByUrl(url); + } + DatenFilm filmDownload = download.film.getCopy(); + // und jetzt die tatsächlichen URLs des Downloads eintragen + filmDownload.arr[DatenFilm.FILM_URL_NR] = download.arr[DatenDownload.DOWNLOAD_URL_NR]; + filmDownload.arr[DatenFilm.FILM_URL_RTMP_NR] = download.arr[DatenDownload.DOWNLOAD_URL_RTMP_NR]; + filmDownload.arr[DatenFilm.FILM_URL_KLEIN_NR] = ""; + filmDownload.arr[DatenFilm.FILM_URL_RTMP_KLEIN_NR] = ""; + // in die History eintragen + //ddaten.history.add(film.getUrlNormal()); + // und starten + ddaten.starterClass.urlStarten(gruppe, filmDownload); + } + } else { + MVMessageDialog.showMessageDialog(parentComponent, "Im Menü unter \"Datei->Optionen->Videoplayer\" ein Programm zum Abspielen festlegen.", + "kein Videoplayer!", JOptionPane.INFORMATION_MESSAGE); + } + } + } + }); + jPopupMenu.add(itemPlayer); + + // Infos + JMenuItem itemInfo = new JMenuItem("Infos anzeigen"); + itemInfo.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (!filmInfoHud.isVisible()) { + filmInfoHud.show(); + } + } + }); + jPopupMenu.add(itemInfo); + + // ###################### + // Menü anzeigen + jPopupMenu.show(evt.getComponent(), evt.getX(), evt.getY()); + } + } + +// private class BeobAbstractActionAendern extends AbstractAction { +// +// @Override +// public void actionPerformed(ActionEvent e) { +// downloadAendern(); +// } +// } +// +// private class BeobAbstractActionLoeschen extends AbstractAction { +// +// @Override +// public void actionPerformed(ActionEvent e) { +// downloadLoeschen(true); +// } +// } + private class BeobAnzeige implements ActionListener { + + @Override + public void actionPerformed(ActionEvent e) { + tabelleLaden(); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `download` last assigned on line 556 could be null and is dereferenced at line 557. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GuiDownloads.aktFilmSetzen() + +### Procedure Id: +mediathek.gui.GuiDownloads.aktFilmSetzen():void.c1d2911746eadb64a75346fa1e2fbbf1 + +### File: +src/mediathek/gui/GuiDownloads.java + +### Key: +GuiDownloads.java|aktFilmSetzen|NULL_DEREFERENCE + +### Node Key: +151541eced37bb787cd76e7bc7cd8f29 + +### Hash: +0957349f9c3b753e6914336f4513c4bc + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8957/instruction.md b/inferredbugs-8957/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0a8998f0925045c6e0f432541dee093681fe3ee7 --- /dev/null +++ b/inferredbugs-8957/instruction.md @@ -0,0 +1,361 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 53 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * 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 of the License, or + * 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, see . + */ +package mediathek.controller.filmeLaden.suchen.sender; + +import mediathek.controller.filmeLaden.suchen.FilmeSuchenSender; +import mediathek.controller.io.GetUrl; +import mediathek.daten.Daten; +import mediathek.daten.DatenFilm; +import mediathek.tool.Konstanten; +import mediathek.tool.Log; +import mediathek.tool.MVStringBuilder; +import org.apache.commons.lang3.StringEscapeUtils; + +public class MediathekKika extends MediathekReader implements Runnable { + + public static final String SENDER = "KiKA"; + private MVStringBuilder seiteHttp = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); + + public MediathekKika(FilmeSuchenSender ssearch, int startPrio) { + super(ssearch, /* name */ SENDER, /* threads */ 2, /* urlWarten */ 500, startPrio); + } + + @Override + synchronized void meldungThreadUndFertig() { + if (threads <= 1) { + // vorher noch laufen + addToListHttp(); + } + --threads; + if (threads <= 0) { + //wird erst ausgeführt wenn alle Threads beendet sind + suchen.meldenFertig(nameSenderMReader); + } else { + // läuft noch was + suchen.melden(nameSenderMReader, max, progress, "" /* text */); + } + } + + @Override + void addToList() { + //Sesamstraße präsentiert: Eine Möhre für Zwei
    + //42. Ordnung ist das halbe Chaos
    + //41. Über den Wolken
    + final String ADRESSE = "http://kikaplus.net/clients/kika/kikaplus/"; + final String MUSTER_URL = ""; + final String MUSTER_DATUM = "title=\"Sendung vom "; + listeThemen.clear(); + MVStringBuilder seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); + meldungStart(); + seite = getUrlIo.getUri(nameSenderMReader, ADRESSE, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite"); + int pos = 0; + int pos1, pos2, stop, pDatum1, pDatum2, pTitel1, pTitel2; + String url, thema, datum, titel; + while ((pos = seite.indexOf(MUSTER_THEMA, pos)) != -1) { + try { + thema = ""; + pos += MUSTER_THEMA.length(); + stop = seite.indexOf(MUSTER_THEMA, pos); + pos1 = pos; + if ((pos2 = seite.indexOf("<", pos1)) != -1) { + thema = seite.substring(pos1, pos2); + } + while ((pos1 = seite.indexOf(MUSTER_URL, pos1)) != -1) { + titel = ""; + datum = ""; + if (stop != -1 && pos1 > stop) { + // dann schon das nächste Thema + break; + } + pos1 += MUSTER_URL.length(); + if ((pos2 = seite.indexOf("\"", pos1)) != -1) { + url = seite.substring(pos1, pos2); + //if (!url.equals("")) { + url = StringEscapeUtils.unescapeXml(url); + if (!url.equals("") && !url.startsWith("http://") && !url.startsWith("/")) { // Datum + if ((pDatum1 = seite.indexOf(MUSTER_DATUM, pos2)) != -1) { + pDatum1 += MUSTER_DATUM.length(); + if ((pDatum2 = seite.indexOf("\"", pDatum1)) != -1) { + if (stop != -1 && pDatum1 < stop && pDatum2 < stop) { + // dann schon das nächste Thema + datum = seite.substring(pDatum1, pDatum2); + } + } + } + + // Titel + if ((pTitel1 = seite.indexOf(">", pos2)) != -1) { + pTitel1 += 1; + if ((pTitel2 = seite.indexOf("<", pTitel1)) != -1) { + //if (stop != -1 && pTitel1 > stop && pTitel2 > stop) { + if (stop != -1 && pTitel1 < stop && pTitel2 < stop) { + titel = seite.substring(pTitel1, pTitel2); + } + } + } + // in die Liste eintragen + String[] add = new String[]{ADRESSE + url, thema, titel, datum}; + listeThemen.addUrl(add); + } + } + } + } catch (Exception ex) { + Log.fehlerMeldung(-302025469, Log.FEHLER_ART_MREADER, "MediathekKiKA.addToList", ex, ""); + } + } + if (Daten.filmeLaden.getStop()) { + meldungThreadUndFertig(); + } else if (listeThemen.size() == 0) { + meldungThreadUndFertig(); + } else { + listeSort(listeThemen, 1); + meldungAddMax(listeThemen.size()); + for (int t = 0; t < maxThreadLaufen; ++t) { + //new Thread(new ThemaLaden()).start(); + Thread th = new Thread(new ThemaLaden()); + th.setName(nameSenderMReader + t); + th.start(); + } + + } + } + + private class ThemaLaden implements Runnable { + + GetUrl getUrl = new GetUrl(wartenSeiteLaden); + private MVStringBuilder seite1 = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); + + @Override + public synchronized void run() { + try { + meldungAddThread(); + String[] link; + while (!Daten.filmeLaden.getStop() && (link = listeThemen.getListeThemen()) != null) { + meldungProgress(link[0]); + laden(link[0] /* url */, link[1] /* Thema */, link[2] /* Titel */, link[3] /*Datum*/); + } + } catch (Exception ex) { + Log.fehlerMeldung(-987452384, Log.FEHLER_ART_MREADER, "Mediathek3Sat.ThemaLaden.run", ex, ""); + } + meldungThreadUndFertig(); + } + + void laden(String filmWebsite, String thema, String titel, String datum) { + //so.addVariable("pfad","rtmp://88.198.74.226/vod/mp4:1348908081-7b8b1356b478db154fdbf8bf6a01fc1f.mp4"); + //so.addVariable("fullscreenPfad", "rtmp://88.198.74.226/vod/mp4:1348908081-7b8b1356b478db154fdbf8bf6a01fc1f-01.mp4"); + //xajax.config.requestURI = "http://kikaplus.net/clients/kika/kikaplus/?programm=270&id=33172&ag=5"; + final String MUSTER_URL_1 = "so.addVariable(\"pfad\",\""; + final String MUSTER_URL_2 = "so.addVariable(\"fullscreenPfad\", \""; + final String MUSTER_ID = "xajax.config.requestURI = \""; + seite1 = getUrlIo.getUri(nameSenderMReader, filmWebsite, Konstanten.KODIERUNG_UTF, 1, seite1, thema + " " + titel); + int pos1, pos2; + String id; + String urlFilm = ""; + id = seite1.extract(MUSTER_ID, "\""); + if ((pos1 = seite1.indexOf(MUSTER_URL_2)) != -1) { + pos1 += MUSTER_URL_2.length(); + if ((pos2 = seite1.indexOf("\"", pos1)) != -1) { + urlFilm = seite1.substring(pos1, pos2); + } + } + if (urlFilm.equals("")) { + if ((pos1 = seite1.indexOf(MUSTER_URL_1)) != -1) { + pos1 += MUSTER_URL_1.length(); + if ((pos2 = seite1.indexOf("\"", pos1)) != -1) { + urlFilm = seite1.substring(pos1, pos2); + } + } + } + if (!urlFilm.equals("")) { + meldung(urlFilm); + addFilm(new DatenFilm(nameSenderMReader, thema, filmWebsite, titel, urlFilm, "-r " + urlFilm + " --flashVer WIN11,4,402,265"/* urlRtmp */, + datum/*datum*/, ""/*zeit*/, 0, "", "", "", new String[]{""})); + } + } + } + + void addToListHttp() { + //http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=3&page=all + //http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=6&page=all + //http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=10&page=all + + final String ADRESSE_1 = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age="; + final String ADRESSE_2 = "&page=all"; + final String MUSTER_START = "var programletterlist = {\""; + final String[] ALTER = {"3", "6", "10"}; +// listeThemen.clear(); + MVStringBuilder seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); + meldungStart(); + int pos1 = 0, pos2, start = 0, stop = 0; + String id = "", thema = "", url = ""; + for (String alter : ALTER) { + seite = getUrlIo.getUri(nameSenderMReader, ADRESSE_1 + alter + ADRESSE_2, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite"); + if ((start = seite.indexOf(MUSTER_START)) != -1) { + start += MUSTER_START.length(); + pos1 = start; + if ((stop = seite.indexOf("}};", start)) != -1) { + while ((pos1 = seite.indexOf("\"", pos1)) != -1) { + thema = ""; + id = ""; + pos1 += 1; + if ((pos2 = seite.indexOf("\"", pos1)) != -1) { + id = seite.substring(pos1, pos2); + try { + // Testen auf Zehl + int z = Integer.parseInt(id); + } catch (Exception ex) { + continue; + } + ++pos2; + if ((pos1 = seite.indexOf("\"", pos2)) != -1) { + ++pos1; + if ((pos2 = seite.indexOf("\"", pos1)) != -1) { + thema = seite.substring(pos1, pos2); + } + } + // http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=program&id=165&age=10 + url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=program&id=" + id + "&age=" + alter; + ladenHttp(url, thema, alter); + } + } + } + } + } + } + + void ladenHttp(String filmWebsite, String thema, String alter) { + // erst die Nummer suchen + // >25420<4<165<23. Die b + // ", "<"); + bild = seiteHttp.extract(MUSTER_BILD, "<"); + if (!bild.isEmpty()) { + bild = "http://www." + bild; + } + // die URL bauen: + // http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=10&id=25420&page=az + if (!nummer.isEmpty()) { + url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=" + alter + "&id=" + nummer + "&page=az"; + seiteHttp = getUrlIo.getUri(nameSenderMReader, url, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema); + final String MUSTER_URL = "var videofile = \""; + final String MUSTER_TITEL = "var videotitle = \""; + urlFilm = seiteHttp.extract(MUSTER_URL, "\""); + titel = seiteHttp.extract(MUSTER_TITEL, "\""); + if (!urlFilm.equals("")) { + meldung(urlFilm); + // DatenFilm(String ssender, String tthema, String filmWebsite, String ttitel, String uurl, String uurlRtmp, + // String datum, String zeit, + // long dauerSekunden, String description, String thumbnailUrl, String imageUrl, String[] keywords) { + DatenFilm film = null; + if ((film = istInFilmListe(nameSenderMReader, thema, titel)) != null) { + film.addUrlKlein(urlFilm, ""); + } else { + // dann gibs ihn noch nicht + addFilm(new DatenFilm(nameSenderMReader, thema, "http://www.kika.de/fernsehen/mediathek/index.shtml", titel, urlFilm, ""/* urlRtmp */, + ""/*datum*/, ""/*zeit*/, + 0, "", bild, "", new String[]{""})); + } + } else { + Log.fehlerMeldung(-915263078, Log.FEHLER_ART_MREADER, "MediathekKika", "keine URL: " + filmWebsite); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `mediathek.controller.filmeLaden.suchen.sender.MediathekKika.ladenHttp` indirectly reads without synchronization from `this.mediathek.controller.filmeLaden.suchen.sender.MediathekKika.seiteHttp.mediathek.tool.MVStringBuilder.pos1`. Potentially races with write in method `MediathekKika.meldungThreadUndFertig()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +Note that the prefix path this.mediathek.controller.filmeLaden.suchen.sender.MediathekKika.seiteHttp has been contaminated during the execution, so the reported race on this.mediathek.controller.filmeLaden.suchen.sender.MediathekKika.seiteHttp.mediathek.tool.MVStringBuilder.pos1 might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MediathekKika.ladenHttp(String,String,String) + +### Procedure Id: +mediathek.controller.filmeLaden.suchen.sender.MediathekKika.ladenHttp(java.lang.String,java.lang.Str.baacf86a2519544ecd111ab867b66324 + +### File: +src/mediathek/controller/filmeLaden/suchen/sender/MediathekKika.java + +### Key: +MediathekKika.java|ladenHttp|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +c187f1647c18c7fadb201c66ffd28fcf + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8959/instruction.md b/inferredbugs-8959/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9d3eee9a8268ed8e2d883fa24b70d470a6da6d94 --- /dev/null +++ b/inferredbugs-8959/instruction.md @@ -0,0 +1,315 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 37 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * 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 of the License, or + * 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, see . + */ +package mediathek.tool; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Font; +import javax.swing.BorderFactory; +import javax.swing.JPanel; +import javax.swing.JProgressBar; +import javax.swing.JTable; +import javax.swing.SwingConstants; +import javax.swing.UIManager; +import javax.swing.plaf.basic.BasicProgressBarUI; +import javax.swing.table.DefaultTableCellRenderer; +import mediathek.controller.io.starter.Start; +import mediathek.daten.DDaten; +import mediathek.daten.DatenDownload; + +public class CellRendererDownloads extends DefaultTableCellRenderer { + + private DDaten ddaten; + + public CellRendererDownloads(DDaten d) { + ddaten = d; + } + + @Override + public Component getTableCellRendererComponent( + JTable table, + Object value, + boolean isSelected, + boolean hasFocus, + int row, + int column) { + try { + setBackground(null); + setForeground(null); + setFont(null); + setIcon(null); + setHorizontalAlignment(SwingConstants.LEADING); + super.getTableCellRendererComponent( + table, value, isSelected, hasFocus, row, column); + int r = table.convertRowIndexToModel(row); + int c = table.convertColumnIndexToModel(column); + String url = table.getModel().getValueAt(r, DatenDownload.DOWNLOAD_URL_NR).toString(); + // Abos + boolean abo = !table.getModel().getValueAt(r, DatenDownload.DOWNLOAD_ABO_NR).equals(""); + // Starts + Start s = ddaten.starterClass.getStart(url); + if (s != null) { + setColor(this, s, isSelected); + if (c == DatenDownload.DOWNLOAD_RESTZEIT_NR) { + if (s.restSekunden > 0) { + if (s.restSekunden < 60) { + this.setText("< 1 Min."); + } else { + this.setText(Long.toString(s.restSekunden / 60) + " Min."); + } + } else { + this.setText(""); + } + } else if (c == DatenDownload.DOWNLOAD_PROGRESS_NR) { + int i = Integer.parseInt(s.datenDownload.arr[DatenDownload.DOWNLOAD_PROGRESS_NR]); + setHorizontalAlignment(SwingConstants.CENTER); + if (i == -1) { + // noch nicht gestartet + this.setText(""); + } else if (i == DatenDownload.PROGRESS_WARTEN) { + this.setText("warten"); + } else if (i == DatenDownload.PROGRESS_GESTARTET) { + this.setText("gestartet"); + } else if (1 < i && i < DatenDownload.PROGRESS_FERTIG) { +////// return new ProgressPanel(s).progressPanel(); + JProgressBar progressBar = new JProgressBar(0, 1000); + JPanel panel = new JPanel(new BorderLayout()); + setColor(panel, s, isSelected); + setColor(progressBar, s, isSelected); + progressBar.setBorder(BorderFactory.createEmptyBorder()); + progressBar.setStringPainted(true); + progressBar.setUI(new BasicProgressBarUI() { + @Override + protected Color getSelectionBackground() { + return UIManager.getDefaults().getColor("Table.foreground"); + } + + @Override + protected Color getSelectionForeground() { + return Color.white; + } + }); + panel.add(progressBar); + panel.setBorder(BorderFactory.createEmptyBorder()); + progressBar.setValue(i); + double d = i / 10.0; + progressBar.setString(Double.toString(d) + "%"); + return panel; + } else if (i == DatenDownload.PROGRESS_FERTIG) { + if (s != null) { + if (s.status == Start.STATUS_ERR) { + this.setText("fehlerhaft"); + } else { + this.setText("fertig"); + } + } else { + this.setText("fertig"); + } + } + } + } else { + if (c == DatenDownload.DOWNLOAD_PROGRESS_NR) { + this.setText(""); + } + } + if (c == DatenDownload.DOWNLOAD_ABO_NR) { + setFont(new java.awt.Font("Dialog", Font.BOLD, 12)); + if (abo) { + setForeground(GuiKonstanten.ABO_FOREGROUND); + } else { + setForeground(GuiKonstanten.DOWNLOAD_FOREGROUND); + setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/nein_12.png"))); + setHorizontalAlignment(SwingConstants.CENTER); + } + } + if (c == DatenDownload.DOWNLOAD_PROGRAMM_RESTART_NR) { + boolean restart = ddaten.listeDownloads.getDownloadByUrl(url).isRestart(); + setHorizontalAlignment(SwingConstants.CENTER); + if (restart) { + setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/ja_16.png"))); + } else { + setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/nein_12.png"))); + } + } + } catch (Exception ex) { + Log.fehlerMeldung(758200166, Log.FEHLER_ART_PROG, this.getClass().getName(), ex); + } + return this; + } + + private void setColor(Component c, Start s, boolean isSelected) { + switch (s.status) { + case Start.STATUS_INIT: + if (isSelected) { + c.setBackground(GuiKonstanten.DOWNLOAD_FARBE_WAIT_SEL); + } else { + c.setBackground(GuiKonstanten.DOWNLOAD_FARBE_WAIT); + } + break; + case Start.STATUS_RUN: + if (isSelected) { + c.setBackground(GuiKonstanten.DOWNLOAD_FARBE_RUN_SEL); + } else { + c.setBackground(GuiKonstanten.DOWNLOAD_FARBE_RUN); + } + break; + case Start.STATUS_FERTIG: + if (isSelected) { + c.setBackground(GuiKonstanten.DOWNLOAD_FARBE_FERTIG_SEL); + } else { + c.setBackground(GuiKonstanten.DOWNLOAD_FARBE_FERTIG); + } + break; + case Start.STATUS_ERR: + if (isSelected) { + c.setBackground(GuiKonstanten.DOWNLOAD_FARBE_ERR_SEL); + } else { + c.setBackground(GuiKonstanten.DOWNLOAD_FARBE_ERR); + } + break; + } + } +// private class ProgressPanel extends JPanel { +// +// private JPanel panel = new JPanel(new BorderLayout()); +// private Start s = null; +// private int i = 0; +// private JProgressBar progressBar = new JProgressBar(0, 1000); +// +// public ProgressPanel(Start s_) { +// s = s_; +// ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_ART_DOWNLOAD_PROZENT, CellRendererDownloads.class.getSimpleName()) { +// @Override +// public void ping() { +// panelUpdate(); +// } +// }); +// setHorizontalAlignment(SwingConstants.CENTER); +// // JProgressBar progressBar = new JProgressBar(0, 1000); +// // JPanel panel = new JPanel(new BorderLayout()); +// // setColor(panel, s, isSelected); +// // setColor(progressBar, s, isSelected); +// progressBar.setBorder(BorderFactory.createEmptyBorder()); +// progressBar.setStringPainted(true); +// progressBar.setUI(new BasicProgressBarUI() { +// @Override +// protected Color getSelectionBackground() { +// return UIManager.getDefaults().getColor("Table.foreground"); +// } +// +// @Override +// protected Color getSelectionForeground() { +// return Color.white; +// } +// }); +// panel.add(progressBar); +// panel.setBorder(BorderFactory.createEmptyBorder()); +// } +// +// public JPanel progressPanel() { +// return panel; +// } +// +// private void panelUpdate() { +// if (s != null) { +// i = Integer.parseInt(s.datenDownload.arr[DatenDownload.DOWNLOAD_PROGRESS_NR]); +// progressBar.setValue(i); +// double d = i / 10.0; +// progressBar.setString(Double.toString(d) + "%"); +// this.updateUI(); +// } +// } +// } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `CellRendererDownloads.ddaten.listeDownloads.getDownloadByUrl(url)` could be null and is dereferenced at line 144. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Component CellRendererDownloads.getTableCellRendererComponent(JTable,Object,boolean,boolean,int,int) + +### Procedure Id: +mediathek.tool.CellRendererDownloads.getTableCellRendererComponent(javax.swing.JTable,java.lang.Obje.95c322753a790aa637f8dfe2f8bc2679 + +### File: +src/mediathek/tool/CellRendererDownloads.java + +### Key: +CellRendererDownloads.java|getTableCellRendererComponent|NULL_DEREFERENCE + +### Node Key: +85f6f5d6678fe27e5119d8f5b7885afd + +### Hash: +b3b97d02d7a26e77934d4f2ce3b2a2f7 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8961/instruction.md b/inferredbugs-8961/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1f2904b57346cfd54acb8dfca244607946ce70b2 --- /dev/null +++ b/inferredbugs-8961/instruction.md @@ -0,0 +1,359 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 52 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * 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 of the License, or + * 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, see . + */ +package mediathek.controller.filmeLaden.suchen.sender; + +import mediathek.controller.filmeLaden.suchen.FilmeSuchenSender; +import mediathek.controller.io.GetUrl; +import mediathek.daten.Daten; +import mediathek.daten.DatenFilm; +import mediathek.tool.Konstanten; +import mediathek.tool.Log; +import mediathek.tool.MVStringBuilder; +import org.apache.commons.lang3.StringEscapeUtils; + +public class MediathekKika extends MediathekReader implements Runnable { + + public static final String SENDER = "KiKA"; + private MVStringBuilder seiteHttp = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); + + public MediathekKika(FilmeSuchenSender ssearch, int startPrio) { + super(ssearch, /* name */ SENDER, /* threads */ 2, /* urlWarten */ 500, startPrio); + } + + @Override + synchronized void meldungThreadUndFertig() { + if (threads <= 1) { + // vorher noch laufen + addToListHttp(); + } + --threads; + if (threads <= 0) { + //wird erst ausgeführt wenn alle Threads beendet sind + suchen.meldenFertig(nameSenderMReader); + } else { + // läuft noch was + suchen.melden(nameSenderMReader, max, progress, "" /* text */); + } + } + + @Override + void addToList() { + //Sesamstraße präsentiert: Eine Möhre für Zwei
    + //
    42. Ordnung ist das halbe Chaos
    + //41. Über den Wolken
    + final String ADRESSE = "http://kikaplus.net/clients/kika/kikaplus/"; + final String MUSTER_URL = ""; + final String MUSTER_DATUM = "title=\"Sendung vom "; + listeThemen.clear(); + MVStringBuilder seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); + meldungStart(); + seite = getUrlIo.getUri(nameSenderMReader, ADRESSE, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite"); + int pos = 0; + int pos1, pos2, stop, pDatum1, pDatum2, pTitel1, pTitel2; + String url, thema, datum, titel; + while ((pos = seite.indexOf(MUSTER_THEMA, pos)) != -1) { + try { + thema = ""; + pos += MUSTER_THEMA.length(); + stop = seite.indexOf(MUSTER_THEMA, pos); + pos1 = pos; + if ((pos2 = seite.indexOf("<", pos1)) != -1) { + thema = seite.substring(pos1, pos2); + } + while ((pos1 = seite.indexOf(MUSTER_URL, pos1)) != -1) { + titel = ""; + datum = ""; + if (stop != -1 && pos1 > stop) { + // dann schon das nächste Thema + break; + } + pos1 += MUSTER_URL.length(); + if ((pos2 = seite.indexOf("\"", pos1)) != -1) { + url = seite.substring(pos1, pos2); + //if (!url.equals("")) { + url = StringEscapeUtils.unescapeXml(url); + if (!url.equals("") && !url.startsWith("http://") && !url.startsWith("/")) { // Datum + if ((pDatum1 = seite.indexOf(MUSTER_DATUM, pos2)) != -1) { + pDatum1 += MUSTER_DATUM.length(); + if ((pDatum2 = seite.indexOf("\"", pDatum1)) != -1) { + if (stop != -1 && pDatum1 < stop && pDatum2 < stop) { + // dann schon das nächste Thema + datum = seite.substring(pDatum1, pDatum2); + } + } + } + + // Titel + if ((pTitel1 = seite.indexOf(">", pos2)) != -1) { + pTitel1 += 1; + if ((pTitel2 = seite.indexOf("<", pTitel1)) != -1) { + //if (stop != -1 && pTitel1 > stop && pTitel2 > stop) { + if (stop != -1 && pTitel1 < stop && pTitel2 < stop) { + titel = seite.substring(pTitel1, pTitel2); + } + } + } + // in die Liste eintragen + String[] add = new String[]{ADRESSE + url, thema, titel, datum}; + listeThemen.addUrl(add); + } + } + } + } catch (Exception ex) { + Log.fehlerMeldung(-302025469, Log.FEHLER_ART_MREADER, "MediathekKiKA.addToList", ex, ""); + } + } + if (Daten.filmeLaden.getStop()) { + meldungThreadUndFertig(); + } else if (listeThemen.size() == 0) { + meldungThreadUndFertig(); + } else { + listeSort(listeThemen, 1); + meldungAddMax(listeThemen.size()); + for (int t = 0; t < maxThreadLaufen; ++t) { + //new Thread(new ThemaLaden()).start(); + Thread th = new Thread(new ThemaLaden()); + th.setName(nameSenderMReader + t); + th.start(); + } + + } + } + + private class ThemaLaden implements Runnable { + + GetUrl getUrl = new GetUrl(wartenSeiteLaden); + private MVStringBuilder seite1 = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); + + @Override + public synchronized void run() { + try { + meldungAddThread(); + String[] link; + while (!Daten.filmeLaden.getStop() && (link = listeThemen.getListeThemen()) != null) { + meldungProgress(link[0]); + laden(link[0] /* url */, link[1] /* Thema */, link[2] /* Titel */, link[3] /*Datum*/); + } + } catch (Exception ex) { + Log.fehlerMeldung(-987452384, Log.FEHLER_ART_MREADER, "Mediathek3Sat.ThemaLaden.run", ex, ""); + } + meldungThreadUndFertig(); + } + + void laden(String filmWebsite, String thema, String titel, String datum) { + //so.addVariable("pfad","rtmp://88.198.74.226/vod/mp4:1348908081-7b8b1356b478db154fdbf8bf6a01fc1f.mp4"); + //so.addVariable("fullscreenPfad", "rtmp://88.198.74.226/vod/mp4:1348908081-7b8b1356b478db154fdbf8bf6a01fc1f-01.mp4"); + //xajax.config.requestURI = "http://kikaplus.net/clients/kika/kikaplus/?programm=270&id=33172&ag=5"; + final String MUSTER_URL_1 = "so.addVariable(\"pfad\",\""; + final String MUSTER_URL_2 = "so.addVariable(\"fullscreenPfad\", \""; + final String MUSTER_ID = "xajax.config.requestURI = \""; + seite1 = getUrlIo.getUri(nameSenderMReader, filmWebsite, Konstanten.KODIERUNG_UTF, 1, seite1, thema + " " + titel); + int pos1, pos2; + String id; + String urlFilm = ""; + id = seite1.extract(MUSTER_ID, "\""); + if ((pos1 = seite1.indexOf(MUSTER_URL_2)) != -1) { + pos1 += MUSTER_URL_2.length(); + if ((pos2 = seite1.indexOf("\"", pos1)) != -1) { + urlFilm = seite1.substring(pos1, pos2); + } + } + if (urlFilm.equals("")) { + if ((pos1 = seite1.indexOf(MUSTER_URL_1)) != -1) { + pos1 += MUSTER_URL_1.length(); + if ((pos2 = seite1.indexOf("\"", pos1)) != -1) { + urlFilm = seite1.substring(pos1, pos2); + } + } + } + if (!urlFilm.equals("")) { + meldung(urlFilm); + addFilm(new DatenFilm(nameSenderMReader, thema, filmWebsite, titel, urlFilm, "-r " + urlFilm + " --flashVer WIN11,4,402,265"/* urlRtmp */, + datum/*datum*/, ""/*zeit*/, 0, "", "", "", new String[]{""})); + } + } + } + + void addToListHttp() { + //http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=3&page=all + //http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=6&page=all + //http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=10&page=all + + final String ADRESSE_1 = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age="; + final String ADRESSE_2 = "&page=all"; + final String MUSTER_START = "var programletterlist = {\""; + final String[] ALTER = {"3", "6", "10"}; +// listeThemen.clear(); + MVStringBuilder seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); + meldungStart(); + int pos1 = 0, pos2, start = 0, stop = 0; + String id = "", thema = "", url = ""; + for (String alter : ALTER) { + seite = getUrlIo.getUri(nameSenderMReader, ADRESSE_1 + alter + ADRESSE_2, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite"); + if ((start = seite.indexOf(MUSTER_START)) != -1) { + start += MUSTER_START.length(); + pos1 = start; + if ((stop = seite.indexOf("}};", start)) != -1) { + while ((pos1 = seite.indexOf("\"", pos1)) != -1) { + thema = ""; + id = ""; + pos1 += 1; + if ((pos2 = seite.indexOf("\"", pos1)) != -1) { + id = seite.substring(pos1, pos2); + try { + // Testen auf Zehl + int z = Integer.parseInt(id); + } catch (Exception ex) { + continue; + } + ++pos2; + if ((pos1 = seite.indexOf("\"", pos2)) != -1) { + ++pos1; + if ((pos2 = seite.indexOf("\"", pos1)) != -1) { + thema = seite.substring(pos1, pos2); + } + } + // http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=program&id=165&age=10 + url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=program&id=" + id + "&age=" + alter; + ladenHttp(url, thema, alter); + } + } + } + } + } + } + + void ladenHttp(String filmWebsite, String thema, String alter) { + // erst die Nummer suchen + // >25420<4<165<23. Die b + // ", "<"); + bild = seiteHttp.extract(MUSTER_BILD, "<"); + if (!bild.isEmpty()) { + bild = "http://www." + bild; + } + // die URL bauen: + // http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=10&id=25420&page=az + if (!nummer.isEmpty()) { + url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=" + alter + "&id=" + nummer + "&page=az"; + seiteHttp = getUrlIo.getUri(nameSenderMReader, url, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema); + final String MUSTER_URL = "var videofile = \""; + final String MUSTER_TITEL = "var videotitle = \""; + urlFilm = seiteHttp.extract(MUSTER_URL, "\""); + titel = seiteHttp.extract(MUSTER_TITEL, "\""); + if (!urlFilm.equals("")) { + meldung(urlFilm); + // DatenFilm(String ssender, String tthema, String filmWebsite, String ttitel, String uurl, String uurlRtmp, + // String datum, String zeit, + // long dauerSekunden, String description, String thumbnailUrl, String imageUrl, String[] keywords) { + DatenFilm film = null; + if ((film = istInFilmListe(nameSenderMReader, thema, titel)) != null) { + film.addUrlKlein(urlFilm, ""); + } else { + // dann gibs ihn noch nicht + addFilm(new DatenFilm(nameSenderMReader, thema, "http://www.kika.de/fernsehen/mediathek/index.shtml", titel, urlFilm, ""/* urlRtmp */, + ""/*datum*/, ""/*zeit*/, + 0, "", bild, "", new String[]{""})); + } + } else { + Log.fehlerMeldung(-915263078, Log.FEHLER_ART_MREADER, "MediathekKika", "keine URL: " + filmWebsite); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `mediathek.controller.filmeLaden.suchen.sender.MediathekKika.ladenHttp` writes to field `this.mediathek.controller.filmeLaden.suchen.sender.MediathekKika.seiteHttp` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MediathekKika.ladenHttp(String,String,String) + +### Procedure Id: +mediathek.controller.filmeLaden.suchen.sender.MediathekKika.ladenHttp(java.lang.String,java.lang.Str.baacf86a2519544ecd111ab867b66324 + +### File: +src/mediathek/controller/filmeLaden/suchen/sender/MediathekKika.java + +### Key: +MediathekKika.java|ladenHttp|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +194500732d131bec18d5d4faddb58503 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8966/instruction.md b/inferredbugs-8966/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4d4bee424eef0df62b7891f6ee9aec485b2f9a91 --- /dev/null +++ b/inferredbugs-8966/instruction.md @@ -0,0 +1,408 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 24 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * 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 of the License, or + * 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, see . + */ +package mediathek.tool; + +import java.io.File; +import java.io.InputStream; +import java.util.Iterator; +import javax.swing.JOptionPane; +import mediathek.controller.io.IoXmlLesen; +import mediathek.daten.DDaten; +import mediathek.daten.Daten; +import mediathek.daten.DatenProg; +import mediathek.daten.DatenPset; +import mediathek.daten.ListePset; +import mediathek.file.GetFile; +import mediathek.gui.dialog.DialogHilfe; +import mediathek.gui.dialog.DialogOk; +import mediathek.gui.dialogEinstellungen.DialogImportPset; +import mediathek.gui.dialogEinstellungen.PanelProgrammPfade; + +public class GuiFunktionenProgramme { + + private static String getWindowsMplayerPath() { + //Für Windows den Pfad des VLC ermitteln + //sonst den deutschen Defaultpfad für Programme verwenden verwenden + final String PFAD_WIN_DEFAULT = "C:\\Program Files\\SMPlayer\\mplayer\\mplayer.exe"; + final String PFAD_WIN = "\\SMPlayer\\mplayer\\mplayer.exe"; + String vlcPfad; + try { + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + if (System.getenv("ProgramFiles") != null) { + vlcPfad = System.getenv("ProgramFiles") + PFAD_WIN; + if (new File(vlcPfad).exists()) { + return vlcPfad; + } + } + } + if (System.getenv("ProgramFiles(x86)") != null) { + vlcPfad = System.getenv("ProgramFiles(x86)") + PFAD_WIN; + if (new File(vlcPfad).exists()) { + return vlcPfad; + } + } + } catch (Exception ex) { + } + return PFAD_WIN_DEFAULT; + } + + private static String getWindowsVlcPath() { + //Für Windows den Pfad des VLC ermitteln + //sonst den deutschen Defaultpfad für Programme verwenden verwenden + final String PFAD_WIN_DEFAULT = "C:\\Programme\\VideoLAN\\VLC\\vlc.exe"; + final String PFAD_WIN = "\\VideoLAN\\VLC\\vlc.exe"; + String vlcPfad; + try { + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + if (System.getenv("ProgramFiles") != null) { + vlcPfad = System.getenv("ProgramFiles") + PFAD_WIN; + if (new File(vlcPfad).exists()) { + return vlcPfad; + } + } + } + if (System.getenv("ProgramFiles(x86)") != null) { + vlcPfad = System.getenv("ProgramFiles(x86)") + PFAD_WIN; + if (new File(vlcPfad).exists()) { + return vlcPfad; + } + } + } catch (Exception ex) { + } + return PFAD_WIN_DEFAULT; + } + + public static String getMusterPfadMplayer() { + final String PFAD_LINUX = "/usr/bin/mplayer"; + final String PFAD_MAC = "/opt/local/bin/mplayer"; + String pfad = ""; + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + pfad = getWindowsMplayerPath(); + } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { + pfad = PFAD_LINUX; + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + pfad = PFAD_MAC; + } + if (new File(pfad).exists()) { + return pfad; + } else { + return ""; + } + } + + public static String getMusterPfadVlc() { + final String PFAD_LINUX_VLC = "/usr/bin/vlc"; + final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC"; + String pfad = ""; + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + pfad = getWindowsVlcPath(); + } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { + pfad = PFAD_LINUX_VLC; + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + pfad = PFAD_MAC_VLC; + } + if (new File(pfad).exists()) { + return pfad; + } else { + return ""; + } + } + + public static String getMusterPfadFlv() { + final String PFAD_LINUX_FLV = "/usr/bin/flvstreamer"; + final String PFAD_WINDOWS_FLV = "bin\\flvstreamer_win32_latest.exe"; + final String PFAD_MAC_FLV = "bin\\flvstreamer_macosx_intel_32bit_latest"; + String pfad = ""; + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + pfad = Funktionen.getPathJar() + PFAD_WINDOWS_FLV; + } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { + pfad = PFAD_LINUX_FLV; + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + pfad = Funktionen.getPathJar() + PFAD_MAC_FLV; + } + if (new File(pfad).exists()) { + return pfad; + } else { + return ""; + } + } + + public static String getPfadMplayer() { + if (Daten.system[Konstanten.SYSTEM_PFAD_MPLAYER_NR].equals("")) { + new DialogOk(null, true, new PanelProgrammPfade(false /* vlc */, false /* flvstreamer */, true /* mplayer */), "Pfade Standardprogramme").setVisible(true); + } + return Daten.system[Konstanten.SYSTEM_PFAD_MPLAYER_NR]; + } + + public static String getPfadVlc() { + if (Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR].equals("")) { + new DialogOk(null, true, new PanelProgrammPfade(true /* vlc */, false /* flvstreamer */, false /* mplayer */), "Pfade Standardprogramme").setVisible(true); + } + return Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR]; + } + + public static String getPfadFlv() { + if (Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR].equals("")) { + new DialogOk(null, true, new PanelProgrammPfade(false /* vlc */, true /* flvstreamer */, false /* mplayer */), "Pfade Standardprogramme").setVisible(true); + } + return Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR]; + } + + public static String getPfadScript() { + String pfadScript; + final String PFAD_LINUX_SCRIPT = "bin/flv.sh"; + final String PFAD_WINDOWS_SCRIPT = "bin\\flv.bat"; + if (System.getProperty("os.name").toLowerCase().contains("linux")) { + pfadScript = Funktionen.getPathJar() + PFAD_LINUX_SCRIPT; + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + pfadScript = Funktionen.getPathJar() + PFAD_LINUX_SCRIPT; + } else { + pfadScript = Funktionen.getPathJar() + PFAD_WINDOWS_SCRIPT; + } + return pfadScript; + } + + public static ListePset getStandardprogramme(DDaten ddaten) { + ListePset pSet; + InputStream datei; + if (System.getProperty("os.name").toLowerCase().contains("linux")) { + datei = new GetFile().getPsetVorlageLinux(); + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + datei = new GetFile().getPsetVorlageMac(); + } else { + datei = new GetFile().getPsetVorlageWindows(); + } + // Standardgruppen laden + pSet = IoXmlLesen.importPset(datei, true); + return pSet; + } + + public static boolean addVorlagen(DDaten ddaten, ListePset pSet, boolean auto) { + // Standardgruppen laden + if (pSet != null) { + if (!auto) { + DialogImportPset dialog = new DialogImportPset(null, true, ddaten, pSet); + dialog.setVisible(true); + if (!dialog.ok) { + return false; + } + } + if (ddaten.listePset.addPset(pSet)) { + ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_LISTE_PSET, GuiFunktionenProgramme.class.getSimpleName()); + JOptionPane.showMessageDialog(null, pSet.size() + " Programmset importiert!", + "Ok", JOptionPane.INFORMATION_MESSAGE); + } + return true; + } else { + JOptionPane.showMessageDialog(null, "Die Datei wurde nicht importiert!", + "Fehler", JOptionPane.ERROR_MESSAGE); + return false; + } + } + + public static boolean praefixTesten(String str, String uurl, boolean praefix) { + //prüfen ob url beginnt/endet mit einem Argument in str + //wenn str leer dann true + boolean ret = false; + String url = uurl.toLowerCase(); + String s1 = ""; + if (str.equals("")) { + ret = true; + } else { + for (int i = 0; i < str.length(); ++i) { + if (str.charAt(i) != ',') { + s1 += str.charAt(i); + } + if (str.charAt(i) == ',' || i >= str.length() - 1) { + if (praefix) { + //Präfix prüfen + if (url.startsWith(s1.toLowerCase())) { + ret = true; + break; + } + } else { + //Suffix prüfen + if (url.endsWith(s1.toLowerCase())) { + ret = true; + break; + } + } + s1 = ""; + } + } + } + return ret; + } + + public static boolean checkPfadBeschreibbar(String pfad) { + boolean ret = false; + File testPfad = new File(pfad); + try { + if (!testPfad.exists()) { + testPfad.mkdirs(); + } + if (pfad.equals("")) { + } else if (!testPfad.isDirectory()) { + } else { + if (testPfad.canWrite()) { + File tmpFile = File.createTempFile("mediathek", "tmp", testPfad); + tmpFile.delete(); + ret = true; + } + } + } catch (Exception ex) { + } + return ret; + } + + public static boolean programmePruefen(DDaten daten) { + final String PIPE = "| "; + final String LEER = " "; + final String PFEIL = " -> "; + boolean ret = true; + String text = ""; + Iterator itPset = daten.listePset.iterator(); + DatenPset datenPset; + DatenProg datenProg; + while (itPset.hasNext()) { + datenPset = itPset.next(); + ret = true; + if (!datenPset.isFreeLine() && !datenPset.isLable()) { + // nur wenn kein Lable oder freeline + text += "++++++++++++++++++++++++++++++++++++++++++++" + "\n"; + text += PIPE + "Programmgruppe: " + datenPset.arr[DatenPset.PROGRAMMSET_NAME_NR] + "\n"; + String zielPfad = datenPset.arr[DatenPset.PROGRAMMSET_ZIEL_PFAD_NR]; + if (datenPset.progsContainPath()) { + // beim nur Abspielen wird er nicht gebraucht + if (zielPfad.equals("")) { + ret = false; + text += PIPE + LEER + "Zielpfad fehlt!\n"; + } else { + // Pfad beschreibbar? + if (!checkPfadBeschreibbar(zielPfad)) { + //da Pfad-leer und "kein" Pfad schon abgeprüft + ret = false; + text += PIPE + LEER + "Falscher Zielpfad!\n"; + text += PIPE + LEER + PFEIL + "Zielpfad \"" + zielPfad + "\" nicht beschreibbar!" + "\n"; + } + } + } + Iterator itProg = datenPset.getListeProg().iterator(); + while (itProg.hasNext()) { + datenProg = itProg.next(); + // Programmpfad prüfen + //if (!new File(datenProg.arr[Konstanten.PROGRAMM_PROGRAMMPFAD_NR]).exists()) { + if (!new File(datenProg.arr[DatenProg.PROGRAMM_PROGRAMMPFAD_NR]).canExecute()) { + // Programme prüfen + ret = false; + text += PIPE + LEER + "Falscher Programmpfad!\n"; + text += PIPE + LEER + PFEIL + "Programmname: " + datenProg.arr[DatenProg.PROGRAMM_NAME_NR] + "\n"; + text += PIPE + LEER + LEER + "Pfad: " + datenProg.arr[DatenProg.PROGRAMM_PROGRAMMPFAD_NR] + "\n"; + if (!datenProg.arr[DatenProg.PROGRAMM_PROGRAMMPFAD_NR].contains(File.separator)) { + text += PIPE + LEER + PFEIL + "Wenn das Programm nicht im Systempfad liegt, " + "\n"; + text += PIPE + LEER + LEER + "wird der Start nicht klappen!" + "\n"; + } + } + } + if (ret) { + //sollte alles passen + text += PIPE + PFEIL + "Ok!" + "\n"; + } + text += "++++++++++++++++++++++++++++++++++++++++++++" + "\n\n\n"; + } + } + new DialogHilfe(null, true, text).setVisible(true); + return ret; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getProperty("os.name")` could be null and is dereferenced at line 135. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String GuiFunktionenProgramme.getMusterPfadFlv() + +### Procedure Id: +mediathek.tool.GuiFunktionenProgramme.getMusterPfadFlv():java.lang.String.49113afa97873e7d8711b73d64fc0270 + +### File: +src/mediathek/tool/GuiFunktionenProgramme.java + +### Key: +GuiFunktionenProgramme.java|getMusterPfadFlv|NULL_DEREFERENCE + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +5d27b599e6bb2a94c82046198cc54a78 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8968/instruction.md b/inferredbugs-8968/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c0ff6a2e3d1719cf364bd69ecc2ef088032da634 --- /dev/null +++ b/inferredbugs-8968/instruction.md @@ -0,0 +1,372 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * 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 of the License, or + * 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, see . + */ +package mediathek.tool; + +import java.io.File; +import java.io.InputStream; +import java.security.CodeSource; +import java.util.Iterator; +import javax.swing.JOptionPane; +import mediathek.Daten; +import mediathek.Konstanten; +import mediathek.Main; +import mediathek.controller.filme.filmeImportieren.MediathekListener; +import mediathek.controller.io.IoXmlLesen; +import mediathek.daten.DDaten; +import mediathek.daten.DatenPset; +import mediathek.daten.DatenProg; +import mediathek.daten.ListePset; +import mediathek.file.GetFile; +import mediathek.gui.dialog.DialogHilfe; +import mediathek.gui.dialog.DialogLeer; +import mediathek.gui.dialogEinstellungen.DialogImportPset; +import mediathek.gui.dialogEinstellungen.PanelProgrammPfade; +import mediathek.gui.dialogEinstellungen.PanelPsetImport; + +public class GuiFunktionenProgramme { + + public static String getPathJar() { + String pFilePath = "pFile"; + File propFile = new File(pFilePath); + if (!propFile.exists()) { + try { + CodeSource cS = Main.class.getProtectionDomain().getCodeSource(); + File jarFile = new File(cS.getLocation().toURI().getPath()); + String jarDir = jarFile.getParentFile().getPath(); + propFile = new File(jarDir + File.separator + pFilePath); + } catch (Exception ex) { + } + } + return propFile.getAbsolutePath().replace(pFilePath, ""); + } + + private static String getWindowsVlcPath() { + //Für Windows den Pfad des VLC ermitteln + //sonst den deutschen Defaultpfad für Programme verwenden verwenden + final String PFAD_WIN_VLC_DEFAULT = "C:\\Programme\\VideoLAN\\VLC\\vlc.exe"; + final String PFAD_WIN_VLC = "\\VideoLAN\\VLC\\vlc.exe"; + String vlcPfad = ""; + try { + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + if (System.getenv("ProgramFiles") != null) { + vlcPfad = System.getenv("ProgramFiles") + PFAD_WIN_VLC; + if (new File(vlcPfad).exists()) { + return vlcPfad; + } + } + } + if (System.getenv("ProgramFiles(x86)") != null) { + vlcPfad = System.getenv("ProgramFiles(x86)") + PFAD_WIN_VLC; + if (new File(vlcPfad).exists()) { + return vlcPfad; + } + } + } catch (Exception ex) { + } + return PFAD_WIN_VLC_DEFAULT; + } + + public static String getPfadVlc() { + /////////////////////// + if (!Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR].equals("")) { + return Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR]; + } + final String PFAD_LINUX_VLC = "/usr/bin/vlc"; + final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC"; + String pfad = ""; + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + pfad = getWindowsVlcPath(); + } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { + pfad = PFAD_LINUX_VLC; + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + pfad = PFAD_MAC_VLC; + } + if (new File(pfad).exists()) { + return pfad; + } else { + return ""; + } + } + + public static String getPfadFlv() { + ///////////////////// + if (!Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR].equals("")) { + return Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR]; + } + final String PFAD_LINUX_FLV = "/usr/bin/flvstreamer"; + final String PFAD_WINDOWS_FLV = "bin\\flvstreamer_win32_latest.exe"; + String pfad = ""; + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + pfad = GuiFunktionenProgramme.getPathJar() + PFAD_WINDOWS_FLV; + } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { + pfad = PFAD_LINUX_FLV; + } + if (new File(pfad).exists()) { + return pfad; + } else { + return ""; + } + } + + public static String getPfadScript() { + String pfadScript; + final String PFAD_LINUX_SCRIPT = "bin/flv.sh"; + final String PFAD_WINDOWS_SCRIPT = "bin\\flv.bat"; + if (System.getProperty("os.name").toLowerCase().contains("linux")) { + pfadScript = GuiFunktionenProgramme.getPathJar() + PFAD_LINUX_SCRIPT; + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + pfadScript = GuiFunktionenProgramme.getPathJar() + PFAD_LINUX_SCRIPT; + } else { + pfadScript = GuiFunktionenProgramme.getPathJar() + PFAD_WINDOWS_SCRIPT; + } + return pfadScript; + } + + public static boolean addStandardprogramme(DDaten ddaten, boolean auto) { + ListePset pSet; + InputStream datei; + if (System.getProperty("os.name").toLowerCase().contains("linux")) { + datei = new GetFile().getPsetVorlageLinux(); + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + datei = new GetFile().getPsetVorlageMac(); + } else { + datei = new GetFile().getPsetVorlageWindows(); + } + // Standardgruppen laden + pSet = IoXmlLesen.importPset(datei, true); + return addVorlagen(ddaten, pSet, auto); + } + + public static boolean addVorlagen(DDaten ddaten, ListePset pSet, boolean auto) { + // Standardgruppen laden + if (pSet != null) { + if (!auto) { + DialogImportPset dialog = new DialogImportPset(null, true, ddaten, pSet); + dialog.setVisible(true); + if (!dialog.ok) { + return false; + } + } + if (ddaten.listePset.addPset(pSet)) { + Daten.notifyMediathekListener(MediathekListener.EREIGNIS_LISTE_PSET, PanelPsetImport.class.getSimpleName()); + JOptionPane.showMessageDialog(null, pSet.size() + " Programmset importiert!", + "Ok", JOptionPane.INFORMATION_MESSAGE); + } + return true; + } else { + JOptionPane.showMessageDialog(null, "Die Datei wurde nicht importiert!", + "Fehler", JOptionPane.ERROR_MESSAGE); + return false; + } + } + + public static boolean praefixTesten(String str, String uurl, boolean praefix) { + //prüfen ob url beginnt/endet mit einem Argument in str + //wenn str leer dann true + boolean ret = false; + String url = uurl.toLowerCase(); + String s1 = ""; + if (str.equals("")) { + ret = true; + } else { + for (int i = 0; i < str.length(); ++i) { + if (str.charAt(i) != ',') { + s1 += str.charAt(i); + } + if (str.charAt(i) == ',' || i >= str.length() - 1) { + if (praefix) { + //Präfix prüfen + if (url.startsWith(s1.toLowerCase())) { + ret = true; + break; + } + } else { + //Suffix prüfen + if (url.endsWith(s1.toLowerCase())) { + ret = true; + break; + } + } + s1 = ""; + } + } + } + return ret; + } + + public static boolean checkPfadBeschreibbar(String pfad) { + boolean ret = false; + File testPfad = new File(pfad); + try { + if (pfad.equals("")) { + } else if (!testPfad.isDirectory()) { + } else { + if (testPfad.canWrite()) { + File tmpFile = File.createTempFile("mediathek", "tmp", testPfad); + tmpFile.delete(); + ret = true; + } + } + } catch (Exception ex) { + } + return ret; + } + + public static boolean programmePruefen(DDaten daten) { + final String PIPE = "| "; + final String LEER = " "; + final String PFEIL = " -> "; + boolean ret = true; + String text = ""; + Iterator itPset = daten.listePset.iterator(); + DatenPset datenPset; + DatenProg datenProg; + while (itPset.hasNext()) { + datenPset = itPset.next(); + ret = true; + if (!datenPset.isFreeLine() && !datenPset.isLable()) { + // nur wenn kein Lable oder freeline + text += "++++++++++++++++++++++++++++++++++++++++++++" + "\n"; + text += PIPE + "Programmgruppe: " + datenPset.arr[DatenPset.PROGRAMMSET_NAME_NR] + "\n"; + String zielPfad = datenPset.arr[DatenPset.PROGRAMMSET_ZIEL_PFAD_NR]; + if (zielPfad.equals("")) { + // beim nur Abspielen wird er nicht gebraucht + if (datenPset.needsPath()) { + ret = false; + text += PIPE + LEER + "Zielpfad fehlt!\n"; + } + } else { + File pfad = new File(zielPfad); + if (!pfad.isDirectory()) { + ret = false; + text += PIPE + LEER + "Falscher Zielpfad!\n"; + text += PIPE + LEER + PFEIL + "Zielpfad \"" + zielPfad + "\" ist kein Verzeichnis!" + "\n"; + } else { + // Pfad beschreibbar? + if (!checkPfadBeschreibbar(zielPfad)) { + //da Pfad-leer und "kein" Pfad schon abgeprüft + ret = false; + text += PIPE + LEER + "Falscher Zielpfad!\n"; + text += PIPE + LEER + PFEIL + "Zielpfad \"" + zielPfad + "\" nicht beschreibbar!" + "\n"; + } + } + } + Iterator itProg = datenPset.getListeProg().iterator(); + while (itProg.hasNext()) { + datenProg = itProg.next(); + // Programmpfad prüfen + //if (!new File(datenProg.arr[Konstanten.PROGRAMM_PROGRAMMPFAD_NR]).exists()) { + if (!new File(datenProg.arr[DatenProg.PROGRAMM_PROGRAMMPFAD_NR]).canExecute()) { + // Programme prüfen + ret = false; + text += PIPE + LEER + "Falscher Programmpfad!\n"; + text += PIPE + LEER + PFEIL + "Programmname: " + datenProg.arr[DatenProg.PROGRAMM_NAME_NR] + "\n"; + text += PIPE + LEER + LEER + "Pfad: " + datenProg.arr[DatenProg.PROGRAMM_PROGRAMMPFAD_NR] + "\n"; + if (!datenProg.arr[DatenProg.PROGRAMM_PROGRAMMPFAD_NR].contains(File.separator)) { + text += PIPE + LEER + PFEIL + "Wenn das Programm nicht im Systempfad liegt, " + "\n"; + text += PIPE + LEER + LEER + "wird der Start nicht klappen!" + "\n"; + } + } + } + if (ret) { + //sollte alles passen + text += PIPE + PFEIL + "Ok!" + "\n"; + } + text += "++++++++++++++++++++++++++++++++++++++++++++" + "\n\n\n"; + } + } + new DialogHilfe(null, true, text).setVisible(true); + return ret; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getProperty("os.name")` could be null and is dereferenced at line 116. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String GuiFunktionenProgramme.getPfadFlv() + +### Procedure Id: +mediathek.tool.GuiFunktionenProgramme.getPfadFlv():java.lang.String.c214c570861b842bfe60ef716d6d36d0 + +### File: +src/mediathek/tool/GuiFunktionenProgramme.java + +### Key: +GuiFunktionenProgramme.java|getPfadFlv|NULL_DEREFERENCE + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +3359fb2cc47080b5f04c9dc790cbdaa0 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8992/instruction.md b/inferredbugs-8992/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a6255b860289304cf064840029a0eeb140583fcb --- /dev/null +++ b/inferredbugs-8992/instruction.md @@ -0,0 +1,127 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nextrtc-signaling-server +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nextrtc.signalingserver.domain.signal; + +import static org.apache.commons.lang3.StringUtils.EMPTY; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.nextrtc.signalingserver.BaseTest; +import org.nextrtc.signalingserver.MessageMatcher; +import org.nextrtc.signalingserver.domain.*; +import org.nextrtc.signalingserver.repository.Conversations; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.base.Optional; + +public class CreateSignalTest extends BaseTest { + + @Autowired + private CreateSignal create; + + @Autowired + private Conversations conversations; + + @Test + public void shouldCreateConversation() throws Exception { + // given + MessageMatcher matcher = new MessageMatcher(); + InternalMessage message = InternalMessage.create()// + .from(Member.builder()// + .session(mockSession("sessionId", matcher))// + .build())// + .signal(create)// + .content("c1")// + .build(); + + // when + create.executeMessage(message); + + // then + Optional conv = conversations.findBy("c1"); + assertTrue(conv.isPresent()); + Message send = matcher.getMessage(); + assertNotNull(send); + assertThat(send.getFrom(), is(EMPTY)); + assertThat(send.getTo(), is("sessionId")); + assertThat(send.getSignal(), is("created")); + assertThat(send.getContent(), is("c1")); + assertThat(send.getParameters(), notNullValue()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `send` last assigned on line 45 could be null and is dereferenced at line 47. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CreateSignalTest.shouldCreateConversation() + +### Procedure Id: +org.nextrtc.signalingserver.domain.signal.CreateSignalTest.shouldCreateConversation():void.21a170a4b864dcf15b987c8df572a80d + +### File: +src/test/java/org/nextrtc/signalingserver/domain/signal/CreateSignalTest.java + +### Key: +CreateSignalTest.java|shouldCreateConversation|NULL_DEREFERENCE + +### Node Key: +029769b47f6bc348a94d4e034c2162d6 + +### Hash: +6d42bfb0dc04c708307f4aa103323fd9 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8995/instruction.md b/inferredbugs-8995/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..15d5923ae2dad7916571da97ba5b764a33f498bb --- /dev/null +++ b/inferredbugs-8995/instruction.md @@ -0,0 +1,231 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nextrtc-signaling-server +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nextrtc.signalingserver.domain; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.nextrtc.signalingserver.api.annotation.NextRTCEvents.CONVERSATION_CREATED; +import static org.nextrtc.signalingserver.api.annotation.NextRTCEvents.SESSION_STARTED; + +import java.util.List; + +import javax.websocket.Session; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.nextrtc.signalingserver.BaseTest; +import org.nextrtc.signalingserver.EventChecker; +import org.nextrtc.signalingserver.MessageMatcher; +import org.nextrtc.signalingserver.api.NextRTCEvent; +import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener; +import org.nextrtc.signalingserver.domain.ServerTest.ServerEventCheck; +import org.nextrtc.signalingserver.exception.Exceptions; +import org.nextrtc.signalingserver.exception.SignalingException; +import org.nextrtc.signalingserver.repository.Members; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; + +@ContextConfiguration(classes = { ServerEventCheck.class }) +public class ServerTest extends BaseTest { + + @NextRTCEventListener({ SESSION_STARTED, CONVERSATION_CREATED }) + public static class ServerEventCheck extends EventChecker { + + } + + @Rule + public ExpectedException expect = ExpectedException.none(); + + @Autowired + private Server server; + + @Autowired + private Members members; + + @Autowired + private ServerEventCheck eventCheckerCall; + + @Test + public void shouldThrowExceptionWhenMemberDoesntExists() throws Exception { + // given + Session session = mock(Session.class); + when(session.getId()).thenReturn("s1"); + + // then + expect.expect(SignalingException.class); + expect.expectMessage(Exceptions.MEMBER_NOT_FOUND.name()); + + // when + server.handle(mock(Message.class), session); + } + + @Test + public void shouldRegisterUserOnWebSocketConnection() throws Exception { + // given + Session session = mock(Session.class); + when(session.getId()).thenReturn("s1"); + + // when + server.register(session); + + // then + assertTrue(members.findBy("s1").isPresent()); + + } + + @Test + public void shouldCreateConversationOnCreateSignal() throws Exception { + // given + Session session = mockSession("s1"); + server.register(session); + + // when + server.handle(Message.create()// + .signal("create")// + .build(), session); + + // then + List events = eventCheckerCall.getEvents(); + assertThat(events.size(), is(2)); + } + + @Test + public void shouldCreateConversationCreate() throws Exception { + // given + MessageMatcher s1Matcher = new MessageMatcher(); + MessageMatcher s2Matcher = new MessageMatcher(); + Session s1 = mockSession("s1", s1Matcher); + Session s2 = mockSession("s2", s2Matcher); + server.register(s1); + server.register(s2); + + // when + server.handle(Message.create()// + .signal("create")// + .build(), s1); + + // then + assertThat(s1Matcher.getMessages().size(), is(1)); + assertThat(s1Matcher.getMessage().getSignal(), is("created")); + assertThat(s2Matcher.getMessages().size(), is(0)); + } + + @Test + public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception { + // given + MessageMatcher s1Matcher = new MessageMatcher(); + MessageMatcher s2Matcher = new MessageMatcher(); + Session s1 = mockSession("s1", s1Matcher); + Session s2 = mockSession("s2", s2Matcher); + server.register(s1); + server.register(s2); + + // when + server.handle(Message.create()// + .signal("create")// + .build(), s1); + String conversationKey = s1Matcher.getMessage().getContent(); + s1Matcher.reset(); + server.handle(Message.create()// + .signal("join")// + .content(conversationKey)// + .build(), s2); + + // then + assertThat(s1Matcher.getMessages().size(), is(2)); + assertThat(s1Matcher.getMessage().getFrom(), is("s2")); + assertThat(s1Matcher.getMessage().getTo(), is("s1")); + assertThat(s1Matcher.getMessage().getSignal(), is("joined")); + + assertThat(s1Matcher.getMessage(1).getFrom(), is("s2")); + assertThat(s1Matcher.getMessage(1).getTo(), is("s1")); + assertThat(s1Matcher.getMessage(1).getSignal(), is("offerRequest")); + + assertThat(s2Matcher.getMessages().size(), is(1)); + assertThat(s2Matcher.getMessage().getSignal(), is("joined")); + assertThat(s2Matcher.getMessage().getContent(), is(conversationKey)); + } + + @Before + public void resetObjects() { + eventCheckerCall.reset(); + members.unregister("s1"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `s1Matcher.getMessage(1)` could be null and is dereferenced at line 143. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ServerTest.shouldCreateConversationThenJoinAndSendOfferRequest() + +### Procedure Id: +org.nextrtc.signalingserver.domain.ServerTest.shouldCreateConversationThenJoinAndSendOfferRequest():.5452bc9fe9b49eb29db200551bf60d9c + +### File: +src/test/java/org/nextrtc/signalingserver/domain/ServerTest.java + +### Key: +ServerTest.java|shouldCreateConversationThenJoinAndSendOfferRequest|NULL_DEREFERENCE + +### Node Key: +9275dffb92243fffa4fb0ef78102c621 + +### Hash: +9660862a8446298c14ed77c4fbfe3b25 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9011/instruction.md b/inferredbugs-9011/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..085b398ea54b1c4e19a6154defe01c550069f0cb --- /dev/null +++ b/inferredbugs-9011/instruction.md @@ -0,0 +1,320 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** boxable +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + Quodlibet.be + */ +package be.quodlibet.boxable; + +import com.google.common.io.Files; +import org.apache.pdfbox.exceptions.COSVisitorException; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPage; +import org.apache.pdfbox.pdmodel.font.PDType1Font; +import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline; +import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem; +import org.junit.Test; + +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + + +public class TableTest { + + @Test + public void Sample1 () throws IOException, COSVisitorException { + + //Set margins + float margin = 10; + + + List facts = getFacts(); + + //Initialize Document + PDDocument doc = new PDDocument(); + PDPage page = addNewPage(doc); + float top = page.findMediaBox().getHeight() - (2 * margin); + + //Initialize table + float tableWidth = page.findMediaBox().getWidth() - (2 * margin); + boolean drawContent = false; + Table table = new Table(top,tableWidth, margin, doc, page, true, drawContent); + + //Create Header row + Row headerRow = table.createRow(15f); + Cell cell = headerRow.createCell(100, "Awesome Facts About Belgium"); + cell.setFont(PDType1Font.HELVETICA_BOLD); + cell.setFillColor(Color.BLACK); + cell.setTextColor(Color.WHITE); + + + table.setHeader(headerRow); + + //Create 2 column row + Row row = table.createRow(15f); + cell = row.createCell(30,"Source:"); + cell.setFont(PDType1Font.HELVETICA); + + cell = row.createCell(70, "http://www.factsofbelgium.com/"); + cell.setFont(PDType1Font.HELVETICA_OBLIQUE); + + //Create Fact header row + Row factHeaderrow = table.createRow(15f); + + cell = factHeaderrow.createCell((100 / 3) * 2, "Fact"); + cell.setFont(PDType1Font.HELVETICA); + cell.setFontSize(6); + cell.setFillColor(Color.LIGHT_GRAY); + + cell = factHeaderrow.createCell((100 / 3), "Tags"); + cell.setFillColor(Color.LIGHT_GRAY); + cell.setFont(PDType1Font.HELVETICA_OBLIQUE); + cell.setFontSize(6); + + //Add multiple rows with random facts about Belgium + for (String[] fact : facts) { + + row = table.createRow(10f); + cell = row.createCell((100 / 3) * 2, fact[0]); + cell.setFont(PDType1Font.HELVETICA); + cell.setFontSize(6); + + for (int i = 1; i < fact.length; i++) { + + cell = row.createCell((100 / 9), fact[i]); + cell.setFont(PDType1Font.HELVETICA_OBLIQUE); + cell.setFontSize(6); + //Set colors + if (fact[i].contains("beer")) cell.setFillColor(Color.yellow); + if (fact[i].contains("champion")) cell.setTextColor(Color.GREEN); + } + } + + table.draw(); + + //Close Stream and save pdf + File file = new File("target/BoxableSample1.pdf"); + Files.createParentDirs(file); + doc.save(file); + doc.close(); + + } + + + + private static List getFacts() { + List facts = new ArrayList(); + facts.add(new String[]{"Oil Painting was invented by the Belgian van Eyck brothers", "art", "inventions", "science"}); + facts.add(new String[]{"The Belgian Adolphe Sax invented the Saxophone", "inventions", "music", ""}); + facts.add(new String[]{"11 sites in Belgium are on the UNESCO World Heritage List", "art", "history", ""}); + facts.add(new String[]{"Belgium was the second country in the world to legalize same-sex marriage", "politics", "", ""}); + facts.add(new String[]{"In the seventies, schools served light beer during lunch", "beer", "health", ""}); + facts.add(new String[]{"Belgium has the sixth fastest domestic internet connection in the world", "science", "technology", ""}); + facts.add(new String[]{"Belgium hosts the World's Largest Sand Sculpture Festival", "art", "festivals", "world championship"}); + facts.add(new String[]{"Belgium has compulsary education between the ages of 6 and 18", "education", "", ""}); + facts.add(new String[]{"Belgium also has more comic makers per square kilometer than any other country in the world", "art", "social", "world championship"}); + facts.add(new String[]{"Belgium has one of the lowest proportion of McDonald's restaurants per inhabitant in the developed world", "food", "health", ""}); + facts.add(new String[]{"Belgium has approximately 178 beer breweries", "beer", "food", ""}); + facts.add(new String[]{"Gotye was born in Bruges, Belgium", "music", "celebrities", ""}); + facts.add(new String[]{"The Belgian Coast Tram is the longest tram line in the world", "technology", "world championship", ""}); + facts.add(new String[]{"Stefan Everts is the only motocross racer with 10 World Championship titles.", "celebrities", "sports", "world champions"}); + facts.add(new String[]{"Tintin was conceived by Belgian artist Hergé", "art", "celebrities", "inventions"}); + facts.add(new String[]{"Brussels Airport is the world's biggest selling point of chocolate", "food", "world champions", ""}); + facts.add(new String[]{"Tomorrowland is the biggest electronic dance music festival in the world", "festivals", "music", "world champion"}); + facts.add(new String[]{"French Fries are actually from Belgium", "food", "inventions", ""}); + facts.add(new String[]{"Herman Van Rompy is the first full-time president of the European Council", "politics", "", ""}); + facts.add(new String[]{"Belgians are the fourth most money saving people in the world", "economy", "social", ""}); + facts.add(new String[]{"The Belgian highway system is the only man-made structure visible from the moon at night", "technology", "world champions", ""}); + facts.add(new String[]{"Andreas Vesalius, the founder of modern human anatomy, is from Belgium", "celebrities", "education", "history"}); + facts.add(new String[]{"Napoleon was defeated in Waterloo, Belgium", "celebrities", "history", "politicians"}); + facts.add(new String[]{"The first natural color picture in National Geographic was of a flower garden in Gent, Belgium in 1914", "art", "history", "science"}); + facts.add(new String[]{"Rock Werchter is the Best Festival in the World", "festivals", "music", "world champions"}); + + //Make the table a bit bigger + facts.addAll(facts); + facts.addAll(facts); + facts.addAll(facts); + + + return facts; + } + + + + @Test + public void SampleTest2() throws IOException, COSVisitorException { + + //Set margins + float margin = 10; + + List facts = getFacts(); + + //A list of bookmarks of all the tables + List bookmarks = new ArrayList(); + + //Initialize Document + PDDocument doc = new PDDocument(); + PDPage page = addNewPage(doc); + + //Initialize table + float tableWidth = page.findMediaBox().getWidth()-(2*margin); + float top = page.findMediaBox().getHeight() - (2 * margin); + boolean drawContent = true; + boolean drawLines = true; + Table table = new Table(top,tableWidth, margin, doc, page, drawLines, drawContent); + + + //Create Header row + Row headerRow = table.createRow(15f); + Cell cell = headerRow.createCell(100,"Awesome Facts About Belgium"); + cell.setFont(PDType1Font.HELVETICA_BOLD); + cell.setFillColor(Color.BLACK);cell.setTextColor(Color.WHITE); + + table.setHeader(headerRow); + + //Create 2 column row + Row row = table.createRow(15f); + cell = row.createCell(75,"Source:"); + cell.setFont(PDType1Font.HELVETICA); + + cell = row.createCell(25,"http://www.factsofbelgium.com/"); + cell.setFont(PDType1Font.HELVETICA_OBLIQUE); + + //Create Fact header row + Row factHeaderrow = table.createRow(15f); + cell = factHeaderrow.createCell((100/3) * 2 ,"Fact"); + cell.setFont(PDType1Font.HELVETICA); + cell.setFontSize(6); + cell.setFillColor(Color.LIGHT_GRAY); + + cell = factHeaderrow.createCell((100/3),"Tags"); + cell.setFillColor(Color.LIGHT_GRAY); + cell.setFont(PDType1Font.HELVETICA_OBLIQUE);cell.setFontSize(6); + + //Add multiple rows with random facts about Belgium + int bookmarkid = 0; + for(String[] fact : facts) { + + row = table.createRow(10f); + cell = row.createCell((100/3)*2 ,fact[0]+ " " + fact[0]+ " " + fact[0]); + cell.setFont(PDType1Font.HELVETICA);cell.setFontSize(6); + + //Create a bookmark for each record + PDOutlineItem outlineItem = new PDOutlineItem(); + outlineItem.setTitle((++bookmarkid ) + ") " + fact[0]); + row.setBookmark( outlineItem); + + for(int i = 1; i< fact.length; i++) { + cell = row.createCell((100/9) ,fact[i]); + cell.setFont(PDType1Font.HELVETICA_OBLIQUE);cell.setFontSize(6); + + //Set colors + if(fact[i].contains("beer"))cell.setFillColor(Color.yellow); + if(fact[i].contains("champion"))cell.setTextColor(Color.GREEN); + + } + } + table.draw(); + + //Get all bookmarks of previous table + bookmarks.addAll(table.getBookmarks()); + + //Create document outline + PDDocumentOutline outline = new PDDocumentOutline(); + + for(PDOutlineItem bm : bookmarks) { + outline.appendChild(bm); + } + + doc.getDocumentCatalog().setDocumentOutline(outline); + + //Save the document + File file = new File("target/BoxableSample2.pdf"); + Files.createParentDirs(file); + doc.save(file); + doc.close(); + + } + + private static PDPage addNewPage(PDDocument doc) { + PDPage page = new PDPage(); + doc.addPage(page); + return page; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.pdfbox.pdmodel.PDDocument` acquired by call to `new()` at line 156 is not released after line 237. +**Note**: potential exception at line 169 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TableTest.SampleTest2() + +### Procedure Id: +be.quodlibet.boxable.TableTest.SampleTest2():void.7a1b7ef48a844eb9c3143d4ce68d5575 + +### File: +src/test/java/be/quodlibet/boxable/TableTest.java + +### Key: +TableTest.java|SampleTest2|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +fcc3d1468dcc1635c170b1addf641a54 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9016/instruction.md b/inferredbugs-9016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..674cb64cd399296de0137e84133c5521040f7e00 --- /dev/null +++ b/inferredbugs-9016/instruction.md @@ -0,0 +1,709 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jnr-posix +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java + +package jnr.posix; + +import jnr.constants.platform.Fcntl; +import jnr.constants.platform.Sysconf; +import jnr.ffi.Pointer; +import jnr.posix.util.ProcessMaker; + +import java.io.FileDescriptor; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.Collection; +import jnr.constants.platform.Confstr; +import jnr.constants.platform.Pathconf; +import jnr.constants.platform.Signal; + +final class LazyPOSIX implements POSIX { + + private final POSIXHandler handler; + private final boolean useNativePosix; + + // NOTE: because all implementations of POSIX that are loaded via loadPOSIX() + // are immutable, there is no need for 'posix' to be a volatile field. + // See http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html + // (but since volatile reads on x86 and x86_64 are cheap, do it anyway) + private volatile POSIX posix; + + LazyPOSIX(POSIXHandler handler, boolean useNativePosix) { + this.handler = handler; + this.useNativePosix = useNativePosix; + } + + private final POSIX posix() { + return posix != null ? posix : loadPOSIX(); + } + + private final synchronized POSIX loadPOSIX() { + return posix != null + ? posix + : (posix = POSIXFactory.loadPOSIX(handler, useNativePosix)); + } + + public ProcessMaker newProcessMaker(String... command) { + return posix().newProcessMaker(command); + } + + public ProcessMaker newProcessMaker() { + return posix().newProcessMaker(); + } + + public FileStat allocateStat() { + return posix().allocateStat(); + } + + public MsgHdr allocateMsgHdr() { + return posix().allocateMsgHdr(); + } + + public int chdir(String path) { + return posix().chdir(path); + } + + public int chmod(String filename, int mode) { + return posix().chmod(filename, mode); + } + + public int fchmod(int fd, int mode) { + return posix().fchmod(fd, mode); + } + + public int chown(String filename, int user, int group) { + return posix().chown(filename, user, group); + } + + public CharSequence crypt(CharSequence key, CharSequence salt) { + return posix().crypt(key, salt); + } + + public byte[] crypt(byte[] key, byte[] salt) { + return posix().crypt(key, salt); + } + + public int fchown(int fd, int user, int group) { + return posix().fchown(fd, user, group); + } + + public int endgrent() { + return posix().endgrent(); + } + + public int endpwent() { + return posix().endpwent(); + } + + public int errno() { + return posix().errno(); + } + + public void errno(int value) { + posix().errno(value); + } + + public int exec(String path, String... args) { + return posix().exec(path, args); + } + + public int exec(String path, String[] args, String[] envp) { + return posix().exec(path, args, envp); + } + + public int execv(String path, String[] argv) { + return posix().execv(path, argv); + } + + public int execve(String path, String[] argv, String[] envp) { + return posix().execve(path, argv, envp); + } + + public int fork() { + return posix().fork(); + } + + public FileStat fstat(int fd) { + return posix().fstat(fd); + } + + public int fstat(int fd, FileStat stat) { + return posix().fstat(fd, stat); + } + + public FileStat fstat(FileDescriptor descriptor) { + return posix().fstat(descriptor); + } + + public int fstat(FileDescriptor descriptor, FileStat stat) { + return posix().fstat(descriptor, stat); + } + + public int getegid() { + return posix().getegid(); + } + + public int geteuid() { + return posix().geteuid(); + } + + public int getgid() { + return posix().getgid(); + } + + public int getdtablesize() { + return posix().getdtablesize(); + } + + public Group getgrent() { + return posix().getgrent(); + } + + public Group getgrgid(int which) { + return posix().getgrgid(which); + } + + public Group getgrnam(String which) { + return posix().getgrnam(which); + } + + public String getlogin() { + return posix().getlogin(); + } + + public int getpgid() { + return posix().getpgid(); + } + + public int getpgid(int pid) { + return posix().getpgid(pid); + } + + public int getpgrp() { + return posix().getpgrp(); + } + + public int getpid() { + return posix().getpid(); + } + + public int getppid() { + return posix().getppid(); + } + + public int getpriority(int which, int who) { + return posix().getpriority(which, who); + } + + public Passwd getpwent() { + return posix().getpwent(); + } + + public Passwd getpwnam(String which) { + return posix().getpwnam(which); + } + + public Passwd getpwuid(int which) { + return posix().getpwuid(which); + } + + public int getuid() { + return posix().getuid(); + } + + public int getrlimit(int resource, RLimit rlim) { + return posix().getrlimit(resource, rlim); + } + + public int getrlimit(int resource, Pointer rlim) { + return posix().getrlimit(resource, rlim); + } + + public RLimit getrlimit(int resource) { + return posix().getrlimit(resource); + } + + public int setrlimit(int resource, RLimit rlim) { + return posix().setrlimit(resource, rlim); + } + + public int setrlimit(int resource, Pointer rlim) { + return posix().setrlimit(resource, rlim); + } + + public int setrlimit(int resource, long rlimCur, long rlimMax) { + return posix().setrlimit(resource, rlimCur, rlimMax); + } + + public boolean isatty(FileDescriptor descriptor) { + return posix().isatty(descriptor); + } + + public int isatty(int descriptor) { + return posix().isatty(descriptor); + } + + public int kill(int pid, int signal) { + return kill((long) pid, signal); + } + + public int kill(long pid, int signal) { + return posix().kill(pid, signal); + } + + public SignalHandler signal(Signal sig, SignalHandler handler) { + return posix().signal(sig, handler); + } + + public int raise(int sig) { + return posix().raise(sig); + } + + public int lchmod(String filename, int mode) { + return posix().lchmod(filename, mode); + } + + public int lchown(String filename, int user, int group) { + return posix().lchown(filename, user, group); + } + + public int link(String oldpath, String newpath) { + return posix().link(oldpath, newpath); + } + + public FileStat lstat(String path) { + return posix().lstat(path); + } + + public int lstat(String path, FileStat stat) { + return posix().lstat(path, stat); + } + + public int mkdir(String path, int mode) { + return posix().mkdir(path, mode); + } + + public String readlink(String path) throws IOException { + return posix().readlink(path); + } + + public int readlink(CharSequence path, byte[] buf, int bufsize) { + return posix().readlink(path, buf, bufsize); + } + + public int readlink(CharSequence path, ByteBuffer buf, int bufsize) { + return posix().readlink(path, buf, bufsize); + } + + public int readlink(CharSequence path, Pointer bufPtr, int bufsize) { + return posix().readlink(path, bufPtr, bufsize); + } + + public int rmdir(String path) { + return posix().rmdir(path); + } + + public int setegid(int egid) { + return posix().setegid(egid); + } + + public int seteuid(int euid) { + return posix().seteuid(euid); + } + + public int setgid(int gid) { + return posix().setgid(gid); + } + + public int setgrent() { + return posix().setgrent(); + } + + public int setpgid(int pid, int pgid) { + return posix().setpgid(pid, pgid); + } + + public int setpgrp(int pid, int pgrp) { + return posix().setpgrp(pid, pgrp); + } + + public int setpriority(int which, int who, int prio) { + return posix().setpriority(which, who, prio); + } + + public int setpwent() { + return posix().setpwent(); + } + + public int setsid() { + return posix().setsid(); + } + + public int setuid(int uid) { + return posix().setuid(uid); + } + + public FileStat stat(String path) { + return posix().stat(path); + } + + public int stat(String path, FileStat stat) { + return posix().stat(path, stat); + } + + public int symlink(String oldpath, String newpath) { + return posix().symlink(oldpath, newpath); + } + + public int umask(int mask) { + return posix().umask(mask); + } + + public int utimes(String path, long[] atimeval, long[] mtimeval) { + return posix().utimes(path, atimeval, mtimeval); + } + + public int utimes(String path, Pointer times) { + return posix().utimes(path, times); + } + + public int futimes(int fd, long[] atimeval, long[] mtimeval) { + return posix().futimes(fd, atimeval, mtimeval); + } + + public int lutimes(String path, long[] atimeval, long[] mtimeval) { + return posix().lutimes(path, atimeval, mtimeval); + } + + public int utimensat(int dirfd, String path, long[] atimespec, long[] mtimespec, int flag) { + return posix().utimensat(dirfd, path, atimespec, mtimespec, flag); + } + + public int utimensat(int dirfd, String path, Pointer times, int flag) { + return posix().utimensat(dirfd, path, times, flag); + } + + public int futimens(int fd, long[] atimespec, long[] mtimespec) { + return posix().futimens(fd, atimespec, mtimespec); + } + + public int futimens(int fd, Pointer times) { + return posix().futimens(fd, times); + } + + public int wait(int[] status) { + return posix().wait(status); + } + + public int waitpid(int pid, int[] status, int flags) { + return waitpid((long) pid, status, flags); + } + + public int waitpid(long pid, int[] status, int flags) { + return posix().waitpid(pid, status, flags); + } + + public boolean isNative() { + return posix().isNative(); + } + + public LibC libc() { + return posix().libc(); + } + + public Pointer environ() { + return posix().environ(); + } + + public String getenv(String envName) { + return posix().getenv(envName); + } + + public int setenv(String envName, String envValue, int overwrite) { + return posix().setenv(envName, envValue, overwrite); + } + + public int unsetenv(String envName) { + return posix().unsetenv(envName); + } + + public long posix_spawnp(String path, Collection fileActions, Collection argv, Collection envp) { + return posix().posix_spawnp(path, fileActions, argv, envp); + } + + public long posix_spawnp(String path, Collection fileActions, + Collection spawnAttributes, + Collection argv, Collection envp) { + return posix().posix_spawnp(path, fileActions, spawnAttributes, argv, envp); + } + + public long sysconf(Sysconf name) { + return posix().sysconf(name); + } + + public int confstr(Confstr name, ByteBuffer buf, int len) { + return libc().confstr(name, buf, len); + } + + public int fpathconf(int fd, Pathconf name) { + return libc().fpathconf(fd, name); + } + + public Times times() { + return posix().times(); + } + + public int flock(int fd, int mode) { + return posix().flock(fd, mode); + } + + public int dup(int fd) { + return posix().dup(fd); + } + + public int dup2(int oldFd, int newFd) { + return posix().dup2(oldFd, newFd); + } + + public int fcntlInt(int fd, Fcntl fcntlConst, int arg) { + return posix().fcntlInt(fd, fcntlConst, arg); + } + + public int fcntl(int fd, Fcntl fcntlConst) { + return posix().fcntl(fd, fcntlConst); + } + + public int fcntl(int fd, Fcntl fcntlConst, int arg) { + return posix().fcntl(fd, fcntlConst, arg); + } + + @Deprecated + public int fcntl(int fd, Fcntl fcntlConst, int... arg) { + return posix().fcntl(fd, fcntlConst); + } + + public int access(CharSequence path, int amode) { + return posix().access(path, amode); + } + + public int close(int fd) { + return posix().close(fd); + } + + public int unlink(CharSequence path) { + return posix().unlink(path); + } + + public int open(CharSequence path, int flags, int perm) { + return posix().open(path, flags, perm); + } + + public long read(int fd, byte[] buf, long n) { + return posix().read(fd, buf, n); + } + public long write(int fd, byte[] buf, long n) { + return posix().write(fd, buf, n); + } + public long read(int fd, ByteBuffer buf, long n) { + return posix().read(fd, buf, n); + } + public long write(int fd, ByteBuffer buf, long n) { + return posix().write(fd, buf, n); + } + public long pread(int fd, byte[] buf, long n, long offset) { + return posix().pread(fd, buf, n, offset); + } + public long pwrite(int fd, byte[] buf, long n, long offset) { + return posix().pwrite(fd, buf, n, offset); + } + public long pread(int fd, ByteBuffer buf, long n, long offset) { + return posix().pread(fd, buf, n, offset); + } + public long pwrite(int fd, ByteBuffer buf, long n, long offset) { + return posix().pwrite(fd, buf, n, offset); + } + + public int read(int fd, byte[] buf, int n) + { + return posix().read(fd, buf, n); + } + public int write(int fd, byte[] buf, int n) { + return posix().write(fd, buf, n); + } + public int read(int fd, ByteBuffer buf, int n) { + return posix().read(fd, buf, n); + } + public int write(int fd, ByteBuffer buf, int n) { + return posix().write(fd, buf, n); + } + public int pread(int fd, byte[] buf, int n, int offset) { + return posix().pread(fd, buf, n, offset); + } + public int pwrite(int fd, byte[] buf, int n, int offset) { + return posix().pwrite(fd, buf, n, offset); + } + public int pread(int fd, ByteBuffer buf, int n, int offset) { + return posix().pread(fd, buf, n, offset); + } + public int pwrite(int fd, ByteBuffer buf, int n, int offset) { + return posix().pwrite(fd, buf, n, offset); + } + + public int lseek(int fd, long offset, int whence) { + return posix().lseek(fd, offset, whence); + } + + public long lseekLong(int fd, long offset, int whence) { + return posix().lseekLong(fd, offset, whence); + } + + public int pipe(int[] fds) { + return posix().pipe(fds); + } + + public int socketpair(int domain, int type, int protocol, int[] fds) { + return posix().socketpair(domain, type, protocol, fds); + } + + public int sendmsg(int socket, MsgHdr message, int flags) { + return posix().sendmsg(socket, message, flags); + } + + public int recvmsg(int socket, MsgHdr message, int flags) { + return posix().recvmsg(socket, message, flags); + } + + public int truncate(CharSequence path, long length) { + return posix().truncate(path, length); + } + + public int ftruncate(int fd, long offset) { + return posix().ftruncate(fd, offset); + } + + public int rename(CharSequence oldName, CharSequence newName) { + return posix().rename(oldName, newName); + } + + public String getcwd() { + return posix().getcwd(); + } + + public int fsync(int fd) { + return posix().fsync(fd); + } + + public int fdatasync(int fd) { + return posix().fdatasync(fd); + } + + public int mkfifo(String path, int mode) { + return posix().mkfifo(path, mode); + } + + public String gethostname() { + return posix().gethostname(); + } + + public int daemon(int nochdir, int noclose) { + return posix().daemon(nochdir, noclose); + } + + public long[] getgroups() { + return posix().getgroups(); + } + + public int getgroups(int size, int[] groups) { + return posix().getgroups(size, groups); + } + + public String nl_langinfo(int item) { + return posix().nl_langinfo(item); + } + + public String setlocale(int category, String locale) { + return posix().setlocale(category, locale); + } + + @Override + public String strerror(int code) { + return posix().strerror(code); + } + + @Override + public Timeval allocateTimeval() { return posix().allocateTimeval(); } + + @Override + public int gettimeofday(Timeval tv) { return posix().gettimeofday(tv); } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `libc()` could be null and is dereferenced at line 446. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int LazyPOSIX.fpathconf(int,Pathconf) + +### Procedure Id: +jnr.posix.LazyPOSIX.fpathconf(int,jnr.constants.platform.Pathconf):int.c7b32cd360dedf01b210044c975abcc2 + +### File: +src/main/java/jnr/posix/LazyPOSIX.java + +### Key: +LazyPOSIX.java|fpathconf|NULL_DEREFERENCE + +### Node Key: +2f1ce606f9790f4abba1ebc761dd6bee + +### Hash: +f1043d2721917ec949e1c0debd0d6085 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9018/instruction.md b/inferredbugs-9018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..740eec63dd03edd1336b458b8922071a805591a5 --- /dev/null +++ b/inferredbugs-9018/instruction.md @@ -0,0 +1,196 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jnr-posix +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java + +package jnr.posix; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; + +import jnr.constants.platform.LangInfo; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + */ +public class GroupTest { + + public GroupTest() { + } + + private static POSIX posix; + @BeforeClass + public static void setUpClass() throws Exception { + posix = POSIXFactory.getPOSIX(new DummyPOSIXHandler(), true); + } + + @AfterClass + public static void tearDownClass() throws Exception { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + // TODO add test methods here. + // The methods must be annotated with annotation @Test. For example: + // + // @Test + // public void hello() {} + @Test + public void getgrnam() { + if (jnr.ffi.Platform.getNativePlatform().isUnix()) { + final String LOGIN = "nogroup"; + Group grp = posix.getgrnam(LOGIN); + assertNotNull(grp); + assertEquals("Login name not equal", LOGIN, grp.getName()); + } + } + + @Test + public void nonExistantGroupReturnsNull() { + if (jnr.ffi.Platform.getNativePlatform().isUnix()) { + final String LOGIN = "dkjhfjkdsfhjksdhfsdjkhfsdkjhfdskj"; + assertNull("getpwnam for non-existant group should return null", posix.getgrnam(LOGIN)); + } + } + + @Test + public void getgrent() { + if (jnr.ffi.Platform.getNativePlatform().isUnix()) { + ArrayList grps = new ArrayList(); + while (true) { + Group grp = posix.getgrent(); + if (grp == null) { + break; + } + grps.add(grp); + } + for (Group grp : grps) { + assertNotNull(grp.getName()); + assertNotNull(grp.getPassword()); + assertNotNull(grp.getGID()); + for (String member : grp.getMembers()) { + assertNotNull(member); + } + } + } + } + + @Test + public void getgroups() throws Throwable { + if (jnr.ffi.Platform.getNativePlatform().isUnix()) { + InputStreamReader isr = null; + BufferedReader reader = null; + + try { + isr = new InputStreamReader(Runtime.getRuntime().exec("id -G").getInputStream()); + reader = new BufferedReader(isr); + + String[] groupIdsAsStrings = reader.readLine().split(" "); + long[] expectedGroupIds = new long[groupIdsAsStrings.length]; + + for (int i = 0; i < groupIdsAsStrings.length; i++) { + expectedGroupIds[i] = Long.parseLong(groupIdsAsStrings[i]); + } + + long[] actualGroupIds = posix.getgroups(); + + Arrays.sort(expectedGroupIds); + Arrays.sort(actualGroupIds); + + assertArrayEquals(expectedGroupIds, actualGroupIds); + } finally { + if (reader != null) { + reader.close(); + } + + if (isr != null) { + isr.close(); + } + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.lang.Process` acquired by call to `exec(...)` at line 95 is not released after line 95. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GroupTest.getgroups() + +### Procedure Id: +jnr.posix.GroupTest.getgroups():void.1918103b0f6b7f5dea5de7dfe6d819d0 + +### File: +src/test/java/jnr/posix/GroupTest.java + +### Key: +GroupTest.java|getgroups|RESOURCE_LEAK + +### Node Key: +3451cb93d845d85a147a6855623bf280 + +### Hash: +c2060851771c4b95cc266705f5c2e6f9 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9019/instruction.md b/inferredbugs-9019/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0453a7e9a72eef869108dd6683d270ed87feb028 --- /dev/null +++ b/inferredbugs-9019/instruction.md @@ -0,0 +1,287 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jnr-posix +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package jnr.posix; + +import jnr.constants.platform.windows.OpenFlags; +import jnr.ffi.Library; +import jnr.ffi.Platform; +import jnr.ffi.annotations.Out; +import org.junit.*; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.*; +import static jnr.posix.SpawnFileAction.*; + +public class SpawnTest { + private static POSIX posix; + private static LibC libc; + private static final List emptyEnv = Arrays.asList(new String[0]); + private static final List emptyActions = Arrays.asList(new SpawnFileAction[0]); + + public static interface LibC { + int pipe(@Out int[] fds); + } + + @BeforeClass + public static void setUpClass() throws Exception { + if (Platform.getNativePlatform().isUnix()) { + posix = POSIXFactory.getPOSIX(new DummyPOSIXHandler(), true); + libc = Library.loadLibrary(LibC.class, "c"); + } + } + + @Test public void validPid() { + if (Platform.getNativePlatform().isUnix()) { + long pid = -1; + try { + pid = posix.posix_spawnp("true", emptyActions, Arrays.asList("true"), emptyEnv); + assertTrue(pid != -1); + } finally { + if (pid != -1) posix.libc().waitpid((int) pid, null, 0); + } + } + } + + @Test public void emptyCommand() { + if (Platform.getNativePlatform().isUnix()) { + long pid = -1; + try { + pid = posix.posix_spawnp("", emptyActions, Collections.EMPTY_LIST, emptyEnv); + assertEquals(-1, pid); + } finally { + if (pid != -1) posix.libc().waitpid((int) pid, null, 0); + } + } + } + + private static void closePipe(int[] fds) { + posix.libc().close(fds[0]); + posix.libc().close(fds[1]); + } + + private static void killChild(long pid) { + if (pid > 0) { + posix.libc().kill((int) pid, 9); posix.libc().waitpid((int) pid, null, 0); + } + } + + @Test public void outputPipe() { + if (Platform.getNativePlatform().isUnix()) { + int[] outputPipe = { -1, -1 }; + long pid = -1; + try { + assertFalse(libc.pipe(outputPipe) < 0); + assertNotSame(-1, outputPipe[0]); + assertNotSame(-1, outputPipe[1]); + + List actions = Arrays.asList(dup(outputPipe[1], 1)); + pid = posix.posix_spawnp("echo", actions, Arrays.asList("echo", "bar"), emptyEnv); + assertTrue(pid != -1); + + // close the write side of the output pipe, so read() will return immediately once the process has exited + posix.libc().close(outputPipe[1]); + + ByteBuffer output = ByteBuffer.allocate(100); + long nbytes = posix.libc().read(outputPipe[0], output, output.remaining()); + assertEquals(4L, nbytes); + output.position((int) nbytes).flip(); + byte[] bytes = new byte[output.remaining()]; + output.get(bytes); + assertEquals("bar", new String(bytes).trim()); + } finally { + closePipe(outputPipe); + killChild(pid); + } + } + } + + @Test public void inputPipe() { + if (Platform.getNativePlatform().isUnix()) { + int[] outputPipe = { -1, -1 }; + int[] inputPipe = { -1, -1 }; + long pid = -1; + try { + assertFalse(libc.pipe(outputPipe) < 0); + assertFalse(libc.pipe(inputPipe) < 0); + assertNotSame(-1, outputPipe[0]); + assertNotSame(-1, outputPipe[1]); + assertNotSame(-1, inputPipe[0]); + assertNotSame(-1, inputPipe[1]); + + List actions = Arrays.asList(dup(inputPipe[0], 0), dup(outputPipe[1], 1)); + pid = posix.posix_spawnp("cat", actions, Arrays.asList("cat", "-"), emptyEnv); + assertTrue(pid != -1); + posix.libc().close(inputPipe[0]); + assertEquals(3, posix.libc().write(inputPipe[1], ByteBuffer.wrap("foo".getBytes(Charset.forName("US-ASCII"))), 3)); + posix.libc().close(inputPipe[1]); // send EOF to process + + // close the write side of the output pipe, so read() will return immediately once the process has exited + posix.libc().close(outputPipe[1]); + + ByteBuffer output = ByteBuffer.allocate(100); + long nbytes = posix.libc().read(outputPipe[0], output, output.remaining()); + assertEquals(3L, nbytes); + output.position((int) nbytes).flip(); + byte[] bytes = new byte[output.remaining()]; + output.get(bytes); + assertEquals("foo", new String(bytes).trim()); + } finally { + closePipe(outputPipe); + closePipe(inputPipe); + killChild(pid); + } + } + } + + @Test public void inputFile() throws IOException { + if (Platform.getNativePlatform().isUnix()) { + File inputFile = File.createTempFile("foo", null); + FileOutputStream inputStream = new FileOutputStream(inputFile); + inputStream.write("foo".getBytes("US-ASCII")); + inputStream.close(); + int[] outputPipe = { -1, -1 }; + long pid = -1; + try { + assertFalse(libc.pipe(outputPipe) < 0); + assertNotSame(-1, outputPipe[0]); + assertNotSame(-1, outputPipe[1]); + + List actions = Arrays.asList(open(inputFile.getAbsolutePath(), 0, OpenFlags.O_RDONLY.intValue(), 0444), + dup(outputPipe[1], 1)); + pid = posix.posix_spawnp("cat", actions, Arrays.asList("cat", "-"), emptyEnv); + assertTrue(pid != -1); + + // close the write side of the output pipe, so read() will return immediately once the process has exited + posix.libc().close(outputPipe[1]); + + ByteBuffer output = ByteBuffer.allocate(100); + long nbytes = posix.libc().read(outputPipe[0], output, output.remaining()); + assertEquals(3L, nbytes); + output.position((int) nbytes).flip(); + byte[] bytes = new byte[output.remaining()]; + output.get(bytes); + assertEquals("foo", new String(bytes).trim()); + } finally { + closePipe(outputPipe); + killChild(pid); + } + } + } + + @Test public void closeInput() throws IOException { + if (Platform.getNativePlatform().isUnix()) { + int[] outputPipe = { -1, -1 }; + int[] inputPipe = { -1, -1 }; + long pid = -1; + try { + assertFalse(libc.pipe(outputPipe) < 0); + assertFalse(libc.pipe(inputPipe) < 0); + assertNotSame(-1, outputPipe[0]); + assertNotSame(-1, outputPipe[1]); + assertNotSame(-1, inputPipe[0]); + assertNotSame(-1, inputPipe[1]); + + List actions = Arrays.asList(dup(outputPipe[1], 1), + open("/dev/null", 2, OpenFlags.O_WRONLY.intValue(), 0444), + close(inputPipe[0]), close(inputPipe[1])); + pid = posix.posix_spawnp("cat", actions, Arrays.asList("cat", "/dev/fd/" + inputPipe[0]), emptyEnv); + assertTrue(pid != -1); + assertEquals(3, posix.libc().write(inputPipe[1], ByteBuffer.wrap("foo".getBytes(Charset.forName("US-ASCII"))), 3)); + posix.libc().close(inputPipe[1]); // send EOF to process + + // close the write side of the output pipe, so read() will return immediately once the process has exited + posix.libc().close(outputPipe[1]); + + // Output from the process on stdout should be empty + ByteBuffer output = ByteBuffer.allocate(100); + long nbytes = posix.libc().read(outputPipe[0], output, output.remaining()); + assertEquals(0L, nbytes); + } finally { + closePipe(inputPipe); + closePipe(outputPipe); + killChild(pid); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileOutputStream` acquired to `inputStream` by call to `FileOutputStream(...)` at line 145 is not released after line 175. +**Note**: potential exception at line 146 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SpawnTest.inputFile() + +### Procedure Id: +jnr.posix.SpawnTest.inputFile():void.8291dbb506208a239f26dfb926c16165 + +### File: +src/test/java/jnr/posix/SpawnTest.java + +### Key: +SpawnTest.java|inputFile|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +61c4b61bc9f3622c2b9ce9047217d002 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9020/instruction.md b/inferredbugs-9020/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..49bdf3b1d730e0ee9171f20e130222997061705e --- /dev/null +++ b/inferredbugs-9020/instruction.md @@ -0,0 +1,239 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jnr-posix +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package jnr.posix; + +import jnr.constants.platform.Fcntl; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; +import java.io.FileDescriptor; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.RandomAccessFile; +import java.nio.channels.FileChannel; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class FileTest { + private static POSIX posix; + + @BeforeClass + public static void setUpClass() throws Exception { + posix = POSIXFactory.getPOSIX(new DummyPOSIXHandler(), true); + } + + @Test + public void utimeTest() throws Throwable { + File f = File.createTempFile("utime", null); + long oldTime = posix.stat(f.getAbsolutePath()).mtime(); + Thread.sleep(2000); + int rval = posix.utimes(f.getAbsolutePath(), null, null); + assertEquals("utime did not return 0", 0, rval); + long newTime = posix.stat(f.getAbsolutePath()).mtime(); + f.delete(); + assertTrue("mtime failed", newTime > oldTime); + } + + @Test + public void linkTest() throws Throwable { + File f1 = File.createTempFile("utime", null); + File f2 = new File(f1.getAbsolutePath() + "link"); + int rval = posix.link(f1.getAbsolutePath(), f2.getAbsolutePath()); + assertEquals("link did not return 0", 0, rval); + assertTrue("Link was not created", f2.exists()); + f1.delete(); + f2.delete(); + } + + @Test + public void mkdirRelativeTest() throws Throwable { + File dir = new File("tmp"); + int rval = posix.mkdir(dir.getPath(), 0); + assertEquals("mkdir did not return 0", 0, rval); + assertTrue("Directory was not created", dir.exists()); + dir.delete(); + } + + @Test + public void mkdirAbsoluteTest() throws Throwable { + File dir = new File("tmp"); + int rval = posix.mkdir(dir.getAbsolutePath(), 0); + assertEquals("mkdir did not return 0", 0, rval); + assertTrue("Directory was not created", dir.exists()); + dir.delete(); + } + + @Test + public void flockTest() throws Throwable { + File tmp = File.createTempFile("flockTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + RandomAccessFile raf2 = new RandomAccessFile(tmp, "rw"); + FileChannel fc = raf.getChannel(); + FileChannel fc2 = raf2.getChannel(); + FileDescriptor FD = JavaLibCHelper.getDescriptorFromChannel(fc); + FileDescriptor FD2 = JavaLibCHelper.getDescriptorFromChannel(fc2); + int fd = JavaLibCHelper.getfdFromDescriptor(FD); + int fd2 = JavaLibCHelper.getfdFromDescriptor(FD2); + + assertEquals(0, posix.flock(fd, 1)); // LOCK_SH + assertEquals(0, posix.flock(fd, 8)); // LOCK_UN + assertEquals(0, posix.flock(fd, 2)); // LOCK_EX + assertEquals(-1, posix.flock(fd2, 2 | 4)); // LOCK_EX | LOCK_NB + assertEquals(0, posix.flock(fd, 8)); // LOCK_UN + } + + @Test + public void dupTest() throws Throwable { + File tmp = File.createTempFile("dupTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + FileChannel fileChannel = raf.getChannel(); + int fileDescriptor = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(fileChannel)); + + byte[] outContent = "foo".getBytes(); + + FileDescriptor newFileDescriptor = JavaLibCHelper.toFileDescriptor(posix.dup(fileDescriptor)); + + new FileOutputStream(JavaLibCHelper.toFileDescriptor(fileDescriptor)).write(outContent); + raf.seek(0); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(newFileDescriptor).read(inContent, 0, 3); + + assertArrayEquals(inContent, outContent); + } + + @Test + public void dup2Test() throws Throwable { + File tmp = File.createTempFile("dupTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + int oldFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(new RandomAccessFile(tmp, "rw").getChannel())); + int newFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(raf.getChannel())); + + byte[] outContent = "foo".getBytes(); + + FileDescriptor newFileDescriptor = JavaLibCHelper.toFileDescriptor(posix.dup2(oldFd, newFd)); + + new FileOutputStream(JavaLibCHelper.toFileDescriptor(oldFd)).write(outContent); + raf.seek(0); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(newFileDescriptor).read(inContent, 0, 3); + + assertArrayEquals(inContent, outContent); + } + + @Test + public void fcntlDupfdTest() throws Throwable { + File tmp = File.createTempFile("fcntlTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + int fd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(raf.getChannel())); + + byte[] outContent = "foo".getBytes(); + + int newFd = posix.fcntl(fd, Fcntl.F_DUPFD); + + new FileOutputStream(JavaLibCHelper.toFileDescriptor(fd)).write(outContent); + raf.seek(0); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(JavaLibCHelper.toFileDescriptor(newFd)).read(inContent, 0, 3); + + assertArrayEquals(inContent, outContent); + } + + @Test + public void fcntlDupfdWithArgTest() throws Throwable { + File tmp = File.createTempFile("dupTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + int oldFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(new RandomAccessFile(tmp, "rw").getChannel())); + int newFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(raf.getChannel())); + + byte[] outContent = "foo".getBytes(); + + FileDescriptor newFileDescriptor = JavaLibCHelper.toFileDescriptor(posix.fcntl(oldFd, Fcntl.F_DUPFD, newFd)); + + new FileOutputStream(JavaLibCHelper.toFileDescriptor(newFd)).write(outContent); + raf.seek(0); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(newFileDescriptor).read(inContent, 0, 3); + + assertArrayEquals(inContent, outContent); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.RandomAccessFile` acquired to `raf` by call to `RandomAccessFile(...)` at line 148 is not released after line 163. +**Note**: potential exception at line 156 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void FileTest.fcntlDupfdWithArgTest() + +### Procedure Id: +jnr.posix.FileTest.fcntlDupfdWithArgTest():void.1559e792a5ac762b376e2e99e5807f23 + +### File: +src/test/java/jnr/posix/FileTest.java + +### Key: +FileTest.java|fcntlDupfdWithArgTest|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +8de0f1e5c6ce266644c2cbf09a56e940 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9021/instruction.md b/inferredbugs-9021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..77e00f24c6128a539b8aa0a06b0bd6de8c126b82 --- /dev/null +++ b/inferredbugs-9021/instruction.md @@ -0,0 +1,741 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jnr-posix +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package jnr.posix; + +import jnr.constants.platform.Access; +import jnr.constants.platform.Fcntl; +import jnr.constants.platform.Errno; +import jnr.constants.platform.OpenFlags; +import jnr.ffi.Pointer; +import jnr.posix.util.Platform; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.Charset; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +public class FileTest { + private static POSIX posix; + + @BeforeClass + public static void setUpClass() throws Exception { + posix = POSIXFactory.getPOSIX(new DummyPOSIXHandler(), true); + } + + @Test + public void utimesTest() throws Throwable { + // FIXME: On Windows this is working but providing wrong numbers and therefore getting wrong results. + if (!Platform.IS_WINDOWS) { + File f = File.createTempFile("utimes", null); + + int rval = posix.utimes(f.getAbsolutePath(), new long[]{800, 200}, new long[]{900, 300}); + assertEquals("utimes did not return 0", 0, rval); + + FileStat stat = posix.stat(f.getAbsolutePath()); + + assertEquals("atime seconds failed", 800, stat.atime()); + assertEquals("mtime seconds failed", 900, stat.mtime()); + + // The nano secs part is available in other stat implementations. We really just want to verify that the + // nsec portion of the timeval is passed through to the POSIX call. + // Mac seems to fail this test sporadically. + if (stat instanceof NanosecondFileStat && !Platform.IS_MAC) { + NanosecondFileStat linuxStat = (NanosecondFileStat) stat; + + assertEquals("atime useconds failed", 200000, linuxStat.aTimeNanoSecs()); + assertEquals("mtime useconds failed", 300000, linuxStat.mTimeNanoSecs()); + } + + f.delete(); + } + } + + @Test + public void utimesDefaultValuesTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File f = File.createTempFile("utimes", null); + + long oldTime = posix.stat(f.getAbsolutePath()).mtime(); + Thread.sleep(2000); + + int rval = posix.utimes(f.getAbsolutePath(), null, null); + assertEquals("utimes did not return 0", 0, rval); + + FileStat stat = posix.stat(f.getAbsolutePath()); + + assertTrue("atime failed", stat.atime() > oldTime); + assertTrue("mtime failed", stat.mtime() > oldTime); + + f.delete(); + } + } + + @Test + public void utimesPointerTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File f = File.createTempFile("utimes", null); + + Pointer times = jnr.ffi.Runtime.getSystemRuntime().getMemoryManager().allocateDirect(8 * 4); // long[2][2] == 4 longs. + times.putLong(0, 800); + times.putLong(8, 200); + times.putLong(16, 900); + times.putLong(24, 300); + + int rval = posix.utimes(f.getAbsolutePath(), times); + assertEquals("utimes did not return 0", 0, rval); + + FileStat stat = posix.stat(f.getAbsolutePath()); + + assertEquals("atime seconds failed", 800, stat.atime()); + assertEquals("mtime seconds failed", 900, stat.mtime()); + + // The nano secs part is available in other stat implementations. We use Linux x86_64 because it's + // representative. We really just want to verify that the usec portion of the timeval is passed throug + // to the POSIX call. + if (hasNanosecondPrecision(stat)) { + NanosecondFileStat linuxStat = (NanosecondFileStat) stat; + +// assertEquals("atime useconds failed", 200000, linuxStat.aTimeNanoSecs()); + assertEquals("mtime useconds failed", 300000, linuxStat.mTimeNanoSecs()); + } + + f.delete(); + } + } + + @Test + public void utimensatAbsolutePath() throws Throwable { + File file = File.createTempFile("utimensat", null); + utimensat(file, 0); + } + + @Test + public void utimensatRelativePath() throws Throwable { + String path = "utimensat"; + File file = new File(path); + file.createNewFile(); + int parentFd = posix.open(".", OpenFlags.O_DIRECTORY.intValue(), 0444); + utimensat(file, parentFd); + } + + @Test + public void futimens() throws Throwable { + File file = File.createTempFile("futimens", null); + FileStat fileStat = posix.stat(file.getPath()); + if (!hasNanosecondPrecision(fileStat)) { + file.delete(); + return; + } + + long atimeSeconds = fileStat.atime()+1; + long mtimeSeconds = fileStat.mtime()-1; + long atimeNanoSeconds = 123456789; + long mtimeNanoSeconds = 135; + int fd = posix.open(file.getAbsolutePath(), OpenFlags.O_RDWR.intValue(), 0444); + posix.futimens(fd, + new long[] {atimeSeconds, atimeNanoSeconds}, + new long[] {mtimeSeconds, mtimeNanoSeconds}); + assertStatNanoSecond(file, atimeSeconds, atimeNanoSeconds, mtimeSeconds, mtimeNanoSeconds); + } + + @Test + public void lutimesTest() throws Throwable { + // FIXME: On Windows this is working but providing wrong numbers and therefore getting wrong results. + if (!Platform.IS_WINDOWS) { + File f1 = File.createTempFile("lutimes", null); + File f2 = new File(f1.getParentFile(), "lutimes-link"); + posix.symlink(f1.getAbsolutePath(), f2.getAbsolutePath()); + + int rval = posix.utimes(f1.getAbsolutePath(), new long[]{800, 0}, new long[]{900, 0}); + assertEquals("utimes did not return 0", 0, rval); + + rval = posix.lutimes(f2.getAbsolutePath(), new long[]{1800, 0}, new long[]{1900, 0}); + assertEquals("lutimes did not return 0", 0, rval); + + FileStat stat = posix.stat(f1.getAbsolutePath()); + assertEquals("atime seconds failed", 800, stat.atime()); + assertEquals("mtime seconds failed", 900, stat.mtime()); + + stat = posix.lstat(f2.getAbsolutePath()); + assertEquals("atime seconds failed", 1800, stat.atime()); + assertEquals("mtime seconds failed", 1900, stat.mtime()); + + f1.delete(); + f2.delete(); + } + } + + @Test + public void futimeTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File f = File.createTempFile("jnr-posix-futime", "tmp"); + long oldTime = posix.stat(f.getAbsolutePath()).mtime(); + Thread.sleep(2000); + int fd = posix.open(f.getAbsolutePath(), OpenFlags.O_RDWR.intValue(), 0666); + int rval = posix.futimes(fd, null, null); + assertEquals("futime did not return 0", 0, rval); + long newTime = posix.stat(f.getAbsolutePath()).mtime(); + f.delete(); + assertTrue("mtime failed", newTime > oldTime); + } + } + + @Test + public void linkTest() throws Throwable { + File f1 = File.createTempFile("utime", null); + File f2 = new File(f1.getAbsolutePath() + "link"); + int rval = posix.link(f1.getAbsolutePath(), f2.getAbsolutePath()); + assertEquals("link did not return 0", 0, rval); + assertTrue("Link was not created", f2.exists()); + f1.delete(); + f2.delete(); + } + + @Test + public void mkdirRelativeTest() throws Throwable { + File dir = new File("tmp"); + int rval = posix.mkdir(dir.getPath(), 0); + assertEquals("mkdir did not return 0", 0, rval); + assertTrue("Directory was not created", dir.exists()); + dir.delete(); + } + + @Test + public void mkdirAbsoluteTest() throws Throwable { + File dir = new File("tmp"); + int rval = posix.mkdir(dir.getAbsolutePath(), 0); + assertEquals("mkdir did not return 0", 0, rval); + assertTrue("Directory was not created", dir.exists()); + dir.delete(); + } + + @Test + public void flockTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("flockTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + RandomAccessFile raf2 = new RandomAccessFile(tmp, "rw"); + FileChannel fc = raf.getChannel(); + FileChannel fc2 = raf2.getChannel(); + FileDescriptor FD = JavaLibCHelper.getDescriptorFromChannel(fc); + FileDescriptor FD2 = JavaLibCHelper.getDescriptorFromChannel(fc2); + int fd = JavaLibCHelper.getfdFromDescriptor(FD); + int fd2 = JavaLibCHelper.getfdFromDescriptor(FD2); + + assertEquals(0, posix.flock(fd, 1)); // LOCK_SH + assertEquals(0, posix.flock(fd, 8)); // LOCK_UN + assertEquals(0, posix.flock(fd, 2)); // LOCK_EX + assertEquals(-1, posix.flock(fd2, 2 | 4)); // LOCK_EX | LOCK_NB + assertEquals(0, posix.flock(fd, 8)); // LOCK_UN + } + } + + @Test + public void dupTest() throws Throwable { + File tmp = File.createTempFile("dupTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + FileChannel fileChannel = raf.getChannel(); + int fileDescriptor = getFdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(fileChannel)); + + byte[] outContent = "foo".getBytes(); + + FileDescriptor newFileDescriptor = toDescriptor(posix.dup(fileDescriptor)); + + new FileOutputStream(toDescriptor(fileDescriptor)).write(outContent); + raf.seek(0); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(newFileDescriptor).read(inContent, 0, 3); + + assertArrayEquals(inContent, outContent); + } + + @Test + public void dup2Test() throws Throwable { + File tmp = File.createTempFile("dupTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + int oldFd = getFdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(new RandomAccessFile(tmp, "rw").getChannel())); + int newFd = getFdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(raf.getChannel())); + + byte[] outContent = "foo".getBytes(); + + // NB: Windows differs a bit from POSIX's return value. Both will return -1 on failure, but Windows will return + // 0 upon success, while POSIX will return the new FD. Since we already know what the FD will be if the call + // is successful, it's easy to make code that works with both forms. But it is something to watch out for. + assertNotEquals(-1, posix.dup2(oldFd, newFd)); + FileDescriptor newFileDescriptor = toDescriptor(newFd); + + new FileOutputStream(toDescriptor(oldFd)).write(outContent); + raf.seek(0); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(newFileDescriptor).read(inContent, 0, 3); + + assertArrayEquals(inContent, outContent); + } + + @Test + public void fcntlDupfdTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("fcntlTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + int fd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(raf.getChannel())); + + byte[] outContent = "foo".getBytes(); + + int newFd = posix.fcntl(fd, Fcntl.F_DUPFD); + + new FileOutputStream(JavaLibCHelper.toFileDescriptor(fd)).write(outContent); + raf.seek(0); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(JavaLibCHelper.toFileDescriptor(newFd)).read(inContent, 0, 3); + + assertArrayEquals(inContent, outContent); + } + } + + @Test + public void fcntlDupfdWithArgTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("dupTest", "tmp"); + int oldFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel( + new RandomAccessFile(tmp, "rw").getChannel())); + int newFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel( + new RandomAccessFile(tmp, "rw").getChannel())); + + byte[] outContent = "foo".getBytes(); + + int dupFd = posix.fcntl(oldFd, Fcntl.F_DUPFD, newFd); + + new FileOutputStream(JavaLibCHelper.toFileDescriptor(newFd)).write(outContent); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(JavaLibCHelper.toFileDescriptor(dupFd)).read(inContent, 0, 3); + + assertTrue(dupFd > newFd); + assertArrayEquals(inContent, outContent); + } + } + + @Test + public void closeTest() throws Throwable { + File tmp = File.createTempFile("closeTest", "tmp"); + int fd = getFdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(new RandomAccessFile(tmp, "rw").getChannel())); + + int result; + + result = posix.close(fd); + assertEquals(0, result); + + result = posix.close(fd); + assertEquals(-1, result); + + // TODO (nirvdrum 06-May-15) We're not getting the correct errno value from Windows currently, so we need to skip this test. + if (!Platform.IS_WINDOWS) { + assertEquals(Errno.EBADF.intValue(), posix.errno()); + } + } + + @Test + public void unlinkTestNonWindows() throws Throwable { + if (! Platform.IS_WINDOWS) { + File tmp = File.createTempFile("unlinkTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + + raf.write("hello".getBytes()); + + int res = posix.unlink(tmp.getCanonicalPath()); + + assertEquals(0, res); + assertFalse(tmp.exists()); + + raf.write("world".getBytes()); + raf.seek(0); + + byte[] actual = new byte[10]; + raf.read(actual); + + assertArrayEquals("helloworld".getBytes(), actual); + } + } + + @Test + public void openTest() throws Throwable { + int fd = posix.open("pom.xml", 0, 0666); + + assertNotEquals(-1, fd); + + int result = posix.close(fd); + assertEquals(0, result); + + result = posix.close(fd); + assertEquals(-1, result); + } + + @Test + public void writeTest() throws Throwable { + String str = "To thine own self be true"; + File tmp = File.createTempFile("writeTest", "tmp"); + ByteBuffer buffer = ByteBuffer.wrap(str.getBytes()); + + int fd = posix.open(tmp.getAbsolutePath(), 1, 066); + posix.write(fd, buffer, str.length()); + posix.close(fd); + + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + assertEquals(raf.readLine(), new String(buffer.array())); + posix.unlink(tmp.getAbsolutePath()); + } + + @Test + public void pwriteTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + String str = "Now is the winter of our discontent"; + File tmp = File.createTempFile("pwriteTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + raf.write(str.getBytes()); + raf.close(); + + String str2 = "summer"; + ByteBuffer buffer = ByteBuffer.wrap(str2.getBytes()); + + int fd = posix.open(tmp.getAbsolutePath(), 1, 066); + posix.pwrite(fd, buffer, str2.length(), 11); + posix.close(fd); + + raf = new RandomAccessFile(tmp, "r"); + assertEquals(raf.readLine(), "Now is the summer of our discontent"); + posix.unlink(tmp.getAbsolutePath()); + } + } + + @Test + public void truncateTest() throws Throwable { + String str = "Beware the Jabberwock, my son!"; + File tmp = File.createTempFile("truncateTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + raf.write(str.getBytes()); + raf.close(); + + int shorterLength = str.length() - 10; + int longerLength = shorterLength * 2; + + // Truncate should make a file shorter if the new length is less than the old length. + posix.truncate(tmp.getAbsolutePath(), shorterLength); + assertEquals(shorterLength, tmp.length()); + + // Truncate should extend a file if the new length is greater than the old length. + posix.truncate(tmp.getAbsolutePath(), longerLength); + assertEquals(longerLength, tmp.length()); + } + + @Test + public void ftruncateTest() throws Throwable { + String str = "Beware the Jabberwock, my son!"; + File tmp = File.createTempFile("ftruncateTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + raf.write(str.getBytes()); + raf.close(); + + int fd = posix.open(tmp.getAbsolutePath(), OpenFlags.O_RDWR.intValue(), 0666); + posix.ftruncate(fd, 21); + posix.lseekLong(fd, 0, 0); + byte[] buf = new byte[21]; + int read = posix.read(fd, buf, 31); + assertEquals(21, read); + assertArrayEquals(buf, "Beware the Jabberwock".getBytes()); + } + + @Test + public void fcntlIntTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + int[] fds = new int[2]; + int ret = posix.pipe(fds); + assertEquals(0, ret); + int flags = posix.fcntlInt(fds[0], Fcntl.F_GETFD, 0); + posix.fcntlInt(fds[0], Fcntl.F_SETFD, flags | 1); // FD_CLOEXEC + assertEquals(flags | 1, posix.fcntlInt(fds[0], Fcntl.F_GETFD, 0)); + } + } + + @Test + public void fchmodTest() throws IOException { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("jnr-posix-chmod-test", "tmp"); + int fd = posix.open(tmp.getAbsolutePath(), OpenFlags.O_RDWR.intValue(), 0600); + + assertEquals("chmod: ", 0, posix.fchmod(fd, 0)); + assertEquals("chmod: ", 0, posix.fchmod(fd, 0777)); + tmp.delete(); + } + } + + + @Test + public void renameTest() throws IOException { + File oldFile = File.createTempFile("jnr-posix-rename-test", "tmp"); + File newFile = new File(oldFile.getParent() + File.separatorChar + "jnr-posix-rename-test-new"); + + assertTrue(oldFile.exists()); + assertFalse(newFile.exists()); + + posix.rename(oldFile.getCanonicalPath(), newFile.getCanonicalPath()); + + assertFalse(oldFile.exists()); + assertTrue(newFile.exists()); + + newFile.delete(); + } + + @Test + public void accessTest() throws IOException { + File tmp = File.createTempFile("jnr-posix-access-test", "tmp"); + + jnr.constants.platform.Access.F_OK.intValue(); + + // Set permissions to read-only and verify we don't have permissions to write. + posix.chmod(tmp.getCanonicalPath(), 0400); + assertEquals("access: ", -1, posix.access(tmp.getCanonicalPath(), Access.W_OK.intValue())); + assertEquals("access: ", 0, posix.access(tmp.getCanonicalPath(), Access.R_OK.intValue())); + + // Reset the permissions to read-wrinte and verify we now have permissions to write. + posix.chmod(tmp.getCanonicalPath(), 0600); + assertEquals("access: ", 0, posix.access(tmp.getCanonicalPath(), Access.W_OK.intValue())); + assertEquals("access: ", 0, posix.access(tmp.getCanonicalPath(), Access.R_OK.intValue())); + + // F_OK just checks the file exists and should pass. + assertEquals("access: ", 0, posix.access(tmp.getCanonicalPath(), Access.F_OK.intValue())); + } + + @Test + public void readlinkTest() throws IOException { + if (!Platform.IS_WINDOWS) { + File file = File.createTempFile("jnr-pøsix-réådlînk-tést", "tmp"); + File link = new File(file.getAbsolutePath() + "link"); + + posix.symlink(file.getAbsolutePath(), link.getAbsolutePath()); + + byte[] fileBytes = file.getAbsolutePath().getBytes(); + int fileLength = fileBytes.length; + + byte[] buffer = new byte[fileLength]; + + assertEquals(fileLength, posix.readlink(link.getAbsolutePath(), buffer, buffer.length)); + + assertArrayEquals(fileBytes, buffer); + + link.delete(); + file.delete(); + } + } + + @Test + public void readlinkByteBufferTest() throws IOException { + if (!Platform.IS_WINDOWS) { + File file = File.createTempFile("jnr-pøsix-réådlînk-tést", "tmp"); + File link = new File(file.getAbsolutePath() + "link"); + + posix.symlink(file.getAbsolutePath(), link.getAbsolutePath()); + + byte[] fileBytes = file.getAbsolutePath().getBytes(); + int fileLength = fileBytes.length; + ByteBuffer buffer = ByteBuffer.allocate(fileLength); + + assertEquals(fileLength, posix.readlink(link.getAbsolutePath(), buffer, buffer.capacity())); + + assertArrayEquals(buffer.array(), file.getAbsolutePath().getBytes()); + + link.delete(); + file.delete(); + } + } + + @Test + public void readlinkPointerTest() throws IOException { + if (!Platform.IS_WINDOWS) { + File file = File.createTempFile("jnr-pøsix-réådlînk-tést", "tmp"); + File link = new File(file.getAbsolutePath() + "link"); + + int bufSize = 1024; + + Pointer buffer = jnr.ffi.Runtime.getSystemRuntime().getMemoryManager().allocateDirect(bufSize); + + posix.symlink(file.getAbsolutePath(), link.getAbsolutePath()); + + byte[] fileBytes = file.getAbsolutePath().getBytes(); + int fileLength = fileBytes.length; + + assertEquals(fileLength, posix.readlink(link.getAbsolutePath(), buffer, bufSize)); + + assertEquals(file.getAbsolutePath(), buffer.getString(0, fileLength, Charset.defaultCharset())); + + link.delete(); + file.delete(); + } + } + + @Test + public void mkfifoTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("mkfifoTest", "tmp"); + tmp.deleteOnExit(); + + int ret = posix.mkfifo(tmp.getAbsolutePath(), 0666); + + FileInputStream fis = new FileInputStream(tmp); + FileOutputStream fos = new FileOutputStream(tmp); + + byte[] content = "hello".getBytes(); + + fos.write(content); + fis.read(content); + + assertArrayEquals("hello".getBytes(), content); + } + } + + @Test + public void lseekTest() throws Throwable { + if (Platform.IS_MAC) { + int fd = posix.open("/dev/zero", 0, 0); + + // use 2^33 to ensure we're out of int range + long offset = (long) Math.pow(2, 33); + long seek = posix.lseekLong(fd, offset, 0); + + assertEquals(seek, offset); + } + } + + private int getFdFromDescriptor(FileDescriptor descriptor) { + if (Platform.IS_WINDOWS) { + HANDLE handle = JavaLibCHelper.gethandle(descriptor); + return ((WindowsLibC) posix.libc())._open_osfhandle(handle, 0); + } else { + return JavaLibCHelper.getfdFromDescriptor(descriptor); + } + } + + private FileDescriptor toDescriptor(int fd) { + if (Platform.IS_WINDOWS) { + HANDLE handle = ((WindowsLibC) posix.libc())._get_osfhandle(fd); + return JavaLibCHelper.toFileDescriptor(handle); + } else { + return JavaLibCHelper.toFileDescriptor(fd); + } + } + + private boolean hasNanosecondPrecision(FileStat fileStat) { + return fileStat instanceof NanosecondFileStat && !Platform.IS_MAC; + } + + private void utimensat(File file, int parentFd) { + String path = file.getAbsolutePath(); + FileStat fileStat = posix.stat(path); + if (!hasNanosecondPrecision(fileStat)) { + file.delete(); + return; + } + + long atimeSeconds = fileStat.atime()+2; + long mtimeSeconds = fileStat.mtime()-2; + long atimeNanoSeconds = 123456789; + long mtimeNanoSeconds = 135; + posix.utimensat(parentFd, + path, + new long[] {atimeSeconds, atimeNanoSeconds}, + new long[] {mtimeSeconds, mtimeNanoSeconds}, + 0); + assertStatNanoSecond(file, atimeSeconds, atimeNanoSeconds, mtimeSeconds, mtimeNanoSeconds); + } + + private void assertStatNanoSecond(File file, long atimeSeconds, long atimeNanoSeconds, long mtimeSeconds, long mtimeNanoSeconds) { + NanosecondFileStat nanosecondFileStat = (NanosecondFileStat) posix.stat(file.getPath()); + assertEquals("Access timestamp should be updated", atimeSeconds, nanosecondFileStat.atime()); + assertEquals("Modification timestamp should be updated", mtimeSeconds, nanosecondFileStat.mtime()); + assertEquals("Access time precision should be in ns", atimeNanoSeconds, nanosecondFileStat.aTimeNanoSecs()); + assertEquals("Modification time precision should be in ns", mtimeNanoSeconds, nanosecondFileStat.mTimeNanoSecs()); + file.delete(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.RandomAccessFile` acquired by call to `RandomAccessFile(...)` at line 263 is not released after line 263. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void FileTest.dup2Test() + +### Procedure Id: +jnr.posix.FileTest.dup2Test():void.aed3687fbd91ea79315b596c1b2fe38a + +### File: +src/test/java/jnr/posix/FileTest.java + +### Key: +FileTest.java|dup2Test|RESOURCE_LEAK + +### Node Key: +09e5c4f3b1fdd2ad7fa33b90979cdcf7 + +### Hash: +c8791198ebb9ca0c76d7a0a0e1ad7973 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9026/instruction.md b/inferredbugs-9026/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e4220bfbbbb7883b9b5025c844a8c91bf8e37f2f --- /dev/null +++ b/inferredbugs-9026/instruction.md @@ -0,0 +1,278 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** graphchi-java +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package edu.cmu.graphchi.shards; + +import edu.cmu.graphchi.ChiVertex; +import edu.cmu.graphchi.datablocks.BytesToValueConverter; +import edu.cmu.graphchi.datablocks.DataBlockManager; + +import java.io.*; + +/** + * Copyright [2012] [Aapo Kyrola, Guy Blelloch, Carlos Guestrin / Carnegie Mellon University] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class MemoryShard { + + private String edgeDataFilename; + private String adjDataFilename; + private int rangeStart; + private int rangeEnd; + + private byte[] adjData; + private int blockId; + private int edataFilesize; + private boolean loaded = false; + private boolean hasSetRangeOffset = false, hasSetOffset = false; + + private int rangeStartOffset, rangeStartEdgePtr, rangeContVid; + + private DataBlockManager dataBlockManager; + private BytesToValueConverter converter; + private int streamingOffset, streamingOffsetEdgePtr, streamingOffsetVid; + + private MemoryShard() {} + + public MemoryShard(String edgeDataFilename, String adjDataFilename, int rangeStart, int rangeEnd) { + this.edgeDataFilename = edgeDataFilename; + this.adjDataFilename = adjDataFilename; + this.rangeStart = rangeStart; + this.rangeEnd = rangeEnd; + } + + public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException { + byte[] data = dataBlockManager.getRawBlock(blockId); + + if (modifiesInedges) { + FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename)); + fos.write(data); + fos.close(); + } else if (modifiesOutedges) { + ucar.unidata.io.RandomAccessFile rFile = + new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd"); + rFile.seek(rangeStartEdgePtr); + int last = streamingOffsetEdgePtr; + if (last == 0) last = edataFilesize; + rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr); + rFile.close(); + } + dataBlockManager.release(blockId); + + } + + public void loadVertices(int windowStart, int windowEnd, ChiVertex[] vertices) + throws FileNotFoundException, IOException { + if (adjData == null) { + loadAdj(); + + edataFilesize = (int) new File(edgeDataFilename).length(); + blockId = dataBlockManager.allocateBlock(edataFilesize); + } + + + System.out.println("Load memory shard"); + int vid = 0; + int edataPtr = 0; + int adjOffset = 0; + int sizeOf = converter.sizeOf(); + DataInputStream adjInput = new DataInputStream(new ByteArrayInputStream(adjData)); + while(adjInput.available() > 0) { + if (!hasSetOffset && vid > rangeEnd) { + streamingOffset = adjOffset; + streamingOffsetEdgePtr = edataPtr; + streamingOffsetVid = vid; + hasSetOffset = true; + } + if (!hasSetRangeOffset && vid >= rangeStart) { + rangeStartOffset = adjOffset; + rangeStartEdgePtr = edataPtr; + hasSetRangeOffset = true; + } + + int n = 0; + int ns = adjInput.readUnsignedByte(); + adjOffset += 1; + assert(ns >= 0); + if (ns == 0) { + // next value tells the number of vertices with zeros + vid++; + int nz = adjInput.readUnsignedByte(); + adjOffset += 1; + vid += nz; + continue; + } + if (ns == 0xff) { // If 255 is not enough, then stores a 32-bit integer after. + n = Integer.reverseBytes(adjInput.readInt()); + adjOffset += 4; + } else { + n = ns; + } + + ChiVertex vertex = null; + if (vid >= windowStart && vid <= windowEnd) { + vertex = vertices[vid - windowStart]; + } + + while (--n >= 0) { + int target = Integer.reverseBytes(adjInput.readInt()); + adjOffset += 4; + if (!(target >= rangeStart && target <= rangeEnd)) + throw new IllegalStateException("Target " + target + " not in range!"); + if (vertex != null) { + vertex.addOutEdge(blockId, edataPtr, target); + } + + if (target >= windowStart) { + if (target <= windowEnd) { + ChiVertex dstVertex = vertices[target - windowStart]; + if (dstVertex != null) { + dstVertex.addInEdge(blockId, edataPtr, vid); + } + if (vertex != null && dstVertex != null) { + dstVertex.parallelSafe = false; + vertex.parallelSafe = false; + } + } + } + edataPtr += sizeOf; + + // TODO: skip + } + vid++; + } + + /* Load the edge data from file. Should be done asynchronously. */ + if (!loaded) { + int read = 0; + FileInputStream fdis = new FileInputStream(new File(edgeDataFilename)); + while (read < edataFilesize) { + read += fdis.read(dataBlockManager.getRawBlock(blockId), read, edataFilesize - read); + } + + loaded = true; + } + } + + + private void loadAdj() throws FileNotFoundException, IOException { + File adjFile = new File(adjDataFilename); + FileInputStream fis = new FileInputStream(adjFile); + + int filesize = (int) adjFile.length(); + adjData = new byte[filesize]; + + int read = 0; + while (read < filesize) { + read += fis.read(adjData, read, filesize - read); + } + + } + + public DataBlockManager getDataBlockManager() { + return dataBlockManager; + } + + public void setDataBlockManager(DataBlockManager dataBlockManager) { + this.dataBlockManager = dataBlockManager; + } + + public void setConverter(BytesToValueConverter converter) { + this.converter = converter; + } + + public int getStreamingOffset() { + return streamingOffset; + } + + public int getStreamingOffsetEdgePtr() { + return streamingOffsetEdgePtr; + } + + public int getStreamingOffsetVid() { + return streamingOffsetVid; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileOutputStream` acquired to `fos` by call to `FileOutputStream(...)` at line 56 is not released after line 70. +**Note**: potential exception at line 57 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MemoryShard.commitAndRelease(boolean,boolean) + +### Procedure Id: +edu.cmu.graphchi.shards.MemoryShard.commitAndRelease(boolean,boolean):void.2d929323907b6d7f6e71be996df592b1 + +### File: +src/edu/cmu/graphchi/shards/MemoryShard.java + +### Key: +MemoryShard.java|commitAndRelease|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +75dcc8ea05b6b116cfe783201608b79d + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9027/instruction.md b/inferredbugs-9027/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ecdc7afbc8db5890332f1e826a0804d6cc8c45d4 --- /dev/null +++ b/inferredbugs-9027/instruction.md @@ -0,0 +1,278 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** graphchi-java +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package edu.cmu.graphchi.shards; + +import edu.cmu.graphchi.ChiVertex; +import edu.cmu.graphchi.datablocks.BytesToValueConverter; +import edu.cmu.graphchi.datablocks.DataBlockManager; + +import java.io.*; + +/** + * Copyright [2012] [Aapo Kyrola, Guy Blelloch, Carlos Guestrin / Carnegie Mellon University] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class MemoryShard { + + private String edgeDataFilename; + private String adjDataFilename; + private int rangeStart; + private int rangeEnd; + + private byte[] adjData; + private int blockId; + private int edataFilesize; + private boolean loaded = false; + private boolean hasSetRangeOffset = false, hasSetOffset = false; + + private int rangeStartOffset, rangeStartEdgePtr, rangeContVid; + + private DataBlockManager dataBlockManager; + private BytesToValueConverter converter; + private int streamingOffset, streamingOffsetEdgePtr, streamingOffsetVid; + + private MemoryShard() {} + + public MemoryShard(String edgeDataFilename, String adjDataFilename, int rangeStart, int rangeEnd) { + this.edgeDataFilename = edgeDataFilename; + this.adjDataFilename = adjDataFilename; + this.rangeStart = rangeStart; + this.rangeEnd = rangeEnd; + } + + public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException { + byte[] data = dataBlockManager.getRawBlock(blockId); + + if (modifiesInedges) { + FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename)); + fos.write(data); + fos.close(); + } else if (modifiesOutedges) { + ucar.unidata.io.RandomAccessFile rFile = + new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd"); + rFile.seek(rangeStartEdgePtr); + int last = streamingOffsetEdgePtr; + if (last == 0) last = edataFilesize; + rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr); + rFile.close(); + } + dataBlockManager.release(blockId); + + } + + public void loadVertices(int windowStart, int windowEnd, ChiVertex[] vertices) + throws FileNotFoundException, IOException { + if (adjData == null) { + loadAdj(); + + edataFilesize = (int) new File(edgeDataFilename).length(); + blockId = dataBlockManager.allocateBlock(edataFilesize); + } + + + System.out.println("Load memory shard"); + int vid = 0; + int edataPtr = 0; + int adjOffset = 0; + int sizeOf = converter.sizeOf(); + DataInputStream adjInput = new DataInputStream(new ByteArrayInputStream(adjData)); + while(adjInput.available() > 0) { + if (!hasSetOffset && vid > rangeEnd) { + streamingOffset = adjOffset; + streamingOffsetEdgePtr = edataPtr; + streamingOffsetVid = vid; + hasSetOffset = true; + } + if (!hasSetRangeOffset && vid >= rangeStart) { + rangeStartOffset = adjOffset; + rangeStartEdgePtr = edataPtr; + hasSetRangeOffset = true; + } + + int n = 0; + int ns = adjInput.readUnsignedByte(); + adjOffset += 1; + assert(ns >= 0); + if (ns == 0) { + // next value tells the number of vertices with zeros + vid++; + int nz = adjInput.readUnsignedByte(); + adjOffset += 1; + vid += nz; + continue; + } + if (ns == 0xff) { // If 255 is not enough, then stores a 32-bit integer after. + n = Integer.reverseBytes(adjInput.readInt()); + adjOffset += 4; + } else { + n = ns; + } + + ChiVertex vertex = null; + if (vid >= windowStart && vid <= windowEnd) { + vertex = vertices[vid - windowStart]; + } + + while (--n >= 0) { + int target = Integer.reverseBytes(adjInput.readInt()); + adjOffset += 4; + if (!(target >= rangeStart && target <= rangeEnd)) + throw new IllegalStateException("Target " + target + " not in range!"); + if (vertex != null) { + vertex.addOutEdge(blockId, edataPtr, target); + } + + if (target >= windowStart) { + if (target <= windowEnd) { + ChiVertex dstVertex = vertices[target - windowStart]; + if (dstVertex != null) { + dstVertex.addInEdge(blockId, edataPtr, vid); + } + if (vertex != null && dstVertex != null) { + dstVertex.parallelSafe = false; + vertex.parallelSafe = false; + } + } + } + edataPtr += sizeOf; + + // TODO: skip + } + vid++; + } + + /* Load the edge data from file. Should be done asynchronously. */ + if (!loaded) { + int read = 0; + FileInputStream fdis = new FileInputStream(new File(edgeDataFilename)); + while (read < edataFilesize) { + read += fdis.read(dataBlockManager.getRawBlock(blockId), read, edataFilesize - read); + } + + loaded = true; + } + } + + + private void loadAdj() throws FileNotFoundException, IOException { + File adjFile = new File(adjDataFilename); + FileInputStream fis = new FileInputStream(adjFile); + + int filesize = (int) adjFile.length(); + adjData = new byte[filesize]; + + int read = 0; + while (read < filesize) { + read += fis.read(adjData, read, filesize - read); + } + + } + + public DataBlockManager getDataBlockManager() { + return dataBlockManager; + } + + public void setDataBlockManager(DataBlockManager dataBlockManager) { + this.dataBlockManager = dataBlockManager; + } + + public void setConverter(BytesToValueConverter converter) { + this.converter = converter; + } + + public int getStreamingOffset() { + return streamingOffset; + } + + public int getStreamingOffsetEdgePtr() { + return streamingOffsetEdgePtr; + } + + public int getStreamingOffsetVid() { + return streamingOffsetVid; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.RandomAccessFile` acquired by call to `RandomAccessFile(...)` at line 60 is not released after line 70. +**Note**: potential exception at line 62 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MemoryShard.commitAndRelease(boolean,boolean) + +### Procedure Id: +edu.cmu.graphchi.shards.MemoryShard.commitAndRelease(boolean,boolean):void.2d929323907b6d7f6e71be996df592b1 + +### File: +src/edu/cmu/graphchi/shards/MemoryShard.java + +### Key: +MemoryShard.java|commitAndRelease|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +b94b8cad6c296115455f572176604680 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9028/instruction.md b/inferredbugs-9028/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fd69f4651024fa54fedc9a96b1200093d9ff4cfb --- /dev/null +++ b/inferredbugs-9028/instruction.md @@ -0,0 +1,277 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** graphchi-java +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package edu.cmu.graphchi.shards; + +import edu.cmu.graphchi.ChiVertex; +import edu.cmu.graphchi.datablocks.BytesToValueConverter; +import edu.cmu.graphchi.datablocks.DataBlockManager; + +import java.io.*; + +/** + * Copyright [2012] [Aapo Kyrola, Guy Blelloch, Carlos Guestrin / Carnegie Mellon University] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class MemoryShard { + + private String edgeDataFilename; + private String adjDataFilename; + private int rangeStart; + private int rangeEnd; + + private byte[] adjData; + private int blockId; + private int edataFilesize; + private boolean loaded = false; + private boolean hasSetRangeOffset = false, hasSetOffset = false; + + private int rangeStartOffset, rangeStartEdgePtr, rangeContVid; + + private DataBlockManager dataBlockManager; + private BytesToValueConverter converter; + private int streamingOffset, streamingOffsetEdgePtr, streamingOffsetVid; + + private MemoryShard() {} + + public MemoryShard(String edgeDataFilename, String adjDataFilename, int rangeStart, int rangeEnd) { + this.edgeDataFilename = edgeDataFilename; + this.adjDataFilename = adjDataFilename; + this.rangeStart = rangeStart; + this.rangeEnd = rangeEnd; + } + + public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException { + byte[] data = dataBlockManager.getRawBlock(blockId); + + if (modifiesInedges) { + FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename)); + fos.write(data); + fos.close(); + } else if (modifiesOutedges) { + ucar.unidata.io.RandomAccessFile rFile = + new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd"); + rFile.seek(rangeStartEdgePtr); + int last = streamingOffsetEdgePtr; + if (last == 0) last = edataFilesize; + rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr); + rFile.close(); + } + dataBlockManager.release(blockId); + + } + + public void loadVertices(int windowStart, int windowEnd, ChiVertex[] vertices) + throws FileNotFoundException, IOException { + if (adjData == null) { + loadAdj(); + + edataFilesize = (int) new File(edgeDataFilename).length(); + blockId = dataBlockManager.allocateBlock(edataFilesize); + } + + + System.out.println("Load memory shard"); + int vid = 0; + int edataPtr = 0; + int adjOffset = 0; + int sizeOf = converter.sizeOf(); + DataInputStream adjInput = new DataInputStream(new ByteArrayInputStream(adjData)); + while(adjInput.available() > 0) { + if (!hasSetOffset && vid > rangeEnd) { + streamingOffset = adjOffset; + streamingOffsetEdgePtr = edataPtr; + streamingOffsetVid = vid; + hasSetOffset = true; + } + if (!hasSetRangeOffset && vid >= rangeStart) { + rangeStartOffset = adjOffset; + rangeStartEdgePtr = edataPtr; + hasSetRangeOffset = true; + } + + int n = 0; + int ns = adjInput.readUnsignedByte(); + adjOffset += 1; + assert(ns >= 0); + if (ns == 0) { + // next value tells the number of vertices with zeros + vid++; + int nz = adjInput.readUnsignedByte(); + adjOffset += 1; + vid += nz; + continue; + } + if (ns == 0xff) { // If 255 is not enough, then stores a 32-bit integer after. + n = Integer.reverseBytes(adjInput.readInt()); + adjOffset += 4; + } else { + n = ns; + } + + ChiVertex vertex = null; + if (vid >= windowStart && vid <= windowEnd) { + vertex = vertices[vid - windowStart]; + } + + while (--n >= 0) { + int target = Integer.reverseBytes(adjInput.readInt()); + adjOffset += 4; + if (!(target >= rangeStart && target <= rangeEnd)) + throw new IllegalStateException("Target " + target + " not in range!"); + if (vertex != null) { + vertex.addOutEdge(blockId, edataPtr, target); + } + + if (target >= windowStart) { + if (target <= windowEnd) { + ChiVertex dstVertex = vertices[target - windowStart]; + if (dstVertex != null) { + dstVertex.addInEdge(blockId, edataPtr, vid); + } + if (vertex != null && dstVertex != null) { + dstVertex.parallelSafe = false; + vertex.parallelSafe = false; + } + } + } + edataPtr += sizeOf; + + // TODO: skip + } + vid++; + } + + /* Load the edge data from file. Should be done asynchronously. */ + if (!loaded) { + int read = 0; + FileInputStream fdis = new FileInputStream(new File(edgeDataFilename)); + while (read < edataFilesize) { + read += fdis.read(dataBlockManager.getRawBlock(blockId), read, edataFilesize - read); + } + + loaded = true; + } + } + + + private void loadAdj() throws FileNotFoundException, IOException { + File adjFile = new File(adjDataFilename); + FileInputStream fis = new FileInputStream(adjFile); + + int filesize = (int) adjFile.length(); + adjData = new byte[filesize]; + + int read = 0; + while (read < filesize) { + read += fis.read(adjData, read, filesize - read); + } + + } + + public DataBlockManager getDataBlockManager() { + return dataBlockManager; + } + + public void setDataBlockManager(DataBlockManager dataBlockManager) { + this.dataBlockManager = dataBlockManager; + } + + public void setConverter(BytesToValueConverter converter) { + this.converter = converter; + } + + public int getStreamingOffset() { + return streamingOffset; + } + + public int getStreamingOffsetEdgePtr() { + return streamingOffsetEdgePtr; + } + + public int getStreamingOffsetVid() { + return streamingOffsetVid; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired by call to `FileInputStream(...)` at line 156 is not released after line 161. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MemoryShard.loadVertices(int,int,edu.cmu.graphchi.ChiVertex[]) + +### Procedure Id: +edu.cmu.graphchi.shards.MemoryShard.loadVertices(int,int,edu.cmu.graphchi.ChiVertex[]):void.08eca2a67801347d010929569207ca9c + +### File: +src/edu/cmu/graphchi/shards/MemoryShard.java + +### Key: +MemoryShard.java|loadVertices|RESOURCE_LEAK + +### Node Key: +e7f9be6aabb11ae72a0c3b2e5bdb8259 + +### Hash: +c097d90878ba6f679d10540f3e7d3033 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9043/instruction.md b/inferredbugs-9043/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..488db36c48cc13558a128ab935cffcdb1a44728f --- /dev/null +++ b/inferredbugs-9043/instruction.md @@ -0,0 +1,735 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jMetal +**Bug ID:** 26 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +// +// Special Session on Real-Parameter Optimization at CEC-05 +// Edinburgh, UK, 2-5 Sept. 2005 +// +// Organizers: +// Prof. Kalyanmoy Deb +// deb@iitk.ac.in +// http://www.iitk.ac.in/kangal/deb.htm +// A/Prof. P. N. Suganthan +// epnsugan@ntu.edu.sg +// http://www.ntu.edu.sg/home/EPNSugan +// +// Java version of the org.uma.test functions +// +// Matlab reference code +// http://www.ntu.edu.sg/home/EPNSugan +// +// Java version developer: +// Assistant Prof. Ying-ping Chen +// Department of Computer Science +// National Chiao Tung University +// HsinChu City, Taiwan +// ypchen@csie.nctu.edu.tw +// http://www.csie.nctu.edu.tw/~ypchen/ +// +// Typical use of the org.uma.test functions in the Benchmark: +// +// // Create a Benchmark object +// Benchmark theBenchmark = new Benchmark(); +// // Use the factory function call to create a org.uma.test function object +// // org.uma.test function 3 with 50 dimension +// // the object class is "TestFunc" +// TestFunc aTestFunc = theBenchmark.testFunctionFactory(3, 50); +// // Invoke the function with x +// double experimentoutput = aTestFunc.f(x); +// +// Version 0.90 +// Currently, this version cannot handle any numbers of dimensions. +// It cannot generate the shifted global optima and rotation matrices +// that are not provided with the Matlab reference code. +// It can handle all cases whose data files are provided with +// the Matlab reference code. +// Version 0.91 +// Revised according to the Matlab reference code and the PDF document +// dated March 8, 2005. +// + +package org.uma.jmetal.problem.singleobjective.cec2005competitioncode; + +import org.uma.jmetal.util.JMetalException; +import org.uma.jmetal.util.JMetalLogger; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.text.DecimalFormat; +import java.util.Random; +import java.util.StringTokenizer; +import java.util.logging.Level; + +public class Benchmark { + + // Fixed (class) parameters + static final public int NUM_TEST_FUNC = 25; + static final public String DEFAULT_FILE_BIAS = + JMetalLogger.cec2005SupportDataDirectory + "/fbias_data.txt"; + static final public String[] test_func_class_names = { + "F01_shifted_sphere", + "F02_shifted_schwefel", + "F03_shifted_rotated_high_cond_elliptic", + "F04_shifted_schwefel_noise", + "F05_schwefel_global_opt_bound", + "F06_shifted_rosenbrock", + "F07_shifted_rotated_griewank", + "F08_shifted_rotated_ackley_global_opt_bound", + "F09_shifted_rastrigin", + "F10_shifted_rotated_rastrigin", + "F11_shifted_rotated_weierstrass", + "F12_schwefel", + "F13_shifted_expanded_griewank_rosenbrock", + "F14_shifted_rotated_expanded_scaffer", + "F15_hybrid_composition_1", + "F16_rotated_hybrid_composition_1", + "F17_rotated_hybrid_composition_1_noise", + "F18_rotated_hybrid_composition_2", + "F19_rotated_hybrid_composition_2_narrow_basin_global_opt", + "F20_rotated_hybrid_composition_2_global_opt_bound", + "F21_rotated_hybrid_composition_3", + "F22_rotated_hybrid_composition_3_high_cond_num_matrix", + "F23_noncontinuous_rotated_hybrid_composition_3", + "F24_rotated_hybrid_composition_4", + "F25_rotated_hybrid_composition_4_bound" + }; + + // For certain functions, some essential data can be calculated beforehand. + // Hence, a maximum supported number of dimensions should be specified. + // Specifiy the number of dimensions here if you need more. + static final public int MAX_SUPPORT_DIM = 100; + static final public double PIx2 = Math.PI * 2.0; + + // Formatter for the number representation + static final public DecimalFormat scientificFormatter = + new DecimalFormat("0.0000000000000000E00"); + static final public DecimalFormat numberFormatter = scientificFormatter; + static final public DecimalFormat percentageFormatter = new DecimalFormat("0.0000000000"); + + // Random number generator + // If you want to plan a specific seed, do it here. + static final public Random random = new Random(); + + // Class loader & reflection + static final public ClassLoader loader = ClassLoader.getSystemClassLoader(); + static final Class[] test_func_arg_types = {int.class, double.class}; + + // Class variables + static private double[] m_iSqrt; + + // Instance variables + private double[] m_biases; + + // Constructors + // Load the data common to all org.uma.test functions. + // Get ready for creating org.uma.test function instances. + public Benchmark() throws JMetalException { + this(DEFAULT_FILE_BIAS); + } + + public Benchmark(String file_bias) throws JMetalException { + m_biases = new double[NUM_TEST_FUNC]; + m_iSqrt = new double[MAX_SUPPORT_DIM]; + + loadRowVectorFromFile(file_bias, NUM_TEST_FUNC, m_biases); + + for (int i = 0; i < MAX_SUPPORT_DIM; i++) { + m_iSqrt[i] = Math.sqrt(((double) i) + 1.0); + } + } + + // Entry point + // If the Benchmark class is executed as a stand-alone application, + // its job is to run the org.uma.test on all the org.uma.test functions. + static public void main(String args[]) throws JMetalException { + Benchmark theBenchmark = new Benchmark(); + theBenchmark.runTest(0); + } + + // Sphere function + static public double sphere(double[] x) { + + double sum = 0.0; + + for (int i = 0; i < x.length; i++) { + sum += x[i] * x[i]; + } + + return (sum); + } + + // Sphere function with noise + static public double sphere_noise(double[] x) { + + double sum = 0.0; + + for (int i = 0; i < x.length; i++) { + sum += x[i] * x[i]; + } + + // NOISE + // Comment the next line to remove the noise + sum *= (1.0 + 0.1 * Math.abs(random.nextGaussian())); + + return (sum); + } + + // Schwefel's problem 1.2 + static public double schwefel_102(double[] x) { + + double prev_sum, curr_sum, outer_sum; + + curr_sum = x[0]; + outer_sum = (curr_sum * curr_sum); + + for (int i = 1; i < x.length; i++) { + prev_sum = curr_sum; + curr_sum = prev_sum + x[i]; + outer_sum += (curr_sum * curr_sum); + } + + return (outer_sum); + } + + // + // Basic functions + // + + // Rosenbrock's function + static public double rosenbrock(double[] x) { + + double sum = 0.0; + + for (int i = 0; i < (x.length - 1); i++) { + double temp1 = (x[i] * x[i]) - x[i + 1]; + double temp2 = x[i] - 1.0; + sum += (100.0 * temp1 * temp1) + (temp2 * temp2); + } + + return (sum); + } + + // F2: Rosenbrock's Function -- 2D version + static public double F2(double x, double y) { + double temp1 = (x * x) - y; + double temp2 = x - 1.0; + return ((100.0 * temp1 * temp1) + (temp2 * temp2)); + } + + // Griewank's function + static public double griewank(double[] x) { + + double sum = 0.0; + double product = 1.0; + + for (int i = 0; i < x.length; i++) { + sum += ((x[i] * x[i]) / 4000.0); + product *= Math.cos(x[i] / m_iSqrt[i]); + } + + return (sum - product + 1.0); + } + + // F8: Griewank's Function -- 1D version + static public double F8(double x) { + return (((x * x) / 4000.0) - Math.cos(x) + 1.0); + } + + // Ackley's function + static public double ackley(double[] x) { + + double sum1 = 0.0; + double sum2 = 0.0; + + for (int i = 0; i < x.length; i++) { + sum1 += (x[i] * x[i]); + sum2 += (Math.cos(PIx2 * x[i])); + } + + return (-20.0 * Math.exp(-0.2 * Math.sqrt(sum1 / ((double) x.length))) - Math + .exp(sum2 / ((double) x.length)) + 20.0 + Math.E); + } + + // Round function + // 0. Use the Matlab version for rounding numbers + static public double myRound(double x) { + return (Math.signum(x) * Math.round(Math.abs(x))); + } + + // 1. "o" is provided + static public double myXRound(double x, double o) { + return ((Math.abs(x - o) < 0.5) ? x : (myRound(2.0 * x) / 2.0)); + } + + // 2. "o" is not provided + static public double myXRound(double x) { + return ((Math.abs(x) < 0.5) ? x : (myRound(2.0 * x) / 2.0)); + } + + // Rastrigin's function + static public double rastrigin(double[] x) { + + double sum = 0.0; + + for (int i = 0; i < x.length; i++) { + sum += (x[i] * x[i]) - (10.0 * Math.cos(PIx2 * x[i])) + 10.0; + } + + return (sum); + } + + // Non-Continuous Rastrigin's function + static public double rastriginNonCont(double[] x) { + + double sum = 0.0; + double currX; + + for (int i = 0; i < x.length; i++) { + currX = myXRound(x[i]); + sum += (currX * currX) - (10.0 * Math.cos(PIx2 * currX)) + 10.0; + } + + return (sum); + } + + // Weierstrass function + static public double weierstrass(double[] x) { + return (weierstrass(x, 0.5, 3.0, 20)); + } + + static public double weierstrass(double[] x, double a, double b, int Kmax) { + + double sum1 = 0.0; + for (int i = 0; i < x.length; i++) { + for (int k = 0; k <= Kmax; k++) { + sum1 += Math.pow(a, k) * Math.cos(PIx2 * Math.pow(b, k) * (x[i] + 0.5)); + } + } + + double sum2 = 0.0; + for (int k = 0; k <= Kmax; k++) { + sum2 += Math.pow(a, k) * Math.cos(PIx2 * Math.pow(b, k) * (0.5)); + } + + return (sum1 - sum2 * ((double) (x.length))); + } + + // F8F2 + static public double F8F2(double[] x) { + + double sum = 0.0; + + for (int i = 1; i < x.length; i++) { + sum += F8(F2(x[i - 1], x[i])); + } + sum += F8(F2(x[x.length - 1], x[0])); + + return (sum); + } + + // Scaffer's F6 function + static public double ScafferF6(double x, double y) { + double temp1 = x * x + y * y; + double temp2 = Math.sin(Math.sqrt(temp1)); + double temp3 = 1.0 + 0.001 * temp1; + return (0.5 + ((temp2 * temp2 - 0.5) / (temp3 * temp3))); + } + + // Expanded Scaffer's F6 function + static public double EScafferF6(double[] x) { + + double sum = 0.0; + + for (int i = 1; i < x.length; i++) { + sum += ScafferF6(x[i - 1], x[i]); + } + sum += ScafferF6(x[x.length - 1], x[0]); + + return (sum); + } + + // Non-Continuous Expanded Scaffer's F6 function + static public double EScafferF6NonCont(double[] x) { + + double sum = 0.0; + double prevX, currX; + + currX = myXRound(x[0]); + for (int i = 1; i < x.length; i++) { + prevX = currX; + currX = myXRound(x[i]); + sum += ScafferF6(prevX, currX); + } + prevX = currX; + currX = myXRound(x[0]); + sum += ScafferF6(prevX, currX); + + return (sum); + } + + // Elliptic + static public double elliptic(double[] x) { + + double sum = 0.0; + double a = 1e6; + + for (int i = 0; i < x.length; i++) { + sum += Math.pow(a, (((double) i) / ((double) (x.length - 1)))) * x[i] * x[i]; + } + + return (sum); + } + + // Hybrid composition + static public double hybrid_composition(double[] x, HCJob job) throws JMetalException { + + int num_func = job.num_func; + int num_dim = job.num_dim; + + // Get the raw weights + double wMax = Double.NEGATIVE_INFINITY; + for (int i = 0; i < num_func; i++) { + double sumSqr = 0.0; + shift(job.z[i], x, job.o[i]); + for (int j = 0; j < num_dim; j++) { + sumSqr += (job.z[i][j] * job.z[i][j]); + } + job.w[i] = Math.exp(-1.0 * sumSqr / (2.0 * num_dim * job.sigma[i] * job.sigma[i])); + if (wMax < job.w[i]) { + wMax = job.w[i]; + } + } + + // Modify the weights + double wSum = 0.0; + double w1mMaxPow = 1.0 - Math.pow(wMax, 10.0); + for (int i = 0; i < num_func; i++) { + if (job.w[i] != wMax) { + job.w[i] *= w1mMaxPow; + } + wSum += job.w[i]; + } + + // Normalize the weights + for (int i = 0; i < num_func; i++) { + job.w[i] /= wSum; + } + + double sumF = 0.0; + for (int i = 0; i < num_func; i++) { + for (int j = 0; j < num_dim; j++) { + job.z[i][j] /= job.lambda[i]; + } + rotate(job.zM[i], job.z[i], job.M[i]); + sumF += + job.w[i] * + ( + job.C * job.basic_func(i, job.zM[i]) / job.fmax[i] + + job.biases[i] + ); + } + return (sumF); + } + + // Shift + static public void shift(double[] results, double[] x, double[] o) { + for (int i = 0; i < x.length; i++) { + results[i] = x[i] - o[i]; + } + } + + // Rotate + static public void rotate(double[] results, double[] x, double[][] matrix) { + xA(results, x, matrix); + } + + // (1xD) row vector * (Dx1) column vector = (1) scalar + static public double xy(double[] x, double[] y) { + double result = 0.0; + for (int i = 0; i < x.length; i++) { + result += (x[i] * y[i]); + } + + return (result); + } + + // + // Elementary operations + // + + // (1xD) row vector * (DxD) matrix = (1xD) row vector + static public void xA(double[] result, double[] x, double[][] A) { + for (int i = 0; i < result.length; i++) { + result[i] = 0.0; + for (int j = 0; j < result.length; j++) { + result[i] += (x[j] * A[j][i]); + } + } + } + + // (DxD) matrix * (Dx1) column vector = (Dx1) column vector + static public void Ax(double[] result, double[][] A, double[] x) { + for (int i = 0; i < result.length; i++) { + result[i] = 0.0; + for (int j = 0; j < result.length; j++) { + result[i] += (A[i][j] * x[j]); + } + } + } + + // + // Matrix & vector operations + // + + // + // Utility functions for loading data from the given text file + // + static public void loadTestDataFromFile(String file, int num_test_points, int test_dimension, + double[][] x, double[] f) throws JMetalException { + try { + JMetalLogger.logger.info("File bias: " + file); + + BufferedReader brSrc = new BufferedReader(new FileReader(file)); + loadMatrix(brSrc, num_test_points, test_dimension, x); + loadColumnVector(brSrc, num_test_points, f); + brSrc.close(); + } catch (Exception e) { + JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); + throw new JMetalException("Error in Benchmark.java"); + } + } + + static public void loadRowVectorFromFile(String file, int columns, double[] row) + throws JMetalException { + try { + BufferedReader brSrc = new BufferedReader(new FileReader(file)); + loadRowVector(brSrc, columns, row); + brSrc.close(); + } catch (Exception e) { + JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); + throw new JMetalException("Error in Benchmark.java"); + } + } + + static public void loadRowVector(BufferedReader brSrc, int columns, double[] row) + throws Exception { + String stToken; + StringTokenizer stTokenizer = new StringTokenizer(brSrc.readLine()); + for (int i = 0; i < columns; i++) { + stToken = stTokenizer.nextToken(); + row[i] = Double.parseDouble(stToken); + } + } + + static public void loadColumnVectorFromFile(String file, int rows, double[] column) + throws JMetalException { + try { + BufferedReader brSrc = new BufferedReader(new FileReader(file)); + loadColumnVector(brSrc, rows, column); + brSrc.close(); + } catch (Exception e) { + JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); + throw new JMetalException("Error in Benchmark.java"); + } + } + + static public void loadColumnVector(BufferedReader brSrc, int rows, double[] column) + throws Exception { + String stToken; + for (int i = 0; i < rows; i++) { + StringTokenizer stTokenizer = new StringTokenizer(brSrc.readLine()); + stToken = stTokenizer.nextToken(); + column[i] = Double.parseDouble(stToken); + } + } + + static public void loadNMatrixFromFile(String file, int N, int rows, int columns, + double[][][] matrix) throws JMetalException { + try { + BufferedReader brSrc = new BufferedReader(new FileReader(file)); + for (int i = 0; i < N; i++) { + loadMatrix(brSrc, rows, columns, matrix[i]); + } + brSrc.close(); + } catch (Exception e) { + JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); + throw new JMetalException("Error in Benchmark.java"); + } + } + + static public void loadMatrixFromFile(String file, int rows, int columns, double[][] matrix) + throws JMetalException { + try { + BufferedReader brSrc = new BufferedReader(new FileReader(file)); + loadMatrix(brSrc, rows, columns, matrix); + brSrc.close(); + } catch (Exception e) { + JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); + throw new JMetalException("Error in Benchmark.java"); + } + } + + static public void loadMatrix(BufferedReader brSrc, int rows, int columns, double[][] matrix) + throws Exception { + for (int i = 0; i < rows; i++) { + loadRowVector(brSrc, columns, matrix[i]); + } + } + + // + // Use this function to manufacture new org.uma.test function objects + // + public TestFunc testFunctionFactory(int func_num, int dimension) throws JMetalException { + TestFunc returnFunc = null; + try { + returnFunc = (TestFunc) + loader.loadClass(JMetalLogger.cec2005Package + "." + test_func_class_names[func_num - 1]) + .getConstructor(test_func_arg_types) + .newInstance( + new Object[] { + new Integer(dimension), + new Double(m_biases[func_num - 1]) + } + ); + } catch (Exception e) { + JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); + throw new JMetalException("Error in Benchmark.java"); + } + return (returnFunc); + } + + // Run tests on the org.uma.test functions + // < 0: Error! + // = 0: On all the functions + // > 0: On the specified org.uma.test function + public void runTest() throws JMetalException { + runTest(0); + } + + public void runTest(int func_num) throws JMetalException { + if (func_num == 0) { + for (int i = 1; i <= NUM_TEST_FUNC; i++) { + runTest(i); + } + } else if ((func_num < 0) || (func_num > NUM_TEST_FUNC)) { + throw new JMetalException("The specified func_num is out of range."); + } else { + // Run the org.uma.test function against the check points + int num_test_points = 10; + int test_dimension = 50; + + double[] test_f = new double[num_test_points]; + double[][] test_x = new double[num_test_points][test_dimension]; + + String file_test = "testData/test_data_func" + func_num + ".txt"; + + // Create the org.uma.test function object + TestFunc aFunc = testFunctionFactory(func_num, test_dimension); + + JMetalLogger.logger.info("Run tests on function " + func_num + + " (" + aFunc.name() + "):"); + JMetalLogger.logger.info(" " + + num_test_points + " " + + aFunc.dimension() + "-dimension check points"); + + loadTestDataFromFile(file_test, num_test_points, test_dimension, test_x, test_f); + + for (int i = 0; i < num_test_points; i++) { + // Execute the org.uma.test function + // Collect and compare the results + double result = aFunc.f(test_x[i]); + double diff = result - test_f[i]; + double ratio = Math.abs(diff / test_f[i]); + JMetalLogger.logger.info(" " + + numberFormatter.format(result) + + " - " + + numberFormatter.format(test_f[i]) + + " = " + + numberFormatter.format(diff)); + JMetalLogger.logger.info(" " + " " + + "Difference ratio = " + numberFormatter.format(ratio)); + if (ratio != 0.0) { + if (ratio <= 1e-12) { + JMetalLogger.logger.info(" (<= 1E-12)"); + } else { + JMetalLogger.logger.info(" (> 1E-12) *****"); + } + } else { + JMetalLogger.logger.info(""); + } + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileReader` acquired by call to `new()` at line 546 is not released after line 551. +**Note**: potential exception at line 548 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Benchmark.loadNMatrixFromFile(String,int,int,int,double[][][]) + +### Procedure Id: +org.uma.jmetal.problem.singleobjective.cec2005competitioncode.Benchmark.loadNMatrixFromFile(java.lan.9663dfdb841e44a6eb87a5a5fdb43830 + +### File: +jmetal-core/src/main/java/org/uma/jmetal/problem/singleobjective/cec2005competitioncode/Benchmark.java + +### Key: +Benchmark.java|loadNMatrixFromFile|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +757f0fbe692229c22f3dac53e29eafcf + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9044/instruction.md b/inferredbugs-9044/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4365fba83db1eac7981813f921ff8c3c9b025ed5 --- /dev/null +++ b/inferredbugs-9044/instruction.md @@ -0,0 +1,234 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jMetal +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +// NSGAIIRunner.java +// +// Author: +// Antonio J. Nebro +// +// Copyright (c) 2014 Antonio J. Nebro +// +// This program 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. +// +// 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see . + +package jmetal.metaheuristics.nsgaII.runner; + +import jmetal.core.Algorithm; +import jmetal.core.Operator; +import jmetal.core.Problem; +import jmetal.core.SolutionSet; +import jmetal.metaheuristics.nsgaII.NSGAII; +import jmetal.operators.crossover.SBXCrossover; +import jmetal.operators.mutation.PolynomialMutation; +import jmetal.operators.selection.BinaryTournament2; +import jmetal.problems.Kursawe; +import jmetal.problems.ProblemFactory; +import jmetal.qualityIndicator.QualityIndicator; +import jmetal.util.Configuration; +import jmetal.util.JMException; +import jmetal.util.evaluator.MultithreadedSolutionSetEvaluator; +import jmetal.util.evaluator.SolutionSetEvaluator; +import jmetal.util.fileOutput.DefaultFileOutputContext; +import jmetal.util.fileOutput.FileOutputContext; +import jmetal.util.fileOutput.SolutionSetOutput; + +import java.io.IOException; +import java.util.logging.FileHandler; +import java.util.logging.Logger; + +/** + * Class to configure and execute the NSGA-II algorithm. + *

    + * Besides the classic NSGA-II, a steady-state version (ssNSGAII) is also + * included (See: J.J. Durillo, A.J. Nebro, F. Luna and E. Alba + * "On the Effect of the Steady-State Selection Scheme in + * Multi-Objective Genetic Algorithms" + * 5th International Conference, EMO 2009, pp: 183-197. + * April 2009) + */ + +public class ParallelNSGAIIRunner { + private static Logger logger_; + private static FileHandler fileHandler_; + + /** + * @param args Command line arguments. + * @throws jmetal.util.JMException + * @throws java.io.IOException + * @throws SecurityException Usage: three options + * - jmetal.metaheuristics.nsgaII.NSGAII_main + * - jmetal.metaheuristics.nsgaII.NSGAII_main problemName + * - jmetal.metaheuristics.nsgaII.NSGAII_main problemName paretoFrontFile + */ + public static void main(String[] args) throws + JMException, + SecurityException, + IOException, + ClassNotFoundException { + + Problem problem; + Algorithm algorithm; + Operator crossover; + Operator mutation; + Operator selection; + + QualityIndicator indicators; + + // Logger object and file to store log messages + logger_ = Configuration.logger_; + fileHandler_ = new FileHandler("NSGAII_main.log"); + logger_.addHandler(fileHandler_); + + indicators = null; + if (args.length == 1) { + Object[] params = {"Real"}; + problem = (new ProblemFactory()).getProblem(args[0], params); + } else if (args.length == 2) { + Object[] params = {"Real"}; + problem = (new ProblemFactory()).getProblem(args[0], params); + indicators = new QualityIndicator(problem, args[1]); + } else { + problem = new Kursawe("Real", 3); + /* + Examples: + problem = new Kursawe("BinaryReal", 3); + problem = new Water("Real"); + problem = new ZDT3("ArrayReal", 30); + problem = new ConstrEx("Real"); + problem = new DTLZ1("Real"); + problem = new OKA2("Real") + */ + } + + SolutionSetEvaluator evaluator = new MultithreadedSolutionSetEvaluator(4, problem) ; + crossover = new SBXCrossover.Builder() + .distributionIndex(20.0) + .probability(0.9) + .build() ; + + mutation = new PolynomialMutation.Builder() + .distributionIndex(20.0) + .probability(1.0/problem.getNumberOfVariables()) + .build(); + + selection = new BinaryTournament2.Builder() + .build(); + + algorithm = new NSGAII.Builder(problem, evaluator) + .crossover(crossover) + .mutation(mutation) + .selection(selection) + .maxEvaluations(25000) + .populationSize(100) + .build() ; + + // Execute the Algorithm + long initTime = System.currentTimeMillis(); + SolutionSet population = algorithm.execute(); + long estimatedTime = System.currentTimeMillis() - initTime; + logger_.info("Total execution time: " + estimatedTime + "ms"); + + // Result messages + FileOutputContext fileContext = new DefaultFileOutputContext("VAR.tsv") ; + fileContext.setSeparator("\t"); + + logger_.info("Variables values have been writen to file VAR.tsv"); + SolutionSetOutput.printVariablesToFile(fileContext, population) ; + + fileContext = new DefaultFileOutputContext("FUN.tsv"); + fileContext.setSeparator("\t"); + + SolutionSetOutput.printObjectivesToFile(fileContext, population); + logger_.info("Objectives values have been written to file FUN"); + + if (indicators != null) { + logger_.info("Quality indicators"); + logger_.info("Hypervolume: " + indicators.getHypervolume(population)); + logger_.info("GD : " + indicators.getGD(population)); + logger_.info("IGD : " + indicators.getIGD(population)); + logger_.info("Spread : " + indicators.getSpread(population)); + logger_.info("Epsilon : " + indicators.getEpsilon(population)); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `algorithm` last assigned on line 130 could be null and is dereferenced at line 134. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ParallelNSGAIIRunner.main(java.lang.String[]) + +### Procedure Id: +jmetal.metaheuristics.nsgaII.runner.ParallelNSGAIIRunner.main(java.lang.String[]):void.d59a511d69e36bce2ad75adb6824d800 + +### File: +src/main/java/jmetal/metaheuristics/nsgaII/runner/ParallelNSGAIIRunner.java + +### Key: +ParallelNSGAIIRunner.java|main|NULL_DEREFERENCE + +### Node Key: +c58cafd227048c844596bed077180490 + +### Hash: +8ec87d4ddafeb1f550e04a2a64f5f7d1 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9072/instruction.md b/inferredbugs-9072/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f59b71689c41e2b9ca61edf80aea2a9aa9b6f17a --- /dev/null +++ b/inferredbugs-9072/instruction.md @@ -0,0 +1,494 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-binary-block-parser +**Bug ID:** 32 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.igormaznitsa.jbbp.io; + +import static com.igormaznitsa.jbbp.io.JBBPOut.*; +import java.io.*; +import static org.junit.Assert.*; +import org.junit.Test; + +public class JBBPOutTest { + + @Test + public void testBinStart() throws Exception { + assertArrayEquals(new byte[]{1},binStart().Byte(1).end().toByteArray()); + assertArrayEquals(new byte[]{0x02,0x01},binStart(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{0x40,(byte)0x80},binStart(JBBPByteOrder.LITTLE_ENDIAN,JBBPBitOrder.MSB0).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{(byte)0x80},binStart(JBBPBitOrder.MSB0).Byte(1).end().toByteArray()); + + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + assertSame(buffer, binStart(buffer).end()); + } + + @Test + public void testAlign() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).end().toByteArray()); + } + + @Test + public void testAlignWithArgument() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).Align(2).end().toByteArray().length); + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Align(3).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(2).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Int(0x01020304).Align(5).Byte(0xF1).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(5).Byte(0xF1).end().toByteArray()); + } + + @Test + public void testEmptyArray() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).end().toByteArray().length); + } + + @Test + public void testByte() throws Exception { + assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).end().toByteArray()); + } + + @Test + public void testByteArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + } + + @Test + public void testByteArrayAsByteArray() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}).end().toByteArray()); + } + + @Test + public void testBit() throws Exception { + assertArrayEquals(new byte[]{1}, binStart().Bit(1).end().toByteArray()); + } + + @Test + public void testBit_MSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x80}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.MSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBit_LSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.LSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBits_Int() throws Exception { + assertArrayEquals(new byte[]{0xD}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD).end().toByteArray()); + } + + @Test + public void testBits_IntArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD, 0xFE).end().toByteArray()); + } + + @Test + public void testBits_ByteArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).end().toByteArray()); + } + + @Test + public void testBitArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray()); + } + + @Test + public void testBitArrayAsBytes() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray()); + } + + @Test + public void testBitArrayAsBooleans() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray()); + } + + @Test + public void testShort() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_LittleEndian() throws Exception { + assertArrayEquals(new byte []{0x02,01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_BigEndian() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_LittleEndian() throws Exception { + assertArrayEquals(new byte []{2,1,4,3}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShorts() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short((short)0x0102, (short)0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShortArray() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short(new short[]{(short)0x0102, (short)0x0304}).end().toByteArray()); + } + + @Test + public void testInt() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04}, binStart().Int(0x01020304).end().toByteArray()); + } + + @Test + public void testIntArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Int(0x01020304, 0x05060708).end().toByteArray()); + } + + @Test + public void testInt_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testInt_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testLong() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLongArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, binStart().Long(0x0102030405060708L,0x1112131415161718L).end().toByteArray()); + } + + @Test + public void testLong_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLong_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testFlush() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPOut out = binStart(buffer); + + out.Bit(true); + assertEquals(0, buffer.size()); + out.Flush(); + assertEquals(1, buffer.size()); + } + + @Test + public void testExceptionForOperatioOverEndedProcess() throws Exception { + final JBBPOut out = binStart(); + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end(); + try{ + out.Align(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Align(3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34,(byte)12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(34,12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte((byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Flush(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1,2); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L,2L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short((short)1,(short)2,(short)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.end(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + } + + @Test + public void testExternalStreamButNoByteArrayOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final DataOutputStream dout = new DataOutputStream(buffer); + + assertNull(binStart(dout).Byte(1,2,3).end()); + assertArrayEquals(new byte[]{1,2,3}, buffer.toByteArray()); + } + + @Test(expected = IllegalArgumentException.class) + public void testExceptionForBitOrderConfilctInCaseOfUsageBitOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPBitOutputStream bitstream = new JBBPBitOutputStream(buffer,JBBPBitOrder.LSB0); + + new JBBPOut(bitstream,JBBPByteOrder.BIG_ENDIAN,JBBPBitOrder.MSB0); + } + + @Test + public void testComplexWriting_1() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384); + + final JBBPOut begin = new JBBPOut(buffer); + + begin. + Bit(1, 2, 3, 0). + Bit(true, false, true). + Align(). + Byte(5). + Short(1, 2, 3, 4, 5). + Bool(true, false, true, true). + Int(0xABCDEF23, 0xCAFEBABE). + Long(0x123456789ABCDEF1L, 0x212356239091AB32L). + end(); + + final byte[] array = buffer.toByteArray(); + + assertEquals(40, array.length); + assertArrayEquals(new byte[]{ + (byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1, + (byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, + 0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32 + + }, array); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.igormaznitsa.jbbp.io.JBBPBitOutputStream` acquired by call to `binStart(...)` at line 211 is not released after line 215. +**Note**: potential exception at line 215 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JBBPOutTest.testFlush() + +### Procedure Id: +com.igormaznitsa.jbbp.io.JBBPOutTest.testFlush():void.1138c460030b0f6775397c32ec6108d2 + +### File: +src/test/java/com/igormaznitsa/jbbp/io/JBBPOutTest.java + +### Key: +JBBPOutTest.java|testFlush|RESOURCE_LEAK + +### Node Key: +dd4a74aeaaf0a6c2a3a8877464bb9a91 + +### Hash: +9c4fc80a1cb127020e87bce055c24053 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9075/instruction.md b/inferredbugs-9075/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a995bfa59ca35f415fa062ca22a54a94c0e875c4 --- /dev/null +++ b/inferredbugs-9075/instruction.md @@ -0,0 +1,493 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-binary-block-parser +**Bug ID:** 34 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.igormaznitsa.jbbp.io; + +import static com.igormaznitsa.jbbp.io.JBBPOut.*; +import java.io.*; +import static org.junit.Assert.*; +import org.junit.Test; + +public class JBBPOutTest { + + @Test + public void testBinStart() throws Exception { + assertArrayEquals(new byte[]{1},binStart().Byte(1).end().toByteArray()); + assertArrayEquals(new byte[]{0x02,0x01},binStart(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{0x40,(byte)0x80},binStart(JBBPByteOrder.LITTLE_ENDIAN,JBBPBitOrder.MSB0).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{(byte)0x80},binStart(JBBPBitOrder.MSB0).Byte(1).end().toByteArray()); + + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + assertSame(buffer, binStart(buffer).end()); + } + + @Test + public void testAlign() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).end().toByteArray()); + } + + @Test + public void testAlignWithArgument() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).Align(2).end().toByteArray().length); + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Align(3).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(2).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Int(0x01020304).Align(5).Byte(0xF1).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(5).Byte(0xF1).end().toByteArray()); + } + + @Test + public void testEmptyArray() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).end().toByteArray().length); + } + + @Test + public void testByte() throws Exception { + assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).end().toByteArray()); + } + + @Test + public void testByteArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + } + + @Test + public void testByteArrayAsByteArray() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}).end().toByteArray()); + } + + @Test + public void testBit() throws Exception { + assertArrayEquals(new byte[]{1}, binStart().Bit(1).end().toByteArray()); + } + + @Test + public void testBit_MSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x80}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.MSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBit_LSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.LSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBits_Int() throws Exception { + assertArrayEquals(new byte[]{0xD}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD).end().toByteArray()); + } + + @Test + public void testBits_IntArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD, 0xFE).end().toByteArray()); + } + + @Test + public void testBits_ByteArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).end().toByteArray()); + } + + @Test + public void testBitArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray()); + } + + @Test + public void testBitArrayAsBytes() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray()); + } + + @Test + public void testBitArrayAsBooleans() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray()); + } + + @Test + public void testShort() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_LittleEndian() throws Exception { + assertArrayEquals(new byte []{0x02,01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_BigEndian() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_LittleEndian() throws Exception { + assertArrayEquals(new byte []{2,1,4,3}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShorts() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short((short)0x0102, (short)0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShortArray() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short(new short[]{(short)0x0102, (short)0x0304}).end().toByteArray()); + } + + @Test + public void testInt() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04}, binStart().Int(0x01020304).end().toByteArray()); + } + + @Test + public void testIntArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Int(0x01020304, 0x05060708).end().toByteArray()); + } + + @Test + public void testInt_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testInt_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testLong() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLongArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, binStart().Long(0x0102030405060708L,0x1112131415161718L).end().toByteArray()); + } + + @Test + public void testLong_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLong_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testFlush() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPOut out = binStart(buffer); + + out.Bit(true); + assertEquals(0, buffer.size()); + out.Flush(); + assertEquals(1, buffer.size()); + } + + @Test + public void testExceptionForOperatioOverEndedProcess() throws Exception { + final JBBPOut out = binStart(); + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end(); + try{ + out.Align(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Align(3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34,(byte)12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(34,12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte((byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Flush(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1,2); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L,2L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short((short)1,(short)2,(short)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.end(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + } + + @Test + public void testExternalStreamButNoByteArrayOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final DataOutputStream dout = new DataOutputStream(buffer); + + assertNull(binStart(dout).Byte(1,2,3).end()); + assertArrayEquals(new byte[]{1,2,3}, buffer.toByteArray()); + } + + @Test(expected = IllegalArgumentException.class) + public void testExceptionForBitOrderConfilctInCaseOfUsageBitOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPBitOutputStream bitstream = new JBBPBitOutputStream(buffer,JBBPBitOrder.LSB0); + + new JBBPOut(bitstream,JBBPByteOrder.BIG_ENDIAN,JBBPBitOrder.MSB0); + } + + @Test + public void testComplexWriting_1() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384); + + final JBBPOut begin = new JBBPOut(buffer); + + begin. + Bit(1, 2, 3, 0). + Bit(true, false, true). + Align(). + Byte(5). + Short(1, 2, 3, 4, 5). + Bool(true, false, true, true). + Int(0xABCDEF23, 0xCAFEBABE). + Long(0x123456789ABCDEF1L, 0x212356239091AB32L). + end(); + + final byte[] array = buffer.toByteArray(); + + assertEquals(40, array.length); + assertArrayEquals(new byte[]{ + (byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1, + (byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, + 0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32 + + }, array); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.igormaznitsa.jbbp.io.JBBPBitOutputStream` acquired by call to `binStart(...)` at line 379 is not released after line 379. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JBBPOutTest.testExternalStreamButNoByteArrayOutputStream() + +### Procedure Id: +com.igormaznitsa.jbbp.io.JBBPOutTest.testExternalStreamButNoByteArrayOutputStream():void.f83c8887767ce273c5d52c0ee4262d0c + +### File: +src/test/java/com/igormaznitsa/jbbp/io/JBBPOutTest.java + +### Key: +JBBPOutTest.java|testExternalStreamButNoByteArrayOutputStream|RESOURCE_LEAK + +### Node Key: +4993c9594a0fc46e69f9bfd2837c960e + +### Hash: +6871ab89c8ce6dbdd2ec104fc889fa43 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9081/instruction.md b/inferredbugs-9081/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c6e0959b7323bea948c7c7075bfdb0b6759bc96 --- /dev/null +++ b/inferredbugs-9081/instruction.md @@ -0,0 +1,493 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-binary-block-parser +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.igormaznitsa.jbbp.io; + +import static com.igormaznitsa.jbbp.io.JBBPOut.*; +import java.io.*; +import static org.junit.Assert.*; +import org.junit.Test; + +public class JBBPOutTest { + + @Test + public void testBinStart() throws Exception { + assertArrayEquals(new byte[]{1},binStart().Byte(1).end().toByteArray()); + assertArrayEquals(new byte[]{0x02,0x01},binStart(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{0x40,(byte)0x80},binStart(JBBPByteOrder.LITTLE_ENDIAN,JBBPBitOrder.MSB0).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{(byte)0x80},binStart(JBBPBitOrder.MSB0).Byte(1).end().toByteArray()); + + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + assertSame(buffer, binStart(buffer).end()); + } + + @Test + public void testAlign() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).end().toByteArray()); + } + + @Test + public void testAlignWithArgument() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).Align(2).end().toByteArray().length); + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Align(3).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(2).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Int(0x01020304).Align(5).Byte(0xF1).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(5).Byte(0xF1).end().toByteArray()); + } + + @Test + public void testEmptyArray() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).end().toByteArray().length); + } + + @Test + public void testByte() throws Exception { + assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).end().toByteArray()); + } + + @Test + public void testByteArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + } + + @Test + public void testByteArrayAsByteArray() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}).end().toByteArray()); + } + + @Test + public void testBit() throws Exception { + assertArrayEquals(new byte[]{1}, binStart().Bit(1).end().toByteArray()); + } + + @Test + public void testBit_MSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x80}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.MSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBit_LSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.LSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBits_Int() throws Exception { + assertArrayEquals(new byte[]{0xD}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD).end().toByteArray()); + } + + @Test + public void testBits_IntArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD, 0xFE).end().toByteArray()); + } + + @Test + public void testBits_ByteArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).end().toByteArray()); + } + + @Test + public void testBitArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray()); + } + + @Test + public void testBitArrayAsBytes() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray()); + } + + @Test + public void testBitArrayAsBooleans() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray()); + } + + @Test + public void testShort() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_LittleEndian() throws Exception { + assertArrayEquals(new byte []{0x02,01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_BigEndian() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_LittleEndian() throws Exception { + assertArrayEquals(new byte []{2,1,4,3}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShorts() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short((short)0x0102, (short)0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShortArray() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short(new short[]{(short)0x0102, (short)0x0304}).end().toByteArray()); + } + + @Test + public void testInt() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04}, binStart().Int(0x01020304).end().toByteArray()); + } + + @Test + public void testIntArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Int(0x01020304, 0x05060708).end().toByteArray()); + } + + @Test + public void testInt_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testInt_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testLong() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLongArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, binStart().Long(0x0102030405060708L,0x1112131415161718L).end().toByteArray()); + } + + @Test + public void testLong_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLong_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testFlush() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPOut out = binStart(buffer); + + out.Bit(true); + assertEquals(0, buffer.size()); + out.Flush(); + assertEquals(1, buffer.size()); + } + + @Test + public void testExceptionForOperatioOverEndedProcess() throws Exception { + final JBBPOut out = binStart(); + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end(); + try{ + out.Align(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Align(3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34,(byte)12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(34,12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte((byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Flush(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1,2); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L,2L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short((short)1,(short)2,(short)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.end(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + } + + @Test + public void testExternalStreamButNoByteArrayOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final DataOutputStream dout = new DataOutputStream(buffer); + + assertNull(binStart(dout).Byte(1,2,3).end()); + assertArrayEquals(new byte[]{1,2,3}, buffer.toByteArray()); + } + + @Test(expected = IllegalArgumentException.class) + public void testExceptionForBitOrderConfilctInCaseOfUsageBitOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPBitOutputStream bitstream = new JBBPBitOutputStream(buffer,JBBPBitOrder.LSB0); + + new JBBPOut(bitstream,JBBPByteOrder.BIG_ENDIAN,JBBPBitOrder.MSB0); + } + + @Test + public void testComplexWriting_1() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384); + + final JBBPOut begin = new JBBPOut(buffer); + + begin. + Bit(1, 2, 3, 0). + Bit(true, false, true). + Align(). + Byte(5). + Short(1, 2, 3, 4, 5). + Bool(true, false, true, true). + Int(0xABCDEF23, 0xCAFEBABE). + Long(0x123456789ABCDEF1L, 0x212356239091AB32L). + end(); + + final byte[] array = buffer.toByteArray(); + + assertEquals(40, array.length); + assertArrayEquals(new byte[]{ + (byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1, + (byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, + 0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32 + + }, array); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.igormaznitsa.jbbp.io.JBBPBitOutputStream` acquired by call to `binStart()` at line 113 is not released after line 113. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JBBPOutTest.testBitArrayAsInts() + +### Procedure Id: +com.igormaznitsa.jbbp.io.JBBPOutTest.testBitArrayAsInts():void.3f3fd2cef56633234ae1a8b2d02bdba7 + +### File: +src/test/java/com/igormaznitsa/jbbp/io/JBBPOutTest.java + +### Key: +JBBPOutTest.java|testBitArrayAsInts|RESOURCE_LEAK + +### Node Key: +07c4ca0274b2c82c8349f056d2a4ea49 + +### Hash: +8c913ea817228108bada6455b38116e9 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9086/instruction.md b/inferredbugs-9086/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a4c5e16c42eeb5c3e03378383f697ccd13551600 --- /dev/null +++ b/inferredbugs-9086/instruction.md @@ -0,0 +1,847 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-binary-block-parser +**Bug ID:** 45 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.igormaznitsa.jbbp.io; + +import com.igormaznitsa.jbbp.utils.JBBPSystemProperty; +import com.igormaznitsa.jbbp.utils.JBBPUtils; +import java.io.*; + +/** + * A Filter stream implementing a countable bit stream interface. It allows read + * not only bytes but also bits from an input stream. The Class is not a + * thread-safe one. + */ +public class JBBPBitInputStream extends FilterInputStream implements JBBPCountableBitStream { + + /** + * The Initial an Array buffer size for whole stream read. + */ + protected static final int INITIAL_ARRAY_BUFFER_SIZE = JBBPSystemProperty.PROPERTY_INPUT_INITIAL_ARRAY_BUFFER_SIZE.getAsInteger(32); + + /** + * The Inside bit buffer, + */ + private int bitBuffer; + /** + * The Inside counter of bits in the bit buffer. + */ + private int bitsInBuffer; + /** + * The Byte counter. + */ + private long byteCounter; + + /** + * Inside temp variable to keep the bit buffer temporarily. + */ + private int markedBitBuffer; + /** + * Inside temp variable to keep the bit buffer counter temporarily. + */ + private int markedBitsInBuffer; + /** + * Inside temp variable to keep the byte counter temporarily. + */ + private long markedByteCounter; + + /** + * Flag shows that bit operations must be processed for MSB0 (most significant + * bit 0) mode. + */ + private final boolean msb0; + + /** + * A Constructor, the LSB0 bit order will be used by default. + * + * @param in an input stream to be filtered. + */ + public JBBPBitInputStream(final InputStream in) { + this(in, JBBPBitOrder.LSB0); + } + + /** + * A Constructor. + * + * @param in an input stream to be filtered. + * @param order a bit order mode for the filter. + * @see JBBPBitOrder#LSB0 + * @see JBBPBitOrder#MSB0 + */ + public JBBPBitInputStream(final InputStream in, final JBBPBitOrder order) { + super(in); + this.bitsInBuffer = 0; + this.msb0 = order == JBBPBitOrder.MSB0; + } + + /** + * Read array of boolean values. + * + * @param items number of items to be read, if less than zero then read whole + * stream till the end + * @return read values as boolean array + * @throws IOException it will be thrown for transport error + */ + public boolean[] readBoolArray(final int items) throws IOException { + int pos = 0; + byte[] buffer; + if (items < 0) { + buffer = new byte[INITIAL_ARRAY_BUFFER_SIZE]; + // till end + while (true) { + final int read = this.read(buffer, pos, buffer.length - pos); + if (read < 0) { + break; + } + pos += read; + + if (buffer.length == pos) { + final byte[] newbuffer = new byte[buffer.length << 1]; + System.arraycopy(buffer, 0, newbuffer, 0, buffer.length); + buffer = newbuffer; + } + } + } + else { + // number + buffer = new byte[items]; + int len = items; + while (len > 0) { + final int read = this.read(buffer, pos, len); + if (read < 0) { + throw new EOFException("Have read only " + pos + " bit portions instead of " + items); + } + pos += read; + len -= read; + } + } + + final boolean[] result = new boolean[pos]; + for (int i = 0; i < pos; i++) { + result[i] = buffer[i] != 0; + } + return result; + } + + /** + * Read array of bit sequence. + * + * @param bitNumber bit number for each bit sequence item, must be 1..8 + * @param items number of items to be read, if less than zero then read whole + * stream till the end + * @return array of read bit items as a byte array + * @throws IOException it will be thrown for any transport problem during the + * operation + */ + public byte[] readBitsArray(final int items, final JBBPBitNumber bitNumber) throws IOException { + int pos = 0; + if (items < 0) { + byte[] buffer = new byte[INITIAL_ARRAY_BUFFER_SIZE]; + // till end + while (true) { + final int next = readBits(bitNumber); + if (next < 0) { + break; + } + if (buffer.length == pos) { + final byte[] newbuffer = new byte[buffer.length << 1]; + System.arraycopy(buffer, 0, newbuffer, 0, buffer.length); + buffer = newbuffer; + } + buffer[pos++] = (byte) next; + } + if (buffer.length == pos) { + return buffer; + } + final byte[] result = new byte[pos]; + System.arraycopy(buffer, 0, result, 0, pos); + return result; + } + else { + // number + final byte[] buffer = new byte[items]; + for (int i = 0; i < items; i++) { + final int next = readBits(bitNumber); + if (next < 0) { + throw new EOFException("Have read only " + i + " bit portions instead of " + items); + } + buffer[i] = (byte) next; + } + return buffer; + } + } + + /** + * Read number of bytes for the stream. + * + * @param items number of items to be read, if less than zero then read whole + * stream till the end + * @return read byte items as a byte array + * @throws IOException it will be thrown for any transport problem during the + * operation + */ + public byte[] readByteArray(final int items) throws IOException { + int pos = 0; + if (items < 0) { + byte[] buffer = new byte[INITIAL_ARRAY_BUFFER_SIZE]; + // till end + while (true) { + final int next = read(); + if (next < 0) { + break; + } + if (buffer.length == pos) { + final byte[] newbuffer = new byte[buffer.length << 1]; + System.arraycopy(buffer, 0, newbuffer, 0, buffer.length); + buffer = newbuffer; + } + buffer[pos++] = (byte) next; + } + if (buffer.length == pos) { + return buffer; + } + final byte[] result = new byte[pos]; + System.arraycopy(buffer, 0, result, 0, pos); + return result; + } + else { + // number + final byte[] buffer = new byte[items]; + final int read = this.read(buffer, 0, items); + if (read != items) { + throw new EOFException("Have read only " + read + " byte(s) instead of " + items + " byte(s)"); + } + return buffer; + } + } + + /** + * Read number of short items from the input stream. + * + * @param items number of items to be read from the input stream, if less than + * zero then all stream till the end will be read + * @param byteOrder the order of bytes to be used to decode short values + * @return read items as a short array + * @throws IOException it will be thrown for any transport problem during the + * operation + * @see JBBPByteOrder#BIG_ENDIAN + * @see JBBPByteOrder#LITTLE_ENDIAN + */ + public short[] readShortArray(final int items, final JBBPByteOrder byteOrder) throws IOException { + int pos = 0; + if (items < 0) { + short[] buffer = new short[INITIAL_ARRAY_BUFFER_SIZE]; + // till end + while (hasAvailableData()) { + final int next = readUnsignedShort(byteOrder); + if (buffer.length == pos) { + final short[] newbuffer = new short[buffer.length << 1]; + System.arraycopy(buffer, 0, newbuffer, 0, buffer.length); + buffer = newbuffer; + } + buffer[pos++] = (short) next; + } + if (buffer.length == pos) { + return buffer; + } + final short[] result = new short[pos]; + System.arraycopy(buffer, 0, result, 0, pos); + return result; + } + else { + // number + final short[] buffer = new short[items]; + for (int i = 0; i < items; i++) { + buffer[i] = (short) readUnsignedShort(byteOrder); + } + return buffer; + } + } + + /** + * Read number of integer items from the input stream. + * + * @param items number of items to be read from the input stream, if less than + * zero then all stream till the end will be read + * @param byteOrder the order of bytes to be used to decode values + * @return read items as an integer array + * @throws IOException it will be thrown for any transport problem during the + * operation + * @see JBBPByteOrder#BIG_ENDIAN + * @see JBBPByteOrder#LITTLE_ENDIAN + */ + public int[] readIntArray(final int items, final JBBPByteOrder byteOrder) throws IOException { + int pos = 0; + if (items < 0) { + int[] buffer = new int[INITIAL_ARRAY_BUFFER_SIZE]; + // till end + while (hasAvailableData()) { + final long next = readInt(byteOrder); + if (buffer.length == pos) { + final int[] newbuffer = new int[buffer.length << 1]; + System.arraycopy(buffer, 0, newbuffer, 0, buffer.length); + buffer = newbuffer; + } + buffer[pos++] = (int) next; + } + if (buffer.length == pos) { + return buffer; + } + final int[] result = new int[pos]; + System.arraycopy(buffer, 0, result, 0, pos); + return result; + } + else { + // number + final int[] buffer = new int[items]; + for (int i = 0; i < items; i++) { + buffer[i] = readInt(byteOrder); + } + return buffer; + } + } + + /** + * Read number of long items from the input stream. + * + * @param items number of items to be read from the input stream, if less than + * zero then all stream till the end will be read + * @param byteOrder the order of bytes to be used to decode values + * @return read items as a long array + * @throws IOException it will be thrown for any transport problem during the + * operation + * @see JBBPByteOrder#BIG_ENDIAN + * @see JBBPByteOrder#LITTLE_ENDIAN + */ + public long[] readLongArray(final int items, final JBBPByteOrder byteOrder) throws IOException { + int pos = 0; + if (items < 0) { + long[] buffer = new long[INITIAL_ARRAY_BUFFER_SIZE]; + // till end + while (hasAvailableData()) { + final long next = readLong(byteOrder); + if (buffer.length == pos) { + final long[] newbuffer = new long[buffer.length << 1]; + System.arraycopy(buffer, 0, newbuffer, 0, buffer.length); + buffer = newbuffer; + } + buffer[pos++] = next; + } + if (buffer.length == pos) { + return buffer; + } + final long[] result = new long[pos]; + System.arraycopy(buffer, 0, result, 0, pos); + return result; + } + else { + // number + final long[] buffer = new long[items]; + for (int i = 0; i < items; i++) { + buffer[i] = readLong(byteOrder); + } + return buffer; + } + } + + /** + * Read a unsigned short value from the stream. + * + * @param byteOrder he order of bytes to be used to decode the read value + * @return the unsigned short value read from stream + * @throws IOException it will be thrown for any transport problem during the + * operation + * @throws EOFException if the end of the stream has been reached + * @see JBBPByteOrder#BIG_ENDIAN + * @see JBBPByteOrder#LITTLE_ENDIAN + */ + public int readUnsignedShort(final JBBPByteOrder byteOrder) throws IOException { + final int b0 = this.read(); + if (b0 < 0) { + throw new EOFException(); + } + final int b1 = this.read(); + if (b1 < 0) { + throw new EOFException(); + } + return byteOrder == JBBPByteOrder.BIG_ENDIAN ? (b0 << 8) | b1 : (b1 << 8) | b0; + } + + /** + * Read an integer value from the stream. + * + * @param byteOrder he order of bytes to be used to decode the read value + * @return the unsigned short value read from stream or -1 if the end of + * stream has been reached + * @throws IOException it will be thrown for any transport problem during the + * operation + * @throws EOFException if the end of the stream has been reached + * @see JBBPByteOrder#BIG_ENDIAN + * @see JBBPByteOrder#LITTLE_ENDIAN + */ + public int readInt(final JBBPByteOrder byteOrder) throws IOException { + if (byteOrder == JBBPByteOrder.BIG_ENDIAN) { + return (readUnsignedShort(byteOrder) << 16) | readUnsignedShort(byteOrder); + } + else { + return readUnsignedShort(byteOrder) | (readUnsignedShort(byteOrder) << 16); + } + } + + /** + * Read a long value from the stream. + * + * @param byteOrder he order of bytes to be used to decode the read value + * @return the unsigned short value read from stream or -1 if the end of + * stream has been reached + * @throws IOException it will be thrown for any transport problem during the + * operation + * @throws EOFException if the end of the stream has been reached + * @see JBBPByteOrder#BIG_ENDIAN + * @see JBBPByteOrder#LITTLE_ENDIAN + */ + public long readLong(final JBBPByteOrder byteOrder) throws IOException { + if (byteOrder == JBBPByteOrder.BIG_ENDIAN) { + return (((long) readInt(byteOrder) & 0xFFFFFFFFL) << 32) | ((long) readInt(byteOrder) & 0xFFFFFFFFL); + } + else { + return ((long) readInt(byteOrder) & 0xFFFFFFFFL) | (((long) readInt(byteOrder) & 0xFFFFFFFFL) << 32); + } + } + + /** + * Get the current byte counter state. + * + * @return the number of bytes read from the stream currently + */ + public long getCounter() { + return this.byteCounter; + } + + /** + * Get the value of the inside bit buffer + * + * @return the bit buffer state + */ + public int getBitBuffer() { + return this.bitBuffer; + } + + /** + * Get the number of buffered bits in the inside bit buffer + * + * @return the number of buffered bits in the bit buffer + */ + public int getBufferedBitsNumber() { + return this.bitsInBuffer; + } + + /** + * Get the bit order option for read operations. + * + * @return the bit order parameter + * @see JBBPBitOrder#LSB0 + * @see JBBPBitOrder#MSB0 + */ + public JBBPBitOrder getBitOrder() { + return this.msb0 ? JBBPBitOrder.MSB0 : JBBPBitOrder.LSB0; + } + + /** + * Read number of bits from the input stream. It reads bits from input stream + * since 0 bit and make reversion to return bits in the right order when 0 bit + * is 0 bit. if the stream is completed early than the data read then reading + * is just stopped and read value returned. The First read bit is placed as + * 0th bit. + * + * @param numOfBitsToRead the number of bits to be read, must be 1..8 + * @return the read bits as integer, -1 if the end of stream has been reached + * @throws IOException it will be thrown for transport errors to be read + * @throws NullPointerException if number of bits to be read is null + */ + public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException { + int result; + + final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber(); + + if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) { + result = this.readByteFromStream(); + return result; + } + else { + result = 0; + + if (numOfBitsAsNumber == this.bitsInBuffer){ + result = this.bitBuffer; + this.bitBuffer = 0; + this.bitsInBuffer = 0; + return result; + } + + int i = numOfBitsAsNumber; + int theBitBuffer = this.bitBuffer; + int theBitBufferCounter = this.bitsInBuffer; + + while (i > 0) { + if (theBitBufferCounter == 0) { + final int nextByte = this.readByteFromStream(); + if (nextByte < 0) { + if (i == numOfBitsAsNumber) { + return nextByte; + } + else { + break; + } + } + else { + theBitBuffer = nextByte; + theBitBufferCounter = 8; + } + } + + result = (result << 1) | (theBitBuffer & 1); + theBitBuffer >>= 1; + theBitBufferCounter--; + i--; + } + + this.bitBuffer = theBitBuffer; + this.bitsInBuffer = theBitBufferCounter; + + return (JBBPUtils.reverseByte((byte) result) & 0xFF) >> (8 - (numOfBitsAsNumber - i)); + } + } + + /** + * Read a boolean value saved as a byte. + * + * @return true if the value is not zero, false if the value is zero + * @throws IOException it will be thrown for transport errors. + */ + public boolean readBoolean() throws IOException { + final int read = this.read(); + if (read < 0) { + throw new EOFException("Can't read a boolean value"); + } + return read != 0; + } + + /** + * Read a byte value. + * + * @return the byte value read from the stream + * @throws IOException it will be thrown for transport errors. + */ + public int readByte() throws IOException { + final int read = this.read(); + if (read < 0) { + throw new EOFException("Can't read a byte value"); + } + return read; + } + + @Override + public boolean markSupported() { + return super.markSupported(); + } + + @Override + public synchronized void reset() throws IOException { + in.reset(); + this.bitBuffer = this.markedBitBuffer; + this.byteCounter = this.markedByteCounter; + this.bitsInBuffer = this.markedBitsInBuffer; + } + + @Override + public synchronized void mark(final int readlimit) { + in.mark(readlimit); + this.markedBitBuffer = this.bitBuffer; + this.markedByteCounter = this.byteCounter; + this.markedBitsInBuffer = this.bitsInBuffer; + } + + @Override + public int available() throws IOException { + return super.available(); + } + + /** + * Read padding bytes from the stream and ignore them to align the stream + * counter. + * + * @param alignByteNumber the byte number to align the stream + * @throws IOException it will be thrown for transport errors + * @throws EOFException it will be thrown if the stream end has been reached + * the before align border. + */ + public void align(final long alignByteNumber) throws IOException { + this.alignByte(); + + if (alignByteNumber > 0) { + long padding = (alignByteNumber - (this.byteCounter % alignByteNumber)) % alignByteNumber; + + while (padding > 0) { + final int skippedByte = this.read(); + if (skippedByte < 0) { + throw new EOFException("Can't align for " + alignByteNumber + " byte(s)"); + } + padding--; + } + } + + } + + @Override + public long skip(final long numOfBytes) throws IOException { + if (this.bitsInBuffer == 0) { + final long r = in.skip(numOfBytes); + this.byteCounter += (int) r; + return r; + } + else { + long i = numOfBytes; + long count = 0L; + while (i > 0) { + final int nxt = readBits(JBBPBitNumber.BITS_8); + if (nxt < 0) { + break; + } + count++; + i--; + } + return count; + } + } + + /** + * Inside method to read a byte from stream. + * + * @return the read byte or -1 if the end of the stream has been reached + * @throws IOException it will be thrown for transport errors + */ + private int readByteFromStream() throws IOException { + int result = this.in.read(); + if (result >= 0) { + if (this.msb0) { + result = JBBPUtils.reverseByte((byte) result) & 0xFF; + } + this.byteCounter++; + } + return result; + } + + /** + * Read the next stream byte into bit buffer. + * + * @return the read byte or -1 if the endo of stream has been reached. + * @throws IOException it will be thrown for transport errors + */ + private int loadNextByteInBuffer() throws IOException { + final int value = this.readByteFromStream(); + if (value < 0) { + return value; + } + + this.bitBuffer = value; + this.bitsInBuffer = 8; + + return value; + } + + /** + * Align read byte. If there are unread bits in inside bit buffer, it will be + * aligned to read the next byte from stream instead of reading from the bit + * buffer. + */ + public void alignByte() { + if (this.bitsInBuffer > 0 && this.bitsInBuffer < 8) { + this.bitsInBuffer = 0; + } + } + + /** + * Check that there is available data to read from stream. NB: It will read + * one byte from the stream and will save it into inside bit buffer. + * + * @return true if there is data to be read + * @throws IOException it will be thrown for transport errors + */ + public boolean hasAvailableData() throws IOException { + if (this.bitsInBuffer > 0) { + return true; + } + return loadNextByteInBuffer() >= 0; + } + + @Override + public int read(final byte[] array, final int offset, final int length) throws IOException { + if (this.bitsInBuffer == 0) { + int readBytes = 0; + int tmpoffset = offset; + int tmplen = length; + while (tmplen > 0) { + int read = this.in.read(array, tmpoffset, tmplen); + if (read < 0) { + readBytes = readBytes == 0 ? read : readBytes; + break; + } + tmplen -= read; + tmpoffset += read; + readBytes += read; + this.byteCounter += read; + } + + if (this.msb0) { + int index = offset; + int number = readBytes; + while (number > 0) { + array[index] = JBBPUtils.reverseByte(array[index]); + index++; + number--; + } + } + + return readBytes; + } + else { + int count = length; + int i = offset; + while (count > 0) { + final int nextByte = this.readBits(JBBPBitNumber.BITS_8); + if (nextByte < 0) { + break; + } + count--; + array[i++] = (byte) nextByte; + } + return length - count; + } + } + + /** + * Reset the byte counter for the stream. The Inside bit buffer will be reset + * also if it is not full. + * + * @see #align(long) + * @see #alignByte() + * @see #getBitBuffer() + * @see #getBufferedBitsNumber() + * @see #hasAvailableData() . + */ + public void resetCounter() { + if (this.bitsInBuffer < 8) { + this.bitsInBuffer = 0; + this.bitBuffer = 0; + } + this.byteCounter = 0L; + } + + @Override + public int read(final byte[] array) throws IOException { + return this.read(array, 0, array.length); + } + + @Override + public int read() throws IOException { + final int result; + if (this.bitsInBuffer == 0) { + result = this.readByteFromStream(); + if (result < 0) { + return result; + } + return result; + } + else { + return this.readBits(JBBPBitNumber.BITS_8); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.igormaznitsa.jbbp.io.JBBPBitInputStream.readBits` indirectly writes to field `this.com.igormaznitsa.jbbp.io.JBBPBitInputStream.byteCounter` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int JBBPBitInputStream.readBits(JBBPBitNumber) + +### Procedure Id: +com.igormaznitsa.jbbp.io.JBBPBitInputStream.readBits(com.igormaznitsa.jbbp.io.JBBPBitNumber):int.6da80f561b7ca898a0e77b0e3a6afd2d + +### File: +src/main/java/com/igormaznitsa/jbbp/io/JBBPBitInputStream.java + +### Key: +JBBPBitInputStream.java|readBits|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +8e55f4a4c21933cfa8e6bf1338c512ee + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9088/instruction.md b/inferredbugs-9088/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4457a0f0224c0861b1315d0a5228cc5c449829a6 --- /dev/null +++ b/inferredbugs-9088/instruction.md @@ -0,0 +1,494 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-binary-block-parser +**Bug ID:** 28 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.igormaznitsa.jbbp.io; + +import static com.igormaznitsa.jbbp.io.JBBPOut.*; +import java.io.*; +import static org.junit.Assert.*; +import org.junit.Test; + +public class JBBPOutTest { + + @Test + public void testBinStart() throws Exception { + assertArrayEquals(new byte[]{1},binStart().Byte(1).end().toByteArray()); + assertArrayEquals(new byte[]{0x02,0x01},binStart(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{0x40,(byte)0x80},binStart(JBBPByteOrder.LITTLE_ENDIAN,JBBPBitOrder.MSB0).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{(byte)0x80},binStart(JBBPBitOrder.MSB0).Byte(1).end().toByteArray()); + + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + assertSame(buffer, binStart(buffer).end()); + } + + @Test + public void testAlign() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).end().toByteArray()); + } + + @Test + public void testAlignWithArgument() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).Align(2).end().toByteArray().length); + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Align(3).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(2).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Int(0x01020304).Align(5).Byte(0xF1).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(5).Byte(0xF1).end().toByteArray()); + } + + @Test + public void testEmptyArray() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).end().toByteArray().length); + } + + @Test + public void testByte() throws Exception { + assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).end().toByteArray()); + } + + @Test + public void testByteArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + } + + @Test + public void testByteArrayAsByteArray() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}).end().toByteArray()); + } + + @Test + public void testBit() throws Exception { + assertArrayEquals(new byte[]{1}, binStart().Bit(1).end().toByteArray()); + } + + @Test + public void testBit_MSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x80}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.MSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBit_LSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.LSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBits_Int() throws Exception { + assertArrayEquals(new byte[]{0xD}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD).end().toByteArray()); + } + + @Test + public void testBits_IntArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD, 0xFE).end().toByteArray()); + } + + @Test + public void testBits_ByteArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).end().toByteArray()); + } + + @Test + public void testBitArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray()); + } + + @Test + public void testBitArrayAsBytes() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray()); + } + + @Test + public void testBitArrayAsBooleans() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray()); + } + + @Test + public void testShort() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_LittleEndian() throws Exception { + assertArrayEquals(new byte []{0x02,01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_BigEndian() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_LittleEndian() throws Exception { + assertArrayEquals(new byte []{2,1,4,3}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShorts() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short((short)0x0102, (short)0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShortArray() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short(new short[]{(short)0x0102, (short)0x0304}).end().toByteArray()); + } + + @Test + public void testInt() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04}, binStart().Int(0x01020304).end().toByteArray()); + } + + @Test + public void testIntArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Int(0x01020304, 0x05060708).end().toByteArray()); + } + + @Test + public void testInt_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testInt_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testLong() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLongArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, binStart().Long(0x0102030405060708L,0x1112131415161718L).end().toByteArray()); + } + + @Test + public void testLong_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLong_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testFlush() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPOut out = binStart(buffer); + + out.Bit(true); + assertEquals(0, buffer.size()); + out.Flush(); + assertEquals(1, buffer.size()); + } + + @Test + public void testExceptionForOperatioOverEndedProcess() throws Exception { + final JBBPOut out = binStart(); + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end(); + try{ + out.Align(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Align(3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34,(byte)12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(34,12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte((byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Flush(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1,2); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L,2L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short((short)1,(short)2,(short)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.end(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + } + + @Test + public void testExternalStreamButNoByteArrayOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final DataOutputStream dout = new DataOutputStream(buffer); + + assertNull(binStart(dout).Byte(1,2,3).end()); + assertArrayEquals(new byte[]{1,2,3}, buffer.toByteArray()); + } + + @Test(expected = IllegalArgumentException.class) + public void testExceptionForBitOrderConfilctInCaseOfUsageBitOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPBitOutputStream bitstream = new JBBPBitOutputStream(buffer,JBBPBitOrder.LSB0); + + new JBBPOut(bitstream,JBBPByteOrder.BIG_ENDIAN,JBBPBitOrder.MSB0); + } + + @Test + public void testComplexWriting_1() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384); + + final JBBPOut begin = new JBBPOut(buffer); + + begin. + Bit(1, 2, 3, 0). + Bit(true, false, true). + Align(). + Byte(5). + Short(1, 2, 3, 4, 5). + Bool(true, false, true, true). + Int(0xABCDEF23, 0xCAFEBABE). + Long(0x123456789ABCDEF1L, 0x212356239091AB32L). + end(); + + final byte[] array = buffer.toByteArray(); + + assertEquals(40, array.length); + assertArrayEquals(new byte[]{ + (byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1, + (byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, + 0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32 + + }, array); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.igormaznitsa.jbbp.io.JBBPBitOutputStream` acquired by call to `binStart()` at line 190 is not released after line 190. +**Note**: potential exception at line 190 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JBBPOutTest.testLong() + +### Procedure Id: +com.igormaznitsa.jbbp.io.JBBPOutTest.testLong():void.681aeeaa0eaac76620569dcf7dec17b7 + +### File: +src/test/java/com/igormaznitsa/jbbp/io/JBBPOutTest.java + +### Key: +JBBPOutTest.java|testLong|RESOURCE_LEAK + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +87343c50541fbf7b0c5dd7edb6bd53dc + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9153/instruction.md b/inferredbugs-9153/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ada0748698caef175462fe00a4dea05de5a81e4e --- /dev/null +++ b/inferredbugs-9153/instruction.md @@ -0,0 +1,189 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rtree +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.davidmoten.rtree.fbs; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Test; + +import com.github.davidmoten.rtree.Entry; +import com.github.davidmoten.rtree.GreekEarthquakes; +import com.github.davidmoten.rtree.InternalStructure; +import com.github.davidmoten.rtree.RTree; +import com.github.davidmoten.rtree.geometry.Geometries; +import com.github.davidmoten.rtree.geometry.Point; + +import rx.Observable; +import rx.functions.Func1; + +public class SerializerFlatBuffersTest { + + private static final byte[] EMPTY = new byte[] {}; + + @Test + public void testSerializeRoundTripToFlatBuffersSingleArray() throws Exception { + roundTrip(InternalStructure.FLATBUFFERS_SINGLE_ARRAY, false); + } + + @Test + public void testSerializeRoundTripToDefaultStructure() throws Exception { + roundTrip(InternalStructure.DEFAULT, false); + } + + @Test + public void testSerializeRoundTripToFlatBuffersSingleArrayBackpressure() throws Exception { + roundTrip(InternalStructure.FLATBUFFERS_SINGLE_ARRAY, true); + } + + @Test + public void testSerializeRoundTripToDefaultStructureBackpressure() throws Exception { + roundTrip(InternalStructure.DEFAULT, true); + } + + private void roundTrip(InternalStructure structure, boolean backpressure) throws Exception { + RTree tree = RTree.star().maxChildren(10).create(); + tree = tree.add(GreekEarthquakes.entries()).last().toBlocking().single(); + long t = System.currentTimeMillis(); + File file = new File("target/file"); + FileOutputStream os = new FileOutputStream(file); + SerializerFlatBuffers fbSerializer = createSerializer(); + + serialize(tree, t, file, os, fbSerializer); + + deserialize(structure, file, fbSerializer, backpressure); + } + + private static SerializerFlatBuffers createSerializer() { + Func1 serializer = new Func1() { + @Override + public byte[] call(Object o) { + return EMPTY; + } + }; + Func1 deserializer = new Func1() { + @Override + public Object call(byte[] bytes) { + return null; + } + }; + SerializerFlatBuffers fbSerializer = SerializerFlatBuffers.create(serializer, + deserializer); + return fbSerializer; + } + + private static void serialize(RTree tree, long t, File file, FileOutputStream os, + SerializerFlatBuffers fbSerializer) throws IOException { + fbSerializer.serialize(tree, os); + os.close(); + System.out.println("written in " + (System.currentTimeMillis() - t) + "ms, " + "file size=" + + file.length() / 1000000.0 + "MB"); + System.out.println("bytes per entry=" + file.length() / tree.size()); + } + + private static void deserialize(InternalStructure structure, File file, + SerializerFlatBuffers fbSerializer, boolean backpressure) + throws Exception { + long t = System.currentTimeMillis(); + InputStream is = new FileInputStream(file); + t = System.currentTimeMillis(); + RTree tr = fbSerializer.deserialize(file.length(), is, structure); + System.out.println(tr.root().get()); + + System.out.println("read in " + (System.currentTimeMillis() - t) + "ms"); + Observable> o = tr.search(Geometries.rectangle(40, 27.0, 40.5, 27.5)); + if (backpressure) + o = o.take(10000); + int found = o.count().toBlocking().single(); + System.out.println("found=" + found); + assertEquals(22, found); + System.out.println(tr.size()); + } + + public static void main(String[] args) throws Exception { + // use this with jvisualvm and heap dump, find biggest objects to check + // memory usage of rtree + // deserialize(InternalStructure.FLATBUFFERS_SINGLE_ARRAY, new + // File("target/file"), + // createSerializer()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileOutputStream` acquired to `os` by call to `FileOutputStream(...)` at line 52 is not released after line 55. +**Note**: potential exception at line 55 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SerializerFlatBuffersTest.roundTrip(InternalStructure,boolean) + +### Procedure Id: +com.github.davidmoten.rtree.fbs.SerializerFlatBuffersTest.roundTrip(com.github.davidmoten.rtree.Inte.607f51cc64bf124406df7514d64f5723 + +### File: +src/test/java/com/github/davidmoten/rtree/fbs/SerializerFlatBuffersTest.java + +### Key: +SerializerFlatBuffersTest.java|roundTrip|RESOURCE_LEAK + +### Node Key: +d2e626c85af908753b28d1a09fad00d5 + +### Hash: +f5dc2b9f36a8d631411b1acc7537702a + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9162/instruction.md b/inferredbugs-9162/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43cca2f5cd6308f58810a0aa07941829143254a0 --- /dev/null +++ b/inferredbugs-9162/instruction.md @@ -0,0 +1,293 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helidon +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2017, 2019 Oracle and/or its affiliates. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.helidon.config.internal; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.file.Paths; +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; +import java.util.logging.Level; +import java.util.logging.Logger; + +import io.helidon.config.Config; +import io.helidon.config.ConfigException; +import io.helidon.config.ConfigHelper; +import io.helidon.config.ConfigMappingException; +import io.helidon.config.MissingValueException; +import io.helidon.config.spi.AbstractParsableConfigSource; +import io.helidon.config.spi.ConfigParser; +import io.helidon.config.spi.ConfigSource; +import io.helidon.config.spi.PollingStrategy; + +/** + * {@link ConfigSource} implementation that loads configuration content from specified endpoint URL. + * + * @see AbstractParsableConfigSource.Builder + */ +public class UrlConfigSource extends AbstractParsableConfigSource { + + private static final Logger LOGGER = Logger.getLogger(UrlConfigSource.class.getName()); + + private static final String HEAD_METHOD = "HEAD"; + private static final String GET_METHOD = "GET"; + private static final String URL_KEY = "url"; + + private final URL url; + + UrlConfigSource(UrlBuilder builder, URL url) { + super(builder); + + this.url = url; + } + + /** + * Initializes config source instance from configuration properties. + *

    + * Mandatory {@code properties}, see {@link io.helidon.config.ConfigSources#url(URL)}: + *

      + *
    • {@code url} - type {@link URL}
    • + *
    + * Optional {@code properties}: see {@link AbstractParsableConfigSource.Builder#init(Config)}. + * + * @param metaConfig meta-configuration used to initialize returned config source instance from. + * @return new instance of config source described by {@code metaConfig} + * @throws MissingValueException in case the configuration tree does not contain all expected sub-nodes + * required by the mapper implementation to provide instance of Java type. + * @throws ConfigMappingException in case the mapper fails to map the (existing) configuration tree represented by the + * supplied configuration node to an instance of a given Java type. + * @see io.helidon.config.ConfigSources#url(URL) + * @see AbstractParsableConfigSource.Builder#init(Config) + */ + public static UrlConfigSource create(Config metaConfig) throws ConfigMappingException, MissingValueException { + return (UrlConfigSource) new UrlBuilder(metaConfig.get(URL_KEY).as(URL.class).get()) + .init(metaConfig) + .build(); + } + + @Override + protected String uid() { + return url.toString(); + } + + @Override + protected ConfigParser.Content content() throws ConfigException { + try { + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod(GET_METHOD); + + final String mediaType = mediaType(connection.getContentType()); + final Optional timestamp; + if (connection.getLastModified() != 0) { + timestamp = Optional.of(Instant.ofEpochMilli(connection.getLastModified())); + } else { + timestamp = Optional.of(Instant.now()); + LOGGER.fine("Missing GET '" + url + "' response header 'Last-Modified'. Used current time '" + + timestamp + "' as a content timestamp."); + } + + Reader reader = new InputStreamReader(connection.getInputStream(), + ConfigUtils.getContentCharset(connection.getContentEncoding())); + + return ConfigParser.Content.create(reader, mediaType, timestamp); + } catch (ConfigException ex) { + throw ex; + } catch (Exception ex) { + throw new ConfigException("Configuration at url '" + url + "' GET is not accessible.", ex); + } + } + + @Override + protected String mediaType() { + //do not call ConfigHelper.guessMediaType here - it is done in content() method + return super.mediaType(); + } + + private String mediaType(String responseMediaType) { + String mediaType = mediaType(); + if (mediaType == null) { + mediaType = responseMediaType; + if (mediaType == null) { + mediaType = probeContentType(); + if (LOGGER.isLoggable(Level.FINE)) { + LOGGER.fine("HTTP response does not contain content-type, used guessed one: " + mediaType + "."); + } + } + } + return mediaType; + } + + private String probeContentType() { + String path = url.getPath(); + return ConfigHelper.detectContentType(Paths.get(path)); + } + + @Override + protected Optional dataStamp() { + try { + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod(HEAD_METHOD); + + if (connection.getLastModified() != 0) { + return Optional.of(Instant.ofEpochMilli(connection.getLastModified())); + } + } catch (IOException ex) { + LOGGER.log(Level.FINE, ex, () -> "Configuration at url '" + url + "' HEAD is not accessible."); + } + Optional timestamp = Optional.of(Instant.MAX); + LOGGER.finer("Missing HEAD '" + url + "' response header 'Last-Modified'. Used time '" + + timestamp + "' as a content timestamp."); + return timestamp; + } + + /** + * Url ConfigSource Builder. + *

    + * It allows to configure following properties: + *

      + *
    • {@code url} - configuration endpoint URL;
    • + *
    • {@code mandatory} - is existence of configuration resource mandatory (by default) or is {@code optional}?
    • + *
    • {@code media-type} - configuration content media type to be used to look for appropriate {@link ConfigParser};
    • + *
    • {@code parser} - or directly set {@link ConfigParser} instance to be used to parse the source;
    • + *
    + *

    + * If the Url ConfigSource is {@code mandatory} and a {@code url} endpoint does not exist + * then {@link ConfigSource#load} throws {@link ConfigException}. + *

    + * If {@code media-type} not set it uses HTTP response header {@code content-type}. + * If {@code media-type} not returned it tries to guess it from url suffix. + */ + public static final class UrlBuilder extends Builder { + private URL url; + + /** + * Initialize builder. + * + * @param url configuration url + */ + public UrlBuilder(URL url) { + super(URL.class); + + Objects.requireNonNull(url, "url cannot be null"); + + this.url = url; + } + + @Override + protected UrlBuilder init(Config metaConfig) { + return super.init(metaConfig); + } + + @Override + protected URL target() { + return url; + } + + /** + * Builds new instance of Url ConfigSource. + *

    + * If {@code media-type} not set it tries to use {@code content-type} response header or guesses it from file extension. + * + * @return new instance of Url ConfigSource. + */ + public ConfigSource build() { + return new UrlConfigSource(this, url); + } + + PollingStrategy pollingStrategyInternal() { //just for testing purposes + return super.pollingStrategy(); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.net.HttpURLConnection` acquired to `connection` by call to `openConnection()` at line 146 is not released after line 149. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Optional UrlConfigSource.dataStamp() + +### Procedure Id: +io.helidon.config.internal.UrlConfigSource.dataStamp():java.util.Optional.5a16bbceafb3034f95ceb8aac29d718e + +### File: +config/config/src/main/java/io/helidon/config/internal/UrlConfigSource.java + +### Key: +UrlConfigSource.java|dataStamp|RESOURCE_LEAK + +### Node Key: +66e7046a1695213a47623278c33e5e81 + +### Hash: +28090557035dd92abed0714dba18011a + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9165/instruction.md b/inferredbugs-9165/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0a123d1063ae60f54bcff320c24eb4bb71372962 --- /dev/null +++ b/inferredbugs-9165/instruction.md @@ -0,0 +1,468 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helidon +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.helidon.microprofile.faulttolerance; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.logging.Logger; + +import javax.interceptor.InvocationContext; + +import com.netflix.config.ConfigurationManager; +import com.netflix.hystrix.HystrixCommand; +import com.netflix.hystrix.HystrixCommandGroupKey; +import com.netflix.hystrix.HystrixCommandKey; +import com.netflix.hystrix.HystrixCommandProperties; +import com.netflix.hystrix.HystrixThreadPoolKey; +import com.netflix.hystrix.HystrixThreadPoolProperties; +import org.apache.commons.configuration.AbstractConfiguration; + +import static com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy.THREAD; + +/** + * Class FaultToleranceCommand. + */ +public class FaultToleranceCommand extends HystrixCommand { + private static final Logger LOGGER = Logger.getLogger(FaultToleranceCommand.class.getName()); + + private final String commandKey; + + private final MethodIntrospector introspector; + + private final InvocationContext context; + + private long executionTime = -1L; + + private CircuitBreakerHelper breakerHelper; + + private BulkheadHelper bulkheadHelper; + + private long queuedNanos = -1L; + + /** + * A Hystrix command that can be used to open or close a circuit breaker + * by running a succession of passing or failing commands that are part + * of a {@link Runnable}. + */ + private static class RunnableCommand extends HystrixCommand { + + private final Runnable runnable; + + RunnableCommand(String commandKey, Runnable runnable) { + super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("io.j4c.faulttolerance")) + .andCommandKey( + HystrixCommandKey.Factory.asKey(commandKey)) + .andCommandPropertiesDefaults( + HystrixCommandProperties.Setter().withFallbackEnabled(false))); + this.runnable = runnable; + } + + @Override + protected Object run() throws Exception { + runnable.run(); + return ""; + } + } + + /** + * Default thread pool size for a command or a command group. + */ + private static final int MAX_THREAD_POOL_SIZE = 10; + + /** + * Default max thread pool queue size. + */ + private static final int MAX_THREAD_POOL_QUEUE_SIZE = -1; + + /** + * Constructor. Specify a thread pool key if a {@code @Bulkhead} is specified + * on the method. A unique thread pool key will enable setting limits for this + * command only based on the {@code Bulkhead} properties. + * + * @param commandKey The command key. + * @param introspector The method introspector. + * @param context CDI invocation context. + */ + public FaultToleranceCommand(String commandKey, MethodIntrospector introspector, InvocationContext context) { + super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("io.j4c.faulttolerance")) + .andCommandKey( + HystrixCommandKey.Factory.asKey(commandKey)) + .andCommandPropertiesDefaults( + HystrixCommandProperties.Setter() + .withFallbackEnabled(false) + .withExecutionIsolationStrategy(THREAD)) + .andThreadPoolKey( + introspector.hasBulkhead() + ? HystrixThreadPoolKey.Factory.asKey(commandKey) + : null) + .andThreadPoolPropertiesDefaults( + HystrixThreadPoolProperties.Setter() + .withCoreSize( + introspector.hasBulkhead() + ? introspector.getBulkhead().value() + : MAX_THREAD_POOL_SIZE) + .withMaximumSize( + introspector.hasBulkhead() + ? introspector.getBulkhead().value() + : MAX_THREAD_POOL_SIZE) + .withMaxQueueSize( + introspector.hasBulkhead() + ? introspector.getBulkhead().waitingTaskQueue() + : MAX_THREAD_POOL_QUEUE_SIZE) + .withQueueSizeRejectionThreshold( + introspector.hasBulkhead() + ? introspector.getBulkhead().waitingTaskQueue() + : MAX_THREAD_POOL_QUEUE_SIZE + ))); + this.commandKey = commandKey; + this.introspector = introspector; + this.context = context; + + // Special initialization for methods with breakers + if (introspector.hasCircuitBreaker()) { + this.breakerHelper = new CircuitBreakerHelper(this, introspector.getCircuitBreaker()); + + // Register gauges for this method + FaultToleranceMetrics.registerGauge(introspector.getMethod(), + FaultToleranceMetrics.BREAKER_OPEN_TOTAL, + "Amount of time the circuit breaker has spent in open state", + () -> breakerHelper.getInStateNanos(CircuitBreakerHelper.State.OPEN_MP)); + FaultToleranceMetrics.registerGauge(introspector.getMethod(), + FaultToleranceMetrics.BREAKER_HALF_OPEN_TOTAL, + "Amount of time the circuit breaker has spent in half-open state", + () -> breakerHelper.getInStateNanos(CircuitBreakerHelper.State.HALF_OPEN_MP)); + FaultToleranceMetrics.registerGauge(introspector.getMethod(), + FaultToleranceMetrics.BREAKER_CLOSED_TOTAL, + "Amount of time the circuit breaker has spent in closed state", + () -> breakerHelper.getInStateNanos(CircuitBreakerHelper.State.CLOSED_MP)); + } + + if (introspector.hasBulkhead()) { + bulkheadHelper = new BulkheadHelper(this, introspector.getBulkhead()); + // Record instance if command is getting queued + if (bulkheadHelper.isQueueFull()) { + queuedNanos = System.nanoTime(); + } + bulkheadHelper.addCommand(this); + + // Register guages for this method + FaultToleranceMetrics.registerGauge(introspector.getMethod(), + FaultToleranceMetrics.BULKHEAD_CONCURRENT_EXECUTIONS, + "Number of currently running executions", + () -> bulkheadHelper.runningCommands()); + if (introspector.isAsynchronous()) { + FaultToleranceMetrics.registerGauge(introspector.getMethod(), + FaultToleranceMetrics.BULKHEAD_WAITING_QUEUE_POPULATION, + "Number of executions currently waiting in the queue", + () -> bulkheadHelper.waitingCommands()); + } + } + } + + /** + * Get command's execution time in nanos. + * + * @return Execution time in nanos. + * @throws IllegalStateException If called before command is executed. + */ + long getExecutionTime() { + if (executionTime == -1L) { + throw new IllegalStateException("Command has not been executed yet"); + } + return executionTime; + } + + /** + * Code to run as part of this command. + * + * @return Result of command. + * @throws Exception If an error occurs. + */ + @Override + public Object run() throws Exception { + if (introspector.hasBulkhead()) { + bulkheadHelper.markAsRunning(this); + // Update waiting time histogram + if (introspector.isAsynchronous() && queuedNanos != -1L) { + FaultToleranceMetrics.getHistogram(introspector.getMethod(), FaultToleranceMetrics.BULKHEAD_WAITING_DURATION) + .update(System.nanoTime() - queuedNanos); + } + } + + // Command execution + Object result = context.proceed(); + + if (introspector.hasBulkhead()) { + bulkheadHelper.markAsNotRunning(this); + } + return result; + } + + /** + * Executes this command returning a result or throwing an exception. + * + * @return The result. + * @throws RuntimeException If something goes wrong. + */ + @Override + public Object execute() { + // Configure command before execution + introspector.getHystrixProperties() + .entrySet() + .forEach(entry -> setProperty(entry.getKey(), entry.getValue())); + + // Record state of breaker + boolean wasBreakerOpen = isCircuitBreakerOpen(); + + // Execute command + Object result = null; + Throwable throwable = null; + long startNanos = System.nanoTime(); + try { + result = super.execute(); + } catch (Throwable t) { + throwable = t; + } + executionTime = System.nanoTime() - startNanos; + boolean hasFailed = (throwable != null); + + if (introspector.hasCircuitBreaker()) { + // Keep track of failure ratios + breakerHelper.pushResult(throwable == null); + + // Query breaker states + boolean breakerWillOpen = false; + boolean isClosedNow = !isCircuitBreakerOpen(); + + /* + * Special logic for MP circuit breakers to support failOn. If not a + * throwable to fail on, restore underlying breaker and return. + */ + if (hasFailed) { + final Throwable throwableFinal = throwable; + Class[] throwableClasses = introspector.getCircuitBreaker().failOn(); + boolean failOn = Arrays.asList(throwableClasses) + .stream() + .anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass())); + if (!failOn) { + restoreBreaker(); // clears Hystrix counters + updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen); + throw ExceptionUtil.wrapThrowable(throwable); + } + } + + /* + * Special logic for MP circuit breakers to support an arbitrary success + * threshold use to return a breaker back to its CLOSED state. Hystrix + * only supports a threshold of 1 here, so additional logic is required. + */ + synchronized (breakerHelper.getSyncObject()) { + if (hasFailed) { + if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) { + // If failed and in HALF_OPEN_MP, we need to force braker to open + runTripBreaker(); + breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP); + } else if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) { + // Determine if breaker will open given failure ratio + double failureRatio = breakerHelper.getFailureRatio(); + if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) { + breakerWillOpen = true; + breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP); + } + } + updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen); + throw ExceptionUtil.wrapThrowable(throwable); + } + + if (wasBreakerOpen && isClosedNow) { + // We stay in HALF_OPEN_MP until successThreshold is reached + if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) { + breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP); + breakerHelper.incSuccessCount(); + } else { + breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP); + } + } + } + + updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen); + } + + // Update bulkhead helper + if (introspector.hasBulkhead()) { + bulkheadHelper.removeCommand(this); + } + + // Outcome of execution + if (throwable != null) { + throw ExceptionUtil.wrapThrowable(throwable); + } else { + return result; + } + } + + private void updateMetricsAfter(Throwable throwable, boolean wasBreakerOpen, boolean breakerWillOpen) { + assert introspector.hasCircuitBreaker(); + Method method = introspector.getMethod(); + + if (throwable == null) { + // If no errors increment success counter + FaultToleranceMetrics.getCounter(method, FaultToleranceMetrics.BREAKER_CALLS_SUCCEEDED_TOTAL).inc(); + } else if (!wasBreakerOpen) { + // If error and breaker was closed, increment failed counter + FaultToleranceMetrics.getCounter(method, FaultToleranceMetrics.BREAKER_CALLS_FAILED_TOTAL).inc(); + // If it will open, increment counter + if (breakerWillOpen) { + FaultToleranceMetrics.getCounter(method, FaultToleranceMetrics.BREAKER_OPENED_TOTAL).inc(); + } + } + if (wasBreakerOpen) { + // If breaker was open, increment prevented counter + FaultToleranceMetrics.getCounter(method, FaultToleranceMetrics.BREAKER_CALLS_PREVENTED_TOTAL).inc(); + } + } + + /** + * Run a failing command for an entire window to force a circuit breaker to + * open. Unfortunately, there is no access to the underlying circuit breaker + * so this is the only way to control its internal state. Notice the use of + * the same {@code commandKey}. + */ + private void runTripBreaker() { + LOGGER.fine("Attempting to trip circuit breaker for command " + commandKey); + final int windowSize = introspector.getCircuitBreaker().requestVolumeThreshold(); + for (int i = 0; i < windowSize; i++) { + try { + new RunnableCommand(commandKey, () -> { + throw new RuntimeException("Oops"); + }).execute(); + } catch (Throwable t) { + // ignore + } + } + if (!isCircuitBreakerOpen()) { + LOGGER.fine("Attempt to manually open breaker failed for command " + + commandKey); + } + } + + /** + * Run a successful command for an entire window to force a circuit breaker + * to close. Unfortunately, there is no access to the underlying circuit breaker + * so this is the only way to control its internal state. Notice the use of + * the same {@code commandKey}. + */ + private void restoreBreaker() { + LOGGER.fine("Attempting to restore circuit breaker for command " + commandKey); + final int windowSize = introspector.getCircuitBreaker().requestVolumeThreshold(); + for (int i = 0; i < windowSize; i++) { + new RunnableCommand(commandKey, () -> {}).execute(); + } + if (isCircuitBreakerOpen()) { + LOGGER.fine("Attempt to manually close breaker failed for command " + + commandKey); + } + } + + /** + * Sets a Hystrix property on a command. + * + * @param key Property key. + * @param value Property value. + */ + private void setProperty(String key, Object value) { + final AbstractConfiguration configManager = ConfigurationManager.getConfigInstance(); + configManager.setProperty(String.format("hystrix.command.%s.%s", commandKey, key), value); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `io.helidon.microprofile.faulttolerance.FaultToleranceCommand.execute` indirectly writes to field `$T1_94.io.helidon.microprofile.faulttolerance.CircuitBreakerHelper.commandData.io.helidon.microprofile.faulttolerance.CircuitBreakerHelper$CommandData.results.[_]` outside of synchronization. + Reporting because this access may occur on a background thread. + +Note that the prefix path $T1_94 has been contaminated during the execution, so the reported race on $T1_94.io.helidon.microprofile.faulttolerance.CircuitBreakerHelper.commandData.io.helidon.microprofile.faulttolerance.CircuitBreakerHelper$CommandData.results.[_] might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object FaultToleranceCommand.execute() + +### Procedure Id: +io.helidon.microprofile.faulttolerance.FaultToleranceCommand.execute():java.lang.Object.6f91f033edc2673e231ef5e0cdf97018 + +### File: +microprofile/fault-tolerance/src/main/java/io/helidon/microprofile/faulttolerance/FaultToleranceCommand.java + +### Key: +FaultToleranceCommand.java|execute|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +0d08804324267f3d22852a495423e3bc + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9191/instruction.md b/inferredbugs-9191/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..341598b75ba80c7cde9ee608921846598c86fb22 --- /dev/null +++ b/inferredbugs-9191/instruction.md @@ -0,0 +1,745 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** openmessaging-storage-dledger +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.rocketmq.dleger.store.file; + +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.concurrent.CopyOnWriteArrayList; +import org.apache.rocketmq.dleger.protocol.DLegerResponseCode; +import org.apache.rocketmq.dleger.utils.PreConditions; +import org.apache.rocketmq.dleger.utils.UtilAll; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MmapFileList { + private static final Logger logger = LoggerFactory.getLogger(MmapFile.class); + + private static final int DELETE_FILES_BATCH_MAX = 10; + + public static final int MIN_BLANK_LEN = 8; + public static final int BLANK_MAGIC_CODE = -1; + + private final String storePath; + + private final int mappedFileSize; + + private final CopyOnWriteArrayList mappedFiles = new CopyOnWriteArrayList(); + + + private long flushedWhere = 0; + private long committedWhere = 0; + + private volatile long storeTimestamp = 0; + + public MmapFileList(final String storePath, int mappedFileSize) { + this.storePath = storePath; + this.mappedFileSize = mappedFileSize; + } + + public boolean checkSelf() { + if (!this.mappedFiles.isEmpty()) { + Iterator iterator = mappedFiles.iterator(); + MmapFile pre = null; + while (iterator.hasNext()) { + MmapFile cur = iterator.next(); + + if (pre != null) { + if (cur.getFileFromOffset() - pre.getFileFromOffset() != this.mappedFileSize) { + logger.error("[BUG]The mappedFile queue's data is damaged, the adjacent mappedFile's offset don't match pre file {}, cur file {}", + pre.getFileName(), cur.getFileName()); + return false; + } + } + pre = cur; + } + } + return true; + } + + public MmapFile getMappedFileByTime(final long timestamp) { + Object[] mfs = this.copyMappedFiles(); + + if (null == mfs) + return null; + + for (int i = 0; i < mfs.length; i++) { + MmapFile mappedFile = (MmapFile) mfs[i]; + if (mappedFile.getLastModifiedTimestamp() >= timestamp) { + return mappedFile; + } + } + + return (MmapFile) mfs[mfs.length - 1]; + } + + private Object[] copyMappedFiles() { + if (this.mappedFiles.size() <= 0) { + return null; + } + return this.mappedFiles.toArray(); + } + + public void truncateOffset(long offset) { + Object[] mfs = this.copyMappedFiles(); + if (mfs == null) { + return; + } + List willRemoveFiles = new ArrayList(); + + for (int i = 0; i < mfs.length; i++) { + MmapFile file = (MmapFile)mfs[i]; + long fileTailOffset = file.getFileFromOffset() + this.mappedFileSize; + if (fileTailOffset > offset) { + if (offset >= file.getFileFromOffset()) { + file.setWrotePosition((int) (offset % this.mappedFileSize)); + file.setCommittedPosition((int) (offset % this.mappedFileSize)); + file.setFlushedPosition((int) (offset % this.mappedFileSize)); + } else { + file.destroy(1000); + willRemoveFiles.add(file); + } + } + } + + this.deleteExpiredFile(willRemoveFiles); + } + + + public void resetOffset(long offset) { + Object[] mfs = this.copyMappedFiles(); + if (mfs == null) { + return; + } + List willRemoveFiles = new ArrayList(); + + for (int i = mfs.length - 1; i >= 0; i--) { + MmapFile file = (MmapFile)mfs[i]; + long fileTailOffset = file.getFileFromOffset() + this.mappedFileSize; + if (file.getFileFromOffset() <= offset) { + if (offset < fileTailOffset) { + file.setStartPosition((int) (offset % this.mappedFileSize)); + } else { + file.destroy(1000); + willRemoveFiles.add(file); + } + } + } + + this.deleteExpiredFile(willRemoveFiles); + } + + public void updateWherePosition(long wherePosition) { + if (wherePosition > getMaxWrotePosition()) { + logger.warn("[UpdateWherePosition] wherePosition {} > maxWrotePosition {}", wherePosition, getMaxWrotePosition()); + return; + } + this.setFlushedWhere(wherePosition); + this.setCommittedWhere(wherePosition); + } + + public long append(byte[] data) { + return append(data, 0, data.length); + } + + public long append(byte[] data, int pos, int len) { + return append(data, pos, len, true); + } + + public long append(byte[] data, boolean useBlank) { + return append(data, 0, data.length, useBlank); + } + + public long append(byte[] data, int pos, int len, boolean useBlank) { + MmapFile mappedFile = getLastMappedFile(); + if (null == mappedFile || mappedFile.isFull()) { + mappedFile = getLastMappedFile(0); + } + if (null == mappedFile) { + logger.error("Create mapped file for {}", storePath); + return -1; + } + int blank = useBlank ? MIN_BLANK_LEN : 0; + if (len + blank > mappedFile.getFileSize() - mappedFile.getWrotePosition()) { + if (blank < MIN_BLANK_LEN) { + logger.error("Blank {} should ge {}", blank, MIN_BLANK_LEN); + return -1; + } else { + ByteBuffer byteBuffer = ByteBuffer.allocate(mappedFile.getFileSize() - mappedFile.getWrotePosition()); + byteBuffer.putInt(BLANK_MAGIC_CODE); + byteBuffer.putInt(mappedFile.getFileSize() - mappedFile.getWrotePosition()); + if (mappedFile.appendMessage(byteBuffer.array())) { + //need to set the wrote position + mappedFile.setWrotePosition(mappedFile.getFileSize()); + } else { + logger.error("Append blank error for {}", storePath); + return -1; + } + mappedFile = getLastMappedFile(0); + if (null == mappedFile) { + logger.error("Create mapped file for {}", storePath); + return -1; + } + } + } + long currPosition = mappedFile.getFileFromOffset() + mappedFile.getWrotePosition(); + if (!mappedFile.appendMessage(data, pos, len)) { + logger.error("Append error for {}", storePath); + return -1; + } + return currPosition; + } + + + public SelectMmapBufferResult getData(final long offset, final int size) { + MmapFile mappedFile = findMappedFileByOffset(offset, offset == 0); + if (mappedFile != null) { + int pos = (int) (offset % mappedFileSize); + return mappedFile.selectMappedBuffer(pos, size); + } + return null; + } + + public SelectMmapBufferResult getData(final long offset) { + MmapFile mappedFile = findMappedFileByOffset(offset, offset == 0); + if (mappedFile != null) { + int pos = (int) (offset % mappedFileSize); + return mappedFile.selectMappedBuffer(pos); + } + return null; + } + + + void deleteExpiredFile(List files) { + + if (!files.isEmpty()) { + + Iterator iterator = files.iterator(); + while (iterator.hasNext()) { + MmapFile cur = iterator.next(); + if (!this.mappedFiles.contains(cur)) { + iterator.remove(); + logger.info("This mappedFile {} is not contained by mappedFiles, so skip it.", cur.getFileName()); + } + } + + try { + if (!this.mappedFiles.removeAll(files)) { + logger.error("deleteExpiredFile remove failed."); + } + } catch (Exception e) { + logger.error("deleteExpiredFile has exception.", e); + } + } + } + + public boolean load() { + File dir = new File(this.storePath); + File[] files = dir.listFiles(); + if (files != null) { + // ascending order + Arrays.sort(files); + for (File file : files) { + + if (file.length() != this.mappedFileSize) { + logger.warn(file + "\t" + file.length() + + " length not matched message store config value, ignore it"); + return true; + } + try { + MmapFile mappedFile = new DefaultMmapFile(file.getPath(), mappedFileSize); + + mappedFile.setWrotePosition(this.mappedFileSize); + mappedFile.setFlushedPosition(this.mappedFileSize); + mappedFile.setCommittedPosition(this.mappedFileSize); + this.mappedFiles.add(mappedFile); + logger.info("load " + file.getPath() + " OK"); + } catch (IOException e) { + logger.error("load file " + file + " error", e); + return false; + } + } + } + + return true; + } + + + public MmapFile getLastMappedFile(final long startOffset, boolean needCreate) { + long createOffset = -1; + MmapFile mappedFileLast = getLastMappedFile(); + + if (mappedFileLast == null) { + createOffset = startOffset - (startOffset % this.mappedFileSize); + } else if (mappedFileLast.isFull()) { + createOffset = mappedFileLast.getFileFromOffset() + this.mappedFileSize; + } + + if (createOffset != -1 && needCreate) { + String nextFilePath = this.storePath + File.separator + UtilAll.offset2FileName(createOffset); + MmapFile mappedFile = null; + try { + mappedFile = new DefaultMmapFile(nextFilePath, this.mappedFileSize); + } catch (IOException e) { + logger.error("create mappedFile exception", e); + } + + if (mappedFile != null) { + if (this.mappedFiles.isEmpty()) { + mappedFile.setFirstCreateInQueue(true); + } + this.mappedFiles.add(mappedFile); + } + + return mappedFile; + } + + return mappedFileLast; + } + + public MmapFile getLastMappedFile(final long startOffset) { + return getLastMappedFile(startOffset, true); + } + + public MmapFile getLastMappedFile() { + MmapFile mappedFileLast = null; + + while (!this.mappedFiles.isEmpty()) { + try { + mappedFileLast = this.mappedFiles.get(this.mappedFiles.size() - 1); + break; + } catch (IndexOutOfBoundsException e) { + //continue; + } catch (Exception e) { + logger.error("getLastMappedFile has exception.", e); + break; + } + } + + return mappedFileLast; + } + + + + public long getMinOffset() { + MmapFile mmapFile = getFirstMappedFile(); + if (mmapFile != null) { + return mmapFile.getFileFromOffset() + mmapFile.getStartPosition(); + } + return 0; + } + + public long getMaxReadPosition() { + MmapFile mappedFile = getLastMappedFile(); + if (mappedFile != null) { + return mappedFile.getFileFromOffset() + mappedFile.getReadPosition(); + } + return 0; + } + + public long getMaxWrotePosition() { + MmapFile mappedFile = getLastMappedFile(); + if (mappedFile != null) { + return mappedFile.getFileFromOffset() + mappedFile.getWrotePosition(); + } + return 0; + } + + public long remainHowManyDataToCommit() { + return getMaxWrotePosition() - committedWhere; + } + + public long remainHowManyDataToFlush() { + return getMaxReadPosition() - flushedWhere; + } + + public void deleteLastMappedFile() { + MmapFile lastMappedFile = getLastMappedFile(); + if (lastMappedFile != null) { + lastMappedFile.destroy(1000); + this.mappedFiles.remove(lastMappedFile); + logger.info("on recover, destroy a logic mapped file " + lastMappedFile.getFileName()); + + } + } + + public int deleteExpiredFileByTime(final long expiredTime, + final int deleteFilesInterval, + final long intervalForcibly, + final boolean cleanImmediately) { + Object[] mfs = this.copyMappedFiles(); + + if (null == mfs) + return 0; + + int mfsLength = mfs.length - 1; + int deleteCount = 0; + List files = new ArrayList(); + if (null != mfs) { + for (int i = 0; i < mfsLength; i++) { + MmapFile mappedFile = (MmapFile) mfs[i]; + long liveMaxTimestamp = mappedFile.getLastModifiedTimestamp() + expiredTime; + if (System.currentTimeMillis() >= liveMaxTimestamp || cleanImmediately) { + if (mappedFile.destroy(intervalForcibly)) { + files.add(mappedFile); + deleteCount++; + + if (files.size() >= DELETE_FILES_BATCH_MAX) { + break; + } + + if (deleteFilesInterval > 0 && (i + 1) < mfsLength) { + try { + Thread.sleep(deleteFilesInterval); + } catch (InterruptedException e) { + } + } + } else { + break; + } + } else { + //avoid deleting files in the middle + break; + } + } + } + + deleteExpiredFile(files); + + return deleteCount; + } + + public int deleteExpiredFileByOffset(long offset, int unitSize) { + Object[] mfs = this.copyMappedFiles(); + + List files = new ArrayList(); + int deleteCount = 0; + if (null != mfs) { + + int mfsLength = mfs.length - 1; + + for (int i = 0; i < mfsLength; i++) { + boolean destroy; + MmapFile mappedFile = (MmapFile) mfs[i]; + SelectMmapBufferResult result = mappedFile.selectMappedBuffer(this.mappedFileSize - unitSize); + if (result != null) { + long maxOffsetInLogicQueue = result.getByteBuffer().getLong(); + result.release(); + destroy = maxOffsetInLogicQueue < offset; + if (destroy) { + logger.info("physic min offset " + offset + ", logics in current mappedFile max offset " + + maxOffsetInLogicQueue + ", delete it"); + } + } else if (!mappedFile.isAvailable()) { // Handle hanged file. + logger.warn("Found a hanged consume queue file, attempting to delete it."); + destroy = true; + } else { + logger.warn("this being not executed forever."); + break; + } + + if (destroy && mappedFile.destroy(1000 * 60)) { + files.add(mappedFile); + deleteCount++; + } else { + break; + } + } + } + + deleteExpiredFile(files); + + return deleteCount; + } + + public boolean flush(final int flushLeastPages) { + boolean result = true; + MmapFile mappedFile = this.findMappedFileByOffset(this.flushedWhere, this.flushedWhere == 0); + if (mappedFile != null) { + int offset = mappedFile.flush(flushLeastPages); + long where = mappedFile.getFileFromOffset() + offset; + result = where == this.flushedWhere; + this.flushedWhere = where; + } + + return result; + } + + public boolean commit(final int commitLeastPages) { + boolean result = true; + MmapFile mappedFile = this.findMappedFileByOffset(this.committedWhere, this.committedWhere == 0); + if (mappedFile != null) { + int offset = mappedFile.commit(commitLeastPages); + long where = mappedFile.getFileFromOffset() + offset; + result = where == this.committedWhere; + this.committedWhere = where; + } + + return result; + } + + /** + * Finds a mapped file by offset. + * + * @param offset Offset. + * @param returnFirstOnNotFound If the mapped file is not found, then return the first one. + * @return Mapped file or null (when not found and returnFirstOnNotFound is false). + */ + public MmapFile findMappedFileByOffset(final long offset, final boolean returnFirstOnNotFound) { + try { + MmapFile firstMappedFile = this.getFirstMappedFile(); + MmapFile lastMappedFile = this.getLastMappedFile(); + if (firstMappedFile != null && lastMappedFile != null) { + if (offset < firstMappedFile.getFileFromOffset() || offset >= lastMappedFile.getFileFromOffset() + this.mappedFileSize) { + logger.warn("Offset not matched. Request offset: {}, firstOffset: {}, lastOffset: {}, mappedFileSize: {}, mappedFiles count: {}", + offset, + firstMappedFile.getFileFromOffset(), + lastMappedFile.getFileFromOffset() + this.mappedFileSize, + this.mappedFileSize, + this.mappedFiles.size()); + } else { + int index = (int) ((offset / this.mappedFileSize) - (firstMappedFile.getFileFromOffset() / this.mappedFileSize)); + MmapFile targetFile = null; + try { + targetFile = this.mappedFiles.get(index); + } catch (Exception ignored) { + } + + if (targetFile != null && offset >= targetFile.getFileFromOffset() + && offset < targetFile.getFileFromOffset() + this.mappedFileSize) { + return targetFile; + } + + logger.warn("Offset is matched, but get file failed, maybe the file number is changed. Request offset: {}, firstOffset: {}, lastOffset: {}, mappedFileSize: {}, mappedFiles count: {}", + offset, + firstMappedFile.getFileFromOffset(), + lastMappedFile.getFileFromOffset() + this.mappedFileSize, + this.mappedFileSize, + this.mappedFiles.size()); + + for (MmapFile tmpMappedFile : this.mappedFiles) { + if (offset >= tmpMappedFile.getFileFromOffset() + && offset < tmpMappedFile.getFileFromOffset() + this.mappedFileSize) { + return tmpMappedFile; + } + } + } + + if (returnFirstOnNotFound) { + return firstMappedFile; + } + } + } catch (Exception e) { + logger.error("findMappedFileByOffset Exception", e); + } + + return null; + } + + public MmapFile getFirstMappedFile() { + MmapFile mappedFileFirst = null; + + if (!this.mappedFiles.isEmpty()) { + try { + mappedFileFirst = this.mappedFiles.get(0); + } catch (IndexOutOfBoundsException e) { + //ignore + } catch (Exception e) { + logger.error("getFirstMappedFile has exception.", e); + } + } + + return mappedFileFirst; + } + + public MmapFile findMappedFileByOffset(final long offset) { + return findMappedFileByOffset(offset, false); + } + + public long getMappedMemorySize() { + long size = 0; + + Object[] mfs = this.copyMappedFiles(); + if (mfs != null) { + for (Object mf : mfs) { + if (((ReferenceResource) mf).isAvailable()) { + size += this.mappedFileSize; + } + } + } + + return size; + } + + public boolean retryDeleteFirstFile(final long intervalForcibly) { + MmapFile mappedFile = this.getFirstMappedFile(); + if (mappedFile != null) { + if (!mappedFile.isAvailable()) { + logger.warn("the mappedFile was destroyed once, but still alive, " + mappedFile.getFileName()); + boolean result = mappedFile.destroy(intervalForcibly); + if (result) { + logger.info("the mappedFile re delete OK, " + mappedFile.getFileName()); + List tmpFiles = new ArrayList(); + tmpFiles.add(mappedFile); + this.deleteExpiredFile(tmpFiles); + } else { + logger.warn("the mappedFile re delete failed, " + mappedFile.getFileName()); + } + + return result; + } + } + + return false; + } + + public void shutdown(final long intervalForcibly) { + for (MmapFile mf : this.mappedFiles) { + mf.shutdown(intervalForcibly); + } + } + + public void destroy() { + for (MmapFile mf : this.mappedFiles) { + mf.destroy(1000 * 3); + } + this.mappedFiles.clear(); + this.flushedWhere = 0; + + // delete parent directory + File file = new File(storePath); + if (file.isDirectory()) { + file.delete(); + } + } + + public boolean rebuildWithPos(long pos) { + truncateOffset(-1); + getLastMappedFile(pos); + truncateOffset(pos); + resetOffset(pos); + return pos == getMaxWrotePosition() && pos == getMinOffset(); + } + + + public long getFlushedWhere() { + return flushedWhere; + } + + public void setFlushedWhere(long flushedWhere) { + this.flushedWhere = flushedWhere; + } + + public long getStoreTimestamp() { + return storeTimestamp; + } + + public List getMappedFiles() { + return mappedFiles; + } + + public int getMappedFileSize() { + return mappedFileSize; + } + + public long getCommittedWhere() { + return committedWhere; + } + + public void setCommittedWhere(final long committedWhere) { + this.committedWhere = committedWhere; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.RandomAccessFile` acquired by call to `getLastMappedFile(...)` at line 175 is not released after line 205. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +long MmapFileList.append(byte[],int,int,boolean) + +### Procedure Id: +org.apache.rocketmq.dleger.store.file.MmapFileList.append(byte[],int,int,boolean):long.1d46d4bcc006515160be196b1b22c8b0 + +### File: +src/main/java/org/apache/rocketmq/dleger/store/file/MmapFileList.java + +### Key: +MmapFileList.java|append|RESOURCE_LEAK + +### Node Key: +d3122034bdd2343473bf0b6247309efd + +### Hash: +94ca6b1442ade8724847f17abeecc70a + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9196/instruction.md b/inferredbugs-9196/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d4a30017f1892c23aeb1c281cfeacfb7668440af --- /dev/null +++ b/inferredbugs-9196/instruction.md @@ -0,0 +1,397 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** openmessaging-storage-dledger +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.rocketmq.dleger.store.file; + +import java.nio.ByteBuffer; +import java.util.List; +import org.apache.rocketmq.dleger.DLegerConfig; +import org.apache.rocketmq.dleger.entry.DLegerEntry; +import org.apache.rocketmq.dleger.MemberState; +import org.apache.rocketmq.dleger.entry.DLegerEntryCoder; +import org.apache.rocketmq.dleger.exception.DLegerException; +import org.apache.rocketmq.dleger.store.DLegerStore; +import org.apache.rocketmq.dleger.utils.PreConditions; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DLegerMmapFileStore extends DLegerStore { + + private static Logger logger = LoggerFactory.getLogger(DLegerMmapFileStore.class); + + public static final int MAGIC_1 = 1; + public static final int CURRENT_MAGIC = MAGIC_1; + + public static final int INDEX_NUIT_SIZE = 32; + + private long legerBeginIndex = -1; + private long legerEndIndex = -1; + private long committedIndex = -1; + private long legerEndTerm; + + private DLegerConfig dLegerConfig; + private MemberState memberState; + + private MmapFileQueue dataFileQueue; + private MmapFileQueue indexFileQueue; + + private ThreadLocal localEntryBuffer; + private ThreadLocal localIndexBuffer; + + + public DLegerMmapFileStore(DLegerConfig dLegerConfig, MemberState memberState) { + this.dLegerConfig = dLegerConfig; + this.memberState = memberState; + this.dataFileQueue = new MmapFileQueue(dLegerConfig.getDataStorePath(), dLegerConfig.getMappedFileSizeForEntryData()); + this.indexFileQueue = new MmapFileQueue(dLegerConfig.getIndexStorePath(), dLegerConfig.getMappedFileSizeForEntryIndex()); + localEntryBuffer = ThreadLocal.withInitial(() -> ByteBuffer.allocate(4 * 1024 * 1024)); + localIndexBuffer = ThreadLocal.withInitial(() -> ByteBuffer.allocate(INDEX_NUIT_SIZE * 2)); + } + + + public void startup() { + this.dataFileQueue.load(); + this.indexFileQueue.load(); + PreConditions.check(dataFileQueue.checkSelf(), DLegerException.Code.DISK_ERROR, "check data file order failed before recovery"); + PreConditions.check(indexFileQueue.checkSelf(), DLegerException.Code.DISK_ERROR, "check index file order failed before recovery"); + recover(); + PreConditions.check(dataFileQueue.checkSelf(), DLegerException.Code.DISK_ERROR, "check data file order failed after recovery"); + PreConditions.check(indexFileQueue.checkSelf(), DLegerException.Code.DISK_ERROR, "check index file order failed after recovery"); + } + + public void shutdown() { + this.dataFileQueue.flush(0); + this.indexFileQueue.flush(0); + } + + + public long getWritePos() { + return dataFileQueue.getMaxWrotePosition(); + } + public long getFlushPos() { + return dataFileQueue.getFlushedWhere(); + } + public void flush() { + this.dataFileQueue.flush(0); + this.indexFileQueue.flush(0); + } + + public void recover() { + final List mappedFiles = this.dataFileQueue.getMappedFiles(); + if (mappedFiles.isEmpty()) { + this.indexFileQueue.updateWherePosition(0); + this.indexFileQueue.truncateDirtyFiles(0); + return; + } + int index = mappedFiles.size() - 3; + if (index < 0) { + index = 0; + } + + long firstEntryIndex = -1; + for (int i = index; i >= 0; i--) { + index = i; + MmapFile mappedFile = mappedFiles.get(index); + ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); + try { + int magic = byteBuffer.getInt(); + int size = byteBuffer.getInt(); + long entryIndex = byteBuffer.getLong(); + long entryTerm = byteBuffer.get(); + PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic); + PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); + + SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); + PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); + indexSbr.release(); + ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); + int magicFromIndex = indexByteBuffer.getInt(); + long posFromIndex = indexByteBuffer.getLong(); + int sizeFromIndex = indexByteBuffer.getInt(); + long indexFromIndex = indexByteBuffer.getLong(); + long termFromIndex = indexByteBuffer.get(); + PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); + PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); + PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); + PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); + PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); + firstEntryIndex = entryIndex; + break; + } catch (Throwable t) { + logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t); + } + } + + MmapFile mappedFile = mappedFiles.get(index); + ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); + logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName()); + long lastEntryIndex = -1; + long lastEntryTerm = -1; + long processOffset = mappedFile.getFileFromOffset(); + boolean needWriteIndex = false; + while (true) { + try { + int relativePos = byteBuffer.position(); + long absolutePos = mappedFile.getFileFromOffset() + relativePos; + int magic = byteBuffer.getInt(); + if (magic == MmapFileQueue.BLANK_MAGIC_CODE) { + processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize(); + index++; + if (index >= mappedFiles.size()) { + logger.info("Recover data file over, the last file {}", mappedFile.getFileName()); + break; + } else { + mappedFile = mappedFiles.get(index); + byteBuffer = mappedFile.sliceByteBuffer(); + processOffset = mappedFile.getFileFromOffset(); + logger.info("Trying to recover index file {}", mappedFile.getFileName()); + continue; + } + } + + int size = byteBuffer.getInt(); + long entryIndex = byteBuffer.getLong(); + long entryTerm = byteBuffer.get(); + byteBuffer.position(relativePos + size); + + String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm); + PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC)); + if (lastEntryIndex != -1) { + PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex)); + } + PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm)); + PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); + if (!needWriteIndex) { + try { + SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); + PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); + indexSbr.release(); + ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); + int magicFromIndex = indexByteBuffer.getInt(); + long posFromIndex = indexByteBuffer.getLong(); + int sizeFromIndex = indexByteBuffer.getInt(); + long indexFromIndex = indexByteBuffer.getLong(); + long termFromIndex = indexByteBuffer.get(); + PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); + PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); + PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); + PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); + PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); + } catch (Exception e) { + logger.warn("Compare data to index failed {}", mappedFile.getFileName()); + indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE); + if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) { + logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE); + indexFileQueue.truncateDirtyFiles(0); + } + if (indexFileQueue.getMappedFiles().isEmpty()) { + indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE); + } + needWriteIndex = true; + } + } + if (needWriteIndex) { + ByteBuffer indexBuffer = localIndexBuffer.get(); + DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer); + long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); + PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex)); + } + lastEntryIndex = entryIndex; + lastEntryTerm = entryTerm; + processOffset += size; + } catch (Throwable t) { + logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t); + break; + } + } + logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset); + legerEndIndex = lastEntryIndex; + legerEndTerm = lastEntryTerm; + if (lastEntryIndex != -1) { + DLegerEntry entry = get(lastEntryIndex); + PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry"); + PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex)); + //get leger begin index + ByteBuffer tmpBuffer = dataFileQueue.getFirstMappedFile().sliceByteBuffer(); + tmpBuffer.getInt(); //magic + tmpBuffer.getInt(); //size + legerBeginIndex = byteBuffer.getLong(); + } else { + processOffset = 0; + } + this.dataFileQueue.updateWherePosition(processOffset); + this.dataFileQueue.truncateDirtyFiles(processOffset); + long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE; + this.indexFileQueue.updateWherePosition(indexProcessOffset); + this.indexFileQueue.truncateDirtyFiles(indexProcessOffset); + return; + } + + @Override + public long appendAsLeader(DLegerEntry entry) { + PreConditions.check(memberState.isLeader(), DLegerException.Code.NOT_LEADER, null, memberState.getLeaderId()); + ByteBuffer dataBuffer = localEntryBuffer.get(); + ByteBuffer indexBuffer = localIndexBuffer.get(); + DLegerEntryCoder.encode(entry, dataBuffer); + int entrySize = dataBuffer.remaining(); + synchronized (memberState) { + //TODO handle disk error + long nextIndex = legerEndIndex + 1; + PreConditions.check(memberState.isLeader(), DLegerException.Code.NOT_LEADER, null, memberState.getLeaderId()); + entry.setIndex(nextIndex); + entry.setTerm(memberState.currTerm()); + entry.setMagic(CURRENT_MAGIC); + DLegerEntryCoder.setIndexTerm(dataBuffer, nextIndex, memberState.currTerm(), CURRENT_MAGIC); + long dataPos = dataFileQueue.append(dataBuffer.array(), 0, dataBuffer.remaining()); + PreConditions.check(dataPos != -1, DLegerException.Code.DISK_ERROR, null); + DLegerEntryCoder.encodeIndex(dataPos, entrySize, CURRENT_MAGIC, nextIndex, memberState.currTerm(), indexBuffer); + long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); + PreConditions.check(indexPos == entry.getIndex() * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, null); + if (logger.isDebugEnabled()) { + logger.info("[{}] Append as Leader {} {}", memberState.getSelfId(), entry.getIndex(), entry.getBody().length); + } + legerEndIndex++; + committedIndex++; + legerEndTerm = memberState.currTerm(); + if (legerBeginIndex == -1) { + legerBeginIndex = legerEndIndex; + } + return legerEndIndex; + } + } + + + @Override + public long appendAsFollower(DLegerEntry entry, long leaderTerm, String leaderId) { + PreConditions.check(memberState.isFollower(), DLegerException.Code.NOT_FOLLOWER, null, memberState.getLeaderId()); + ByteBuffer dataBuffer = localEntryBuffer.get(); + ByteBuffer indexBuffer = localIndexBuffer.get(); + DLegerEntryCoder.encode(entry, dataBuffer); + int entrySize = dataBuffer.remaining(); + synchronized(memberState) { + long nextIndex = legerEndIndex + 1; + PreConditions.check(nextIndex == entry.getIndex(), DLegerException.Code.UNCONSISTENCT_INDEX, null, memberState.getLeaderId()); + PreConditions.check(memberState.isFollower(), DLegerException.Code.NOT_FOLLOWER, null, memberState.getLeaderId()); + PreConditions.check(leaderTerm == memberState.currTerm(), DLegerException.Code.UNCONSISTENCT_TERM, null, memberState.getLeaderId()); + PreConditions.check(leaderId.equals(memberState.getLeaderId()), DLegerException.Code.UNCONSISTENCT_LEADER, null, memberState.getLeaderId()); + long dataPos = dataFileQueue.append(dataBuffer.array(), 0, dataBuffer.remaining()); + PreConditions.check(dataPos != -1, DLegerException.Code.DISK_ERROR, null); + DLegerEntryCoder.encodeIndex(dataPos, entrySize, entry.getMagic(), entry.getIndex(), entry.getTerm(), indexBuffer); + long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); + PreConditions.check(indexPos == entry.getIndex() * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, null); + legerEndTerm = memberState.currTerm(); + legerEndIndex = entry.getIndex(); + committedIndex = entry.getIndex(); + if (legerBeginIndex == -1) { + legerBeginIndex = legerEndIndex; + } + return entry.getIndex(); + } + + } + + public long getLegerEndIndex() { + return legerEndIndex; + } + + @Override public long getLegerBeginIndex() { + return legerBeginIndex; + } + + @Override + public DLegerEntry get(Long index) { + PreConditions.check(index <= legerEndIndex && index >= legerBeginIndex, DLegerException.Code.INDEX_OUT_OF_RANGE, String.format("%d should between %d-%d", index, legerBeginIndex, legerEndIndex), memberState.getLeaderId()); + SelectMmapBufferResult indexSbr = indexFileQueue.getData(index * INDEX_NUIT_SIZE, INDEX_NUIT_SIZE); + PreConditions.check(indexSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); + indexSbr.getByteBuffer().getInt(); //magic + long pos = indexSbr.getByteBuffer().getLong(); + int size = indexSbr.getByteBuffer().getInt(); + indexSbr.release(); + SelectMmapBufferResult dataSbr = dataFileQueue.getData(pos, size); + PreConditions.check(dataSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); + DLegerEntry dLegerEntry = DLegerEntryCoder.decode(dataSbr.getByteBuffer()); + dataSbr.release(); + return dLegerEntry; + } + + + public long getCommittedIndex() { + return committedIndex; + } + + public long getLegerEndTerm() { + return legerEndTerm; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.apache.rocketmq.dleger.store.file.DLegerMmapFileStore.recover` writes to field `this.org.apache.rocketmq.dleger.store.file.DLegerMmapFileStore.legerBeginIndex` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DLegerMmapFileStore.recover() + +### Procedure Id: +org.apache.rocketmq.dleger.store.file.DLegerMmapFileStore.recover():void.18199b85df36c85ee1c81733e23bd25b + +### File: +src/main/java/org/apache/rocketmq/dleger/store/file/DLegerMmapFileStore.java + +### Key: +DLegerMmapFileStore.java|recover|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +2303b18c506f7c6cb532311da68dec79 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9212/instruction.md b/inferredbugs-9212/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fa7a2aad13cc37325f1f507e56f1686e0532cbd0 --- /dev/null +++ b/inferredbugs-9212/instruction.md @@ -0,0 +1,3032 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-jraft +**Bug ID:** 28 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.jraft.core; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alipay.sofa.jraft.Closure; +import com.alipay.sofa.jraft.FSMCaller; +import com.alipay.sofa.jraft.JRaftServiceFactory; +import com.alipay.sofa.jraft.Node; +import com.alipay.sofa.jraft.NodeManager; +import com.alipay.sofa.jraft.ReadOnlyService; +import com.alipay.sofa.jraft.ReplicatorGroup; +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.closure.CatchUpClosure; +import com.alipay.sofa.jraft.closure.ClosureQueue; +import com.alipay.sofa.jraft.closure.ClosureQueueImpl; +import com.alipay.sofa.jraft.closure.ReadIndexClosure; +import com.alipay.sofa.jraft.closure.SynchronizedClosure; +import com.alipay.sofa.jraft.conf.Configuration; +import com.alipay.sofa.jraft.conf.ConfigurationEntry; +import com.alipay.sofa.jraft.conf.ConfigurationManager; +import com.alipay.sofa.jraft.entity.Ballot; +import com.alipay.sofa.jraft.entity.EnumOutter; +import com.alipay.sofa.jraft.entity.LeaderChangeContext; +import com.alipay.sofa.jraft.entity.LogEntry; +import com.alipay.sofa.jraft.entity.LogId; +import com.alipay.sofa.jraft.entity.NodeId; +import com.alipay.sofa.jraft.entity.PeerId; +import com.alipay.sofa.jraft.entity.RaftOutter; +import com.alipay.sofa.jraft.entity.Task; +import com.alipay.sofa.jraft.entity.UserLog; +import com.alipay.sofa.jraft.error.LogIndexOutOfBoundsException; +import com.alipay.sofa.jraft.error.LogNotFoundException; +import com.alipay.sofa.jraft.error.RaftError; +import com.alipay.sofa.jraft.error.RaftException; +import com.alipay.sofa.jraft.option.BallotBoxOptions; +import com.alipay.sofa.jraft.option.BootstrapOptions; +import com.alipay.sofa.jraft.option.FSMCallerOptions; +import com.alipay.sofa.jraft.option.LogManagerOptions; +import com.alipay.sofa.jraft.option.NodeOptions; +import com.alipay.sofa.jraft.option.RaftMetaStorageOptions; +import com.alipay.sofa.jraft.option.RaftOptions; +import com.alipay.sofa.jraft.option.ReadOnlyOption; +import com.alipay.sofa.jraft.option.ReadOnlyServiceOptions; +import com.alipay.sofa.jraft.option.ReplicatorGroupOptions; +import com.alipay.sofa.jraft.option.SnapshotExecutorOptions; +import com.alipay.sofa.jraft.rpc.RaftClientService; +import com.alipay.sofa.jraft.rpc.RaftServerService; +import com.alipay.sofa.jraft.rpc.RpcRequestClosure; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.ReadIndexRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.ReadIndexResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.RequestVoteRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.RequestVoteResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowResponse; +import com.alipay.sofa.jraft.rpc.RpcResponseClosure; +import com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter; +import com.alipay.sofa.jraft.rpc.RpcResponseFactory; +import com.alipay.sofa.jraft.rpc.impl.core.BoltRaftClientService; +import com.alipay.sofa.jraft.storage.LogManager; +import com.alipay.sofa.jraft.storage.LogStorage; +import com.alipay.sofa.jraft.storage.RaftMetaStorage; +import com.alipay.sofa.jraft.storage.SnapshotExecutor; +import com.alipay.sofa.jraft.storage.impl.LogManagerImpl; +import com.alipay.sofa.jraft.storage.snapshot.SnapshotExecutorImpl; +import com.alipay.sofa.jraft.util.DisruptorBuilder; +import com.alipay.sofa.jraft.util.DisruptorMetricSet; +import com.alipay.sofa.jraft.util.JRaftServiceLoader; +import com.alipay.sofa.jraft.util.JRaftSignalHandler; +import com.alipay.sofa.jraft.util.LogExceptionHandler; +import com.alipay.sofa.jraft.util.NamedThreadFactory; +import com.alipay.sofa.jraft.util.OnlyForTest; +import com.alipay.sofa.jraft.util.Platform; +import com.alipay.sofa.jraft.util.RepeatedTimer; +import com.alipay.sofa.jraft.util.Requires; +import com.alipay.sofa.jraft.util.SignalHelper; +import com.alipay.sofa.jraft.util.ThreadHelper; +import com.alipay.sofa.jraft.util.ThreadId; +import com.alipay.sofa.jraft.util.Utils; +import com.google.protobuf.Message; +import com.lmax.disruptor.BlockingWaitStrategy; +import com.lmax.disruptor.EventFactory; +import com.lmax.disruptor.EventHandler; +import com.lmax.disruptor.EventTranslator; +import com.lmax.disruptor.RingBuffer; +import com.lmax.disruptor.dsl.Disruptor; +import com.lmax.disruptor.dsl.ProducerType; + +/** + * The raft replica node implementation. + * + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-03 4:26:51 PM + */ +public class NodeImpl implements Node, RaftServerService { + + private static final Logger LOG = LoggerFactory + .getLogger(NodeImpl.class); + + static { + try { + if (SignalHelper.supportSignal()) { + // TODO support windows signal + if (!Platform.isWindows()) { + final List handlers = JRaftServiceLoader.load(JRaftSignalHandler.class) // + .sort(); + SignalHelper.addSignal(SignalHelper.SIG_USR2, handlers); + } + } + } catch (final Throwable t) { + LOG.error("Fail to add signal.", t); + } + } + + // Max retry times when applying tasks. + private static final int MAX_APPLY_RETRY_TIMES = 3; + + public static final AtomicInteger GLOBAL_NUM_NODES = new AtomicInteger( + 0); + + /** Internal states */ + private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); + protected final Lock writeLock = this.readWriteLock + .writeLock(); + protected final Lock readLock = this.readWriteLock + .readLock(); + private volatile State state; + private volatile CountDownLatch shutdownLatch; + private long currTerm; + private volatile long lastLeaderTimestamp; + private PeerId leaderId = new PeerId(); + private PeerId votedId; + private final Ballot voteCtx = new Ballot(); + private final Ballot prevVoteCtx = new Ballot(); + private ConfigurationEntry conf; + private StopTransferArg stopTransferArg; + /** Raft group and node options and identifier */ + private final String groupId; + private NodeOptions options; + private RaftOptions raftOptions; + private final PeerId serverId; + /** Other services */ + private final ConfigurationCtx confCtx; + private LogStorage logStorage; + private RaftMetaStorage metaStorage; + private ClosureQueue closureQueue; + private ConfigurationManager configManager; + private LogManager logManager; + private FSMCaller fsmCaller; + private BallotBox ballotBox; + private SnapshotExecutor snapshotExecutor; + private ReplicatorGroup replicatorGroup; + private final List shutdownContinuations = new ArrayList<>(); + private RaftClientService rpcService; + private ReadOnlyService readOnlyService; + /** Timers */ + private TimerManager timerManager; + private RepeatedTimer electionTimer; + private RepeatedTimer voteTimer; + private RepeatedTimer stepDownTimer; + private RepeatedTimer snapshotTimer; + private ScheduledFuture transferTimer; + private ThreadId wakingCandidate; + /** Disruptor to run node service */ + private Disruptor applyDisruptor; + private RingBuffer applyQueue; + + /** Metrics*/ + private NodeMetrics metrics; + + private NodeId nodeId; + private JRaftServiceFactory serviceFactory; + + /** ReplicatorStateListeners */ + private final CopyOnWriteArrayList replicatorStateListeners = new CopyOnWriteArrayList<>(); + + /** + * Node service event. + * + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-03 4:29:55 PM + */ + private static class LogEntryAndClosure { + LogEntry entry; + Closure done; + long expectedTerm; + CountDownLatch shutdownLatch; + + public void reset() { + this.entry = null; + this.done = null; + this.expectedTerm = 0; + this.shutdownLatch = null; + } + } + + private static class LogEntryAndClosureFactory implements EventFactory { + + @Override + public LogEntryAndClosure newInstance() { + return new LogEntryAndClosure(); + } + } + + /** + * Event handler. + * + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-03 4:30:07 PM + */ + private class LogEntryAndClosureHandler implements EventHandler { + // task list for batch + private final List tasks = new ArrayList<>(NodeImpl.this.raftOptions.getApplyBatch()); + + @Override + public void onEvent(final LogEntryAndClosure event, final long sequence, final boolean endOfBatch) + throws Exception { + if (event.shutdownLatch != null) { + if (!this.tasks.isEmpty()) { + executeApplyingTasks(this.tasks); + } + final int num = GLOBAL_NUM_NODES.decrementAndGet(); + LOG.info("The number of active nodes decrement to {}.", num); + event.shutdownLatch.countDown(); + return; + } + + this.tasks.add(event); + if (this.tasks.size() >= NodeImpl.this.raftOptions.getApplyBatch() || endOfBatch) { + executeApplyingTasks(this.tasks); + this.tasks.clear(); + } + } + } + + /** + * Configuration commit context. + * + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-03 4:29:38 PM + */ + private static class ConfigurationCtx { + enum Stage { + STAGE_NONE, // none stage + STAGE_CATCHING_UP, // the node is catching-up + STAGE_JOINT, // joint stage + STAGE_STABLE // stable stage + } + + final NodeImpl node; + Stage stage; + int nchanges; + long version; + List newPeers = new ArrayList<>(); + List oldPeers = new ArrayList<>(); + List addingPeers = new ArrayList<>(); + Closure done; + + public ConfigurationCtx(final NodeImpl node) { + super(); + this.node = node; + this.stage = Stage.STAGE_NONE; + this.version = 0; + this.done = null; + } + + /** + * Start change configuration. + */ + void start(final Configuration oldConf, final Configuration newConf, final Closure done) { + if (isBusy()) { + if (done != null) { + Utils.runClosureInThread(done, new Status(RaftError.EBUSY, "Already in busy stage.")); + } + throw new IllegalStateException("Busy stage"); + } + if (this.done != null) { + if (done != null) { + Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "Already have done closure.")); + } + throw new IllegalArgumentException("Already have done closure"); + } + this.done = done; + this.stage = Stage.STAGE_CATCHING_UP; + this.oldPeers = oldConf.listPeers(); + this.newPeers = newConf.listPeers(); + final Configuration adding = new Configuration(); + final Configuration removing = new Configuration(); + newConf.diff(oldConf, adding, removing); + this.nchanges = adding.size() + removing.size(); + if (adding.isEmpty()) { + nextStage(); + return; + } + this.addingPeers = adding.listPeers(); + LOG.info("Adding peers: {}.", this.addingPeers); + for (final PeerId newPeer : this.addingPeers) { + if (!this.node.replicatorGroup.addReplicator(newPeer)) { + LOG.error("Node {} start the replicator failed, peer={}.", this.node.getNodeId(), newPeer); + onCaughtUp(this.version, newPeer, false); + return; + } + final OnCaughtUp caughtUp = new OnCaughtUp(this.node, this.node.currTerm, newPeer, this.version); + final long dueTime = Utils.nowMs() + this.node.options.getElectionTimeoutMs(); + if (!this.node.replicatorGroup.waitCaughtUp(newPeer, this.node.options.getCatchupMargin(), dueTime, + caughtUp)) { + LOG.error("Node {} waitCaughtUp, peer={}.", this.node.getNodeId(), newPeer); + onCaughtUp(this.version, newPeer, false); + return; + } + } + } + + void onCaughtUp(final long version, final PeerId peer, final boolean success) { + if (version != this.version) { + return; + } + Requires.requireTrue(this.stage == Stage.STAGE_CATCHING_UP, "Stage is not in STAGE_CATCHING_UP"); + if (success) { + this.addingPeers.remove(peer); + if (this.addingPeers.isEmpty()) { + nextStage(); + return; + } + return; + } + LOG.warn("Node {} fail to catch up peer {} when trying to change peers from {} to {}.", + this.node.getNodeId(), peer, this.oldPeers, this.newPeers); + reset(new Status(RaftError.ECATCHUP, "Peer %s failed to catch up.", peer)); + } + + void reset() { + reset(null); + } + + void reset(final Status st) { + if (st != null && st.isOk()) { + this.node.stopReplicator(this.newPeers, this.oldPeers); + } else { + this.node.stopReplicator(this.oldPeers, this.newPeers); + } + this.newPeers.clear(); + this.oldPeers.clear(); + this.addingPeers.clear(); + this.version++; + this.stage = Stage.STAGE_NONE; + this.nchanges = 0; + if (this.done != null) { + Utils.runClosureInThread(this.done, st != null ? st : new Status(RaftError.EPERM, + "Leader stepped down.")); + this.done = null; + } + } + + /** + * Invoked when this node becomes the leader, write a configuration change log as the first log. + */ + void flush(final Configuration conf, final Configuration oldConf) { + Requires.requireTrue(!isBusy(), "Flush when busy"); + this.newPeers = conf.listPeers(); + if (oldConf == null || oldConf.isEmpty()) { + this.stage = Stage.STAGE_STABLE; + this.oldPeers = this.newPeers; + } else { + this.stage = Stage.STAGE_JOINT; + this.oldPeers = oldConf.listPeers(); + } + this.node.unsafeApplyConfiguration(conf, oldConf == null || oldConf.isEmpty() ? null : oldConf, true); + } + + void nextStage() { + Requires.requireTrue(isBusy(), "Not in busy stage"); + switch (this.stage) { + case STAGE_CATCHING_UP: + if (this.nchanges > 1) { + this.stage = Stage.STAGE_JOINT; + this.node.unsafeApplyConfiguration(new Configuration(this.newPeers), new Configuration( + this.oldPeers), false); + return; + } + // Skip joint consensus since only one peers has been changed here. Make + // it a one-stage change to be compatible with the legacy + // implementation. + case STAGE_JOINT: + this.stage = Stage.STAGE_STABLE; + this.node.unsafeApplyConfiguration(new Configuration(this.newPeers), null, false); + break; + case STAGE_STABLE: + final boolean shouldStepDown = !this.newPeers.contains(this.node.serverId); + reset(new Status()); + if (shouldStepDown) { + this.node.stepDown(this.node.currTerm, true, new Status(RaftError.ELEADERREMOVED, + "This node was removed.")); + } + break; + case STAGE_NONE: + // noinspection ConstantConditions + Requires.requireTrue(false, "Can't reach here"); + break; + } + } + + boolean isBusy() { + return this.stage != Stage.STAGE_NONE; + } + } + + public NodeImpl() { + this(null, null); + } + + public NodeImpl(final String groupId, final PeerId serverId) { + super(); + if (groupId != null) { + Utils.verifyGroupId(groupId); + } + this.groupId = groupId; + this.serverId = serverId != null ? serverId.copy() : null; + this.state = State.STATE_UNINITIALIZED; + this.currTerm = 0; + updateLastLeaderTimestamp(Utils.monotonicMs()); + this.confCtx = new ConfigurationCtx(this); + this.wakingCandidate = null; + final int num = GLOBAL_NUM_NODES.incrementAndGet(); + LOG.info("The number of active nodes increment to {}.", num); + } + + private boolean initSnapshotStorage() { + if (StringUtils.isEmpty(this.options.getSnapshotUri())) { + LOG.warn("Do not set snapshot uri, ignore initSnapshotStorage."); + return true; + } + this.snapshotExecutor = new SnapshotExecutorImpl(); + final SnapshotExecutorOptions opts = new SnapshotExecutorOptions(); + opts.setUri(this.options.getSnapshotUri()); + opts.setFsmCaller(this.fsmCaller); + opts.setNode(this); + opts.setLogManager(this.logManager); + opts.setAddr(this.serverId != null ? this.serverId.getEndpoint() : null); + opts.setInitTerm(this.currTerm); + opts.setFilterBeforeCopyRemote(this.options.isFilterBeforeCopyRemote()); + // get snapshot throttle + opts.setSnapshotThrottle(this.options.getSnapshotThrottle()); + return this.snapshotExecutor.init(opts); + } + + private boolean initLogStorage() { + Requires.requireNonNull(this.fsmCaller, "Null fsm caller"); + this.logStorage = this.serviceFactory.createLogStorage(this.options.getLogUri(), this.raftOptions); + this.logManager = new LogManagerImpl(); + final LogManagerOptions opts = new LogManagerOptions(); + opts.setLogEntryCodecFactory(this.serviceFactory.createLogEntryCodecFactory()); + opts.setLogStorage(this.logStorage); + opts.setConfigurationManager(this.configManager); + opts.setFsmCaller(this.fsmCaller); + opts.setNodeMetrics(this.metrics); + opts.setDisruptorBufferSize(this.raftOptions.getDisruptorBufferSize()); + opts.setRaftOptions(this.raftOptions); + return this.logManager.init(opts); + } + + private boolean initMetaStorage() { + this.metaStorage = this.serviceFactory.createRaftMetaStorage(this.options.getRaftMetaUri(), this.raftOptions); + RaftMetaStorageOptions opts = new RaftMetaStorageOptions(); + opts.setNode(this); + if (!this.metaStorage.init(opts)) { + LOG.error("Node {} init meta storage failed, uri={}.", this.serverId, this.options.getRaftMetaUri()); + return false; + } + this.currTerm = this.metaStorage.getTerm(); + this.votedId = this.metaStorage.getVotedFor().copy(); + return true; + } + + private void handleSnapshotTimeout() { + this.writeLock.lock(); + try { + if (!this.state.isActive()) { + return; + } + } finally { + this.writeLock.unlock(); + } + // do_snapshot in another thread to avoid blocking the timer thread. + Utils.runInThread(() -> doSnapshot(null)); + } + + private void handleElectionTimeout() { + boolean doUnlock = true; + this.writeLock.lock(); + try { + if (this.state != State.STATE_FOLLOWER) { + return; + } + if (isCurrentLeaderValid()) { + return; + } + resetLeaderId(PeerId.emptyPeer(), new Status(RaftError.ERAFTTIMEDOUT, "Lost connection from leader %s.", + this.leaderId)); + doUnlock = false; + preVote(); + } finally { + if (doUnlock) { + this.writeLock.unlock(); + } + } + } + + private boolean initFSMCaller(final LogId bootstrapId) { + if (this.fsmCaller == null) { + LOG.error("Fail to init fsm caller, null instance, bootstrapId={}.", bootstrapId); + return false; + } + this.closureQueue = new ClosureQueueImpl(); + final FSMCallerOptions opts = new FSMCallerOptions(); + opts.setAfterShutdown(status -> afterShutdown()); + opts.setLogManager(this.logManager); + opts.setFsm(this.options.getFsm()); + opts.setClosureQueue(this.closureQueue); + opts.setNode(this); + opts.setBootstrapId(bootstrapId); + opts.setDisruptorBufferSize(this.raftOptions.getDisruptorBufferSize()); + return this.fsmCaller.init(opts); + } + + private static class BootstrapStableClosure extends LogManager.StableClosure { + + private final SynchronizedClosure done = new SynchronizedClosure(); + + public BootstrapStableClosure() { + super(null); + } + + public Status await() throws InterruptedException { + return this.done.await(); + } + + @Override + public void run(final Status status) { + this.done.run(status); + } + } + + public boolean bootstrap(final BootstrapOptions opts) throws InterruptedException { + if (opts.getLastLogIndex() > 0 && (opts.getGroupConf().isEmpty() || opts.getFsm() == null)) { + LOG.error("Invalid arguments for bootstrap, groupConf={}, fsm={}, lastLogIndex={}.", opts.getGroupConf(), + opts.getFsm(), opts.getLastLogIndex()); + return false; + } + if (opts.getGroupConf().isEmpty()) { + LOG.error("Bootstrapping an empty node makes no sense."); + return false; + } + Requires.requireNonNull(opts.getServiceFactory(), "Null jraft service factory"); + this.serviceFactory = opts.getServiceFactory(); + // Term is not an option since changing it is very dangerous + final long bootstrapLogTerm = opts.getLastLogIndex() > 0 ? 1 : 0; + final LogId bootstrapId = new LogId(opts.getLastLogIndex(), bootstrapLogTerm); + this.options = new NodeOptions(); + this.raftOptions = this.options.getRaftOptions(); + this.metrics = new NodeMetrics(opts.isEnableMetrics()); + this.options.setFsm(opts.getFsm()); + this.options.setLogUri(opts.getLogUri()); + this.options.setRaftMetaUri(opts.getRaftMetaUri()); + this.options.setSnapshotUri(opts.getSnapshotUri()); + + this.configManager = new ConfigurationManager(); + // Create fsmCaller at first as logManager needs it to report error + this.fsmCaller = new FSMCallerImpl(); + + if (!initLogStorage()) { + LOG.error("Fail to init log storage."); + return false; + } + if (!initMetaStorage()) { + LOG.error("Fail to init meta storage."); + return false; + } + if (this.currTerm == 0) { + this.currTerm = 1; + if (!this.metaStorage.setTermAndVotedFor(1, new PeerId())) { + LOG.error("Fail to set term."); + return false; + } + } + + if (opts.getFsm() != null && !initFSMCaller(bootstrapId)) { + LOG.error("Fail to init fsm caller."); + return false; + } + + final LogEntry entry = new LogEntry(EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION); + entry.getId().setTerm(this.currTerm); + entry.setPeers(opts.getGroupConf().listPeers()); + + final List entries = new ArrayList<>(); + entries.add(entry); + + final BootstrapStableClosure bootstrapDone = new BootstrapStableClosure(); + this.logManager.appendEntries(entries, bootstrapDone); + if (!bootstrapDone.await().isOk()) { + LOG.error("Fail to append configuration."); + return false; + } + + if (opts.getLastLogIndex() > 0) { + if (!initSnapshotStorage()) { + LOG.error("Fail to init snapshot storage."); + return false; + } + final SynchronizedClosure snapshotDone = new SynchronizedClosure(); + this.snapshotExecutor.doSnapshot(snapshotDone); + if (!snapshotDone.await().isOk()) { + LOG.error("Fail to save snapshot, status={}.", snapshotDone.getStatus()); + return false; + } + } + + if (this.logManager.getFirstLogIndex() != opts.getLastLogIndex() + 1) { + throw new IllegalStateException("First and last log index mismatch"); + } + if (opts.getLastLogIndex() > 0) { + if (this.logManager.getLastLogIndex() != opts.getLastLogIndex()) { + throw new IllegalStateException("Last log index mismatch"); + } + } else { + if (this.logManager.getLastLogIndex() != opts.getLastLogIndex() + 1) { + throw new IllegalStateException("Last log index mismatch"); + } + } + + return true; + } + + private int heartbeatTimeout(final int electionTimeout) { + return Math.max(electionTimeout / this.raftOptions.getElectionHeartbeatFactor(), 10); + } + + private int randomTimeout(final int timeoutMs) { + return ThreadLocalRandom.current().nextInt(timeoutMs, timeoutMs + this.raftOptions.getMaxElectionDelayMs()); + } + + @Override + public boolean init(final NodeOptions opts) { + Requires.requireNonNull(opts, "Null node options"); + Requires.requireNonNull(opts.getRaftOptions(), "Null raft options"); + Requires.requireNonNull(opts.getServiceFactory(), "Null jraft service factory"); + this.serviceFactory = opts.getServiceFactory(); + this.options = opts; + this.raftOptions = opts.getRaftOptions(); + this.metrics = new NodeMetrics(opts.isEnableMetrics()); + + if (this.serverId.getIp().equals(Utils.IP_ANY)) { + LOG.error("Node can't started from IP_ANY."); + return false; + } + + if (!NodeManager.getInstance().serverExists(this.serverId.getEndpoint())) { + LOG.error("No RPC server attached to, did you forget to call addService?"); + return false; + } + + this.timerManager = new TimerManager(); + if (!this.timerManager.init(this.options.getTimerPoolSize())) { + LOG.error("Fail to init timer manager."); + return false; + } + + // Init timers + this.voteTimer = new RepeatedTimer("JRaft-VoteTimer", this.options.getElectionTimeoutMs()) { + + @Override + protected void onTrigger() { + handleVoteTimeout(); + } + + @Override + protected int adjustTimeout(final int timeoutMs) { + return randomTimeout(timeoutMs); + } + }; + this.electionTimer = new RepeatedTimer("JRaft-ElectionTimer", this.options.getElectionTimeoutMs()) { + + @Override + protected void onTrigger() { + handleElectionTimeout(); + } + + @Override + protected int adjustTimeout(final int timeoutMs) { + return randomTimeout(timeoutMs); + } + }; + this.stepDownTimer = new RepeatedTimer("JRaft-StepDownTimer", this.options.getElectionTimeoutMs() >> 1) { + + @Override + protected void onTrigger() { + handleStepDownTimeout(); + } + }; + this.snapshotTimer = new RepeatedTimer("JRaft-SnapshotTimer", this.options.getSnapshotIntervalSecs() * 1000) { + + @Override + protected void onTrigger() { + handleSnapshotTimeout(); + } + }; + + this.configManager = new ConfigurationManager(); + + this.applyDisruptor = DisruptorBuilder. newInstance() // + .setRingBufferSize(this.raftOptions.getDisruptorBufferSize()) // + .setEventFactory(new LogEntryAndClosureFactory()) // + .setThreadFactory(new NamedThreadFactory("JRaft-NodeImpl-Disruptor-", true)) // + .setProducerType(ProducerType.MULTI) // + .setWaitStrategy(new BlockingWaitStrategy()) // + .build(); + this.applyDisruptor.handleEventsWith(new LogEntryAndClosureHandler()); + this.applyDisruptor.setDefaultExceptionHandler(new LogExceptionHandler(getClass().getSimpleName())); + this.applyQueue = this.applyDisruptor.start(); + if (this.metrics.getMetricRegistry() != null) { + this.metrics.getMetricRegistry().register("jraft-node-impl-disruptor", + new DisruptorMetricSet(this.applyQueue)); + } + + this.fsmCaller = new FSMCallerImpl(); + if (!initLogStorage()) { + LOG.error("Node {} initLogStorage failed.", getNodeId()); + return false; + } + if (!initMetaStorage()) { + LOG.error("Node {} initMetaStorage failed.", getNodeId()); + return false; + } + if (!initFSMCaller(new LogId(0, 0))) { + LOG.error("Node {} initFSMCaller failed.", getNodeId()); + return false; + } + this.ballotBox = new BallotBox(); + final BallotBoxOptions ballotBoxOpts = new BallotBoxOptions(); + ballotBoxOpts.setWaiter(this.fsmCaller); + ballotBoxOpts.setClosureQueue(this.closureQueue); + if (!this.ballotBox.init(ballotBoxOpts)) { + LOG.error("Node {} init ballotBox failed.", getNodeId()); + return false; + } + + if (!initSnapshotStorage()) { + LOG.error("Node {} initSnapshotStorage failed.", getNodeId()); + return false; + } + + final Status st = this.logManager.checkConsistency(); + if (!st.isOk()) { + LOG.error("Node {} is initialized with inconsistent log, status={}.", getNodeId(), st); + return false; + } + this.conf = new ConfigurationEntry(); + this.conf.setId(new LogId()); + // if have log using conf in log, else using conf in options + if (this.logManager.getLastLogIndex() > 0) { + this.conf = this.logManager.checkAndSetConfiguration(this.conf); + } else { + this.conf.setConf(this.options.getInitialConf()); + } + + // TODO RPC service and ReplicatorGroup is in cycle dependent, refactor it + this.replicatorGroup = new ReplicatorGroupImpl(); + this.rpcService = new BoltRaftClientService(this.replicatorGroup); + final ReplicatorGroupOptions rgOpts = new ReplicatorGroupOptions(); + rgOpts.setHeartbeatTimeoutMs(heartbeatTimeout(this.options.getElectionTimeoutMs())); + rgOpts.setElectionTimeoutMs(this.options.getElectionTimeoutMs()); + rgOpts.setLogManager(this.logManager); + rgOpts.setBallotBox(this.ballotBox); + rgOpts.setNode(this); + rgOpts.setRaftRpcClientService(this.rpcService); + rgOpts.setSnapshotStorage(this.snapshotExecutor != null ? this.snapshotExecutor.getSnapshotStorage() : null); + rgOpts.setRaftOptions(this.raftOptions); + rgOpts.setTimerManager(this.timerManager); + + // Adds metric registry to RPC service. + this.options.setMetricRegistry(this.metrics.getMetricRegistry()); + + if (!this.rpcService.init(this.options)) { + LOG.error("Fail to init rpc service."); + return false; + } + this.replicatorGroup.init(new NodeId(this.groupId, this.serverId), rgOpts); + + this.readOnlyService = new ReadOnlyServiceImpl(); + final ReadOnlyServiceOptions rosOpts = new ReadOnlyServiceOptions(); + rosOpts.setFsmCaller(this.fsmCaller); + rosOpts.setNode(this); + rosOpts.setRaftOptions(this.raftOptions); + + if (!this.readOnlyService.init(rosOpts)) { + LOG.error("Fail to init readOnlyService."); + return false; + } + + // set state to follower + this.state = State.STATE_FOLLOWER; + + if (LOG.isInfoEnabled()) { + LOG.info("Node {} init, term={}, lastLogId={}, conf={}, oldConf={}.", getNodeId(), this.currTerm, + this.logManager.getLastLogId(false), this.conf.getConf(), this.conf.getOldConf()); + } + + if (this.snapshotExecutor != null && this.options.getSnapshotIntervalSecs() > 0) { + LOG.debug("Node {} start snapshot timer, term={}.", getNodeId(), this.currTerm); + this.snapshotTimer.start(); + } + + if (!this.conf.isEmpty()) { + stepDown(this.currTerm, false, new Status()); + } + + if (!NodeManager.getInstance().add(this)) { + LOG.error("NodeManager add {} failed.", getNodeId()); + return false; + } + + // Now the raft node is started , have to acquire the writeLock to avoid race + // conditions + this.writeLock.lock(); + if (this.conf.isStable() && this.conf.getConf().size() == 1 && this.conf.getConf().contains(this.serverId)) { + // The group contains only this server which must be the LEADER, trigger + // the timer immediately. + electSelf(); + } else { + this.writeLock.unlock(); + } + + return true; + } + + // should be in writeLock + private void electSelf() { + long oldTerm; + try { + LOG.info("Node {} start vote and grant vote self, term={}.", getNodeId(), this.currTerm); + if (!this.conf.contains(this.serverId)) { + LOG.warn("Node {} can't do electSelf as it is not in {}.", getNodeId(), this.conf); + return; + } + if (this.state == State.STATE_FOLLOWER) { + LOG.debug("Node {} stop election timer, term={}.", getNodeId(), this.currTerm); + this.electionTimer.stop(); + } + resetLeaderId(PeerId.emptyPeer(), new Status(RaftError.ERAFTTIMEDOUT, + "A follower's leader_id is reset to NULL as it begins to request_vote.")); + this.state = State.STATE_CANDIDATE; + this.currTerm++; + this.votedId = this.serverId.copy(); + LOG.debug("Node {} start vote timer, term={} .", getNodeId(), this.currTerm); + this.voteTimer.start(); + this.voteCtx.init(this.conf.getConf(), this.conf.isStable() ? null : this.conf.getOldConf()); + oldTerm = this.currTerm; + } finally { + this.writeLock.unlock(); + } + + final LogId lastLogId = this.logManager.getLastLogId(true); + + this.writeLock.lock(); + try { + // vote need defense ABA after unlock&writeLock + if (oldTerm != this.currTerm) { + LOG.warn("Node {} raise term {} when getLastLogId.", getNodeId(), this.currTerm); + return; + } + for (final PeerId peer : this.conf.listPeers()) { + if (peer.equals(this.serverId)) { + continue; + } + if (!this.rpcService.connect(peer.getEndpoint())) { + LOG.warn("Node {} channel init failed, address={}.", getNodeId(), peer.getEndpoint()); + continue; + } + final OnRequestVoteRpcDone done = new OnRequestVoteRpcDone(peer, this.currTerm, this); + done.request = RequestVoteRequest.newBuilder() // + .setPreVote(false) // It's not a pre-vote request. + .setGroupId(this.groupId) // + .setServerId(this.serverId.toString()) // + .setPeerId(peer.toString()) // + .setTerm(this.currTerm) // + .setLastLogIndex(lastLogId.getIndex()) // + .setLastLogTerm(lastLogId.getTerm()) // + .build(); + this.rpcService.requestVote(peer.getEndpoint(), done.request, done); + } + + this.metaStorage.setTermAndVotedFor(this.currTerm, this.serverId); + this.voteCtx.grant(this.serverId); + if (this.voteCtx.isGranted()) { + becomeLeader(); + } + } finally { + this.writeLock.unlock(); + } + } + + private void resetLeaderId(final PeerId newLeaderId, final Status status) { + if (newLeaderId.isEmpty()) { + if (!this.leaderId.isEmpty() && this.state.compareTo(State.STATE_TRANSFERRING) > 0) { + this.fsmCaller.onStopFollowing(new LeaderChangeContext(this.leaderId.copy(), this.currTerm, status)); + } + this.leaderId = PeerId.emptyPeer(); + } else { + if (this.leaderId == null || this.leaderId.isEmpty()) { + this.fsmCaller.onStartFollowing(new LeaderChangeContext(newLeaderId, this.currTerm, status)); + } + this.leaderId = newLeaderId.copy(); + } + } + + // in writeLock + private void checkStepDown(final long requestTerm, final PeerId serverId) { + final Status status = new Status(); + if (requestTerm > this.currTerm) { + status.setError(RaftError.ENEWLEADER, "Raft node receives message from new leader with higher term."); + stepDown(requestTerm, false, status); + } else if (this.state != State.STATE_FOLLOWER) { + status.setError(RaftError.ENEWLEADER, "Candidate receives message from new leader with the same term."); + stepDown(requestTerm, false, status); + } else if (this.leaderId.isEmpty()) { + status.setError(RaftError.ENEWLEADER, "Follower receives message from new leader with the same term."); + stepDown(requestTerm, false, status); + } + // save current leader + if (this.leaderId == null || this.leaderId.isEmpty()) { + resetLeaderId(serverId, status); + } + } + + private void becomeLeader() { + Requires.requireTrue(this.state == State.STATE_CANDIDATE, "Illegal state: " + this.state); + LOG.info("Node {} become leader of group, term={}, conf={}, oldConf={}.", getNodeId(), this.currTerm, + this.conf.getConf(), this.conf.getOldConf()); + // cancel candidate vote timer + stopVoteTimer(); + this.state = State.STATE_LEADER; + this.leaderId = this.serverId.copy(); + this.replicatorGroup.resetTerm(this.currTerm); + for (final PeerId peer : this.conf.listPeers()) { + if (peer.equals(this.serverId)) { + continue; + } + LOG.debug("Node {} add replicator, term={}, peer={}.", getNodeId(), this.currTerm, peer); + if (!this.replicatorGroup.addReplicator(peer)) { + LOG.error("Fail to add replicator, peer={}.", peer); + } + } + // init commit manager + this.ballotBox.resetPendingIndex(this.logManager.getLastLogIndex() + 1); + // Register _conf_ctx to reject configuration changing before the first log + // is committed. + if (this.confCtx.isBusy()) { + throw new IllegalStateException(); + } + this.confCtx.flush(this.conf.getConf(), this.conf.getOldConf()); + this.stepDownTimer.start(); + } + + // should be in writeLock + private void stepDown(final long term, final boolean wakeupCandidate, final Status status) { + LOG.debug("Node {} stepDown, term={}, newTerm={}, wakeupCandidate={}.", getNodeId(), this.currTerm, term, + wakeupCandidate); + if (!this.state.isActive()) { + return; + } + if (this.state == State.STATE_CANDIDATE) { + stopVoteTimer(); + } else if (this.state.compareTo(State.STATE_TRANSFERRING) <= 0) { + stopStepDownTimer(); + this.ballotBox.clearPendingTasks(); + // signal fsm leader stop immediately + if (this.state == State.STATE_LEADER) { + onLeaderStop(status); + } + } + // reset leader_id + resetLeaderId(PeerId.emptyPeer(), status); + + // soft state in memory + this.state = State.STATE_FOLLOWER; + this.confCtx.reset(); + updateLastLeaderTimestamp(Utils.monotonicMs()); + if (this.snapshotExecutor != null) { + this.snapshotExecutor.interruptDownloadingSnapshots(term); + } + + // meta state + if (term > this.currTerm) { + this.currTerm = term; + this.votedId = PeerId.emptyPeer(); + this.metaStorage.setTermAndVotedFor(term, this.votedId); + } + + if (wakeupCandidate) { + this.wakingCandidate = this.replicatorGroup.stopAllAndFindTheNextCandidate(this.conf); + if (this.wakingCandidate != null) { + Replicator.sendTimeoutNowAndStop(this.wakingCandidate, this.options.getElectionTimeoutMs()); + } + } else { + this.replicatorGroup.stopAll(); + } + if (this.stopTransferArg != null) { + if (this.transferTimer != null) { + this.transferTimer.cancel(true); + } + // There is at most one StopTransferTimer at the same term, it's safe to + // mark stopTransferArg to NULL + this.stopTransferArg = null; + } + this.electionTimer.start(); + } + + private void stopStepDownTimer() { + if (this.stepDownTimer != null) { + this.stepDownTimer.stop(); + } + } + + private void stopVoteTimer() { + if (this.voteTimer != null) { + this.voteTimer.stop(); + } + } + + class LeaderStableClosure extends LogManager.StableClosure { + + public LeaderStableClosure(final List entries) { + super(entries); + } + + @Override + public void run(final Status status) { + if (status.isOk()) { + NodeImpl.this.ballotBox.commitAt(this.firstLogIndex, this.firstLogIndex + this.nEntries - 1, + NodeImpl.this.serverId); + } else { + LOG.error("Node {} append [{}, {}] failed.", getNodeId(), this.firstLogIndex, this.firstLogIndex + + this.nEntries - 1); + } + } + } + + private void executeApplyingTasks(final List tasks) { + this.writeLock.lock(); + try { + final int size = tasks.size(); + if (this.state != State.STATE_LEADER) { + final Status st = new Status(); + if (this.state != State.STATE_TRANSFERRING) { + st.setError(RaftError.EPERM, "Is not leader."); + } else { + st.setError(RaftError.EBUSY, "Is transferring leadership."); + } + LOG.debug("Node {} can't apply, status={}.", getNodeId(), st); + for (int i = 0; i < size; i++) { + Utils.runClosureInThread(tasks.get(i).done, st); + } + return; + } + final List entries = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + final LogEntryAndClosure task = tasks.get(i); + if (task.expectedTerm != -1 && task.expectedTerm != this.currTerm) { + LOG.debug("Node {} can't apply task whose expectedTerm={} doesn't match currTerm={}.", getNodeId(), + task.expectedTerm, this.currTerm); + if (task.done != null) { + final Status st = new Status(RaftError.EPERM, "expected_term=%d doesn't match current_term=%d", + task.expectedTerm, this.currTerm); + Utils.runClosureInThread(task.done, st); + } + continue; + } + if (!this.ballotBox.appendPendingTask(this.conf.getConf(), + this.conf.isStable() ? null : this.conf.getOldConf(), task.done)) { + Utils.runClosureInThread(task.done, new Status(RaftError.EINTERNAL, "Fail to append task.")); + continue; + } + // set task entry info before adding to list. + task.entry.getId().setTerm(this.currTerm); + task.entry.setType(EnumOutter.EntryType.ENTRY_TYPE_DATA); + entries.add(task.entry); + } + this.logManager.appendEntries(entries, new LeaderStableClosure(entries)); + // update conf.first + this.conf = this.logManager.checkAndSetConfiguration(this.conf); + } finally { + this.writeLock.unlock(); + } + } + + /** + * Returns the node metrics. + * + * @return returns metrics of current node. + */ + @Override + public NodeMetrics getNodeMetrics() { + return this.metrics; + } + + /** + * Returns the JRaft service factory for current node. + *@since 1.2.6 + * @return the service factory + */ + public JRaftServiceFactory getServiceFactory() { + return this.serviceFactory; + } + + @Override + public void readIndex(final byte[] requestContext, final ReadIndexClosure done) { + if (this.shutdownLatch != null) { + Utils.runClosureInThread(done, new Status(RaftError.ENODESHUTDOWN, "Node is shutting down.")); + throw new IllegalStateException("Node is shutting down"); + } + Requires.requireNonNull(done, "Null closure"); + this.readOnlyService.addRequest(requestContext, done); + } + + /** + * ReadIndex response closure + * @author dennis + */ + private class ReadIndexHeartbeatResponseClosure extends RpcResponseClosureAdapter { + final ReadIndexResponse.Builder respBuilder; + final RpcResponseClosure closure; + final int quorum; + final int failPeersThreshold; + int ackSuccess; + int ackFailures; + boolean isDone; + + public ReadIndexHeartbeatResponseClosure(final RpcResponseClosure closure, + final ReadIndexResponse.Builder rb, final int quorum, + final int peersCount) { + super(); + this.closure = closure; + this.respBuilder = rb; + this.quorum = quorum; + this.failPeersThreshold = peersCount % 2 == 0 ? (quorum - 1) : quorum; + this.ackSuccess = 0; + this.ackFailures = 0; + this.isDone = false; + } + + @Override + public synchronized void run(final Status status) { + if (this.isDone) { + return; + } + if (status.isOk() && getResponse().getSuccess()) { + this.ackSuccess++; + } else { + this.ackFailures++; + } + // Include leader self vote yes. + if (this.ackSuccess + 1 >= this.quorum) { + this.respBuilder.setSuccess(true); + this.closure.setResponse(this.respBuilder.build()); + this.closure.run(Status.OK()); + this.isDone = true; + } else if (this.ackFailures >= this.failPeersThreshold) { + this.respBuilder.setSuccess(false); + this.closure.setResponse(this.respBuilder.build()); + this.closure.run(Status.OK()); + this.isDone = true; + } + } + } + + /** + * Handle read index request. + */ + @Override + public void handleReadIndexRequest(final ReadIndexRequest request, final RpcResponseClosure done) { + final long startMs = Utils.monotonicMs(); + this.readLock.lock(); + try { + switch (this.state) { + case STATE_LEADER: + readLeader(request, ReadIndexResponse.newBuilder(), done); + break; + case STATE_FOLLOWER: + readFollower(request, done); + break; + case STATE_TRANSFERRING: + done.run(new Status(RaftError.EBUSY, "Is transferring leadership.")); + break; + default: + done.run(new Status(RaftError.EPERM, "Invalid state for readIndex: %s.", this.state)); + break; + } + } finally { + this.readLock.unlock(); + this.metrics.recordLatency("handle-read-index", Utils.monotonicMs() - startMs); + this.metrics.recordSize("handle-read-index-entries", request.getEntriesCount()); + } + } + + private int getQuorum() { + final Configuration c = this.conf.getConf(); + if (c.isEmpty()) { + return 0; + } + return c.getPeers().size() / 2 + 1; + } + + private void readFollower(final ReadIndexRequest request, final RpcResponseClosure closure) { + if (this.leaderId == null || this.leaderId.isEmpty()) { + closure.run(new Status(RaftError.EPERM, "No leader at term %d.", this.currTerm)); + return; + } + // send request to leader. + final ReadIndexRequest newRequest = ReadIndexRequest.newBuilder() // + .mergeFrom(request) // + .setPeerId(this.leaderId.toString()) // + .build(); + this.rpcService.readIndex(this.leaderId.getEndpoint(), newRequest, -1, closure); + } + + private void readLeader(final ReadIndexRequest request, final ReadIndexResponse.Builder respBuilder, + final RpcResponseClosure closure) { + final int quorum = getQuorum(); + if (quorum <= 1) { + // Only one peer, fast path. + respBuilder.setSuccess(true) // + .setIndex(this.ballotBox.getLastCommittedIndex()); + closure.setResponse(respBuilder.build()); + closure.run(Status.OK()); + return; + } + + final long lastCommittedIndex = this.ballotBox.getLastCommittedIndex(); + if (this.logManager.getTerm(lastCommittedIndex) != this.currTerm) { + // Reject read only request when this leader has not committed any log entry at its term + closure + .run(new Status( + RaftError.EAGAIN, + "ReadIndex request rejected because leader has not committed any log entry at its term, logIndex=%d, currTerm=%d.", + lastCommittedIndex, this.currTerm)); + return; + } + respBuilder.setIndex(lastCommittedIndex); + + if (request.getPeerId() != null) { + // request from follower, check if the follower is in current conf. + final PeerId peer = new PeerId(); + peer.parse(request.getServerId()); + if (!this.conf.contains(peer)) { + closure + .run(new Status(RaftError.EPERM, "Peer %s is not in current configuration: {}.", peer, this.conf)); + return; + } + } + + ReadOnlyOption readOnlyOpt = this.raftOptions.getReadOnlyOptions(); + if (readOnlyOpt == ReadOnlyOption.ReadOnlyLeaseBased && !isLeaderLeaseValid()) { + // If leader lease timeout, we must change option to ReadOnlySafe + readOnlyOpt = ReadOnlyOption.ReadOnlySafe; + } + + switch (readOnlyOpt) { + case ReadOnlySafe: + final List peers = this.conf.getConf().getPeers(); + Requires.requireTrue(peers != null && !peers.isEmpty(), "Empty peers"); + final ReadIndexHeartbeatResponseClosure heartbeatDone = new ReadIndexHeartbeatResponseClosure(closure, + respBuilder, quorum, peers.size()); + // Send heartbeat requests to followers + for (final PeerId peer : peers) { + if (peer.equals(this.serverId)) { + continue; + } + this.replicatorGroup.sendHeartbeat(peer, heartbeatDone); + } + break; + case ReadOnlyLeaseBased: + // Responses to followers and local node. + respBuilder.setSuccess(true); + closure.setResponse(respBuilder.build()); + closure.run(Status.OK()); + break; + } + } + + @Override + public void apply(final Task task) { + if (this.shutdownLatch != null) { + Utils.runClosureInThread(task.getDone(), new Status(RaftError.ENODESHUTDOWN, "Node is shutting down.")); + throw new IllegalStateException("Node is shutting down"); + } + Requires.requireNonNull(task, "Null task"); + + final LogEntry entry = new LogEntry(); + entry.setData(task.getData()); + int retryTimes = 0; + try { + final EventTranslator translator = (event, sequence) -> { + event.reset(); + event.done = task.getDone(); + event.entry = entry; + event.expectedTerm = task.getExpectedTerm(); + }; + while (true) { + if (this.applyQueue.tryPublishEvent(translator)) { + break; + } else { + retryTimes++; + if (retryTimes > MAX_APPLY_RETRY_TIMES) { + Utils.runClosureInThread(task.getDone(), + new Status(RaftError.EBUSY, "Node is busy, has too many tasks.")); + LOG.warn("Node {} applyQueue is overload.", getNodeId()); + this.metrics.recordTimes("apply-task-overload-times", 1); + return; + } + ThreadHelper.onSpinWait(); + } + } + + } catch (final Exception e) { + Utils.runClosureInThread(task.getDone(), new Status(RaftError.EPERM, "Node is down.")); + } + } + + @Override + public Message handlePreVoteRequest(final RequestVoteRequest request) { + boolean doUnlock = true; + this.writeLock.lock(); + try { + if (!this.state.isActive()) { + LOG.warn("Node {} is not in active state, currTerm={}.", getNodeId(), this.currTerm); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Node %s is not in active state, state %s.", + getNodeId(), this.state.name()); + } + final PeerId candidateId = new PeerId(); + if (!candidateId.parse(request.getServerId())) { + LOG.warn("Node {} received PreVoteRequest from {} serverId bad format.", getNodeId(), + request.getServerId()); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Parse candidateId failed: %s.", + request.getServerId()); + } + boolean granted = false; + // noinspection ConstantConditions + do { + if (this.leaderId != null && !this.leaderId.isEmpty() && isCurrentLeaderValid()) { + LOG.info( + "Node {} ignore PreVoteRequest from {}, term={}, currTerm={}, because the leader {}'s lease is still valid.", + getNodeId(), request.getServerId(), request.getTerm(), this.currTerm, this.leaderId); + break; + } + if (request.getTerm() < this.currTerm) { + LOG.info("Node {} ignore PreVoteRequest from {}, term={}, currTerm={}.", getNodeId(), + request.getServerId(), request.getTerm(), this.currTerm); + // A follower replicator may not be started when this node become leader, so we must check it. + checkReplicator(candidateId); + break; + } else if (request.getTerm() == this.currTerm + 1) { + // A follower replicator may not be started when this node become leader, so we must check it. + // check replicator state + checkReplicator(candidateId); + } + doUnlock = false; + this.writeLock.unlock(); + + final LogId lastLogId = this.logManager.getLastLogId(true); + + doUnlock = true; + this.writeLock.lock(); + final LogId requestLastLogId = new LogId(request.getLastLogIndex(), request.getLastLogTerm()); + granted = requestLastLogId.compareTo(lastLogId) >= 0; + + LOG.info( + "Node {} received PreVoteRequest from {}, term={}, currTerm={}, granted={}, requestLastLogId={}, lastLogId={}.", + getNodeId(), request.getServerId(), request.getTerm(), this.currTerm, granted, requestLastLogId, + lastLogId); + } while (false); + + return RequestVoteResponse.newBuilder() // + .setTerm(this.currTerm) // + .setGranted(granted) // + .build(); + } finally { + if (doUnlock) { + this.writeLock.unlock(); + } + } + } + + // in read_lock + private boolean isLeaderLeaseValid() { + final long monotonicNowMs = Utils.monotonicMs(); + if (checkLeaderLease(monotonicNowMs)) { + return true; + } + checkDeadNodes0(this.conf.getConf().getPeers(), monotonicNowMs, false, null); + return checkLeaderLease(monotonicNowMs); + } + + private boolean checkLeaderLease(final long monotonicNowMs) { + return monotonicNowMs - this.lastLeaderTimestamp < this.options.getLeaderLeaseTimeoutMs(); + } + + private boolean isCurrentLeaderValid() { + return Utils.monotonicMs() - this.lastLeaderTimestamp < this.options.getElectionTimeoutMs(); + } + + private void updateLastLeaderTimestamp(final long lastLeaderTimestamp) { + this.lastLeaderTimestamp = lastLeaderTimestamp; + } + + private void checkReplicator(final PeerId candidateId) { + if (this.state == State.STATE_LEADER) { + this.replicatorGroup.checkReplicator(candidateId, false); + } + } + + @Override + public Message handleRequestVoteRequest(final RequestVoteRequest request) { + boolean doUnlock = true; + this.writeLock.lock(); + try { + if (!this.state.isActive()) { + LOG.warn("Node {} is not in active state, currTerm={}.", getNodeId(), this.currTerm); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Node %s is not in active state, state %s.", + getNodeId(), this.state.name()); + } + final PeerId candidateId = new PeerId(); + if (!candidateId.parse(request.getServerId())) { + LOG.warn("Node {} received RequestVoteRequest from {} serverId bad format.", getNodeId(), + request.getServerId()); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Parse candidateId failed: %s.", + request.getServerId()); + } + + // noinspection ConstantConditions + do { + // check term + if (request.getTerm() >= this.currTerm) { + LOG.info("Node {} received RequestVoteRequest from {}, term={}, currTerm={}.", getNodeId(), + request.getServerId(), request.getTerm(), this.currTerm); + // increase current term, change state to follower + if (request.getTerm() > this.currTerm) { + stepDown(request.getTerm(), false, new Status(RaftError.EHIGHERTERMRESPONSE, + "Raft node receives higher term RequestVoteRequest.")); + } + } else { + // ignore older term + LOG.info("Node {} ignore RequestVoteRequest from {}, term={}, currTerm={}.", getNodeId(), + request.getServerId(), request.getTerm(), this.currTerm); + break; + } + doUnlock = false; + this.writeLock.unlock(); + + final LogId lastLogId = this.logManager.getLastLogId(true); + + doUnlock = true; + this.writeLock.lock(); + // vote need ABA check after unlock&writeLock + if (request.getTerm() != this.currTerm) { + LOG.warn("Node {} raise term {} when get lastLogId.", getNodeId(), this.currTerm); + break; + } + + final boolean logIsOk = new LogId(request.getLastLogIndex(), request.getLastLogTerm()) + .compareTo(lastLogId) >= 0; + + if (logIsOk && (this.votedId == null || this.votedId.isEmpty())) { + stepDown(request.getTerm(), false, new Status(RaftError.EVOTEFORCANDIDATE, + "Raft node votes for some candidate, step down to restart election_timer.")); + this.votedId = candidateId.copy(); + this.metaStorage.setVotedFor(candidateId); + } + } while (false); + + return RequestVoteResponse.newBuilder() // + .setTerm(this.currTerm) // + .setGranted(request.getTerm() == this.currTerm && candidateId.equals(this.votedId)) // + .build(); + } finally { + if (doUnlock) { + this.writeLock.unlock(); + } + } + } + + private static class FollowerStableClosure extends LogManager.StableClosure { + + final long committedIndex; + final AppendEntriesResponse.Builder responseBuilder; + final NodeImpl node; + final RpcRequestClosure done; + final long term; + + public FollowerStableClosure(final AppendEntriesRequest request, + final AppendEntriesResponse.Builder responseBuilder, final NodeImpl node, + final RpcRequestClosure done, final long term) { + super(null); + this.committedIndex = Math.min( + // committed index is likely less than the lastLogIndex + request.getCommittedIndex(), + // The logs after the appended entries can not be trust, so we can't commit them even if their indexes are less than request's committed index. + request.getPrevLogIndex() + request.getEntriesCount()); + this.responseBuilder = responseBuilder; + this.node = node; + this.done = done; + this.term = term; + } + + @Override + public void run(final Status status) { + + if (!status.isOk()) { + this.done.run(status); + return; + } + + this.node.readLock.lock(); + try { + if (this.term != this.node.currTerm) { + // The change of term indicates that leader has been changed during + // appending entries, so we can't respond ok to the old leader + // because we are not sure if the appended logs would be truncated + // by the new leader: + // - If they won't be truncated and we respond failure to the old + // leader, the new leader would know that they are stored in this + // peer and they will be eventually committed when the new leader + // found that quorum of the cluster have stored. + // - If they will be truncated and we responded success to the old + // leader, the old leader would possibly regard those entries as + // committed (very likely in a 3-nodes cluster) and respond + // success to the clients, which would break the rule that + // committed entries would never be truncated. + // So we have to respond failure to the old leader and set the new + // term to make it stepped down if it didn't. + this.responseBuilder.setSuccess(false).setTerm(this.node.currTerm); + this.done.sendResponse(this.responseBuilder.build()); + return; + } + } finally { + // It's safe to release lock as we know everything is ok at this point. + this.node.readLock.unlock(); + } + + // Don't touch node any more. + this.responseBuilder.setSuccess(true).setTerm(this.term); + + // Ballot box is thread safe and tolerates disorder. + this.node.ballotBox.setLastCommittedIndex(this.committedIndex); + + this.done.sendResponse(this.responseBuilder.build()); + } + } + + @Override + public Message handleAppendEntriesRequest(final AppendEntriesRequest request, final RpcRequestClosure done) { + boolean doUnlock = true; + final long startMs = Utils.monotonicMs(); + this.writeLock.lock(); + final int entriesCount = request.getEntriesCount(); + try { + if (!this.state.isActive()) { + LOG.warn("Node {} is not in active state, currTerm={}.", getNodeId(), this.currTerm); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Node %s is not in active state, state %s.", + getNodeId(), this.state.name()); + } + + final PeerId serverId = new PeerId(); + if (!serverId.parse(request.getServerId())) { + LOG.warn("Node {} received AppendEntriesRequest from {} serverId bad format.", getNodeId(), + request.getServerId()); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Parse serverId failed: %s.", + request.getServerId()); + } + + // Check stale term + if (request.getTerm() < this.currTerm) { + LOG.warn("Node {} ignore stale AppendEntriesRequest from {}, term={}, currTerm={}.", getNodeId(), + request.getServerId(), request.getTerm(), this.currTerm); + return AppendEntriesResponse.newBuilder() // + .setSuccess(false) // + .setTerm(this.currTerm) // + .build(); + } + + // Check term and state to step down + checkStepDown(request.getTerm(), serverId); + if (!serverId.equals(this.leaderId)) { + LOG.error("Another peer {} declares that it is the leader at term {} which was occupied by leader {}.", + serverId, this.currTerm, this.leaderId); + // Increase the term by 1 and make both leaders step down to minimize the + // loss of split brain + stepDown(request.getTerm() + 1, false, new Status(RaftError.ELEADERCONFLICT, + "More than one leader in the same term.")); + return AppendEntriesResponse.newBuilder() // + .setSuccess(false) // + .setTerm(request.getTerm() + 1) // + .build(); + } + + updateLastLeaderTimestamp(Utils.monotonicMs()); + + if (entriesCount > 0 && this.snapshotExecutor != null && this.snapshotExecutor.isInstallingSnapshot()) { + LOG.warn("Node {} received AppendEntriesRequest while installing snapshot.", getNodeId()); + return RpcResponseFactory.newResponse(RaftError.EBUSY, "Node %s:%s is installing snapshot.", + this.groupId, this.serverId); + } + + final long prevLogIndex = request.getPrevLogIndex(); + final long prevLogTerm = request.getPrevLogTerm(); + final long localPrevLogTerm = this.logManager.getTerm(prevLogIndex); + if (localPrevLogTerm != prevLogTerm) { + final long lastLogIndex = this.logManager.getLastLogIndex(); + + LOG.warn( + "Node {} reject term_unmatched AppendEntriesRequest from {}, term={}, prevLogIndex={}, prevLogTerm={}, localPrevLogTerm={}, lastLogIndex={}, entriesSize={}.", + getNodeId(), request.getServerId(), request.getTerm(), prevLogIndex, prevLogTerm, localPrevLogTerm, + lastLogIndex, entriesCount); + + return AppendEntriesResponse.newBuilder() // + .setSuccess(false) // + .setTerm(this.currTerm) // + .setLastLogIndex(lastLogIndex) // + .build(); + } + + if (entriesCount == 0) { + // heartbeat + final AppendEntriesResponse.Builder respBuilder = AppendEntriesResponse.newBuilder() // + .setSuccess(true) // + .setTerm(this.currTerm) // + .setLastLogIndex(this.logManager.getLastLogIndex()); + doUnlock = false; + this.writeLock.unlock(); + // see the comments at FollowerStableClosure#run() + this.ballotBox.setLastCommittedIndex(Math.min(request.getCommittedIndex(), prevLogIndex)); + return respBuilder.build(); + } + + // Parse request + long index = prevLogIndex; + final List entries = new ArrayList<>(entriesCount); + ByteBuffer allData = null; + if (request.hasData()) { + allData = request.getData().asReadOnlyByteBuffer(); + } + + final List entriesList = request.getEntriesList(); + for (int i = 0; i < entriesCount; i++) { + final RaftOutter.EntryMeta entry = entriesList.get(i); + index++; + if (entry.getType() != EnumOutter.EntryType.ENTRY_TYPE_UNKNOWN) { + final LogEntry logEntry = new LogEntry(); + logEntry.setId(new LogId(index, entry.getTerm())); + logEntry.setType(entry.getType()); + if (entry.hasChecksum()) { + logEntry.setChecksum(entry.getChecksum()); // since 1.2.6 + } + final long dataLen = entry.getDataLen(); + if (dataLen > 0) { + final byte[] bs = new byte[(int) dataLen]; + assert allData != null; + allData.get(bs, 0, bs.length); + logEntry.setData(ByteBuffer.wrap(bs)); + } + + if (entry.getPeersCount() > 0) { + if (entry.getType() != EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION) { + throw new IllegalStateException( + "Invalid log entry that contains peers but is not ENTRY_TYPE_CONFIGURATION type: " + + entry.getType()); + } + + final List peers = new ArrayList<>(entry.getPeersCount()); + for (final String peerStr : entry.getPeersList()) { + final PeerId peer = new PeerId(); + peer.parse(peerStr); + peers.add(peer); + } + logEntry.setPeers(peers); + + if (entry.getOldPeersCount() > 0) { + final List oldPeers = new ArrayList<>(entry.getOldPeersCount()); + for (final String peerStr : entry.getOldPeersList()) { + final PeerId peer = new PeerId(); + peer.parse(peerStr); + oldPeers.add(peer); + } + logEntry.setOldPeers(oldPeers); + } + } else if (entry.getType() == EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION) { + throw new IllegalStateException( + "Invalid log entry that contains zero peers but is ENTRY_TYPE_CONFIGURATION type"); + } + + // Validate checksum + if (this.raftOptions.isEnableLogEntryChecksum() && logEntry.isCorrupted()) { + long realChecksum = logEntry.checksum(); + LOG.error( + "Corrupted log entry received from leader, index={}, term={}, expectedChecksum={}, realChecksum={}", + logEntry.getId().getIndex(), logEntry.getId().getTerm(), logEntry.getChecksum(), + realChecksum); + return RpcResponseFactory.newResponse(RaftError.EINVAL, + "The log entry is corrupted, index=%d, term=%d, expectedChecksum=%d, realChecksum=%d", + logEntry.getId().getIndex(), logEntry.getId().getTerm(), logEntry.getChecksum(), + realChecksum); + } + + entries.add(logEntry); + } + } + + final FollowerStableClosure closure = new FollowerStableClosure(request, AppendEntriesResponse.newBuilder() + .setTerm(this.currTerm), this, done, this.currTerm); + this.logManager.appendEntries(entries, closure); + // update configuration after _log_manager updated its memory status + this.conf = this.logManager.checkAndSetConfiguration(this.conf); + return null; + } finally { + if (doUnlock) { + this.writeLock.unlock(); + } + this.metrics.recordLatency("handle-append-entries", Utils.monotonicMs() - startMs); + this.metrics.recordSize("handle-append-entries-count", entriesCount); + } + } + + // called when leader receive greater term in AppendEntriesResponse + void increaseTermTo(final long newTerm, final Status status) { + this.writeLock.lock(); + try { + if (newTerm < this.currTerm) { + return; + } + stepDown(newTerm, false, status); + } finally { + this.writeLock.unlock(); + } + } + + /** + * Peer catch up callback + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-11 2:10:02 PM + */ + private static class OnCaughtUp extends CatchUpClosure { + private final NodeImpl node; + private final long term; + private final PeerId peer; + private final long version; + + public OnCaughtUp(final NodeImpl node, final long term, final PeerId peer, final long version) { + super(); + this.node = node; + this.term = term; + this.peer = peer; + this.version = version; + } + + @Override + public void run(final Status status) { + this.node.onCaughtUp(this.peer, this.term, this.version, status); + } + } + + private void onCaughtUp(final PeerId peer, final long term, final long version, final Status st) { + this.writeLock.lock(); + try { + // check current_term and state to avoid ABA problem + if (term != this.currTerm && this.state != State.STATE_LEADER) { + // term has changed and nothing should be done, otherwise there will be + // an ABA problem. + return; + } + if (st.isOk()) { + // Caught up successfully + this.confCtx.onCaughtUp(version, peer, true); + return; + } + // Retry if this peer is still alive + if (st.getCode() == RaftError.ETIMEDOUT.getNumber() + && Utils.monotonicMs() - this.replicatorGroup.getLastRpcSendTimestamp(peer) <= this.options + .getElectionTimeoutMs()) { + LOG.debug("Node {} waits peer {} to catch up.", getNodeId(), peer); + final OnCaughtUp caughtUp = new OnCaughtUp(this, term, peer, version); + final long dueTime = Utils.nowMs() + this.options.getElectionTimeoutMs(); + if (this.replicatorGroup.waitCaughtUp(peer, this.options.getCatchupMargin(), dueTime, caughtUp)) { + return; + } + LOG.warn("Node {} waitCaughtUp failed, peer={}.", getNodeId(), peer); + } + LOG.warn("Node {} caughtUp failed, status={}, peer={}.", getNodeId(), st, peer); + this.confCtx.onCaughtUp(version, peer, false); + } finally { + this.writeLock.unlock(); + } + } + + private void checkDeadNodes(final Configuration conf, final long monotonicNowMs) { + final List peers = conf.listPeers(); + final Configuration deadNodes = new Configuration(); + if (checkDeadNodes0(peers, monotonicNowMs, true, deadNodes)) { + return; + } + LOG.warn("Node {} steps down when alive nodes don't satisfy quorum, term={}, deadNodes={}, conf={}.", + getNodeId(), this.currTerm, deadNodes, conf); + final Status status = new Status(); + status.setError(RaftError.ERAFTTIMEDOUT, "Majority of the group dies: %d/%d", deadNodes.size(), peers.size()); + stepDown(this.currTerm, false, status); + } + + private boolean checkDeadNodes0(final List peers, final long monotonicNowMs, final boolean checkReplicator, + final Configuration deadNodes) { + final int leaderLeaseTimeoutMs = this.options.getLeaderLeaseTimeoutMs(); + int aliveCount = 0; + long startLease = Long.MAX_VALUE; + for (final PeerId peer : peers) { + if (peer.equals(this.serverId)) { + aliveCount++; + continue; + } + if (checkReplicator) { + checkReplicator(peer); + } + final long lastRpcSendTimestamp = this.replicatorGroup.getLastRpcSendTimestamp(peer); + if (monotonicNowMs - lastRpcSendTimestamp <= leaderLeaseTimeoutMs) { + aliveCount++; + if (startLease > lastRpcSendTimestamp) { + startLease = lastRpcSendTimestamp; + } + continue; + } + if (deadNodes != null) { + deadNodes.addPeer(peer); + } + } + if (aliveCount >= peers.size() / 2 + 1) { + updateLastLeaderTimestamp(startLease); + return true; + } + return false; + } + + // in read_lock + private List getAliveNodes(final List peers, final long monotonicNowMs) { + final int leaderLeaseTimeoutMs = this.options.getLeaderLeaseTimeoutMs(); + final List alivePeers = new ArrayList<>(); + for (final PeerId peer : peers) { + if (peer.equals(this.serverId)) { + alivePeers.add(peer.copy()); + continue; + } + if (monotonicNowMs - this.replicatorGroup.getLastRpcSendTimestamp(peer) <= leaderLeaseTimeoutMs) { + alivePeers.add(peer.copy()); + } + } + return alivePeers; + } + + private void handleStepDownTimeout() { + this.writeLock.lock(); + try { + if (this.state.compareTo(State.STATE_TRANSFERRING) > 0) { + LOG.debug("Node {} stop step-down timer, term={}, state={}.", getNodeId(), this.currTerm, this.state); + return; + } + final long monotonicNowMs = Utils.monotonicMs(); + checkDeadNodes(this.conf.getConf(), monotonicNowMs); + if (!this.conf.getOldConf().isEmpty()) { + checkDeadNodes(this.conf.getOldConf(), monotonicNowMs); + } + } finally { + this.writeLock.unlock(); + } + } + + /** + * Configuration changed callback. + * + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-11 2:53:43 PM + */ + private class ConfigurationChangeDone implements Closure { + private final long term; + private final boolean leaderStart; + + public ConfigurationChangeDone(final long term, final boolean leaderStart) { + super(); + this.term = term; + this.leaderStart = leaderStart; + } + + @Override + public void run(final Status status) { + if (status.isOk()) { + onConfigurationChangeDone(this.term); + if (this.leaderStart) { + getOptions().getFsm().onLeaderStart(this.term); + } + } else { + LOG.error("Fail to run ConfigurationChangeDone, status: {}.", status); + } + } + } + + private void unsafeApplyConfiguration(final Configuration newConf, final Configuration oldConf, + final boolean leaderStart) { + Requires.requireTrue(this.confCtx.isBusy(), "ConfigurationContext is not busy"); + final LogEntry entry = new LogEntry(EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION); + entry.setId(new LogId(0, this.currTerm)); + entry.setPeers(newConf.listPeers()); + if (oldConf != null) { + entry.setOldPeers(oldConf.listPeers()); + } + final ConfigurationChangeDone configurationChangeDone = new ConfigurationChangeDone(this.currTerm, leaderStart); + // Use the new_conf to deal the quorum of this very log + if (!this.ballotBox.appendPendingTask(newConf, oldConf, configurationChangeDone)) { + Utils.runClosureInThread(configurationChangeDone, new Status(RaftError.EINTERNAL, "Fail to append task.")); + return; + } + final List entries = new ArrayList<>(); + entries.add(entry); + this.logManager.appendEntries(entries, new LeaderStableClosure(entries)); + this.conf = this.logManager.checkAndSetConfiguration(this.conf); + } + + private void unsafeRegisterConfChange(final Configuration oldConf, final Configuration newConf, final Closure done) { + if (this.state != State.STATE_LEADER) { + LOG.warn("Node {} refused configuration changing as the state={}.", getNodeId(), this.state); + if (done != null) { + final Status status = new Status(); + if (this.state == State.STATE_TRANSFERRING) { + status.setError(RaftError.EBUSY, "Is transferring leadership."); + } else { + status.setError(RaftError.EPERM, "Not leader"); + } + Utils.runClosureInThread(done, status); + } + return; + } + // check concurrent conf change + if (this.confCtx.isBusy()) { + LOG.warn("Node {} refused configuration concurrent changing.", getNodeId()); + if (done != null) { + Utils.runClosureInThread(done, new Status(RaftError.EBUSY, "Doing another configuration change.")); + } + return; + } + // Return immediately when the new peers equals to current configuration + if (this.conf.getConf().equals(newConf)) { + Utils.runClosureInThread(done); + return; + } + this.confCtx.start(oldConf, newConf, done); + } + + private void afterShutdown() { + List savedDoneList = null; + this.writeLock.lock(); + try { + if (!this.shutdownContinuations.isEmpty()) { + savedDoneList = new ArrayList<>(this.shutdownContinuations); + } + if (this.logStorage != null) { + this.logStorage.shutdown(); + } + this.state = State.STATE_SHUTDOWN; + } finally { + this.writeLock.unlock(); + } + if (savedDoneList != null) { + for (final Closure closure : savedDoneList) { + Utils.runClosureInThread(closure); + } + } + } + + @Override + public NodeOptions getOptions() { + return this.options; + } + + public TimerManager getTimerManager() { + return this.timerManager; + } + + @Override + public RaftOptions getRaftOptions() { + return this.raftOptions; + } + + @OnlyForTest + long getCurrentTerm() { + this.readLock.lock(); + try { + return this.currTerm; + } finally { + this.readLock.unlock(); + } + } + + @OnlyForTest + ConfigurationEntry getConf() { + this.readLock.lock(); + try { + return this.conf; + } finally { + this.readLock.unlock(); + } + } + + @Override + public void shutdown() { + shutdown(null); + } + + public void onConfigurationChangeDone(final long term) { + this.writeLock.lock(); + try { + if (term != this.currTerm || this.state.compareTo(State.STATE_TRANSFERRING) > 0) { + LOG.warn("Node {} process onConfigurationChangeDone at term {} while state={}, currTerm={}.", + getNodeId(), term, this.state, this.currTerm); + return; + } + this.confCtx.nextStage(); + } finally { + this.writeLock.unlock(); + } + } + + @Override + public PeerId getLeaderId() { + this.readLock.lock(); + try { + return this.leaderId.isEmpty() ? null : this.leaderId; + } finally { + this.readLock.unlock(); + } + } + + @Override + public String getGroupId() { + return this.groupId; + } + + public PeerId getServerId() { + return this.serverId; + } + + @Override + public NodeId getNodeId() { + if (this.nodeId == null) { + this.nodeId = new NodeId(this.groupId, this.serverId); + } + return this.nodeId; + } + + public RaftClientService getRpcService() { + return this.rpcService; + } + + public void onError(final RaftException error) { + LOG.warn("Node {} got error: {}.", getNodeId(), error); + if (this.fsmCaller != null) { + // onError of fsmCaller is guaranteed to be executed once. + this.fsmCaller.onError(error); + } + this.writeLock.lock(); + try { + // If it is leader, need to wake up a new one; + // If it is follower, also step down to call on_stop_following. + if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) { + stepDown(this.currTerm, this.state == State.STATE_LEADER, new Status(RaftError.EBADNODE, + "Raft node(leader or candidate) is in error.")); + } + if (this.state.compareTo(State.STATE_ERROR) < 0) { + this.state = State.STATE_ERROR; + } + } finally { + this.writeLock.unlock(); + } + } + + public void handleRequestVoteResponse(final PeerId peerId, final long term, final RequestVoteResponse response) { + this.writeLock.lock(); + try { + if (this.state != State.STATE_CANDIDATE) { + LOG.warn("Node {} received invalid RequestVoteResponse from {}, state not in STATE_CANDIDATE but {}.", + getNodeId(), peerId, this.state); + return; + } + // check stale term + if (term != this.currTerm) { + LOG.warn("Node {} received stale RequestVoteResponse from {}, term={}, currTerm={}.", getNodeId(), + peerId, term, this.currTerm); + return; + } + // check response term + if (response.getTerm() > this.currTerm) { + LOG.warn("Node {} received invalid RequestVoteResponse from {}, term={}, expect={}.", getNodeId(), + peerId, response.getTerm(), this.currTerm); + stepDown(response.getTerm(), false, new Status(RaftError.EHIGHERTERMRESPONSE, + "Raft node receives higher term request_vote_response.")); + return; + } + // check granted quorum? + if (response.getGranted()) { + this.voteCtx.grant(peerId); + if (this.voteCtx.isGranted()) { + becomeLeader(); + } + } + } finally { + this.writeLock.unlock(); + } + } + + private class OnRequestVoteRpcDone extends RpcResponseClosureAdapter { + + final long startMs; + final PeerId peer; + final long term; + final NodeImpl node; + RequestVoteRequest request; + + public OnRequestVoteRpcDone(final PeerId peer, final long term, final NodeImpl node) { + super(); + this.startMs = Utils.monotonicMs(); + this.peer = peer; + this.term = term; + this.node = node; + } + + @Override + public void run(final Status status) { + NodeImpl.this.metrics.recordLatency("request-vote", Utils.monotonicMs() - this.startMs); + if (!status.isOk()) { + LOG.warn("Node {} RequestVote to {} error: {}.", this.node.getNodeId(), this.peer, status); + } else { + this.node.handleRequestVoteResponse(this.peer, this.term, getResponse()); + } + } + } + + public void handlePreVoteResponse(final PeerId peerId, final long term, final RequestVoteResponse response) { + boolean doUnlock = true; + this.writeLock.lock(); + try { + if (this.state != State.STATE_FOLLOWER) { + LOG.warn("Node {} received invalid PreVoteResponse from {}, state not in STATE_FOLLOWER but {}.", + getNodeId(), peerId, this.state); + return; + } + if (term != this.currTerm) { + LOG.warn("Node {} received invalid PreVoteResponse from {}, term={}, currTerm={}.", getNodeId(), + peerId, term, this.currTerm); + return; + } + if (response.getTerm() > this.currTerm) { + LOG.warn("Node {} received invalid PreVoteResponse from {}, term {}, expect={}.", getNodeId(), peerId, + response.getTerm(), this.currTerm); + stepDown(response.getTerm(), false, new Status(RaftError.EHIGHERTERMRESPONSE, + "Raft node receives higher term pre_vote_response.")); + return; + } + LOG.info("Node {} received PreVoteResponse from {}, term={}, granted={}.", getNodeId(), peerId, + response.getTerm(), response.getGranted()); + // check granted quorum? + if (response.getGranted()) { + this.prevVoteCtx.grant(peerId); + if (this.prevVoteCtx.isGranted()) { + doUnlock = false; + electSelf(); + } + } + } finally { + if (doUnlock) { + this.writeLock.unlock(); + } + } + } + + private class OnPreVoteRpcDone extends RpcResponseClosureAdapter { + + final long startMs; + final PeerId peer; + final long term; + RequestVoteRequest request; + + public OnPreVoteRpcDone(final PeerId peer, final long term) { + super(); + this.startMs = Utils.monotonicMs(); + this.peer = peer; + this.term = term; + } + + @Override + public void run(final Status status) { + NodeImpl.this.metrics.recordLatency("pre-vote", Utils.monotonicMs() - this.startMs); + if (!status.isOk()) { + LOG.warn("Node {} PreVote to {} error: {}.", getNodeId(), this.peer, status); + } else { + handlePreVoteResponse(this.peer, this.term, getResponse()); + } + } + } + + // in writeLock + private void preVote() { + long oldTerm; + try { + LOG.info("Node {} term {} start preVote.", getNodeId(), this.currTerm); + if (this.snapshotExecutor != null && this.snapshotExecutor.isInstallingSnapshot()) { + LOG.warn( + "Node {} term {} doesn't do preVote when installing snapshot as the configuration may be out of date.", + getNodeId()); + return; + } + if (!this.conf.contains(this.serverId)) { + LOG.warn("Node {} can't do preVote as it is not in conf <{}>.", getNodeId(), this.conf); + return; + } + oldTerm = this.currTerm; + } finally { + this.writeLock.unlock(); + } + + final LogId lastLogId = this.logManager.getLastLogId(true); + + boolean doUnlock = true; + this.writeLock.lock(); + try { + // pre_vote need defense ABA after unlock&writeLock + if (oldTerm != this.currTerm) { + LOG.warn("Node {} raise term {} when get lastLogId.", getNodeId(), this.currTerm); + return; + } + this.prevVoteCtx.init(this.conf.getConf(), this.conf.isStable() ? null : this.conf.getOldConf()); + for (final PeerId peer : this.conf.listPeers()) { + if (peer.equals(this.serverId)) { + continue; + } + if (!this.rpcService.connect(peer.getEndpoint())) { + LOG.warn("Node {} channel init failed, address={}.", getNodeId(), peer.getEndpoint()); + continue; + } + final OnPreVoteRpcDone done = new OnPreVoteRpcDone(peer, this.currTerm); + done.request = RequestVoteRequest.newBuilder() // + .setPreVote(true) // it's a pre-vote request. + .setGroupId(this.groupId) // + .setServerId(this.serverId.toString()) // + .setPeerId(peer.toString()) // + .setTerm(this.currTerm + 1) // next term + .setLastLogIndex(lastLogId.getIndex()) // + .setLastLogTerm(lastLogId.getTerm()) // + .build(); + this.rpcService.preVote(peer.getEndpoint(), done.request, done); + } + this.prevVoteCtx.grant(this.serverId); + if (this.prevVoteCtx.isGranted()) { + doUnlock = false; + electSelf(); + } + } finally { + if (doUnlock) { + this.writeLock.unlock(); + } + } + } + + private void handleVoteTimeout() { + this.writeLock.lock(); + if (this.state == State.STATE_CANDIDATE) { + LOG.debug("Node {} term {} retry elect.", getNodeId(), this.currTerm); + electSelf(); + } else { + this.writeLock.unlock(); + } + } + + @Override + public boolean isLeader() { + this.readLock.lock(); + try { + return this.state == State.STATE_LEADER; + } finally { + this.readLock.unlock(); + } + } + + @Override + public void shutdown(final Closure done) { + this.writeLock.lock(); + try { + LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state); + if (this.state.compareTo(State.STATE_SHUTTING) < 0) { + NodeManager.getInstance().remove(this); + // If it is leader, set the wakeup_a_candidate with true; + // If it is follower, call on_stop_following in step_down + if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) { + stepDown(this.currTerm, this.state == State.STATE_LEADER, + new Status(RaftError.ESHUTDOWN, "Raft node is going to quit.")); + } + this.state = State.STATE_SHUTTING; + // Destroy all timers + if (this.electionTimer != null) { + this.electionTimer.destroy(); + } + if (this.voteTimer != null) { + this.voteTimer.destroy(); + } + if (this.stepDownTimer != null) { + this.stepDownTimer.destroy(); + } + if (this.snapshotTimer != null) { + this.snapshotTimer.destroy(); + } + if (this.readOnlyService != null) { + this.readOnlyService.shutdown(); + } + if (this.logManager != null) { + this.logManager.shutdown(); + } + if (this.metaStorage != null) { + this.metaStorage.shutdown(); + } + if (this.snapshotExecutor != null) { + this.snapshotExecutor.shutdown(); + } + if (this.wakingCandidate != null) { + Replicator.stop(this.wakingCandidate); + } + if (this.fsmCaller != null) { + this.fsmCaller.shutdown(); + } + if (this.rpcService != null) { + this.rpcService.shutdown(); + } + if (this.applyQueue != null) { + Utils.runInThread(() -> { + this.shutdownLatch = new CountDownLatch(1); + this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch); + }); + } else { + final int num = GLOBAL_NUM_NODES.decrementAndGet(); + LOG.info("The number of active nodes decrement to {}.", num); + } + if (this.timerManager != null) { + this.timerManager.shutdown(); + } + } + + if (this.state != State.STATE_SHUTDOWN) { + if (done != null) { + this.shutdownContinuations.add(done); + } + return; + } + + // This node is down, it's ok to invoke done right now. Don't invoke this + // in place to avoid the dead writeLock issue when done.Run() is going to acquire + // a writeLock which is already held by the caller + if (done != null) { + Utils.runClosureInThread(done); + } + } finally { + this.writeLock.unlock(); + } + } + + @Override + public synchronized void join() throws InterruptedException { + if (this.shutdownLatch != null) { + if (this.readOnlyService != null) { + this.readOnlyService.join(); + } + if (this.fsmCaller != null) { + this.fsmCaller.join(); + } + if (this.logManager != null) { + this.logManager.join(); + } + if (this.snapshotExecutor != null) { + this.snapshotExecutor.join(); + } + if (this.wakingCandidate != null) { + Replicator.join(this.wakingCandidate); + } + this.shutdownLatch.await(); + this.applyDisruptor.shutdown(); + this.shutdownLatch = null; + } + } + + private static class StopTransferArg { + final NodeImpl node; + final long term; + final PeerId peer; + + public StopTransferArg(final NodeImpl node, final long term, final PeerId peer) { + super(); + this.node = node; + this.term = term; + this.peer = peer; + } + } + + private void handleTransferTimeout(final long term, final PeerId peer) { + LOG.info("Node {} failed to transfer leadership to peer {}, reached timeout.", getNodeId(), peer); + this.writeLock.lock(); + try { + if (term == this.currTerm) { + this.replicatorGroup.stopTransferLeadership(peer); + if (this.state == State.STATE_TRANSFERRING) { + this.fsmCaller.onLeaderStart(term); + this.state = State.STATE_LEADER; + this.stopTransferArg = null; + } + } + } finally { + this.writeLock.unlock(); + } + } + + private void onTransferTimeout(final StopTransferArg arg) { + arg.node.handleTransferTimeout(arg.term, arg.peer); + } + + /** + * Retrieve current configuration this node seen so far. It's not a reliable way to + * retrieve cluster peers info, you should use {@link #listPeers()} instead. + * + * @return current configuration. + * + * @since 1.0.3 + */ + public Configuration getCurrentConf() { + this.readLock.lock(); + try { + if (this.conf != null && this.conf.getConf() != null) { + return this.conf.getConf().copy(); + } + return null; + } finally { + this.readLock.unlock(); + } + } + + @Override + public List listPeers() { + this.readLock.lock(); + try { + if (this.state != State.STATE_LEADER) { + throw new IllegalStateException("Not leader"); + } + return this.conf.getConf().listPeers(); + } finally { + this.readLock.unlock(); + } + } + + @Override + public List listAlivePeers() { + this.readLock.lock(); + try { + if (this.state != State.STATE_LEADER) { + throw new IllegalStateException("Not leader"); + } + return getAliveNodes(this.conf.getConf().getPeers(), Utils.monotonicMs()); + } finally { + this.readLock.unlock(); + } + } + + @Override + public void addPeer(final PeerId peer, final Closure done) { + Requires.requireNonNull(peer, "Null peer"); + this.writeLock.lock(); + try { + Requires.requireTrue(!this.conf.getConf().contains(peer), "Peer already exists in current configuration"); + + final Configuration newConf = new Configuration(this.conf.getConf()); + newConf.addPeer(peer); + unsafeRegisterConfChange(this.conf.getConf(), newConf, done); + } finally { + this.writeLock.unlock(); + } + } + + @Override + public void removePeer(final PeerId peer, final Closure done) { + Requires.requireNonNull(peer, "Null peer"); + this.writeLock.lock(); + try { + Requires.requireTrue(this.conf.getConf().contains(peer), "Peer not found in current configuration"); + + final Configuration newConf = new Configuration(this.conf.getConf()); + newConf.removePeer(peer); + unsafeRegisterConfChange(this.conf.getConf(), newConf, done); + } finally { + this.writeLock.unlock(); + } + } + + @Override + public void changePeers(final Configuration newPeers, final Closure done) { + Requires.requireNonNull(newPeers, "Null new peers"); + Requires.requireTrue(!newPeers.isEmpty(), "Empty new peers"); + this.writeLock.lock(); + try { + LOG.info("Node {} change peers from {} to {}.", getNodeId(), this.conf.getConf(), newPeers); + unsafeRegisterConfChange(this.conf.getConf(), newPeers, done); + } finally { + this.writeLock.unlock(); + } + } + + @Override + public Status resetPeers(final Configuration newPeers) { + Requires.requireNonNull(newPeers, "Null new peers"); + Requires.requireTrue(!newPeers.isEmpty(), "Empty new peers"); + this.writeLock.lock(); + try { + if (newPeers.isEmpty()) { + LOG.warn("Node {} set empty peers.", getNodeId()); + return new Status(RaftError.EINVAL, "newPeers is empty"); + } + if (!this.state.isActive()) { + LOG.warn("Node {} is in state {}, can't set peers.", getNodeId(), this.state); + return new Status(RaftError.EPERM, "Bad state: %s", this.state); + } + // bootstrap? + if (this.conf.getConf().isEmpty()) { + LOG.info("Node {} set peers to {} from empty.", getNodeId(), newPeers); + this.conf.setConf(newPeers); + stepDown(this.currTerm + 1, false, new Status(RaftError.ESETPEER, "Set peer from empty configuration")); + return Status.OK(); + } + if (this.state == State.STATE_LEADER && this.confCtx.isBusy()) { + LOG.warn("Node {} set peers need wait current conf changing.", getNodeId()); + return new Status(RaftError.EBUSY, "Changing to another configuration"); + } + // check equal, maybe retry direct return + if (this.conf.getConf().equals(newPeers)) { + return Status.OK(); + } + final Configuration newConf = new Configuration(newPeers); + LOG.info("Node {} set peers from {} to {}.", getNodeId(), this.conf.getConf(), newPeers); + this.conf.setConf(newConf); + this.conf.getOldConf().reset(); + stepDown(this.currTerm + 1, false, new Status(RaftError.ESETPEER, "Raft node set peer normally")); + return Status.OK(); + } finally { + this.writeLock.unlock(); + } + } + + @Override + public void snapshot(final Closure done) { + doSnapshot(done); + } + + private void doSnapshot(final Closure done) { + if (this.snapshotExecutor != null) { + this.snapshotExecutor.doSnapshot(done); + } else { + if (done != null) { + final Status status = new Status(RaftError.EINVAL, "Snapshot is not supported"); + Utils.runClosureInThread(done, status); + } + } + } + + @Override + public void resetElectionTimeoutMs(final int electionTimeoutMs) { + Requires.requireTrue(electionTimeoutMs > 0, "Invalid electionTimeoutMs"); + this.writeLock.lock(); + try { + this.options.setElectionTimeoutMs(electionTimeoutMs); + this.replicatorGroup.resetHeartbeatInterval(heartbeatTimeout(this.options.getElectionTimeoutMs())); + this.replicatorGroup.resetElectionTimeoutInterval(electionTimeoutMs); + LOG.info("Node {} reset electionTimeout, currTimer {} state {} new electionTimeout {}.", getNodeId(), + this.currTerm, this.state, electionTimeoutMs); + this.electionTimer.reset(electionTimeoutMs); + } finally { + this.writeLock.unlock(); + } + } + + @Override + public Status transferLeadershipTo(final PeerId peer) { + Requires.requireNonNull(peer, "Null peer"); + this.writeLock.lock(); + try { + if (this.state != State.STATE_LEADER) { + LOG.warn("Node {} can't transfer leadership to peer {} as it is in state {}.", getNodeId(), peer, + this.state); + return new Status(this.state == State.STATE_TRANSFERRING ? RaftError.EBUSY : RaftError.EPERM, + "Not a leader"); + } + if (this.confCtx.isBusy()) { + // It's very messy to deal with the case when the |peer| received + // TimeoutNowRequest and increase the term while somehow another leader + // which was not replicated with the newest configuration has been + // elected. If no add_peer with this very |peer| is to be invoked ever + // after nor this peer is to be killed, this peer will spin in the voting + // procedure and make the each new leader stepped down when the peer + // reached vote timeout and it starts to vote (because it will increase + // the term of the group) + // To make things simple, refuse the operation and force users to + // invoke transfer_leadership_to after configuration changing is + // completed so that the peer's configuration is up-to-date when it + // receives the TimeOutNowRequest. + LOG.warn( + "Node {} refused to transfer leadership to peer {} when the leader is changing the configuration.", + getNodeId(), peer); + return new Status(RaftError.EBUSY, "Changing the configuration"); + } + + PeerId peerId = peer.copy(); + // if peer_id is ANY_PEER(0.0.0.0:0:0), the peer with the largest + // last_log_id will be selected. + if (peerId.equals(PeerId.ANY_PEER)) { + LOG.info("Node {} starts to transfer leadership to any peer.", getNodeId()); + if ((peerId = this.replicatorGroup.findTheNextCandidate(this.conf)) == null) { + return new Status(-1, "Candidate not found for any peer"); + } + } + if (peerId.equals(this.serverId)) { + LOG.info("Node {} transferred leadership to self.", this.serverId); + return Status.OK(); + } + if (!this.conf.contains(peerId)) { + LOG.info("Node {} refused to transfer leadership to peer {} as it is not in {}.", getNodeId(), peer, + this.conf); + return new Status(RaftError.EINVAL, "Not in current configuration"); + } + + final long lastLogIndex = this.logManager.getLastLogIndex(); + if (!this.replicatorGroup.transferLeadershipTo(peerId, lastLogIndex)) { + LOG.warn("No such peer {}.", peer); + return new Status(RaftError.EINVAL, "No such peer %s", peer); + } + this.state = State.STATE_TRANSFERRING; + final Status status = new Status(RaftError.ETRANSFERLEADERSHIP, + "Raft leader is transferring leadership to %s", peerId); + onLeaderStop(status); + LOG.info("Node {} starts to transfer leadership to peer {}.", getNodeId(), peer); + final StopTransferArg stopArg = new StopTransferArg(this, this.currTerm, peerId); + this.stopTransferArg = stopArg; + this.transferTimer = this.timerManager.schedule(() -> onTransferTimeout(stopArg), + this.options.getElectionTimeoutMs(), TimeUnit.MILLISECONDS); + + } finally { + this.writeLock.unlock(); + } + return Status.OK(); + } + + private void onLeaderStop(final Status status) { + this.replicatorGroup.clearFailureReplicators(); + this.fsmCaller.onLeaderStop(status); + } + + @Override + public Message handleTimeoutNowRequest(final TimeoutNowRequest request, final RpcRequestClosure done) { + boolean doUnlock = true; + this.writeLock.lock(); + try { + if (request.getTerm() != this.currTerm) { + final long savedCurrTerm = this.currTerm; + if (request.getTerm() > this.currTerm) { + stepDown(request.getTerm(), false, new Status(RaftError.EHIGHERTERMREQUEST, + "Raft node receives higher term request")); + } + LOG.info("Node {} received TimeoutNowRequest from {} while currTerm={} didn't match requestTerm={}.", + getNodeId(), request.getPeerId(), savedCurrTerm, request.getTerm()); + return TimeoutNowResponse.newBuilder() // + .setTerm(this.currTerm) // + .setSuccess(false) // + .build(); + } + if (this.state != State.STATE_FOLLOWER) { + LOG.info("Node {} received TimeoutNowRequest from {}, while state={}, term={}.", getNodeId(), + request.getServerId(), this.state, this.currTerm); + return TimeoutNowResponse.newBuilder() // + .setTerm(this.currTerm) // + .setSuccess(false) // + .build(); + } + + final long savedTerm = this.currTerm; + final TimeoutNowResponse resp = TimeoutNowResponse.newBuilder() // + .setTerm(this.currTerm + 1) // + .setSuccess(true) // + .build(); + // Parallelize response and election + done.sendResponse(resp); + doUnlock = false; + electSelf(); + LOG.info("Node {} received TimeoutNowRequest from {}, term={}.", getNodeId(), request.getServerId(), + savedTerm); + } finally { + if (doUnlock) { + this.writeLock.unlock(); + } + } + return null; + } + + @Override + public Message handleInstallSnapshot(final InstallSnapshotRequest request, final RpcRequestClosure done) { + if (this.snapshotExecutor == null) { + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Not supported snapshot"); + } + final PeerId serverId = new PeerId(); + if (!serverId.parse(request.getServerId())) { + LOG.warn("Node {} ignore InstallSnapshotRequest from {} bad server id.", getNodeId(), request.getServerId()); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Parse serverId failed: %s", request.getServerId()); + } + + this.writeLock.lock(); + try { + if (!this.state.isActive()) { + LOG.warn("Node {} ignore InstallSnapshotRequest as it is not in active state {}.", getNodeId(), + this.state); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Node %s:%s is not in active state, state %s.", + this.groupId, this.serverId, this.state.name()); + } + + if (request.getTerm() < this.currTerm) { + LOG.warn("Node {} ignore stale InstallSnapshotRequest from {}, term={}, currTerm={}.", getNodeId(), + request.getPeerId(), request.getTerm(), this.currTerm); + return InstallSnapshotResponse.newBuilder() // + .setTerm(this.currTerm) // + .setSuccess(false) // + .build(); + } + + checkStepDown(request.getTerm(), serverId); + + if (!serverId.equals(this.leaderId)) { + LOG.error("Another peer {} declares that it is the leader at term {} which was occupied by leader {}.", + serverId, this.currTerm, this.leaderId); + // Increase the term by 1 and make both leaders step down to minimize the + // loss of split brain + stepDown(request.getTerm() + 1, false, new Status(RaftError.ELEADERCONFLICT, + "More than one leader in the same term.")); + return InstallSnapshotResponse.newBuilder() // + .setTerm(request.getTerm() + 1) // + .setSuccess(false) // + .build(); + } + + } finally { + this.writeLock.unlock(); + } + final long startMs = Utils.monotonicMs(); + try { + if (LOG.isInfoEnabled()) { + LOG.info( + "Node {} received InstallSnapshotRequest from {}, lastIncludedLogIndex={}, lastIncludedLogTerm={}, lastLogId={}.", + getNodeId(), request.getServerId(), request.getMeta().getLastIncludedIndex(), request.getMeta() + .getLastIncludedTerm(), this.logManager.getLastLogId(false)); + } + this.snapshotExecutor.installSnapshot(request, InstallSnapshotResponse.newBuilder(), done); + return null; + } finally { + this.metrics.recordLatency("install-snapshot", Utils.monotonicMs() - startMs); + } + } + + public void updateConfigurationAfterInstallingSnapshot() { + this.writeLock.lock(); + try { + this.conf = this.logManager.checkAndSetConfiguration(this.conf); + } finally { + this.writeLock.unlock(); + } + } + + private void stopReplicator(final List keep, final List drop) { + if (drop != null) { + for (final PeerId peer : drop) { + if (!keep.contains(peer) && !peer.equals(this.serverId)) { + this.replicatorGroup.stopReplicator(peer); + } + } + } + } + + @Override + public UserLog readCommittedUserLog(final long index) { + if (index <= 0) { + throw new LogIndexOutOfBoundsException("Request index is invalid: " + index); + } + + final long savedLastAppliedIndex = this.fsmCaller.getLastAppliedIndex(); + + if (index > savedLastAppliedIndex) { + throw new LogIndexOutOfBoundsException("Request index " + index + " is greater than lastAppliedIndex: " + + savedLastAppliedIndex); + } + + long curIndex = index; + LogEntry entry = this.logManager.getEntry(curIndex); + if (entry == null) { + throw new LogNotFoundException("User log is deleted at index: " + index); + } + + do { + if (entry.getType() == EnumOutter.EntryType.ENTRY_TYPE_DATA) { + return new UserLog(curIndex, entry.getData()); + } else { + curIndex++; + } + if (curIndex > savedLastAppliedIndex) { + throw new IllegalStateException("No user log between index:" + index + " and last_applied_index:" + + savedLastAppliedIndex); + } + entry = this.logManager.getEntry(curIndex); + } while (entry != null); + + throw new LogNotFoundException("User log is deleted at index: " + curIndex); + } + + @Override + public void addReplicatorStateListener(final Replicator.ReplicatorStateListener replicatorStateListener) { + Requires.requireNonNull(replicatorStateListener, "replicatorStateListener"); + this.replicatorStateListeners.add(replicatorStateListener); + } + + @Override + public void removeReplicatorStateListener(final Replicator.ReplicatorStateListener replicatorStateListener) { + Requires.requireNonNull(replicatorStateListener, "replicatorStateListener"); + this.replicatorStateListeners.remove(replicatorStateListener); + } + + @Override + public void clearReplicatorStateListeners() { + this.replicatorStateListeners.clear(); + } + + @Override + public List getReplicatorStatueListeners() { + return this.replicatorStateListeners; + } + + @Override + public void describe(final Printer out) { + // node + final String _nodeId; + final String _state; + final long _currTerm; + final String _conf; + this.readLock.lock(); + try { + _nodeId = String.valueOf(getNodeId()); + _state = String.valueOf(this.state); + _currTerm = this.currTerm; + _conf = String.valueOf(this.conf); + } finally { + this.readLock.unlock(); + } + out.print("nodeId: ") // + .println(_nodeId); + out.print("state: ") // + .println(_state); + out.print("term: ") // + .println(_currTerm); + out.print("conf: ") // + .println(_conf); + + // timers + out.println("electionTimer: "); + this.electionTimer.describe(out); + + out.println("voteTimer: "); + this.voteTimer.describe(out); + + out.println("stepDownTimer: "); + this.stepDownTimer.describe(out); + + out.println("snapshotTimer: "); + this.snapshotTimer.describe(out); + + // logManager + out.println("logManager: "); + this.logManager.describe(out); + + // fsmCaller + out.println("fsmCaller: "); + this.fsmCaller.describe(out); + + // ballotBox + out.println("ballotBox: "); + this.ballotBox.describe(out); + + // snapshotExecutor + out.println("snapshotExecutor: "); + this.snapshotExecutor.describe(out); + + // replicators + out.println("replicatorGroup: "); + this.replicatorGroup.describe(out); + } + + @Override + public String toString() { + return "JRaftNode [nodeId=" + getNodeId() + "]"; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.alipay.sofa.jraft.core.NodeImpl.shutdown` reads with synchronization from `this.com.alipay.sofa.jraft.core.NodeImpl.electionTimer`. Potentially races with unsynchronized write in method `NodeImpl.init(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NodeImpl.shutdown(Closure) + +### Procedure Id: +com.alipay.sofa.jraft.core.NodeImpl.shutdown(com.alipay.sofa.jraft.Closure):void.a5f33d4af16042ae72f80f411c7e72c5 + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/core/NodeImpl.java + +### Key: +NodeImpl.java|shutdown|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +23c528e539cd5a9a96cd1400a291e5ad + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9213/instruction.md b/inferredbugs-9213/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1f932aee31114b0ff0d394fc87ede5ea9283b6e8 --- /dev/null +++ b/inferredbugs-9213/instruction.md @@ -0,0 +1,1670 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-jraft +**Bug ID:** 17 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.jraft.core; + +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.HashMap; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import javax.annotation.concurrent.ThreadSafe; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.closure.CatchUpClosure; +import com.alipay.sofa.jraft.entity.EnumOutter; +import com.alipay.sofa.jraft.entity.LogEntry; +import com.alipay.sofa.jraft.entity.PeerId; +import com.alipay.sofa.jraft.entity.RaftOutter; +import com.alipay.sofa.jraft.error.RaftError; +import com.alipay.sofa.jraft.error.RaftException; +import com.alipay.sofa.jraft.option.RaftOptions; +import com.alipay.sofa.jraft.option.ReplicatorOptions; +import com.alipay.sofa.jraft.rpc.RaftClientService; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowResponse; +import com.alipay.sofa.jraft.rpc.RpcResponseClosure; +import com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter; +import com.alipay.sofa.jraft.storage.snapshot.SnapshotReader; +import com.alipay.sofa.jraft.util.ByteBufferCollector; +import com.alipay.sofa.jraft.util.OnlyForTest; +import com.alipay.sofa.jraft.util.Requires; +import com.alipay.sofa.jraft.util.ThreadId; +import com.alipay.sofa.jraft.util.Utils; +import com.codahale.metrics.Gauge; +import com.codahale.metrics.Metric; +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.MetricSet; +import com.google.protobuf.Message; +import com.google.protobuf.ZeroByteStringHelper; + +/** + * Replicator for replicating log entry from leader to followers. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:32:02 AM + */ +@ThreadSafe +public class Replicator implements ThreadId.OnError { + + private static final Logger LOG = LoggerFactory.getLogger(Replicator.class); + + private final RaftClientService rpcService; + // Next sending log index + private volatile long nextIndex; + private int consecutiveErrorTimes = 0; + private boolean hasSucceeded; + private long timeoutNowIndex; + private volatile long lastRpcSendTimestamp; + private volatile long heartbeatCounter = 0; + private volatile long appendEntriesCounter = 0; + private volatile long installSnapshotCounter = 0; + protected Stat statInfo = new Stat(); + private ScheduledFuture blockTimer; + + // Cached the latest RPC in-flight request. + private Inflight rpcInFly; + // Heartbeat RPC future + private Future heartbeatInFly; + // Timeout request RPC future + private Future timeoutNowInFly; + // In-flight RPC requests, FIFO queue + private final ArrayDeque inflights = new ArrayDeque<>(); + + private long waitId = -1L; + protected ThreadId id; + private final ReplicatorOptions options; + private final RaftOptions raftOptions; + + private ScheduledFuture heartbeatTimer; + private volatile SnapshotReader reader; + private CatchUpClosure catchUpClosure; + private final TimerManager timerManager; + private final NodeMetrics nodeMetrics; + private volatile State state; + + // Request sequence + private int reqSeq = 0; + // Response sequence + private int requiredNextSeq = 0; + // Replicator state reset version + private int version = 0; + + // Pending response queue; + private final PriorityQueue pendingResponses = new PriorityQueue<>(50); + + private int getAndIncrementReqSeq() { + final int prev = this.reqSeq; + this.reqSeq++; + if (this.reqSeq < 0) { + this.reqSeq = 0; + } + return prev; + } + + private int getAndIncrementRequiredNextSeq() { + final int prev = this.requiredNextSeq; + this.requiredNextSeq++; + if (this.requiredNextSeq < 0) { + this.requiredNextSeq = 0; + } + return prev; + } + + /** + * Replicator state + * @author dennis + * + */ + public enum State { + Probe, // probe follower state + Snapshot, // installing snapshot to follower + Replicate, // replicate logs normally + Destroyed // destroyed + } + + public Replicator(final ReplicatorOptions replicatorOptions, final RaftOptions raftOptions) { + super(); + this.options = replicatorOptions; + this.nodeMetrics = this.options.getNode().getNodeMetrics(); + this.nextIndex = this.options.getLogManager().getLastLogIndex() + 1; + this.timerManager = replicatorOptions.getTimerManager(); + this.raftOptions = raftOptions; + this.rpcService = replicatorOptions.getRaftRpcService(); + } + + /** + * Replicator metric set. + * @author dennis + * + */ + private static final class ReplicatorMetricSet implements MetricSet { + private final ReplicatorOptions opts; + private final Replicator r; + + private ReplicatorMetricSet(final ReplicatorOptions opts, final Replicator r) { + this.opts = opts; + this.r = r; + } + + @Override + public Map getMetrics() { + final Map gauges = new HashMap<>(); + gauges.put("log-lags", (Gauge) () -> this.opts.getLogManager().getLastLogIndex() - (this.r.nextIndex - 1)); + gauges.put("next-index", (Gauge) () -> this.r.nextIndex); + gauges.put("heartbeat-times", (Gauge) () -> this.r.heartbeatCounter); + gauges.put("install-snapshot-times", (Gauge) () -> this.r.installSnapshotCounter); + gauges.put("append-entries-times", (Gauge) () -> this.r.appendEntriesCounter); + return gauges; + } + } + + /** + * Internal state + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:38:45 AM + */ + enum RunningState { + IDLE, // idle + BLOCKING, // blocking state + APPENDING_ENTRIES, // appending log entries + INSTALLING_SNAPSHOT // installing snapshot + } + + /** + * Statistics structure + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:38:53 AM + */ + static class Stat { + RunningState runningState; + long firstLogIndex; + long lastLogIncluded; + long lastLogIndex; + long lastTermIncluded; + + @Override + public String toString() { + return ""; + } + + } + + // In-flight request type + enum RequestType { + Snapshot, //install snapshot + AppendEntries //replicate logs + } + + /** + * In-flight request. + * @author dennis + * + */ + static class Inflight { + // In-flight request count + final int count; + // Start log index + final long startIndex; + // Entries size in bytes + final int size; + // RPC future + final Future rpcFuture; + final RequestType requestType; + // Request sequence. + final int seq; + + public Inflight(final RequestType requestType, final long startIndex, final int count, final int size, + final int seq, final Future rpcFuture) { + super(); + this.seq = seq; + this.requestType = requestType; + this.count = count; + this.startIndex = startIndex; + this.size = size; + this.rpcFuture = rpcFuture; + } + + @Override + public String toString() { + return "Inflight [count=" + this.count + ", startIndex=" + this.startIndex + ", size=" + this.size + + ", rpcFuture=" + this.rpcFuture + ", requestType=" + this.requestType + ", seq=" + this.seq + "]"; + } + + boolean isSendingLogEntries() { + return this.requestType == RequestType.AppendEntries && this.count > 0; + } + } + + /** + * RPC response for AppendEntries/InstallSnapshot. + * @author dennis + * + */ + static class RpcResponse implements Comparable { + final Status status; + final Message request; + final Message response; + final long rpcSendTime; + final int seq; + final RequestType requestType; + + public RpcResponse(final RequestType reqType, final int seq, final Status status, final Message request, + final Message response, final long rpcSendTime) { + super(); + this.requestType = reqType; + this.seq = seq; + this.status = status; + this.request = request; + this.response = response; + this.rpcSendTime = rpcSendTime; + } + + @Override + public String toString() { + return "RpcResponse [status=" + this.status + ", request=" + this.request + ", response=" + this.response + + ", rpcSendTime=" + this.rpcSendTime + ", seq=" + this.seq + ", requestType=" + this.requestType + + "]"; + } + + /** + * Sort by sequence. + */ + @Override + public int compareTo(final RpcResponse o) { + return Integer.compare(this.seq, o.seq); + } + } + + @OnlyForTest + ArrayDeque getInflights() { + return this.inflights; + } + + @OnlyForTest + State getState() { + return this.state; + } + + @OnlyForTest + void setState(final State state) { + this.state = state; + } + + @OnlyForTest + int getReqSeq() { + return this.reqSeq; + } + + @OnlyForTest + int getRequiredNextSeq() { + return this.requiredNextSeq; + } + + @OnlyForTest + int getVersion() { + return this.version; + } + + @OnlyForTest + public PriorityQueue getPendingResponses() { + return this.pendingResponses; + } + + @OnlyForTest + long getWaitId() { + return this.waitId; + } + + @OnlyForTest + ScheduledFuture getBlockTimer() { + return this.blockTimer; + } + + @OnlyForTest + long getTimeoutNowIndex() { + return this.timeoutNowIndex; + } + + @OnlyForTest + ReplicatorOptions getOpts() { + return this.options; + } + + @OnlyForTest + long getRealNextIndex() { + return this.nextIndex; + } + + @OnlyForTest + Future getRpcInFly() { + if (this.rpcInFly == null) { + return null; + } + return this.rpcInFly.rpcFuture; + } + + @OnlyForTest + Future getHeartbeatInFly() { + return this.heartbeatInFly; + } + + @OnlyForTest + ScheduledFuture getHeartbeatTimer() { + return this.heartbeatTimer; + } + + @OnlyForTest + void setHasSucceeded() { + this.hasSucceeded = true; + } + + @OnlyForTest + Future getTimeoutNowInFly() { + return this.timeoutNowInFly; + } + + /** + * Adds a in-flight request + * @param reqType type of request + * @param count count if request + * @param size size in bytes + */ + private void addInflight(final RequestType reqType, final long startIndex, final int count, final int size, + final int seq, final Future rpcInfly) { + this.rpcInFly = new Inflight(reqType, startIndex, count, size, seq, rpcInfly); + this.inflights.add(this.rpcInFly); + this.nodeMetrics.recordSize("replicate-inflights-count", this.inflights.size()); + } + + /** + * Returns the next in-flight sending index, return -1 when can't send more in-flight requests. + * + * @return next in-flight sending index + */ + long getNextSendIndex() { + // Fast path + if (this.inflights.isEmpty()) { + return this.nextIndex; + } + // Too many in-flight requests. + if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { + return -1L; + } + // Last request should be a AppendEntries request and has some entries. + if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { + return this.rpcInFly.startIndex + this.rpcInFly.count; + } + return -1L; + } + + private Inflight pollInflight() { + return this.inflights.poll(); + } + + private void startHeartbeatTimer(final long startMs) { + final long dueTime = startMs + this.options.getDynamicHeartBeatTimeoutMs(); + try { + this.heartbeatTimer = this.timerManager.schedule(() -> onTimeout(this.id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS); + } catch (final Exception e) { + LOG.error("Fail to schedule heartbeat timer", e); + onTimeout(this.id); + } + } + + void installSnapshot() { + if (this.state == State.Snapshot) { + LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId()); + this.id.unlock(); + return; + } + boolean doUnlock = true; + try { + Requires.requireTrue(this.reader == null, + "Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(), + this.state); + this.reader = this.options.getSnapshotStorage().open(); + if (this.reader == null) { + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot")); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final String uri = this.reader.generateURIForCopy(); + if (uri == null) { + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader")); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final RaftOutter.SnapshotMeta meta = this.reader.load(); + if (meta == null) { + final String snapshotPath = this.reader.getPath(); + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath)); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder(); + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + rb.setMeta(meta); + rb.setUri(uri); + + this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT; + this.statInfo.lastLogIncluded = meta.getLastIncludedIndex(); + this.statInfo.lastTermIncluded = meta.getLastIncludedTerm(); + + final InstallSnapshotRequest request = rb.build(); + this.state = State.Snapshot; + // noinspection NonAtomicOperationOnVolatileField + this.installSnapshotCounter++; + final long monotonicSendTimeMs = Utils.monotonicMs(); + final int stateVersion = this.version; + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(), + request, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq, + stateVersion, monotonicSendTimeMs); + } + }); + addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture); + } finally { + if (doUnlock) { + this.id.unlock(); + } + } + } + + @SuppressWarnings("unused") + static boolean onInstallSnapshotReturned(final ThreadId id, final Replicator r, final Status status, + final InstallSnapshotRequest request, + final InstallSnapshotResponse response) { + boolean success = true; + if (r.reader != null) { + Utils.closeQuietly(r.reader); + r.reader = null; + } + // noinspection ConstantConditions + do { + final StringBuilder sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received InstallSnapshotResponse from ").append(r.options.getPeerId()). // + append(" lastIncludedIndex=").append(request.getMeta().getLastIncludedIndex()). // + append(" lastIncludedTerm=").append(request.getMeta().getLastIncludedTerm()); + if (!status.isOk()) { + sb.append(" error:").append(status); + LOG.info(sb.toString()); + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to install snapshot at peer={}, error={}", r.options.getPeerId(), status); + } + success = false; + break; + } + if (!response.getSuccess()) { + sb.append(" success=false"); + LOG.info(sb.toString()); + success = false; + break; + } + //success + r.nextIndex = request.getMeta().getLastIncludedIndex() + 1; + sb.append(" success=true"); + LOG.info(sb.toString()); + } while (false); + // We don't retry installing the snapshot explicitly. + // id is unlock in sendEntries + if (!success) { + //should reset states + r.resetInflights(); + r.state = State.Probe; + r.block(Utils.nowMs(), status.getCode()); + return false; + } + r.hasSucceeded = true; + r.notifyOnCaughtUp(0, false); + if (r.timeoutNowIndex > 0 && r.timeoutNowIndex < r.nextIndex) { + r.sendTimeoutNow(false, false); + } + // id is unlock in _send_entriesheartbeatCounter + r.state = State.Replicate; + return true; + } + + private void sendEmptyEntries(final boolean isHeartbeat) { + this.sendEmptyEntries(isHeartbeat, null); + } + + /** + * Send probe or heartbeat request + * @param isHeartbeat if current entries is heartbeat + * @param heartBeatClosure heartbeat callback + */ + @SuppressWarnings("NonAtomicOperationOnVolatileField") + private void sendEmptyEntries(final boolean isHeartbeat, + final RpcResponseClosure heartBeatClosure) { + final AppendEntriesRequest.Builder rb = AppendEntriesRequest.newBuilder(); + if (!fillCommonFields(rb, this.nextIndex - 1, isHeartbeat)) { + // id is unlock in installSnapshot + installSnapshot(); + if (isHeartbeat && heartBeatClosure != null) { + Utils.runClosureInThread(heartBeatClosure, new Status(RaftError.EAGAIN, + "Fail to send heartbeat to peer %s", this.options.getPeerId())); + } + return; + } + try { + final long monotonicSendTimeMs = Utils.monotonicMs(); + final AppendEntriesRequest request = rb.build(); + + if (isHeartbeat) { + // Sending a heartbeat request + this.heartbeatCounter++; + RpcResponseClosure heartbeatDone; + // Prefer passed-in closure. + if (heartBeatClosure != null) { + heartbeatDone = heartBeatClosure; + } else { + heartbeatDone = new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onHeartbeatReturned(Replicator.this.id, status, request, getResponse(), monotonicSendTimeMs); + } + }; + } + this.heartbeatInFly = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), request, + this.options.getElectionTimeoutMs() / 2, heartbeatDone); + } else { + // Sending a probe request. + this.statInfo.runningState = RunningState.APPENDING_ENTRIES; + this.statInfo.firstLogIndex = this.nextIndex; + this.statInfo.lastLogIndex = this.nextIndex - 1; + this.appendEntriesCounter++; + this.state = State.Probe; + final int stateVersion = this.version; + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), + request, -1, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onRpcReturned(Replicator.this.id, RequestType.AppendEntries, status, request, + getResponse(), seq, stateVersion, monotonicSendTimeMs); + } + + }); + + addInflight(RequestType.AppendEntries, this.nextIndex, 0, 0, seq, rpcFuture); + } + LOG.debug("Node {} send HeartbeatRequest to {} term {} lastCommittedIndex {}", this.options.getNode() + .getNodeId(), this.options.getPeerId(), this.options.getTerm(), request.getCommittedIndex()); + } finally { + this.id.unlock(); + } + } + + boolean prepareEntry(final long nextSendingIndex, final int offset, final RaftOutter.EntryMeta.Builder emb, + final ByteBufferCollector dateBuffer) { + if (dateBuffer.capacity() >= this.raftOptions.getMaxBodySize()) { + return false; + } + final long logIndex = nextSendingIndex + offset; + final LogEntry entry = this.options.getLogManager().getEntry(logIndex); + if (entry == null) { + return false; + } + emb.setTerm(entry.getId().getTerm()); + if (entry.hasChecksum()) { + emb.setChecksum(entry.getChecksum()); //since 1.2.6 + } + emb.setType(entry.getType()); + if (entry.getPeers() != null) { + Requires.requireTrue(!entry.getPeers().isEmpty(), "Empty peers at logIndex=%d", logIndex); + for (final PeerId peer : entry.getPeers()) { + emb.addPeers(peer.toString()); + } + if (entry.getOldPeers() != null) { + for (final PeerId peer : entry.getOldPeers()) { + emb.addOldPeers(peer.toString()); + } + } + } else { + Requires.requireTrue(entry.getType() != EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION, + "Empty peers but is ENTRY_TYPE_CONFIGURATION type at logIndex=%d", logIndex); + } + final int remaining = entry.getData() != null ? entry.getData().remaining() : 0; + emb.setDataLen(remaining); + if (entry.getData() != null) { + //should slice entry data + dateBuffer.put(entry.getData().slice()); + } + return true; + } + + public static ThreadId start(final ReplicatorOptions opts, final RaftOptions raftOptions) { + if (opts.getLogManager() == null || opts.getBallotBox() == null || opts.getNode() == null) { + throw new IllegalArgumentException("Invalid ReplicatorOptions."); + } + final Replicator r = new Replicator(opts, raftOptions); + if (!r.rpcService.connect(opts.getPeerId().getEndpoint())) { + LOG.error("Fail to init sending channel to {}", opts.getPeerId()); + //Return and it will be retried later. + return null; + } + + //Register replicator metric set. + final MetricRegistry metricRegistry = opts.getNode().getNodeMetrics().getMetricRegistry(); + if (metricRegistry != null) { + try { + final String replicatorMetricName = getReplicatorMetricName(opts); + if (!metricRegistry.getNames().contains(replicatorMetricName)) { + metricRegistry.register(replicatorMetricName, new ReplicatorMetricSet(opts, r)); + } + } catch (final IllegalArgumentException e) { + //ignore + } + } + + //Start replication + r.id = new ThreadId(r, r); + r.id.lock(); + LOG.info("Replicator={}@{} is started", r.id, r.options.getPeerId()); + r.catchUpClosure = null; + r.lastRpcSendTimestamp = Utils.monotonicMs(); + r.startHeartbeatTimer(Utils.nowMs()); + //id.unlock in sendEmptyEntries + r.sendEmptyEntries(false); + return r.id; + } + + private static String getReplicatorMetricName(final ReplicatorOptions opts) { + return "replicator-" + opts.getNode().getGroupId() + "/" + opts.getPeerId(); + } + + public static void waitForCaughtUp(final ThreadId id, final long maxMargin, final long dueTime, final CatchUpClosure done) { + final Replicator r = (Replicator) id.lock(); + + if (r == null) { + Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "No such replicator")); + return; + } + try { + if (r.catchUpClosure != null) { + LOG.error("Previous wait_for_caught_up is not over"); + Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "Duplicated call")); + return; + } + done.setMaxMargin(maxMargin); + if (dueTime > 0) { + done.setTimer(r.timerManager.schedule(() -> onCatchUpTimedOut(id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS)); + } + r.catchUpClosure = done; + } finally { + id.unlock(); + } + } + + @Override + public String toString() { + return "Replicator [state=" + this.state + ", statInfo=" + this.statInfo + ",peerId=" + + this.options.getPeerId() + "]"; + } + + static void onBlockTimeoutInNewThread(final ThreadId id) { + if (id != null) { + continueSending(id, RaftError.ETIMEDOUT.getNumber()); + } + } + + /** + * Unblock and continue sending right now. + */ + static void unBlockAndSendNow(final ThreadId id) { + if (id == null) { + // It was destroyed already + return; + } + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + try { + if (r.blockTimer != null) { + if (r.blockTimer.cancel(true)) { + onBlockTimeout(id); + } + } + } finally { + id.unlock(); + } + } + + static boolean continueSending(final ThreadId id, final int errCode) { + if (id == null) { + //It was destroyed already + return true; + } + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + r.waitId = -1; + if (errCode == RaftError.ETIMEDOUT.getNumber()) { + // Send empty entries after block timeout to check the correct + // _next_index otherwise the replicator is likely waits in executor.shutdown(); + // _wait_more_entries and no further logs would be replicated even if the + // last_index of this followers is less than |next_index - 1| + r.sendEmptyEntries(false); + } else if (errCode != RaftError.ESTOP.getNumber()) { + // id is unlock in _send_entries + r.sendEntries(); + } else { + LOG.warn("Replicator {} stops sending entries.", id); + id.unlock(); + } + return true; + } + + static void onBlockTimeout(final ThreadId arg) { + Utils.runInThread(() -> onBlockTimeoutInNewThread(arg)); + } + + void block(final long startTimeMs, @SuppressWarnings("unused") final int errorCode) { + // TODO: Currently we don't care about error_code which indicates why the + // very RPC fails. To make it better there should be different timeout for + // each individual error (e.g. we don't need check every + // heartbeat_timeout_ms whether a dead follower has come back), but it's just + // fine now. + final long dueTime = startTimeMs + this.options.getDynamicHeartBeatTimeoutMs(); + try { + LOG.debug("Blocking {} for {} ms", this.options.getPeerId(), this.options.getDynamicHeartBeatTimeoutMs()); + this.blockTimer = this.timerManager.schedule(() -> onBlockTimeout(this.id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS); + this.statInfo.runningState = RunningState.BLOCKING; + this.id.unlock(); + } catch (final Exception e) { + LOG.error("Fail to add timer", e); + // id unlock in sendEmptyEntries. + sendEmptyEntries(false); + } + } + + @Override + public void onError(final ThreadId id, final Object data, final int errorCode) { + final Replicator r = (Replicator) data; + if (errorCode == RaftError.ESTOP.getNumber()) { + for (final Inflight inflight : r.inflights) { + if (inflight != r.rpcInFly) { + inflight.rpcFuture.cancel(true); + } + } + if (r.rpcInFly != null) { + r.rpcInFly.rpcFuture.cancel(true); + r.rpcInFly = null; + } + if (r.heartbeatInFly != null) { + r.heartbeatInFly.cancel(true); + r.heartbeatInFly = null; + } + if (r.timeoutNowInFly != null) { + r.timeoutNowInFly.cancel(true); + r.timeoutNowInFly = null; + } + if (r.heartbeatTimer != null) { + r.heartbeatTimer.cancel(true); + r.heartbeatTimer = null; + } + if (r.waitId >= 0) { + r.options.getLogManager().removeWaiter(r.waitId); + } + r.notifyOnCaughtUp(errorCode, true); + r.destroy(); + } else if (errorCode == RaftError.ETIMEDOUT.getNumber()) { + id.unlock(); + Utils.runInThread(() -> sendHeartbeat(id)); + } else { + id.unlock(); + // noinspection ConstantConditions + Requires.requireTrue(false, "Unknown error code for replicator: " + errorCode); + } + } + + private static void onCatchUpTimedOut(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + try { + r.notifyOnCaughtUp(RaftError.ETIMEDOUT.getNumber(), false); + } finally { + id.unlock(); + } + } + + private void notifyOnCaughtUp(final int code, final boolean beforeDestroy) { + if (this.catchUpClosure == null) { + return; + } + if (code != RaftError.ETIMEDOUT.getNumber()) { + if (this.nextIndex - 1 + this.catchUpClosure.getMaxMargin() < this.options.getLogManager() + .getLastLogIndex()) { + return; + } + if (this.catchUpClosure.isErrorWasSet()) { + return; + } + this.catchUpClosure.setErrorWasSet(true); + if (code != 0) { + this.catchUpClosure.getStatus().setError(code, RaftError.describeCode(code)); + } + if (this.catchUpClosure.hasTimer()) { + if (!beforeDestroy && !this.catchUpClosure.getTimer().cancel(true)) { + // There's running timer task, let timer task trigger + // on_caught_up to void ABA problem + return; + } + } + } else { + //timed out + if (!this.catchUpClosure.isErrorWasSet()) { + this.catchUpClosure.getStatus().setError(code, RaftError.describeCode(code)); + } + } + final CatchUpClosure savedClosure = this.catchUpClosure; + this.catchUpClosure = null; + Utils.runClosureInThread(savedClosure, savedClosure.getStatus()); + } + + private static void onTimeout(final ThreadId id) { + if (id != null) { + id.setError(RaftError.ETIMEDOUT.getNumber()); + } else { + LOG.warn("Replicator id is null when timeout, maybe it's destroyed."); + } + } + + void destroy() { + final ThreadId savedId = this.id; + LOG.info("Replicator {} is going to quit", savedId); + this.id = null; + if (this.reader != null) { + Utils.closeQuietly(this.reader); + this.reader = null; + } + // Unregister replicator metric set + if (this.options.getNode().getNodeMetrics().getMetricRegistry() != null) { + this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options)); + } + this.state = State.Destroyed; + savedId.unlockAndDestroy(); + } + + static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request, + final AppendEntriesResponse response, final long rpcSendTime) { + if (id == null) { + // replicator already was destroyed. + return; + } + final long startTimeMs = Utils.nowMs(); + Replicator r; + if ((r = (Replicator) id.lock()) == null) { + return; + } + try { + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received HeartbeatResponse from "). // + append(r.options.getPeerId()). // + append(" prevLogIndex=").append(request.getPrevLogIndex()). // + append(" prevLogTerm=").append(request.getPrevLogTerm()); + } + if (!status.isOk()) { + if (isLogDebugEnabled) { + sb.append(" fail, sleep."); + LOG.debug(sb.toString()); + } + r.state = State.Probe; + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), + r.consecutiveErrorTimes, status); + } + r.startHeartbeatTimer(startTimeMs); + return; + } + r.consecutiveErrorTimes = 0; + if (response.getTerm() > r.options.getTerm()) { + if (isLogDebugEnabled) { + sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") + .append(r.options.getTerm()); + LOG.debug(sb.toString()); + } + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); + return; + } + if (isLogDebugEnabled) { + LOG.debug(sb.toString()); + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + r.startHeartbeatTimer(startTimeMs); + } finally { + id.unlock(); + } + } + + @SuppressWarnings("ContinueOrBreakFromFinallyBlock") + static void onRpcReturned(final ThreadId id, final RequestType reqType, final Status status, final Message request, + final Message response, final int seq, final int stateVersion, final long rpcSendTime) { + if (id == null) { + return; + } + final long startTimeMs = Utils.nowMs(); + Replicator r; + if ((r = (Replicator) id.lock()) == null) { + return; + } + + if (stateVersion != r.version) { + LOG.debug( + "Replicator {} ignored old version response {}, current version is {}, request is {}\n, and response is {}\n, status is {}.", + r, stateVersion, r.version, request, response, status); + id.unlock(); + return; + } + + final PriorityQueue holdingQueue = r.pendingResponses; + holdingQueue.add(new RpcResponse(reqType, seq, status, request, response, rpcSendTime)); + + if (holdingQueue.size() > r.raftOptions.getMaxReplicatorInflightMsgs()) { + LOG.warn("Too many pending responses {} for replicator {}, maxReplicatorInflightMsgs={}", + holdingQueue.size(), r.options.getPeerId(), r.raftOptions.getMaxReplicatorInflightMsgs()); + r.resetInflights(); + r.state = State.Probe; + r.sendEmptyEntries(false); + return; + } + + boolean continueSendEntries = false; + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Replicator ").append(r).append(" is processing RPC responses,"); + } + try { + int processed = 0; + while (!holdingQueue.isEmpty()) { + final RpcResponse queuedPipelinedResponse = holdingQueue.peek(); + + //sequence mismatch, waiting for next response. + if (queuedPipelinedResponse.seq != r.requiredNextSeq) { + if (processed > 0) { + if (isLogDebugEnabled) { + sb.append("has processed ").append(processed).append(" responses,"); + } + break; + } else { + //Do not processed any responses, UNLOCK id and return. + continueSendEntries = false; + id.unlock(); + return; + } + } + holdingQueue.remove(); + processed++; + final Inflight inflight = r.pollInflight(); + if (inflight == null) { + // The previous in-flight requests were cleared. + if (isLogDebugEnabled) { + sb.append("ignore response because request not found:").append(queuedPipelinedResponse) + .append(",\n"); + } + continue; + } + if (inflight.seq != queuedPipelinedResponse.seq) { + // reset state + LOG.warn( + "Replicator {} response sequence out of order, expect {}, but it is {}, reset state to try again.", + r, inflight.seq, queuedPipelinedResponse.seq); + r.resetInflights(); + r.state = State.Probe; + continueSendEntries = false; + r.block(Utils.nowMs(), RaftError.EREQUEST.getNumber()); + return; + } + try { + switch (queuedPipelinedResponse.requestType) { + case AppendEntries: + continueSendEntries = onAppendEntriesReturned(id, inflight, queuedPipelinedResponse.status, + (AppendEntriesRequest) queuedPipelinedResponse.request, + (AppendEntriesResponse) queuedPipelinedResponse.response, rpcSendTime, startTimeMs, r); + break; + case Snapshot: + continueSendEntries = onInstallSnapshotReturned(id, r, queuedPipelinedResponse.status, + (InstallSnapshotRequest) queuedPipelinedResponse.request, + (InstallSnapshotResponse) queuedPipelinedResponse.response); + break; + } + } finally { + if (continueSendEntries) { + // Success, increase the response sequence. + r.getAndIncrementRequiredNextSeq(); + } else { + // The id is already unlocked in onAppendEntriesReturned/onInstallSnapshotReturned, we SHOULD break out. + break; + } + } + } + } finally { + if (isLogDebugEnabled) { + sb.append(", after processed, continue to send entries: ").append(continueSendEntries); + LOG.debug(sb.toString()); + } + if (continueSendEntries) { + // unlock in sendEntries. + r.sendEntries(); + } + } + } + + /** + * Reset in-flight state. + */ + void resetInflights() { + this.version++; + this.inflights.clear(); + this.pendingResponses.clear(); + final int rs = Math.max(this.reqSeq, this.requiredNextSeq); + this.reqSeq = this.requiredNextSeq = rs; + if (this.reader != null) { + Utils.closeQuietly(this.reader); + this.reader = null; + } + } + + private static boolean onAppendEntriesReturned(final ThreadId id, final Inflight inflight, final Status status, + final AppendEntriesRequest request, + final AppendEntriesResponse response, final long rpcSendTime, + final long startTimeMs, final Replicator r) { + if (inflight.startIndex != request.getPrevLogIndex() + 1) { + LOG.warn( + "Replicator {} received invalid AppendEntriesResponse, in-flight startIndex={}, requset prevLogIndex={}, reset the replicator state and probe again.", + r, inflight.startIndex, request.getPrevLogIndex()); + r.resetInflights(); + r.state = State.Probe; + //unlock id in sendEmptyEntries + r.sendEmptyEntries(false); + return false; + } + //record metrics + if (request.getEntriesCount() > 0) { + r.nodeMetrics.recordLatency("replicate-entries", Utils.monotonicMs() - rpcSendTime); + r.nodeMetrics.recordSize("replicate-entries-count", request.getEntriesCount()); + r.nodeMetrics.recordSize("replicate-entries-bytes", request.getData() != null ? request.getData().size() + : 0); + } + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received AppendEntriesResponse from "). // + append(r.options.getPeerId()). // + append(" prevLogIndex=").append(request.getPrevLogIndex()). // + append(" prevLogTerm=").append(request.getPrevLogTerm()). // + append(" count=").append(request.getEntriesCount()); + } + if (!status.isOk()) { + // If the follower crashes, any RPC to the follower fails immediately, + // so we need to block the follower for a while instead of looping until + // it comes back or be removed + // dummy_id is unlock in block + if (isLogDebugEnabled) { + sb.append(" fail, sleep."); + LOG.debug(sb.toString()); + } + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), + r.consecutiveErrorTimes, status); + } + r.resetInflights(); + r.state = State.Probe; + //unlock in in block + r.block(startTimeMs, status.getCode()); + return false; + } + r.consecutiveErrorTimes = 0; + if (!response.getSuccess()) { + if (response.getTerm() > r.options.getTerm()) { + if (isLogDebugEnabled) { + sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") + .append(r.options.getTerm()); + LOG.debug(sb.toString()); + } + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); + return false; + } + if (isLogDebugEnabled) { + sb.append(" fail, find nextIndex remote lastLogIndex ").append(response.getLastLogIndex()) + .append(" local nextIndex ").append(r.nextIndex); + LOG.debug(sb.toString()); + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + //Fail, reset the state to try again from nextIndex. + r.resetInflights(); + // prev_log_index and prev_log_term doesn't match + if (response.getLastLogIndex() + 1 < r.nextIndex) { + LOG.debug("LastLogIndex at peer={} is {}", r.options.getPeerId(), response.getLastLogIndex()); + // The peer contains less logs than leader + r.nextIndex = response.getLastLogIndex() + 1; + } else { + // The peer contains logs from old term which should be truncated, + // decrease _last_log_at_peer by one to test the right index to keep + if (r.nextIndex > 1) { + LOG.debug("logIndex={} dismatch", r.nextIndex); + r.nextIndex--; + } else { + LOG.error("Peer={} declares that log at index=0 doesn't match, which is not supposed to happen", + r.options.getPeerId()); + } + } + // dummy_id is unlock in _send_heartbeat + r.sendEmptyEntries(false); + return false; + } + if (isLogDebugEnabled) { + sb.append(", success"); + LOG.debug(sb.toString()); + } + // success + if (response.getTerm() != r.options.getTerm()) { + r.resetInflights(); + r.state = State.Probe; + LOG.error("Fail, response term {} dismatch, expect term {}", response.getTerm(), r.options.getTerm()); + id.unlock(); + return false; + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + final int entriesSize = request.getEntriesCount(); + if (entriesSize > 0) { + r.options.getBallotBox().commitAt(r.nextIndex, r.nextIndex + entriesSize - 1, r.options.getPeerId()); + if (LOG.isDebugEnabled()) { + LOG.debug("Replicated logs in [{}, {}] to peer {}", r.nextIndex, r.nextIndex + entriesSize - 1, + r.options.getPeerId()); + } + } else { + //The request is probe request, change the state into Replicate. + r.state = State.Replicate; + } + r.nextIndex += entriesSize; + r.hasSucceeded = true; + r.notifyOnCaughtUp(0, false); + // dummy_id is unlock in _send_entries + if (r.timeoutNowIndex > 0 && r.timeoutNowIndex < r.nextIndex) { + r.sendTimeoutNow(false, false); + } + return true; + } + + private boolean fillCommonFields(final AppendEntriesRequest.Builder rb, long prevLogIndex, final boolean isHeartbeat) { + final long prevLogTerm = this.options.getLogManager().getTerm(prevLogIndex); + if (prevLogTerm == 0 && prevLogIndex != 0) { + if (!isHeartbeat) { + Requires.requireTrue(prevLogIndex < this.options.getLogManager().getFirstLogIndex()); + LOG.debug("logIndex={} was compacted", prevLogIndex); + return false; + } else { + // The log at prev_log_index has been compacted, which indicates + // we is or is going to install snapshot to the follower. So we let + // both prev_log_index and prev_log_term be 0 in the heartbeat + // request so that follower would do nothing besides updating its + // leader timestamp. + prevLogIndex = 0; + } + } + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + rb.setPrevLogIndex(prevLogIndex); + rb.setPrevLogTerm(prevLogTerm); + rb.setCommittedIndex(this.options.getBallotBox().getLastCommittedIndex()); + return true; + } + + private void waitMoreEntries(final long nextWaitIndex) { + try { + LOG.debug("Node {} waits more entries", this.options.getNode().getNodeId()); + if (this.waitId >= 0) { + return; + } + this.waitId = this.options.getLogManager().wait(nextWaitIndex - 1, + (arg, errorCode) -> continueSending((ThreadId) arg, errorCode), this.id); + this.statInfo.runningState = RunningState.IDLE; + } finally { + this.id.unlock(); + } + } + + /** + * Send as many requests as possible. + */ + void sendEntries() { + boolean doUnlock = true; + try { + long prevSendIndex = -1; + while (true) { + final long nextSendingIndex = getNextSendIndex(); + if (nextSendingIndex > prevSendIndex) { + if (sendEntries(nextSendingIndex)) { + prevSendIndex = nextSendingIndex; + } else { + doUnlock = false; + // id already unlock in sendEntries when it returns false. + break; + } + } else { + break; + } + } + } finally { + if (doUnlock) { + this.id.unlock(); + } + } + + } + + /** + * Send log entries to follower, returns true when success, otherwise false and unlock the id. + * + * @param nextSendingIndex next sending index + * @return send result. + */ + private boolean sendEntries(final long nextSendingIndex) { + final AppendEntriesRequest.Builder rb = AppendEntriesRequest.newBuilder(); + if (!fillCommonFields(rb, nextSendingIndex - 1, false)) { + //unlock id in installSnapshot + installSnapshot(); + return false; + } + + final int maxEntriesSize = this.raftOptions.getMaxEntriesSize(); + final ByteBufferCollector dataBuffer = ByteBufferCollector.allocate(); + for (int i = 0; i < maxEntriesSize; i++) { + final RaftOutter.EntryMeta.Builder emb = RaftOutter.EntryMeta.newBuilder(); + if (!prepareEntry(nextSendingIndex, i, emb, dataBuffer)) { + break; + } + rb.addEntries(emb.build()); + } + if (rb.getEntriesCount() == 0) { + if (nextSendingIndex < this.options.getLogManager().getFirstLogIndex()) { + installSnapshot(); + return false; + } + // _id is unlock in _wait_more + waitMoreEntries(nextSendingIndex); + return false; + } + + if (dataBuffer.capacity() > 0) { + final ByteBuffer buf = dataBuffer.getBuffer(); + buf.flip(); + rb.setData(ZeroByteStringHelper.wrap(buf)); + } + final AppendEntriesRequest request = rb.build(); + if (LOG.isDebugEnabled()) { + LOG.debug( + "Node {} send AppendEntriesRequest to {} term {} lastCommittedIndex {} prevLogIndex {} prevLogTerm {} logIndex {} count {}", + this.options.getNode().getNodeId(), this.options.getPeerId(), this.options.getTerm(), + request.getCommittedIndex(), request.getPrevLogIndex(), request.getPrevLogTerm(), nextSendingIndex, + request.getEntriesCount()); + } + this.statInfo.runningState = RunningState.APPENDING_ENTRIES; + this.statInfo.firstLogIndex = rb.getPrevLogIndex() + 1; + this.statInfo.lastLogIndex = rb.getPrevLogIndex() + rb.getEntriesCount(); + + final int v = this.version; + final long monotonicSendTimeMs = Utils.monotonicMs(); + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), + request, -1, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onRpcReturned(Replicator.this.id, RequestType.AppendEntries, status, request, getResponse(), seq, + v, monotonicSendTimeMs); + } + + }); + addInflight(RequestType.AppendEntries, nextSendingIndex, request.getEntriesCount(), request.getData().size(), + seq, rpcFuture); + return true; + + } + + public static void sendHeartbeat(final ThreadId id, final RpcResponseClosure closure) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + Utils.runClosureInThread(closure, new Status(RaftError.EHOSTDOWN, "Peer %s is not connected", id)); + return; + } + //id unlock in send empty entries. + r.sendEmptyEntries(true, closure); + } + + private static void sendHeartbeat(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + //unlock in sendEmptyEntries + r.sendEmptyEntries(true); + } + + @SuppressWarnings("SameParameterValue") + private void sendTimeoutNow(final boolean unlockId, final boolean stopAfterFinish) { + this.sendTimeoutNow(unlockId, stopAfterFinish, -1); + } + + private void sendTimeoutNow(final boolean unlockId, final boolean stopAfterFinish, final int timeoutMs) { + final TimeoutNowRequest.Builder rb = TimeoutNowRequest.newBuilder(); + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + try { + if (!stopAfterFinish) { + // This RPC is issued by transfer_leadership, save this call_id so that + // the RPC can be cancelled by stop. + this.timeoutNowInFly = timeoutNow(rb, false, timeoutMs); + this.timeoutNowIndex = 0; + } else { + timeoutNow(rb, true, timeoutMs); + } + } finally { + if (unlockId) { + this.id.unlock(); + } + } + + } + + private Future timeoutNow(final TimeoutNowRequest.Builder rb, final boolean stopAfterFinish, + final int timeoutMs) { + final TimeoutNowRequest request = rb.build(); + return this.rpcService.timeoutNow(this.options.getPeerId().getEndpoint(), request, timeoutMs, + new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + if (Replicator.this.id != null) { + onTimeoutNowReturned(Replicator.this.id, status, request, getResponse(), stopAfterFinish); + } + } + + }); + } + + @SuppressWarnings("unused") + static void onTimeoutNowReturned(final ThreadId id, final Status status, final TimeoutNowRequest request, + final TimeoutNowResponse response, final boolean stopAfterFinish) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received TimeoutNowResponse from "). // + append(r.options.getPeerId()); + } + if (!status.isOk()) { + if (isLogDebugEnabled) { + sb.append(" fail:").append(status); + LOG.debug(sb.toString()); + } + if (stopAfterFinish) { + r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); + r.destroy(); + } else { + id.unlock(); + } + return; + } + if (isLogDebugEnabled) { + sb.append(response.getSuccess() ? " success" : " fail"); + LOG.debug(sb.toString()); + } + if (response.getTerm() > r.options.getTerm()) { + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term timeout_now_response from peer:%s", r.options.getPeerId())); + return; + } + if (stopAfterFinish) { + r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); + r.destroy(); + } else { + id.unlock(); + } + + } + + public static boolean stop(final ThreadId id) { + id.setError(RaftError.ESTOP.getNumber()); + return true; + } + + public static boolean join(final ThreadId id) { + id.join(); + return true; + } + + public static long getLastRpcSendTimestamp(final ThreadId id) { + final Replicator r = (Replicator) id.getData(); + if (r == null) { + return 0L; + } + return r.lastRpcSendTimestamp; + } + + public static boolean transferLeadership(final ThreadId id, final long logIndex) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + // dummy is unlock in _transfer_leadership + return r.transferLeadership(logIndex); + } + + private boolean transferLeadership(final long logIndex) { + if (this.hasSucceeded && this.nextIndex > logIndex) { + // _id is unlock in _send_timeout_now + this.sendTimeoutNow(true, false); + return true; + } + // Register log_index so that _on_rpc_return trigger + // _send_timeout_now if _next_index reaches log_index + this.timeoutNowIndex = logIndex; + this.id.unlock(); + return true; + } + + public static boolean stopTransferLeadership(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + r.timeoutNowIndex = 0; + id.unlock(); + return true; + } + + public static boolean sendTimeoutNowAndStop(final ThreadId id, final int timeoutMs) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + // id unlock in sendTimeoutNow + r.sendTimeoutNow(true, true, timeoutMs); + return true; + } + + public static long getNextIndex(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return 0; + } + long nextIdx = 0; + if (r.hasSucceeded) { + nextIdx = r.nextIndex; + } + id.unlock(); + return nextIdx; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +INTERFACE_NOT_THREAD_SAFE + +### Qualifier: +Unprotected call to method of un-annotated interface com.alipay.sofa.jraft.util.NonReentrantLock. Consider annotating the class with `@ThreadSafe`, adding a lock, or using an interface that is known to be thread-safe. + Reporting because the current class is annotated `@ThreadSafe`. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Replicator.destroy() + +### Procedure Id: +com.alipay.sofa.jraft.core.Replicator.destroy():void.7d6a56b93dd19c576109b0cec5680863 + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/core/Replicator.java + +### Key: +Replicator.java|destroy|INTERFACE_NOT_THREAD_SAFE + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +69cee80e132faa0d291907132991707b + +### Bug Type Hum: +Interface Not Thread Safe + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9214/instruction.md b/inferredbugs-9214/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bc1ae154d72f093d30a2234c152a2736572c6e88 --- /dev/null +++ b/inferredbugs-9214/instruction.md @@ -0,0 +1,379 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-jraft +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.jraft.storage.snapshot.remote; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import javax.annotation.concurrent.ThreadSafe; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.core.TimerManager; +import com.alipay.sofa.jraft.error.RaftError; +import com.alipay.sofa.jraft.option.CopyOptions; +import com.alipay.sofa.jraft.option.RaftOptions; +import com.alipay.sofa.jraft.rpc.RaftClientService; +import com.alipay.sofa.jraft.rpc.RpcRequests.GetFileRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.GetFileResponse; +import com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter; +import com.alipay.sofa.jraft.storage.SnapshotThrottle; +import com.alipay.sofa.jraft.util.ByteBufferCollector; +import com.alipay.sofa.jraft.util.Endpoint; +import com.alipay.sofa.jraft.util.OnlyForTest; +import com.alipay.sofa.jraft.util.Requires; +import com.alipay.sofa.jraft.util.Utils; +import com.google.protobuf.Message; + +/** + * Copy session based on bolt framework. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-08 12:01:23 PM + */ +@ThreadSafe +public class BoltSession implements Session { + + private static final Logger LOG = LoggerFactory.getLogger(BoltSession.class); + + private final Lock lock; + private final Status st; + private final RaftClientService rpcService; + private int retryTimes; + private boolean finished; + private ByteBufferCollector destBuf; + private CopyOptions copyOptions; + private GetFileRequest.Builder requestBuilder; + private final CountDownLatch finishLatch; + private OutputStream outputStream; + private final Endpoint endpoint; + private final GetFileResponseClosure done = new GetFileResponseClosure(); + private ScheduledFuture timer; + private String destPath; + private final RaftOptions raftOptions; + private Future rpcCall; + private final TimerManager timerManager; + private final SnapshotThrottle snapshotThrottle; + + /** + * Get file response closure to answer client. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-13 4:50:21 PM + */ + private class GetFileResponseClosure extends RpcResponseClosureAdapter { + + @Override + public void run(Status status) { + onRpcReturned(status, getResponse()); + } + + } + + public void setDestPath(String destPath) { + this.destPath = destPath; + } + + @OnlyForTest + GetFileResponseClosure getDone() { + return this.done; + } + + @OnlyForTest + Future getRpcCall() { + return this.rpcCall; + } + + @OnlyForTest + ScheduledFuture getTimer() { + return this.timer; + } + + @Override + public void close() throws IOException { + lock.lock(); + try { + if (!this.finished) { + Utils.closeQuietly(this.outputStream); + } + } finally { + lock.unlock(); + } + } + + public BoltSession(RaftClientService rpcService, TimerManager timerManager, SnapshotThrottle snapshotThrottle, + RaftOptions raftOptions, GetFileRequest.Builder rb, Endpoint ep) { + super(); + this.snapshotThrottle = snapshotThrottle; + this.raftOptions = raftOptions; + this.timerManager = timerManager; + this.rpcService = rpcService; + this.requestBuilder = rb; + this.retryTimes = 0; + this.copyOptions = new CopyOptions(); + this.lock = new ReentrantLock(); + this.endpoint = ep; + this.st = Status.OK(); + this.finishLatch = new CountDownLatch(1); + + } + + public void setDestBuf(ByteBufferCollector bufRef) { + this.destBuf = bufRef; + } + + public void setCopyOptions(CopyOptions copyOptions) { + this.copyOptions = copyOptions; + } + + public void setOutputStream(OutputStream out) { + this.outputStream = out; + } + + @Override + public void cancel() { + lock.lock(); + try { + if (this.finished) { + return; + } + if (this.timer != null) { + this.timer.cancel(true); + } + if (this.rpcCall != null) { + this.rpcCall.cancel(true); + } + if (st.isOk()) { + st.setError(RaftError.ECANCELED, RaftError.ECANCELED.name()); + } + + this.onFinished(); + } finally { + lock.unlock(); + } + + } + + @Override + public void join() throws InterruptedException { + this.finishLatch.await(); + } + + @Override + public Status status() { + return st; + } + + private void onFinished() { + if (!this.finished) { + if (outputStream != null) { + Utils.closeQuietly(this.outputStream); + this.outputStream = null; + } + if (this.destBuf != null) { + final ByteBuffer buf = this.destBuf.getBuffer(); + if (buf != null) { + buf.flip(); + } + this.destBuf = null; + } + this.finished = true; + this.finishLatch.countDown(); + } + } + + private void onTimer() { + Utils.runInThread(this::sendNextRpc); + } + + void onRpcReturned(Status status, GetFileResponse response) { + lock.lock(); + try { + if (this.finished) { + return; + } + if (!status.isOk()) { + // Reset count to make next rpc retry the previous one + requestBuilder.setCount(0); + if (status.getCode() == RaftError.ECANCELED.getNumber()) { + if (st.isOk()) { + st.setError(status.getCode(), status.getErrorMsg()); + this.onFinished(); + return; + } + } + + // Throttled reading failure does not increase _retry_times + if (status.getCode() != RaftError.EAGAIN.getNumber() + && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { + if (st.isOk()) { + st.setError(status.getCode(), status.getErrorMsg()); + this.onFinished(); + return; + } + } + this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), + TimeUnit.MILLISECONDS); + return; + } + this.retryTimes = 0; + Requires.requireNonNull(response, "response"); + // Reset count to |real_read_size| to make next rpc get the right offset + if (response.hasReadSize() && response.getReadSize() != 0) { + this.requestBuilder.setCount(response.getReadSize()); + } + if (outputStream != null) { + try { + response.getData().writeTo(outputStream); + } catch (final IOException e) { + LOG.error("Fail to write into file {}", this.destPath); + st.setError(RaftError.EIO, RaftError.EIO.name()); + this.onFinished(); + return; + } + } else { + final byte[] data = response.getData().toByteArray(); + this.destBuf.put(data); + } + if (response.getEof()) { + onFinished(); + return; + } + } finally { + lock.unlock(); + } + this.sendNextRpc(); + } + + /** + * Send next RPC request to get a piece of file data. + */ + void sendNextRpc() { + this.timer = null; + final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); + final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; + this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); + this.lock.lock(); + try { + if (this.finished) { + return; + } + // throttle + long newMaxCount = maxCount; + if (this.snapshotThrottle != null) { + newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); + if (newMaxCount == 0) { + // Reset count to make next rpc retry the previous one + this.requestBuilder.setCount(0); + this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), + TimeUnit.MILLISECONDS); + return; + } + } + this.requestBuilder.setCount(newMaxCount); + LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); + this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), + this.copyOptions.getTimeoutMs(), done); + } finally { + lock.unlock(); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.cancel` reads with synchronization from `this.com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.timer`. Potentially races with unsynchronized write in method `BoltSession.sendNextRpc()`. + Reporting because the current class is annotated `@ThreadSafe`, so we assume that this method can run in parallel with other non-private methods in the class (including itself). + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BoltSession.cancel() + +### Procedure Id: +com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.cancel():void.680b882c9cc64a426afc7e2496c72dc9 + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/storage/snapshot/remote/BoltSession.java + +### Key: +BoltSession.java|cancel|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +81abf346f102c065d1968e6005279354 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9215/instruction.md b/inferredbugs-9215/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b6e3323956da3b77bf9757dbf15413834302c28b --- /dev/null +++ b/inferredbugs-9215/instruction.md @@ -0,0 +1,379 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-jraft +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.jraft.storage.snapshot.remote; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import javax.annotation.concurrent.ThreadSafe; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.core.TimerManager; +import com.alipay.sofa.jraft.error.RaftError; +import com.alipay.sofa.jraft.option.CopyOptions; +import com.alipay.sofa.jraft.option.RaftOptions; +import com.alipay.sofa.jraft.rpc.RaftClientService; +import com.alipay.sofa.jraft.rpc.RpcRequests.GetFileRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.GetFileResponse; +import com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter; +import com.alipay.sofa.jraft.storage.SnapshotThrottle; +import com.alipay.sofa.jraft.util.ByteBufferCollector; +import com.alipay.sofa.jraft.util.Endpoint; +import com.alipay.sofa.jraft.util.OnlyForTest; +import com.alipay.sofa.jraft.util.Requires; +import com.alipay.sofa.jraft.util.Utils; +import com.google.protobuf.Message; + +/** + * Copy session based on bolt framework. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-08 12:01:23 PM + */ +@ThreadSafe +public class BoltSession implements Session { + + private static final Logger LOG = LoggerFactory.getLogger(BoltSession.class); + + private final Lock lock; + private final Status st; + private final RaftClientService rpcService; + private int retryTimes; + private boolean finished; + private ByteBufferCollector destBuf; + private CopyOptions copyOptions; + private GetFileRequest.Builder requestBuilder; + private final CountDownLatch finishLatch; + private OutputStream outputStream; + private final Endpoint endpoint; + private final GetFileResponseClosure done = new GetFileResponseClosure(); + private ScheduledFuture timer; + private String destPath; + private final RaftOptions raftOptions; + private Future rpcCall; + private final TimerManager timerManager; + private final SnapshotThrottle snapshotThrottle; + + /** + * Get file response closure to answer client. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-13 4:50:21 PM + */ + private class GetFileResponseClosure extends RpcResponseClosureAdapter { + + @Override + public void run(Status status) { + onRpcReturned(status, getResponse()); + } + + } + + public void setDestPath(String destPath) { + this.destPath = destPath; + } + + @OnlyForTest + GetFileResponseClosure getDone() { + return this.done; + } + + @OnlyForTest + Future getRpcCall() { + return this.rpcCall; + } + + @OnlyForTest + ScheduledFuture getTimer() { + return this.timer; + } + + @Override + public void close() throws IOException { + lock.lock(); + try { + if (!this.finished) { + Utils.closeQuietly(this.outputStream); + } + } finally { + lock.unlock(); + } + } + + public BoltSession(RaftClientService rpcService, TimerManager timerManager, SnapshotThrottle snapshotThrottle, + RaftOptions raftOptions, GetFileRequest.Builder rb, Endpoint ep) { + super(); + this.snapshotThrottle = snapshotThrottle; + this.raftOptions = raftOptions; + this.timerManager = timerManager; + this.rpcService = rpcService; + this.requestBuilder = rb; + this.retryTimes = 0; + this.copyOptions = new CopyOptions(); + this.lock = new ReentrantLock(); + this.endpoint = ep; + this.st = Status.OK(); + this.finishLatch = new CountDownLatch(1); + + } + + public void setDestBuf(ByteBufferCollector bufRef) { + this.destBuf = bufRef; + } + + public void setCopyOptions(CopyOptions copyOptions) { + this.copyOptions = copyOptions; + } + + public void setOutputStream(OutputStream out) { + this.outputStream = out; + } + + @Override + public void cancel() { + lock.lock(); + try { + if (this.finished) { + return; + } + if (this.timer != null) { + this.timer.cancel(true); + } + if (this.rpcCall != null) { + this.rpcCall.cancel(true); + } + if (st.isOk()) { + st.setError(RaftError.ECANCELED, RaftError.ECANCELED.name()); + } + + this.onFinished(); + } finally { + lock.unlock(); + } + + } + + @Override + public void join() throws InterruptedException { + this.finishLatch.await(); + } + + @Override + public Status status() { + return st; + } + + private void onFinished() { + if (!this.finished) { + if (outputStream != null) { + Utils.closeQuietly(this.outputStream); + this.outputStream = null; + } + if (this.destBuf != null) { + final ByteBuffer buf = this.destBuf.getBuffer(); + if (buf != null) { + buf.flip(); + } + this.destBuf = null; + } + this.finished = true; + this.finishLatch.countDown(); + } + } + + private void onTimer() { + Utils.runInThread(this::sendNextRpc); + } + + void onRpcReturned(Status status, GetFileResponse response) { + lock.lock(); + try { + if (this.finished) { + return; + } + if (!status.isOk()) { + // Reset count to make next rpc retry the previous one + requestBuilder.setCount(0); + if (status.getCode() == RaftError.ECANCELED.getNumber()) { + if (st.isOk()) { + st.setError(status.getCode(), status.getErrorMsg()); + this.onFinished(); + return; + } + } + + // Throttled reading failure does not increase _retry_times + if (status.getCode() != RaftError.EAGAIN.getNumber() + && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { + if (st.isOk()) { + st.setError(status.getCode(), status.getErrorMsg()); + this.onFinished(); + return; + } + } + this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), + TimeUnit.MILLISECONDS); + return; + } + this.retryTimes = 0; + Requires.requireNonNull(response, "response"); + // Reset count to |real_read_size| to make next rpc get the right offset + if (response.hasReadSize() && response.getReadSize() != 0) { + this.requestBuilder.setCount(response.getReadSize()); + } + if (outputStream != null) { + try { + response.getData().writeTo(outputStream); + } catch (final IOException e) { + LOG.error("Fail to write into file {}", this.destPath); + st.setError(RaftError.EIO, RaftError.EIO.name()); + this.onFinished(); + return; + } + } else { + final byte[] data = response.getData().toByteArray(); + this.destBuf.put(data); + } + if (response.getEof()) { + onFinished(); + return; + } + } finally { + lock.unlock(); + } + this.sendNextRpc(); + } + + /** + * Send next RPC request to get a piece of file data. + */ + void sendNextRpc() { + this.timer = null; + final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); + final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; + this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); + this.lock.lock(); + try { + if (this.finished) { + return; + } + // throttle + long newMaxCount = maxCount; + if (this.snapshotThrottle != null) { + newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); + if (newMaxCount == 0) { + // Reset count to make next rpc retry the previous one + this.requestBuilder.setCount(0); + this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), + TimeUnit.MILLISECONDS); + return; + } + } + this.requestBuilder.setCount(newMaxCount); + LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); + this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), + this.copyOptions.getTimeoutMs(), done); + } finally { + lock.unlock(); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.sendNextRpc` indirectly writes to field `this.com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.requestBuilder.com.alipay.sofa.jraft.rpc.RpcRequests$GetFileRequest$Builder.bitField0_` outside of synchronization. + Reporting because the current class is annotated `@ThreadSafe`, so we assume that this method can run in parallel with other non-private methods in the class (including itself). + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BoltSession.sendNextRpc() + +### Procedure Id: +com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.sendNextRpc():void.df8bf8734eb44ec2bca56be19a43f342 + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/storage/snapshot/remote/BoltSession.java + +### Key: +BoltSession.java|sendNextRpc|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +96daf072f05480bec2e6c48192626200 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9223/instruction.md b/inferredbugs-9223/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..15b468f9cba1f00e509fb4bc69b7b9c52755d124 --- /dev/null +++ b/inferredbugs-9223/instruction.md @@ -0,0 +1,1803 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-jraft +**Bug ID:** 36 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.jraft.core; + +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import javax.annotation.concurrent.ThreadSafe; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alipay.sofa.jraft.Node; +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.closure.CatchUpClosure; +import com.alipay.sofa.jraft.entity.EnumOutter; +import com.alipay.sofa.jraft.entity.LogEntry; +import com.alipay.sofa.jraft.entity.PeerId; +import com.alipay.sofa.jraft.entity.RaftOutter; +import com.alipay.sofa.jraft.error.RaftError; +import com.alipay.sofa.jraft.error.RaftException; +import com.alipay.sofa.jraft.option.RaftOptions; +import com.alipay.sofa.jraft.option.ReplicatorOptions; +import com.alipay.sofa.jraft.rpc.RaftClientService; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowResponse; +import com.alipay.sofa.jraft.rpc.RpcResponseClosure; +import com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter; +import com.alipay.sofa.jraft.storage.snapshot.SnapshotReader; +import com.alipay.sofa.jraft.util.ByteBufferCollector; +import com.alipay.sofa.jraft.util.OnlyForTest; +import com.alipay.sofa.jraft.util.Recyclable; +import com.alipay.sofa.jraft.util.RecyclableByteBufferList; +import com.alipay.sofa.jraft.util.RecycleUtil; +import com.alipay.sofa.jraft.util.Requires; +import com.alipay.sofa.jraft.util.ThreadId; +import com.alipay.sofa.jraft.util.Utils; +import com.codahale.metrics.Gauge; +import com.codahale.metrics.Metric; +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.MetricSet; +import com.google.protobuf.Message; +import com.google.protobuf.ZeroByteStringHelper; + +/** + * Replicator for replicating log entry from leader to followers. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:32:02 AM + */ +@ThreadSafe +public class Replicator implements ThreadId.OnError { + + private static final Logger LOG = LoggerFactory.getLogger(Replicator.class); + + private final RaftClientService rpcService; + // Next sending log index + private volatile long nextIndex; + private int consecutiveErrorTimes = 0; + private boolean hasSucceeded; + private long timeoutNowIndex; + private volatile long lastRpcSendTimestamp; + private volatile long heartbeatCounter = 0; + private volatile long appendEntriesCounter = 0; + private volatile long installSnapshotCounter = 0; + protected Stat statInfo = new Stat(); + private ScheduledFuture blockTimer; + + // Cached the latest RPC in-flight request. + private Inflight rpcInFly; + // Heartbeat RPC future + private Future heartbeatInFly; + // Timeout request RPC future + private Future timeoutNowInFly; + // In-flight RPC requests, FIFO queue + private final ArrayDeque inflights = new ArrayDeque<>(); + + private long waitId = -1L; + protected ThreadId id; + private final ReplicatorOptions options; + private final RaftOptions raftOptions; + + private ScheduledFuture heartbeatTimer; + private volatile SnapshotReader reader; + private CatchUpClosure catchUpClosure; + private final TimerManager timerManager; + private final NodeMetrics nodeMetrics; + private volatile State state; + + // Request sequence + private int reqSeq = 0; + // Response sequence + private int requiredNextSeq = 0; + // Replicator state reset version + private int version = 0; + + // Pending response queue; + private final PriorityQueue pendingResponses = new PriorityQueue<>(50); + + private int getAndIncrementReqSeq() { + final int prev = this.reqSeq; + this.reqSeq++; + if (this.reqSeq < 0) { + this.reqSeq = 0; + } + return prev; + } + + private int getAndIncrementRequiredNextSeq() { + final int prev = this.requiredNextSeq; + this.requiredNextSeq++; + if (this.requiredNextSeq < 0) { + this.requiredNextSeq = 0; + } + return prev; + } + + /** + * Replicator state + * @author dennis + * + */ + public enum State { + Probe, // probe follower state + Snapshot, // installing snapshot to follower + Replicate, // replicate logs normally + Destroyed // destroyed + } + + public Replicator(final ReplicatorOptions replicatorOptions, final RaftOptions raftOptions) { + super(); + this.options = replicatorOptions; + this.nodeMetrics = this.options.getNode().getNodeMetrics(); + this.nextIndex = this.options.getLogManager().getLastLogIndex() + 1; + this.timerManager = replicatorOptions.getTimerManager(); + this.raftOptions = raftOptions; + this.rpcService = replicatorOptions.getRaftRpcService(); + } + + /** + * Replicator metric set. + * @author dennis + * + */ + private static final class ReplicatorMetricSet implements MetricSet { + private final ReplicatorOptions opts; + private final Replicator r; + + private ReplicatorMetricSet(final ReplicatorOptions opts, final Replicator r) { + this.opts = opts; + this.r = r; + } + + @Override + public Map getMetrics() { + final Map gauges = new HashMap<>(); + gauges.put("log-lags", + (Gauge) () -> this.opts.getLogManager().getLastLogIndex() - (this.r.nextIndex - 1)); + gauges.put("next-index", (Gauge) () -> this.r.nextIndex); + gauges.put("heartbeat-times", (Gauge) () -> this.r.heartbeatCounter); + gauges.put("install-snapshot-times", (Gauge) () -> this.r.installSnapshotCounter); + gauges.put("append-entries-times", (Gauge) () -> this.r.appendEntriesCounter); + return gauges; + } + } + + /** + * Internal state + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:38:45 AM + */ + enum RunningState { + IDLE, // idle + BLOCKING, // blocking state + APPENDING_ENTRIES, // appending log entries + INSTALLING_SNAPSHOT // installing snapshot + } + + enum ReplicatorEvent { + CREATED, // created + ERROR, // error + DESTROYED // destroyed + } + + /** + * User can implement the ReplicatorStateListener interface by themselves. + * So they can do some their own logic codes when replicator created, destroyed or had some errors. + * + * @author zongtanghu + * + * 2019-Aug-20 2:32:10 PM + */ + public interface ReplicatorStateListener { + + /** + * Called when this replicator has been created. + * + * @param peer replicator related peerId + */ + void onCreated(final PeerId peer); + + /** + * Called when this replicator has some errors. + * + * @param peer replicator related peerId + * @param status replicator's error detailed status + */ + void onError(final PeerId peer, final Status status); + + /** + * Called when this replicator has been destroyed. + * + * @param peer replicator related peerId + */ + void onDestroyed(final PeerId peer); + } + + /** + * Notify replicator event(such as created, error, destroyed) to replicatorStateListener which is implemented by users. + * + * @param replicator replicator object + * @param event replicator's state listener event type + * @param status replicator's error detailed status + */ + private static void notifyReplicatorStatusListener(final Replicator replicator, final ReplicatorEvent event, final Status status) { + final ReplicatorOptions replicatorOpts = Requires.requireNonNull(replicator.getOpts(), "replicatorOptions"); + final Node node = Requires.requireNonNull(replicatorOpts.getNode(), "node"); + final PeerId peer = Requires.requireNonNull(replicatorOpts.getPeerId(), "peer"); + + final List listenerList = node.getReplicatorStatueListeners(); + for (int i = 0; i < listenerList.size(); i++) { + final ReplicatorStateListener listener = listenerList.get(i); + if(listener != null) { + try { + switch (event) { + case CREATED: + Utils.runInThread(() -> listener.onCreated(peer)); + break; + case ERROR: + Utils.runInThread(() -> listener.onError(peer, status)); + break; + case DESTROYED: + Utils.runInThread(() -> listener.onDestroyed(peer)); + break; + default: + break; + } + } catch (final Exception e) { + LOG.error("Fail to notify ReplicatorStatusListener, listener={}, event={}.", listener, event); + } + } + } + } + + /** + * Notify replicator event(such as created, error, destroyed) to replicatorStateListener which is implemented by users for none status. + * + * @param replicator replicator object + * @param event replicator's state listener event type + */ + private static void notifyReplicatorStatusListener(final Replicator replicator, final ReplicatorEvent event) { + notifyReplicatorStatusListener(replicator, event, null); + } + + /** + * Statistics structure + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:38:53 AM + */ + static class Stat { + RunningState runningState; + long firstLogIndex; + long lastLogIncluded; + long lastLogIndex; + long lastTermIncluded; + + @Override + public String toString() { + return ""; + } + + } + + // In-flight request type + enum RequestType { + Snapshot, // install snapshot + AppendEntries // replicate logs + } + + /** + * In-flight request. + * @author dennis + * + */ + static class Inflight { + // In-flight request count + final int count; + // Start log index + final long startIndex; + // Entries size in bytes + final int size; + // RPC future + final Future rpcFuture; + final RequestType requestType; + // Request sequence. + final int seq; + + public Inflight(final RequestType requestType, final long startIndex, final int count, final int size, + final int seq, final Future rpcFuture) { + super(); + this.seq = seq; + this.requestType = requestType; + this.count = count; + this.startIndex = startIndex; + this.size = size; + this.rpcFuture = rpcFuture; + } + + @Override + public String toString() { + return "Inflight [count=" + this.count + ", startIndex=" + this.startIndex + ", size=" + this.size + + ", rpcFuture=" + this.rpcFuture + ", requestType=" + this.requestType + ", seq=" + this.seq + "]"; + } + + boolean isSendingLogEntries() { + return this.requestType == RequestType.AppendEntries && this.count > 0; + } + } + + /** + * RPC response for AppendEntries/InstallSnapshot. + * @author dennis + * + */ + static class RpcResponse implements Comparable { + final Status status; + final Message request; + final Message response; + final long rpcSendTime; + final int seq; + final RequestType requestType; + + public RpcResponse(final RequestType reqType, final int seq, final Status status, final Message request, + final Message response, final long rpcSendTime) { + super(); + this.requestType = reqType; + this.seq = seq; + this.status = status; + this.request = request; + this.response = response; + this.rpcSendTime = rpcSendTime; + } + + @Override + public String toString() { + return "RpcResponse [status=" + this.status + ", request=" + this.request + ", response=" + this.response + + ", rpcSendTime=" + this.rpcSendTime + ", seq=" + this.seq + ", requestType=" + this.requestType + + "]"; + } + + /** + * Sort by sequence. + */ + @Override + public int compareTo(final RpcResponse o) { + return Integer.compare(this.seq, o.seq); + } + } + + @OnlyForTest + ArrayDeque getInflights() { + return this.inflights; + } + + @OnlyForTest + State getState() { + return this.state; + } + + @OnlyForTest + void setState(final State state) { + this.state = state; + } + + @OnlyForTest + int getReqSeq() { + return this.reqSeq; + } + + @OnlyForTest + int getRequiredNextSeq() { + return this.requiredNextSeq; + } + + @OnlyForTest + int getVersion() { + return this.version; + } + + @OnlyForTest + public PriorityQueue getPendingResponses() { + return this.pendingResponses; + } + + @OnlyForTest + long getWaitId() { + return this.waitId; + } + + @OnlyForTest + ScheduledFuture getBlockTimer() { + return this.blockTimer; + } + + @OnlyForTest + long getTimeoutNowIndex() { + return this.timeoutNowIndex; + } + + @OnlyForTest + ReplicatorOptions getOpts() { + return this.options; + } + + @OnlyForTest + long getRealNextIndex() { + return this.nextIndex; + } + + @OnlyForTest + Future getRpcInFly() { + if (this.rpcInFly == null) { + return null; + } + return this.rpcInFly.rpcFuture; + } + + @OnlyForTest + Future getHeartbeatInFly() { + return this.heartbeatInFly; + } + + @OnlyForTest + ScheduledFuture getHeartbeatTimer() { + return this.heartbeatTimer; + } + + @OnlyForTest + void setHasSucceeded() { + this.hasSucceeded = true; + } + + @OnlyForTest + Future getTimeoutNowInFly() { + return this.timeoutNowInFly; + } + + /** + * Adds a in-flight request + * @param reqType type of request + * @param count count if request + * @param size size in bytes + */ + private void addInflight(final RequestType reqType, final long startIndex, final int count, final int size, + final int seq, final Future rpcInfly) { + this.rpcInFly = new Inflight(reqType, startIndex, count, size, seq, rpcInfly); + this.inflights.add(this.rpcInFly); + this.nodeMetrics.recordSize("replicate-inflights-count", this.inflights.size()); + } + + /** + * Returns the next in-flight sending index, return -1 when can't send more in-flight requests. + * + * @return next in-flight sending index + */ + long getNextSendIndex() { + // Fast path + if (this.inflights.isEmpty()) { + return this.nextIndex; + } + // Too many in-flight requests. + if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { + return -1L; + } + // Last request should be a AppendEntries request and has some entries. + if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { + return this.rpcInFly.startIndex + this.rpcInFly.count; + } + return -1L; + } + + private Inflight pollInflight() { + return this.inflights.poll(); + } + + private void startHeartbeatTimer(final long startMs) { + final long dueTime = startMs + this.options.getDynamicHeartBeatTimeoutMs(); + try { + this.heartbeatTimer = this.timerManager.schedule(() -> onTimeout(this.id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS); + } catch (final Exception e) { + LOG.error("Fail to schedule heartbeat timer", e); + onTimeout(this.id); + } + } + + void installSnapshot() { + if (this.state == State.Snapshot) { + LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId()); + this.id.unlock(); + return; + } + boolean doUnlock = true; + try { + Requires.requireTrue(this.reader == null, + "Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(), + this.state); + this.reader = this.options.getSnapshotStorage().open(); + if (this.reader == null) { + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot")); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final String uri = this.reader.generateURIForCopy(); + if (uri == null) { + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader")); + releaseReader(); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final RaftOutter.SnapshotMeta meta = this.reader.load(); + if (meta == null) { + final String snapshotPath = this.reader.getPath(); + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath)); + releaseReader(); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder(); + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + rb.setMeta(meta); + rb.setUri(uri); + + this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT; + this.statInfo.lastLogIncluded = meta.getLastIncludedIndex(); + this.statInfo.lastTermIncluded = meta.getLastIncludedTerm(); + + final InstallSnapshotRequest request = rb.build(); + this.state = State.Snapshot; + // noinspection NonAtomicOperationOnVolatileField + this.installSnapshotCounter++; + final long monotonicSendTimeMs = Utils.monotonicMs(); + final int stateVersion = this.version; + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(), + request, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq, + stateVersion, monotonicSendTimeMs); + } + }); + addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture); + } finally { + if (doUnlock) { + this.id.unlock(); + } + } + } + + @SuppressWarnings("unused") + static boolean onInstallSnapshotReturned(final ThreadId id, final Replicator r, final Status status, + final InstallSnapshotRequest request, + final InstallSnapshotResponse response) { + boolean success = true; + r.releaseReader(); + // noinspection ConstantConditions + do { + final StringBuilder sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received InstallSnapshotResponse from ").append(r.options.getPeerId()). // + append(" lastIncludedIndex=").append(request.getMeta().getLastIncludedIndex()). // + append(" lastIncludedTerm=").append(request.getMeta().getLastIncludedTerm()); + if (!status.isOk()) { + sb.append(" error:").append(status); + LOG.info(sb.toString()); + notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to install snapshot at peer={}, error={}", r.options.getPeerId(), status); + } + success = false; + break; + } + if (!response.getSuccess()) { + sb.append(" success=false"); + LOG.info(sb.toString()); + success = false; + break; + } + // success + r.nextIndex = request.getMeta().getLastIncludedIndex() + 1; + sb.append(" success=true"); + LOG.info(sb.toString()); + } while (false); + // We don't retry installing the snapshot explicitly. + // id is unlock in sendEntries + if (!success) { + //should reset states + r.resetInflights(); + r.state = State.Probe; + r.block(Utils.nowMs(), status.getCode()); + return false; + } + r.hasSucceeded = true; + r.notifyOnCaughtUp(RaftError.SUCCESS.getNumber(), false); + if (r.timeoutNowIndex > 0 && r.timeoutNowIndex < r.nextIndex) { + r.sendTimeoutNow(false, false); + } + // id is unlock in _send_entriesheartbeatCounter + r.state = State.Replicate; + return true; + } + + private void sendEmptyEntries(final boolean isHeartbeat) { + sendEmptyEntries(isHeartbeat, null); + } + + /** + * Send probe or heartbeat request + * @param isHeartbeat if current entries is heartbeat + * @param heartBeatClosure heartbeat callback + */ + @SuppressWarnings("NonAtomicOperationOnVolatileField") + private void sendEmptyEntries(final boolean isHeartbeat, + final RpcResponseClosure heartBeatClosure) { + final AppendEntriesRequest.Builder rb = AppendEntriesRequest.newBuilder(); + if (!fillCommonFields(rb, this.nextIndex - 1, isHeartbeat)) { + // id is unlock in installSnapshot + installSnapshot(); + if (isHeartbeat && heartBeatClosure != null) { + Utils.runClosureInThread(heartBeatClosure, new Status(RaftError.EAGAIN, + "Fail to send heartbeat to peer %s", this.options.getPeerId())); + } + return; + } + try { + final long monotonicSendTimeMs = Utils.monotonicMs(); + final AppendEntriesRequest request = rb.build(); + + if (isHeartbeat) { + // Sending a heartbeat request + this.heartbeatCounter++; + RpcResponseClosure heartbeatDone; + // Prefer passed-in closure. + if (heartBeatClosure != null) { + heartbeatDone = heartBeatClosure; + } else { + heartbeatDone = new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onHeartbeatReturned(Replicator.this.id, status, request, getResponse(), monotonicSendTimeMs); + } + }; + } + this.heartbeatInFly = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), request, + this.options.getElectionTimeoutMs() / 2, heartbeatDone); + } else { + // Sending a probe request. + this.statInfo.runningState = RunningState.APPENDING_ENTRIES; + this.statInfo.firstLogIndex = this.nextIndex; + this.statInfo.lastLogIndex = this.nextIndex - 1; + this.appendEntriesCounter++; + this.state = State.Probe; + final int stateVersion = this.version; + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), + request, -1, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onRpcReturned(Replicator.this.id, RequestType.AppendEntries, status, request, + getResponse(), seq, stateVersion, monotonicSendTimeMs); + } + + }); + + addInflight(RequestType.AppendEntries, this.nextIndex, 0, 0, seq, rpcFuture); + } + LOG.debug("Node {} send HeartbeatRequest to {} term {} lastCommittedIndex {}", this.options.getNode() + .getNodeId(), this.options.getPeerId(), this.options.getTerm(), request.getCommittedIndex()); + } finally { + this.id.unlock(); + } + } + + boolean prepareEntry(final long nextSendingIndex, final int offset, final RaftOutter.EntryMeta.Builder emb, + final RecyclableByteBufferList dateBuffer) { + if (dateBuffer.getCapacity() >= this.raftOptions.getMaxBodySize()) { + return false; + } + final long logIndex = nextSendingIndex + offset; + final LogEntry entry = this.options.getLogManager().getEntry(logIndex); + if (entry == null) { + return false; + } + emb.setTerm(entry.getId().getTerm()); + if (entry.hasChecksum()) { + emb.setChecksum(entry.getChecksum()); //since 1.2.6 + } + emb.setType(entry.getType()); + if (entry.getPeers() != null) { + Requires.requireTrue(!entry.getPeers().isEmpty(), "Empty peers at logIndex=%d", logIndex); + for (final PeerId peer : entry.getPeers()) { + emb.addPeers(peer.toString()); + } + if (entry.getOldPeers() != null) { + for (final PeerId peer : entry.getOldPeers()) { + emb.addOldPeers(peer.toString()); + } + } + } else { + Requires.requireTrue(entry.getType() != EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION, + "Empty peers but is ENTRY_TYPE_CONFIGURATION type at logIndex=%d", logIndex); + } + final int remaining = entry.getData() != null ? entry.getData().remaining() : 0; + emb.setDataLen(remaining); + if (entry.getData() != null) { + // should slice entry data + dateBuffer.add(entry.getData().slice()); + } + return true; + } + + public static ThreadId start(final ReplicatorOptions opts, final RaftOptions raftOptions) { + if (opts.getLogManager() == null || opts.getBallotBox() == null || opts.getNode() == null) { + throw new IllegalArgumentException("Invalid ReplicatorOptions."); + } + final Replicator r = new Replicator(opts, raftOptions); + if (!r.rpcService.connect(opts.getPeerId().getEndpoint())) { + LOG.error("Fail to init sending channel to {}.", opts.getPeerId()); + // Return and it will be retried later. + return null; + } + + // Register replicator metric set. + final MetricRegistry metricRegistry = opts.getNode().getNodeMetrics().getMetricRegistry(); + if (metricRegistry != null) { + try { + final String replicatorMetricName = getReplicatorMetricName(opts); + if (!metricRegistry.getNames().contains(replicatorMetricName)) { + metricRegistry.register(replicatorMetricName, new ReplicatorMetricSet(opts, r)); + } + } catch (final IllegalArgumentException e) { + // ignore + } + } + + // Start replication + r.id = new ThreadId(r, r); + r.id.lock(); + notifyReplicatorStatusListener(r, ReplicatorEvent.CREATED); + LOG.info("Replicator={}@{} is started", r.id, r.options.getPeerId()); + r.catchUpClosure = null; + r.lastRpcSendTimestamp = Utils.monotonicMs(); + r.startHeartbeatTimer(Utils.nowMs()); + // id.unlock in sendEmptyEntries + r.sendEmptyEntries(false); + return r.id; + } + + private static String getReplicatorMetricName(final ReplicatorOptions opts) { + return "replicator-" + opts.getNode().getGroupId() + "/" + opts.getPeerId(); + } + + public static void waitForCaughtUp(final ThreadId id, final long maxMargin, final long dueTime, + final CatchUpClosure done) { + final Replicator r = (Replicator) id.lock(); + + if (r == null) { + Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "No such replicator")); + return; + } + try { + if (r.catchUpClosure != null) { + LOG.error("Previous wait_for_caught_up is not over"); + Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "Duplicated call")); + return; + } + done.setMaxMargin(maxMargin); + if (dueTime > 0) { + done.setTimer(r.timerManager.schedule(() -> onCatchUpTimedOut(id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS)); + } + r.catchUpClosure = done; + } finally { + id.unlock(); + } + } + + @Override + public String toString() { + return "Replicator [state=" + this.state + ", statInfo=" + this.statInfo + ",peerId=" + + this.options.getPeerId() + "]"; + } + + static void onBlockTimeoutInNewThread(final ThreadId id) { + if (id != null) { + continueSending(id, RaftError.ETIMEDOUT.getNumber()); + } + } + + /** + * Unblock and continue sending right now. + */ + static void unBlockAndSendNow(final ThreadId id) { + if (id == null) { + // It was destroyed already + return; + } + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + try { + if (r.blockTimer != null) { + if (r.blockTimer.cancel(true)) { + onBlockTimeout(id); + } + } + } finally { + id.unlock(); + } + } + + static boolean continueSending(final ThreadId id, final int errCode) { + if (id == null) { + //It was destroyed already + return true; + } + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + r.waitId = -1; + if (errCode == RaftError.ETIMEDOUT.getNumber()) { + // Send empty entries after block timeout to check the correct + // _next_index otherwise the replicator is likely waits in executor.shutdown(); + // _wait_more_entries and no further logs would be replicated even if the + // last_index of this followers is less than |next_index - 1| + r.sendEmptyEntries(false); + } else if (errCode != RaftError.ESTOP.getNumber()) { + // id is unlock in _send_entries + r.sendEntries(); + } else { + LOG.warn("Replicator {} stops sending entries.", id); + id.unlock(); + } + return true; + } + + static void onBlockTimeout(final ThreadId arg) { + Utils.runInThread(() -> onBlockTimeoutInNewThread(arg)); + } + + void block(final long startTimeMs, @SuppressWarnings("unused") final int errorCode) { + // TODO: Currently we don't care about error_code which indicates why the + // very RPC fails. To make it better there should be different timeout for + // each individual error (e.g. we don't need check every + // heartbeat_timeout_ms whether a dead follower has come back), but it's just + // fine now. + final long dueTime = startTimeMs + this.options.getDynamicHeartBeatTimeoutMs(); + try { + LOG.debug("Blocking {} for {} ms", this.options.getPeerId(), this.options.getDynamicHeartBeatTimeoutMs()); + this.blockTimer = this.timerManager.schedule(() -> onBlockTimeout(this.id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS); + this.statInfo.runningState = RunningState.BLOCKING; + this.id.unlock(); + } catch (final Exception e) { + LOG.error("Fail to add timer", e); + // id unlock in sendEmptyEntries. + sendEmptyEntries(false); + } + } + + @Override + public void onError(final ThreadId id, final Object data, final int errorCode) { + final Replicator r = (Replicator) data; + if (errorCode == RaftError.ESTOP.getNumber()) { + try { + for (final Inflight inflight : r.inflights) { + if (inflight != r.rpcInFly) { + inflight.rpcFuture.cancel(true); + } + } + if (r.rpcInFly != null) { + r.rpcInFly.rpcFuture.cancel(true); + r.rpcInFly = null; + } + if (r.heartbeatInFly != null) { + r.heartbeatInFly.cancel(true); + r.heartbeatInFly = null; + } + if (r.timeoutNowInFly != null) { + r.timeoutNowInFly.cancel(true); + r.timeoutNowInFly = null; + } + if (r.heartbeatTimer != null) { + r.heartbeatTimer.cancel(true); + r.heartbeatTimer = null; + } + if (r.blockTimer != null) { + r.blockTimer.cancel(true); + r.blockTimer = null; + } + if (r.waitId >= 0) { + r.options.getLogManager().removeWaiter(r.waitId); + } + r.notifyOnCaughtUp(errorCode, true); + } finally { + r.destroy(); + } + } else if (errorCode == RaftError.ETIMEDOUT.getNumber()) { + id.unlock(); + Utils.runInThread(() -> sendHeartbeat(id)); + } else { + id.unlock(); + // noinspection ConstantConditions + Requires.requireTrue(false, "Unknown error code for replicator: " + errorCode); + } + } + + private static void onCatchUpTimedOut(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + try { + r.notifyOnCaughtUp(RaftError.ETIMEDOUT.getNumber(), false); + } finally { + id.unlock(); + } + } + + private void notifyOnCaughtUp(final int code, final boolean beforeDestroy) { + if (this.catchUpClosure == null) { + return; + } + if (code != RaftError.ETIMEDOUT.getNumber()) { + if (this.nextIndex - 1 + this.catchUpClosure.getMaxMargin() < this.options.getLogManager() + .getLastLogIndex()) { + return; + } + if (this.catchUpClosure.isErrorWasSet()) { + return; + } + this.catchUpClosure.setErrorWasSet(true); + if (code != RaftError.SUCCESS.getNumber()) { + this.catchUpClosure.getStatus().setError(code, RaftError.describeCode(code)); + } + if (this.catchUpClosure.hasTimer()) { + if (!beforeDestroy && !this.catchUpClosure.getTimer().cancel(true)) { + // There's running timer task, let timer task trigger + // on_caught_up to void ABA problem + return; + } + } + } else { + // timed out + if (!this.catchUpClosure.isErrorWasSet()) { + this.catchUpClosure.getStatus().setError(code, RaftError.describeCode(code)); + } + } + final CatchUpClosure savedClosure = this.catchUpClosure; + this.catchUpClosure = null; + Utils.runClosureInThread(savedClosure, savedClosure.getStatus()); + } + + private static void onTimeout(final ThreadId id) { + if (id != null) { + id.setError(RaftError.ETIMEDOUT.getNumber()); + } else { + LOG.warn("Replicator id is null when timeout, maybe it's destroyed."); + } + } + + void destroy() { + final ThreadId savedId = this.id; + LOG.info("Replicator {} is going to quit", savedId); + this.id = null; + releaseReader(); + // Unregister replicator metric set + if (this.options.getNode().getNodeMetrics().isEnabled()) { + this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options)); + } + this.state = State.Destroyed; + notifyReplicatorStatusListener((Replicator) savedId.getData(), ReplicatorEvent.DESTROYED); + savedId.unlockAndDestroy(); + } + + private void releaseReader() { + if (this.reader != null) { + Utils.closeQuietly(this.reader); + this.reader = null; + } + } + + static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request, + final AppendEntriesResponse response, final long rpcSendTime) { + if (id == null) { + // replicator already was destroyed. + return; + } + final long startTimeMs = Utils.nowMs(); + Replicator r; + if ((r = (Replicator) id.lock()) == null) { + return; + } + boolean doUnlock = true; + try { + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received HeartbeatResponse from "). // + append(r.options.getPeerId()). // + append(" prevLogIndex=").append(request.getPrevLogIndex()). // + append(" prevLogTerm=").append(request.getPrevLogTerm()); + } + if (!status.isOk()) { + if (isLogDebugEnabled) { + sb.append(" fail, sleep."); + LOG.debug(sb.toString()); + } + r.state = State.Probe; + notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), + r.consecutiveErrorTimes, status); + } + r.startHeartbeatTimer(startTimeMs); + return; + } + r.consecutiveErrorTimes = 0; + if (response.getTerm() > r.options.getTerm()) { + if (isLogDebugEnabled) { + sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") + .append(r.options.getTerm()); + LOG.debug(sb.toString()); + } + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); + return; + } + if (!response.getSuccess() && response.hasLastLogIndex()) { + if (isLogDebugEnabled) { + sb.append(" fail, response term ").append(response.getTerm()).append(" lastLogIndex ") + .append(response.getLastLogIndex()); + LOG.debug(sb.toString()); + } + LOG.warn("Heartbeat to peer {} failure, try to send a probe request.", r.options.getPeerId()); + doUnlock = false; + r.sendEmptyEntries(false); + r.startHeartbeatTimer(startTimeMs); + return; + } + if (isLogDebugEnabled) { + LOG.debug(sb.toString()); + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + r.startHeartbeatTimer(startTimeMs); + } finally { + if (doUnlock) { + id.unlock(); + } + } + } + + @SuppressWarnings("ContinueOrBreakFromFinallyBlock") + static void onRpcReturned(final ThreadId id, final RequestType reqType, final Status status, final Message request, + final Message response, final int seq, final int stateVersion, final long rpcSendTime) { + if (id == null) { + return; + } + final long startTimeMs = Utils.nowMs(); + Replicator r; + if ((r = (Replicator) id.lock()) == null) { + return; + } + + if (stateVersion != r.version) { + LOG.debug( + "Replicator {} ignored old version response {}, current version is {}, request is {}\n, and response is {}\n, status is {}.", + r, stateVersion, r.version, request, response, status); + id.unlock(); + return; + } + + final PriorityQueue holdingQueue = r.pendingResponses; + holdingQueue.add(new RpcResponse(reqType, seq, status, request, response, rpcSendTime)); + + if (holdingQueue.size() > r.raftOptions.getMaxReplicatorInflightMsgs()) { + LOG.warn("Too many pending responses {} for replicator {}, maxReplicatorInflightMsgs={}", + holdingQueue.size(), r.options.getPeerId(), r.raftOptions.getMaxReplicatorInflightMsgs()); + r.resetInflights(); + r.state = State.Probe; + r.sendEmptyEntries(false); + return; + } + + boolean continueSendEntries = false; + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Replicator ").append(r).append(" is processing RPC responses,"); + } + try { + int processed = 0; + while (!holdingQueue.isEmpty()) { + final RpcResponse queuedPipelinedResponse = holdingQueue.peek(); + + // Sequence mismatch, waiting for next response. + if (queuedPipelinedResponse.seq != r.requiredNextSeq) { + if (processed > 0) { + if (isLogDebugEnabled) { + sb.append("has processed ").append(processed).append(" responses,"); + } + break; + } else { + // Do not processed any responses, UNLOCK id and return. + continueSendEntries = false; + id.unlock(); + return; + } + } + holdingQueue.remove(); + processed++; + final Inflight inflight = r.pollInflight(); + if (inflight == null) { + // The previous in-flight requests were cleared. + if (isLogDebugEnabled) { + sb.append("ignore response because request not found:").append(queuedPipelinedResponse) + .append(",\n"); + } + continue; + } + if (inflight.seq != queuedPipelinedResponse.seq) { + // reset state + LOG.warn( + "Replicator {} response sequence out of order, expect {}, but it is {}, reset state to try again.", + r, inflight.seq, queuedPipelinedResponse.seq); + r.resetInflights(); + r.state = State.Probe; + continueSendEntries = false; + r.block(Utils.nowMs(), RaftError.EREQUEST.getNumber()); + return; + } + try { + switch (queuedPipelinedResponse.requestType) { + case AppendEntries: + continueSendEntries = onAppendEntriesReturned(id, inflight, queuedPipelinedResponse.status, + (AppendEntriesRequest) queuedPipelinedResponse.request, + (AppendEntriesResponse) queuedPipelinedResponse.response, rpcSendTime, startTimeMs, r); + break; + case Snapshot: + continueSendEntries = onInstallSnapshotReturned(id, r, queuedPipelinedResponse.status, + (InstallSnapshotRequest) queuedPipelinedResponse.request, + (InstallSnapshotResponse) queuedPipelinedResponse.response); + break; + } + } finally { + if (continueSendEntries) { + // Success, increase the response sequence. + r.getAndIncrementRequiredNextSeq(); + } else { + // The id is already unlocked in onAppendEntriesReturned/onInstallSnapshotReturned, we SHOULD break out. + break; + } + } + } + } finally { + if (isLogDebugEnabled) { + sb.append(", after processed, continue to send entries: ").append(continueSendEntries); + LOG.debug(sb.toString()); + } + if (continueSendEntries) { + // unlock in sendEntries. + r.sendEntries(); + } + } + } + + /** + * Reset in-flight state. + */ + void resetInflights() { + this.version++; + this.inflights.clear(); + this.pendingResponses.clear(); + final int rs = Math.max(this.reqSeq, this.requiredNextSeq); + this.reqSeq = this.requiredNextSeq = rs; + releaseReader(); + } + + private static boolean onAppendEntriesReturned(final ThreadId id, final Inflight inflight, final Status status, + final AppendEntriesRequest request, + final AppendEntriesResponse response, final long rpcSendTime, + final long startTimeMs, final Replicator r) { + if (inflight.startIndex != request.getPrevLogIndex() + 1) { + LOG.warn( + "Replicator {} received invalid AppendEntriesResponse, in-flight startIndex={}, request prevLogIndex={}, reset the replicator state and probe again.", + r, inflight.startIndex, request.getPrevLogIndex()); + r.resetInflights(); + r.state = State.Probe; + // unlock id in sendEmptyEntries + r.sendEmptyEntries(false); + return false; + } + // record metrics + if (request.getEntriesCount() > 0) { + r.nodeMetrics.recordLatency("replicate-entries", Utils.monotonicMs() - rpcSendTime); + r.nodeMetrics.recordSize("replicate-entries-count", request.getEntriesCount()); + r.nodeMetrics.recordSize("replicate-entries-bytes", request.getData() != null ? request.getData().size() + : 0); + } + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received AppendEntriesResponse from "). // + append(r.options.getPeerId()). // + append(" prevLogIndex=").append(request.getPrevLogIndex()). // + append(" prevLogTerm=").append(request.getPrevLogTerm()). // + append(" count=").append(request.getEntriesCount()); + } + if (!status.isOk()) { + // If the follower crashes, any RPC to the follower fails immediately, + // so we need to block the follower for a while instead of looping until + // it comes back or be removed + // dummy_id is unlock in block + if (isLogDebugEnabled) { + sb.append(" fail, sleep."); + LOG.debug(sb.toString()); + } + notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), + r.consecutiveErrorTimes, status); + } + r.resetInflights(); + r.state = State.Probe; + // unlock in in block + r.block(startTimeMs, status.getCode()); + return false; + } + r.consecutiveErrorTimes = 0; + if (!response.getSuccess()) { + if (response.getTerm() > r.options.getTerm()) { + if (isLogDebugEnabled) { + sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") + .append(r.options.getTerm()); + LOG.debug(sb.toString()); + } + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); + return false; + } + if (isLogDebugEnabled) { + sb.append(" fail, find nextIndex remote lastLogIndex ").append(response.getLastLogIndex()) + .append(" local nextIndex ").append(r.nextIndex); + LOG.debug(sb.toString()); + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + // Fail, reset the state to try again from nextIndex. + r.resetInflights(); + // prev_log_index and prev_log_term doesn't match + if (response.getLastLogIndex() + 1 < r.nextIndex) { + LOG.debug("LastLogIndex at peer={} is {}", r.options.getPeerId(), response.getLastLogIndex()); + // The peer contains less logs than leader + r.nextIndex = response.getLastLogIndex() + 1; + } else { + // The peer contains logs from old term which should be truncated, + // decrease _last_log_at_peer by one to test the right index to keep + if (r.nextIndex > 1) { + LOG.debug("logIndex={} dismatch", r.nextIndex); + r.nextIndex--; + } else { + LOG.error("Peer={} declares that log at index=0 doesn't match, which is not supposed to happen", + r.options.getPeerId()); + } + } + // dummy_id is unlock in _send_heartbeat + r.sendEmptyEntries(false); + return false; + } + if (isLogDebugEnabled) { + sb.append(", success"); + LOG.debug(sb.toString()); + } + // success + if (response.getTerm() != r.options.getTerm()) { + r.resetInflights(); + r.state = State.Probe; + LOG.error("Fail, response term {} dismatch, expect term {}", response.getTerm(), r.options.getTerm()); + id.unlock(); + return false; + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + final int entriesSize = request.getEntriesCount(); + if (entriesSize > 0) { + r.options.getBallotBox().commitAt(r.nextIndex, r.nextIndex + entriesSize - 1, r.options.getPeerId()); + if (LOG.isDebugEnabled()) { + LOG.debug("Replicated logs in [{}, {}] to peer {}", r.nextIndex, r.nextIndex + entriesSize - 1, + r.options.getPeerId()); + } + } else { + // The request is probe request, change the state into Replicate. + r.state = State.Replicate; + } + r.nextIndex += entriesSize; + r.hasSucceeded = true; + r.notifyOnCaughtUp(RaftError.SUCCESS.getNumber(), false); + // dummy_id is unlock in _send_entries + if (r.timeoutNowIndex > 0 && r.timeoutNowIndex < r.nextIndex) { + r.sendTimeoutNow(false, false); + } + return true; + } + + private boolean fillCommonFields(final AppendEntriesRequest.Builder rb, long prevLogIndex, final boolean isHeartbeat) { + final long prevLogTerm = this.options.getLogManager().getTerm(prevLogIndex); + if (prevLogTerm == 0 && prevLogIndex != 0) { + if (!isHeartbeat) { + Requires.requireTrue(prevLogIndex < this.options.getLogManager().getFirstLogIndex()); + LOG.debug("logIndex={} was compacted", prevLogIndex); + return false; + } else { + // The log at prev_log_index has been compacted, which indicates + // we is or is going to install snapshot to the follower. So we let + // both prev_log_index and prev_log_term be 0 in the heartbeat + // request so that follower would do nothing besides updating its + // leader timestamp. + prevLogIndex = 0; + } + } + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + rb.setPrevLogIndex(prevLogIndex); + rb.setPrevLogTerm(prevLogTerm); + rb.setCommittedIndex(this.options.getBallotBox().getLastCommittedIndex()); + return true; + } + + private void waitMoreEntries(final long nextWaitIndex) { + try { + LOG.debug("Node {} waits more entries", this.options.getNode().getNodeId()); + if (this.waitId >= 0) { + return; + } + this.waitId = this.options.getLogManager().wait(nextWaitIndex - 1, + (arg, errorCode) -> continueSending((ThreadId) arg, errorCode), this.id); + this.statInfo.runningState = RunningState.IDLE; + } finally { + this.id.unlock(); + } + } + + /** + * Send as many requests as possible. + */ + void sendEntries() { + boolean doUnlock = true; + try { + long prevSendIndex = -1; + while (true) { + final long nextSendingIndex = getNextSendIndex(); + if (nextSendingIndex > prevSendIndex) { + if (sendEntries(nextSendingIndex)) { + prevSendIndex = nextSendingIndex; + } else { + doUnlock = false; + // id already unlock in sendEntries when it returns false. + break; + } + } else { + break; + } + } + } finally { + if (doUnlock) { + this.id.unlock(); + } + } + + } + + /** + * Send log entries to follower, returns true when success, otherwise false and unlock the id. + * + * @param nextSendingIndex next sending index + * @return send result. + */ + private boolean sendEntries(final long nextSendingIndex) { + final AppendEntriesRequest.Builder rb = AppendEntriesRequest.newBuilder(); + if (!fillCommonFields(rb, nextSendingIndex - 1, false)) { + // unlock id in installSnapshot + installSnapshot(); + return false; + } + + ByteBufferCollector dataBuf = null; + final int maxEntriesSize = this.raftOptions.getMaxEntriesSize(); + final RecyclableByteBufferList byteBufList = RecyclableByteBufferList.newInstance(); + try { + for (int i = 0; i < maxEntriesSize; i++) { + final RaftOutter.EntryMeta.Builder emb = RaftOutter.EntryMeta.newBuilder(); + if (!prepareEntry(nextSendingIndex, i, emb, byteBufList)) { + break; + } + rb.addEntries(emb.build()); + } + if (rb.getEntriesCount() == 0) { + if (nextSendingIndex < this.options.getLogManager().getFirstLogIndex()) { + installSnapshot(); + return false; + } + // _id is unlock in _wait_more + waitMoreEntries(nextSendingIndex); + return false; + } + if (byteBufList.getCapacity() > 0) { + dataBuf = ByteBufferCollector.allocateByRecyclers(byteBufList.getCapacity()); + for (final ByteBuffer b : byteBufList) { + dataBuf.put(b); + } + final ByteBuffer buf = dataBuf.getBuffer(); + buf.flip(); + rb.setData(ZeroByteStringHelper.wrap(buf)); + } + } finally { + RecycleUtil.recycle(byteBufList); + } + + final AppendEntriesRequest request = rb.build(); + if (LOG.isDebugEnabled()) { + LOG.debug( + "Node {} send AppendEntriesRequest to {} term {} lastCommittedIndex {} prevLogIndex {} prevLogTerm {} logIndex {} count {}", + this.options.getNode().getNodeId(), this.options.getPeerId(), this.options.getTerm(), + request.getCommittedIndex(), request.getPrevLogIndex(), request.getPrevLogTerm(), nextSendingIndex, + request.getEntriesCount()); + } + this.statInfo.runningState = RunningState.APPENDING_ENTRIES; + this.statInfo.firstLogIndex = rb.getPrevLogIndex() + 1; + this.statInfo.lastLogIndex = rb.getPrevLogIndex() + rb.getEntriesCount(); + + final Recyclable recyclable = dataBuf; + final int v = this.version; + final long monotonicSendTimeMs = Utils.monotonicMs(); + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), + request, -1, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + RecycleUtil.recycle(recyclable); + onRpcReturned(Replicator.this.id, RequestType.AppendEntries, status, request, getResponse(), seq, + v, monotonicSendTimeMs); + } + + }); + addInflight(RequestType.AppendEntries, nextSendingIndex, request.getEntriesCount(), request.getData().size(), + seq, rpcFuture); + return true; + + } + + public static void sendHeartbeat(final ThreadId id, final RpcResponseClosure closure) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + Utils.runClosureInThread(closure, new Status(RaftError.EHOSTDOWN, "Peer %s is not connected", id)); + return; + } + //id unlock in send empty entries. + r.sendEmptyEntries(true, closure); + } + + private static void sendHeartbeat(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + // unlock in sendEmptyEntries + r.sendEmptyEntries(true); + } + + @SuppressWarnings("SameParameterValue") + private void sendTimeoutNow(final boolean unlockId, final boolean stopAfterFinish) { + sendTimeoutNow(unlockId, stopAfterFinish, -1); + } + + private void sendTimeoutNow(final boolean unlockId, final boolean stopAfterFinish, final int timeoutMs) { + final TimeoutNowRequest.Builder rb = TimeoutNowRequest.newBuilder(); + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + try { + if (!stopAfterFinish) { + // This RPC is issued by transfer_leadership, save this call_id so that + // the RPC can be cancelled by stop. + this.timeoutNowInFly = timeoutNow(rb, false, timeoutMs); + this.timeoutNowIndex = 0; + } else { + timeoutNow(rb, true, timeoutMs); + } + } finally { + if (unlockId) { + this.id.unlock(); + } + } + + } + + private Future timeoutNow(final TimeoutNowRequest.Builder rb, final boolean stopAfterFinish, + final int timeoutMs) { + final TimeoutNowRequest request = rb.build(); + return this.rpcService.timeoutNow(this.options.getPeerId().getEndpoint(), request, timeoutMs, + new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + if (Replicator.this.id != null) { + onTimeoutNowReturned(Replicator.this.id, status, request, getResponse(), stopAfterFinish); + } + } + + }); + } + + @SuppressWarnings("unused") + static void onTimeoutNowReturned(final ThreadId id, final Status status, final TimeoutNowRequest request, + final TimeoutNowResponse response, final boolean stopAfterFinish) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received TimeoutNowResponse from "). // + append(r.options.getPeerId()); + } + if (!status.isOk()) { + if (isLogDebugEnabled) { + sb.append(" fail:").append(status); + LOG.debug(sb.toString()); + } + notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); + if (stopAfterFinish) { + r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); + r.destroy(); + } else { + id.unlock(); + } + return; + } + if (isLogDebugEnabled) { + sb.append(response.getSuccess() ? " success" : " fail"); + LOG.debug(sb.toString()); + } + if (response.getTerm() > r.options.getTerm()) { + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term timeout_now_response from peer:%s", r.options.getPeerId())); + return; + } + if (stopAfterFinish) { + r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); + r.destroy(); + } else { + id.unlock(); + } + + } + + public static boolean stop(final ThreadId id) { + id.setError(RaftError.ESTOP.getNumber()); + return true; + } + + public static boolean join(final ThreadId id) { + id.join(); + return true; + } + + public static long getLastRpcSendTimestamp(final ThreadId id) { + final Replicator r = (Replicator) id.getData(); + if (r == null) { + return 0L; + } + return r.lastRpcSendTimestamp; + } + + public static boolean transferLeadership(final ThreadId id, final long logIndex) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + // dummy is unlock in _transfer_leadership + return r.transferLeadership(logIndex); + } + + private boolean transferLeadership(final long logIndex) { + if (this.hasSucceeded && this.nextIndex > logIndex) { + // _id is unlock in _send_timeout_now + sendTimeoutNow(true, false); + return true; + } + // Register log_index so that _on_rpc_return trigger + // _send_timeout_now if _next_index reaches log_index + this.timeoutNowIndex = logIndex; + this.id.unlock(); + return true; + } + + public static boolean stopTransferLeadership(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + r.timeoutNowIndex = 0; + id.unlock(); + return true; + } + + public static boolean sendTimeoutNowAndStop(final ThreadId id, final int timeoutMs) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + // id unlock in sendTimeoutNow + r.sendTimeoutNow(true, true, timeoutMs); + return true; + } + + public static long getNextIndex(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return 0; + } + long nextIdx = 0; + if (r.hasSucceeded) { + nextIdx = r.nextIndex; + } + id.unlock(); + return nextIdx; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.alipay.sofa.jraft.core.Replicator.installSnapshot` indirectly reads with synchronization from `n$20.com.alipay.sofa.jraft.entity.PeerId.endpoint.com.alipay.sofa.jraft.util.Endpoint.str`. Potentially races with unsynchronized write in method `Replicator.sendTimeoutNowAndStop(...)`. + Reporting because the current class is annotated `@ThreadSafe`, so we assume that this method can run in parallel with other non-private methods in the class (including itself). + +Note that the prefix path n$20 has been contaminated during the execution, so the reported race on n$20.com.alipay.sofa.jraft.entity.PeerId.endpoint.com.alipay.sofa.jraft.util.Endpoint.str might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Replicator.installSnapshot() + +### Procedure Id: +com.alipay.sofa.jraft.core.Replicator.installSnapshot():void.e3306dc042cb27a2a7f7c45d7a122510 + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/core/Replicator.java + +### Key: +Replicator.java|installSnapshot|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +72774f131a80f398d057675061611ddb + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9224/instruction.md b/inferredbugs-9224/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..389c52342cd0008054e09d84ae19dd9e8af1cf0e --- /dev/null +++ b/inferredbugs-9224/instruction.md @@ -0,0 +1,3032 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-jraft +**Bug ID:** 31 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.jraft.core; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alipay.sofa.jraft.Closure; +import com.alipay.sofa.jraft.FSMCaller; +import com.alipay.sofa.jraft.JRaftServiceFactory; +import com.alipay.sofa.jraft.Node; +import com.alipay.sofa.jraft.NodeManager; +import com.alipay.sofa.jraft.ReadOnlyService; +import com.alipay.sofa.jraft.ReplicatorGroup; +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.closure.CatchUpClosure; +import com.alipay.sofa.jraft.closure.ClosureQueue; +import com.alipay.sofa.jraft.closure.ClosureQueueImpl; +import com.alipay.sofa.jraft.closure.ReadIndexClosure; +import com.alipay.sofa.jraft.closure.SynchronizedClosure; +import com.alipay.sofa.jraft.conf.Configuration; +import com.alipay.sofa.jraft.conf.ConfigurationEntry; +import com.alipay.sofa.jraft.conf.ConfigurationManager; +import com.alipay.sofa.jraft.entity.Ballot; +import com.alipay.sofa.jraft.entity.EnumOutter; +import com.alipay.sofa.jraft.entity.LeaderChangeContext; +import com.alipay.sofa.jraft.entity.LogEntry; +import com.alipay.sofa.jraft.entity.LogId; +import com.alipay.sofa.jraft.entity.NodeId; +import com.alipay.sofa.jraft.entity.PeerId; +import com.alipay.sofa.jraft.entity.RaftOutter; +import com.alipay.sofa.jraft.entity.Task; +import com.alipay.sofa.jraft.entity.UserLog; +import com.alipay.sofa.jraft.error.LogIndexOutOfBoundsException; +import com.alipay.sofa.jraft.error.LogNotFoundException; +import com.alipay.sofa.jraft.error.RaftError; +import com.alipay.sofa.jraft.error.RaftException; +import com.alipay.sofa.jraft.option.BallotBoxOptions; +import com.alipay.sofa.jraft.option.BootstrapOptions; +import com.alipay.sofa.jraft.option.FSMCallerOptions; +import com.alipay.sofa.jraft.option.LogManagerOptions; +import com.alipay.sofa.jraft.option.NodeOptions; +import com.alipay.sofa.jraft.option.RaftMetaStorageOptions; +import com.alipay.sofa.jraft.option.RaftOptions; +import com.alipay.sofa.jraft.option.ReadOnlyOption; +import com.alipay.sofa.jraft.option.ReadOnlyServiceOptions; +import com.alipay.sofa.jraft.option.ReplicatorGroupOptions; +import com.alipay.sofa.jraft.option.SnapshotExecutorOptions; +import com.alipay.sofa.jraft.rpc.RaftClientService; +import com.alipay.sofa.jraft.rpc.RaftServerService; +import com.alipay.sofa.jraft.rpc.RpcRequestClosure; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.ReadIndexRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.ReadIndexResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.RequestVoteRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.RequestVoteResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowResponse; +import com.alipay.sofa.jraft.rpc.RpcResponseClosure; +import com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter; +import com.alipay.sofa.jraft.rpc.RpcResponseFactory; +import com.alipay.sofa.jraft.rpc.impl.core.BoltRaftClientService; +import com.alipay.sofa.jraft.storage.LogManager; +import com.alipay.sofa.jraft.storage.LogStorage; +import com.alipay.sofa.jraft.storage.RaftMetaStorage; +import com.alipay.sofa.jraft.storage.SnapshotExecutor; +import com.alipay.sofa.jraft.storage.impl.LogManagerImpl; +import com.alipay.sofa.jraft.storage.snapshot.SnapshotExecutorImpl; +import com.alipay.sofa.jraft.util.DisruptorBuilder; +import com.alipay.sofa.jraft.util.DisruptorMetricSet; +import com.alipay.sofa.jraft.util.JRaftServiceLoader; +import com.alipay.sofa.jraft.util.JRaftSignalHandler; +import com.alipay.sofa.jraft.util.LogExceptionHandler; +import com.alipay.sofa.jraft.util.NamedThreadFactory; +import com.alipay.sofa.jraft.util.OnlyForTest; +import com.alipay.sofa.jraft.util.Platform; +import com.alipay.sofa.jraft.util.RepeatedTimer; +import com.alipay.sofa.jraft.util.Requires; +import com.alipay.sofa.jraft.util.SignalHelper; +import com.alipay.sofa.jraft.util.ThreadHelper; +import com.alipay.sofa.jraft.util.ThreadId; +import com.alipay.sofa.jraft.util.Utils; +import com.google.protobuf.Message; +import com.lmax.disruptor.BlockingWaitStrategy; +import com.lmax.disruptor.EventFactory; +import com.lmax.disruptor.EventHandler; +import com.lmax.disruptor.EventTranslator; +import com.lmax.disruptor.RingBuffer; +import com.lmax.disruptor.dsl.Disruptor; +import com.lmax.disruptor.dsl.ProducerType; + +/** + * The raft replica node implementation. + * + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-03 4:26:51 PM + */ +public class NodeImpl implements Node, RaftServerService { + + private static final Logger LOG = LoggerFactory + .getLogger(NodeImpl.class); + + static { + try { + if (SignalHelper.supportSignal()) { + // TODO support windows signal + if (!Platform.isWindows()) { + final List handlers = JRaftServiceLoader.load(JRaftSignalHandler.class) // + .sort(); + SignalHelper.addSignal(SignalHelper.SIG_USR2, handlers); + } + } + } catch (final Throwable t) { + LOG.error("Fail to add signal.", t); + } + } + + // Max retry times when applying tasks. + private static final int MAX_APPLY_RETRY_TIMES = 3; + + public static final AtomicInteger GLOBAL_NUM_NODES = new AtomicInteger( + 0); + + /** Internal states */ + private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); + protected final Lock writeLock = this.readWriteLock + .writeLock(); + protected final Lock readLock = this.readWriteLock + .readLock(); + private volatile State state; + private volatile CountDownLatch shutdownLatch; + private long currTerm; + private volatile long lastLeaderTimestamp; + private PeerId leaderId = new PeerId(); + private PeerId votedId; + private final Ballot voteCtx = new Ballot(); + private final Ballot prevVoteCtx = new Ballot(); + private ConfigurationEntry conf; + private StopTransferArg stopTransferArg; + /** Raft group and node options and identifier */ + private final String groupId; + private NodeOptions options; + private RaftOptions raftOptions; + private final PeerId serverId; + /** Other services */ + private final ConfigurationCtx confCtx; + private LogStorage logStorage; + private RaftMetaStorage metaStorage; + private ClosureQueue closureQueue; + private ConfigurationManager configManager; + private LogManager logManager; + private FSMCaller fsmCaller; + private BallotBox ballotBox; + private SnapshotExecutor snapshotExecutor; + private ReplicatorGroup replicatorGroup; + private final List shutdownContinuations = new ArrayList<>(); + private RaftClientService rpcService; + private ReadOnlyService readOnlyService; + /** Timers */ + private TimerManager timerManager; + private RepeatedTimer electionTimer; + private RepeatedTimer voteTimer; + private RepeatedTimer stepDownTimer; + private RepeatedTimer snapshotTimer; + private ScheduledFuture transferTimer; + private ThreadId wakingCandidate; + /** Disruptor to run node service */ + private Disruptor applyDisruptor; + private RingBuffer applyQueue; + + /** Metrics*/ + private NodeMetrics metrics; + + private NodeId nodeId; + private JRaftServiceFactory serviceFactory; + + /** ReplicatorStateListeners */ + private final CopyOnWriteArrayList replicatorStateListeners = new CopyOnWriteArrayList<>(); + + /** + * Node service event. + * + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-03 4:29:55 PM + */ + private static class LogEntryAndClosure { + LogEntry entry; + Closure done; + long expectedTerm; + CountDownLatch shutdownLatch; + + public void reset() { + this.entry = null; + this.done = null; + this.expectedTerm = 0; + this.shutdownLatch = null; + } + } + + private static class LogEntryAndClosureFactory implements EventFactory { + + @Override + public LogEntryAndClosure newInstance() { + return new LogEntryAndClosure(); + } + } + + /** + * Event handler. + * + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-03 4:30:07 PM + */ + private class LogEntryAndClosureHandler implements EventHandler { + // task list for batch + private final List tasks = new ArrayList<>(NodeImpl.this.raftOptions.getApplyBatch()); + + @Override + public void onEvent(final LogEntryAndClosure event, final long sequence, final boolean endOfBatch) + throws Exception { + if (event.shutdownLatch != null) { + if (!this.tasks.isEmpty()) { + executeApplyingTasks(this.tasks); + } + final int num = GLOBAL_NUM_NODES.decrementAndGet(); + LOG.info("The number of active nodes decrement to {}.", num); + event.shutdownLatch.countDown(); + return; + } + + this.tasks.add(event); + if (this.tasks.size() >= NodeImpl.this.raftOptions.getApplyBatch() || endOfBatch) { + executeApplyingTasks(this.tasks); + this.tasks.clear(); + } + } + } + + /** + * Configuration commit context. + * + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-03 4:29:38 PM + */ + private static class ConfigurationCtx { + enum Stage { + STAGE_NONE, // none stage + STAGE_CATCHING_UP, // the node is catching-up + STAGE_JOINT, // joint stage + STAGE_STABLE // stable stage + } + + final NodeImpl node; + Stage stage; + int nchanges; + long version; + List newPeers = new ArrayList<>(); + List oldPeers = new ArrayList<>(); + List addingPeers = new ArrayList<>(); + Closure done; + + public ConfigurationCtx(final NodeImpl node) { + super(); + this.node = node; + this.stage = Stage.STAGE_NONE; + this.version = 0; + this.done = null; + } + + /** + * Start change configuration. + */ + void start(final Configuration oldConf, final Configuration newConf, final Closure done) { + if (isBusy()) { + if (done != null) { + Utils.runClosureInThread(done, new Status(RaftError.EBUSY, "Already in busy stage.")); + } + throw new IllegalStateException("Busy stage"); + } + if (this.done != null) { + if (done != null) { + Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "Already have done closure.")); + } + throw new IllegalArgumentException("Already have done closure"); + } + this.done = done; + this.stage = Stage.STAGE_CATCHING_UP; + this.oldPeers = oldConf.listPeers(); + this.newPeers = newConf.listPeers(); + final Configuration adding = new Configuration(); + final Configuration removing = new Configuration(); + newConf.diff(oldConf, adding, removing); + this.nchanges = adding.size() + removing.size(); + if (adding.isEmpty()) { + nextStage(); + return; + } + this.addingPeers = adding.listPeers(); + LOG.info("Adding peers: {}.", this.addingPeers); + for (final PeerId newPeer : this.addingPeers) { + if (!this.node.replicatorGroup.addReplicator(newPeer)) { + LOG.error("Node {} start the replicator failed, peer={}.", this.node.getNodeId(), newPeer); + onCaughtUp(this.version, newPeer, false); + return; + } + final OnCaughtUp caughtUp = new OnCaughtUp(this.node, this.node.currTerm, newPeer, this.version); + final long dueTime = Utils.nowMs() + this.node.options.getElectionTimeoutMs(); + if (!this.node.replicatorGroup.waitCaughtUp(newPeer, this.node.options.getCatchupMargin(), dueTime, + caughtUp)) { + LOG.error("Node {} waitCaughtUp, peer={}.", this.node.getNodeId(), newPeer); + onCaughtUp(this.version, newPeer, false); + return; + } + } + } + + void onCaughtUp(final long version, final PeerId peer, final boolean success) { + if (version != this.version) { + return; + } + Requires.requireTrue(this.stage == Stage.STAGE_CATCHING_UP, "Stage is not in STAGE_CATCHING_UP"); + if (success) { + this.addingPeers.remove(peer); + if (this.addingPeers.isEmpty()) { + nextStage(); + return; + } + return; + } + LOG.warn("Node {} fail to catch up peer {} when trying to change peers from {} to {}.", + this.node.getNodeId(), peer, this.oldPeers, this.newPeers); + reset(new Status(RaftError.ECATCHUP, "Peer %s failed to catch up.", peer)); + } + + void reset() { + reset(null); + } + + void reset(final Status st) { + if (st != null && st.isOk()) { + this.node.stopReplicator(this.newPeers, this.oldPeers); + } else { + this.node.stopReplicator(this.oldPeers, this.newPeers); + } + this.newPeers.clear(); + this.oldPeers.clear(); + this.addingPeers.clear(); + this.version++; + this.stage = Stage.STAGE_NONE; + this.nchanges = 0; + if (this.done != null) { + Utils.runClosureInThread(this.done, st != null ? st : new Status(RaftError.EPERM, + "Leader stepped down.")); + this.done = null; + } + } + + /** + * Invoked when this node becomes the leader, write a configuration change log as the first log. + */ + void flush(final Configuration conf, final Configuration oldConf) { + Requires.requireTrue(!isBusy(), "Flush when busy"); + this.newPeers = conf.listPeers(); + if (oldConf == null || oldConf.isEmpty()) { + this.stage = Stage.STAGE_STABLE; + this.oldPeers = this.newPeers; + } else { + this.stage = Stage.STAGE_JOINT; + this.oldPeers = oldConf.listPeers(); + } + this.node.unsafeApplyConfiguration(conf, oldConf == null || oldConf.isEmpty() ? null : oldConf, true); + } + + void nextStage() { + Requires.requireTrue(isBusy(), "Not in busy stage"); + switch (this.stage) { + case STAGE_CATCHING_UP: + if (this.nchanges > 1) { + this.stage = Stage.STAGE_JOINT; + this.node.unsafeApplyConfiguration(new Configuration(this.newPeers), new Configuration( + this.oldPeers), false); + return; + } + // Skip joint consensus since only one peers has been changed here. Make + // it a one-stage change to be compatible with the legacy + // implementation. + case STAGE_JOINT: + this.stage = Stage.STAGE_STABLE; + this.node.unsafeApplyConfiguration(new Configuration(this.newPeers), null, false); + break; + case STAGE_STABLE: + final boolean shouldStepDown = !this.newPeers.contains(this.node.serverId); + reset(new Status()); + if (shouldStepDown) { + this.node.stepDown(this.node.currTerm, true, new Status(RaftError.ELEADERREMOVED, + "This node was removed.")); + } + break; + case STAGE_NONE: + // noinspection ConstantConditions + Requires.requireTrue(false, "Can't reach here"); + break; + } + } + + boolean isBusy() { + return this.stage != Stage.STAGE_NONE; + } + } + + public NodeImpl() { + this(null, null); + } + + public NodeImpl(final String groupId, final PeerId serverId) { + super(); + if (groupId != null) { + Utils.verifyGroupId(groupId); + } + this.groupId = groupId; + this.serverId = serverId != null ? serverId.copy() : null; + this.state = State.STATE_UNINITIALIZED; + this.currTerm = 0; + updateLastLeaderTimestamp(Utils.monotonicMs()); + this.confCtx = new ConfigurationCtx(this); + this.wakingCandidate = null; + final int num = GLOBAL_NUM_NODES.incrementAndGet(); + LOG.info("The number of active nodes increment to {}.", num); + } + + private boolean initSnapshotStorage() { + if (StringUtils.isEmpty(this.options.getSnapshotUri())) { + LOG.warn("Do not set snapshot uri, ignore initSnapshotStorage."); + return true; + } + this.snapshotExecutor = new SnapshotExecutorImpl(); + final SnapshotExecutorOptions opts = new SnapshotExecutorOptions(); + opts.setUri(this.options.getSnapshotUri()); + opts.setFsmCaller(this.fsmCaller); + opts.setNode(this); + opts.setLogManager(this.logManager); + opts.setAddr(this.serverId != null ? this.serverId.getEndpoint() : null); + opts.setInitTerm(this.currTerm); + opts.setFilterBeforeCopyRemote(this.options.isFilterBeforeCopyRemote()); + // get snapshot throttle + opts.setSnapshotThrottle(this.options.getSnapshotThrottle()); + return this.snapshotExecutor.init(opts); + } + + private boolean initLogStorage() { + Requires.requireNonNull(this.fsmCaller, "Null fsm caller"); + this.logStorage = this.serviceFactory.createLogStorage(this.options.getLogUri(), this.raftOptions); + this.logManager = new LogManagerImpl(); + final LogManagerOptions opts = new LogManagerOptions(); + opts.setLogEntryCodecFactory(this.serviceFactory.createLogEntryCodecFactory()); + opts.setLogStorage(this.logStorage); + opts.setConfigurationManager(this.configManager); + opts.setFsmCaller(this.fsmCaller); + opts.setNodeMetrics(this.metrics); + opts.setDisruptorBufferSize(this.raftOptions.getDisruptorBufferSize()); + opts.setRaftOptions(this.raftOptions); + return this.logManager.init(opts); + } + + private boolean initMetaStorage() { + this.metaStorage = this.serviceFactory.createRaftMetaStorage(this.options.getRaftMetaUri(), this.raftOptions); + RaftMetaStorageOptions opts = new RaftMetaStorageOptions(); + opts.setNode(this); + if (!this.metaStorage.init(opts)) { + LOG.error("Node {} init meta storage failed, uri={}.", this.serverId, this.options.getRaftMetaUri()); + return false; + } + this.currTerm = this.metaStorage.getTerm(); + this.votedId = this.metaStorage.getVotedFor().copy(); + return true; + } + + private void handleSnapshotTimeout() { + this.writeLock.lock(); + try { + if (!this.state.isActive()) { + return; + } + } finally { + this.writeLock.unlock(); + } + // do_snapshot in another thread to avoid blocking the timer thread. + Utils.runInThread(() -> doSnapshot(null)); + } + + private void handleElectionTimeout() { + boolean doUnlock = true; + this.writeLock.lock(); + try { + if (this.state != State.STATE_FOLLOWER) { + return; + } + if (isCurrentLeaderValid()) { + return; + } + resetLeaderId(PeerId.emptyPeer(), new Status(RaftError.ERAFTTIMEDOUT, "Lost connection from leader %s.", + this.leaderId)); + doUnlock = false; + preVote(); + } finally { + if (doUnlock) { + this.writeLock.unlock(); + } + } + } + + private boolean initFSMCaller(final LogId bootstrapId) { + if (this.fsmCaller == null) { + LOG.error("Fail to init fsm caller, null instance, bootstrapId={}.", bootstrapId); + return false; + } + this.closureQueue = new ClosureQueueImpl(); + final FSMCallerOptions opts = new FSMCallerOptions(); + opts.setAfterShutdown(status -> afterShutdown()); + opts.setLogManager(this.logManager); + opts.setFsm(this.options.getFsm()); + opts.setClosureQueue(this.closureQueue); + opts.setNode(this); + opts.setBootstrapId(bootstrapId); + opts.setDisruptorBufferSize(this.raftOptions.getDisruptorBufferSize()); + return this.fsmCaller.init(opts); + } + + private static class BootstrapStableClosure extends LogManager.StableClosure { + + private final SynchronizedClosure done = new SynchronizedClosure(); + + public BootstrapStableClosure() { + super(null); + } + + public Status await() throws InterruptedException { + return this.done.await(); + } + + @Override + public void run(final Status status) { + this.done.run(status); + } + } + + public boolean bootstrap(final BootstrapOptions opts) throws InterruptedException { + if (opts.getLastLogIndex() > 0 && (opts.getGroupConf().isEmpty() || opts.getFsm() == null)) { + LOG.error("Invalid arguments for bootstrap, groupConf={}, fsm={}, lastLogIndex={}.", opts.getGroupConf(), + opts.getFsm(), opts.getLastLogIndex()); + return false; + } + if (opts.getGroupConf().isEmpty()) { + LOG.error("Bootstrapping an empty node makes no sense."); + return false; + } + Requires.requireNonNull(opts.getServiceFactory(), "Null jraft service factory"); + this.serviceFactory = opts.getServiceFactory(); + // Term is not an option since changing it is very dangerous + final long bootstrapLogTerm = opts.getLastLogIndex() > 0 ? 1 : 0; + final LogId bootstrapId = new LogId(opts.getLastLogIndex(), bootstrapLogTerm); + this.options = new NodeOptions(); + this.raftOptions = this.options.getRaftOptions(); + this.metrics = new NodeMetrics(opts.isEnableMetrics()); + this.options.setFsm(opts.getFsm()); + this.options.setLogUri(opts.getLogUri()); + this.options.setRaftMetaUri(opts.getRaftMetaUri()); + this.options.setSnapshotUri(opts.getSnapshotUri()); + + this.configManager = new ConfigurationManager(); + // Create fsmCaller at first as logManager needs it to report error + this.fsmCaller = new FSMCallerImpl(); + + if (!initLogStorage()) { + LOG.error("Fail to init log storage."); + return false; + } + if (!initMetaStorage()) { + LOG.error("Fail to init meta storage."); + return false; + } + if (this.currTerm == 0) { + this.currTerm = 1; + if (!this.metaStorage.setTermAndVotedFor(1, new PeerId())) { + LOG.error("Fail to set term."); + return false; + } + } + + if (opts.getFsm() != null && !initFSMCaller(bootstrapId)) { + LOG.error("Fail to init fsm caller."); + return false; + } + + final LogEntry entry = new LogEntry(EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION); + entry.getId().setTerm(this.currTerm); + entry.setPeers(opts.getGroupConf().listPeers()); + + final List entries = new ArrayList<>(); + entries.add(entry); + + final BootstrapStableClosure bootstrapDone = new BootstrapStableClosure(); + this.logManager.appendEntries(entries, bootstrapDone); + if (!bootstrapDone.await().isOk()) { + LOG.error("Fail to append configuration."); + return false; + } + + if (opts.getLastLogIndex() > 0) { + if (!initSnapshotStorage()) { + LOG.error("Fail to init snapshot storage."); + return false; + } + final SynchronizedClosure snapshotDone = new SynchronizedClosure(); + this.snapshotExecutor.doSnapshot(snapshotDone); + if (!snapshotDone.await().isOk()) { + LOG.error("Fail to save snapshot, status={}.", snapshotDone.getStatus()); + return false; + } + } + + if (this.logManager.getFirstLogIndex() != opts.getLastLogIndex() + 1) { + throw new IllegalStateException("First and last log index mismatch"); + } + if (opts.getLastLogIndex() > 0) { + if (this.logManager.getLastLogIndex() != opts.getLastLogIndex()) { + throw new IllegalStateException("Last log index mismatch"); + } + } else { + if (this.logManager.getLastLogIndex() != opts.getLastLogIndex() + 1) { + throw new IllegalStateException("Last log index mismatch"); + } + } + + return true; + } + + private int heartbeatTimeout(final int electionTimeout) { + return Math.max(electionTimeout / this.raftOptions.getElectionHeartbeatFactor(), 10); + } + + private int randomTimeout(final int timeoutMs) { + return ThreadLocalRandom.current().nextInt(timeoutMs, timeoutMs + this.raftOptions.getMaxElectionDelayMs()); + } + + @Override + public boolean init(final NodeOptions opts) { + Requires.requireNonNull(opts, "Null node options"); + Requires.requireNonNull(opts.getRaftOptions(), "Null raft options"); + Requires.requireNonNull(opts.getServiceFactory(), "Null jraft service factory"); + this.serviceFactory = opts.getServiceFactory(); + this.options = opts; + this.raftOptions = opts.getRaftOptions(); + this.metrics = new NodeMetrics(opts.isEnableMetrics()); + + if (this.serverId.getIp().equals(Utils.IP_ANY)) { + LOG.error("Node can't started from IP_ANY."); + return false; + } + + if (!NodeManager.getInstance().serverExists(this.serverId.getEndpoint())) { + LOG.error("No RPC server attached to, did you forget to call addService?"); + return false; + } + + this.timerManager = new TimerManager(); + if (!this.timerManager.init(this.options.getTimerPoolSize())) { + LOG.error("Fail to init timer manager."); + return false; + } + + // Init timers + this.voteTimer = new RepeatedTimer("JRaft-VoteTimer", this.options.getElectionTimeoutMs()) { + + @Override + protected void onTrigger() { + handleVoteTimeout(); + } + + @Override + protected int adjustTimeout(final int timeoutMs) { + return randomTimeout(timeoutMs); + } + }; + this.electionTimer = new RepeatedTimer("JRaft-ElectionTimer", this.options.getElectionTimeoutMs()) { + + @Override + protected void onTrigger() { + handleElectionTimeout(); + } + + @Override + protected int adjustTimeout(final int timeoutMs) { + return randomTimeout(timeoutMs); + } + }; + this.stepDownTimer = new RepeatedTimer("JRaft-StepDownTimer", this.options.getElectionTimeoutMs() >> 1) { + + @Override + protected void onTrigger() { + handleStepDownTimeout(); + } + }; + this.snapshotTimer = new RepeatedTimer("JRaft-SnapshotTimer", this.options.getSnapshotIntervalSecs() * 1000) { + + @Override + protected void onTrigger() { + handleSnapshotTimeout(); + } + }; + + this.configManager = new ConfigurationManager(); + + this.applyDisruptor = DisruptorBuilder. newInstance() // + .setRingBufferSize(this.raftOptions.getDisruptorBufferSize()) // + .setEventFactory(new LogEntryAndClosureFactory()) // + .setThreadFactory(new NamedThreadFactory("JRaft-NodeImpl-Disruptor-", true)) // + .setProducerType(ProducerType.MULTI) // + .setWaitStrategy(new BlockingWaitStrategy()) // + .build(); + this.applyDisruptor.handleEventsWith(new LogEntryAndClosureHandler()); + this.applyDisruptor.setDefaultExceptionHandler(new LogExceptionHandler(getClass().getSimpleName())); + this.applyQueue = this.applyDisruptor.start(); + if (this.metrics.getMetricRegistry() != null) { + this.metrics.getMetricRegistry().register("jraft-node-impl-disruptor", + new DisruptorMetricSet(this.applyQueue)); + } + + this.fsmCaller = new FSMCallerImpl(); + if (!initLogStorage()) { + LOG.error("Node {} initLogStorage failed.", getNodeId()); + return false; + } + if (!initMetaStorage()) { + LOG.error("Node {} initMetaStorage failed.", getNodeId()); + return false; + } + if (!initFSMCaller(new LogId(0, 0))) { + LOG.error("Node {} initFSMCaller failed.", getNodeId()); + return false; + } + this.ballotBox = new BallotBox(); + final BallotBoxOptions ballotBoxOpts = new BallotBoxOptions(); + ballotBoxOpts.setWaiter(this.fsmCaller); + ballotBoxOpts.setClosureQueue(this.closureQueue); + if (!this.ballotBox.init(ballotBoxOpts)) { + LOG.error("Node {} init ballotBox failed.", getNodeId()); + return false; + } + + if (!initSnapshotStorage()) { + LOG.error("Node {} initSnapshotStorage failed.", getNodeId()); + return false; + } + + final Status st = this.logManager.checkConsistency(); + if (!st.isOk()) { + LOG.error("Node {} is initialized with inconsistent log, status={}.", getNodeId(), st); + return false; + } + this.conf = new ConfigurationEntry(); + this.conf.setId(new LogId()); + // if have log using conf in log, else using conf in options + if (this.logManager.getLastLogIndex() > 0) { + this.conf = this.logManager.checkAndSetConfiguration(this.conf); + } else { + this.conf.setConf(this.options.getInitialConf()); + } + + // TODO RPC service and ReplicatorGroup is in cycle dependent, refactor it + this.replicatorGroup = new ReplicatorGroupImpl(); + this.rpcService = new BoltRaftClientService(this.replicatorGroup); + final ReplicatorGroupOptions rgOpts = new ReplicatorGroupOptions(); + rgOpts.setHeartbeatTimeoutMs(heartbeatTimeout(this.options.getElectionTimeoutMs())); + rgOpts.setElectionTimeoutMs(this.options.getElectionTimeoutMs()); + rgOpts.setLogManager(this.logManager); + rgOpts.setBallotBox(this.ballotBox); + rgOpts.setNode(this); + rgOpts.setRaftRpcClientService(this.rpcService); + rgOpts.setSnapshotStorage(this.snapshotExecutor != null ? this.snapshotExecutor.getSnapshotStorage() : null); + rgOpts.setRaftOptions(this.raftOptions); + rgOpts.setTimerManager(this.timerManager); + + // Adds metric registry to RPC service. + this.options.setMetricRegistry(this.metrics.getMetricRegistry()); + + if (!this.rpcService.init(this.options)) { + LOG.error("Fail to init rpc service."); + return false; + } + this.replicatorGroup.init(new NodeId(this.groupId, this.serverId), rgOpts); + + this.readOnlyService = new ReadOnlyServiceImpl(); + final ReadOnlyServiceOptions rosOpts = new ReadOnlyServiceOptions(); + rosOpts.setFsmCaller(this.fsmCaller); + rosOpts.setNode(this); + rosOpts.setRaftOptions(this.raftOptions); + + if (!this.readOnlyService.init(rosOpts)) { + LOG.error("Fail to init readOnlyService."); + return false; + } + + // set state to follower + this.state = State.STATE_FOLLOWER; + + if (LOG.isInfoEnabled()) { + LOG.info("Node {} init, term={}, lastLogId={}, conf={}, oldConf={}.", getNodeId(), this.currTerm, + this.logManager.getLastLogId(false), this.conf.getConf(), this.conf.getOldConf()); + } + + if (this.snapshotExecutor != null && this.options.getSnapshotIntervalSecs() > 0) { + LOG.debug("Node {} start snapshot timer, term={}.", getNodeId(), this.currTerm); + this.snapshotTimer.start(); + } + + if (!this.conf.isEmpty()) { + stepDown(this.currTerm, false, new Status()); + } + + if (!NodeManager.getInstance().add(this)) { + LOG.error("NodeManager add {} failed.", getNodeId()); + return false; + } + + // Now the raft node is started , have to acquire the writeLock to avoid race + // conditions + this.writeLock.lock(); + if (this.conf.isStable() && this.conf.getConf().size() == 1 && this.conf.getConf().contains(this.serverId)) { + // The group contains only this server which must be the LEADER, trigger + // the timer immediately. + electSelf(); + } else { + this.writeLock.unlock(); + } + + return true; + } + + // should be in writeLock + private void electSelf() { + long oldTerm; + try { + LOG.info("Node {} start vote and grant vote self, term={}.", getNodeId(), this.currTerm); + if (!this.conf.contains(this.serverId)) { + LOG.warn("Node {} can't do electSelf as it is not in {}.", getNodeId(), this.conf); + return; + } + if (this.state == State.STATE_FOLLOWER) { + LOG.debug("Node {} stop election timer, term={}.", getNodeId(), this.currTerm); + this.electionTimer.stop(); + } + resetLeaderId(PeerId.emptyPeer(), new Status(RaftError.ERAFTTIMEDOUT, + "A follower's leader_id is reset to NULL as it begins to request_vote.")); + this.state = State.STATE_CANDIDATE; + this.currTerm++; + this.votedId = this.serverId.copy(); + LOG.debug("Node {} start vote timer, term={} .", getNodeId(), this.currTerm); + this.voteTimer.start(); + this.voteCtx.init(this.conf.getConf(), this.conf.isStable() ? null : this.conf.getOldConf()); + oldTerm = this.currTerm; + } finally { + this.writeLock.unlock(); + } + + final LogId lastLogId = this.logManager.getLastLogId(true); + + this.writeLock.lock(); + try { + // vote need defense ABA after unlock&writeLock + if (oldTerm != this.currTerm) { + LOG.warn("Node {} raise term {} when getLastLogId.", getNodeId(), this.currTerm); + return; + } + for (final PeerId peer : this.conf.listPeers()) { + if (peer.equals(this.serverId)) { + continue; + } + if (!this.rpcService.connect(peer.getEndpoint())) { + LOG.warn("Node {} channel init failed, address={}.", getNodeId(), peer.getEndpoint()); + continue; + } + final OnRequestVoteRpcDone done = new OnRequestVoteRpcDone(peer, this.currTerm, this); + done.request = RequestVoteRequest.newBuilder() // + .setPreVote(false) // It's not a pre-vote request. + .setGroupId(this.groupId) // + .setServerId(this.serverId.toString()) // + .setPeerId(peer.toString()) // + .setTerm(this.currTerm) // + .setLastLogIndex(lastLogId.getIndex()) // + .setLastLogTerm(lastLogId.getTerm()) // + .build(); + this.rpcService.requestVote(peer.getEndpoint(), done.request, done); + } + + this.metaStorage.setTermAndVotedFor(this.currTerm, this.serverId); + this.voteCtx.grant(this.serverId); + if (this.voteCtx.isGranted()) { + becomeLeader(); + } + } finally { + this.writeLock.unlock(); + } + } + + private void resetLeaderId(final PeerId newLeaderId, final Status status) { + if (newLeaderId.isEmpty()) { + if (!this.leaderId.isEmpty() && this.state.compareTo(State.STATE_TRANSFERRING) > 0) { + this.fsmCaller.onStopFollowing(new LeaderChangeContext(this.leaderId.copy(), this.currTerm, status)); + } + this.leaderId = PeerId.emptyPeer(); + } else { + if (this.leaderId == null || this.leaderId.isEmpty()) { + this.fsmCaller.onStartFollowing(new LeaderChangeContext(newLeaderId, this.currTerm, status)); + } + this.leaderId = newLeaderId.copy(); + } + } + + // in writeLock + private void checkStepDown(final long requestTerm, final PeerId serverId) { + final Status status = new Status(); + if (requestTerm > this.currTerm) { + status.setError(RaftError.ENEWLEADER, "Raft node receives message from new leader with higher term."); + stepDown(requestTerm, false, status); + } else if (this.state != State.STATE_FOLLOWER) { + status.setError(RaftError.ENEWLEADER, "Candidate receives message from new leader with the same term."); + stepDown(requestTerm, false, status); + } else if (this.leaderId.isEmpty()) { + status.setError(RaftError.ENEWLEADER, "Follower receives message from new leader with the same term."); + stepDown(requestTerm, false, status); + } + // save current leader + if (this.leaderId == null || this.leaderId.isEmpty()) { + resetLeaderId(serverId, status); + } + } + + private void becomeLeader() { + Requires.requireTrue(this.state == State.STATE_CANDIDATE, "Illegal state: " + this.state); + LOG.info("Node {} become leader of group, term={}, conf={}, oldConf={}.", getNodeId(), this.currTerm, + this.conf.getConf(), this.conf.getOldConf()); + // cancel candidate vote timer + stopVoteTimer(); + this.state = State.STATE_LEADER; + this.leaderId = this.serverId.copy(); + this.replicatorGroup.resetTerm(this.currTerm); + for (final PeerId peer : this.conf.listPeers()) { + if (peer.equals(this.serverId)) { + continue; + } + LOG.debug("Node {} add replicator, term={}, peer={}.", getNodeId(), this.currTerm, peer); + if (!this.replicatorGroup.addReplicator(peer)) { + LOG.error("Fail to add replicator, peer={}.", peer); + } + } + // init commit manager + this.ballotBox.resetPendingIndex(this.logManager.getLastLogIndex() + 1); + // Register _conf_ctx to reject configuration changing before the first log + // is committed. + if (this.confCtx.isBusy()) { + throw new IllegalStateException(); + } + this.confCtx.flush(this.conf.getConf(), this.conf.getOldConf()); + this.stepDownTimer.start(); + } + + // should be in writeLock + private void stepDown(final long term, final boolean wakeupCandidate, final Status status) { + LOG.debug("Node {} stepDown, term={}, newTerm={}, wakeupCandidate={}.", getNodeId(), this.currTerm, term, + wakeupCandidate); + if (!this.state.isActive()) { + return; + } + if (this.state == State.STATE_CANDIDATE) { + stopVoteTimer(); + } else if (this.state.compareTo(State.STATE_TRANSFERRING) <= 0) { + stopStepDownTimer(); + this.ballotBox.clearPendingTasks(); + // signal fsm leader stop immediately + if (this.state == State.STATE_LEADER) { + onLeaderStop(status); + } + } + // reset leader_id + resetLeaderId(PeerId.emptyPeer(), status); + + // soft state in memory + this.state = State.STATE_FOLLOWER; + this.confCtx.reset(); + updateLastLeaderTimestamp(Utils.monotonicMs()); + if (this.snapshotExecutor != null) { + this.snapshotExecutor.interruptDownloadingSnapshots(term); + } + + // meta state + if (term > this.currTerm) { + this.currTerm = term; + this.votedId = PeerId.emptyPeer(); + this.metaStorage.setTermAndVotedFor(term, this.votedId); + } + + if (wakeupCandidate) { + this.wakingCandidate = this.replicatorGroup.stopAllAndFindTheNextCandidate(this.conf); + if (this.wakingCandidate != null) { + Replicator.sendTimeoutNowAndStop(this.wakingCandidate, this.options.getElectionTimeoutMs()); + } + } else { + this.replicatorGroup.stopAll(); + } + if (this.stopTransferArg != null) { + if (this.transferTimer != null) { + this.transferTimer.cancel(true); + } + // There is at most one StopTransferTimer at the same term, it's safe to + // mark stopTransferArg to NULL + this.stopTransferArg = null; + } + this.electionTimer.start(); + } + + private void stopStepDownTimer() { + if (this.stepDownTimer != null) { + this.stepDownTimer.stop(); + } + } + + private void stopVoteTimer() { + if (this.voteTimer != null) { + this.voteTimer.stop(); + } + } + + class LeaderStableClosure extends LogManager.StableClosure { + + public LeaderStableClosure(final List entries) { + super(entries); + } + + @Override + public void run(final Status status) { + if (status.isOk()) { + NodeImpl.this.ballotBox.commitAt(this.firstLogIndex, this.firstLogIndex + this.nEntries - 1, + NodeImpl.this.serverId); + } else { + LOG.error("Node {} append [{}, {}] failed.", getNodeId(), this.firstLogIndex, this.firstLogIndex + + this.nEntries - 1); + } + } + } + + private void executeApplyingTasks(final List tasks) { + this.writeLock.lock(); + try { + final int size = tasks.size(); + if (this.state != State.STATE_LEADER) { + final Status st = new Status(); + if (this.state != State.STATE_TRANSFERRING) { + st.setError(RaftError.EPERM, "Is not leader."); + } else { + st.setError(RaftError.EBUSY, "Is transferring leadership."); + } + LOG.debug("Node {} can't apply, status={}.", getNodeId(), st); + for (int i = 0; i < size; i++) { + Utils.runClosureInThread(tasks.get(i).done, st); + } + return; + } + final List entries = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + final LogEntryAndClosure task = tasks.get(i); + if (task.expectedTerm != -1 && task.expectedTerm != this.currTerm) { + LOG.debug("Node {} can't apply task whose expectedTerm={} doesn't match currTerm={}.", getNodeId(), + task.expectedTerm, this.currTerm); + if (task.done != null) { + final Status st = new Status(RaftError.EPERM, "expected_term=%d doesn't match current_term=%d", + task.expectedTerm, this.currTerm); + Utils.runClosureInThread(task.done, st); + } + continue; + } + if (!this.ballotBox.appendPendingTask(this.conf.getConf(), + this.conf.isStable() ? null : this.conf.getOldConf(), task.done)) { + Utils.runClosureInThread(task.done, new Status(RaftError.EINTERNAL, "Fail to append task.")); + continue; + } + // set task entry info before adding to list. + task.entry.getId().setTerm(this.currTerm); + task.entry.setType(EnumOutter.EntryType.ENTRY_TYPE_DATA); + entries.add(task.entry); + } + this.logManager.appendEntries(entries, new LeaderStableClosure(entries)); + // update conf.first + this.conf = this.logManager.checkAndSetConfiguration(this.conf); + } finally { + this.writeLock.unlock(); + } + } + + /** + * Returns the node metrics. + * + * @return returns metrics of current node. + */ + @Override + public NodeMetrics getNodeMetrics() { + return this.metrics; + } + + /** + * Returns the JRaft service factory for current node. + *@since 1.2.6 + * @return the service factory + */ + public JRaftServiceFactory getServiceFactory() { + return this.serviceFactory; + } + + @Override + public void readIndex(final byte[] requestContext, final ReadIndexClosure done) { + if (this.shutdownLatch != null) { + Utils.runClosureInThread(done, new Status(RaftError.ENODESHUTDOWN, "Node is shutting down.")); + throw new IllegalStateException("Node is shutting down"); + } + Requires.requireNonNull(done, "Null closure"); + this.readOnlyService.addRequest(requestContext, done); + } + + /** + * ReadIndex response closure + * @author dennis + */ + private class ReadIndexHeartbeatResponseClosure extends RpcResponseClosureAdapter { + final ReadIndexResponse.Builder respBuilder; + final RpcResponseClosure closure; + final int quorum; + final int failPeersThreshold; + int ackSuccess; + int ackFailures; + boolean isDone; + + public ReadIndexHeartbeatResponseClosure(final RpcResponseClosure closure, + final ReadIndexResponse.Builder rb, final int quorum, + final int peersCount) { + super(); + this.closure = closure; + this.respBuilder = rb; + this.quorum = quorum; + this.failPeersThreshold = peersCount % 2 == 0 ? (quorum - 1) : quorum; + this.ackSuccess = 0; + this.ackFailures = 0; + this.isDone = false; + } + + @Override + public synchronized void run(final Status status) { + if (this.isDone) { + return; + } + if (status.isOk() && getResponse().getSuccess()) { + this.ackSuccess++; + } else { + this.ackFailures++; + } + // Include leader self vote yes. + if (this.ackSuccess + 1 >= this.quorum) { + this.respBuilder.setSuccess(true); + this.closure.setResponse(this.respBuilder.build()); + this.closure.run(Status.OK()); + this.isDone = true; + } else if (this.ackFailures >= this.failPeersThreshold) { + this.respBuilder.setSuccess(false); + this.closure.setResponse(this.respBuilder.build()); + this.closure.run(Status.OK()); + this.isDone = true; + } + } + } + + /** + * Handle read index request. + */ + @Override + public void handleReadIndexRequest(final ReadIndexRequest request, final RpcResponseClosure done) { + final long startMs = Utils.monotonicMs(); + this.readLock.lock(); + try { + switch (this.state) { + case STATE_LEADER: + readLeader(request, ReadIndexResponse.newBuilder(), done); + break; + case STATE_FOLLOWER: + readFollower(request, done); + break; + case STATE_TRANSFERRING: + done.run(new Status(RaftError.EBUSY, "Is transferring leadership.")); + break; + default: + done.run(new Status(RaftError.EPERM, "Invalid state for readIndex: %s.", this.state)); + break; + } + } finally { + this.readLock.unlock(); + this.metrics.recordLatency("handle-read-index", Utils.monotonicMs() - startMs); + this.metrics.recordSize("handle-read-index-entries", request.getEntriesCount()); + } + } + + private int getQuorum() { + final Configuration c = this.conf.getConf(); + if (c.isEmpty()) { + return 0; + } + return c.getPeers().size() / 2 + 1; + } + + private void readFollower(final ReadIndexRequest request, final RpcResponseClosure closure) { + if (this.leaderId == null || this.leaderId.isEmpty()) { + closure.run(new Status(RaftError.EPERM, "No leader at term %d.", this.currTerm)); + return; + } + // send request to leader. + final ReadIndexRequest newRequest = ReadIndexRequest.newBuilder() // + .mergeFrom(request) // + .setPeerId(this.leaderId.toString()) // + .build(); + this.rpcService.readIndex(this.leaderId.getEndpoint(), newRequest, -1, closure); + } + + private void readLeader(final ReadIndexRequest request, final ReadIndexResponse.Builder respBuilder, + final RpcResponseClosure closure) { + final int quorum = getQuorum(); + if (quorum <= 1) { + // Only one peer, fast path. + respBuilder.setSuccess(true) // + .setIndex(this.ballotBox.getLastCommittedIndex()); + closure.setResponse(respBuilder.build()); + closure.run(Status.OK()); + return; + } + + final long lastCommittedIndex = this.ballotBox.getLastCommittedIndex(); + if (this.logManager.getTerm(lastCommittedIndex) != this.currTerm) { + // Reject read only request when this leader has not committed any log entry at its term + closure + .run(new Status( + RaftError.EAGAIN, + "ReadIndex request rejected because leader has not committed any log entry at its term, logIndex=%d, currTerm=%d.", + lastCommittedIndex, this.currTerm)); + return; + } + respBuilder.setIndex(lastCommittedIndex); + + if (request.getPeerId() != null) { + // request from follower, check if the follower is in current conf. + final PeerId peer = new PeerId(); + peer.parse(request.getServerId()); + if (!this.conf.contains(peer)) { + closure + .run(new Status(RaftError.EPERM, "Peer %s is not in current configuration: {}.", peer, this.conf)); + return; + } + } + + ReadOnlyOption readOnlyOpt = this.raftOptions.getReadOnlyOptions(); + if (readOnlyOpt == ReadOnlyOption.ReadOnlyLeaseBased && !isLeaderLeaseValid()) { + // If leader lease timeout, we must change option to ReadOnlySafe + readOnlyOpt = ReadOnlyOption.ReadOnlySafe; + } + + switch (readOnlyOpt) { + case ReadOnlySafe: + final List peers = this.conf.getConf().getPeers(); + Requires.requireTrue(peers != null && !peers.isEmpty(), "Empty peers"); + final ReadIndexHeartbeatResponseClosure heartbeatDone = new ReadIndexHeartbeatResponseClosure(closure, + respBuilder, quorum, peers.size()); + // Send heartbeat requests to followers + for (final PeerId peer : peers) { + if (peer.equals(this.serverId)) { + continue; + } + this.replicatorGroup.sendHeartbeat(peer, heartbeatDone); + } + break; + case ReadOnlyLeaseBased: + // Responses to followers and local node. + respBuilder.setSuccess(true); + closure.setResponse(respBuilder.build()); + closure.run(Status.OK()); + break; + } + } + + @Override + public void apply(final Task task) { + if (this.shutdownLatch != null) { + Utils.runClosureInThread(task.getDone(), new Status(RaftError.ENODESHUTDOWN, "Node is shutting down.")); + throw new IllegalStateException("Node is shutting down"); + } + Requires.requireNonNull(task, "Null task"); + + final LogEntry entry = new LogEntry(); + entry.setData(task.getData()); + int retryTimes = 0; + try { + final EventTranslator translator = (event, sequence) -> { + event.reset(); + event.done = task.getDone(); + event.entry = entry; + event.expectedTerm = task.getExpectedTerm(); + }; + while (true) { + if (this.applyQueue.tryPublishEvent(translator)) { + break; + } else { + retryTimes++; + if (retryTimes > MAX_APPLY_RETRY_TIMES) { + Utils.runClosureInThread(task.getDone(), + new Status(RaftError.EBUSY, "Node is busy, has too many tasks.")); + LOG.warn("Node {} applyQueue is overload.", getNodeId()); + this.metrics.recordTimes("apply-task-overload-times", 1); + return; + } + ThreadHelper.onSpinWait(); + } + } + + } catch (final Exception e) { + Utils.runClosureInThread(task.getDone(), new Status(RaftError.EPERM, "Node is down.")); + } + } + + @Override + public Message handlePreVoteRequest(final RequestVoteRequest request) { + boolean doUnlock = true; + this.writeLock.lock(); + try { + if (!this.state.isActive()) { + LOG.warn("Node {} is not in active state, currTerm={}.", getNodeId(), this.currTerm); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Node %s is not in active state, state %s.", + getNodeId(), this.state.name()); + } + final PeerId candidateId = new PeerId(); + if (!candidateId.parse(request.getServerId())) { + LOG.warn("Node {} received PreVoteRequest from {} serverId bad format.", getNodeId(), + request.getServerId()); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Parse candidateId failed: %s.", + request.getServerId()); + } + boolean granted = false; + // noinspection ConstantConditions + do { + if (this.leaderId != null && !this.leaderId.isEmpty() && isCurrentLeaderValid()) { + LOG.info( + "Node {} ignore PreVoteRequest from {}, term={}, currTerm={}, because the leader {}'s lease is still valid.", + getNodeId(), request.getServerId(), request.getTerm(), this.currTerm, this.leaderId); + break; + } + if (request.getTerm() < this.currTerm) { + LOG.info("Node {} ignore PreVoteRequest from {}, term={}, currTerm={}.", getNodeId(), + request.getServerId(), request.getTerm(), this.currTerm); + // A follower replicator may not be started when this node become leader, so we must check it. + checkReplicator(candidateId); + break; + } else if (request.getTerm() == this.currTerm + 1) { + // A follower replicator may not be started when this node become leader, so we must check it. + // check replicator state + checkReplicator(candidateId); + } + doUnlock = false; + this.writeLock.unlock(); + + final LogId lastLogId = this.logManager.getLastLogId(true); + + doUnlock = true; + this.writeLock.lock(); + final LogId requestLastLogId = new LogId(request.getLastLogIndex(), request.getLastLogTerm()); + granted = requestLastLogId.compareTo(lastLogId) >= 0; + + LOG.info( + "Node {} received PreVoteRequest from {}, term={}, currTerm={}, granted={}, requestLastLogId={}, lastLogId={}.", + getNodeId(), request.getServerId(), request.getTerm(), this.currTerm, granted, requestLastLogId, + lastLogId); + } while (false); + + return RequestVoteResponse.newBuilder() // + .setTerm(this.currTerm) // + .setGranted(granted) // + .build(); + } finally { + if (doUnlock) { + this.writeLock.unlock(); + } + } + } + + // in read_lock + private boolean isLeaderLeaseValid() { + final long monotonicNowMs = Utils.monotonicMs(); + if (checkLeaderLease(monotonicNowMs)) { + return true; + } + checkDeadNodes0(this.conf.getConf().getPeers(), monotonicNowMs, false, null); + return checkLeaderLease(monotonicNowMs); + } + + private boolean checkLeaderLease(final long monotonicNowMs) { + return monotonicNowMs - this.lastLeaderTimestamp < this.options.getLeaderLeaseTimeoutMs(); + } + + private boolean isCurrentLeaderValid() { + return Utils.monotonicMs() - this.lastLeaderTimestamp < this.options.getElectionTimeoutMs(); + } + + private void updateLastLeaderTimestamp(final long lastLeaderTimestamp) { + this.lastLeaderTimestamp = lastLeaderTimestamp; + } + + private void checkReplicator(final PeerId candidateId) { + if (this.state == State.STATE_LEADER) { + this.replicatorGroup.checkReplicator(candidateId, false); + } + } + + @Override + public Message handleRequestVoteRequest(final RequestVoteRequest request) { + boolean doUnlock = true; + this.writeLock.lock(); + try { + if (!this.state.isActive()) { + LOG.warn("Node {} is not in active state, currTerm={}.", getNodeId(), this.currTerm); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Node %s is not in active state, state %s.", + getNodeId(), this.state.name()); + } + final PeerId candidateId = new PeerId(); + if (!candidateId.parse(request.getServerId())) { + LOG.warn("Node {} received RequestVoteRequest from {} serverId bad format.", getNodeId(), + request.getServerId()); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Parse candidateId failed: %s.", + request.getServerId()); + } + + // noinspection ConstantConditions + do { + // check term + if (request.getTerm() >= this.currTerm) { + LOG.info("Node {} received RequestVoteRequest from {}, term={}, currTerm={}.", getNodeId(), + request.getServerId(), request.getTerm(), this.currTerm); + // increase current term, change state to follower + if (request.getTerm() > this.currTerm) { + stepDown(request.getTerm(), false, new Status(RaftError.EHIGHERTERMRESPONSE, + "Raft node receives higher term RequestVoteRequest.")); + } + } else { + // ignore older term + LOG.info("Node {} ignore RequestVoteRequest from {}, term={}, currTerm={}.", getNodeId(), + request.getServerId(), request.getTerm(), this.currTerm); + break; + } + doUnlock = false; + this.writeLock.unlock(); + + final LogId lastLogId = this.logManager.getLastLogId(true); + + doUnlock = true; + this.writeLock.lock(); + // vote need ABA check after unlock&writeLock + if (request.getTerm() != this.currTerm) { + LOG.warn("Node {} raise term {} when get lastLogId.", getNodeId(), this.currTerm); + break; + } + + final boolean logIsOk = new LogId(request.getLastLogIndex(), request.getLastLogTerm()) + .compareTo(lastLogId) >= 0; + + if (logIsOk && (this.votedId == null || this.votedId.isEmpty())) { + stepDown(request.getTerm(), false, new Status(RaftError.EVOTEFORCANDIDATE, + "Raft node votes for some candidate, step down to restart election_timer.")); + this.votedId = candidateId.copy(); + this.metaStorage.setVotedFor(candidateId); + } + } while (false); + + return RequestVoteResponse.newBuilder() // + .setTerm(this.currTerm) // + .setGranted(request.getTerm() == this.currTerm && candidateId.equals(this.votedId)) // + .build(); + } finally { + if (doUnlock) { + this.writeLock.unlock(); + } + } + } + + private static class FollowerStableClosure extends LogManager.StableClosure { + + final long committedIndex; + final AppendEntriesResponse.Builder responseBuilder; + final NodeImpl node; + final RpcRequestClosure done; + final long term; + + public FollowerStableClosure(final AppendEntriesRequest request, + final AppendEntriesResponse.Builder responseBuilder, final NodeImpl node, + final RpcRequestClosure done, final long term) { + super(null); + this.committedIndex = Math.min( + // committed index is likely less than the lastLogIndex + request.getCommittedIndex(), + // The logs after the appended entries can not be trust, so we can't commit them even if their indexes are less than request's committed index. + request.getPrevLogIndex() + request.getEntriesCount()); + this.responseBuilder = responseBuilder; + this.node = node; + this.done = done; + this.term = term; + } + + @Override + public void run(final Status status) { + + if (!status.isOk()) { + this.done.run(status); + return; + } + + this.node.readLock.lock(); + try { + if (this.term != this.node.currTerm) { + // The change of term indicates that leader has been changed during + // appending entries, so we can't respond ok to the old leader + // because we are not sure if the appended logs would be truncated + // by the new leader: + // - If they won't be truncated and we respond failure to the old + // leader, the new leader would know that they are stored in this + // peer and they will be eventually committed when the new leader + // found that quorum of the cluster have stored. + // - If they will be truncated and we responded success to the old + // leader, the old leader would possibly regard those entries as + // committed (very likely in a 3-nodes cluster) and respond + // success to the clients, which would break the rule that + // committed entries would never be truncated. + // So we have to respond failure to the old leader and set the new + // term to make it stepped down if it didn't. + this.responseBuilder.setSuccess(false).setTerm(this.node.currTerm); + this.done.sendResponse(this.responseBuilder.build()); + return; + } + } finally { + // It's safe to release lock as we know everything is ok at this point. + this.node.readLock.unlock(); + } + + // Don't touch node any more. + this.responseBuilder.setSuccess(true).setTerm(this.term); + + // Ballot box is thread safe and tolerates disorder. + this.node.ballotBox.setLastCommittedIndex(this.committedIndex); + + this.done.sendResponse(this.responseBuilder.build()); + } + } + + @Override + public Message handleAppendEntriesRequest(final AppendEntriesRequest request, final RpcRequestClosure done) { + boolean doUnlock = true; + final long startMs = Utils.monotonicMs(); + this.writeLock.lock(); + final int entriesCount = request.getEntriesCount(); + try { + if (!this.state.isActive()) { + LOG.warn("Node {} is not in active state, currTerm={}.", getNodeId(), this.currTerm); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Node %s is not in active state, state %s.", + getNodeId(), this.state.name()); + } + + final PeerId serverId = new PeerId(); + if (!serverId.parse(request.getServerId())) { + LOG.warn("Node {} received AppendEntriesRequest from {} serverId bad format.", getNodeId(), + request.getServerId()); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Parse serverId failed: %s.", + request.getServerId()); + } + + // Check stale term + if (request.getTerm() < this.currTerm) { + LOG.warn("Node {} ignore stale AppendEntriesRequest from {}, term={}, currTerm={}.", getNodeId(), + request.getServerId(), request.getTerm(), this.currTerm); + return AppendEntriesResponse.newBuilder() // + .setSuccess(false) // + .setTerm(this.currTerm) // + .build(); + } + + // Check term and state to step down + checkStepDown(request.getTerm(), serverId); + if (!serverId.equals(this.leaderId)) { + LOG.error("Another peer {} declares that it is the leader at term {} which was occupied by leader {}.", + serverId, this.currTerm, this.leaderId); + // Increase the term by 1 and make both leaders step down to minimize the + // loss of split brain + stepDown(request.getTerm() + 1, false, new Status(RaftError.ELEADERCONFLICT, + "More than one leader in the same term.")); + return AppendEntriesResponse.newBuilder() // + .setSuccess(false) // + .setTerm(request.getTerm() + 1) // + .build(); + } + + updateLastLeaderTimestamp(Utils.monotonicMs()); + + if (entriesCount > 0 && this.snapshotExecutor != null && this.snapshotExecutor.isInstallingSnapshot()) { + LOG.warn("Node {} received AppendEntriesRequest while installing snapshot.", getNodeId()); + return RpcResponseFactory.newResponse(RaftError.EBUSY, "Node %s:%s is installing snapshot.", + this.groupId, this.serverId); + } + + final long prevLogIndex = request.getPrevLogIndex(); + final long prevLogTerm = request.getPrevLogTerm(); + final long localPrevLogTerm = this.logManager.getTerm(prevLogIndex); + if (localPrevLogTerm != prevLogTerm) { + final long lastLogIndex = this.logManager.getLastLogIndex(); + + LOG.warn( + "Node {} reject term_unmatched AppendEntriesRequest from {}, term={}, prevLogIndex={}, prevLogTerm={}, localPrevLogTerm={}, lastLogIndex={}, entriesSize={}.", + getNodeId(), request.getServerId(), request.getTerm(), prevLogIndex, prevLogTerm, localPrevLogTerm, + lastLogIndex, entriesCount); + + return AppendEntriesResponse.newBuilder() // + .setSuccess(false) // + .setTerm(this.currTerm) // + .setLastLogIndex(lastLogIndex) // + .build(); + } + + if (entriesCount == 0) { + // heartbeat + final AppendEntriesResponse.Builder respBuilder = AppendEntriesResponse.newBuilder() // + .setSuccess(true) // + .setTerm(this.currTerm) // + .setLastLogIndex(this.logManager.getLastLogIndex()); + doUnlock = false; + this.writeLock.unlock(); + // see the comments at FollowerStableClosure#run() + this.ballotBox.setLastCommittedIndex(Math.min(request.getCommittedIndex(), prevLogIndex)); + return respBuilder.build(); + } + + // Parse request + long index = prevLogIndex; + final List entries = new ArrayList<>(entriesCount); + ByteBuffer allData = null; + if (request.hasData()) { + allData = request.getData().asReadOnlyByteBuffer(); + } + + final List entriesList = request.getEntriesList(); + for (int i = 0; i < entriesCount; i++) { + final RaftOutter.EntryMeta entry = entriesList.get(i); + index++; + if (entry.getType() != EnumOutter.EntryType.ENTRY_TYPE_UNKNOWN) { + final LogEntry logEntry = new LogEntry(); + logEntry.setId(new LogId(index, entry.getTerm())); + logEntry.setType(entry.getType()); + if (entry.hasChecksum()) { + logEntry.setChecksum(entry.getChecksum()); // since 1.2.6 + } + final long dataLen = entry.getDataLen(); + if (dataLen > 0) { + final byte[] bs = new byte[(int) dataLen]; + assert allData != null; + allData.get(bs, 0, bs.length); + logEntry.setData(ByteBuffer.wrap(bs)); + } + + if (entry.getPeersCount() > 0) { + if (entry.getType() != EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION) { + throw new IllegalStateException( + "Invalid log entry that contains peers but is not ENTRY_TYPE_CONFIGURATION type: " + + entry.getType()); + } + + final List peers = new ArrayList<>(entry.getPeersCount()); + for (final String peerStr : entry.getPeersList()) { + final PeerId peer = new PeerId(); + peer.parse(peerStr); + peers.add(peer); + } + logEntry.setPeers(peers); + + if (entry.getOldPeersCount() > 0) { + final List oldPeers = new ArrayList<>(entry.getOldPeersCount()); + for (final String peerStr : entry.getOldPeersList()) { + final PeerId peer = new PeerId(); + peer.parse(peerStr); + oldPeers.add(peer); + } + logEntry.setOldPeers(oldPeers); + } + } else if (entry.getType() == EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION) { + throw new IllegalStateException( + "Invalid log entry that contains zero peers but is ENTRY_TYPE_CONFIGURATION type"); + } + + // Validate checksum + if (this.raftOptions.isEnableLogEntryChecksum() && logEntry.isCorrupted()) { + long realChecksum = logEntry.checksum(); + LOG.error( + "Corrupted log entry received from leader, index={}, term={}, expectedChecksum={}, realChecksum={}", + logEntry.getId().getIndex(), logEntry.getId().getTerm(), logEntry.getChecksum(), + realChecksum); + return RpcResponseFactory.newResponse(RaftError.EINVAL, + "The log entry is corrupted, index=%d, term=%d, expectedChecksum=%d, realChecksum=%d", + logEntry.getId().getIndex(), logEntry.getId().getTerm(), logEntry.getChecksum(), + realChecksum); + } + + entries.add(logEntry); + } + } + + final FollowerStableClosure closure = new FollowerStableClosure(request, AppendEntriesResponse.newBuilder() + .setTerm(this.currTerm), this, done, this.currTerm); + this.logManager.appendEntries(entries, closure); + // update configuration after _log_manager updated its memory status + this.conf = this.logManager.checkAndSetConfiguration(this.conf); + return null; + } finally { + if (doUnlock) { + this.writeLock.unlock(); + } + this.metrics.recordLatency("handle-append-entries", Utils.monotonicMs() - startMs); + this.metrics.recordSize("handle-append-entries-count", entriesCount); + } + } + + // called when leader receive greater term in AppendEntriesResponse + void increaseTermTo(final long newTerm, final Status status) { + this.writeLock.lock(); + try { + if (newTerm < this.currTerm) { + return; + } + stepDown(newTerm, false, status); + } finally { + this.writeLock.unlock(); + } + } + + /** + * Peer catch up callback + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-11 2:10:02 PM + */ + private static class OnCaughtUp extends CatchUpClosure { + private final NodeImpl node; + private final long term; + private final PeerId peer; + private final long version; + + public OnCaughtUp(final NodeImpl node, final long term, final PeerId peer, final long version) { + super(); + this.node = node; + this.term = term; + this.peer = peer; + this.version = version; + } + + @Override + public void run(final Status status) { + this.node.onCaughtUp(this.peer, this.term, this.version, status); + } + } + + private void onCaughtUp(final PeerId peer, final long term, final long version, final Status st) { + this.writeLock.lock(); + try { + // check current_term and state to avoid ABA problem + if (term != this.currTerm && this.state != State.STATE_LEADER) { + // term has changed and nothing should be done, otherwise there will be + // an ABA problem. + return; + } + if (st.isOk()) { + // Caught up successfully + this.confCtx.onCaughtUp(version, peer, true); + return; + } + // Retry if this peer is still alive + if (st.getCode() == RaftError.ETIMEDOUT.getNumber() + && Utils.monotonicMs() - this.replicatorGroup.getLastRpcSendTimestamp(peer) <= this.options + .getElectionTimeoutMs()) { + LOG.debug("Node {} waits peer {} to catch up.", getNodeId(), peer); + final OnCaughtUp caughtUp = new OnCaughtUp(this, term, peer, version); + final long dueTime = Utils.nowMs() + this.options.getElectionTimeoutMs(); + if (this.replicatorGroup.waitCaughtUp(peer, this.options.getCatchupMargin(), dueTime, caughtUp)) { + return; + } + LOG.warn("Node {} waitCaughtUp failed, peer={}.", getNodeId(), peer); + } + LOG.warn("Node {} caughtUp failed, status={}, peer={}.", getNodeId(), st, peer); + this.confCtx.onCaughtUp(version, peer, false); + } finally { + this.writeLock.unlock(); + } + } + + private void checkDeadNodes(final Configuration conf, final long monotonicNowMs) { + final List peers = conf.listPeers(); + final Configuration deadNodes = new Configuration(); + if (checkDeadNodes0(peers, monotonicNowMs, true, deadNodes)) { + return; + } + LOG.warn("Node {} steps down when alive nodes don't satisfy quorum, term={}, deadNodes={}, conf={}.", + getNodeId(), this.currTerm, deadNodes, conf); + final Status status = new Status(); + status.setError(RaftError.ERAFTTIMEDOUT, "Majority of the group dies: %d/%d", deadNodes.size(), peers.size()); + stepDown(this.currTerm, false, status); + } + + private boolean checkDeadNodes0(final List peers, final long monotonicNowMs, final boolean checkReplicator, + final Configuration deadNodes) { + final int leaderLeaseTimeoutMs = this.options.getLeaderLeaseTimeoutMs(); + int aliveCount = 0; + long startLease = Long.MAX_VALUE; + for (final PeerId peer : peers) { + if (peer.equals(this.serverId)) { + aliveCount++; + continue; + } + if (checkReplicator) { + checkReplicator(peer); + } + final long lastRpcSendTimestamp = this.replicatorGroup.getLastRpcSendTimestamp(peer); + if (monotonicNowMs - lastRpcSendTimestamp <= leaderLeaseTimeoutMs) { + aliveCount++; + if (startLease > lastRpcSendTimestamp) { + startLease = lastRpcSendTimestamp; + } + continue; + } + if (deadNodes != null) { + deadNodes.addPeer(peer); + } + } + if (aliveCount >= peers.size() / 2 + 1) { + updateLastLeaderTimestamp(startLease); + return true; + } + return false; + } + + // in read_lock + private List getAliveNodes(final List peers, final long monotonicNowMs) { + final int leaderLeaseTimeoutMs = this.options.getLeaderLeaseTimeoutMs(); + final List alivePeers = new ArrayList<>(); + for (final PeerId peer : peers) { + if (peer.equals(this.serverId)) { + alivePeers.add(peer.copy()); + continue; + } + if (monotonicNowMs - this.replicatorGroup.getLastRpcSendTimestamp(peer) <= leaderLeaseTimeoutMs) { + alivePeers.add(peer.copy()); + } + } + return alivePeers; + } + + private void handleStepDownTimeout() { + this.writeLock.lock(); + try { + if (this.state.compareTo(State.STATE_TRANSFERRING) > 0) { + LOG.debug("Node {} stop step-down timer, term={}, state={}.", getNodeId(), this.currTerm, this.state); + return; + } + final long monotonicNowMs = Utils.monotonicMs(); + checkDeadNodes(this.conf.getConf(), monotonicNowMs); + if (!this.conf.getOldConf().isEmpty()) { + checkDeadNodes(this.conf.getOldConf(), monotonicNowMs); + } + } finally { + this.writeLock.unlock(); + } + } + + /** + * Configuration changed callback. + * + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-11 2:53:43 PM + */ + private class ConfigurationChangeDone implements Closure { + private final long term; + private final boolean leaderStart; + + public ConfigurationChangeDone(final long term, final boolean leaderStart) { + super(); + this.term = term; + this.leaderStart = leaderStart; + } + + @Override + public void run(final Status status) { + if (status.isOk()) { + onConfigurationChangeDone(this.term); + if (this.leaderStart) { + getOptions().getFsm().onLeaderStart(this.term); + } + } else { + LOG.error("Fail to run ConfigurationChangeDone, status: {}.", status); + } + } + } + + private void unsafeApplyConfiguration(final Configuration newConf, final Configuration oldConf, + final boolean leaderStart) { + Requires.requireTrue(this.confCtx.isBusy(), "ConfigurationContext is not busy"); + final LogEntry entry = new LogEntry(EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION); + entry.setId(new LogId(0, this.currTerm)); + entry.setPeers(newConf.listPeers()); + if (oldConf != null) { + entry.setOldPeers(oldConf.listPeers()); + } + final ConfigurationChangeDone configurationChangeDone = new ConfigurationChangeDone(this.currTerm, leaderStart); + // Use the new_conf to deal the quorum of this very log + if (!this.ballotBox.appendPendingTask(newConf, oldConf, configurationChangeDone)) { + Utils.runClosureInThread(configurationChangeDone, new Status(RaftError.EINTERNAL, "Fail to append task.")); + return; + } + final List entries = new ArrayList<>(); + entries.add(entry); + this.logManager.appendEntries(entries, new LeaderStableClosure(entries)); + this.conf = this.logManager.checkAndSetConfiguration(this.conf); + } + + private void unsafeRegisterConfChange(final Configuration oldConf, final Configuration newConf, final Closure done) { + if (this.state != State.STATE_LEADER) { + LOG.warn("Node {} refused configuration changing as the state={}.", getNodeId(), this.state); + if (done != null) { + final Status status = new Status(); + if (this.state == State.STATE_TRANSFERRING) { + status.setError(RaftError.EBUSY, "Is transferring leadership."); + } else { + status.setError(RaftError.EPERM, "Not leader"); + } + Utils.runClosureInThread(done, status); + } + return; + } + // check concurrent conf change + if (this.confCtx.isBusy()) { + LOG.warn("Node {} refused configuration concurrent changing.", getNodeId()); + if (done != null) { + Utils.runClosureInThread(done, new Status(RaftError.EBUSY, "Doing another configuration change.")); + } + return; + } + // Return immediately when the new peers equals to current configuration + if (this.conf.getConf().equals(newConf)) { + Utils.runClosureInThread(done); + return; + } + this.confCtx.start(oldConf, newConf, done); + } + + private void afterShutdown() { + List savedDoneList = null; + this.writeLock.lock(); + try { + if (!this.shutdownContinuations.isEmpty()) { + savedDoneList = new ArrayList<>(this.shutdownContinuations); + } + if (this.logStorage != null) { + this.logStorage.shutdown(); + } + this.state = State.STATE_SHUTDOWN; + } finally { + this.writeLock.unlock(); + } + if (savedDoneList != null) { + for (final Closure closure : savedDoneList) { + Utils.runClosureInThread(closure); + } + } + } + + @Override + public NodeOptions getOptions() { + return this.options; + } + + public TimerManager getTimerManager() { + return this.timerManager; + } + + @Override + public RaftOptions getRaftOptions() { + return this.raftOptions; + } + + @OnlyForTest + long getCurrentTerm() { + this.readLock.lock(); + try { + return this.currTerm; + } finally { + this.readLock.unlock(); + } + } + + @OnlyForTest + ConfigurationEntry getConf() { + this.readLock.lock(); + try { + return this.conf; + } finally { + this.readLock.unlock(); + } + } + + @Override + public void shutdown() { + shutdown(null); + } + + public void onConfigurationChangeDone(final long term) { + this.writeLock.lock(); + try { + if (term != this.currTerm || this.state.compareTo(State.STATE_TRANSFERRING) > 0) { + LOG.warn("Node {} process onConfigurationChangeDone at term {} while state={}, currTerm={}.", + getNodeId(), term, this.state, this.currTerm); + return; + } + this.confCtx.nextStage(); + } finally { + this.writeLock.unlock(); + } + } + + @Override + public PeerId getLeaderId() { + this.readLock.lock(); + try { + return this.leaderId.isEmpty() ? null : this.leaderId; + } finally { + this.readLock.unlock(); + } + } + + @Override + public String getGroupId() { + return this.groupId; + } + + public PeerId getServerId() { + return this.serverId; + } + + @Override + public NodeId getNodeId() { + if (this.nodeId == null) { + this.nodeId = new NodeId(this.groupId, this.serverId); + } + return this.nodeId; + } + + public RaftClientService getRpcService() { + return this.rpcService; + } + + public void onError(final RaftException error) { + LOG.warn("Node {} got error: {}.", getNodeId(), error); + if (this.fsmCaller != null) { + // onError of fsmCaller is guaranteed to be executed once. + this.fsmCaller.onError(error); + } + this.writeLock.lock(); + try { + // If it is leader, need to wake up a new one; + // If it is follower, also step down to call on_stop_following. + if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) { + stepDown(this.currTerm, this.state == State.STATE_LEADER, new Status(RaftError.EBADNODE, + "Raft node(leader or candidate) is in error.")); + } + if (this.state.compareTo(State.STATE_ERROR) < 0) { + this.state = State.STATE_ERROR; + } + } finally { + this.writeLock.unlock(); + } + } + + public void handleRequestVoteResponse(final PeerId peerId, final long term, final RequestVoteResponse response) { + this.writeLock.lock(); + try { + if (this.state != State.STATE_CANDIDATE) { + LOG.warn("Node {} received invalid RequestVoteResponse from {}, state not in STATE_CANDIDATE but {}.", + getNodeId(), peerId, this.state); + return; + } + // check stale term + if (term != this.currTerm) { + LOG.warn("Node {} received stale RequestVoteResponse from {}, term={}, currTerm={}.", getNodeId(), + peerId, term, this.currTerm); + return; + } + // check response term + if (response.getTerm() > this.currTerm) { + LOG.warn("Node {} received invalid RequestVoteResponse from {}, term={}, expect={}.", getNodeId(), + peerId, response.getTerm(), this.currTerm); + stepDown(response.getTerm(), false, new Status(RaftError.EHIGHERTERMRESPONSE, + "Raft node receives higher term request_vote_response.")); + return; + } + // check granted quorum? + if (response.getGranted()) { + this.voteCtx.grant(peerId); + if (this.voteCtx.isGranted()) { + becomeLeader(); + } + } + } finally { + this.writeLock.unlock(); + } + } + + private class OnRequestVoteRpcDone extends RpcResponseClosureAdapter { + + final long startMs; + final PeerId peer; + final long term; + final NodeImpl node; + RequestVoteRequest request; + + public OnRequestVoteRpcDone(final PeerId peer, final long term, final NodeImpl node) { + super(); + this.startMs = Utils.monotonicMs(); + this.peer = peer; + this.term = term; + this.node = node; + } + + @Override + public void run(final Status status) { + NodeImpl.this.metrics.recordLatency("request-vote", Utils.monotonicMs() - this.startMs); + if (!status.isOk()) { + LOG.warn("Node {} RequestVote to {} error: {}.", this.node.getNodeId(), this.peer, status); + } else { + this.node.handleRequestVoteResponse(this.peer, this.term, getResponse()); + } + } + } + + public void handlePreVoteResponse(final PeerId peerId, final long term, final RequestVoteResponse response) { + boolean doUnlock = true; + this.writeLock.lock(); + try { + if (this.state != State.STATE_FOLLOWER) { + LOG.warn("Node {} received invalid PreVoteResponse from {}, state not in STATE_FOLLOWER but {}.", + getNodeId(), peerId, this.state); + return; + } + if (term != this.currTerm) { + LOG.warn("Node {} received invalid PreVoteResponse from {}, term={}, currTerm={}.", getNodeId(), + peerId, term, this.currTerm); + return; + } + if (response.getTerm() > this.currTerm) { + LOG.warn("Node {} received invalid PreVoteResponse from {}, term {}, expect={}.", getNodeId(), peerId, + response.getTerm(), this.currTerm); + stepDown(response.getTerm(), false, new Status(RaftError.EHIGHERTERMRESPONSE, + "Raft node receives higher term pre_vote_response.")); + return; + } + LOG.info("Node {} received PreVoteResponse from {}, term={}, granted={}.", getNodeId(), peerId, + response.getTerm(), response.getGranted()); + // check granted quorum? + if (response.getGranted()) { + this.prevVoteCtx.grant(peerId); + if (this.prevVoteCtx.isGranted()) { + doUnlock = false; + electSelf(); + } + } + } finally { + if (doUnlock) { + this.writeLock.unlock(); + } + } + } + + private class OnPreVoteRpcDone extends RpcResponseClosureAdapter { + + final long startMs; + final PeerId peer; + final long term; + RequestVoteRequest request; + + public OnPreVoteRpcDone(final PeerId peer, final long term) { + super(); + this.startMs = Utils.monotonicMs(); + this.peer = peer; + this.term = term; + } + + @Override + public void run(final Status status) { + NodeImpl.this.metrics.recordLatency("pre-vote", Utils.monotonicMs() - this.startMs); + if (!status.isOk()) { + LOG.warn("Node {} PreVote to {} error: {}.", getNodeId(), this.peer, status); + } else { + handlePreVoteResponse(this.peer, this.term, getResponse()); + } + } + } + + // in writeLock + private void preVote() { + long oldTerm; + try { + LOG.info("Node {} term {} start preVote.", getNodeId(), this.currTerm); + if (this.snapshotExecutor != null && this.snapshotExecutor.isInstallingSnapshot()) { + LOG.warn( + "Node {} term {} doesn't do preVote when installing snapshot as the configuration may be out of date.", + getNodeId()); + return; + } + if (!this.conf.contains(this.serverId)) { + LOG.warn("Node {} can't do preVote as it is not in conf <{}>.", getNodeId(), this.conf); + return; + } + oldTerm = this.currTerm; + } finally { + this.writeLock.unlock(); + } + + final LogId lastLogId = this.logManager.getLastLogId(true); + + boolean doUnlock = true; + this.writeLock.lock(); + try { + // pre_vote need defense ABA after unlock&writeLock + if (oldTerm != this.currTerm) { + LOG.warn("Node {} raise term {} when get lastLogId.", getNodeId(), this.currTerm); + return; + } + this.prevVoteCtx.init(this.conf.getConf(), this.conf.isStable() ? null : this.conf.getOldConf()); + for (final PeerId peer : this.conf.listPeers()) { + if (peer.equals(this.serverId)) { + continue; + } + if (!this.rpcService.connect(peer.getEndpoint())) { + LOG.warn("Node {} channel init failed, address={}.", getNodeId(), peer.getEndpoint()); + continue; + } + final OnPreVoteRpcDone done = new OnPreVoteRpcDone(peer, this.currTerm); + done.request = RequestVoteRequest.newBuilder() // + .setPreVote(true) // it's a pre-vote request. + .setGroupId(this.groupId) // + .setServerId(this.serverId.toString()) // + .setPeerId(peer.toString()) // + .setTerm(this.currTerm + 1) // next term + .setLastLogIndex(lastLogId.getIndex()) // + .setLastLogTerm(lastLogId.getTerm()) // + .build(); + this.rpcService.preVote(peer.getEndpoint(), done.request, done); + } + this.prevVoteCtx.grant(this.serverId); + if (this.prevVoteCtx.isGranted()) { + doUnlock = false; + electSelf(); + } + } finally { + if (doUnlock) { + this.writeLock.unlock(); + } + } + } + + private void handleVoteTimeout() { + this.writeLock.lock(); + if (this.state == State.STATE_CANDIDATE) { + LOG.debug("Node {} term {} retry elect.", getNodeId(), this.currTerm); + electSelf(); + } else { + this.writeLock.unlock(); + } + } + + @Override + public boolean isLeader() { + this.readLock.lock(); + try { + return this.state == State.STATE_LEADER; + } finally { + this.readLock.unlock(); + } + } + + @Override + public void shutdown(final Closure done) { + this.writeLock.lock(); + try { + LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state); + if (this.state.compareTo(State.STATE_SHUTTING) < 0) { + NodeManager.getInstance().remove(this); + // If it is leader, set the wakeup_a_candidate with true; + // If it is follower, call on_stop_following in step_down + if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) { + stepDown(this.currTerm, this.state == State.STATE_LEADER, + new Status(RaftError.ESHUTDOWN, "Raft node is going to quit.")); + } + this.state = State.STATE_SHUTTING; + // Destroy all timers + if (this.electionTimer != null) { + this.electionTimer.destroy(); + } + if (this.voteTimer != null) { + this.voteTimer.destroy(); + } + if (this.stepDownTimer != null) { + this.stepDownTimer.destroy(); + } + if (this.snapshotTimer != null) { + this.snapshotTimer.destroy(); + } + if (this.readOnlyService != null) { + this.readOnlyService.shutdown(); + } + if (this.logManager != null) { + this.logManager.shutdown(); + } + if (this.metaStorage != null) { + this.metaStorage.shutdown(); + } + if (this.snapshotExecutor != null) { + this.snapshotExecutor.shutdown(); + } + if (this.wakingCandidate != null) { + Replicator.stop(this.wakingCandidate); + } + if (this.fsmCaller != null) { + this.fsmCaller.shutdown(); + } + if (this.rpcService != null) { + this.rpcService.shutdown(); + } + if (this.applyQueue != null) { + Utils.runInThread(() -> { + this.shutdownLatch = new CountDownLatch(1); + this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch); + }); + } else { + final int num = GLOBAL_NUM_NODES.decrementAndGet(); + LOG.info("The number of active nodes decrement to {}.", num); + } + if (this.timerManager != null) { + this.timerManager.shutdown(); + } + } + + if (this.state != State.STATE_SHUTDOWN) { + if (done != null) { + this.shutdownContinuations.add(done); + } + return; + } + + // This node is down, it's ok to invoke done right now. Don't invoke this + // in place to avoid the dead writeLock issue when done.Run() is going to acquire + // a writeLock which is already held by the caller + if (done != null) { + Utils.runClosureInThread(done); + } + } finally { + this.writeLock.unlock(); + } + } + + @Override + public synchronized void join() throws InterruptedException { + if (this.shutdownLatch != null) { + if (this.readOnlyService != null) { + this.readOnlyService.join(); + } + if (this.fsmCaller != null) { + this.fsmCaller.join(); + } + if (this.logManager != null) { + this.logManager.join(); + } + if (this.snapshotExecutor != null) { + this.snapshotExecutor.join(); + } + if (this.wakingCandidate != null) { + Replicator.join(this.wakingCandidate); + } + this.shutdownLatch.await(); + this.applyDisruptor.shutdown(); + this.shutdownLatch = null; + } + } + + private static class StopTransferArg { + final NodeImpl node; + final long term; + final PeerId peer; + + public StopTransferArg(final NodeImpl node, final long term, final PeerId peer) { + super(); + this.node = node; + this.term = term; + this.peer = peer; + } + } + + private void handleTransferTimeout(final long term, final PeerId peer) { + LOG.info("Node {} failed to transfer leadership to peer {}, reached timeout.", getNodeId(), peer); + this.writeLock.lock(); + try { + if (term == this.currTerm) { + this.replicatorGroup.stopTransferLeadership(peer); + if (this.state == State.STATE_TRANSFERRING) { + this.fsmCaller.onLeaderStart(term); + this.state = State.STATE_LEADER; + this.stopTransferArg = null; + } + } + } finally { + this.writeLock.unlock(); + } + } + + private void onTransferTimeout(final StopTransferArg arg) { + arg.node.handleTransferTimeout(arg.term, arg.peer); + } + + /** + * Retrieve current configuration this node seen so far. It's not a reliable way to + * retrieve cluster peers info, you should use {@link #listPeers()} instead. + * + * @return current configuration. + * + * @since 1.0.3 + */ + public Configuration getCurrentConf() { + this.readLock.lock(); + try { + if (this.conf != null && this.conf.getConf() != null) { + return this.conf.getConf().copy(); + } + return null; + } finally { + this.readLock.unlock(); + } + } + + @Override + public List listPeers() { + this.readLock.lock(); + try { + if (this.state != State.STATE_LEADER) { + throw new IllegalStateException("Not leader"); + } + return this.conf.getConf().listPeers(); + } finally { + this.readLock.unlock(); + } + } + + @Override + public List listAlivePeers() { + this.readLock.lock(); + try { + if (this.state != State.STATE_LEADER) { + throw new IllegalStateException("Not leader"); + } + return getAliveNodes(this.conf.getConf().getPeers(), Utils.monotonicMs()); + } finally { + this.readLock.unlock(); + } + } + + @Override + public void addPeer(final PeerId peer, final Closure done) { + Requires.requireNonNull(peer, "Null peer"); + this.writeLock.lock(); + try { + Requires.requireTrue(!this.conf.getConf().contains(peer), "Peer already exists in current configuration"); + + final Configuration newConf = new Configuration(this.conf.getConf()); + newConf.addPeer(peer); + unsafeRegisterConfChange(this.conf.getConf(), newConf, done); + } finally { + this.writeLock.unlock(); + } + } + + @Override + public void removePeer(final PeerId peer, final Closure done) { + Requires.requireNonNull(peer, "Null peer"); + this.writeLock.lock(); + try { + Requires.requireTrue(this.conf.getConf().contains(peer), "Peer not found in current configuration"); + + final Configuration newConf = new Configuration(this.conf.getConf()); + newConf.removePeer(peer); + unsafeRegisterConfChange(this.conf.getConf(), newConf, done); + } finally { + this.writeLock.unlock(); + } + } + + @Override + public void changePeers(final Configuration newPeers, final Closure done) { + Requires.requireNonNull(newPeers, "Null new peers"); + Requires.requireTrue(!newPeers.isEmpty(), "Empty new peers"); + this.writeLock.lock(); + try { + LOG.info("Node {} change peers from {} to {}.", getNodeId(), this.conf.getConf(), newPeers); + unsafeRegisterConfChange(this.conf.getConf(), newPeers, done); + } finally { + this.writeLock.unlock(); + } + } + + @Override + public Status resetPeers(final Configuration newPeers) { + Requires.requireNonNull(newPeers, "Null new peers"); + Requires.requireTrue(!newPeers.isEmpty(), "Empty new peers"); + this.writeLock.lock(); + try { + if (newPeers.isEmpty()) { + LOG.warn("Node {} set empty peers.", getNodeId()); + return new Status(RaftError.EINVAL, "newPeers is empty"); + } + if (!this.state.isActive()) { + LOG.warn("Node {} is in state {}, can't set peers.", getNodeId(), this.state); + return new Status(RaftError.EPERM, "Bad state: %s", this.state); + } + // bootstrap? + if (this.conf.getConf().isEmpty()) { + LOG.info("Node {} set peers to {} from empty.", getNodeId(), newPeers); + this.conf.setConf(newPeers); + stepDown(this.currTerm + 1, false, new Status(RaftError.ESETPEER, "Set peer from empty configuration")); + return Status.OK(); + } + if (this.state == State.STATE_LEADER && this.confCtx.isBusy()) { + LOG.warn("Node {} set peers need wait current conf changing.", getNodeId()); + return new Status(RaftError.EBUSY, "Changing to another configuration"); + } + // check equal, maybe retry direct return + if (this.conf.getConf().equals(newPeers)) { + return Status.OK(); + } + final Configuration newConf = new Configuration(newPeers); + LOG.info("Node {} set peers from {} to {}.", getNodeId(), this.conf.getConf(), newPeers); + this.conf.setConf(newConf); + this.conf.getOldConf().reset(); + stepDown(this.currTerm + 1, false, new Status(RaftError.ESETPEER, "Raft node set peer normally")); + return Status.OK(); + } finally { + this.writeLock.unlock(); + } + } + + @Override + public void snapshot(final Closure done) { + doSnapshot(done); + } + + private void doSnapshot(final Closure done) { + if (this.snapshotExecutor != null) { + this.snapshotExecutor.doSnapshot(done); + } else { + if (done != null) { + final Status status = new Status(RaftError.EINVAL, "Snapshot is not supported"); + Utils.runClosureInThread(done, status); + } + } + } + + @Override + public void resetElectionTimeoutMs(final int electionTimeoutMs) { + Requires.requireTrue(electionTimeoutMs > 0, "Invalid electionTimeoutMs"); + this.writeLock.lock(); + try { + this.options.setElectionTimeoutMs(electionTimeoutMs); + this.replicatorGroup.resetHeartbeatInterval(heartbeatTimeout(this.options.getElectionTimeoutMs())); + this.replicatorGroup.resetElectionTimeoutInterval(electionTimeoutMs); + LOG.info("Node {} reset electionTimeout, currTimer {} state {} new electionTimeout {}.", getNodeId(), + this.currTerm, this.state, electionTimeoutMs); + this.electionTimer.reset(electionTimeoutMs); + } finally { + this.writeLock.unlock(); + } + } + + @Override + public Status transferLeadershipTo(final PeerId peer) { + Requires.requireNonNull(peer, "Null peer"); + this.writeLock.lock(); + try { + if (this.state != State.STATE_LEADER) { + LOG.warn("Node {} can't transfer leadership to peer {} as it is in state {}.", getNodeId(), peer, + this.state); + return new Status(this.state == State.STATE_TRANSFERRING ? RaftError.EBUSY : RaftError.EPERM, + "Not a leader"); + } + if (this.confCtx.isBusy()) { + // It's very messy to deal with the case when the |peer| received + // TimeoutNowRequest and increase the term while somehow another leader + // which was not replicated with the newest configuration has been + // elected. If no add_peer with this very |peer| is to be invoked ever + // after nor this peer is to be killed, this peer will spin in the voting + // procedure and make the each new leader stepped down when the peer + // reached vote timeout and it starts to vote (because it will increase + // the term of the group) + // To make things simple, refuse the operation and force users to + // invoke transfer_leadership_to after configuration changing is + // completed so that the peer's configuration is up-to-date when it + // receives the TimeOutNowRequest. + LOG.warn( + "Node {} refused to transfer leadership to peer {} when the leader is changing the configuration.", + getNodeId(), peer); + return new Status(RaftError.EBUSY, "Changing the configuration"); + } + + PeerId peerId = peer.copy(); + // if peer_id is ANY_PEER(0.0.0.0:0:0), the peer with the largest + // last_log_id will be selected. + if (peerId.equals(PeerId.ANY_PEER)) { + LOG.info("Node {} starts to transfer leadership to any peer.", getNodeId()); + if ((peerId = this.replicatorGroup.findTheNextCandidate(this.conf)) == null) { + return new Status(-1, "Candidate not found for any peer"); + } + } + if (peerId.equals(this.serverId)) { + LOG.info("Node {} transferred leadership to self.", this.serverId); + return Status.OK(); + } + if (!this.conf.contains(peerId)) { + LOG.info("Node {} refused to transfer leadership to peer {} as it is not in {}.", getNodeId(), peer, + this.conf); + return new Status(RaftError.EINVAL, "Not in current configuration"); + } + + final long lastLogIndex = this.logManager.getLastLogIndex(); + if (!this.replicatorGroup.transferLeadershipTo(peerId, lastLogIndex)) { + LOG.warn("No such peer {}.", peer); + return new Status(RaftError.EINVAL, "No such peer %s", peer); + } + this.state = State.STATE_TRANSFERRING; + final Status status = new Status(RaftError.ETRANSFERLEADERSHIP, + "Raft leader is transferring leadership to %s", peerId); + onLeaderStop(status); + LOG.info("Node {} starts to transfer leadership to peer {}.", getNodeId(), peer); + final StopTransferArg stopArg = new StopTransferArg(this, this.currTerm, peerId); + this.stopTransferArg = stopArg; + this.transferTimer = this.timerManager.schedule(() -> onTransferTimeout(stopArg), + this.options.getElectionTimeoutMs(), TimeUnit.MILLISECONDS); + + } finally { + this.writeLock.unlock(); + } + return Status.OK(); + } + + private void onLeaderStop(final Status status) { + this.replicatorGroup.clearFailureReplicators(); + this.fsmCaller.onLeaderStop(status); + } + + @Override + public Message handleTimeoutNowRequest(final TimeoutNowRequest request, final RpcRequestClosure done) { + boolean doUnlock = true; + this.writeLock.lock(); + try { + if (request.getTerm() != this.currTerm) { + final long savedCurrTerm = this.currTerm; + if (request.getTerm() > this.currTerm) { + stepDown(request.getTerm(), false, new Status(RaftError.EHIGHERTERMREQUEST, + "Raft node receives higher term request")); + } + LOG.info("Node {} received TimeoutNowRequest from {} while currTerm={} didn't match requestTerm={}.", + getNodeId(), request.getPeerId(), savedCurrTerm, request.getTerm()); + return TimeoutNowResponse.newBuilder() // + .setTerm(this.currTerm) // + .setSuccess(false) // + .build(); + } + if (this.state != State.STATE_FOLLOWER) { + LOG.info("Node {} received TimeoutNowRequest from {}, while state={}, term={}.", getNodeId(), + request.getServerId(), this.state, this.currTerm); + return TimeoutNowResponse.newBuilder() // + .setTerm(this.currTerm) // + .setSuccess(false) // + .build(); + } + + final long savedTerm = this.currTerm; + final TimeoutNowResponse resp = TimeoutNowResponse.newBuilder() // + .setTerm(this.currTerm + 1) // + .setSuccess(true) // + .build(); + // Parallelize response and election + done.sendResponse(resp); + doUnlock = false; + electSelf(); + LOG.info("Node {} received TimeoutNowRequest from {}, term={}.", getNodeId(), request.getServerId(), + savedTerm); + } finally { + if (doUnlock) { + this.writeLock.unlock(); + } + } + return null; + } + + @Override + public Message handleInstallSnapshot(final InstallSnapshotRequest request, final RpcRequestClosure done) { + if (this.snapshotExecutor == null) { + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Not supported snapshot"); + } + final PeerId serverId = new PeerId(); + if (!serverId.parse(request.getServerId())) { + LOG.warn("Node {} ignore InstallSnapshotRequest from {} bad server id.", getNodeId(), request.getServerId()); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Parse serverId failed: %s", request.getServerId()); + } + + this.writeLock.lock(); + try { + if (!this.state.isActive()) { + LOG.warn("Node {} ignore InstallSnapshotRequest as it is not in active state {}.", getNodeId(), + this.state); + return RpcResponseFactory.newResponse(RaftError.EINVAL, "Node %s:%s is not in active state, state %s.", + this.groupId, this.serverId, this.state.name()); + } + + if (request.getTerm() < this.currTerm) { + LOG.warn("Node {} ignore stale InstallSnapshotRequest from {}, term={}, currTerm={}.", getNodeId(), + request.getPeerId(), request.getTerm(), this.currTerm); + return InstallSnapshotResponse.newBuilder() // + .setTerm(this.currTerm) // + .setSuccess(false) // + .build(); + } + + checkStepDown(request.getTerm(), serverId); + + if (!serverId.equals(this.leaderId)) { + LOG.error("Another peer {} declares that it is the leader at term {} which was occupied by leader {}.", + serverId, this.currTerm, this.leaderId); + // Increase the term by 1 and make both leaders step down to minimize the + // loss of split brain + stepDown(request.getTerm() + 1, false, new Status(RaftError.ELEADERCONFLICT, + "More than one leader in the same term.")); + return InstallSnapshotResponse.newBuilder() // + .setTerm(request.getTerm() + 1) // + .setSuccess(false) // + .build(); + } + + } finally { + this.writeLock.unlock(); + } + final long startMs = Utils.monotonicMs(); + try { + if (LOG.isInfoEnabled()) { + LOG.info( + "Node {} received InstallSnapshotRequest from {}, lastIncludedLogIndex={}, lastIncludedLogTerm={}, lastLogId={}.", + getNodeId(), request.getServerId(), request.getMeta().getLastIncludedIndex(), request.getMeta() + .getLastIncludedTerm(), this.logManager.getLastLogId(false)); + } + this.snapshotExecutor.installSnapshot(request, InstallSnapshotResponse.newBuilder(), done); + return null; + } finally { + this.metrics.recordLatency("install-snapshot", Utils.monotonicMs() - startMs); + } + } + + public void updateConfigurationAfterInstallingSnapshot() { + this.writeLock.lock(); + try { + this.conf = this.logManager.checkAndSetConfiguration(this.conf); + } finally { + this.writeLock.unlock(); + } + } + + private void stopReplicator(final List keep, final List drop) { + if (drop != null) { + for (final PeerId peer : drop) { + if (!keep.contains(peer) && !peer.equals(this.serverId)) { + this.replicatorGroup.stopReplicator(peer); + } + } + } + } + + @Override + public UserLog readCommittedUserLog(final long index) { + if (index <= 0) { + throw new LogIndexOutOfBoundsException("Request index is invalid: " + index); + } + + final long savedLastAppliedIndex = this.fsmCaller.getLastAppliedIndex(); + + if (index > savedLastAppliedIndex) { + throw new LogIndexOutOfBoundsException("Request index " + index + " is greater than lastAppliedIndex: " + + savedLastAppliedIndex); + } + + long curIndex = index; + LogEntry entry = this.logManager.getEntry(curIndex); + if (entry == null) { + throw new LogNotFoundException("User log is deleted at index: " + index); + } + + do { + if (entry.getType() == EnumOutter.EntryType.ENTRY_TYPE_DATA) { + return new UserLog(curIndex, entry.getData()); + } else { + curIndex++; + } + if (curIndex > savedLastAppliedIndex) { + throw new IllegalStateException("No user log between index:" + index + " and last_applied_index:" + + savedLastAppliedIndex); + } + entry = this.logManager.getEntry(curIndex); + } while (entry != null); + + throw new LogNotFoundException("User log is deleted at index: " + curIndex); + } + + @Override + public void addReplicatorStateListener(final Replicator.ReplicatorStateListener replicatorStateListener) { + Requires.requireNonNull(replicatorStateListener, "replicatorStateListener"); + this.replicatorStateListeners.add(replicatorStateListener); + } + + @Override + public void removeReplicatorStateListener(final Replicator.ReplicatorStateListener replicatorStateListener) { + Requires.requireNonNull(replicatorStateListener, "replicatorStateListener"); + this.replicatorStateListeners.remove(replicatorStateListener); + } + + @Override + public void clearReplicatorStateListeners() { + this.replicatorStateListeners.clear(); + } + + @Override + public List getReplicatorStatueListeners() { + return this.replicatorStateListeners; + } + + @Override + public void describe(final Printer out) { + // node + final String _nodeId; + final String _state; + final long _currTerm; + final String _conf; + this.readLock.lock(); + try { + _nodeId = String.valueOf(getNodeId()); + _state = String.valueOf(this.state); + _currTerm = this.currTerm; + _conf = String.valueOf(this.conf); + } finally { + this.readLock.unlock(); + } + out.print("nodeId: ") // + .println(_nodeId); + out.print("state: ") // + .println(_state); + out.print("term: ") // + .println(_currTerm); + out.print("conf: ") // + .println(_conf); + + // timers + out.println("electionTimer: "); + this.electionTimer.describe(out); + + out.println("voteTimer: "); + this.voteTimer.describe(out); + + out.println("stepDownTimer: "); + this.stepDownTimer.describe(out); + + out.println("snapshotTimer: "); + this.snapshotTimer.describe(out); + + // logManager + out.println("logManager: "); + this.logManager.describe(out); + + // fsmCaller + out.println("fsmCaller: "); + this.fsmCaller.describe(out); + + // ballotBox + out.println("ballotBox: "); + this.ballotBox.describe(out); + + // snapshotExecutor + out.println("snapshotExecutor: "); + this.snapshotExecutor.describe(out); + + // replicators + out.println("replicatorGroup: "); + this.replicatorGroup.describe(out); + } + + @Override + public String toString() { + return "JRaftNode [nodeId=" + getNodeId() + "]"; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.alipay.sofa.jraft.core.NodeImpl.shutdown` reads with synchronization from `this.com.alipay.sofa.jraft.core.NodeImpl.snapshotTimer`. Potentially races with unsynchronized write in method `NodeImpl.init(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NodeImpl.shutdown(Closure) + +### Procedure Id: +com.alipay.sofa.jraft.core.NodeImpl.shutdown(com.alipay.sofa.jraft.Closure):void.a5f33d4af16042ae72f80f411c7e72c5 + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/core/NodeImpl.java + +### Key: +NodeImpl.java|shutdown|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +8d9149b701a32ce9b80aba6b6c510dbd + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9240/instruction.md b/inferredbugs-9240/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dc79cb65effc239f81f74091b982bbb834c5fa5c --- /dev/null +++ b/inferredbugs-9240/instruction.md @@ -0,0 +1,379 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-jraft +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.jraft.storage.snapshot.remote; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import javax.annotation.concurrent.ThreadSafe; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.core.TimerManager; +import com.alipay.sofa.jraft.error.RaftError; +import com.alipay.sofa.jraft.option.CopyOptions; +import com.alipay.sofa.jraft.option.RaftOptions; +import com.alipay.sofa.jraft.rpc.RaftClientService; +import com.alipay.sofa.jraft.rpc.RpcRequests.GetFileRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.GetFileResponse; +import com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter; +import com.alipay.sofa.jraft.storage.SnapshotThrottle; +import com.alipay.sofa.jraft.util.ByteBufferCollector; +import com.alipay.sofa.jraft.util.Endpoint; +import com.alipay.sofa.jraft.util.OnlyForTest; +import com.alipay.sofa.jraft.util.Requires; +import com.alipay.sofa.jraft.util.Utils; +import com.google.protobuf.Message; + +/** + * Copy session based on bolt framework. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-08 12:01:23 PM + */ +@ThreadSafe +public class BoltSession implements Session { + + private static final Logger LOG = LoggerFactory.getLogger(BoltSession.class); + + private final Lock lock; + private final Status st; + private final RaftClientService rpcService; + private int retryTimes; + private boolean finished; + private ByteBufferCollector destBuf; + private CopyOptions copyOptions; + private GetFileRequest.Builder requestBuilder; + private final CountDownLatch finishLatch; + private OutputStream outputStream; + private final Endpoint endpoint; + private final GetFileResponseClosure done = new GetFileResponseClosure(); + private ScheduledFuture timer; + private String destPath; + private final RaftOptions raftOptions; + private Future rpcCall; + private final TimerManager timerManager; + private final SnapshotThrottle snapshotThrottle; + + /** + * Get file response closure to answer client. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-13 4:50:21 PM + */ + private class GetFileResponseClosure extends RpcResponseClosureAdapter { + + @Override + public void run(Status status) { + onRpcReturned(status, getResponse()); + } + + } + + public void setDestPath(String destPath) { + this.destPath = destPath; + } + + @OnlyForTest + GetFileResponseClosure getDone() { + return this.done; + } + + @OnlyForTest + Future getRpcCall() { + return this.rpcCall; + } + + @OnlyForTest + ScheduledFuture getTimer() { + return this.timer; + } + + @Override + public void close() throws IOException { + lock.lock(); + try { + if (!this.finished) { + Utils.closeQuietly(this.outputStream); + } + } finally { + lock.unlock(); + } + } + + public BoltSession(RaftClientService rpcService, TimerManager timerManager, SnapshotThrottle snapshotThrottle, + RaftOptions raftOptions, GetFileRequest.Builder rb, Endpoint ep) { + super(); + this.snapshotThrottle = snapshotThrottle; + this.raftOptions = raftOptions; + this.timerManager = timerManager; + this.rpcService = rpcService; + this.requestBuilder = rb; + this.retryTimes = 0; + this.copyOptions = new CopyOptions(); + this.lock = new ReentrantLock(); + this.endpoint = ep; + this.st = Status.OK(); + this.finishLatch = new CountDownLatch(1); + + } + + public void setDestBuf(ByteBufferCollector bufRef) { + this.destBuf = bufRef; + } + + public void setCopyOptions(CopyOptions copyOptions) { + this.copyOptions = copyOptions; + } + + public void setOutputStream(OutputStream out) { + this.outputStream = out; + } + + @Override + public void cancel() { + lock.lock(); + try { + if (this.finished) { + return; + } + if (this.timer != null) { + this.timer.cancel(true); + } + if (this.rpcCall != null) { + this.rpcCall.cancel(true); + } + if (st.isOk()) { + st.setError(RaftError.ECANCELED, RaftError.ECANCELED.name()); + } + + this.onFinished(); + } finally { + lock.unlock(); + } + + } + + @Override + public void join() throws InterruptedException { + this.finishLatch.await(); + } + + @Override + public Status status() { + return st; + } + + private void onFinished() { + if (!this.finished) { + if (outputStream != null) { + Utils.closeQuietly(this.outputStream); + this.outputStream = null; + } + if (this.destBuf != null) { + final ByteBuffer buf = this.destBuf.getBuffer(); + if (buf != null) { + buf.flip(); + } + this.destBuf = null; + } + this.finished = true; + this.finishLatch.countDown(); + } + } + + private void onTimer() { + Utils.runInThread(this::sendNextRpc); + } + + void onRpcReturned(Status status, GetFileResponse response) { + lock.lock(); + try { + if (this.finished) { + return; + } + if (!status.isOk()) { + // Reset count to make next rpc retry the previous one + requestBuilder.setCount(0); + if (status.getCode() == RaftError.ECANCELED.getNumber()) { + if (st.isOk()) { + st.setError(status.getCode(), status.getErrorMsg()); + this.onFinished(); + return; + } + } + + // Throttled reading failure does not increase _retry_times + if (status.getCode() != RaftError.EAGAIN.getNumber() + && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { + if (st.isOk()) { + st.setError(status.getCode(), status.getErrorMsg()); + this.onFinished(); + return; + } + } + this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), + TimeUnit.MILLISECONDS); + return; + } + this.retryTimes = 0; + Requires.requireNonNull(response, "response"); + // Reset count to |real_read_size| to make next rpc get the right offset + if (response.hasReadSize() && response.getReadSize() != 0) { + this.requestBuilder.setCount(response.getReadSize()); + } + if (outputStream != null) { + try { + response.getData().writeTo(outputStream); + } catch (final IOException e) { + LOG.error("Fail to write into file {}", this.destPath); + st.setError(RaftError.EIO, RaftError.EIO.name()); + this.onFinished(); + return; + } + } else { + final byte[] data = response.getData().toByteArray(); + this.destBuf.put(data); + } + if (response.getEof()) { + onFinished(); + return; + } + } finally { + lock.unlock(); + } + this.sendNextRpc(); + } + + /** + * Send next RPC request to get a piece of file data. + */ + void sendNextRpc() { + this.timer = null; + final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); + final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; + this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); + this.lock.lock(); + try { + if (this.finished) { + return; + } + // throttle + long newMaxCount = maxCount; + if (this.snapshotThrottle != null) { + newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); + if (newMaxCount == 0) { + // Reset count to make next rpc retry the previous one + this.requestBuilder.setCount(0); + this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), + TimeUnit.MILLISECONDS); + return; + } + } + this.requestBuilder.setCount(newMaxCount); + LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); + this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), + this.copyOptions.getTimeoutMs(), done); + } finally { + lock.unlock(); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.onRpcReturned` indirectly reads with synchronization from `this.com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.requestBuilder.com.alipay.sofa.jraft.rpc.RpcRequests$GetFileRequest$Builder.bitField0_`. Potentially races with unsynchronized write in method `BoltSession.sendNextRpc()`. + Reporting because the current class is annotated `@ThreadSafe`, so we assume that this method can run in parallel with other non-private methods in the class (including itself). + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BoltSession.onRpcReturned(Status,RpcRequests$GetFileResponse) + +### Procedure Id: +com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.onRpcReturned(com.alipay.sofa.jraft.Status.2658788c2bba78a412ddf60eb2b9cb11 + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/storage/snapshot/remote/BoltSession.java + +### Key: +BoltSession.java|onRpcReturned|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +184397a14ddee7ecba7279f7fc244bc9 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9247/instruction.md b/inferredbugs-9247/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d87a930fbc296d7f62aa0e7ce9241568ebd3ad03 --- /dev/null +++ b/inferredbugs-9247/instruction.md @@ -0,0 +1,141 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ff4j +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.ff4j.test.strategy.el; + +/* + * #%L ff4j-core $Id:$ $HeadURL:$ %% Copyright (C) 2013 Ff4J %% Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" + * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. #L% + */ + +import org.ff4j.FF4j; +import org.ff4j.core.FlippingExecutionContext; +import org.ff4j.strategy.el.ExpressionFlipStrategy; +import org.junit.Assert; +import org.junit.Test; + +/** + * Tests for {@link ExpressionFlipStrategy} class. + * + * @author Cedrick LUNVEN + */ +public class ExpressionFlipStategyTest { + + /** current instance of FF4j */ + private final FF4j ff4j = new FF4j("test-expressionFlipStategy-ok.xml"); + + @Test + public void testExpression() throws Exception { + Assert.assertNotNull(ff4j.getFeature("D")); + Assert.assertNotNull(ff4j.getFeature("D").getFlippingStrategy()); + Assert.assertNotNull(ff4j.getFeature("D").getFlippingStrategy().getInitParams()); + boolean dFlipped = ff4j.check("D"); + Assert.assertTrue(dFlipped); + } + + @Test + public void testEnableC() { + ff4j.enable("C"); + boolean dFlipped = ff4j.check("D"); + Assert.assertFalse(dFlipped); + } + + @Test + public void testEnableB() { + ff4j.enable("B"); + boolean dFlipped = ff4j.check("D"); + Assert.assertTrue(dFlipped); + } + + @Test + public void testExplicitevaluate() { + ExpressionFlipStrategy efs = new ExpressionFlipStrategy(); + Assert.assertTrue(efs.evaluate("D", ff4j.getStore(), null)); + Assert.assertTrue(efs.evaluate("TOTO", ff4j.getStore(), null)); + + FlippingExecutionContext fex = new FlippingExecutionContext(); + fex.putString(ExpressionFlipStrategy.PARAM_EXPRESSION, "D"); + Assert.assertTrue(efs.evaluate("D", ff4j.getStore(), fex)); + + fex.putString(ExpressionFlipStrategy.PARAM_EXPRESSION, "TOTO"); + Assert.assertFalse(efs.evaluate("D", ff4j.getStore(), fex)); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `evaluate(...)` at line 56. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExpressionFlipStategyTest.testExplicitevaluate() + +### Procedure Id: +org.ff4j.test.strategy.el.ExpressionFlipStategyTest.testExplicitevaluate():void.2b97c17f492122d3b4aad570c1d345ea + +### File: +ff4j-core/src/test/java/org/ff4j/test/strategy/el/ExpressionFlipStategyTest.java + +### Key: +ExpressionFlipStategyTest.java|testExplicitevaluate|NULL_DEREFERENCE + +### Node Key: +8935e57d7b3f0838a904c444170f4f1f + +### Hash: +88d70bf20f3d188b36700040d90bf7b8 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9249/instruction.md b/inferredbugs-9249/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b71ea7dcd2b34dcc472aa0d307b661c5c9754744 --- /dev/null +++ b/inferredbugs-9249/instruction.md @@ -0,0 +1,377 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** DotCi +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +The MIT License (MIT) + +Copyright (c) 2014, Groupon, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + */ +package com.groupon.jenkins.dynamic.build; + +import com.groupon.jenkins.dynamic.build.repository.DynamicProjectRepository; +import com.groupon.jenkins.util.GReflectionUtils; +import com.mongodb.DBObject; +import hudson.EnvVars; +import hudson.Util; +import hudson.model.*; +import hudson.model.Queue.Executable; +import hudson.scm.ChangeLogSet; +import hudson.scm.ChangeLogSet.Entry; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.security.Timestamp; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; +import java.util.logging.Level; + +import jenkins.model.Jenkins; + +import org.bson.types.ObjectId; +import org.kohsuke.stapler.export.Exported; +import org.mongodb.morphia.annotations.*; +import org.springframework.util.ReflectionUtils; + +import com.groupon.jenkins.dynamic.build.cause.BuildCause; +import com.groupon.jenkins.dynamic.build.repository.DynamicBuildRepository; +import com.groupon.jenkins.github.GitBranch; + +@Entity("run") +public abstract class DbBackedBuild

    , B extends DbBackedBuild> extends Build { + @Id + private ObjectId id; + + private ObjectId projectId; //TODO replace with Reference + + public ObjectId getProjectId() { + return projectId; + } + + @PrePersist + void saveState(final DBObject dbObj) { + dbObj.put("state", getState().toString()); + hudson.model.Items.XSTREAM.ignoreUnknownElements(); + } + + @PostLoad + void restoreState(final DBObject dbObj) { + Object state = getState((String) dbObj.get("state")); + setField(state, "state"); + } + + @PrePersist + private void saveTimestamp(final DBObject dbObj) { + dbObj.put("timestamp", getTime()); + } + + @PostLoad + private void restoreTimestamp(final DBObject dbObj) { + Date time = (Date) dbObj.get("timestamp"); + if(time != null) { + setField(time.getTime(), "timestamp"); + } + } + + @PrePersist + void saveProjectId() { + projectId = project.getId(); + } + + + public void postMorphiaLoad() { + super.onLoad(); + } + + + private static final Logger LOGGER = Logger.getLogger(DbBackedBuild.class.getName()); + + protected DbBackedBuild(P project) throws IOException { + super(project); + } + + public DbBackedBuild(P project, File buildDir) throws IOException { + super(project, buildDir); + } + + public DbBackedBuild(P job, Calendar timestamp) { + super(job, timestamp); + } + + @Override + public synchronized void save() throws IOException { + LOGGER.info("saving build:" + getName() + ": " + getNumber()); + new DynamicBuildRepository().save(this); + } + + @Override + protected void onEndBuilding() { + super.onEndBuilding(); + try { + this.save(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Deprecated + // Keeping this so we can more easily migrate from existing systems + public void restoreFromDb(AbstractProject project, Map input) { + String state = ((String) input.get("state")); + Date date = ((Date) input.get("last_updated")); + setField(project, "project"); + setField(date.getTime(), "timestamp"); + setField(getState(state), "state"); + super.onLoad(); + } + + public String getState() { + String stateName = null; + try { + Field field = Run.class.getDeclaredField("state"); + field.setAccessible(true); + stateName = ReflectionUtils.getField(field, this).toString(); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return stateName; + } + public Object getState(String state) { + try { + return Enum.valueOf((Class) Class.forName("hudson.model.Run$State"), state); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean hasParticipant(User user) { + return false; + } + + @Override + public B getNextBuild() { + return getParent().getBuildByNumber(getNumber() + 1); + } + + @Override + public B getPreviousBuild() { + return null; + } + + private void setField(Object project, String fieldStr) { + Field field; + try { + field = Run.class.getDeclaredField(fieldStr); + field.setAccessible(true); + field.set(this, project); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + @Exported + public Executor getExecutor() { + Jenkins jenkins = Jenkins.getInstance(); + if (jenkins == null) { + return null; + } + for (Computer computer : jenkins.getComputers()) { + for (Executor executor : computer.getExecutors()) { + if (isCurrent(executor)) { + return executor; + } + } + } + return null; + } + + private boolean isCurrent(Executor executor) { + Executable currentExecutable = executor.getCurrentExecutable(); + return currentExecutable != null && currentExecutable instanceof DbBackedBuild && this.equals(currentExecutable); + } + + @Override + public Executor getOneOffExecutor() { + for (Computer c : Jenkins.getInstance().getComputers()) { + for (Executor e : c.getOneOffExecutors()) { + if (isCurrent(e)) + return e; + } + } + return null; + } + + @Override + @Exported + public ChangeLogSet getChangeSet() { + return new GithubChangeLogSet(this, getCause().getChangeLogEntries()); + } + + public String getName() { + return getParent().getName(); + } + + @Override + @Exported + public Set getCulprits() { + return new HashSet(); + } + + public GitBranch getCurrentBranch() { + return getCause().getBranch(); + } + + public String getDisplayTime() { + return Util.getPastTimeString(System.currentTimeMillis() - getTimestamp().getTimeInMillis()) + " ago"; + } + + public abstract BuildCause getCause(); + + @Override + public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException { + EnvVars envVars = getJenkinsEnvVariables(log); + envVars.putAll(getDotCiEnvVars(envVars)); + return envVars; + } + + public Map getDotCiEnvVars(EnvVars jenkinsEnvVars) { + Map envVars = new HashMap(); + envVars.put("DOTCI_BRANCH", jenkinsEnvVars.get("BRANCH")); + envVars.put("DOTCI", "true"); + envVars.put("CI", "true"); + if (getCause() != null) { + envVars.putAll(getCause().getEnvVars()); + } + return envVars; + } + + public String getBuildId() { + return getProject().getId() + getId(); + } + + public EnvVars getJenkinsEnvVariables(TaskListener log) { + try { + return super.getEnvironment(log); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public boolean isSkipped() { + return getAction(SkippedBuildAction.class) != null; + } + + @Override + public String getWhyKeepLog() { + return null; + } + + public Run getPreviousFinishedBuildOfSameBranch(BuildListener listener) { + return new DynamicBuildRepository().getPreviousFinishedBuildOfSameBranch(this, getCurrentBranch().toString()); + } + + public String getPusher() { + return getCause() == null ? null : getCause().getPusher(); + } + + public abstract String getSha(); + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.groupon.jenkins.dynamic.build.DbBackedBuild.getPreviousFinishedBuildOfSameBranch` indirectly reads without synchronization from `mongo.MongoRepository.com.groupon.jenkins.mongo.MongoRepository.datastore`. Potentially races with write in method `DbBackedBuild.save()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Run DbBackedBuild.getPreviousFinishedBuildOfSameBranch(BuildListener) + +### Procedure Id: +com.groupon.jenkins.dynamic.build.DbBackedBuild.getPreviousFinishedBuildOfSameBranch(hudson.model.Bu.f1104300cd4bd50215e21a1cefe22c89 + +### File: +src/main/java/com/groupon/jenkins/dynamic/build/DbBackedBuild.java + +### Key: +DbBackedBuild.java|getPreviousFinishedBuildOfSameBranch|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +8658612cec7af434767465fc1ad3fb4e + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9271/instruction.md b/inferredbugs-9271/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..62e781afe86b7b6bdc6c3e76f45cee10f65862fc --- /dev/null +++ b/inferredbugs-9271/instruction.md @@ -0,0 +1,126 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** easy-random +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * The MIT License + * + * Copyright (c) 2017, Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.benas.randombeans.validation; + +import io.github.benas.randombeans.api.Randomizer; +import io.github.benas.randombeans.randomizers.RegularExpressionRandomizer; + +import javax.validation.constraints.Pattern; +import java.lang.reflect.Field; +import java.util.Random; +import static io.github.benas.randombeans.validation.ReflectionUtils.*; + +class PatternAnnotationHandler implements BeanValidationAnnotationHandler { + + private final Random random; + + public PatternAnnotationHandler(long seed) { + random = new Random(seed); + } + + public Randomizer getRandomizer(Field field) { + Class fieldType = field.getType(); + Pattern patternAnnotation = getAnnotation(field, Pattern.class); + + final String regex = patternAnnotation.regexp(); + if (fieldType.equals(String.class)) { + return new RegularExpressionRandomizer(regex, random.nextLong()); + } + return null; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `patternAnnotation` last assigned on line 44 could be null and is dereferenced at line 46. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Randomizer PatternAnnotationHandler.getRandomizer(Field) + +### Procedure Id: +io.github.benas.randombeans.validation.PatternAnnotationHandler.getRandomizer(java.lang.reflect.Fiel.00bfae714ebde84add67546e74b7b5bd + +### File: +random-beans-validation/src/main/java/io/github/benas/randombeans/validation/PatternAnnotationHandler.java + +### Key: +PatternAnnotationHandler.java|getRandomizer|NULL_DEREFERENCE + +### Node Key: +75a3105ef036e14d28c2a0df35d92164 + +### Hash: +b9d84b83785e1f19b5e23608e59c20fd + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9276/instruction.md b/inferredbugs-9276/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c34aa49babcb7e4fa930c4a6208f48b523c75e8 --- /dev/null +++ b/inferredbugs-9276/instruction.md @@ -0,0 +1,386 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-rpc +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.rpc.registry.mesh; + +import com.alipay.sofa.rpc.client.ProviderGroup; +import com.alipay.sofa.rpc.common.json.JSON; +import com.alipay.sofa.rpc.config.ApplicationConfig; +import com.alipay.sofa.rpc.config.ConsumerConfig; +import com.alipay.sofa.rpc.config.ProviderConfig; +import com.alipay.sofa.rpc.config.RegistryConfig; +import com.alipay.sofa.rpc.config.ServerConfig; +import com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException; +import com.alipay.sofa.rpc.listener.ProviderInfoListener; +import com.alipay.sofa.rpc.registry.RegistryFactory; +import com.alipay.sofa.rpc.registry.mesh.mock.HttpMockServer; +import com.alipay.sofa.rpc.registry.mesh.model.ApplicationInfoResult; +import com.alipay.sofa.rpc.registry.mesh.model.MeshEndpoint; +import com.alipay.sofa.rpc.registry.mesh.model.PublishServiceResult; +import com.alipay.sofa.rpc.registry.mesh.model.SubscribeServiceResult; +import com.alipay.sofa.rpc.registry.mesh.model.UnPublishServiceResult; +import com.alipay.sofa.rpc.registry.mesh.model.UnSubscribeServiceResult; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * @author GengZhang + */ +public class MeshRegistryTest extends BaseMeshTest { + + private static RegistryConfig registryConfig; + + private static MeshRegistry registry; + + @BeforeClass + public static void setUp() { + + HttpMockServer.initSever(7654); + + ApplicationInfoResult applicationInfoResult = new ApplicationInfoResult(); + applicationInfoResult.setSuccess(true); + HttpMockServer.addMockPath(MeshEndpoint.CONFIGS, JSON.toJSONString(applicationInfoResult)); + + PublishServiceResult publishServiceResult = new PublishServiceResult(); + publishServiceResult.setSuccess(true); + HttpMockServer.addMockPath(MeshEndpoint.PUBLISH, JSON.toJSONString(publishServiceResult)); + + SubscribeServiceResult subscribeServiceResult = new SubscribeServiceResult(); + subscribeServiceResult.setSuccess(true); + List datas = new ArrayList(); + datas.add("127.0.0.1:12200?v=4.0&p=1"); + datas.add("127.0.0.1:12201?v=4.0&p=1"); + subscribeServiceResult.setDatas(datas); + HttpMockServer.addMockPath(MeshEndpoint.SUBCRIBE, JSON.toJSONString(subscribeServiceResult)); + + UnPublishServiceResult unPublishServiceResult = new UnPublishServiceResult(); + unPublishServiceResult.setSuccess(true); + HttpMockServer.addMockPath(MeshEndpoint.UN_PUBLISH, JSON.toJSONString(unPublishServiceResult)); + + UnSubscribeServiceResult unSubscribeServiceResult = new UnSubscribeServiceResult(); + unSubscribeServiceResult.setSuccess(true); + HttpMockServer.addMockPath(MeshEndpoint.UN_SUBCRIBE, JSON.toJSONString(unSubscribeServiceResult)); + + HttpMockServer.start(); + registryConfig = new RegistryConfig() + .setProtocol("mesh") + .setSubscribe(true) + .setRegister(true) + .setAddress("http://localhost:7654"); + + registry = (MeshRegistry) RegistryFactory.getRegistry(registryConfig); + + try { + registry.init(); + } catch (Exception e) { + Assert.assertTrue(e instanceof SofaRpcRuntimeException); + } + registry.init(); + registry.start(); + } + + @AfterClass + public static void tearDown() { + try { + registry.destroy(); // destroy可能还会备份异常 + registry = null; + } finally { + // 清理数据 + HttpMockServer.stop(); + } + } + + @Test + public void testOnlyPublish() { + + Field registedAppField = null; + try { + registedAppField = MeshRegistry.class.getDeclaredField("registedApp"); + registedAppField.setAccessible(true); + } catch (NoSuchFieldException e) { + e.printStackTrace(); + } + + Boolean registedAppValue = null; + // in case of effected by other case. + try { + registedAppValue = (Boolean) registedAppField.get(registry); + registedAppField.set(registry, false); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + + LOGGER.info("current registedAppValue is " + registedAppValue); + Assert.assertTrue(!registedAppValue); + + ServerConfig serverConfig = new ServerConfig() + .setProtocol("bolt") + .setHost("0.0.0.0") + .setPort(12200); + ProviderConfig provider = new ProviderConfig(); + provider.setInterfaceId("com.alipay.xxx.TestService") + .setUniqueId("unique123Id") + .setApplication(new ApplicationConfig().setAppName("test-server")) + .setProxy("javassist") + .setRegister(true) + .setRegistry(registryConfig) + .setSerialization("hessian2") + .setServer(serverConfig) + .setWeight(222) + .setTimeout(3000); + + registry.register(provider); + + try { + registedAppValue = (Boolean) registedAppField.get(registry); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + + LOGGER.info("final registedAppValue is " + registedAppValue); + + Assert.assertTrue(registedAppValue); + } + + @Test + public void testAll() throws Exception { + + int timeoutPerSub = 1000; + + ServerConfig serverConfig = new ServerConfig() + .setProtocol("bolt") + .setHost("0.0.0.0") + .setPort(12200); + + ProviderConfig provider = new ProviderConfig(); + provider.setInterfaceId("com.alipay.xxx.TestService") + .setUniqueId("unique123Id") + .setApplication(new ApplicationConfig().setAppName("test-server")) + .setProxy("javassist") + .setRegister(true) + .setRegistry(registryConfig) + .setSerialization("hessian2") + .setServer(serverConfig) + .setWeight(222) + .setTimeout(3000); + + // 注册 + registry.register(provider); + + ConsumerConfig consumer = new ConsumerConfig(); + consumer.setInterfaceId("com.alipay.xxx.TestService") + .setUniqueId("unique123Id") + .setApplication(new ApplicationConfig().setAppName("test-server")) + .setProxy("javassist") + .setSubscribe(true) + .setSerialization("java") + .setInvokeType("sync") + .setTimeout(4444); + + String tag0 = MeshRegistryHelper.buildMeshKey(provider, serverConfig.getProtocol()); + String tag1 = MeshRegistryHelper.buildMeshKey(consumer, consumer.getProtocol()); + Assert.assertEquals(tag1, tag0); + + // 订阅 + MeshRegistryTest.MockProviderInfoListener providerInfoListener = new MeshRegistryTest.MockProviderInfoListener(); + consumer.setProviderInfoListener(providerInfoListener); + List groups = registry.subscribe(consumer); + providerInfoListener.updateAllProviders(groups); + Map ps = providerInfoListener.getData(); + Assert.assertTrue(ps.size() == 1); + + // 反注册 + CountDownLatch latch = new CountDownLatch(1); + providerInfoListener.setCountDownLatch(latch); + registry.unRegister(provider); + latch.await(timeoutPerSub, TimeUnit.MILLISECONDS); + //mesh 并不直接感知. + Assert.assertTrue(ps.size() == 1); + + // 一次发2个端口的再次注册 + latch = new CountDownLatch(1); + providerInfoListener.setCountDownLatch(latch); + provider.getServer().add(new ServerConfig() + .setProtocol("bolt") + .setHost("0.0.0.0") + .setPort(12201)); + registry.register(provider); + latch.await(timeoutPerSub * 2, TimeUnit.MILLISECONDS); + + // 重复订阅 + ConsumerConfig consumer2 = new ConsumerConfig(); + consumer2.setInterfaceId("com.alipay.xxx.TestService") + .setUniqueId("unique123Id") + .setApplication(new ApplicationConfig().setAppName("test-server")) + .setProxy("javassist") + .setSubscribe(true) + .setSerialization("java") + .setInvokeType("sync") + .setTimeout(4444); + CountDownLatch latch2 = new CountDownLatch(1); + MeshRegistryTest.MockProviderInfoListener providerInfoListener2 = new MeshRegistryTest.MockProviderInfoListener(); + providerInfoListener2.setCountDownLatch(latch2); + consumer2.setProviderInfoListener(providerInfoListener2); + List groups2 = registry.subscribe(consumer2); + providerInfoListener2.updateAllProviders(groups2); + + Map ps2 = providerInfoListener2.getData(); + Assert.assertTrue(ps2.size() == 1); + + // 取消订阅者1 + registry.unSubscribe(consumer); + + // 批量反注册,判断订阅者2的数据 + latch = new CountDownLatch(1); + providerInfoListener2.setCountDownLatch(latch); + List providerConfigList = new ArrayList(); + providerConfigList.add(provider); + registry.batchUnRegister(providerConfigList); + + latch.await(timeoutPerSub, TimeUnit.MILLISECONDS); + Assert.assertTrue(ps2.size() == 1); + + // 批量取消订阅 + List consumerConfigList = new ArrayList(); + consumerConfigList.add(consumer2); + registry.batchUnSubscribe(consumerConfigList); + + } + + private static class MockProviderInfoListener implements ProviderInfoListener { + + Map ps = new HashMap(); + + private CountDownLatch countDownLatch; + + public void setCountDownLatch(CountDownLatch countDownLatch) { + this.countDownLatch = countDownLatch; + } + + @Override + public void addProvider(ProviderGroup providerGroup) { + + } + + @Override + public void removeProvider(ProviderGroup providerGroup) { + + } + + @Override + public void updateProviders(ProviderGroup providerGroup) { + ps.put(providerGroup.getName(), providerGroup); + if (countDownLatch != null) { + countDownLatch.countDown(); + countDownLatch = null; + } + } + + @Override + public void updateAllProviders(List providerGroups) { + for (ProviderGroup providerGroup : providerGroups) { + ps.put(providerGroup.getName(), providerGroup); + } + } + + public Map getData() { + return ps; + } + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `groups` last assigned on line 210 could be null and is dereferenced by call to `updateAllProviders(...)` at line 211. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MeshRegistryTest.testAll() + +### Procedure Id: +com.alipay.sofa.rpc.registry.mesh.MeshRegistryTest.testAll():void.afc1aef69c14beb5d00bb7a74f5f8828 + +### File: +extension-impl/registry-mesh/src/test/java/com/alipay/sofa/rpc/registry/mesh/MeshRegistryTest.java + +### Key: +MeshRegistryTest.java|testAll|NULL_DEREFERENCE + +### Node Key: +4f833ed5eb912cebab1b90df303d47a5 + +### Hash: +6ab9c6e1001bdb22624a8d153b4ab2c6 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9278/instruction.md b/inferredbugs-9278/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..73cba3220091d235e1fa8cfc0146b97ce4b7ae69 --- /dev/null +++ b/inferredbugs-9278/instruction.md @@ -0,0 +1,871 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-rpc +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.rpc.client; + +import com.alipay.sofa.rpc.bootstrap.ConsumerBootstrap; +import com.alipay.sofa.rpc.common.RpcConstants; +import com.alipay.sofa.rpc.common.utils.ClassUtils; +import com.alipay.sofa.rpc.common.utils.CommonUtils; +import com.alipay.sofa.rpc.common.utils.StringUtils; +import com.alipay.sofa.rpc.config.ConsumerConfig; +import com.alipay.sofa.rpc.context.AsyncRuntime; +import com.alipay.sofa.rpc.context.RpcInternalContext; +import com.alipay.sofa.rpc.context.RpcRuntimeContext; +import com.alipay.sofa.rpc.core.exception.RpcErrorType; +import com.alipay.sofa.rpc.core.exception.SofaRouteException; +import com.alipay.sofa.rpc.core.exception.SofaRpcException; +import com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException; +import com.alipay.sofa.rpc.core.invoke.SofaResponseCallback; +import com.alipay.sofa.rpc.core.request.SofaRequest; +import com.alipay.sofa.rpc.core.response.SofaResponse; +import com.alipay.sofa.rpc.event.EventBus; +import com.alipay.sofa.rpc.event.ProviderInfoAddEvent; +import com.alipay.sofa.rpc.event.ProviderInfoRemoveEvent; +import com.alipay.sofa.rpc.event.ProviderInfoUpdateAllEvent; +import com.alipay.sofa.rpc.event.ProviderInfoUpdateEvent; +import com.alipay.sofa.rpc.filter.ConsumerInvoker; +import com.alipay.sofa.rpc.filter.FilterChain; +import com.alipay.sofa.rpc.listener.ConsumerStateListener; +import com.alipay.sofa.rpc.log.LogCodes; +import com.alipay.sofa.rpc.log.Logger; +import com.alipay.sofa.rpc.log.LoggerFactory; +import com.alipay.sofa.rpc.message.ResponseFuture; +import com.alipay.sofa.rpc.transport.ClientTransport; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import static com.alipay.sofa.rpc.client.ProviderInfoAttrs.ATTR_TIMEOUT; +import static com.alipay.sofa.rpc.common.RpcConfigs.getIntValue; +import static com.alipay.sofa.rpc.common.RpcOptions.CONSUMER_INVOKE_TIMEOUT; + +/** + * Abstract cluster, contains router chain, filter chain, address holder, connection holder and load balancer. + * + * @author GengZhang + */ +public abstract class AbstractCluster extends Cluster { + + /** + * slf4j Logger for this class + */ + private final static Logger LOGGER = LoggerFactory.getLogger(AbstractCluster.class); + + /** + * 构造函数 + * + * @param consumerBootstrap 服务端消费者启动器 + */ + public AbstractCluster(ConsumerBootstrap consumerBootstrap) { + super(consumerBootstrap); + } + + /** + * 是否已启动(已建立连接) + */ + protected volatile boolean initialized = false; + + /** + * 是否已经销毁(已经销毁不能再继续使用) + */ + protected volatile boolean destroyed = false; + + /** + * 当前Client正在发送的调用数量 + */ + protected AtomicInteger countOfInvoke = new AtomicInteger(0); + + /** + * 路由列表 + */ + protected RouterChain routerChain; + /** + * 负载均衡接口 + */ + protected LoadBalancer loadBalancer; + /** + * 地址保持器 + */ + protected AddressHolder addressHolder; + /** + * 连接管理器 + */ + protected ConnectionHolder connectionHolder; + /** + * 过滤器链 + */ + protected FilterChain filterChain; + + @Override + public synchronized void init() { + if (initialized) { // 已初始化 + return; + } + // 构造Router链 + routerChain = RouterChain.buildConsumerChain(consumerBootstrap); + // 负载均衡策略 考虑是否可动态替换? + loadBalancer = LoadBalancerFactory.getLoadBalancer(consumerBootstrap); + // 地址管理器 + addressHolder = AddressHolderFactory.getAddressHolder(consumerBootstrap); + // 连接管理器 + connectionHolder = ConnectionHolderFactory.getConnectionHolder(consumerBootstrap); + // 构造Filter链,最底层是调用过滤器 + this.filterChain = FilterChain.buildConsumerChain(this.consumerConfig, + new ConsumerInvoker(consumerBootstrap)); + + if (consumerConfig.isLazy()) { // 延迟连接 + if (LOGGER.isInfoEnabled(consumerConfig.getAppName())) { + LOGGER.infoWithApp(consumerConfig.getAppName(), "Connection will be initialized when first invoke."); + } + } + + // 启动重连线程 + connectionHolder.init(); + try { + // 得到服务端列表 + List all = consumerBootstrap.subscribe(); + if (CommonUtils.isNotEmpty(all)) { + // 初始化服务端连接(建立长连接) + updateAllProviders(all); + } + } catch (SofaRpcRuntimeException e) { + throw e; + } catch (Throwable e) { + throw new SofaRpcRuntimeException("Init provider's transport error!", e); + } + + // 启动成功 + initialized = true; + + // 如果check=true表示强依赖 + if (consumerConfig.isCheck() && !isAvailable()) { + throw new SofaRpcRuntimeException("The consumer is depend on alive provider " + + "and there is no alive provider, you can ignore it " + + "by ConsumerConfig.setCheck(boolean) (default is false)"); + } + } + + /** + * 检测状态 + */ + protected void checkClusterState() { + if (destroyed) { // 已销毁 + throw new SofaRpcRuntimeException("Client has been destroyed!"); + } + if (!initialized) { // 未初始化 + init(); + } + } + + @Override + public void addProvider(ProviderGroup providerGroup) { + // 包装了各个组件的操作 + addressHolder.addProvider(providerGroup); + connectionHolder.addProvider(providerGroup); + if (EventBus.isEnable(ProviderInfoAddEvent.class)) { + ProviderInfoAddEvent event = new ProviderInfoAddEvent(consumerConfig, providerGroup); + EventBus.post(event); + } + } + + @Override + public void removeProvider(ProviderGroup providerGroup) { + // 包装了各个组件的操作 + addressHolder.removeProvider(providerGroup); + connectionHolder.removeProvider(providerGroup); + if (EventBus.isEnable(ProviderInfoRemoveEvent.class)) { + ProviderInfoRemoveEvent event = new ProviderInfoRemoveEvent(consumerConfig, providerGroup); + EventBus.post(event); + } + } + + @Override + public void updateProviders(ProviderGroup providerGroup) { + checkProviderInfo(providerGroup); + ProviderGroup oldProviderGroup = addressHolder.getProviderGroup(providerGroup.getName()); + if (ProviderHelper.isEmpty(providerGroup)) { + addressHolder.updateProviders(providerGroup); + if (CommonUtils.isNotEmpty(oldProviderGroup.getProviderInfos())) { + if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) { + LOGGER.warnWithApp(consumerConfig.getAppName(), "Provider list is emptied, may be all " + + "providers has been closed, or this consumer has been add to blacklist"); + closeTransports(); + } + } + } else { + addressHolder.updateProviders(providerGroup); + connectionHolder.updateProviders(providerGroup); + } + if (EventBus.isEnable(ProviderInfoUpdateEvent.class)) { + ProviderInfoUpdateEvent event = new ProviderInfoUpdateEvent(consumerConfig, oldProviderGroup, providerGroup); + EventBus.post(event); + } + } + + @Override + public void updateAllProviders(List providerGroups) { + List oldProviderGroups = new ArrayList(addressHolder.getProviderGroups()); + int count = 0; + if (providerGroups != null) { + for (ProviderGroup providerGroup : providerGroups) { + checkProviderInfo(providerGroup); + count += providerGroup.size(); + } + } + if (count == 0) { + Collection currentProviderList = currentProviderList(); + addressHolder.updateAllProviders(providerGroups); + if (CommonUtils.isNotEmpty(currentProviderList)) { + if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) { + LOGGER.warnWithApp(consumerConfig.getAppName(), "Provider list is emptied, may be all " + + "providers has been closed, or this consumer has been add to blacklist"); + closeTransports(); + } + } + } else { + addressHolder.updateAllProviders(providerGroups); + connectionHolder.updateAllProviders(providerGroups); + } + if (EventBus.isEnable(ProviderInfoUpdateAllEvent.class)) { + ProviderInfoUpdateAllEvent event = new ProviderInfoUpdateAllEvent(consumerConfig, oldProviderGroups, + providerGroups); + EventBus.post(event); + } + } + + /** + * 检测服务节点的一些信息 + * + * @param providerGroup 服务列表分组 + */ + protected void checkProviderInfo(ProviderGroup providerGroup) { + List providerInfos = providerGroup == null ? null : providerGroup.getProviderInfos(); + if (CommonUtils.isEmpty(providerInfos)) { + return; + } + Iterator iterator = providerInfos.iterator(); + while (iterator.hasNext()) { + ProviderInfo providerInfo = iterator.next(); + if (!StringUtils.equals(providerInfo.getProtocolType(), consumerConfig.getProtocol())) { + if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) { + LOGGER.warnWithApp(consumerConfig.getAppName(), + "Unmatched protocol between consumer [{}] and provider [{}].", + consumerConfig.getProtocol(), providerInfo.getProtocolType()); + } + } + if (StringUtils.isEmpty(providerInfo.getSerializationType())) { + providerInfo.setSerializationType(consumerConfig.getSerialization()); + } + } + } + + @Override + public SofaResponse invoke(SofaRequest request) throws SofaRpcException { + SofaResponse response = null; + try { + // 做一些初始化检查,例如未连接可以连接 + checkClusterState(); + // 开始调用 + countOfInvoke.incrementAndGet(); // 计数+1 + response = doInvoke(request); + return response; + } catch (SofaRpcException e) { + // 客户端收到异常(客户端自己的异常) + throw e; + } finally { + countOfInvoke.decrementAndGet(); // 计数-1 + } + } + + /** + * 子类实现各自逻辑的调用,例如重试等 + * + * @param msg Request对象 + * @return 调用结果 + * @throws SofaRpcException rpc异常 + */ + protected abstract SofaResponse doInvoke(SofaRequest msg) throws SofaRpcException; + + /** + * 检查服务端版本,特殊处理 + * + * @param providerInfo 服务端 + * @param request 请求对象 + */ + protected void checkProviderVersion(ProviderInfo providerInfo, SofaRequest request) { + + } + + /** + * 上一次连接,目前是记录整个接口的,是否需要方法级的?? + */ + private volatile ProviderInfo lastProviderInfo; + + /** + * 根据规则进行负载均衡 + * + * @param message 调用对象 + * @return 一个可用的provider + * @throws SofaRpcException rpc异常 + */ + protected ProviderInfo select(SofaRequest message) throws SofaRpcException { + return select(message, null); + } + + /** + * 根据规则进行负载均衡 + * + * @param message 调用对象 + * @param invokedProviderInfos 已调用列表 + * @return 一个可用的provider + * @throws SofaRpcException rpc异常 + */ + protected ProviderInfo select(SofaRequest message, List invokedProviderInfos) + throws SofaRpcException { + // 粘滞连接,当前连接可用 + if (consumerConfig.isSticky()) { + if (lastProviderInfo != null) { + ProviderInfo providerInfo = lastProviderInfo; + ClientTransport lastTransport = connectionHolder.getAvailableClientTransport(providerInfo); + if (lastTransport != null && lastTransport.isAvailable()) { + checkAlias(providerInfo, message); + return providerInfo; + } + } + } + // 原始服务列表数据 --> 路由结果 + List providerInfos = routerChain.route(message, null); + if (CommonUtils.isEmpty(providerInfos)) { + throw noAvailableProviderException(message.getTargetServiceUniqueName()); + } + if (CommonUtils.isNotEmpty(invokedProviderInfos) && providerInfos.size() > invokedProviderInfos.size()) { // 总数大于已调用数 + providerInfos.removeAll(invokedProviderInfos);// 已经调用异常的本次不再重试 + } + + String targetIP = null; + ProviderInfo providerInfo; + RpcInternalContext context = RpcInternalContext.peekContext(); + if (context != null) { + targetIP = (String) RpcInternalContext.getContext().getAttachment(RpcConstants.HIDDEN_KEY_PINPOINT); + } + if (StringUtils.isNotBlank(targetIP)) { + // 如果指定了调用地址 + providerInfo = selectPinpointProvider(targetIP, providerInfos); + if (providerInfo == null) { + // 指定的不存在 + throw unavailableProviderException(message.getTargetServiceUniqueName(), targetIP); + } + ClientTransport clientTransport = selectByProvider(message, providerInfo); + if (clientTransport == null) { + // 指定的不存在或已死,抛出异常 + throw unavailableProviderException(message.getTargetServiceUniqueName(), targetIP); + } + return providerInfo; + } else { + do { + // 再进行负载均衡筛选 + providerInfo = loadBalancer.select(message, providerInfos); + ClientTransport transport = selectByProvider(message, providerInfo); + if (transport != null) { + return providerInfo; + } + providerInfos.remove(providerInfo); + } while (!providerInfos.isEmpty()); + } + throw noAvailableProviderException(message.getTargetServiceUniqueName()); + } + + /** + * Select provider. + * + * @param targetIP the target ip + * @return the provider + */ + protected ProviderInfo selectPinpointProvider(String targetIP, List providerInfos) { + ProviderInfo tp = ProviderHelper.toProviderInfo(targetIP); + for (ProviderInfo providerInfo : providerInfos) { + if (providerInfo.getHost().equals(tp.getHost()) + && StringUtils.equals(providerInfo.getProtocolType(), tp.getProtocolType()) + && providerInfo.getPort() == tp.getPort()) { + return providerInfo; + } + } + return null; + } + + /** + * 找不到可用的服务列表的异常 + * + * @param serviceKey 服务关键字 + * @return 服务端 + */ + protected SofaRouteException noAvailableProviderException(String serviceKey) { + return new SofaRouteException(LogCodes.getLog(LogCodes.ERROR_NO_AVAILBLE_PROVIDER, serviceKey)); + } + + /** + * 指定地址不可用 + * + * @param serviceKey 服务关键字 + * @return 服务端 + */ + protected SofaRouteException unavailableProviderException(String serviceKey, String providerInfo) { + return new SofaRouteException(LogCodes.getLog(LogCodes.ERROR_TARGET_URL_INVALID, serviceKey, providerInfo)); + } + + /** + * 得到provider得到连接 + * + * @param message 调用对象 + * @param providerInfo 指定Provider + * @return 一个可用的transport或者null + */ + protected ClientTransport selectByProvider(SofaRequest message, ProviderInfo providerInfo) { + ClientTransport transport = connectionHolder.getAvailableClientTransport(providerInfo); + if (transport != null) { + if (transport.isAvailable()) { + lastProviderInfo = providerInfo; + checkAlias(providerInfo, message); //检查分组 + return transport; + } else { + connectionHolder.setUnavailable(providerInfo, transport); + } + } + return null; + } + + /** + * 检查分组映射 + * + * @param providerInfo 服务端 + * @param message 请求对象 + */ + protected void checkAlias(ProviderInfo providerInfo, SofaRequest message) { + + } + + /** + * 发起调用链 + * + * @param providerInfo 服务端信息 + * @param request 请求对象 + * @return 执行后返回的响应 + * @throws SofaRpcException 请求RPC异常 + */ + protected SofaResponse filterChain(ProviderInfo providerInfo, SofaRequest request) throws SofaRpcException { + RpcInternalContext context = RpcInternalContext.getContext(); + context.setProviderInfo(providerInfo); + return filterChain.invoke(request); + } + + @Override + public SofaResponse sendMsg(ProviderInfo providerInfo, SofaRequest request) throws SofaRpcException { + ClientTransport clientTransport = connectionHolder.getAvailableClientTransport(providerInfo); + if (clientTransport != null && clientTransport.isAvailable()) { + return doSendMsg(providerInfo, clientTransport, request); + } else { + throw unavailableProviderException(request.getTargetServiceUniqueName(), providerInfo.getOriginUrl()); + } + } + + /** + * 调用客户端 + * + * @param transport 客户端连接 + * @param request Request对象 + * @return 调用结果 + * @throws SofaRpcException rpc异常 + */ + protected SofaResponse doSendMsg(ProviderInfo providerInfo, ClientTransport transport, + SofaRequest request) throws SofaRpcException { + RpcInternalContext context = RpcInternalContext.getContext(); + // 添加调用的服务端远程地址 + RpcInternalContext.getContext().setRemoteAddress(providerInfo.getHost(), providerInfo.getPort()); + try { + checkProviderVersion(providerInfo, request); // 根据服务端版本特殊处理 + String invokeType = request.getInvokeType(); + int timeout = resolveTimeout(request, consumerConfig, providerInfo); + + SofaResponse response = null; + // 同步调用 + if (RpcConstants.INVOKER_TYPE_SYNC.equals(invokeType)) { + long start = RpcRuntimeContext.now(); + try { + response = transport.syncSend(request, timeout); + } finally { + if (RpcInternalContext.isAttachmentEnable()) { + long elapsed = RpcRuntimeContext.now() - start; + context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE, elapsed); + } + } + } + // 单向调用 + else if (RpcConstants.INVOKER_TYPE_ONEWAY.equals(invokeType)) { + long start = RpcRuntimeContext.now(); + try { + transport.oneWaySend(request, timeout); + response = buildEmptyResponse(request); + } finally { + if (RpcInternalContext.isAttachmentEnable()) { + long elapsed = RpcRuntimeContext.now() - start; + context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE, elapsed); + } + } + } + // Callback调用 + else if (RpcConstants.INVOKER_TYPE_CALLBACK.equals(invokeType)) { + // 调用级别回调监听器 + SofaResponseCallback sofaResponseCallback = request.getSofaResponseCallback(); + if (sofaResponseCallback == null) { + SofaResponseCallback methodResponseCallback = consumerConfig + .getMethodOnreturn(request.getMethodName()); + if (methodResponseCallback != null) { // 方法的Callback + request.setSofaResponseCallback(methodResponseCallback); + } + } + // 记录发送开始时间 + context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME, RpcRuntimeContext.now()); + // 开始调用 + transport.asyncSend(request, timeout); + response = buildEmptyResponse(request); + } + // Future调用 + else if (RpcConstants.INVOKER_TYPE_FUTURE.equals(invokeType)) { + // 记录发送开始时间 + context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME, RpcRuntimeContext.now()); + // 开始调用 + ResponseFuture future = transport.asyncSend(request, timeout); + // 放入线程上下文 + RpcInternalContext.getContext().setFuture(future); + response = buildEmptyResponse(request); + } else { + throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, "Unknown invoke type:" + invokeType); + } + return response; + } catch (SofaRpcException e) { + throw e; + } catch (Throwable e) { // 客户端其它异常 + throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, e); + } + } + + private SofaResponse buildEmptyResponse(SofaRequest request) { + SofaResponse response = new SofaResponse(); + Method method = request.getMethod(); + if (method != null) { + response.setAppResponse(ClassUtils.getDefaultPrimitiveValue(method.getReturnType())); + } + return response; + } + + /** + * 决定超时时间 + * + * @param request 请求 + * @param consumerConfig 客户端配置 + * @param providerInfo 服务提供者信息 + * @return 调用超时 + */ + private int resolveTimeout(SofaRequest request, ConsumerConfig consumerConfig, ProviderInfo providerInfo) { + // 先去调用级别配置 + Integer timeout = request.getTimeout(); + if (timeout == null) { + // 取客户端配置(先方法级别再接口级别) + timeout = consumerConfig.getMethodTimeout(request.getMethodName()); + if (timeout == null || timeout < 0) { + // 再取服务端配置 + timeout = (Integer) providerInfo.getDynamicAttr(ATTR_TIMEOUT); + if (timeout == null) { + // 取框架默认值 + timeout = getIntValue(CONSUMER_INVOKE_TIMEOUT); + } + } + } + return timeout; + } + + @Override + public void destroy() { + destroy(null); + } + + @Override + public void destroy(DestroyHook hook) { + if (destroyed) { + return; + } + if (hook != null) { + hook.postDestroy(); + } + if (connectionHolder != null) { + connectionHolder.destroy(new GracefulDestroyHook()); + } + destroyed = true; + initialized = false; + if (hook != null) { + hook.postDestroy(); + } + } + + /** + * 关闭连接
    + * 注意:关闭有风险,可能有正在调用的请求,建议判断下isAvailable() + */ + protected void closeTransports() { + if (connectionHolder != null) { + connectionHolder.closeAllClientTransports(new GracefulDestroyHook()); + } + } + + /** + * 优雅关闭的钩子 + */ + protected class GracefulDestroyHook implements DestroyHook { + @Override + public void preDestroy() { + // 准备关闭连接 + int count = countOfInvoke.get(); + final int timeout = consumerConfig.getDisconnectTimeout(); // 等待结果超时时间 + if (count > 0) { // 有正在调用的请求 + long start = RpcRuntimeContext.now(); + if (LOGGER.isWarnEnabled()) { + LOGGER.warn("There are {} outstanding call in client, will close transports util return", + count); + } + while (countOfInvoke.get() > 0 && RpcRuntimeContext.now() - start < timeout) { // 等待返回结果 + try { + Thread.sleep(10); + } catch (InterruptedException ignore) { + } + } + } + } + + @Override + public void postDestroy() { + } + } + + @Override + public boolean isAvailable() { + if (destroyed || !initialized) { + return false; + } + List providerGroups = addressHolder.getProviderGroups(); + if (CommonUtils.isEmpty(providerGroups)) { + return false; + } + for (ProviderGroup entry : providerGroups) { + List providerInfos = entry.getProviderInfos(); + for (ProviderInfo providerInfo : providerInfos) { + ClientTransport transport = connectionHolder.getAvailableClientTransport(providerInfo); + if (transport != null && transport.isAvailable()) { + return true; // 只有有1个可用 即可返回 + } else { + connectionHolder.setUnavailable(providerInfo, transport); + } + } + } + return false; + } + + @Override + public void checkStateChange(boolean originalState) { + if (originalState) { // 原来可以 + if (!isAvailable()) { // 变不可以 + notifyStateChangeToUnavailable(); + } + } else { // 原来不可用 + if (isAvailable()) { // 变成可用 + notifyStateChangeToAvailable(); + } + } + } + + /** + * 通知状态变成不可用,主要是:
    + * 1.注册中心删除,更新节点后变成不可用时
    + * 2.连接断线后(心跳+调用),如果是可用节点为空 + */ + public void notifyStateChangeToUnavailable() { + final List onprepear = consumerConfig.getOnAvailable(); + if (onprepear != null) { + AsyncRuntime.getAsyncThreadPool().execute(new Runnable() { + @Override + public void run() { + // 状态变化通知监听器 + for (ConsumerStateListener listener : onprepear) { + try { + listener.onUnavailable(consumerBootstrap.getProxyIns()); + } catch (Exception e) { + LOGGER.error("Failed to notify consumer state listener when state change to unavailable"); + } + } + } + }); + } + } + + /** + * 通知状态变成可用,主要是:
    + * 1.启动成功变成可用时
    + * 2.注册中心增加,更新节点后变成可用时
    + * 3.重连上从一个可用节点都没有-->有可用节点时 + */ + public void notifyStateChangeToAvailable() { + final List onprepear = consumerConfig.getOnAvailable(); + if (onprepear != null) { + AsyncRuntime.getAsyncThreadPool().execute(new Runnable() { + @Override + public void run() { + // 状态变化通知监听器 + for (ConsumerStateListener listener : onprepear) { + try { + listener.onAvailable(consumerBootstrap.getProxyIns()); + } catch (Exception e) { + LOGGER.error("Failed to notify consumer state listener when state change to available"); + } + } + } + }); + } + } + + /** + * 获取当前的Provider全部列表(包括连上和没连上的),比较费性能,慎用 + * + * @return 当前的Provider列表 + */ + public Collection currentProviderList() { + List providerInfos = new ArrayList(); + List providerGroups = addressHolder.getProviderGroups(); + if (CommonUtils.isNotEmpty(providerGroups)) { + for (ProviderGroup entry : providerGroups) { + providerInfos.addAll(entry.getProviderInfos()); + } + } + return providerInfos; + } + + /** + * @return the consumerConfig + */ + public ConsumerConfig getConsumerConfig() { + return consumerConfig; + } + + @Override + public AddressHolder getAddressHolder() { + return addressHolder; + } + + @Override + public ConnectionHolder getConnectionHolder() { + return connectionHolder; + } + + @Override + public FilterChain getFilterChain() { + return filterChain; + } + + @Override + public RouterChain getRouterChain() { + return routerChain; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.alipay.sofa.rpc.client.AbstractCluster.checkProviderInfo` indirectly writes to field `providerInfo.com.alipay.sofa.rpc.client.ProviderInfo.serializationType` outside of synchronization. + Reporting because a superclass `class com.alipay.sofa.rpc.client.Cluster` is annotated `@ThreadSafe`, so we assume that this method can run in parallel with other non-private methods in the class (including itself). + +Note that the prefix path providerInfo has been contaminated during the execution, so the reported race on providerInfo.com.alipay.sofa.rpc.client.ProviderInfo.serializationType might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AbstractCluster.checkProviderInfo(ProviderGroup) + +### Procedure Id: +com.alipay.sofa.rpc.client.AbstractCluster.checkProviderInfo(com.alipay.sofa.rpc.client.ProviderGrou.9db25bff2d0ae187b89c3ca220495277 + +### File: +core-impl/client/src/main/java/com/alipay/sofa/rpc/client/AbstractCluster.java + +### Key: +AbstractCluster.java|checkProviderInfo|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +43fbb7792312110c96d4ab9703fe4dd2 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9282/instruction.md b/inferredbugs-9282/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fc405b78f4c1127325e7ce550057e2001a38f269 --- /dev/null +++ b/inferredbugs-9282/instruction.md @@ -0,0 +1,170 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** extract +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.icij.extract.cli; + +import org.icij.extract.core.Report; +import org.icij.extract.core.ExtractionResult; +import org.icij.extract.core.ReportType; +import org.icij.extract.json.ReportSerializer; +import org.icij.extract.cli.options.ReporterOptionSet; +import org.icij.extract.cli.options.RedisOptionSet; +import org.icij.extract.cli.factory.ReportFactory; + +import java.util.logging.Logger; + +import java.io.IOException; + +import org.apache.commons.cli.Option; +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.ParseException; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonEncoding; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; + +import hu.ssh.progressbar.ProgressBar; +import hu.ssh.progressbar.console.ConsoleProgressBar; + +/** + * Extract + * + * @author Matthew Caruana Galizia + * @since 1.0.0-beta + */ +public class DumpReportCli extends Cli { + + public DumpReportCli(final Logger logger) { + super(logger, new ReporterOptionSet(), new RedisOptionSet()); + + options.addOption(Option.builder() + .desc("Only dump reports matching the given status.") + .longOpt("reporter-status") + .hasArg() + .argName("status") + .build()); + } + + public CommandLine parse(final String[] args) throws ParseException, IllegalArgumentException { + final CommandLine cmd = super.parse(args); + + final Report report = ReportFactory.createReport(cmd, ReportType.REDIS); + ExtractionResult match = null; + + if (cmd.hasOption("reporter-status")) { + match = ExtractionResult.get(((Number) cmd.getParsedOptionValue("reporter-status"))); + + if (null == match) { + throw new IllegalArgumentException(String.format("%s is not a valid report status.", + cmd.getOptionValue("reporter-status"))); + } + } + + final ProgressBar progressBar = ConsoleProgressBar.on(System.err) + .withFormat("[:bar] :percent% :elapsed/:total ETA: :eta") + .withTotalSteps(report.size()); + + final ObjectMapper mapper = new ObjectMapper(); + final SimpleModule module = new SimpleModule(); + + module.addSerializer(Report.class, new ReportSerializer(progressBar, match)); + mapper.registerModule(module); + + try ( + final JsonGenerator jsonGenerator = new JsonFactory() + .setCodec(mapper) + .createGenerator(System.out, JsonEncoding.UTF8) + ) { + jsonGenerator.useDefaultPrettyPrinter(); + jsonGenerator.writeObject(report); + jsonGenerator.writeRaw('\n'); + } catch (IOException e) { + throw new RuntimeException("Unable to output JSON.", e); + } + + try { + report.close(); + } catch (IOException e) { + throw new RuntimeException("Exception while closing report.", e); + } + + return cmd; + } + + public void printHelp() { + super.printHelp(Command.DUMP_REPORT, "Dump the report for debugging. The name option is respected."); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `report` last assigned on line 50 could be null and is dereferenced at line 64. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +CommandLine DumpReportCli.parse(java.lang.String[]) + +### Procedure Id: +org.icij.extract.cli.DumpReportCli.parse(java.lang.String[]):org.apache.commons.cli.CommandLine.121d36a41c1bcab01f5633bd07eb4e91 + +### File: +src/main/java/org/icij/extract/cli/DumpReportCli.java + +### Key: +DumpReportCli.java|parse|NULL_DEREFERENCE + +### Node Key: +3677875e6aead27ee1320f16c80d8b0f + +### Hash: +f8fdfa3fbbae467403c3d3c283da77d0 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9285/instruction.md b/inferredbugs-9285/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f566ac3e7a72369c76cd382e285b13aa1f8769ec --- /dev/null +++ b/inferredbugs-9285/instruction.md @@ -0,0 +1,293 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** javacpp +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2012,2013,2014 Arnaud Nauwynck, Samuel Audet + * + * This file is part of JavaCPP. + * + * JavaCPP 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 (subject to the "Classpath" exception + * as provided in the LICENSE.txt file that accompanied this code). + * + * JavaCPP 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 JavaCPP. If not, see . + */ + +package org.bytedeco.javacpp.tools; + +import java.io.File; +import java.util.Arrays; +import java.util.Map; +import java.util.Properties; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.project.MavenProject; + +/** + * A Maven Mojo to call the {@link Builder} (C++ header file -> Java class -> C++ JNI -> native library). + * Can also be considered as an example of how to use the Builder programmatically. + * + * @goal build + * @phase process-classes + * @author Arnaud Nauwynck + * @author Samuel Audet + */ +public class BuildMojo extends AbstractMojo { + + /** + * Load user classes from classPath + * @parameter property="classPath" default-value="${project.build.outputDirectory}" + */ + private String classPath = null; + + /** + * Load user classes from classPaths + * @parameter property="classPaths" + */ + private String[] classPaths = null; + + /** + * Output all generated files to outputDirectory + * @parameter property="outputDirectory" + */ + private File outputDirectory = null; + + /** + * Output everything in a file named after given outputName + * @parameter property="outputName" + */ + private String outputName = null; + + /** + * Compile and delete the generated .cpp files + * @parameter property="compile" default-value="true" + */ + private boolean compile = true; + + /** + * Generate header file with declarations of callbacks functions + * @parameter property="header" default-value="false" + */ + private boolean header = false; + + /** + * Copy to output directory dependent libraries (link and preload) + * @parameter property="copyLibs" default-value="false" + */ + private boolean copyLibs = false; + + /** + * Also create a JAR file named {@code -.jar} + * @parameter property="jarPrefix" + */ + private String jarPrefix = null; + + /** + * Load all properties from resource + * @parameter property="properties" + */ + private String properties = null; + + /** + * Load all properties from file + * @parameter property="propertyFile" + */ + private File propertyFile = null; + + /** + * Set property keys to values + * @parameter property="propertyKeysAndValues" + */ + private Properties propertyKeysAndValues = null; + + /** + * Process only this class or package (suffixed with .* or .**) + * @parameter property="classOrPackageName" + */ + private String classOrPackageName = null; + + /** + * Process only these classes or packages (suffixed with .* or .**) + * @parameter property="classOrPackageNames" + */ + private String[] classOrPackageNames = null; + + /** + * Environment variables added to the compiler subprocess + * @parameter property="environmentVariables" + */ + private Map environmentVariables = null; + + /** + * Pass compilerOptions directly to compiler + * @parameter property="compilerOptions" + */ + private String[] compilerOptions = null; + + /** + * Skip the execution. + * @parameter property="skip" default-value="false" + */ + private boolean skip = false; + + /** + * @parameter default-value="${project}" + * @required + * @readonly + */ + private MavenProject project; + + @Override public void execute() throws MojoExecutionException { + final Log log = getLog(); + try { + log.info("Executing JavaCPP Builder"); + if (log.isDebugEnabled()) { + log.debug("classPath: " + classPath); + log.debug("classPaths: " + Arrays.deepToString(classPaths)); + log.debug("outputDirectory: " + outputDirectory); + log.debug("outputName: " + outputName); + log.debug("compile: " + compile); + log.debug("header: " + header); + log.debug("copyLibs: " + copyLibs); + log.debug("jarPrefix: " + jarPrefix); + log.debug("properties: " + properties); + log.debug("propertyFile: " + propertyFile); + log.debug("propertyKeysAndValues: " + propertyKeysAndValues); + log.debug("classOrPackageName: " + classOrPackageName); + log.debug("classOrPackageNames: " + Arrays.deepToString(classOrPackageNames)); + log.debug("environmentVariables: " + environmentVariables); + log.debug("compilerOptions: " + Arrays.deepToString(compilerOptions)); + log.debug("skip: " + skip); + } + + if (skip) { + log.info("Skipped execution of JavaCPP Builder"); + return; + } + + if (classPaths != null && classPath != null) { + classPaths = Arrays.copyOf(classPaths, classPaths.length + 1); + classPaths[classPaths.length - 1] = classPath; + } else if (classPath != null) { + classPaths = new String[] { classPath }; + } + + if (classOrPackageNames != null && classOrPackageName != null) { + classOrPackageNames = Arrays.copyOf(classOrPackageNames, classOrPackageNames.length + 1); + classOrPackageNames[classOrPackageNames.length - 1] = classOrPackageName; + } else if (classOrPackageName != null) { + classOrPackageNames = new String[] { classOrPackageName }; + } + + Logger logger = new Logger() { + @Override public void debug(CharSequence cs) { log.debug(cs); } + @Override public void info (CharSequence cs) { log.info(cs); } + @Override public void warn (CharSequence cs) { log.warn(cs); } + @Override public void error(CharSequence cs) { log.error(cs); } + }; + Builder builder = new Builder(logger) + .classPaths(classPaths) + .outputDirectory(outputDirectory) + .outputName(outputName) + .compile(compile) + .header(header) + .copyLibs(copyLibs) + .jarPrefix(jarPrefix) + .properties(properties) + .propertyFile(propertyFile) + .properties(propertyKeysAndValues) + .classesOrPackages(classOrPackageNames) + .environmentVariables(environmentVariables) + .compilerOptions(compilerOptions); + project.getProperties().putAll(builder.properties); + File[] outputFiles = builder.build(); + log.info("Successfully executed JavaCPP Builder"); + if (log.isDebugEnabled()) { + log.debug("outputFiles: " + Arrays.deepToString(outputFiles)); + } + } catch (Exception e) { + log.error("Failed to execute JavaCPP Builder: " + e.getMessage()); + throw new MojoExecutionException("Failed to execute JavaCPP Builder", e); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.bytedeco.javacpp.tools.UserClassLoader` acquired by call to `Builder(...)` at line 194 is not released after line 209. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BuildMojo.execute() + +### Procedure Id: +org.bytedeco.javacpp.tools.BuildMojo.execute():void.aa926aee98d1b386fbb4ea3e462da3cd + +### File: +src/main/java/org/bytedeco/javacpp/tools/BuildMojo.java + +### Key: +BuildMojo.java|execute|RESOURCE_LEAK + +### Node Key: +db2fd08a6ab5595b4130d0f14f3e4469 + +### Hash: +010940f4264b7a237fe8f8667c44fb7f + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9350/instruction.md b/inferredbugs-9350/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8b2f43b7dc667969584ac070af7b2bda746403f2 --- /dev/null +++ b/inferredbugs-9350/instruction.md @@ -0,0 +1,837 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fabric-sdk-java +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.hyperledger.fabric_ca.sdkintegration; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.CertificateParsingException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.x509.CertificateList; +import org.bouncycastle.asn1.x509.TBSCertList; +import org.hyperledger.fabric.sdk.Enrollment; +import org.hyperledger.fabric.sdk.security.CryptoSuite; +import org.hyperledger.fabric.sdk.testutils.TestConfig; +import org.hyperledger.fabric.sdkintegration.SampleStore; +import org.hyperledger.fabric.sdkintegration.SampleUser; +import org.hyperledger.fabric_ca.sdk.Attribute; +import org.hyperledger.fabric_ca.sdk.EnrollmentRequest; +import org.hyperledger.fabric_ca.sdk.HFCAClient; +import org.hyperledger.fabric_ca.sdk.MockHFCAClient; +import org.hyperledger.fabric_ca.sdk.RegistrationRequest; +import org.hyperledger.fabric_ca.sdk.exception.EnrollmentException; +import org.hyperledger.fabric_ca.sdk.exception.RevocationException; +import org.hyperledger.fabric_ca.sdk.helper.Config; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import static java.lang.String.format; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class HFCAClientIT { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private static final String TEST_ADMIN_NAME = "admin"; + private static final String TEST_ADMIN_PW = "adminpw"; + private static final String TEST_ADMIN_ORG = "org1"; + private static final String TEST_USER1_ORG = "Org2"; + private static final String TEST_USER1_AFFILIATION = "org1.department1"; + private static final String TEST_WITH_INTEGRATION_ORG = "peerOrg1"; + + private SampleStore sampleStore; + private HFCAClient client; + private SampleUser admin; + + private static CryptoSuite crypto; + + // Keeps track of how many test users we've created + private static int userCount = 0; + + // Common prefix for all test users (the suffix will be the current user count) + // Note that we include the time value so that these tests can be executed repeatedly + // without needing to restart the CA (because you cannot register a username more than once!) + private static String userNamePrefix = "user" + (System.currentTimeMillis() / 1000) + "_"; + + private static TestConfig testConfig = TestConfig.getConfig(); + + @BeforeClass + public static void init() throws Exception { + out("\n\n\nRUNNING: HFCAClientEnrollIT.\n"); + + crypto = CryptoSuite.Factory.getCryptoSuite(); + } + + @Before + public void setup() throws Exception { + + File sampleStoreFile = new File(System.getProperty("java.io.tmpdir") + "/HFCSampletest.properties"); + if (sampleStoreFile.exists()) { // For testing start fresh + sampleStoreFile.delete(); + } + sampleStore = new SampleStore(sampleStoreFile); + sampleStoreFile.deleteOnExit(); + + client = HFCAClient.createNewInstance( + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCALocation(), + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCAProperties()); + client.setCryptoSuite(crypto); + + // SampleUser can be any implementation that implements org.hyperledger.fabric.sdk.User Interface + admin = sampleStore.getMember(TEST_ADMIN_NAME, TEST_ADMIN_ORG); + if (!admin.isEnrolled()) { // Preregistered admin only needs to be enrolled with Fabric CA. + admin.setEnrollment(client.enroll(admin.getName(), TEST_ADMIN_PW)); + } + + } + + // Tests attributes + @Test + public void testRegisterAttributes() throws Exception { + + if (testConfig.isRunningAgainstFabric10()) { + return; // needs v1.1 + } + + SampleUser user = new SampleUser("mrAttributes", TEST_ADMIN_ORG, sampleStore); + + RegistrationRequest rr = new RegistrationRequest(user.getName(), TEST_USER1_AFFILIATION); + String password = "mrAttributespassword"; + rr.setSecret(password); + + rr.addAttribute(new Attribute("testattr1", "mrAttributesValue1")); + rr.addAttribute(new Attribute("testattr2", "mrAttributesValue2")); + rr.addAttribute(new Attribute("testattrDEFAULTATTR", "mrAttributesValueDEFAULTATTR", true)); + user.setEnrollmentSecret(client.register(rr, admin)); + if (!user.getEnrollmentSecret().equals(password)) { + fail("Secret returned from RegistrationRequest not match : " + user.getEnrollmentSecret()); + } + EnrollmentRequest req = new EnrollmentRequest(); + req.addAttrReq("testattr2").setOptional(false); + + user.setEnrollment(client.enroll(user.getName(), user.getEnrollmentSecret(), req)); + + Enrollment enrollment = user.getEnrollment(); + String cert = enrollment.getCert(); + String certdec = getStringCert(cert); + + assertTrue(format("Missing testattr2 in certficate decoded: %s", certdec), certdec.contains("\"testattr2\":\"mrAttributesValue2\"")); + //Since request had specific attributes don't expect defaults. + assertFalse(format("Contains testattrDEFAULTATTR in certificate decoded: %s", certdec), certdec.contains("\"testattrDEFAULTATTR\"") + || certdec.contains("\"mrAttributesValueDEFAULTATTR\"")); + assertFalse(format("Contains testattr1 in certificate decoded: %s", certdec), certdec.contains("\"testattr1\"") || certdec.contains("\"mrAttributesValue1\"")); + + } + + /** + * Test that we get default attributes. + * + * @throws Exception + */ + @Test + public void testRegisterAttributesDefault() throws Exception { + + if (testConfig.isRunningAgainstFabric10()) { + return; // needs v1.1 + } + + SampleUser user = new SampleUser("mrAttributesDefault", TEST_ADMIN_ORG, sampleStore); + + RegistrationRequest rr = new RegistrationRequest(user.getName(), TEST_USER1_AFFILIATION); + String password = "mrAttributespassword"; + rr.setSecret(password); + + rr.addAttribute(new Attribute("testattr1", "mrAttributesValue1")); + rr.addAttribute(new Attribute("testattr2", "mrAttributesValue2")); + rr.addAttribute(new Attribute("testattrDEFAULTATTR", "mrAttributesValueDEFAULTATTR", true)); + user.setEnrollmentSecret(client.register(rr, admin)); + if (!user.getEnrollmentSecret().equals(password)) { + fail("Secret returned from RegistrationRequest not match : " + user.getEnrollmentSecret()); + } + + user.setEnrollment(client.enroll(user.getName(), user.getEnrollmentSecret())); + + Enrollment enrollment = user.getEnrollment(); + String cert = enrollment.getCert(); + + String certdec = getStringCert(cert); + + assertTrue(format("Missing testattrDEFAULTATTR in certficate decoded: %s", certdec), certdec.contains("\"testattrDEFAULTATTR\":\"mrAttributesValueDEFAULTATTR\"")); + //Since request and no attribute requests at all defaults should be in certificate. + + assertFalse(format("Contains testattr1 in certificate decoded: %s", certdec), certdec.contains("\"testattr1\"") || certdec.contains("\"mrAttributesValue1\"")); + assertFalse(format("Contains testattr2 in certificate decoded: %s", certdec), certdec.contains("\"testattr2\"") || certdec.contains("\"mrAttributesValue2\"")); + + } + + /** + * Test that we get no attributes. + * + * @throws Exception + */ + @Test + public void testRegisterAttributesNONE() throws Exception { + SampleUser user = new SampleUser("mrAttributesNone", TEST_ADMIN_ORG, sampleStore); + + RegistrationRequest rr = new RegistrationRequest(user.getName(), TEST_USER1_AFFILIATION); + String password = "mrAttributespassword"; + rr.setSecret(password); + + rr.addAttribute(new Attribute("testattr1", "mrAttributesValue1")); + rr.addAttribute(new Attribute("testattr2", "mrAttributesValue2")); + rr.addAttribute(new Attribute("testattrDEFAULTATTR", "mrAttributesValueDEFAULTATTR", true)); + user.setEnrollmentSecret(client.register(rr, admin)); + if (!user.getEnrollmentSecret().equals(password)) { + fail("Secret returned from RegistrationRequest not match : " + user.getEnrollmentSecret()); + } + + EnrollmentRequest req = new EnrollmentRequest(); + req.addAttrReq(); // empty ensure no attributes. + + user.setEnrollment(client.enroll(user.getName(), user.getEnrollmentSecret(), req)); + + Enrollment enrollment = user.getEnrollment(); + String cert = enrollment.getCert(); + + String certdec = getStringCert(cert); + + assertFalse(format("Contains testattrDEFAULTATTR in certificate decoded: %s", certdec), + certdec.contains("\"testattrDEFAULTATTR\"") || certdec.contains("\"mrAttributesValueDEFAULTATTR\"")); + assertFalse(format("Contains testattr1 in certificate decoded: %s", certdec), certdec.contains("\"testattr1\"") || certdec.contains("\"mrAttributesValue1\"")); + assertFalse(format("Contains testattr2 in certificate decoded: %s", certdec), certdec.contains("\"testattr2\"") || certdec.contains("\"mrAttributesValue2\"")); + + } + + private static final Pattern compile = Pattern.compile("^-----BEGIN CERTIFICATE-----$" + "(.*?)" + "\n-----END CERTIFICATE-----\n", Pattern.DOTALL | Pattern.MULTILINE); + + static String getStringCert(String pemFormat) { + String ret = null; + + final Matcher matcher = compile.matcher(pemFormat); + if (matcher.matches()) { + final String base64part = matcher.group(1).replaceAll("\n", ""); + Base64.Decoder b64dec = Base64.getDecoder(); + ret = new String(b64dec.decode(base64part.getBytes(UTF_8))); + + } else { + fail("Certificate failed to match expected pattern. Certificate:\n" + pemFormat); + } + + return ret; + } + + // Tests re-enrolling a user that has had an enrollment revoked + @Test + public void testReenrollAndRevoke() throws Exception { + + SampleUser user = getTestUser(TEST_ADMIN_ORG); + + if (!user.isRegistered()) { // users need to be registered AND enrolled + RegistrationRequest rr = new RegistrationRequest(user.getName(), TEST_USER1_AFFILIATION); + String password = "testReenrollAndRevoke"; + rr.setSecret(password); + user.setEnrollmentSecret(client.register(rr, admin)); + if (!user.getEnrollmentSecret().equals(password)) { + fail("Secret returned from RegistrationRequest not match : " + user.getEnrollmentSecret()); + } + } + if (!user.isEnrolled()) { + user.setEnrollment(client.enroll(user.getName(), user.getEnrollmentSecret())); + } + + sleepALittle(); + + // get another enrollment + EnrollmentRequest req = new EnrollmentRequest("profile 1", "label 1", null); + req.addHost("example1.ibm.com"); + req.addHost("example2.ibm.com"); + Enrollment tmpEnroll = client.reenroll(user, req); + + // verify + String cert = tmpEnroll.getCert(); + verifyOptions(cert, req); + + sleepALittle(); + + // revoke one enrollment of this user + client.revoke(admin, tmpEnroll, "remove user 2"); + + // trying to reenroll should be ok (revocation above is only for a particular enrollment of this user) + client.reenroll(user); + + } + + // Tests attempting to re-enroll a revoked user + @Test + public void testUserRevoke() throws Exception { + + thrown.expect(EnrollmentException.class); + thrown.expectMessage("Failed to re-enroll user"); + + Calendar calendar = Calendar.getInstance(); // gets a calendar using the default time zone and locale. + calendar.add(Calendar.SECOND, -1); + Date revokedTinyBitAgoTime = calendar.getTime(); //avoid any clock skewing. + + SampleUser user = getTestUser(TEST_USER1_ORG); + + if (!user.isRegistered()) { + RegistrationRequest rr = new RegistrationRequest(user.getName(), TEST_USER1_AFFILIATION); + String password = "testUserRevoke"; + rr.setSecret(password); + rr.addAttribute(new Attribute("user.role", "department lead")); + rr.addAttribute(new Attribute("hf.revoker", "true")); + user.setEnrollmentSecret(client.register(rr, admin)); // Admin can register other users. + if (!user.getEnrollmentSecret().equals(password)) { + fail("Secret returned from RegistrationRequest not match : " + user.getEnrollmentSecret()); + } + } + + sleepALittle(); + + if (!user.isEnrolled()) { + EnrollmentRequest req = new EnrollmentRequest("profile 2", "label 2", null); + req.addHost("example3.ibm.com"); + user.setEnrollment(client.enroll(user.getName(), user.getEnrollmentSecret(), req)); + + // verify + String cert = user.getEnrollment().getCert(); + verifyOptions(cert, req); + } + + sleepALittle(); + + int startedWithRevokes = -1; + + if (!testConfig.isRunningAgainstFabric10()) { + + startedWithRevokes = getRevokes(null).length; //one more after we do this revoke. + } + + // revoke all enrollment of this user + client.revoke(admin, user.getName(), "revoke user 3"); + if (!testConfig.isRunningAgainstFabric10()) { + + final int newRevokes = getRevokes(null).length; + + assertEquals(format("Expected one more revocation %d, but got %d", startedWithRevokes + 1, newRevokes), startedWithRevokes + 1, newRevokes); + + final int revokestinybitago = getRevokes(revokedTinyBitAgoTime).length; //Should be same number when test case was started. + assertEquals(format("Expected same revocations %d, but got %d", startedWithRevokes, revokestinybitago), startedWithRevokes, revokestinybitago); + } + + // trying to reenroll the revoked user should fail with an EnrollmentException + client.reenroll(user); + } + + // Tests attempting to revoke a user with Null reason + @Test + public void testUserRevokeNullReason() throws Exception { + + thrown.expect(EnrollmentException.class); + thrown.expectMessage("Failed to re-enroll user"); + + Calendar calendar = Calendar.getInstance(); // gets a calendar using the default time zone and locale. + calendar.add(Calendar.SECOND, -1); + Date revokedTinyBitAgoTime = calendar.getTime(); //avoid any clock skewing. + + SampleUser user = getTestUser(TEST_USER1_ORG); + + if (!user.isRegistered()) { + RegistrationRequest rr = new RegistrationRequest(user.getName(), TEST_USER1_AFFILIATION); + String password = "testUserRevoke"; + rr.setSecret(password); + rr.addAttribute(new Attribute("user.role", "department lead")); + rr.addAttribute(new Attribute("hf.revoker", "true")); + user.setEnrollmentSecret(client.register(rr, admin)); // Admin can register other users. + if (!user.getEnrollmentSecret().equals(password)) { + fail("Secret returned from RegistrationRequest not match : " + user.getEnrollmentSecret()); + } + } + + sleepALittle(); + + if (!user.isEnrolled()) { + EnrollmentRequest req = new EnrollmentRequest("profile 2", "label 2", null); + req.addHost("example3.ibm.com"); + user.setEnrollment(client.enroll(user.getName(), user.getEnrollmentSecret(), req)); + + // verify + String cert = user.getEnrollment().getCert(); + verifyOptions(cert, req); + } + + sleepALittle(); + + int startedWithRevokes = -1; + + if (!testConfig.isRunningAgainstFabric10()) { + + startedWithRevokes = getRevokes(null).length; //one more after we do this revoke. + } + + // revoke all enrollment of this user + client.revoke(admin, user.getName(), null); + if (!testConfig.isRunningAgainstFabric10()) { + final int newRevokes = getRevokes(null).length; + + assertEquals(format("Expected one more revocation %d, but got %d", startedWithRevokes + 1, newRevokes), startedWithRevokes + 1, newRevokes); + } + + // trying to reenroll the revoked user should fail with an EnrollmentException + client.reenroll(user); + } + + // Tests revoking a user with genCRL using the revoke API + @Test + public void testUserRevokeGenCRL() throws Exception { + + if (testConfig.isRunningAgainstFabric10()) { + return; // needs v1.1 + } + + thrown.expect(EnrollmentException.class); + thrown.expectMessage("Failed to re-enroll user"); + + Calendar calendar = Calendar.getInstance(); // gets a calendar using the default time zone and locale. + calendar.add(Calendar.SECOND, -1); + Date revokedTinyBitAgoTime = calendar.getTime(); //avoid any clock skewing. + + SampleUser user1 = getTestUser(TEST_USER1_ORG); + SampleUser user2 = getTestUser(TEST_USER1_ORG); + + SampleUser[] users = new SampleUser[]{user1, user2}; + + for (SampleUser user : users) { + if (!user.isRegistered()) { + RegistrationRequest rr = new RegistrationRequest(user.getName(), TEST_USER1_AFFILIATION); + String password = "testUserRevoke"; + rr.setSecret(password); + rr.addAttribute(new Attribute("user.role", "department lead")); + rr.addAttribute(new Attribute("hf.revoker", "true")); + user.setEnrollmentSecret(client.register(rr, admin)); // Admin can register other users. + if (!user.getEnrollmentSecret().equals(password)) { + fail("Secret returned from RegistrationRequest not match : " + user.getEnrollmentSecret()); + } + } + + sleepALittle(); + + if (!user.isEnrolled()) { + EnrollmentRequest req = new EnrollmentRequest("profile 2", "label 2", null); + req.addHost("example3.ibm.com"); + user.setEnrollment(client.enroll(user.getName(), user.getEnrollmentSecret(), req)); + + // verify + String cert = user.getEnrollment().getCert(); + verifyOptions(cert, req); + } + } + + sleepALittle(); + + int startedWithRevokes = -1; + + startedWithRevokes = getRevokes(null).length; //one more after we do this revoke. + + // revoke all enrollment of this user and request back a CRL + String crl = client.revoke(admin, user1.getName(), null, true); + assertNotNull("Failed to get CRL using the Revoke API", crl); + + final int newRevokes = getRevokes(null).length; + + assertEquals(format("Expected one more revocation %d, but got %d", startedWithRevokes + 1, newRevokes), startedWithRevokes + 1, newRevokes); + + final int crlLength = parseCRL(crl).length; + + assertEquals(format("The number of revokes %d does not equal the number of revoked certificates (%d) in crl", newRevokes, crlLength), newRevokes, crlLength); + + // trying to reenroll the revoked user should fail with an EnrollmentException + client.reenroll(user1); + + String crl2 = client.revoke(admin, user2.getName(), null, false); + assertEquals("CRL not requested, CRL should be empty", "", crl2); + + } + + + TBSCertList.CRLEntry[] getRevokes(Date r) throws Exception { + + String crl = client.generateCRL(admin, r, null, null, null); + + return parseCRL(crl); + } + + TBSCertList.CRLEntry[] parseCRL(String crl) throws Exception { + + Base64.Decoder b64dec = Base64.getDecoder(); + final byte[] decode = b64dec.decode(crl.getBytes(UTF_8)); + + ByteArrayInputStream inStream = new ByteArrayInputStream(decode); + ASN1InputStream asnInputStream = new ASN1InputStream(inStream); + + return CertificateList.getInstance(asnInputStream.readObject()).getRevokedCertificates(); + } + + @Test + public void testEnrollNoKeyPair() throws Exception { + + thrown.expect(EnrollmentException.class); + thrown.expectMessage("Failed to enroll user"); + + SampleUser user = getEnrolledUser(TEST_ADMIN_ORG); + + EnrollmentRequest req = new EnrollmentRequest("profile 1", "label 1", null); + req.setCsr("test"); + client.enroll(user.getName(), user.getEnrollmentSecret(), req); + } + + @Test + public void testRevokeNotAuthorized() throws Exception { + + thrown.expect(RevocationException.class); + thrown.expectMessage("Error while revoking the user"); + + // See if a normal user can revoke the admin... + SampleUser user = getEnrolledUser(TEST_ADMIN_ORG); + client.revoke(user, admin.getName(), "revoke admin"); + } + + @Test + public void testEnrollSameUser() throws Exception { + + // thrown.expect(RevocationException.class); + // thrown.expectMessage("does not have attribute 'hf.Revoker'"); + + // See if a normal user can revoke the admin... + SampleUser user1 = getEnrolledUser(TEST_ADMIN_ORG); + + File sampleStoreFile = new File(System.getProperty("java.io.tmpdir") + "/HFCSampletest.properties"); + if (sampleStoreFile.exists()) { // For testing start fresh + sampleStoreFile.delete(); + } + sampleStore = new SampleStore(sampleStoreFile); + sampleStoreFile.deleteOnExit(); + + SampleUser user2 = getEnrolledUser(TEST_ADMIN_ORG); + + // client.revoke(user, admin.getName(), "revoke admin"); + client.enroll(user1.getName(), user2.getEnrollmentSecret()); + } + + // Tests enrolling a user to an unknown CA client + @Test + public void testEnrollUnknownClient() throws Exception { + + thrown.expect(EnrollmentException.class); + thrown.expectMessage("Failed to enroll user"); + + CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite(); + + // This client does not exist + String clientName = "test CA client"; + + HFCAClient clientWithName = HFCAClient.createNewInstance(clientName, + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCALocation(), + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCAProperties()); + clientWithName.setCryptoSuite(cryptoSuite); + + clientWithName.enroll(admin.getName(), TEST_ADMIN_PW); + } + + // revoke2: revoke(User revoker, String revokee, String reason) + @Test + public void testRevoke2UnknownUser() throws Exception { + + thrown.expect(RevocationException.class); + thrown.expectMessage("Error while revoking"); + + client.revoke(admin, "unknownUser", "remove user2"); + } + + @Test + public void testMockEnrollSuccessFalse() throws Exception { + + thrown.expect(EnrollmentException.class); + thrown.expectMessage("failed enrollment for user"); + + MockHFCAClient mockClient = MockHFCAClient.createNewInstance( + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCALocation(), + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCAProperties()); + mockClient.setCryptoSuite(crypto); + + SampleUser user = getEnrolledUser(TEST_ADMIN_ORG); + + mockClient.setHttpPostResponse("{\"success\":false}"); + mockClient.enroll(user.getName(), user.getEnrollmentSecret()); + } + + @Ignore + @Test + public void testMockEnrollNoCert() throws Exception { + + thrown.expect(EnrollmentException.class); + thrown.expectMessage("failed enrollment for user"); + + MockHFCAClient mockClient = MockHFCAClient.createNewInstance( + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCALocation(), + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCAProperties()); + mockClient.setCryptoSuite(crypto); + + SampleUser user = getEnrolledUser(TEST_ADMIN_ORG); + + mockClient.setHttpPostResponse("{\"success\":true}"); + mockClient.enroll(user.getName(), user.getEnrollmentSecret()); + } + + @Test + public void testMockEnrollNoResult() throws Exception { + + thrown.expect(EnrollmentException.class); + thrown.expectMessage("response did not contain a result"); + + MockHFCAClient mockClient = MockHFCAClient.createNewInstance( + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCALocation(), + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCAProperties()); + mockClient.setCryptoSuite(crypto); + + SampleUser user = getEnrolledUser(TEST_ADMIN_ORG); + + mockClient.setHttpPostResponse("{\"success\":true}"); + mockClient.enroll(user.getName(), user.getEnrollmentSecret()); + } + + @Test + public void testMockEnrollWithMessages() throws Exception { + + MockHFCAClient mockClient = MockHFCAClient.createNewInstance( + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCALocation(), + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCAProperties()); + mockClient.setCryptoSuite(crypto); + + SampleUser user = getEnrolledUser(TEST_ADMIN_ORG); + + mockClient.setHttpPostResponse( + "{\"success\":true, \"result\":{\"Cert\":\"abc\"}, \"messages\":[{\"code\":123, \"message\":\"test message\"}]}"); + mockClient.enroll(user.getName(), user.getEnrollmentSecret()); + } + + @Test + public void testMockReenrollNoResult() throws Exception { + + thrown.expect(EnrollmentException.class); + // thrown.expectMessage("failed"); + + MockHFCAClient mockClient = MockHFCAClient.createNewInstance( + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCALocation(), + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCAProperties()); + mockClient.setCryptoSuite(crypto); + + SampleUser user = getEnrolledUser(TEST_ADMIN_ORG); + + mockClient.setHttpPostResponse("{\"success\":true}"); + mockClient.reenroll(user); + } + + @Ignore + @Test + public void testMockReenrollNoCert() throws Exception { + + thrown.expect(EnrollmentException.class); + thrown.expectMessage("failed re-enrollment for user"); + + MockHFCAClient mockClient = MockHFCAClient.createNewInstance( + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCALocation(), + testConfig.getIntegrationTestsSampleOrg(TEST_WITH_INTEGRATION_ORG).getCAProperties()); + mockClient.setCryptoSuite(crypto); + + SampleUser user = getEnrolledUser(TEST_ADMIN_ORG); + + mockClient.setHttpPostResponse("{\"success\":true}"); + mockClient.reenroll(user); + } + + // ========================================================================================== + // Helper methods + // ========================================================================================== + + private void verifyOptions(String cert, EnrollmentRequest req) throws CertificateException { + try { + BufferedInputStream pem = new BufferedInputStream(new ByteArrayInputStream(cert.getBytes())); + CertificateFactory certFactory = CertificateFactory.getInstance(Config.getConfig().getCertificateFormat()); + X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(pem); + + // check Subject Alternative Names + Collection> altNames = certificate.getSubjectAlternativeNames(); + if (altNames == null) { + if (req.getHosts() != null && !req.getHosts().isEmpty()) { + fail("Host name is not included in certificate"); + } + return; + } + ArrayList subAltList = new ArrayList<>(); + for (List item : altNames) { + int type = (Integer) item.get(0); + if (type == 2) { + subAltList.add((String) item.get(1)); + } + } + if (!subAltList.equals(req.getHosts())) { + fail("Subject Alternative Names not matched the host names specified in enrollment request"); + } + + } catch (CertificateParsingException e) { + fail("Cannot parse certificate. Error is: " + e.getMessage()); + throw e; + } catch (CertificateException e) { + fail("Cannot regenerate x509 certificate. Error is: " + e.getMessage()); + throw e; + } + } + + // Returns a new (unique) user for use in a single test + private SampleUser getTestUser(String org) { + String userName = userNamePrefix + (++userCount); + return sampleStore.getMember(userName, org); + } + + // Returns an enrolled user + private SampleUser getEnrolledUser(String org) throws Exception { + SampleUser user = getTestUser(org); + RegistrationRequest rr = new RegistrationRequest(user.getName(), TEST_USER1_AFFILIATION); + String password = "password"; + rr.setSecret(password); + user.setEnrollmentSecret(client.register(rr, admin)); + if (!user.getEnrollmentSecret().equals(password)) { + fail("Secret returned from RegistrationRequest not match : " + user.getEnrollmentSecret()); + } + user.setEnrollment(client.enroll(user.getName(), user.getEnrollmentSecret())); + return user; + } + + private void sleepALittle() { + // Seems to be an odd that calling back too quickly can once in a while generate an error on the fabric_ca + // try { + // Thread.sleep(5000); + // } catch (InterruptedException e) { + // e.printStackTrace(); + // } + + } + + static void out(String format, Object... args) { + + System.err.flush(); + System.out.flush(); + + System.out.println(format(format, args)); + System.err.flush(); + System.out.flush(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.bouncycastle.asn1.ASN1InputStream` acquired to `asnInputStream` by call to `new()` at line 502 is not released after line 504. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +org.bouncycastle.asn1.x509.TBSCertList$CRLEntry[] HFCAClientIT.parseCRL(String) + +### Procedure Id: +org.hyperledger.fabric_ca.sdkintegration.HFCAClientIT.parseCRL(java.lang.String):org.bouncycastle.as.b8b9da58d6addc514010b0ac62bee3c1 + +### File: +src/test/java/org/hyperledger/fabric_ca/sdkintegration/HFCAClientIT.java + +### Key: +HFCAClientIT.java|parseCRL|RESOURCE_LEAK + +### Node Key: +a0a09701532a90f811384aa246f63b0e + +### Hash: +e2b0e01c3b058f6f179dc11f9f86ef50 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9357/instruction.md b/inferredbugs-9357/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ec768410db232e1e1616c8d09637d6998767f217 --- /dev/null +++ b/inferredbugs-9357/instruction.md @@ -0,0 +1,3731 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fabric-sdk-java +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2016, 2017 DTCC, Fujitsu Australia Software Technology, IBM - All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.hyperledger.fabric.sdk; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.regex.Pattern; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import io.grpc.StatusRuntimeException; +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hyperledger.fabric.protos.common.Common.Block; +import org.hyperledger.fabric.protos.common.Common.BlockMetadata; +import org.hyperledger.fabric.protos.common.Common.ChannelHeader; +import org.hyperledger.fabric.protos.common.Common.Envelope; +import org.hyperledger.fabric.protos.common.Common.Header; +import org.hyperledger.fabric.protos.common.Common.HeaderType; +import org.hyperledger.fabric.protos.common.Common.LastConfig; +import org.hyperledger.fabric.protos.common.Common.Metadata; +import org.hyperledger.fabric.protos.common.Common.Payload; +import org.hyperledger.fabric.protos.common.Common.Status; +import org.hyperledger.fabric.protos.common.Configtx.ConfigEnvelope; +import org.hyperledger.fabric.protos.common.Configtx.ConfigGroup; +import org.hyperledger.fabric.protos.common.Configtx.ConfigSignature; +import org.hyperledger.fabric.protos.common.Configtx.ConfigUpdateEnvelope; +import org.hyperledger.fabric.protos.common.Configtx.ConfigValue; +import org.hyperledger.fabric.protos.common.Ledger; +import org.hyperledger.fabric.protos.msp.MspConfig; +import org.hyperledger.fabric.protos.orderer.Ab; +import org.hyperledger.fabric.protos.orderer.Ab.BroadcastResponse; +import org.hyperledger.fabric.protos.orderer.Ab.DeliverResponse; +import org.hyperledger.fabric.protos.orderer.Ab.SeekInfo; +import org.hyperledger.fabric.protos.orderer.Ab.SeekPosition; +import org.hyperledger.fabric.protos.orderer.Ab.SeekSpecified; +import org.hyperledger.fabric.protos.peer.FabricProposal; +import org.hyperledger.fabric.protos.peer.FabricProposal.SignedProposal; +import org.hyperledger.fabric.protos.peer.FabricProposalResponse; +import org.hyperledger.fabric.protos.peer.FabricProposalResponse.Response; +import org.hyperledger.fabric.protos.peer.FabricTransaction.ProcessedTransaction; +import org.hyperledger.fabric.protos.peer.Query; +import org.hyperledger.fabric.protos.peer.Query.ChaincodeInfo; +import org.hyperledger.fabric.protos.peer.Query.ChaincodeQueryResponse; +import org.hyperledger.fabric.protos.peer.Query.ChannelQueryResponse; +import org.hyperledger.fabric.sdk.BlockEvent.TransactionEvent; +import org.hyperledger.fabric.sdk.Peer.PeerRole; +import org.hyperledger.fabric.sdk.exception.CryptoException; +import org.hyperledger.fabric.sdk.exception.EventHubException; +import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; +import org.hyperledger.fabric.sdk.exception.PeerException; +import org.hyperledger.fabric.sdk.exception.ProposalException; +import org.hyperledger.fabric.sdk.exception.TransactionEventException; +import org.hyperledger.fabric.sdk.exception.TransactionException; +import org.hyperledger.fabric.sdk.helper.Config; +import org.hyperledger.fabric.sdk.helper.DiagnosticFileDumper; +import org.hyperledger.fabric.sdk.helper.Utils; +import org.hyperledger.fabric.sdk.transaction.InstallProposalBuilder; +import org.hyperledger.fabric.sdk.transaction.InstantiateProposalBuilder; +import org.hyperledger.fabric.sdk.transaction.JoinPeerProposalBuilder; +import org.hyperledger.fabric.sdk.transaction.ProposalBuilder; +import org.hyperledger.fabric.sdk.transaction.ProtoUtils; +import org.hyperledger.fabric.sdk.transaction.QueryInstalledChaincodesBuilder; +import org.hyperledger.fabric.sdk.transaction.QueryInstantiatedChaincodesBuilder; +import org.hyperledger.fabric.sdk.transaction.QueryPeerChannelsBuilder; +import org.hyperledger.fabric.sdk.transaction.TransactionBuilder; +import org.hyperledger.fabric.sdk.transaction.TransactionContext; +import org.hyperledger.fabric.sdk.transaction.UpgradeProposalBuilder; + +import static java.lang.String.format; +import static org.hyperledger.fabric.sdk.User.userContextCheck; +import static org.hyperledger.fabric.sdk.helper.Utils.isNullOrEmpty; +import static org.hyperledger.fabric.sdk.transaction.ProtoUtils.createSeekInfoEnvelope; +import static org.hyperledger.fabric.sdk.transaction.ProtoUtils.getSignatureHeaderAsByteString; + +/** + * The class representing a channel with which the client SDK interacts. + *

    + */ +public class Channel implements Serializable { + private static final long serialVersionUID = -3266164166893832538L; + private static final Log logger = LogFactory.getLog(Channel.class); + private static final boolean IS_DEBUG_LEVEL = logger.isDebugEnabled(); + private static final boolean IS_TRACE_LEVEL = logger.isTraceEnabled(); + + private static final Config config = Config.getConfig(); + private static final DiagnosticFileDumper diagnosticFileDumper = IS_TRACE_LEVEL + ? config.getDiagnosticFileDumper() : null; + private static final String SYSTEM_CHANNEL_NAME = ""; + + private static final long ORDERER_RETRY_WAIT_TIME = config.getOrdererRetryWaitTime(); + private static final long CHANNEL_CONFIG_WAIT_TIME = config.getChannelConfigWaitTime(); + private static final Random RANDOM = new Random(); + private static final String BLOCK_LISTENER_TAG = "BLOCK_LISTENER_HANDLE"; + // final Set eventingPeers = Collections.synchronizedSet(new HashSet<>()); + private static final long DELTA_SWEEP = config.getTransactionListenerCleanUpTimeout(); + private static final String CHAINCODE_EVENTS_TAG = "CHAINCODE_EVENTS_HANDLE"; + final Collection orderers = new LinkedList<>(); + final Collection eventHubs = new LinkedList<>(); + // Name of the channel is only meaningful to the client + private final String name; + // The peers on this channel to which the client can connect + private final Collection peers = Collections.synchronizedSet(new HashSet<>()); + private final Map peerOptionsMap = Collections.synchronizedMap(new HashMap<>()); + private final Map> peerRoleSetMap = Collections.synchronizedMap(new HashMap<>()); + private final boolean systemChannel; + private final LinkedHashMap chainCodeListeners = new LinkedHashMap<>(); + transient HFClient client; + /** + * Runs processing events from event hubs. + */ + + transient Thread eventQueueThread = null; + private transient volatile boolean initialized = false; + private transient boolean shutdown = false; + private transient Block genesisBlock; + private transient Map msps = new HashMap<>(); + /** + * A queue each eventing hub will write events to. + */ + + private transient ChannelEventQue channelEventQue = new ChannelEventQue(); + private transient LinkedHashMap blockListeners = new LinkedHashMap<>(); + private transient LinkedHashMap> txListeners = new LinkedHashMap<>(); + //Cleans up any transaction listeners that will probably never complete. + private transient ScheduledFuture sweeper = null; + private transient String blh = null; + + { + for (Peer.PeerRole peerRole : PeerRole.ALL) { + + peerRoleSetMap.put(peerRole, Collections.synchronizedSet(new HashSet<>())); + + } + } + + private Channel(String name, HFClient hfClient, Orderer orderer, ChannelConfiguration channelConfiguration, byte[][] signers) throws InvalidArgumentException, TransactionException { + this(name, hfClient, false); + + logger.debug(format("Creating new channel %s on the Fabric", name)); + + Channel ordererChannel = orderer.getChannel(); + + try { + addOrderer(orderer); + + //----------------------------------------- + Envelope ccEnvelope = Envelope.parseFrom(channelConfiguration.getChannelConfigurationAsBytes()); + + final Payload ccPayload = Payload.parseFrom(ccEnvelope.getPayload()); + final ChannelHeader ccChannelHeader = ChannelHeader.parseFrom(ccPayload.getHeader().getChannelHeader()); + + if (ccChannelHeader.getType() != HeaderType.CONFIG_UPDATE.getNumber()) { + throw new InvalidArgumentException(format("Creating channel; %s expected config block type %s, but got: %s", + name, + HeaderType.CONFIG_UPDATE.name(), + HeaderType.forNumber(ccChannelHeader.getType()))); + } + + if (!name.equals(ccChannelHeader.getChannelId())) { + + throw new InvalidArgumentException(format("Expected config block for channel: %s, but got: %s", name, + ccChannelHeader.getChannelId())); + } + + final ConfigUpdateEnvelope configUpdateEnv = ConfigUpdateEnvelope.parseFrom(ccPayload.getData()); + ByteString configUpdate = configUpdateEnv.getConfigUpdate(); + + sendUpdateChannel(configUpdate.toByteArray(), signers, orderer); + // final ConfigUpdateEnvelope.Builder configUpdateEnvBuilder = configUpdateEnv.toBuilder();` + + //--------------------------------------- + + // sendUpdateChannel(channelConfiguration, signers, orderer); + + getGenesisBlock(orderer); // get Genesis block to make sure channel was created. + if (genesisBlock == null) { + throw new TransactionException(format("New channel %s error. Genesis bock returned null", name)); + } + + logger.debug(format("Created new channel %s on the Fabric done.", name)); + } catch (TransactionException e) { + + orderer.unsetChannel(); + if (null != ordererChannel) { + orderer.setChannel(ordererChannel); + } + + logger.error(format("Channel %s error: %s", name, e.getMessage()), e); + throw e; + } catch (Exception e) { + orderer.unsetChannel(); + if (null != ordererChannel) { + orderer.setChannel(ordererChannel); + } + String msg = format("Channel %s error: %s", name, e.getMessage()); + + logger.error(msg, e); + throw new TransactionException(msg, e); + } + + } + + Channel(String name, HFClient client) throws InvalidArgumentException { + this(name, client, false); + } + + /** + * @param name + * @param client + * @throws InvalidArgumentException + */ + + private Channel(String name, HFClient client, final boolean systemChannel) throws InvalidArgumentException { + + this.systemChannel = systemChannel; + + if (systemChannel) { + name = SYSTEM_CHANNEL_NAME; //It's special ! + initialized = true; + } else { + if (isNullOrEmpty(name)) { + throw new InvalidArgumentException("Channel name is invalid can not be null or empty."); + } + } + + if (null == client) { + throw new InvalidArgumentException("Channel client is invalid can not be null."); + } + this.name = name; + this.client = client; + logger.debug(format("Creating channel: %s, client context %s", isSystemChannel() ? "SYSTEM_CHANNEL" : name, client.getUserContext().getName())); + + } + + /** + * For requests that are not targeted for a specific channel. + * User's can not directly create this channel. + * + * @param client + * @return a new system channel. + * @throws InvalidArgumentException + */ + + static Channel newSystemChannel(HFClient client) throws InvalidArgumentException { + return new Channel(SYSTEM_CHANNEL_NAME, client, true); + } + + /** + * createNewInstance + * + * @param name + * @return A new channel + */ + static Channel createNewInstance(String name, HFClient clientContext) throws InvalidArgumentException { + return new Channel(name, clientContext); + } + + static Channel createNewInstance(String name, HFClient hfClient, Orderer orderer, ChannelConfiguration channelConfiguration, byte[]... signers) throws InvalidArgumentException, TransactionException { + + return new Channel(name, hfClient, orderer, channelConfiguration, signers); + + } + + private static void checkHandle(final String tag, final String handle) throws InvalidArgumentException { + + if (isNullOrEmpty(handle)) { + throw new InvalidArgumentException("Handle is invalid."); + } + if (!handle.startsWith(tag) || !handle.endsWith(tag)) { + throw new InvalidArgumentException("Handle is wrong type."); + } + + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + + in.defaultReadObject(); + initialized = false; + shutdown = false; + msps = new HashMap<>(); + txListeners = new LinkedHashMap<>(); + channelEventQue = new ChannelEventQue(); + blockListeners = new LinkedHashMap<>(); + + for (EventHub eventHub : getEventHubs()) { + eventHub.setEventQue(channelEventQue); + } + + } + + /** + * Get all Event Hubs on this channel. + * + * @return Event Hubs + */ + public Collection getEventHubs() { + return Collections.unmodifiableCollection(eventHubs); + } + + /** + * Update channel with specified channel configuration + * + * @param updateChannelConfiguration Updated Channel configuration + * @param signers signers + * @throws TransactionException + * @throws InvalidArgumentException + */ + + public void updateChannelConfiguration(UpdateChannelConfiguration updateChannelConfiguration, byte[]... signers) throws TransactionException, InvalidArgumentException { + + updateChannelConfiguration(updateChannelConfiguration, getRandomOrderer(), signers); + + } + + /** + * Update channel with specified channel configuration + * + * @param updateChannelConfiguration Channel configuration + * @param signers signers + * @param orderer The specific orderer to use. + * @throws TransactionException + * @throws InvalidArgumentException + */ + + public void updateChannelConfiguration(UpdateChannelConfiguration updateChannelConfiguration, Orderer orderer, byte[]... signers) throws TransactionException, InvalidArgumentException { + + checkChannelState(); + + checkOrderer(orderer); + + try { + final long startLastConfigIndex = getLastConfigIndex(orderer); + logger.trace(format("startLastConfigIndex: %d. Channel config wait time is: %d", + startLastConfigIndex, CHANNEL_CONFIG_WAIT_TIME)); + + sendUpdateChannel(updateChannelConfiguration.getUpdateChannelConfigurationAsBytes(), signers, orderer); + + long currentLastConfigIndex = -1; + final long nanoTimeStart = System.nanoTime(); + + //Try to wait to see the channel got updated but don't fail if we don't see it. + do { + currentLastConfigIndex = getLastConfigIndex(orderer); + if (currentLastConfigIndex == startLastConfigIndex) { + + final long duration = TimeUnit.MILLISECONDS.convert(System.nanoTime() - nanoTimeStart, TimeUnit.NANOSECONDS); + + if (duration > CHANNEL_CONFIG_WAIT_TIME) { + logger.warn(format("Channel %s did not get updated last config after %d ms, Config wait time: %d ms. startLastConfigIndex: %d, currentLastConfigIndex: %d ", + name, duration, CHANNEL_CONFIG_WAIT_TIME, startLastConfigIndex, currentLastConfigIndex)); + //waited long enough .. + currentLastConfigIndex = startLastConfigIndex - 1L; // just bail don't throw exception. + } else { + + try { + Thread.sleep(ORDERER_RETRY_WAIT_TIME); //try again sleep + } catch (InterruptedException e) { + TransactionException te = new TransactionException("update channel thread Sleep", e); + logger.warn(te.getMessage(), te); + } + } + + } + + logger.trace(format("currentLastConfigIndex: %d", currentLastConfigIndex)); + + } while (currentLastConfigIndex == startLastConfigIndex); + + } catch (TransactionException e) { + + logger.error(format("Channel %s error: %s", name, e.getMessage()), e); + throw e; + } catch (Exception e) { + String msg = format("Channel %s error: %s", name, e.getMessage()); + + logger.error(msg, e); + throw new TransactionException(msg, e); + } + + } + + private void sendUpdateChannel(byte[] configupdate, byte[][] signers, Orderer orderer) throws TransactionException, InvalidArgumentException { + + logger.debug(format("Channel %s sendUpdateChannel", name)); + checkOrderer(orderer); + + try { + + final long nanoTimeStart = System.nanoTime(); + int statusCode = 0; + + do { + + //Make sure we have fresh transaction context for each try just to be safe. + TransactionContext transactionContext = getTransactionContext(); + + ConfigUpdateEnvelope.Builder configUpdateEnvBuilder = ConfigUpdateEnvelope.newBuilder(); + + configUpdateEnvBuilder.setConfigUpdate(ByteString.copyFrom(configupdate)); + + for (byte[] signer : signers) { + + configUpdateEnvBuilder.addSignatures( + ConfigSignature.parseFrom(signer)); + + } + + //-------------- + // Construct Payload Envelope. + + final ByteString sigHeaderByteString = getSignatureHeaderAsByteString(transactionContext); + + final ChannelHeader payloadChannelHeader = ProtoUtils.createChannelHeader(HeaderType.CONFIG_UPDATE, + transactionContext.getTxID(), name, transactionContext.getEpoch(), transactionContext.getFabricTimestamp(), null); + + final Header payloadHeader = Header.newBuilder().setChannelHeader(payloadChannelHeader.toByteString()) + .setSignatureHeader(sigHeaderByteString).build(); + + final ByteString payloadByteString = Payload.newBuilder() + .setHeader(payloadHeader) + .setData(configUpdateEnvBuilder.build().toByteString()) + .build().toByteString(); + + ByteString payloadSignature = transactionContext.signByteStrings(payloadByteString); + + Envelope payloadEnv = Envelope.newBuilder() + .setSignature(payloadSignature) + .setPayload(payloadByteString).build(); + + BroadcastResponse trxResult = orderer.sendTransaction(payloadEnv); + + statusCode = trxResult.getStatusValue(); + + logger.debug(format("Channel %s sendUpdateChannel %d", name, statusCode)); + if (statusCode == 404 || statusCode == 503) { + // these we can retry.. + final long duration = TimeUnit.MILLISECONDS.convert(System.nanoTime() - nanoTimeStart, TimeUnit.NANOSECONDS); + + if (duration > CHANNEL_CONFIG_WAIT_TIME) { + //waited long enough .. throw an exception + String info = trxResult.getInfo(); + if (null == info) { + info = ""; + + } + + throw new TransactionException(format("Channel %s update error timed out after %d ms. Status value %d. Status %s. %s", name, + duration, statusCode, trxResult.getStatus().name(), info)); + } + + try { + Thread.sleep(ORDERER_RETRY_WAIT_TIME); //try again sleep + } catch (InterruptedException e) { + TransactionException te = new TransactionException("update thread Sleep", e); + logger.warn(te.getMessage(), te); + } + + } else if (200 != statusCode) { + // Can't retry. + + String info = trxResult.getInfo(); + if (null == info) { + info = ""; + } + + throw new TransactionException(format("New channel %s error. StatusValue %d. Status %s. %s", name, + statusCode, "" + trxResult.getStatus(), info)); + } + + } while (200 != statusCode); // try again + + } catch (TransactionException e) { + + logger.error(format("Channel %s error: %s", name, e.getMessage()), e); + throw e; + } catch (Exception e) { + String msg = format("Channel %s error: %s", name, e.getMessage()); + + logger.error(msg, e); + throw new TransactionException(msg, e); + } + + } + + Enrollment getEnrollment() { + return client.getUserContext().getEnrollment(); + } + + /** + * Is channel initialized. + * + * @return true if the channel has been initialized. + */ + + public boolean isInitialized() { + return initialized; + } + + /** + * Get the channel name + * + * @return The name of the channel + */ + public String getName() { + return this.name; + } + + /** + * Add a peer to the channel + * + * @param peer The Peer to add. + * @return Channel The current channel added. + * @throws InvalidArgumentException + */ + public Channel addPeer(Peer peer) throws InvalidArgumentException { + + return addPeer(peer, PeerOptions.createPeerOptions()); + + } + + /** + * Add a peer to the channel + * + * @param peer The Peer to add. + * @param peerOptions see {@link PeerRole} + * @return Channel The current channel added. + * @throws InvalidArgumentException + */ + public Channel addPeer(Peer peer, PeerOptions peerOptions) throws InvalidArgumentException { + if (shutdown) { + throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); + } + + if (initialized) { + throw new InvalidArgumentException(format("Channel %s has been initialized.", name)); + } + + if (null == peer) { + throw new InvalidArgumentException("Peer is invalid can not be null."); + } + + if (peer.getChannel() != null && peer.getChannel() != this) { + throw new InvalidArgumentException(format("Peer already connected to channel %s", peer.getChannel().getName())); + } + + if (null == peerOptions) { + throw new InvalidArgumentException("Peer is invalid can not be null."); + } + peer.setChannel(this); + + peers.add(peer); + peerOptionsMap.put(peer, peerOptions.clone()); + + for (Map.Entry> peerRole : peerRoleSetMap.entrySet()) { + if (peerOptions.getPeerRoles().contains(peerRole.getKey())) { + peerRole.getValue().add(peer); + } + } + return this; + } + + /** + * Join the peer to the channel. The peer is added with all roles see {@link PeerOptions} + * + * @param peer the peer to join the channel. + * @return + * @throws ProposalException + */ + + public Channel joinPeer(Peer peer) throws ProposalException { + return joinPeer(peer, PeerOptions.createPeerOptions()); + } + + private Collection getEventingPeers() { + + return Collections.unmodifiableCollection(peerRoleSetMap.get(PeerRole.EVENT_SOURCE)); + } + + private Collection getEndorsingPeers() { + + return Collections.unmodifiableCollection(peerRoleSetMap.get(PeerRole.ENDORSING_PEER)); + } + + private Collection getChaincodePeers() { + + return Collections.unmodifiableCollection(getPeers(EnumSet.of(PeerRole.CHAINCODE_QUERY, PeerRole.ENDORSING_PEER))); + } + + private Collection getChaincodeQueryPeers() { + + return Collections.unmodifiableCollection(peerRoleSetMap.get(PeerRole.CHAINCODE_QUERY)); + } + + private Collection getLedgerQueryPeers() { + + return Collections.unmodifiableCollection(peerRoleSetMap.get(PeerRole.LEDGER_QUERY)); + } + + /** + * @param peer the peer to join the channel. + * @param peerOptions see {@link PeerOptions} + * @return + * @throws ProposalException + */ + + public Channel joinPeer(Peer peer, PeerOptions peerOptions) throws ProposalException { + + logger.debug(format("Channel %s joining peer %s, url: %s", name, peer.getName(), peer.getUrl())); + + if (shutdown) { + throw new ProposalException(format("Channel %s has been shutdown.", name)); + } + + Channel peerChannel = peer.getChannel(); + if (null != peerChannel && peerChannel != this) { + throw new ProposalException(format("Can not add peer %s to channel %s because it already belongs to channel %s.", peer.getName(), name, peerChannel.getName())); + + } + + if (genesisBlock == null && orderers.isEmpty()) { + ProposalException e = new ProposalException("Channel missing genesis block and no orderers configured"); + logger.error(e.getMessage(), e); + } + try { + + genesisBlock = getGenesisBlock(getRandomOrderer()); + logger.debug(format("Channel %s got genesis block", name)); + + final Channel systemChannel = newSystemChannel(client); //channel is not really created and this is targeted to system channel + + TransactionContext transactionContext = systemChannel.getTransactionContext(); + + FabricProposal.Proposal joinProposal = JoinPeerProposalBuilder.newBuilder() + .context(transactionContext) + .genesisBlock(genesisBlock) + .build(); + + logger.debug("Getting signed proposal."); + SignedProposal signedProposal = getSignedProposal(transactionContext, joinProposal); + logger.debug("Got signed proposal."); + + addPeer(peer, peerOptions); //need to add peer. + + Collection resp = sendProposalToPeers(new ArrayList<>(Collections.singletonList(peer)), + signedProposal, transactionContext); + + ProposalResponse pro = resp.iterator().next(); + + if (pro.getStatus() == ProposalResponse.Status.SUCCESS) { + logger.info(format("Peer %s joined into channel %s", peer.getName(), name)); + } else { + removePeerInternal(peer); + throw new ProposalException(format("Join peer to channel %s failed. Status %s, details: %s", + name, pro.getStatus().toString(), pro.getMessage())); + + } + } catch (ProposalException e) { + removePeerInternal(peer); + logger.error(e); + throw e; + } catch (Exception e) { + peers.remove(peer); + logger.error(e); + throw new ProposalException(e.getMessage(), e); + } + + return this; + } + + /** + * Removes the peer connection from the channel. + * This does NOT unjoin the peer from from the channel. + * Fabric does not support that at this time -- maybe some day, but not today + * + * @param peer + */ + public void removePeer(Peer peer) throws InvalidArgumentException { + if (initialized) { + throw new InvalidArgumentException(format("Can not remove peer from channel %s already initialized.", name)); + } + if (shutdown) { + throw new InvalidArgumentException(format("Can not remove peer from channel %s already shutdown.", name)); + } + + checkPeer(peer); + removePeerInternal(peer); + + } + + private void removePeerInternal(Peer peer) { + + peers.remove(peer); + peerOptionsMap.remove(peer); + + for (Set peerRoleSet : peerRoleSetMap.values()) { + peerRoleSet.remove(peer); + } + peer.unsetChannel(); + } + + /** + * Add an Orderer to this channel. + * + * @param orderer the orderer to add. + * @return this channel. + * @throws InvalidArgumentException + */ + + public Channel addOrderer(Orderer orderer) throws InvalidArgumentException { + + if (shutdown) { + throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); + } + + if (null == orderer) { + throw new InvalidArgumentException("Orderer is invalid can not be null."); + } + + logger.debug(format("Channel %s adding orderer%s, url: %s", name, orderer.getName(), orderer.getUrl())); + + orderer.setChannel(this); + orderers.add(orderer); + return this; + } + + public PeerOptions getPeersOptions(Peer peer) { + PeerOptions ret = peerOptionsMap.get(peer); + if (ret != null) { + ret = ret.clone(); + } + return ret; + + } + +// private Set traverseConfigGroupsAnchors(String name, ConfigGroup configGroup, Set anchorPeers) throws InvalidProtocolBufferException, InvalidArgumentException { +// ConfigValue anchorsConfig = configGroup.getValuesMap().get("AnchorPeers"); +// if (anchorsConfig != null) { +// AnchorPeers anchors = AnchorPeers.parseFrom(anchorsConfig.getValue()); +// for (AnchorPeer anchorPeer : anchors.getAnchorPeersList()) { +// String hostName = anchorPeer.getHost(); +// int port = anchorPeer.getPort(); +// logger.debug(format("parsed from config block: anchor peer %s:%d", hostName, port)); +// anchorPeers.add(new Anchor(hostName, port)); +// } +// } +// +// for (Map.Entry gm : configGroup.getGroupsMap().entrySet()) { +// traverseConfigGroupsAnchors(gm.getKey(), gm.getValue(), anchorPeers); +// } +// +// return anchorPeers; +// } + + /** + * Add an Event Hub to this channel. + * + * @param eventHub + * @return this channel + * @throws InvalidArgumentException + */ + + public Channel addEventHub(EventHub eventHub) throws InvalidArgumentException { + + if (shutdown) { + throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); + } + if (null == eventHub) { + throw new InvalidArgumentException("EventHub is invalid can not be null."); + } + + logger.debug(format("Channel %s adding event hub %s, url: %s", name, eventHub.getName(), eventHub.getUrl())); + eventHub.setChannel(this); + eventHub.setEventQue(channelEventQue); + eventHubs.add(eventHub); + return this; + + } + + /** + * Get the peers for this channel. + * + * @return the peers. + */ + public Collection getPeers() { + return Collections.unmodifiableCollection(peers); + } + + /** + * Get the peers for this channel. + * + * @return the peers. + */ + public Collection getPeers(EnumSet roles) { + + Set ret = new HashSet<>(getPeers().size()); + + for (PeerRole peerRole : roles) { + ret.addAll(peerRoleSetMap.get(peerRole)); + } + + return Collections.unmodifiableCollection(ret); + } + + /** + * Set peerOptions in the channel that has not be initialized yet. + * + * @param peer the peer to set options on. + * @param peerOptions see {@link PeerOptions} + * @return old options. + */ + + PeerOptions setPeerOptions(Peer peer, PeerOptions peerOptions) throws InvalidArgumentException { + if (initialized) { + throw new InvalidArgumentException(format("Channel %s already initialized.", name)); + } + + checkPeer(peer); + PeerOptions ret = getPeersOptions(peer); + removePeerInternal(peer); + addPeer(peer, peerOptions); + + return ret; + + } + + /** + * Initialize the Channel. Starts the channel. event hubs will connect. + * + * @return this channel. + * @throws InvalidArgumentException + * @throws TransactionException + */ + + public Channel initialize() throws InvalidArgumentException, TransactionException { + + logger.debug(format("Channel %s initialize shutdown %b", name, shutdown)); + + if (shutdown) { + throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); + } + + if (isNullOrEmpty(name)) { + + throw new InvalidArgumentException("Can not initialize channel without a valid name."); + + } + if (client == null) { + throw new InvalidArgumentException("Can not initialize channel without a client object."); + } + + userContextCheck(client.getUserContext()); + + try { + parseConfigBlock(); // Parse config block for this channel to get it's information. + + loadCACertificates(); // put all MSP certs into cryptoSuite + + logger.debug(format("Eventque started %s", "" + eventQueueThread)); + + for (EventHub eh : eventHubs) { //Connect all event hubs + eh.connect(getTransactionContext()); + } + + for (Peer peer : getEventingPeers()) { + peer.initiateEventing(getTransactionContext(), getPeersOptions(peer)); + } + + logger.debug(format("%d eventhubs initialized", getEventHubs().size())); + + registerTransactionListenerProcessor(); //Manage transactions. + logger.debug(format("Channel %s registerTransactionListenerProcessor completed", name)); + startEventQue(); //Run the event for event messages from event hubs. + + this.initialized = true; + + logger.debug(format("Channel %s initialized", name)); + + return this; + } catch (TransactionException e) { + logger.error(e.getMessage(), e); + throw e; + + } catch (Exception e) { + TransactionException exp = new TransactionException(e); + logger.error(exp.getMessage(), exp); + throw exp; + } + + } + + /** + * load the peer organizations CA certificates into the channel's trust store so that we + * can verify signatures from peer messages + * + * @throws InvalidArgumentException + * @throws CryptoException + */ + protected void loadCACertificates() throws InvalidArgumentException, CryptoException { + logger.debug(format("Channel %s loadCACertificates", name)); + + if (msps == null || msps.isEmpty()) { + throw new InvalidArgumentException("Unable to load CA certificates. Channel " + name + " does not have any MSPs."); + } + + List certList; + for (MSP msp : msps.values()) { + logger.debug("loading certificates for MSP : " + msp.getID()); + certList = Arrays.asList(msp.getRootCerts()); + if (certList.size() > 0) { + client.getCryptoSuite().loadCACertificatesAsBytes(certList); + } + certList = Arrays.asList(msp.getIntermediateCerts()); + if (certList.size() > 0) { + client.getCryptoSuite().loadCACertificatesAsBytes(certList); + } + // not adding admin certs. Admin certs should be signed by the CA + } + logger.debug(format("Channel %s loadCACertificates completed ", name)); + } + + private Block getGenesisBlock(Orderer orderer) throws TransactionException { + try { + if (genesisBlock != null) { + logger.debug(format("Channel %s getGenesisBlock already present", name)); + + } else { + + final long start = System.currentTimeMillis(); + + SeekSpecified seekSpecified = SeekSpecified.newBuilder() + .setNumber(0) + .build(); + SeekPosition seekPosition = SeekPosition.newBuilder() + .setSpecified(seekSpecified) + .build(); + + SeekSpecified seekStopSpecified = SeekSpecified.newBuilder() + .setNumber(0) + .build(); + + SeekPosition seekStopPosition = SeekPosition.newBuilder() + .setSpecified(seekStopSpecified) + .build(); + + SeekInfo seekInfo = SeekInfo.newBuilder() + .setStart(seekPosition) + .setStop(seekStopPosition) + .setBehavior(SeekInfo.SeekBehavior.BLOCK_UNTIL_READY) + .build(); + + ArrayList deliverResponses = new ArrayList<>(); + + seekBlock(seekInfo, deliverResponses, orderer); + + DeliverResponse blockresp = deliverResponses.get(1); + Block configBlock = blockresp.getBlock(); + if (configBlock == null) { + throw new TransactionException(format("In getGenesisBlock newest block for channel %s fetch bad deliver returned null:", name)); + } + + int dataCount = configBlock.getData().getDataCount(); + if (dataCount < 1) { + throw new TransactionException(format("In getGenesisBlock bad config block data count %d", dataCount)); + } + + genesisBlock = blockresp.getBlock(); + + } + } catch (TransactionException e) { + logger.error(e.getMessage(), e); + throw e; + } catch (Exception e) { + TransactionException exp = new TransactionException("getGenesisBlock " + e.getMessage(), e); + logger.error(exp.getMessage(), exp); + throw exp; + } + + if (genesisBlock == null) { //make sure it was really set. + TransactionException exp = new TransactionException("getGenesisBlock returned null"); + logger.error(exp.getMessage(), exp); + throw exp; + + } + + logger.debug(format("Channel %s getGenesisBlock done.", name)); + return genesisBlock; + } + + boolean isSystemChannel() { + return systemChannel; + } + + /** + * Is the channel shutdown. + * + * @return return true if the channel is shutdown. + */ + public boolean isShutdown() { + return shutdown; + } + + /** + * Get signed byes of the update channel. + * + * @param updateChannelConfiguration + * @param signer + * @return + * @throws InvalidArgumentException + */ + public byte[] getUpdateChannelConfigurationSignature(UpdateChannelConfiguration updateChannelConfiguration, User signer) throws InvalidArgumentException { + + userContextCheck(signer); + + if (null == updateChannelConfiguration) { + + throw new InvalidArgumentException("channelConfiguration is null"); + + } + + try { + + TransactionContext transactionContext = getTransactionContext(signer); + + final ByteString configUpdate = ByteString.copyFrom(updateChannelConfiguration.getUpdateChannelConfigurationAsBytes()); + + ByteString sigHeaderByteString = getSignatureHeaderAsByteString(signer, transactionContext); + + ByteString signatureByteSting = transactionContext.signByteStrings(new User[] {signer}, + sigHeaderByteString, configUpdate)[0]; + + return ConfigSignature.newBuilder() + .setSignatureHeader(sigHeaderByteString) + .setSignature(signatureByteSting) + .build().toByteArray(); + + } catch (Exception e) { + + throw new InvalidArgumentException(e); + } finally { + logger.debug("finally done"); + } + } + + ChannelEventQue getChannelEventQue() { + return channelEventQue; + } + + ExecutorService getExecutorService() { + return client.getExecutorService(); + } + + protected void parseConfigBlock() throws TransactionException { + + try { + + final Block configBlock = getConfigurationBlock(); + + logger.debug(format("Channel %s Got config block getting MSP data and anchorPeers data", name)); + + Envelope envelope = Envelope.parseFrom(configBlock.getData().getData(0)); + Payload payload = Payload.parseFrom(envelope.getPayload()); + ConfigEnvelope configEnvelope = ConfigEnvelope.parseFrom(payload.getData()); + ConfigGroup channelGroup = configEnvelope.getConfig().getChannelGroup(); + Map newMSPS = traverseConfigGroupsMSP("", channelGroup, new HashMap<>(20)); + + msps = Collections.unmodifiableMap(newMSPS); + +// anchorPeers = Collections.unmodifiableSet(traverseConfigGroupsAnchors("", channelGroup, new HashSet<>())); + + } catch (TransactionException e) { + logger.error(e.getMessage(), e); + throw e; + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new TransactionException(e); + } + + } + + private Map traverseConfigGroupsMSP(String name, ConfigGroup configGroup, Map msps) throws InvalidProtocolBufferException { + + ConfigValue mspv = configGroup.getValuesMap().get("MSP"); + if (null != mspv) { + if (!msps.containsKey(name)) { + + MspConfig.MSPConfig mspConfig = MspConfig.MSPConfig.parseFrom(mspv.getValue()); + + MspConfig.FabricMSPConfig fabricMSPConfig = MspConfig.FabricMSPConfig.parseFrom(mspConfig.getConfig()); + + msps.put(name, new MSP(name, fabricMSPConfig)); + + } + } + + for (Map.Entry gm : configGroup.getGroupsMap().entrySet()) { + traverseConfigGroupsMSP(gm.getKey(), gm.getValue(), msps); + } + + return msps; + } + + /** + * Provide the Channel's latest raw Configuration Block. + * + * @return Channel configuration block. + * @throws TransactionException + */ + + private Block getConfigurationBlock() throws TransactionException { + + logger.debug(format("getConfigurationBlock for channel %s", name)); + + try { + Orderer orderer = getRandomOrderer(); + + long lastConfigIndex = getLastConfigIndex(orderer); + + logger.debug(format("Last config index is %d", lastConfigIndex)); + + Block configBlock = getBlockByNumber(lastConfigIndex); + + //Little extra parsing but make sure this really is a config block for this channel. + Envelope envelopeRet = Envelope.parseFrom(configBlock.getData().getData(0)); + Payload payload = Payload.parseFrom(envelopeRet.getPayload()); + ChannelHeader channelHeader = ChannelHeader.parseFrom(payload.getHeader().getChannelHeader()); + if (channelHeader.getType() != HeaderType.CONFIG.getNumber()) { + throw new TransactionException(format("Bad last configuration block type %d, expected %d", + channelHeader.getType(), HeaderType.CONFIG.getNumber())); + } + + if (!name.equals(channelHeader.getChannelId())) { + throw new TransactionException(format("Bad last configuration block channel id %s, expected %s", + channelHeader.getChannelId(), name)); + } + + if (null != diagnosticFileDumper) { + logger.trace(format("Channel %s getConfigurationBlock returned %s", name, + diagnosticFileDumper.createDiagnosticFile(String.valueOf(configBlock).getBytes()))); + } + + if (!logger.isTraceEnabled()) { + logger.debug(format("Channel %s getConfigurationBlock returned", name)); + } + + return configBlock; + + } catch (TransactionException e) { + logger.error(e.getMessage(), e); + throw e; + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new TransactionException(e); + } + + } + + /** + * Channel Configuration bytes. Bytes that can be used with configtxlator tool to upgrade the channel. + * Convert to Json for editing with: + * {@code + *

    + * curl -v POST --data-binary @fooConfig http://host/protolator/decode/common.Config + *

    + * } + * See http://hyperledger-fabric.readthedocs.io/en/latest/configtxlator.html + * + * @return Channel configuration bytes. + * @throws TransactionException + */ + + public byte[] getChannelConfigurationBytes() throws TransactionException { + try { + final Block configBlock = getConfigurationBlock(); + + Envelope envelopeRet = Envelope.parseFrom(configBlock.getData().getData(0)); + + Payload payload = Payload.parseFrom(envelopeRet.getPayload()); + + ConfigEnvelope configEnvelope = ConfigEnvelope.parseFrom(payload.getData()); + return configEnvelope.getConfig().toByteArray(); + + } catch (Exception e) { + throw new TransactionException(e); + } + + } + + private long getLastConfigIndex(Orderer orderer) throws CryptoException, TransactionException, InvalidArgumentException, InvalidProtocolBufferException { + Block latestBlock = getLatestBlock(orderer); + + BlockMetadata blockMetadata = latestBlock.getMetadata(); + + Metadata metaData = Metadata.parseFrom(blockMetadata.getMetadata(1)); + + LastConfig lastConfig = LastConfig.parseFrom(metaData.getValue()); + + return lastConfig.getIndex(); + } + + private Block getBlockByNumber(final long number) throws TransactionException { + + logger.trace(format("getConfigurationBlock for channel %s", name)); + + try { + + logger.trace(format("Last config index is %d", number)); + + SeekSpecified seekSpecified = SeekSpecified.newBuilder().setNumber(number).build(); + + SeekPosition seekPosition = SeekPosition.newBuilder() + .setSpecified(seekSpecified) + .build(); + + SeekInfo seekInfo = SeekInfo.newBuilder() + .setStart(seekPosition) + .setStop(seekPosition) + .setBehavior(SeekInfo.SeekBehavior.BLOCK_UNTIL_READY) + .build(); + + ArrayList deliverResponses = new ArrayList<>(); + + seekBlock(seekInfo, deliverResponses, getRandomOrderer()); + + DeliverResponse blockresp = deliverResponses.get(1); + + Block retBlock = blockresp.getBlock(); + if (retBlock == null) { + throw new TransactionException(format("newest block for channel %s fetch bad deliver returned null:", name)); + } + + int dataCount = retBlock.getData().getDataCount(); + if (dataCount < 1) { + throw new TransactionException(format("Bad config block data count %d", dataCount)); + } + + logger.trace(format("Received block for channel %s, block no:%d, transaction count: %d", + name, retBlock.getHeader().getNumber(), retBlock.getData().getDataCount())); + + return retBlock; + + } catch (TransactionException e) { + logger.error(e.getMessage(), e); + throw e; + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new TransactionException(e); + } + + } + + private int seekBlock(SeekInfo seekInfo, List deliverResponses, Orderer ordererIn) throws TransactionException { + + logger.trace(format("seekBlock for channel %s", name)); + final long start = System.currentTimeMillis(); + @SuppressWarnings ("UnusedAssignment") + int statusRC = 404; + + try { + + do { + + statusRC = 404; + + final Orderer orderer = ordererIn != null ? ordererIn : getRandomOrderer(); + + TransactionContext txContext = getTransactionContext(); + + DeliverResponse[] deliver = orderer.sendDeliver(createSeekInfoEnvelope(txContext, seekInfo)); + + if (deliver.length < 1) { + logger.warn(format("Genesis block for channel %s fetch bad deliver missing status block only got blocks:%d", name, deliver.length)); + //odd so lets try again.... + statusRC = 404; + + } else { + + DeliverResponse status = deliver[0]; + statusRC = status.getStatusValue(); + + if (statusRC == 404 || statusRC == 503) { //404 - block not found. 503 - service not available usually means kafka is not ready but starting. + logger.warn(format("Bad deliver expected status 200 got %d, Channel %s", status.getStatusValue(), name)); + // keep trying... else + statusRC = 404; + + } else if (statusRC != 200) { // Assume for anything other than 200 we have a non retryable situation + throw new TransactionException(format("Bad newest block expected status 200 got %d, Channel %s", status.getStatusValue(), name)); + } else { + if (deliver.length < 2) { + throw new TransactionException(format("Newest block for channel %s fetch bad deliver missing genesis block only got %d:", name, deliver.length)); + } else { + + deliverResponses.addAll(Arrays.asList(deliver)); + } + } + + } + + // Not 200 so sleep to try again + + if (200 != statusRC) { + long duration = System.currentTimeMillis() - start; + + if (duration > config.getGenesisBlockWaitTime()) { + throw new TransactionException(format("Getting block time exceeded %s seconds for channel %s", Long.toString(TimeUnit.MILLISECONDS.toSeconds(duration)), name)); + } + try { + Thread.sleep(ORDERER_RETRY_WAIT_TIME); //try again + } catch (InterruptedException e) { + TransactionException te = new TransactionException("seekBlock thread Sleep", e); + logger.warn(te.getMessage(), te); + } + } + + } while (statusRC != 200); + + } catch (TransactionException e) { + logger.error(e.getMessage(), e); + throw e; + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new TransactionException(e); + } + + return statusRC; + + } + + private Block getLatestBlock(Orderer orderer) throws TransactionException { + + logger.debug(format("getConfigurationBlock for channel %s", name)); + + SeekPosition seekPosition = SeekPosition.newBuilder() + .setNewest(Ab.SeekNewest.getDefaultInstance()) + .build(); + + SeekInfo seekInfo = SeekInfo.newBuilder() + .setStart(seekPosition) + .setStop(seekPosition) + .setBehavior(SeekInfo.SeekBehavior.BLOCK_UNTIL_READY) + .build(); + + ArrayList deliverResponses = new ArrayList<>(); + + seekBlock(seekInfo, deliverResponses, orderer); + + DeliverResponse blockresp = deliverResponses.get(1); + + Block latestBlock = blockresp.getBlock(); + + if (latestBlock == null) { + throw new TransactionException(format("newest block for channel %s fetch bad deliver returned null:", name)); + } + + logger.trace(format("Received latest block for channel %s, block no:%d", name, latestBlock.getHeader().getNumber())); + return latestBlock; + } + + public Collection getOrderers() { + return Collections.unmodifiableCollection(orderers); + } + + /** + * Send instantiate request to the channel. Chaincode is created and initialized. + * + * @param instantiateProposalRequest send instantiate chaincode proposal request. + * @return Collections of proposal responses + * @throws InvalidArgumentException + * @throws ProposalException + */ + + public Collection sendInstantiationProposal(InstantiateProposalRequest instantiateProposalRequest) throws InvalidArgumentException, ProposalException { + + return sendInstantiationProposal(instantiateProposalRequest, getChaincodePeers()); + } + + /** + * Send instantiate request to the channel. Chaincode is created and initialized. + * + * @param instantiateProposalRequest + * @param peers + * @return responses from peers. + * @throws InvalidArgumentException + * @throws ProposalException + */ + public Collection sendInstantiationProposal(InstantiateProposalRequest instantiateProposalRequest, + Collection peers) throws InvalidArgumentException, ProposalException { + checkChannelState(); + if (null == instantiateProposalRequest) { + throw new InvalidArgumentException("InstantiateProposalRequest is null"); + } + + instantiateProposalRequest.setSubmitted(); + + checkPeers(peers); + + try { + TransactionContext transactionContext = getTransactionContext(instantiateProposalRequest.getUserContext()); + transactionContext.setProposalWaitTime(instantiateProposalRequest.getProposalWaitTime()); + InstantiateProposalBuilder instantiateProposalbuilder = InstantiateProposalBuilder.newBuilder(); + instantiateProposalbuilder.context(transactionContext); + instantiateProposalbuilder.argss(instantiateProposalRequest.getArgs()); + instantiateProposalbuilder.chaincodeName(instantiateProposalRequest.getChaincodeName()); + instantiateProposalbuilder.chaincodePath(instantiateProposalRequest.getChaincodePath()); + instantiateProposalbuilder.chaincodeVersion(instantiateProposalRequest.getChaincodeVersion()); + instantiateProposalbuilder.chaincodEndorsementPolicy(instantiateProposalRequest.getChaincodeEndorsementPolicy()); + instantiateProposalbuilder.setTransientMap(instantiateProposalRequest.getTransientMap()); + + FabricProposal.Proposal instantiateProposal = instantiateProposalbuilder.build(); + SignedProposal signedProposal = getSignedProposal(transactionContext, instantiateProposal); + + return sendProposalToPeers(peers, signedProposal, transactionContext); + } catch (Exception e) { + throw new ProposalException(e); + } + } + + private TransactionContext getTransactionContext() throws InvalidArgumentException { + return getTransactionContext(client.getUserContext()); + } + + private TransactionContext getTransactionContext(User userContext) throws InvalidArgumentException { + userContext = userContext != null ? userContext : client.getUserContext(); + + userContextCheck(userContext); + + return new TransactionContext(this, userContext, client.getCryptoSuite()); + } + + /** + * Send install chaincode request proposal to all the channels on the peer. + * + * @param installProposalRequest + * @return + * @throws ProposalException + * @throws InvalidArgumentException + */ + + Collection sendInstallProposal(InstallProposalRequest installProposalRequest) + throws ProposalException, InvalidArgumentException { + return sendInstallProposal(installProposalRequest, getChaincodePeers()); + + } + + /** + * Send install chaincode request proposal to the channel. + * + * @param installProposalRequest + * @param peers + * @return + * @throws ProposalException + * @throws InvalidArgumentException + */ + + Collection sendInstallProposal(InstallProposalRequest installProposalRequest, Collection peers) + throws ProposalException, InvalidArgumentException { + + checkChannelState(); + checkPeers(peers); + if (null == installProposalRequest) { + throw new InvalidArgumentException("InstallProposalRequest is null"); + } + + try { + TransactionContext transactionContext = getTransactionContext(installProposalRequest.getUserContext()); + transactionContext.verify(false); // Install will have no signing cause it's not really targeted to a channel. + transactionContext.setProposalWaitTime(installProposalRequest.getProposalWaitTime()); + InstallProposalBuilder installProposalbuilder = InstallProposalBuilder.newBuilder(); + installProposalbuilder.context(transactionContext); + installProposalbuilder.setChaincodeLanguage(installProposalRequest.getChaincodeLanguage()); + installProposalbuilder.chaincodeName(installProposalRequest.getChaincodeName()); + installProposalbuilder.chaincodePath(installProposalRequest.getChaincodePath()); + installProposalbuilder.chaincodeVersion(installProposalRequest.getChaincodeVersion()); + installProposalbuilder.setChaincodeSource(installProposalRequest.getChaincodeSourceLocation()); + installProposalbuilder.setChaincodeInputStream(installProposalRequest.getChaincodeInputStream()); + + FabricProposal.Proposal deploymentProposal = installProposalbuilder.build(); + SignedProposal signedProposal = getSignedProposal(transactionContext, deploymentProposal); + + return sendProposalToPeers(peers, signedProposal, transactionContext); + } catch (Exception e) { + throw new ProposalException(e); + } + + } + + /** + * Send Upgrade proposal proposal to upgrade chaincode to a new version. + * + * @param upgradeProposalRequest + * @return Collection of proposal responses. + * @throws ProposalException + * @throws InvalidArgumentException + */ + + public Collection sendUpgradeProposal(UpgradeProposalRequest upgradeProposalRequest) throws ProposalException, InvalidArgumentException { + + return sendUpgradeProposal(upgradeProposalRequest, getChaincodePeers()); + + } + + /** + * Send Upgrade proposal proposal to upgrade chaincode to a new version. + * + * @param upgradeProposalRequest + * @param peers the specific peers to send to. + * @return Collection of proposal responses. + * @throws ProposalException + * @throws InvalidArgumentException + */ + + public Collection sendUpgradeProposal(UpgradeProposalRequest upgradeProposalRequest, Collection peers) + throws InvalidArgumentException, ProposalException { + + checkChannelState(); + checkPeers(peers); + + if (null == upgradeProposalRequest) { + throw new InvalidArgumentException("Upgradeproposal is null"); + } + + try { + TransactionContext transactionContext = getTransactionContext(upgradeProposalRequest.getUserContext()); + //transactionContext.verify(false); // Install will have no signing cause it's not really targeted to a channel. + transactionContext.setProposalWaitTime(upgradeProposalRequest.getProposalWaitTime()); + UpgradeProposalBuilder upgradeProposalBuilder = UpgradeProposalBuilder.newBuilder(); + upgradeProposalBuilder.context(transactionContext); + upgradeProposalBuilder.argss(upgradeProposalRequest.getArgs()); + upgradeProposalBuilder.chaincodeName(upgradeProposalRequest.getChaincodeName()); + upgradeProposalBuilder.chaincodePath(upgradeProposalRequest.getChaincodePath()); + upgradeProposalBuilder.chaincodeVersion(upgradeProposalRequest.getChaincodeVersion()); + upgradeProposalBuilder.chaincodEndorsementPolicy(upgradeProposalRequest.getChaincodeEndorsementPolicy()); + + SignedProposal signedProposal = getSignedProposal(transactionContext, upgradeProposalBuilder.build()); + + return sendProposalToPeers(peers, signedProposal, transactionContext); + } catch (Exception e) { + throw new ProposalException(e); + } + } + + private SignedProposal getSignedProposal(TransactionContext transactionContext, FabricProposal.Proposal proposal) throws CryptoException { + + return SignedProposal.newBuilder() + .setProposalBytes(proposal.toByteString()) + .setSignature(transactionContext.signByteString(proposal.toByteArray())) + .build(); + + } + + /** + * query this channel for a Block by the block hash. + * The request is sent to a random peer in the channel. + * + * @param blockHash the hash of the Block in the chain + * @return the {@link BlockInfo} with the given block Hash + * @throws InvalidArgumentException + * @throws ProposalException + */ + public BlockInfo queryBlockByHash(byte[] blockHash) throws InvalidArgumentException, ProposalException { + + checkChannelState(); + + if (blockHash == null) { + throw new InvalidArgumentException("blockHash parameter is null."); + } + return queryBlockByHash(getRandomLedgerQueryPeer(), blockHash); + } + + private void checkChannelState() throws InvalidArgumentException { + if (shutdown) { + throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); + } + + if (!initialized) { + throw new InvalidArgumentException(format("Channel %s has not been initialized.", name)); + } + + userContextCheck(client.getUserContext()); + + } + + /** + * Query a peer in this channel for a Block by the block hash. + * + * @param peer the Peer to query. + * @param blockHash the hash of the Block in the chain. + * @return the {@link BlockInfo} with the given block Hash + * @throws InvalidArgumentException if the channel is shutdown or any of the arguments are not valid. + * @throws ProposalException if an error occurred processing the query. + */ + public BlockInfo queryBlockByHash(Peer peer, byte[] blockHash) throws InvalidArgumentException, ProposalException { + + checkChannelState(); + checkPeer(peer); + + if (blockHash == null) { + throw new InvalidArgumentException("blockHash parameter is null."); + } + + ProposalResponse proposalResponse; + BlockInfo responseBlock; + try { + logger.debug("queryBlockByHash with hash : " + Hex.encodeHexString(blockHash) + "\n to peer " + peer.getName() + " on channel " + name); + QuerySCCRequest querySCCRequest = new QuerySCCRequest(client.getUserContext()); + querySCCRequest.setFcn(QuerySCCRequest.GETBLOCKBYHASH); + querySCCRequest.setArgs(name); + querySCCRequest.setArgBytes(new byte[][] {blockHash}); + + Collection proposalResponses = sendProposal(querySCCRequest, Collections.singletonList(peer)); + proposalResponse = proposalResponses.iterator().next(); + + if (proposalResponse.getStatus().getStatus() != 200) { + throw new PeerException(format("Unable to query block by hash %s %n.... for channel %s from peer %s \n with message %s", + Hex.encodeHexString(blockHash), + name, + peer.getName(), + proposalResponse.getMessage())); + } + responseBlock = new BlockInfo(Block.parseFrom(proposalResponse.getProposalResponse().getResponse().getPayload())); + } catch (Exception e) { + String emsg = format("queryBlockByHash hash: %s peer %s channel %s error: %s", + Hex.encodeHexString(blockHash), peer.getName(), name, e.getMessage()); + logger.error(emsg, e); + throw new ProposalException(emsg, e); + } + + return responseBlock; + } + + /** + * query this channel for a Block by the blockNumber. + * The request is sent to a random peer in the channel. + * + * @param blockNumber index of the Block in the chain + * @return the {@link BlockInfo} with the given blockNumber + * @throws InvalidArgumentException + * @throws ProposalException + */ + public BlockInfo queryBlockByNumber(long blockNumber) throws InvalidArgumentException, ProposalException { + return queryBlockByNumber(getRandomLedgerQueryPeer(), blockNumber); + } + + private Peer getRandomLedgerQueryPeer() throws InvalidArgumentException { + final ArrayList ledgerQueryPeers = new ArrayList<>(new HashSet<>(getLedgerQueryPeers())); //copy to avoid unlikely changes + if (ledgerQueryPeers.isEmpty()) { + throw new InvalidArgumentException("Channel " + name + " does not have any ledger querying peers associated with it."); + } + + return ledgerQueryPeers.get(RANDOM.nextInt(ledgerQueryPeers.size())); + + } + + private Orderer getRandomOrderer() throws InvalidArgumentException { + + final ArrayList randPicks = new ArrayList<>(new HashSet<>(getOrderers())); //copy to avoid unlikely changes + + if (randPicks.isEmpty()) { + throw new InvalidArgumentException("Channel " + name + " does not have any orderers associated with it."); + } + + return randPicks.get(RANDOM.nextInt(randPicks.size())); + + } + + private void checkPeer(Peer peer) throws InvalidArgumentException { + + if (peer == null) { + throw new InvalidArgumentException("Peer value is null."); + } + if (isSystemChannel()) { + return; // System owns no peers + } + if (!getPeers().contains(peer)) { + throw new InvalidArgumentException("Channel " + name + " does not have peer " + peer.getName()); + } + if (peer.getChannel() != this) { + throw new InvalidArgumentException("Peer " + peer.getName() + " not set for channel " + name); + } + + } + + private void checkOrderer(Orderer orderer) throws InvalidArgumentException { + + if (orderer == null) { + throw new InvalidArgumentException("Orderer value is null."); + } + if (isSystemChannel()) { + return; // System owns no Orderers + } + if (!getOrderers().contains(orderer)) { + throw new InvalidArgumentException("Channel " + name + " does not have orderer " + orderer.getName()); + } + if (orderer.getChannel() != this) { + throw new InvalidArgumentException("Orderer " + orderer.getName() + " not set for channel " + name); + } + + } + + private void checkPeers(Collection peers) throws InvalidArgumentException { + + if (peers == null) { + throw new InvalidArgumentException("Collection of peers is null."); + } + + if (peers.isEmpty()) { + throw new InvalidArgumentException("Collection of peers is empty."); + } + + for (Peer peer : peers) { + checkPeer(peer); + } + } + + /** + * query a peer in this channel for a Block by the blockNumber + * + * @param peer the peer to send the request to + * @param blockNumber index of the Block in the chain + * @return the {@link BlockInfo} with the given blockNumber + * @throws InvalidArgumentException + * @throws ProposalException + */ + public BlockInfo queryBlockByNumber(Peer peer, long blockNumber) throws InvalidArgumentException, ProposalException { + + checkChannelState(); + checkPeer(peer); + + ProposalResponse proposalResponse; + BlockInfo responseBlock; + try { + logger.debug("queryBlockByNumber with blockNumber " + blockNumber + " to peer " + peer.getName() + " on channel " + name); + QuerySCCRequest querySCCRequest = new QuerySCCRequest(client.getUserContext()); + querySCCRequest.setFcn(QuerySCCRequest.GETBLOCKBYNUMBER); + querySCCRequest.setArgs(name, Long.toUnsignedString(blockNumber)); + + Collection proposalResponses = sendProposal(querySCCRequest, Collections.singletonList(peer)); + proposalResponse = proposalResponses.iterator().next(); + + if (proposalResponse.getStatus().getStatus() != 200) { + throw new PeerException(format("Unable to query block by number %d for channel %s from peer %s with message %s", + blockNumber, + name, + peer.getName(), + proposalResponse.getMessage())); + } + responseBlock = new BlockInfo(Block.parseFrom(proposalResponse.getProposalResponse().getResponse().getPayload())); + } catch (Exception e) { + String emsg = format("queryBlockByNumber blockNumber %d peer %s channel %s error %s", + blockNumber, + peer.getName(), + name, + e.getMessage()); + logger.error(emsg, e); + throw new ProposalException(emsg, e); + } + + return responseBlock; + } + + /** + * query this channel for a Block by a TransactionID contained in the block + * The request is sent to a random peer in the channel + * + * @param txID the transactionID to query on + * @return the {@link BlockInfo} for the Block containing the transaction + * @throws InvalidArgumentException + * @throws ProposalException + */ + public BlockInfo queryBlockByTransactionID(String txID) throws InvalidArgumentException, ProposalException { + + return queryBlockByTransactionID(getRandomLedgerQueryPeer(), txID); + } + + /** + * query a peer in this channel for a Block by a TransactionID contained in the block + * + * @param peer the peer to send the request to + * @param txID the transactionID to query on + * @return the {@link BlockInfo} for the Block containing the transaction + * @throws InvalidArgumentException + * @throws ProposalException + */ + public BlockInfo queryBlockByTransactionID(Peer peer, String txID) throws InvalidArgumentException, ProposalException { + + checkChannelState(); + checkPeer(peer); + + if (txID == null) { + throw new InvalidArgumentException("TxID parameter is null."); + } + + ProposalResponse proposalResponse; + BlockInfo responseBlock; + try { + logger.debug("queryBlockByTransactionID with txID " + txID + " \n to peer" + peer.getName() + " on channel " + name); + QuerySCCRequest querySCCRequest = new QuerySCCRequest(client.getUserContext()); + querySCCRequest.setFcn(QuerySCCRequest.GETBLOCKBYTXID); + querySCCRequest.setArgs(name, txID); + + Collection proposalResponses = sendProposal(querySCCRequest, Collections.singletonList(peer)); + proposalResponse = proposalResponses.iterator().next(); + + if (proposalResponse.getStatus().getStatus() != 200) { + throw new PeerException(format("Unable to query block by TxID %s%n for channel %s from peer %s with message %s", + txID, + name, + peer.getName(), + proposalResponse.getMessage())); + } + responseBlock = new BlockInfo(Block.parseFrom(proposalResponse.getProposalResponse().getResponse().getPayload())); + } catch (Exception e) { + String emsg = format("QueryBlockByTransactionID TxID %s%n peer %s channel %s error %s", + txID, + peer.getName(), + name, + e.getMessage()); + logger.error(emsg, e); + throw new ProposalException(emsg, e); + } + + return responseBlock; + } + + /** + * query this channel for chain information. + * The request is sent to a random peer in the channel + * + * @return a {@link BlockchainInfo} object containing the chain info requested + * @throws InvalidArgumentException + * @throws ProposalException + */ + public BlockchainInfo queryBlockchainInfo() throws ProposalException, InvalidArgumentException { + + return queryBlockchainInfo(getRandomLedgerQueryPeer()); + } + + /** + * query for chain information + * + * @param peer The peer to send the request to + * @return a {@link BlockchainInfo} object containing the chain info requested + * @throws InvalidArgumentException + * @throws ProposalException + */ + public BlockchainInfo queryBlockchainInfo(Peer peer) throws ProposalException, InvalidArgumentException { + + checkChannelState(); + checkPeer(peer); + + BlockchainInfo response; + try { + logger.debug("queryBlockchainInfo to peer " + peer.getName() + " on channel " + name); + QuerySCCRequest querySCCRequest = new QuerySCCRequest(client.getUserContext()); + querySCCRequest.setFcn(QuerySCCRequest.GETCHAININFO); + querySCCRequest.setArgs(name); + + Collection proposalResponses = sendProposal(querySCCRequest, Collections.singletonList(peer)); + ProposalResponse proposalResponse = proposalResponses.iterator().next(); + + if (proposalResponse.getStatus().getStatus() != 200) { + throw new PeerException(format("Unable to query block channel info for channel %s from peer %s with message %s", + name, + peer.getName(), + proposalResponse.getMessage())); + } + response = new BlockchainInfo(Ledger.BlockchainInfo.parseFrom(proposalResponse.getProposalResponse().getResponse().getPayload())); + } catch (Exception e) { + String emsg = format("queryBlockchainInfo peer %s channel %s error %s", + peer.getName(), + name, + e.getMessage()); + logger.error(emsg, e); + throw new ProposalException(emsg, e); + } + + return response; + } + + /** + * Query this channel for a Fabric Transaction given its transactionID. + * The request is sent to a random peer in the channel. + * + * @param txID the ID of the transaction + * @return a {@link TransactionInfo} + * @throws ProposalException + * @throws InvalidArgumentException + */ + public TransactionInfo queryTransactionByID(String txID) throws ProposalException, InvalidArgumentException { + + return queryTransactionByID(getRandomLedgerQueryPeer(), txID); + } + + /** + * Query for a Fabric Transaction given its transactionID + * + * @param txID the ID of the transaction + * @param peer the peer to send the request to + * @return a {@link TransactionInfo} + * @throws ProposalException + * @throws InvalidArgumentException + */ + public TransactionInfo queryTransactionByID(Peer peer, String txID) throws ProposalException, InvalidArgumentException { + + checkChannelState(); + checkPeer(peer); + + if (txID == null) { + throw new InvalidArgumentException("TxID parameter is null."); + } + + TransactionInfo transactionInfo; + try { + logger.debug("queryTransactionByID with txID " + txID + "\n from peer " + peer.getName() + " on channel " + name); + QuerySCCRequest querySCCRequest = new QuerySCCRequest(client.getUserContext()); + querySCCRequest.setFcn(QuerySCCRequest.GETTRANSACTIONBYID); + querySCCRequest.setArgs(name, txID); + + Collection proposalResponses = sendProposal(querySCCRequest, Collections.singletonList(peer)); + ProposalResponse proposalResponse = proposalResponses.iterator().next(); + + if (proposalResponse.getStatus().getStatus() != 200) { + throw new PeerException(format("Unable to query transaction info for ID %s%n for channel %s from peer %s with message %s", + txID, + name, + peer.getName(), + proposalResponse.getMessage())); + } + transactionInfo = new TransactionInfo(txID, ProcessedTransaction.parseFrom(proposalResponse.getProposalResponse().getResponse().getPayload())); + } catch (Exception e) { + String emsg = format("queryTransactionByID TxID %s%n peer %s channel %s error %s", + txID, + peer.getName(), + name, + e.getMessage()); + logger.error(emsg, e); + throw new ProposalException(emsg, e); + } + + return transactionInfo; + } + + ///////////////////////////////////////////////////////// + // transactions order + + Set queryChannels(Peer peer) throws InvalidArgumentException, ProposalException { + + checkPeer(peer); + + if (!isSystemChannel()) { + throw new InvalidArgumentException("queryChannels should only be invoked on system channel."); + } + + try { + + TransactionContext context = getTransactionContext(); + + FabricProposal.Proposal q = QueryPeerChannelsBuilder.newBuilder().context(context).build(); + + SignedProposal qProposal = getSignedProposal(context, q); + Collection proposalResponses = sendProposalToPeers(Collections.singletonList(peer), qProposal, context); + + if (null == proposalResponses) { + throw new ProposalException(format("Peer %s channel query return with null for responses", peer.getName())); + } + + if (proposalResponses.size() != 1) { + + throw new ProposalException(format("Peer %s channel query expected one response but got back %d responses ", peer.getName(), proposalResponses.size())); + } + + ProposalResponse proposalResponse = proposalResponses.iterator().next(); + if (proposalResponse.getStatus() != ChaincodeResponse.Status.SUCCESS) { + throw new ProposalException(format("Failed exception message is %s, status is %d", proposalResponse.getMessage(), proposalResponse.getStatus().getStatus())); + + } + + FabricProposalResponse.ProposalResponse fabricResponse = proposalResponse.getProposalResponse(); + if (null == fabricResponse) { + throw new ProposalException(format("Peer %s channel query return with empty fabric response", peer.getName())); + + } + + final Response fabricResponseResponse = fabricResponse.getResponse(); + + if (null == fabricResponseResponse) { //not likely but check it. + throw new ProposalException(format("Peer %s channel query return with empty fabricResponseResponse", peer.getName())); + } + + if (200 != fabricResponseResponse.getStatus()) { + throw new ProposalException(format("Peer %s channel query expected 200, actual returned was: %d. " + + fabricResponseResponse.getMessage(), peer.getName(), fabricResponseResponse.getStatus())); + + } + + ChannelQueryResponse qr = ChannelQueryResponse.parseFrom(fabricResponseResponse.getPayload()); + + Set ret = new HashSet<>(qr.getChannelsCount()); + + for (Query.ChannelInfo x : qr.getChannelsList()) { + ret.add(x.getChannelId()); + + } + return ret; + + } catch (ProposalException e) { + throw e; + } catch (Exception e) { + throw new ProposalException(format("Query for peer %s channels failed. " + e.getMessage(), name), e); + + } + + } + + List queryInstalledChaincodes(Peer peer) throws InvalidArgumentException, ProposalException { + + checkPeer(peer); + + if (!isSystemChannel()) { + throw new InvalidArgumentException("queryInstalledChaincodes should only be invoked on system channel."); + } + + try { + + TransactionContext context = getTransactionContext(); + + FabricProposal.Proposal q = QueryInstalledChaincodesBuilder.newBuilder().context(context).build(); + + SignedProposal qProposal = getSignedProposal(context, q); + Collection proposalResponses = sendProposalToPeers(Collections.singletonList(peer), qProposal, context); + + if (null == proposalResponses) { + throw new ProposalException(format("Peer %s channel query return with null for responses", peer.getName())); + } + + if (proposalResponses.size() != 1) { + + throw new ProposalException(format("Peer %s channel query expected one response but got back %d responses ", peer.getName(), proposalResponses.size())); + } + + ProposalResponse proposalResponse = proposalResponses.iterator().next(); + + FabricProposalResponse.ProposalResponse fabricResponse = proposalResponse.getProposalResponse(); + if (null == fabricResponse) { + throw new ProposalException(format("Peer %s channel query return with empty fabric response", peer.getName())); + + } + + final Response fabricResponseResponse = fabricResponse.getResponse(); + + if (null == fabricResponseResponse) { //not likely but check it. + throw new ProposalException(format("Peer %s channel query return with empty fabricResponseResponse", peer.getName())); + } + + if (200 != fabricResponseResponse.getStatus()) { + throw new ProposalException(format("Peer %s channel query expected 200, actual returned was: %d. " + + fabricResponseResponse.getMessage(), peer.getName(), fabricResponseResponse.getStatus())); + + } + + ChaincodeQueryResponse chaincodeQueryResponse = ChaincodeQueryResponse.parseFrom(fabricResponseResponse.getPayload()); + + return chaincodeQueryResponse.getChaincodesList(); + + } catch (ProposalException e) { + throw e; + } catch (Exception e) { + throw new ProposalException(format("Query for peer %s channels failed. " + e.getMessage(), name), e); + + } + + } + + /** + * Query peer for chaincode that has been instantiated + * + * @param peer The peer to query. + * @return A list of ChaincodeInfo @see {@link ChaincodeInfo} + * @throws InvalidArgumentException + * @throws ProposalException + */ + + public List queryInstantiatedChaincodes(Peer peer) throws InvalidArgumentException, ProposalException { + + checkChannelState(); + checkPeer(peer); + + try { + + TransactionContext context = getTransactionContext(); + + FabricProposal.Proposal q = QueryInstantiatedChaincodesBuilder.newBuilder().context(context).build(); + + SignedProposal qProposal = getSignedProposal(context, q); + Collection proposalResponses = sendProposalToPeers(Collections.singletonList(peer), qProposal, context); + + if (null == proposalResponses) { + throw new ProposalException(format("Peer %s channel query return with null for responses", peer.getName())); + } + + if (proposalResponses.size() != 1) { + + throw new ProposalException(format("Peer %s channel query expected one response but got back %d responses ", peer.getName(), proposalResponses.size())); + } + + ProposalResponse proposalResponse = proposalResponses.iterator().next(); + + FabricProposalResponse.ProposalResponse fabricResponse = proposalResponse.getProposalResponse(); + if (null == fabricResponse) { + throw new ProposalException(format("Peer %s channel query return with empty fabric response", peer.getName())); + + } + + final Response fabricResponseResponse = fabricResponse.getResponse(); + + if (null == fabricResponseResponse) { //not likely but check it. + throw new ProposalException(format("Peer %s channel query return with empty fabricResponseResponse", peer.getName())); + } + + if (200 != fabricResponseResponse.getStatus()) { + throw new ProposalException(format("Peer %s channel query expected 200, actual returned was: %d. " + + fabricResponseResponse.getMessage(), peer.getName(), fabricResponseResponse.getStatus())); + + } + + ChaincodeQueryResponse chaincodeQueryResponse = ChaincodeQueryResponse.parseFrom(fabricResponseResponse.getPayload()); + + return chaincodeQueryResponse.getChaincodesList(); + + } catch (ProposalException e) { + throw e; + } catch (Exception e) { + throw new ProposalException(format("Query for peer %s channels failed. " + e.getMessage(), name), e); + + } + + } + + /** + * Send a transaction proposal. + * + * @param transactionProposalRequest The transaction proposal to be sent to all the peers. + * @return responses from peers. + * @throws InvalidArgumentException + * @throws ProposalException + */ + public Collection sendTransactionProposal(TransactionProposalRequest transactionProposalRequest) throws ProposalException, InvalidArgumentException { + + return sendProposal(transactionProposalRequest, getEndorsingPeers()); + } + + /** + * Send a transaction proposal to specific peers. + * + * @param transactionProposalRequest The transaction proposal to be sent to the peers. + * @param peers + * @return responses from peers. + * @throws InvalidArgumentException + * @throws ProposalException + */ + public Collection sendTransactionProposal(TransactionProposalRequest transactionProposalRequest, Collection peers) throws ProposalException, InvalidArgumentException { + + return sendProposal(transactionProposalRequest, peers); + } + + /** + * Send Query proposal + * + * @param queryByChaincodeRequest + * @return Collection proposal responses. + * @throws InvalidArgumentException + * @throws ProposalException + */ + + public Collection queryByChaincode(QueryByChaincodeRequest queryByChaincodeRequest) throws InvalidArgumentException, ProposalException { + return queryByChaincode(queryByChaincodeRequest, getChaincodeQueryPeers()); + } + + /** + * Send Query proposal + * + * @param queryByChaincodeRequest + * @param peers + * @return responses from peers. + * @throws InvalidArgumentException + * @throws ProposalException + */ + + public Collection queryByChaincode(QueryByChaincodeRequest queryByChaincodeRequest, Collection peers) throws InvalidArgumentException, ProposalException { + return sendProposal(queryByChaincodeRequest, peers); + } + //////////////// Channel Block monitoring ////////////////////////////////// + + private Collection sendProposal(TransactionRequest proposalRequest, Collection peers) throws InvalidArgumentException, ProposalException { + + checkChannelState(); + checkPeers(peers); + + if (null == proposalRequest) { + throw new InvalidArgumentException("sendProposal queryProposalRequest is null"); + } + + proposalRequest.setSubmitted(); + + try { + TransactionContext transactionContext = getTransactionContext(proposalRequest.getUserContext()); + transactionContext.verify(proposalRequest.doVerify()); + transactionContext.setProposalWaitTime(proposalRequest.getProposalWaitTime()); + + // Protobuf message builder + ProposalBuilder proposalBuilder = ProposalBuilder.newBuilder(); + proposalBuilder.context(transactionContext); + proposalBuilder.request(proposalRequest); + + SignedProposal invokeProposal = getSignedProposal(transactionContext, proposalBuilder.build()); + return sendProposalToPeers(peers, invokeProposal, transactionContext); + } catch (ProposalException e) { + throw e; + + } catch (Exception e) { + ProposalException exp = new ProposalException(e); + logger.error(exp.getMessage(), exp); + throw exp; + } + } + + private Collection sendProposalToPeers(Collection peers, + SignedProposal signedProposal, + TransactionContext transactionContext) throws InvalidArgumentException, ProposalException { + checkPeers(peers); + + class Pair { + private final Peer peer; + private final Future future; + + private Pair(Peer peer, Future future) { + this.peer = peer; + this.future = future; + } + } + List peerFuturePairs = new ArrayList<>(); + for (Peer peer : peers) { + logger.debug(format("Channel %s send proposal to peer %s at url %s", + name, peer.getName(), peer.getUrl())); + + if (null != diagnosticFileDumper) { + logger.trace(format("Sending to channel %s, peer: %s, proposal: %s", name, peer.getName(), + diagnosticFileDumper.createDiagnosticProtobufFile(signedProposal.toByteArray()))); + + } + + Future proposalResponseListenableFuture; + try { + proposalResponseListenableFuture = peer.sendProposalAsync(signedProposal); + } catch (Exception e) { + proposalResponseListenableFuture = new CompletableFuture<>(); + ((CompletableFuture) proposalResponseListenableFuture).completeExceptionally(e); + + } + peerFuturePairs.add(new Pair(peer, proposalResponseListenableFuture)); + + } + + Collection proposalResponses = new ArrayList<>(); + for (Pair peerFuturePair : peerFuturePairs) { + + FabricProposalResponse.ProposalResponse fabricResponse = null; + String message; + int status = 500; + final String peerName = peerFuturePair.peer.getName(); + try { + fabricResponse = peerFuturePair.future.get(transactionContext.getProposalWaitTime(), TimeUnit.MILLISECONDS); + message = fabricResponse.getResponse().getMessage(); + status = fabricResponse.getResponse().getStatus(); + logger.debug(format("Channel %s got back from peer %s status: %d, message: %s", + name, peerName, status, message)); + if (null != diagnosticFileDumper) { + logger.trace(format("Got back from channel %s, peer: %s, proposal response: %s", name, peerName, + diagnosticFileDumper.createDiagnosticProtobufFile(fabricResponse.toByteArray()))); + + } + } catch (InterruptedException e) { + message = "Sending proposal to " + peerName + " failed because of interruption"; + logger.error(message, e); + } catch (TimeoutException e) { + message = format("Sending proposal to " + peerName + " failed because of timeout(%d milliseconds) expiration", + transactionContext.getProposalWaitTime()); + logger.error(message, e); + } catch (ExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof Error) { + String emsg = "Sending proposal to " + peerName + " failed because of " + cause.getMessage(); + logger.error(emsg, new Exception(cause)); //wrapped in exception to get full stack trace. + throw (Error) cause; + } else { + if (cause instanceof StatusRuntimeException) { + message = format("Sending proposal to " + peerName + " failed because of: gRPC failure=%s", + ((StatusRuntimeException) cause).getStatus()); + } else { + message = format("Sending proposal to " + peerName + " failed because of: %s", cause.getMessage()); + } + logger.error(message, new Exception(cause)); //wrapped in exception to get full stack trace. + } + } + + ProposalResponse proposalResponse = new ProposalResponse(transactionContext.getTxID(), + transactionContext.getChannelID(), status, message); + proposalResponse.setProposalResponse(fabricResponse); + proposalResponse.setProposal(signedProposal); + proposalResponse.setPeer(peerFuturePair.peer); + + if (fabricResponse != null && transactionContext.getVerify()) { + proposalResponse.verify(client.getCryptoSuite()); + } + + proposalResponses.add(proposalResponse); + } + + return proposalResponses; + } + + /** + * Send transaction to one of the orderers on the channel using a specific user context. + * + * @param proposalResponses The proposal responses to be sent to the orderer. + * @param userContext The usercontext used for signing transaction. + * @return a future allowing access to the result of the transaction invocation once complete. + */ + public CompletableFuture sendTransaction(Collection proposalResponses, User userContext) { + + return sendTransaction(proposalResponses, orderers, userContext); + + } + + /** + * Send transaction to one of the orderers on the channel using the usercontext set on the client. + * + * @param proposalResponses . + * @return a future allowing access to the result of the transaction invocation once complete. + */ + public CompletableFuture sendTransaction(Collection proposalResponses) { + + return sendTransaction(proposalResponses, orderers); + + } + + /** + * Send transaction to one of the specified orderers using the usercontext set on the client.. + * + * @param proposalResponses The proposal responses to be sent to the orderer + * @param orderers The orderers to send the transaction to. + * @return a future allowing access to the result of the transaction invocation once complete. + */ + + public CompletableFuture sendTransaction(Collection proposalResponses, Collection orderers) { + + return sendTransaction(proposalResponses, orderers, client.getUserContext()); + } + + /** + * Send transaction to one of a specified set of orderers with the specified user context. + * IF there are no event hubs or eventing peers this future returns immediately completed + * indicating that orderer has accepted the transaction only. + * + * @param proposalResponses + * @param orderers + * @return Future allowing access to the result of the transaction invocation. + */ + + public CompletableFuture sendTransaction(Collection proposalResponses, Collection orderers, User userContext) { + try { + checkChannelState(); + userContextCheck(userContext); + if (null == proposalResponses) { + throw new InvalidArgumentException("sendTransaction proposalResponses was null"); + } + + if (null == orderers) { + throw new InvalidArgumentException("sendTransaction Orderers is null"); + } + + final ArrayList shuffeledOrderers = new ArrayList<>(orderers); + Collections.shuffle(shuffeledOrderers); + + if (shuffeledOrderers.isEmpty()) { + throw new InvalidArgumentException("sendTransaction Orderers to send to is empty."); + } + + if (config.getProposalConsistencyValidation()) { + HashSet invalid = new HashSet<>(); + int consistencyGroups = SDKUtils.getProposalConsistencySets(proposalResponses, invalid).size(); + + if (consistencyGroups != 1 || !invalid.isEmpty()) { + throw new IllegalArgumentException(format( + "The proposal responses have %d inconsistent groups with %d that are invalid." + + " Expected all to be consistent and none to be invalid.", + consistencyGroups, invalid.size())); + + } + + } + + List ed = new LinkedList<>(); + FabricProposal.Proposal proposal = null; + ByteString proposalResponsePayload = null; + String proposalTransactionID = null; + + for (ProposalResponse sdkProposalResponse : proposalResponses) { + ed.add(sdkProposalResponse.getProposalResponse().getEndorsement()); + if (proposal == null) { + proposal = sdkProposalResponse.getProposal(); + proposalTransactionID = sdkProposalResponse.getTransactionID(); + proposalResponsePayload = sdkProposalResponse.getProposalResponse().getPayload(); + + } + } + + TransactionBuilder transactionBuilder = TransactionBuilder.newBuilder(); + + Payload transactionPayload = transactionBuilder + .chaincodeProposal(proposal) + .endorsements(ed) + .proposalResponsePayload(proposalResponsePayload).build(); + + Envelope transactionEnvelope = createTransactionEnvelope(transactionPayload, userContext); + + CompletableFuture sret; + if (getEventHubs().isEmpty() && getEventingPeers().isEmpty()) { //If there are no eventhubs to complete the future, complete it + // immediately but give no transaction event + logger.debug(format("Completing transaction id %s immediately no event hubs or peer eventing services found in channel %s.", proposalTransactionID, name)); + sret = new CompletableFuture<>(); + sret.complete(null); + } else { + sret = registerTxListener(proposalTransactionID); + } + + logger.debug(format("Channel %s sending transaction to orderer(s) with TxID %s ", name, proposalTransactionID)); + boolean success = false; + Exception lException = null; // Save last exception to report to user .. others are just logged. + + BroadcastResponse resp = null; + for (Orderer orderer : shuffeledOrderers) { + try { + + if (null != diagnosticFileDumper) { + logger.trace(format("Sending to channel %s, orderer: %s, transaction: %s", name, orderer.getName(), + diagnosticFileDumper.createDiagnosticProtobufFile(transactionEnvelope.toByteArray()))); + } + + resp = orderer.sendTransaction(transactionEnvelope); + lException = null; // no longer last exception .. maybe just failed. + if (resp.getStatus() == Status.SUCCESS) { + success = true; + break; + } + } catch (Exception e) { + String emsg = format("Channel %s unsuccessful sendTransaction to orderer %s (%s)", + name, orderer.getName(), orderer.getUrl()); + if (resp != null) { + + emsg = format("Channel %s unsuccessful sendTransaction to orderer %s (%s). %s", + name, orderer.getName(), orderer.getUrl(), getRespData(resp)); + } + + logger.error(emsg, e); + lException = new Exception(emsg, e); + + } + + } + + if (success) { + logger.debug(format("Channel %s successful sent to Orderer transaction id: %s", + name, proposalTransactionID)); + return sret; + } else { + + String emsg = format("Channel %s failed to place transaction %s on Orderer. Cause: UNSUCCESSFUL. %s", + name, proposalTransactionID, getRespData(resp)); + + unregisterTxListener(proposalTransactionID); + + CompletableFuture ret = new CompletableFuture<>(); + ret.completeExceptionally(lException != null ? new Exception(emsg, lException) : new Exception(emsg)); + return ret; + } + } catch (Exception e) { + + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(e); + return future; + + } + + } + + /** + * Build response details + * + * @param resp + * @return + */ + private String getRespData(BroadcastResponse resp) { + + StringBuilder respdata = new StringBuilder(400); + if (resp != null) { + Status status = resp.getStatus(); + if (null != status) { + respdata.append(status.name()); + respdata.append("-"); + respdata.append(status.getNumber()); + } + + String info = resp.getInfo(); + if (null != info && !info.isEmpty()) { + if (respdata.length() > 0) { + respdata.append(", "); + } + + respdata.append("Additional information: ").append(info); + + } + + } + + return respdata.toString(); + + } + + private Envelope createTransactionEnvelope(Payload transactionPayload, User user) throws CryptoException { + + return Envelope.newBuilder() + .setPayload(transactionPayload.toByteString()) + .setSignature(ByteString.copyFrom(client.getCryptoSuite().sign(user.getEnrollment().getKey(), transactionPayload.toByteArray()))) + .build(); + + } + + byte[] getChannelConfigurationSignature(ChannelConfiguration channelConfiguration, User signer) throws InvalidArgumentException { + + userContextCheck(signer); + + if (null == channelConfiguration) { + + throw new InvalidArgumentException("channelConfiguration is null"); + + } + + try { + + Envelope ccEnvelope = Envelope.parseFrom(channelConfiguration.getChannelConfigurationAsBytes()); + + final Payload ccPayload = Payload.parseFrom(ccEnvelope.getPayload()); + + TransactionContext transactionContext = getTransactionContext(signer); + + final ConfigUpdateEnvelope configUpdateEnv = ConfigUpdateEnvelope.parseFrom(ccPayload.getData()); + + final ByteString configUpdate = configUpdateEnv.getConfigUpdate(); + + ByteString sigHeaderByteString = getSignatureHeaderAsByteString(signer, transactionContext); + + ByteString signatureByteSting = transactionContext.signByteStrings(new User[] {signer}, + sigHeaderByteString, configUpdate)[0]; + + return ConfigSignature.newBuilder() + .setSignatureHeader(sigHeaderByteString) + .setSignature(signatureByteSting) + .build().toByteArray(); + + } catch (Exception e) { + + throw new InvalidArgumentException(e); + } finally { + logger.debug("finally done"); + } + + } + + /** + * Register a block listener. + * + * @param listener function with single argument with type {@link BlockEvent} + * @return The handle of the registered block listener. + * @throws InvalidArgumentException if the channel is shutdown. + */ + public String registerBlockListener(BlockListener listener) throws InvalidArgumentException { + + if (shutdown) { + throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); + } + + return new BL(listener).getHandle(); + + } + + /** + * Unregister a block listener. + * + * @param handle of Block listener to remove. + * @return false if not found. + * @throws InvalidArgumentException if the channel is shutdown or invalid arguments. + */ + public boolean unregisterBlockListener(String handle) throws InvalidArgumentException { + + if (shutdown) { + throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); + } + + checkHandle(BLOCK_LISTENER_TAG, handle); + + synchronized (blockListeners) { + + return null != blockListeners.remove(handle); + + } + } + ////////// Transaction monitoring ///////////////////////////// + + private void startEventQue() { + + if (eventQueueThread != null) { + return; + } + + client.getExecutorService().execute(() -> { + eventQueueThread = Thread.currentThread(); + + while (!shutdown) { + if (!initialized) { + try { + logger.debug("not intialized:" + initialized); + Thread.sleep(1); + } catch (InterruptedException e) { + logger.warn(e); + } + continue; //wait on sending events till the channel is initialized. + } + final BlockEvent blockEvent; + try { + blockEvent = channelEventQue.getNextEvent(); + } catch (EventHubException e) { + if (!shutdown) { + logger.error(e); + } + + continue; + } + if (blockEvent == null) { + logger.warn("GOT null block event."); + continue; + } + + try { + + final String blockchainID = blockEvent.getChannelId(); + final String from = + format("Channel %s eventqueue got block event with block number: %d for channel: %s, from %s", + name, blockEvent.getBlockNumber(), blockchainID, blockEvent.getPeer() != null ? ("Peer: " + blockEvent.getPeer().getName()) : + ("Eventhub: " + blockEvent.getEventHub().getName())); + + logger.trace(from); + + if (!Objects.equals(name, blockchainID)) { + logger.warn(format("Channel %s eventqueue got block event NOT FOR ME channelId %s from %s", name, blockchainID, from)); + continue; // not targeted for this channel + } + + final ArrayList blcopy = new ArrayList<>(blockListeners.size() + 3); + synchronized (blockListeners) { + blcopy.addAll(blockListeners.values()); + } + + for (BL l : blcopy) { + try { + logger.trace(format("Sending block event '%s' to block listener %s", from, l.handle)); + client.getExecutorService().execute(() -> l.listener.received(blockEvent)); + } catch (Throwable e) { //Don't let one register stop rest. + logger.error(format("Error calling block listener %s on channel: %s event: %s ", l.handle, name, from), e); + } + } + } catch (Exception e) { + logger.error("Unable to parse event", e); + logger.debug("event:\n)"); + logger.debug(blockEvent.toString()); + } + } + }); + + } + + /** + * Own block listener to manage transactions. + * + * @return + */ + + private String registerTransactionListenerProcessor() throws InvalidArgumentException { + logger.debug(format("Channel %s registerTransactionListenerProcessor starting", name)); + + // Transaction listener is internal Block listener for transactions + + return registerBlockListener(blockEvent -> { + + if (txListeners.isEmpty()) { + return; + } + + for (TransactionEvent transactionEvent : blockEvent.getTransactionEvents()) { + + logger.debug(format("Channel %s got event for transaction %s ", name, transactionEvent.getTransactionID())); + + List txL = new ArrayList<>(txListeners.size() + 2); + synchronized (txListeners) { + LinkedList list = txListeners.get(transactionEvent.getTransactionID()); + if (null != list) { + txL.addAll(list); + } + } + + for (TL l : txL) { + try { + // only if we get events from each eventhub on the channel fire the transactions event. + // if (getEventHubs().containsAll(l.eventReceived(transactionEvent.getEventHub()))) { + if (l.eventReceived(transactionEvent)) { + l.fire(transactionEvent); + } + + } catch (Throwable e) { + logger.error(e); // Don't let one register stop rest. + } + } + } + }); + } + + void runSweeper() { + + if (shutdown || DELTA_SWEEP < 1) { + return; + } + + if (sweeper == null) { + + sweeper = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = Executors.defaultThreadFactory().newThread(r); + t.setDaemon(true); + return t; + }).scheduleAtFixedRate(() -> { + try { + + if (txListeners != null) { + + synchronized (txListeners) { + + for (Iterator>> it = txListeners.entrySet().iterator(); it.hasNext(); + ) { + + Map.Entry> es = it.next(); + + LinkedList tlLinkedList = es.getValue(); + tlLinkedList.removeIf(TL::sweepMe); + if (tlLinkedList.isEmpty()) { + it.remove(); + } + } + } + } + } catch (Exception e) { + logger.warn("Sweeper got error:" + e.getMessage(), e); + } + + }, 0, DELTA_SWEEP, TimeUnit.MILLISECONDS); + } + + } + + /** + * Register a transactionId that to get notification on when the event is seen in the block chain. + * + * @param txid + * @return + */ + + private CompletableFuture registerTxListener(String txid) { + + CompletableFuture future = new CompletableFuture<>(); + + new TL(txid, future); + + return future; + + } + + /** + * Unregister a transactionId + * + * @param txid + */ + private void unregisterTxListener(String txid) { + + synchronized (txListeners) { + + txListeners.remove(txid); + } + + } + + /** + * Register a chaincode event listener. Both chaincodeId pattern AND eventName pattern must match to invoke + * the chaincodeEventListener + * + * @param chaincodeId Java pattern for chaincode identifier also know as chaincode name. If ma + * @param eventName Java pattern to match the event name. + * @param chaincodeEventListener The listener to be invoked if both chaincodeId and eventName pattern matches. + * @return Handle to be used to unregister the event listener {@link #unregisterChaincodeEventListener(String)} + * @throws InvalidArgumentException + */ + + public String registerChaincodeEventListener(Pattern chaincodeId, Pattern eventName, ChaincodeEventListener chaincodeEventListener) throws InvalidArgumentException { + + if (shutdown) { + throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); + } + + if (chaincodeId == null) { + throw new InvalidArgumentException("The chaincodeId argument may not be null."); + } + + if (eventName == null) { + throw new InvalidArgumentException("The eventName argument may not be null."); + } + + if (chaincodeEventListener == null) { + throw new InvalidArgumentException("The chaincodeEventListener argument may not be null."); + } + + ChaincodeEventListenerEntry chaincodeEventListenerEntry = new ChaincodeEventListenerEntry(chaincodeId, eventName, chaincodeEventListener); + synchronized (this) { + if (null == blh) { + blh = registerChaincodeListenerProcessor(); + } + } + return chaincodeEventListenerEntry.handle; + + } + + /** + * Unregister an existing chaincode event listener. + * + * @param handle Chaincode event listener handle to be unregistered. + * @return True if the chaincode handler was found and removed. + * @throws InvalidArgumentException + */ + + public boolean unregisterChaincodeEventListener(String handle) throws InvalidArgumentException { + boolean ret; + + if (shutdown) { + throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); + } + + checkHandle(CHAINCODE_EVENTS_TAG, handle); + + synchronized (chainCodeListeners) { + ret = null != chainCodeListeners.remove(handle); + + } + + synchronized (this) { + if (null != blh && chainCodeListeners.isEmpty()) { + + unregisterBlockListener(blh); + blh = null; + } + } + + return ret; + + } + + //////////////////////////////////////////////////////////////////////// + //////////////// Chaincode Events.. ////////////////////////////////// + + private String registerChaincodeListenerProcessor() throws InvalidArgumentException { + logger.debug(format("Channel %s registerChaincodeListenerProcessor starting", name)); + + // Chaincode event listener is internal Block listener for chaincode events. + + return registerBlockListener(blockEvent -> { + + if (chainCodeListeners.isEmpty()) { + return; + } + + LinkedList chaincodeEvents = new LinkedList<>(); + + //Find the chaincode events in the transactions. + + for (TransactionEvent transactionEvent : blockEvent.getTransactionEvents()) { + + logger.debug(format("Channel %s got event for transaction %s ", name, transactionEvent.getTransactionID())); + + for (BlockInfo.TransactionEnvelopeInfo.TransactionActionInfo info : transactionEvent.getTransactionActionInfos()) { + + ChaincodeEvent event = info.getEvent(); + if (null != event) { + chaincodeEvents.add(event); + } + + } + + } + + if (!chaincodeEvents.isEmpty()) { + + class MatchPair { + final ChaincodeEventListenerEntry eventListener; + final ChaincodeEvent event; + + MatchPair(ChaincodeEventListenerEntry eventListener, ChaincodeEvent event) { + this.eventListener = eventListener; + this.event = event; + } + } + + List matches = new LinkedList(); //Find matches. + + synchronized (chainCodeListeners) { + + for (ChaincodeEventListenerEntry chaincodeEventListenerEntry : chainCodeListeners.values()) { + + for (ChaincodeEvent chaincodeEvent : chaincodeEvents) { + + if (chaincodeEventListenerEntry.isMatch(chaincodeEvent)) { + + matches.add(new MatchPair(chaincodeEventListenerEntry, chaincodeEvent)); + } + + } + + } + } + + //fire events + for (MatchPair match : matches) { + + ChaincodeEventListenerEntry chaincodeEventListenerEntry = match.eventListener; + ChaincodeEvent ce = match.event; + chaincodeEventListenerEntry.fire(blockEvent, ce); + + } + + } + + }); + } + + /** + * Shutdown the channel with all resources released. + * + * @param force force immediate shutdown. + */ + + public synchronized void shutdown(boolean force) { + + if (shutdown) { + return; + } + + initialized = false; + shutdown = true; + if (chainCodeListeners != null) { + chainCodeListeners.clear(); + + } + + if (blockListeners != null) { + blockListeners.clear(); + } + + if (client != null) { + client.removeChannel(this); + } + + client = null; + + for (EventHub eh : eventHubs) { + + try { + eh.shutdown(); + } catch (Exception e) { + // Best effort. + } + + } + eventHubs.clear(); + for (Peer peer : new ArrayList<>(getPeers())) { + + try { + removePeerInternal(peer); + peer.shutdown(force); + } catch (Exception e) { + // Best effort. + } + } + peers.clear(); // make sure. + + //Make sure + for (Set peerRoleSet : peerRoleSetMap.values()) { + peerRoleSet.clear(); + } + + for (Orderer orderer : getOrderers()) { + orderer.shutdown(force); + } + + orderers.clear(); + + if (null != eventQueueThread) { + + if (eventQueueThread != null) { + eventQueueThread.interrupt(); + } + eventQueueThread = null; + } + ScheduledFuture lsweeper = sweeper; + sweeper = null; + + if (null != lsweeper) { + lsweeper.cancel(true); + } + } + + /** + * Serialize channel to a file using Java serialization. + * Deserialized channel will NOT be in an initialized state. + * + * @param file file + * @throws IOException + * @throws InvalidArgumentException + */ + + public void serializeChannel(File file) throws IOException, InvalidArgumentException { + + if (null == file) { + throw new InvalidArgumentException("File parameter may not be null"); + } + + Files.write(Paths.get(file.getAbsolutePath()), serializeChannel(), + StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); + + } + + /** + * Serialize channel to a byte array using Java serialization. + * Deserialized channel will NOT be in an initialized state. + * + * @throws InvalidArgumentException + * @throws IOException + */ + public byte[] serializeChannel() throws IOException, InvalidArgumentException { + + if (isShutdown()) { + throw new InvalidArgumentException(format("Channel %s has been shutdown.", getName())); + } + + ObjectOutputStream out = null; + + try { + ByteArrayOutputStream bai = new ByteArrayOutputStream(); + out = new ObjectOutputStream(bai); + out.writeObject(this); + out.flush(); + return bai.toByteArray(); + } finally { + if (null != out) { + try { + out.close(); + } catch (IOException e) { + logger.error(e); // best effort. + } + } + } + + } + + @Override + protected void finalize() throws Throwable { + shutdown(true); + super.finalize(); + + } + + /** + * Options for the peer. + * These options are channel based. + */ + public static class PeerOptions implements Cloneable, Serializable { + private static final long serialVersionUID = -6906605662806520793L; + + protected EnumSet peerRoles; + protected Boolean newest = true; + protected Long startEvents; + protected Long stopEvents = Long.MAX_VALUE; + protected boolean registerEventsForFilteredBlocks = false; + + /** + * Is the peer eventing service registered for filtered blocks + * + * @return true if filtered blocks will be returned by the peer eventing service. + */ + public boolean isRegisterEventsForFilteredBlocks() { + return registerEventsForFilteredBlocks; + } + + /** + * Register the peer eventing services to return filtered blocks. + * + * @return the PeerOptions instance. + */ + + public PeerOptions registerEventsForFilteredBlocks() { + registerEventsForFilteredBlocks = true; + return this; + } + + /** + * Register the peer eventing services to return full event blocks. + * + * @return the PeerOptions instance. + */ + + public PeerOptions registerEventsForBlocks() { + registerEventsForFilteredBlocks = false; + return this; + } + + /** + * Get newest block on startup of peer eventing service. + * + * @return + */ + public Boolean getNewest() { + return newest; + } + + /** + * The block number to start getting events from on start up of the peer eventing service.. + * + * @return the start number + */ + + public Long getStartEvents() { + return startEvents; + } + + /** + * The stopping block number when the peer eventing service will stop sending blocks. + * + * @return the stop block number. + */ + + public Long getStopEvents() { + return stopEvents; + } + + protected PeerOptions() { + + } + + /** + * Create an instance of PeerOptions. + * + * @return the PeerOptions instance. + */ + + public static PeerOptions createPeerOptions() { + return new PeerOptions(); + } + + /** + * Return the roles the peer has. + * + * @return the roles {@link PeerRole} + */ + + public EnumSet getPeerRoles() { + if (peerRoles == null) { + return PeerRole.ALL; + } + return peerRoles; + } + + /** + * Set the roles this peer will have on the chain it will added or joined. + * + * @param peerRoles {@link PeerRole} + * @return This PeerOptions. + */ + + public PeerOptions setPeerRoles(EnumSet peerRoles) { + this.peerRoles = peerRoles; + return this; + } + + /** + * Add to the roles this peer will have on the chain it will added or joined. + * + * @param peerRole see {@link PeerRole} + * @return This PeerOptions. + */ + + public PeerOptions addPeerRole(PeerRole peerRole) { + + if (peerRoles == null) { + peerRoles = EnumSet.noneOf(PeerRole.class); + + } + peerRoles.add(peerRole); + return this; + } + + /** + * Set the block number the eventing peer will start relieving events. + * + * @param start The staring block number. + * @return This PeerOptions. + */ + public PeerOptions startEvents(long start) { + startEvents = start; + newest = null; + + return this; + } + + /** + * This is the default. It will start retrieving events with the newest. Note this is not the + * next block that is added to the chain but the current block on the chain. + * + * @return This PeerOptions. + */ + + public PeerOptions startEventsNewest() { + startEvents = null; + newest = true; + + return this; + } + + /** + * The block number to stop sending events. + * + * @param stop the number to stop sending events. + * @return This PeerOptions. + */ + public PeerOptions stopEvents(long stop) { + stopEvents = stop; + return this; + } + + /** + * Clone. + * + * @return return a duplicate of this instance. + */ + + public PeerOptions clone() { + try { + return (PeerOptions) super.clone(); + } catch (CloneNotSupportedException e) { + throw new RuntimeException(e); + } + + } + + } + + /** + * MSPs + */ + + class MSP { + final String orgName; + final MspConfig.FabricMSPConfig fabricMSPConfig; + byte[][] adminCerts; + byte[][] rootCerts; + byte[][] intermediateCerts; + + MSP(String orgName, MspConfig.FabricMSPConfig fabricMSPConfig) { + this.orgName = orgName; + this.fabricMSPConfig = fabricMSPConfig; + } + + /** + * Known as the MSPID internally + * + * @return + */ + + String getID() { + return fabricMSPConfig.getName(); + + } + + /** + * AdminCerts + * + * @return array of admin certs in PEM bytes format. + */ + byte[][] getAdminCerts() { + + if (null == adminCerts) { + adminCerts = new byte[fabricMSPConfig.getAdminsList().size()][]; + int i = 0; + for (ByteString cert : fabricMSPConfig.getAdminsList()) { + adminCerts[i++] = cert.toByteArray(); + } + } + return adminCerts; + } + + /** + * RootCerts + * + * @return array of admin certs in PEM bytes format. + */ + byte[][] getRootCerts() { + + if (null == rootCerts) { + rootCerts = new byte[fabricMSPConfig.getRootCertsList().size()][]; + int i = 0; + for (ByteString cert : fabricMSPConfig.getRootCertsList()) { + rootCerts[i++] = cert.toByteArray(); + } + } + + return rootCerts; + } + + /** + * IntermediateCerts + * + * @return array of intermediate certs in PEM bytes format. + */ + byte[][] getIntermediateCerts() { + + if (null == intermediateCerts) { + intermediateCerts = new byte[fabricMSPConfig.getIntermediateCertsList().size()][]; + int i = 0; + for (ByteString cert : fabricMSPConfig.getIntermediateCertsList()) { + intermediateCerts[i++] = cert.toByteArray(); + } + } + return intermediateCerts; + } + + } + + class ChannelEventQue { + + private final BlockingQueue events = new LinkedBlockingQueue<>(); //Thread safe + private Throwable eventException; + + void eventError(Throwable t) { + eventException = t; + } + + boolean addBEvent(BlockEvent event) { + if (shutdown) { + return false; + } + + //For now just support blocks --- other types are also reported as blocks. + + if (!event.isBlockEvent()) { + return false; + } + + // May be fed by multiple eventhubs but BlockingQueue.add() is thread-safe + events.add(event); + + return true; + + } + + BlockEvent getNextEvent() throws EventHubException { + if (shutdown) { + throw new EventHubException(format("Channel %s has been shutdown", name)); + + } + BlockEvent ret = null; + if (eventException != null) { + throw new EventHubException(eventException); + } + try { + ret = events.take(); + } catch (InterruptedException e) { + if (shutdown) { + throw new EventHubException(eventException); + + } else { + logger.warn(e); + if (eventException != null) { + + EventHubException eve = new EventHubException(eventException); + logger.error(eve.getMessage(), eve); + throw eve; + } + } + } + + if (eventException != null) { + throw new EventHubException(eventException); + } + + if (shutdown) { + + throw new EventHubException(format("Channel %s has been shutdown.", name)); + + } + + return ret; + } + + } + + class BL { + + final BlockListener listener; + final String handle; + + BL(BlockListener listener) { + + handle = BLOCK_LISTENER_TAG + Utils.generateUUID() + BLOCK_LISTENER_TAG; + logger.debug(format("Channel %s blockListener %s starting", name, handle)); + + this.listener = listener; + synchronized (blockListeners) { + + blockListeners.put(handle, this); + + } + + } + + public String getHandle() { + return handle; + } + } + + private class TL { + final String txID; + final long createTime = System.currentTimeMillis(); + final AtomicBoolean fired = new AtomicBoolean(false); + final CompletableFuture future; + final Set unSeenEventHubs = Collections.synchronizedSet(new HashSet<>()); + final Set unSeenPeers = Collections.synchronizedSet(new HashSet<>()); + long sweepTime = System.currentTimeMillis() + (long) (DELTA_SWEEP * 1.5); + + TL(String txID, CompletableFuture future) { + this.txID = txID; + this.future = future; + unSeenPeers.addAll(getEventingPeers()); + unSeenEventHubs.addAll(eventHubs); + addListener(); + } + + /** + * Record transactions event. + * + * @param transactionEvent + * @return True if transactions have been seen on all eventing peers and eventhubs. + */ + boolean eventReceived(TransactionEvent transactionEvent) { + sweepTime = System.currentTimeMillis() + DELTA_SWEEP; //seen activity keep it active. + + Peer peer = transactionEvent.getPeer(); + if (peer != null) { + unSeenPeers.remove(peer); + logger.debug(format("Channel %s seen transaction event %s for peer %s", name, txID, peer.getName())); + } else if (null != transactionEvent.getEventHub()) { + EventHub eventHub = transactionEvent.getEventHub(); + logger.debug(format("Channel %s seen transaction event %s for eventHub %s", name, txID, eventHub.toString())); + unSeenEventHubs.remove(eventHub); + } else { + logger.error(format("Channel %s seen transaction event %s with no associated peer or eventhub", name, txID)); + } + + boolean isEmpty; + synchronized (this) { + isEmpty = unSeenEventHubs.isEmpty() && unSeenPeers.isEmpty(); + } + return isEmpty; + } + + private void addListener() { + runSweeper(); + synchronized (txListeners) { + LinkedList tl = txListeners.computeIfAbsent(txID, k -> new LinkedList<>()); + tl.add(this); + } + } + + boolean sweepMe() { // Sweeps DO NOT fire future. user needs to put timeout on their futures for timeouts. + + final boolean ret = sweepTime < System.currentTimeMillis() || fired.get() || future.isDone(); + + if (IS_DEBUG_LEVEL && ret) { + + StringBuilder sb = new StringBuilder(10000); + sb.append("Non reporting event hubs:"); + String sep = ""; + for (EventHub eh : unSeenEventHubs) { + sb.append(sep).append(eh.getName()); + sep = ","; + + } + if (sb.length() != 0) { + sb.append(". "); + + } + sep = "Non reporting peers: "; + for (Peer peer : unSeenPeers) { + sb.append(sep).append(peer.getName()); + sep = ","; + } + + logger.debug(format("Force removing transaction listener after %d ms for transaction %s. %s" + + ". sweep timeout: %b, fired: %b, future done:%b", + System.currentTimeMillis() - createTime, txID, sb.toString(), + sweepTime < System.currentTimeMillis(), fired.get(), future.isDone())); + + } + + return ret; + + } + + void fire(BlockEvent.TransactionEvent transactionEvent) { + + if (fired.getAndSet(true)) { + return; + } + + synchronized (txListeners) { + LinkedList l = txListeners.get(txID); + + if (null != l) { + l.removeFirstOccurrence(this); + if (l.size() == 0) { + txListeners.remove(txID); + } + } + } + if (future.isDone()) { + fired.set(true); + return; + } + + if (transactionEvent.isValid()) { + logger.debug(format("Completing future for channel %s and transaction id: %s", name, txID)); + client.getExecutorService().execute(() -> future.complete(transactionEvent)); + } else { + logger.debug(format("Completing future as exception for channel %s and transaction id: %s, validation code: %02X", + name, txID, transactionEvent.getValidationCode())); + client.getExecutorService().execute(() -> future.completeExceptionally( + new TransactionEventException(format("Received invalid transaction event. Transaction ID %s status %s", + transactionEvent.getTransactionID(), + transactionEvent.getValidationCode()), + transactionEvent))); + } + } + + } + + private class ChaincodeEventListenerEntry { + + private final Pattern chaincodeIdPattern; + private final Pattern eventNamePattern; + private final ChaincodeEventListener chaincodeEventListener; + private final String handle; + + ChaincodeEventListenerEntry(Pattern chaincodeIdPattern, Pattern eventNamePattern, ChaincodeEventListener chaincodeEventListener) { + this.chaincodeIdPattern = chaincodeIdPattern; + this.eventNamePattern = eventNamePattern; + this.chaincodeEventListener = chaincodeEventListener; + this.handle = CHAINCODE_EVENTS_TAG + Utils.generateUUID() + CHAINCODE_EVENTS_TAG; + + synchronized (chainCodeListeners) { + + chainCodeListeners.put(handle, this); + + } + } + + boolean isMatch(ChaincodeEvent chaincodeEvent) { + + return chaincodeIdPattern.matcher(chaincodeEvent.getChaincodeId()).matches() && eventNamePattern.matcher(chaincodeEvent.getEventName()).matches(); + + } + + void fire(BlockEvent blockEvent, ChaincodeEvent ce) { + + client.getExecutorService().execute(() -> chaincodeEventListener.received(handle, blockEvent, ce)); + + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.hyperledger.fabric.sdk.Channel.parseConfigBlock` indirectly reads without synchronization from `this.org.hyperledger.fabric.sdk.Channel.client`. Potentially races with write in method `Channel.shutdown(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Channel.parseConfigBlock() + +### Procedure Id: +org.hyperledger.fabric.sdk.Channel.parseConfigBlock():void.5fa4f5e62d18ae6a53bf5338c7662212 + +### File: +src/main/java/org/hyperledger/fabric/sdk/Channel.java + +### Key: +Channel.java|parseConfigBlock|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +b1646c8695f79f47fcdbea8cd20f27f4 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9361/instruction.md b/inferredbugs-9361/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..21f5efa5684180e98ce9271e727799be622cb4d3 --- /dev/null +++ b/inferredbugs-9361/instruction.md @@ -0,0 +1,1416 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fabric-sdk-java +**Bug ID:** 24 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * + * Copyright 2016,2017 DTCC, Fujitsu Australia Software Technology, IBM - All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.hyperledger.fabric.sdk; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import io.netty.util.internal.ConcurrentSet; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hyperledger.fabric.protos.discovery.Protocol; +import org.hyperledger.fabric.protos.gossip.Message; +import org.hyperledger.fabric.protos.msp.Identities; +import org.hyperledger.fabric.protos.msp.MspConfigPackage; +import org.hyperledger.fabric.sdk.Channel.ServiceDiscoveryChaincodeCalls; +import org.hyperledger.fabric.sdk.ServiceDiscovery.SDLayout.SDGroup; +import org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException; +import org.hyperledger.fabric.sdk.exception.ServiceDiscoveryException; +import org.hyperledger.fabric.sdk.helper.Config; +import org.hyperledger.fabric.sdk.helper.DiagnosticFileDumper; +import org.hyperledger.fabric.sdk.transaction.TransactionContext; + +import static java.lang.String.format; +import static org.hyperledger.fabric.sdk.helper.Utils.toHexString; + +public class ServiceDiscovery { + private static final Log logger = LogFactory.getLog(ServiceDiscovery.class); + private static final boolean DEBUG = logger.isDebugEnabled(); + private static final Config config = Config.getConfig(); + private static final boolean IS_TRACE_LEVEL = logger.isTraceEnabled(); + private static final DiagnosticFileDumper diagnosticFileDumper = IS_TRACE_LEVEL + ? config.getDiagnosticFileDumper() : null; + private static final int SERVICE_DISCOVERY_WAITTIME = config.getServiceDiscoveryWaitTime(); + private static final Random random = new Random(); + private final Collection serviceDiscoveryPeers; + private final Channel channel; + private final TransactionContext transactionContext; + private final String channelName; + private volatile Map chaindcodeMap = new HashMap<>(); + private static final boolean asLocalhost = config.discoverAsLocalhost(); + + ServiceDiscovery(Channel channel, Collection serviceDiscoveryPeers, TransactionContext transactionContext) { + this.serviceDiscoveryPeers = serviceDiscoveryPeers; + this.channel = channel; + this.channelName = channel.getName(); + this.transactionContext = transactionContext.retryTransactionSameContext(); + } + + SDChaindcode discoverEndorserEndpoint(TransactionContext transactionContext, final String name) throws ServiceDiscoveryException { + Map lchaindcodeMap = chaindcodeMap; + if (lchaindcodeMap != null) { // check if we have it already. + SDChaindcode sdChaindcode = lchaindcodeMap.get(name); + if (null != sdChaindcode) { + return sdChaindcode; + } + } + + final ServiceDiscoveryChaincodeCalls serviceDiscoveryChaincodeCalls = new ServiceDiscoveryChaincodeCalls(name); + LinkedList cc = new LinkedList<>(); + cc.add(serviceDiscoveryChaincodeCalls); + List> ccl = new LinkedList<>(); + ccl.add(cc); + + Map dchaindcodeMap = discoverEndorserEndpoints(transactionContext, ccl); + final SDChaindcode sdChaindcode = dchaindcodeMap.get(name); + if (null == sdChaindcode) { + throw new ServiceDiscoveryException(format("Failed to find any endorsers for chaincode %s. See logs for details", name)); + } + return sdChaindcode; + } + + Collection getDiscoveredChaincodeNames() { + final SDNetwork lsdNetwork = fullNetworkDiscovery(false); + if (null == lsdNetwork) { + return Collections.emptyList(); + } + + return new ArrayList<>(lsdNetwork.getChaincodesNames()); + } + + class SDNetwork { + final Map> tlsCerts = new HashMap<>(); + final Map> tlsIntermCerts = new HashMap<>(); + long discoveryTime; + + void addTlsCert(String mspid, byte[] cert) { + if (IS_TRACE_LEVEL) { + logger.trace(format("Channel %s service discovery MSPID %s adding TLSCert %s", channelName, mspid, toHexString(cert))); + } + tlsCerts.computeIfAbsent(mspid, k -> new LinkedList<>()).add(cert); + } + + void addTlsIntermCert(String mspid, byte[] cert) { + if (IS_TRACE_LEVEL) { + logger.trace(format("Channel %s service discovery MSPID %s adding intermediate TLSCert %s", channelName, mspid, toHexString(cert))); + } + tlsIntermCerts.computeIfAbsent(mspid, k -> new LinkedList<>()).add(cert); + } + + SDEndorser getEndorserByEndpoint(String endpoint) { + return endorsers.get(endpoint); + } + + public Collection getEndorsers() { + return Collections.unmodifiableCollection(endorsers.values()); + } + + Map endorsers = Collections.emptyMap(); + + Map ordererEndpoints = Collections.emptyMap(); + + Set getOrdererEndpoints() { + return Collections.unmodifiableSet(ordererEndpoints.keySet()); + } + + Collection getSDOrderers() { + return ordererEndpoints.values(); + } + + Set getPeerEndpoints() { + return Collections.unmodifiableSet(endorsers.keySet()); + } + + Set chaincodeNames = null; + + Set getChaincodesNames() { + if (null == chaincodeNames) { + if (null == endorsers) { + chaincodeNames = Collections.emptySet(); + return chaincodeNames; + } + + Set ret = new HashSet<>(); + endorsers.values().forEach(sdEndorser -> { + if (null != sdEndorser.chaincodesList) { + sdEndorser.chaincodesList.forEach(chaincode -> ret.add(chaincode.getName())); + } + }); + chaincodeNames = ret; + } + + return chaincodeNames; + } + + Collection getTlsCerts(final String mspid) { + + final Collection bytes = tlsCerts.get(mspid); + if (null == bytes) { + logger.debug(format("Channel %s no tls ca certs for mspid: %s", channelName, mspid)); + return Collections.emptyList(); + + } + if (bytes.isEmpty()) { + logger.debug(format("Channel %s no tls ca certs for mspid: %s", channelName, mspid)); + } + return Collections.unmodifiableCollection(bytes); + } + + Collection getTlsIntermediateCerts(String mspid) { + final Collection bytes = tlsIntermCerts.get(mspid); + + if (null == bytes) { + logger.debug(format("Channel %s no tls intermediary ca certs for mspid: %s", channelName, mspid)); + return Collections.emptyList(); + + } + if (bytes.isEmpty()) { + logger.debug(format("Channel %s no tls intermediary ca certs for mspid: %s", channelName, mspid)); + } + return Collections.unmodifiableCollection(bytes); + + } + } + + private volatile SDNetwork sdNetwork = null; + + private final ConcurrentSet certs = new ConcurrentSet<>(); + + SDNetwork networkDiscovery(TransactionContext ltransactionContext, boolean force) { + logger.trace(format("Network discovery force: %b", force)); + + ArrayList speers = new ArrayList<>(serviceDiscoveryPeers); + Collections.shuffle(speers); + SDNetwork ret = sdNetwork; + + if (!force && null != ret && ret.discoveryTime + SERVICE_DISCOVER_FREQ_SECONDS * 1000 > System.currentTimeMillis()) { + return ret; + } + ret = null; + + for (final Peer serviceDiscoveryPeer : speers) { + try { + SDNetwork lsdNetwork = new SDNetwork(); + final byte[] clientTLSCertificateDigest = serviceDiscoveryPeer.getClientTLSCertificateDigest(); + + logger.info(format("Channel %s doing discovery with peer: %s", channelName, serviceDiscoveryPeer.toString())); + + if (null == clientTLSCertificateDigest) { + throw new RuntimeException(format("Channel %s, peer %s requires mutual tls for service discovery.", channelName, serviceDiscoveryPeer)); + } + + ByteString clientIdent = ltransactionContext.getIdentity().toByteString(); + ByteString tlshash = ByteString.copyFrom(clientTLSCertificateDigest); + Protocol.AuthInfo authentication = Protocol.AuthInfo.newBuilder().setClientIdentity(clientIdent).setClientTlsCertHash(tlshash).build(); + + List fq = new ArrayList<>(2); + fq.add(Protocol.Query.newBuilder().setChannel(channelName).setConfigQuery(Protocol.ConfigQuery.newBuilder().build()).build()); + fq.add(Protocol.Query.newBuilder().setChannel(channelName).setPeerQuery(Protocol.PeerMembershipQuery.newBuilder().build()).build()); + + Protocol.Request request = Protocol.Request.newBuilder().addAllQueries(fq).setAuthentication(authentication).build(); + ByteString payloadBytes = request.toByteString(); + ByteString signatureBytes = ltransactionContext.signByteStrings(payloadBytes); + Protocol.SignedRequest sr = Protocol.SignedRequest.newBuilder() + .setPayload(payloadBytes).setSignature(signatureBytes).build(); + + if (IS_TRACE_LEVEL && null != diagnosticFileDumper) { // dump protobuf we sent + logger.trace(format("Service discovery channel %s %s service chaincode query sent %s", channelName, serviceDiscoveryPeer, + diagnosticFileDumper.createDiagnosticProtobufFile(sr.toByteArray()))); + } + + final Protocol.Response response = serviceDiscoveryPeer.sendDiscoveryRequestAsync(sr).get(SERVICE_DISCOVERY_WAITTIME, TimeUnit.MILLISECONDS); + + if (IS_TRACE_LEVEL && null != diagnosticFileDumper) { // dump protobuf we get + logger.trace(format("Service discovery channel %s %s service discovery returned %s", channelName, serviceDiscoveryPeer, + diagnosticFileDumper.createDiagnosticProtobufFile(response.toByteArray()))); + } + + serviceDiscoveryPeer.hasConnected(); + final List resultsList = response.getResultsList(); + Protocol.QueryResult queryResult; + Protocol.QueryResult queryResult2; + + queryResult = resultsList.get(0); //configquery + if (queryResult.getResultCase().getNumber() == Protocol.QueryResult.ERROR_FIELD_NUMBER) { + logger.warn(format("Channel %s peer: %s error during service discovery %s", channelName, serviceDiscoveryPeer.toString(), queryResult.getError().getContent())); + continue; + } + queryResult2 = resultsList.get(1); + if (queryResult2.getResultCase().getNumber() == Protocol.QueryResult.ERROR_FIELD_NUMBER) { + logger.warn(format("Channel %s peer %s service discovery error %s", channelName, serviceDiscoveryPeer.toString(), queryResult2.getError().getContent())); + continue; + } + Protocol.ConfigResult configResult = queryResult.getConfigResult(); + + Map msps = configResult.getMspsMap(); + Set cbbs = new HashSet<>(msps.size() * 4); + + for (Map.Entry i : msps.entrySet()) { + final MspConfigPackage.FabricMSPConfig value = i.getValue(); + final String mspid = value.getName(); + cbbs.addAll(value.getRootCertsList()); + cbbs.addAll(value.getIntermediateCertsList()); + + value.getTlsRootCertsList().forEach(bytes -> lsdNetwork.addTlsCert(mspid, bytes.toByteArray())); + + value.getTlsIntermediateCertsList().forEach(bytes -> lsdNetwork.addTlsIntermCert(mspid, bytes.toByteArray())); + } + + List toaddCerts = new LinkedList<>(); + + synchronized (certs) { + cbbs.forEach(bytes -> { + if (certs.add(bytes)) { + toaddCerts.add(bytes.toByteArray()); + } + }); + } + if (!toaddCerts.isEmpty()) { // add them to crypto store. + channel.client.getCryptoSuite().loadCACertificatesAsBytes(toaddCerts); + } + + Map ordererEndpoints = new HashMap<>(); + Map orderersMap = configResult.getOrderersMap(); + for (Map.Entry i : orderersMap.entrySet()) { + final String mspid = i.getKey(); + + Protocol.Endpoints value = i.getValue(); + for (Protocol.Endpoint l : value.getEndpointList()) { + logger.trace(format("Channel: %s peer: %s discovered orderer MSPID: %s, endpoint: %s:%s", channelName, serviceDiscoveryPeer, mspid, l.getHost(), l.getPort())); + String host = asLocalhost ? "localhost" : l.getHost(); + String endpoint = (host + ":" + l.getPort()).trim().toLowerCase(); + + SDOrderer discoveredAlready = ordererEndpoints.get(endpoint); + if (discoveredAlready != null) { + if (!mspid.equals(discoveredAlready.getMspid())) { + logger.error(format("Service discovery in channel: %s, peer: %s found Orderer endpoint: %s with two mspids: '%s', '%s'", channelName, serviceDiscoveryPeer, endpoint, mspid, discoveredAlready.getMspid())); + continue; // report it and ignore. + } + logger.debug(format("Service discovery in channel: %s, peer: %s found Orderer endpoint: %s mspid: %s discovered twice", channelName, serviceDiscoveryPeer, endpoint, mspid)); + continue; + } + + Properties properties = new Properties(); + if (asLocalhost) { + properties.put("hostnameOverride", l.getHost()); + } + + final SDOrderer sdOrderer = new SDOrderer(mspid, endpoint, lsdNetwork.getTlsCerts(mspid), lsdNetwork.getTlsIntermediateCerts(mspid), properties); + + ordererEndpoints.put(sdOrderer.getEndPoint(), sdOrderer); + } + } + lsdNetwork.ordererEndpoints = ordererEndpoints; + + Protocol.PeerMembershipResult membership = queryResult2.getMembers(); + + lsdNetwork.endorsers = new HashMap<>(); + + for (Map.Entry peers : membership.getPeersByOrgMap().entrySet()) { + final String mspId = peers.getKey(); + final Protocol.Peers peer = peers.getValue(); + + for (Protocol.Peer pp : peer.getPeersList()) { + SDEndorser ppp = new SDEndorser(pp, lsdNetwork.getTlsCerts(mspId), lsdNetwork.getTlsIntermediateCerts(mspId), asLocalhost); + + SDEndorser discoveredAlready = lsdNetwork.endorsers.get(ppp.getEndpoint()); + if (null != discoveredAlready) { + if (!mspId.equals(discoveredAlready.getMspid())) { + logger.error(format("Service discovery in channel: %s, peer: %s, found endorser endpoint: %s with two mspids: '%s', '%s'", channelName, serviceDiscoveryPeer, ppp.getEndpoint(), mspId, discoveredAlready.getMspid())); + continue; // report it and ignore. + } + logger.debug(format("Service discovery in channel %s peer: %s found Endorser endpoint: %s mspid: %s discovered twice", channelName, serviceDiscoveryPeer, ppp.getEndpoint(), mspId)); + continue; + } + + logger.trace(format("Channel %s peer: %s discovered peer mspid group: %s, endpoint: %s, mspid: %s", channelName, serviceDiscoveryPeer, mspId, ppp.getEndpoint(), ppp.getMspid())); + + lsdNetwork.endorsers.put(ppp.getEndpoint(), ppp); + } + } + lsdNetwork.discoveryTime = System.currentTimeMillis(); + + sdNetwork = lsdNetwork; + ret = lsdNetwork; + break; + } catch (Exception e) { + logger.warn(format("Channel %s peer %s service discovery error %s", channelName, serviceDiscoveryPeer, e.getMessage())); + } + } + + logger.debug(format("Channel %s service discovery completed: %b", channelName, ret != null)); + + return ret; + } + + public static class SDOrderer { + private final String mspid; + private final Collection tlsCerts; + private final Collection tlsIntermediateCerts; + private final String endPoint; + private final Properties properties; + + SDOrderer(String mspid, String endPoint, Collection tlsCerts, Collection tlsIntermediateCerts, Properties properties) { + this.mspid = mspid; + this.endPoint = endPoint; + this.tlsCerts = tlsCerts; + this.tlsIntermediateCerts = tlsIntermediateCerts; + this.properties = properties; + } + + public Collection getTlsIntermediateCerts() { + return tlsIntermediateCerts; + } + + public String getEndPoint() { + return endPoint; + } + + public String getMspid() { + return mspid; + } + + public Collection getTlsCerts() { + return tlsCerts; + } + + public Properties getProperties() { + return properties; + } + } + + Map discoverEndorserEndpoints(TransactionContext transactionContext, List> chaincodeNames) throws ServiceDiscoveryException { + if (null == chaincodeNames) { + logger.warn("Discover of chaincode names was null."); + return Collections.emptyMap(); + } + if (chaincodeNames.isEmpty()) { + logger.warn("Discover of chaincode names was empty."); + return Collections.emptyMap(); + } + if (DEBUG) { + StringBuilder cns = new StringBuilder(1000); + String sep = ""; + cns.append("["); + for (List s : chaincodeNames) { + + ServiceDiscoveryChaincodeCalls n = s.get(0); + cns.append(sep).append(n.write(s.subList(1, s.size()))); + sep = ", "; + } + cns.append("]"); + logger.debug(format("Channel %s doing discovery for chaincodes: %s", channelName, cns.toString())); + } + + ArrayList speers = new ArrayList<>(serviceDiscoveryPeers); + Collections.shuffle(speers); + final Map ret = new HashMap<>(); + SDNetwork sdNetwork = networkDiscovery(transactionContext, false); + ServiceDiscoveryException serviceDiscoveryException = null; + + for (Peer serviceDiscoveryPeer : speers) { + serviceDiscoveryException = null; + try { + logger.debug(format("Channel %s doing discovery for chaincodes on peer: %s", channelName, serviceDiscoveryPeer.toString())); + + TransactionContext ltransactionContext = transactionContext.retryTransactionSameContext(); + final byte[] clientTLSCertificateDigest = serviceDiscoveryPeer.getClientTLSCertificateDigest(); + + if (null == clientTLSCertificateDigest) { + logger.warn(format("Channel %s peer %s requires mutual tls for service discovery.", channelName, serviceDiscoveryPeer.toString())); + continue; + } + + ByteString clientIdent = ltransactionContext.getIdentity().toByteString(); + ByteString tlshash = ByteString.copyFrom(clientTLSCertificateDigest); + Protocol.AuthInfo authentication = Protocol.AuthInfo.newBuilder().setClientIdentity(clientIdent).setClientTlsCertHash(tlshash).build(); + + List fq = new ArrayList<>(chaincodeNames.size()); + + for (List chaincodeName : chaincodeNames) { + if (ret.containsKey(chaincodeName.get(0).getName())) { + continue; + } + LinkedList chaincodeCalls = new LinkedList<>(); + chaincodeName.forEach(serviceDiscoveryChaincodeCalls -> chaincodeCalls.add(serviceDiscoveryChaincodeCalls.build())); + List cinn = new ArrayList<>(1); + chaincodeName.forEach(ServiceDiscoveryChaincodeCalls::build); + Protocol.ChaincodeInterest cci = Protocol.ChaincodeInterest.newBuilder().addAllChaincodes(chaincodeCalls).build(); + cinn.add(cci); + Protocol.ChaincodeQuery chaincodeQuery = Protocol.ChaincodeQuery.newBuilder().addAllInterests(cinn).build(); + + fq.add(Protocol.Query.newBuilder().setChannel(channelName).setCcQuery(chaincodeQuery).build()); + } + + if (fq.size() == 0) { + //this would be odd but lets take care of it. + break; + } + + Protocol.Request request = Protocol.Request.newBuilder().addAllQueries(fq).setAuthentication(authentication).build(); + ByteString payloadBytes = request.toByteString(); + ByteString signatureBytes = ltransactionContext.signByteStrings(payloadBytes); + Protocol.SignedRequest sr = Protocol.SignedRequest.newBuilder() + .setPayload(payloadBytes).setSignature(signatureBytes).build(); + if (IS_TRACE_LEVEL && null != diagnosticFileDumper) { // dump protobuf we sent + logger.trace(format("Service discovery channel %s %s service chaincode query sent %s", channelName, serviceDiscoveryPeer, + diagnosticFileDumper.createDiagnosticProtobufFile(sr.toByteArray()))); + } + + logger.debug(format("Channel %s peer %s sending chaincode query request", channelName, serviceDiscoveryPeer.toString())); + final Protocol.Response response = serviceDiscoveryPeer.sendDiscoveryRequestAsync(sr).get(SERVICE_DISCOVERY_WAITTIME, TimeUnit.MILLISECONDS); + if (IS_TRACE_LEVEL && null != diagnosticFileDumper) { // dump protobuf we get + logger.trace(format("Service discovery channel %s %s service chaincode query returned %s", channelName, serviceDiscoveryPeer, + diagnosticFileDumper.createDiagnosticProtobufFile(response.toByteArray()))); + } + logger.debug(format("Channel %s peer %s completed chaincode query request", channelName, serviceDiscoveryPeer.toString())); + serviceDiscoveryPeer.hasConnected(); + + for (Protocol.QueryResult queryResult : response.getResultsList()) { + if (queryResult.getResultCase().getNumber() == Protocol.QueryResult.ERROR_FIELD_NUMBER) { + ServiceDiscoveryException discoveryException = new ServiceDiscoveryException(format("Error %s", queryResult.getError().getContent())); + logger.error(discoveryException.getMessage()); + continue; + } + + if (queryResult.getResultCase().getNumber() != Protocol.QueryResult.CC_QUERY_RES_FIELD_NUMBER) { + ServiceDiscoveryException discoveryException = new ServiceDiscoveryException(format("Error expected chaincode endorsement query but got %s : ", queryResult.getResultCase().toString())); + logger.error(discoveryException.getMessage()); + continue; + } + + Protocol.ChaincodeQueryResult ccQueryRes = queryResult.getCcQueryRes(); + if (ccQueryRes.getContentList().isEmpty()) { + throw new ServiceDiscoveryException(format("Error %s", queryResult.getError().getContent())); + } + + for (Protocol.EndorsementDescriptor es : ccQueryRes.getContentList()) { + final String chaincode = es.getChaincode(); + List layouts = new LinkedList<>(); + for (Protocol.Layout layout : es.getLayoutsList()) { + SDLayout sdLayout = null; + Map quantitiesByGroupMap = layout.getQuantitiesByGroupMap(); + for (Map.Entry qmap : quantitiesByGroupMap.entrySet()) { + final String key = qmap.getKey(); + final int quantity = qmap.getValue(); + if (quantity < 1) { + continue; + } + Protocol.Peers peers = es.getEndorsersByGroupsMap().get(key); + if (peers == null || peers.getPeersCount() == 0) { + continue; + } + + List sdEndorsers = new LinkedList<>(); + + for (Protocol.Peer pp : peers.getPeersList()) { + SDEndorser ppp = new SDEndorser(pp, null, null, asLocalhost); + final String endPoint = ppp.getEndpoint(); + SDEndorser nppp = sdNetwork.getEndorserByEndpoint(endPoint); + if (null == nppp) { + sdNetwork = networkDiscovery(transactionContext, true); + if (null == sdNetwork) { + throw new ServiceDiscoveryException("Failed to discover network resources."); + } + nppp = sdNetwork.getEndorserByEndpoint(ppp.getEndpoint()); + if (null == nppp) { + throw new ServiceDiscoveryException(format("Failed to discover peer endpoint information %s for chaincode %s ", endPoint, chaincode)); + } + } + sdEndorsers.add(nppp); + } + if (sdLayout == null) { + sdLayout = new SDLayout(); + layouts.add(sdLayout); + } + sdLayout.addGroup(key, quantity, sdEndorsers); + } + } + if (layouts.isEmpty()) { + logger.warn(format("Channel %s chaincode %s discovered no layouts!", channelName, chaincode)); + } else { + if (DEBUG) { + StringBuilder sb = new StringBuilder(1000); + sb.append("Channel ").append(channelName) + .append(" found ").append(layouts.size()).append(" layouts for chaincode: ").append(es.getChaincode()); + sb.append(", layouts: ["); + + String sep = ""; + for (SDLayout layout : layouts) { + sb.append(sep).append(layout); + sep = ", "; + } + sb.append("]"); + + logger.debug(sb.toString()); + } + ret.put(es.getChaincode(), new SDChaindcode(es.getChaincode(), layouts)); + } + } + } + + if (ret.size() == chaincodeNames.size()) { + break; // found them all. + } + } catch (ServiceDiscoveryException e) { + logger.warn(format("Service discovery error on peer %s. Error: %s", serviceDiscoveryPeer.toString(), e.getMessage())); + serviceDiscoveryException = e; + } catch (Exception e) { + logger.warn(format("Service discovery error on peer %s. Error: %s", serviceDiscoveryPeer.toString(), e.getMessage())); + serviceDiscoveryException = new ServiceDiscoveryException(e); + } + } + + if (null != serviceDiscoveryException) { + throw serviceDiscoveryException; + } + if (ret.size() != chaincodeNames.size()) { + logger.warn((format("Channel %s failed to find all layouts for chaincodes. Expected: %d and found: %d", channelName, chaincodeNames.size(), ret.size()))); + } + + return ret; + } + + /** + * Endorsement selection by layout group that has least required and block height is the highest (most up to date). + */ + static final EndorsementSelector ENDORSEMENT_SELECTION_LEAST_REQUIRED_BLOCKHEIGHT = sdChaindcode -> { + List layouts = sdChaindcode.getLayouts(); + + class LGroup { // local book keeping. + int stillRequred; + final Set endorsers = new HashSet<>(); + + LGroup(SDGroup group) { + endorsers.addAll(group.getEndorsers()); + this.stillRequred = group.getStillRequired(); + } + + // return true if still required + boolean endorsed(Set endorsed) { + for (SDEndorser sdEndorser : endorsed) { + if (endorsers.contains(sdEndorser)) { + endorsers.remove(sdEndorser); + stillRequred = Math.max(0, stillRequred - 1); + } + } + return stillRequred > 0; + } + } + + SDLayout pickedLayout = null; + + Map> layoutEndorsers = new HashMap<>(); + + // if (layouts.size() > 1) { // pick layout by least number of endorsers .. least number of peers hit and smaller block! + + for (SDLayout sdLayout : layouts) { + Set remainingGroups = new HashSet<>(); + for (SDGroup sdGroup : sdLayout.getSDLGroups()) { + remainingGroups.add(new LGroup(sdGroup)); + } + // These are required as there is no choice. + Set required = new HashSet<>(); + for (LGroup lgroup : remainingGroups) { + if (lgroup.stillRequred == lgroup.endorsers.size()) { + required.addAll(lgroup.endorsers); + } + } + //add those that there are no choice. + + if (required.size() > 0) { + Set remove = new HashSet<>(remainingGroups.size()); + for (LGroup lGroup : remainingGroups) { + if (!lGroup.endorsed(required)) { + remove.add(lGroup); + } + } + remainingGroups.removeAll(remove); + Set sdEndorsers = layoutEndorsers.computeIfAbsent(sdLayout, k -> new HashSet<>()); + sdEndorsers.addAll(required); + } + + if (remainingGroups.isEmpty()) { // no more groups here done for this layout. + continue; // done with this layout there really were no choices. + } + + //Now go through groups finding which endorsers can satisfy the most groups. + + do { + Map matchCount = new HashMap<>(); + + for (LGroup group : remainingGroups) { + for (SDEndorser sdEndorser : group.endorsers) { + Integer count = matchCount.get(sdEndorser); + if (count == null) { + matchCount.put(sdEndorser, 1); + } else { + matchCount.put(sdEndorser, ++count); + } + } + } + + Set theMost = new HashSet<>(); + int maxMatch = 0; + for (Map.Entry m : matchCount.entrySet()) { + int count = m.getValue(); + SDEndorser sdEndorser = m.getKey(); + if (count > maxMatch) { + theMost.clear(); + theMost.add(sdEndorser); + maxMatch = count; + } else if (count == maxMatch) { + theMost.add(sdEndorser); + } + } + + Set theVeryMost = new HashSet<>(1); + long max = 0L; + // Tie breaker: Pick one with greatest ledger height. + for (SDEndorser sd : theMost) { + if (sd.getLedgerHeight() > max) { + max = sd.getLedgerHeight(); + theVeryMost.clear(); + theVeryMost.add(sd); + } + + } + + Set remove2 = new HashSet<>(remainingGroups.size()); + for (LGroup lGroup : remainingGroups) { + if (!lGroup.endorsed(theVeryMost)) { + remove2.add(lGroup); + } + } + Set sdEndorsers = layoutEndorsers.computeIfAbsent(sdLayout, k -> new HashSet<>()); + sdEndorsers.addAll(theVeryMost); + remainingGroups.removeAll(remove2); + } while (!remainingGroups.isEmpty()); + + // Now pick the layout with least endorsers + } + //Pick layout which needs least endorsements. + int min = Integer.MAX_VALUE; + Set theLeast = new HashSet<>(); + + for (Map.Entry> l : layoutEndorsers.entrySet()) { + SDLayout sdLayoutK = l.getKey(); + Integer count = l.getValue().size(); + if (count < min) { + theLeast.clear(); + theLeast.add(sdLayoutK); + min = count; + } else if (count == min) { + theLeast.add(sdLayoutK); + } + } + + if (theLeast.size() == 1) { + pickedLayout = theLeast.iterator().next(); + } else { + long max = 0L; + // Tie breaker: Pick one with greatest ledger height. + for (SDLayout sdLayout : theLeast) { + int height = 0; + for (SDEndorser sdEndorser : layoutEndorsers.get(sdLayout)) { + height += sdEndorser.getLedgerHeight(); + } + if (height > max) { + max = height; + pickedLayout = sdLayout; + } + } + } + + final SDEndorserState sdEndorserState = new SDEndorserState(); + sdEndorserState.setPickedEndorsers(layoutEndorsers.get(pickedLayout)); + sdEndorserState.setPickedLayout(pickedLayout); + + return sdEndorserState; + }; + + public static final EndorsementSelector DEFAULT_ENDORSEMENT_SELECTION = ENDORSEMENT_SELECTION_LEAST_REQUIRED_BLOCKHEIGHT; + + /** + * Endorsement selection by random layout group and random endorsers there in. + */ + public static final EndorsementSelector ENDORSEMENT_SELECTION_RANDOM = sdChaindcode -> { + List layouts = sdChaindcode.getLayouts(); + + SDLayout pickedLayout = layouts.get(0); + + if (layouts.size() > 1) { // more than one pick a random one. + pickedLayout = layouts.get(random.nextInt(layouts.size())); + } + + Map retMap = new HashMap<>(); //hold results. + + for (SDGroup group : pickedLayout.getSDLGroups()) { // go through groups getting random required endorsers + List endorsers = new ArrayList<>(group.getEndorsers()); + int required = group.getStillRequired(); // what's needed in that group. + Collections.shuffle(endorsers); // randomize. + List sdEndorsers = endorsers.subList(0, required); // pick top endorsers. + sdEndorsers.forEach(sdEndorser -> { + retMap.putIfAbsent(sdEndorser.getEndpoint(), sdEndorser); // put if endpoint is not in there already. + }); + } + + final SDEndorserState sdEndorserState = new SDEndorserState(); //returned result. + sdEndorserState.setPickedEndorsers(retMap.values()); + sdEndorserState.setPickedLayout(pickedLayout); + + return sdEndorserState; + }; + + public static class SDChaindcode { + final String name; + final List layouts; + + SDChaindcode(SDChaindcode sdChaindcode) { + name = sdChaindcode.name; + layouts = new LinkedList<>(); + sdChaindcode.layouts.forEach(sdLayout -> layouts.add(new SDLayout(sdLayout))); + } + + SDChaindcode(String name, List layouts) { + this.name = name; + this.layouts = layouts; + } + + public List getLayouts() { + return Collections.unmodifiableList(layouts); + } + + // returns number of layouts left. + int ignoreList(Collection names) { + if (names != null && !names.isEmpty()) { + layouts.removeIf(sdLayout -> !sdLayout.ignoreList(names)); + } + return layouts.size(); + } + + int ignoreListSDEndorser(Collection sdEndorsers) { + if (sdEndorsers != null && !sdEndorsers.isEmpty()) { + layouts.removeIf(sdLayout -> !sdLayout.ignoreListSDEndorser(sdEndorsers)); + } + return layouts.size(); + } + + boolean endorsedList(Collection sdEndorsers) { + boolean ret = false; + + for (SDLayout sdLayout : layouts) { + if (sdLayout.endorsedList(sdEndorsers)) { + ret = true; + } + } + return ret; + } + + // return the set needed or null if the policy was not meet. + Collection meetsEndorsmentPolicy(Set endpoints) { + Collection ret = null; // not meet. + + for (SDLayout sdLayout : layouts) { + final Collection needed = sdLayout.meetsEndorsmentPolicy(endpoints); + + if (needed != null && (ret == null || ret.size() > needed.size())) { + ret = needed; // needed is less so lets go with that. + } + } + return ret; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(1000); + sb.append("SDChaindcode(name: ").append(name); + if (null != layouts && !layouts.isEmpty()) { + sb.append(", layouts: ["); + String sep = ""; + for (SDLayout sdLayout : layouts) { + sb.append(sep).append(sdLayout + ""); + sep = " ,"; + } + sb.append("]"); + } + sb.append(")"); + return sb.toString(); + } + } + + public static class SDLayout { + final List groups = new LinkedList<>(); + + SDLayout() { } + + //Copy constructor + SDLayout(SDLayout sdLayout) { + for (SDGroup group : sdLayout.groups) { + new SDGroup(group); + } + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(1000); + + sb.append("SDLayout: {"); + + if (!groups.isEmpty()) { + sb.append("groups: ["); + String sep2 = ""; + for (SDGroup group : groups) { + sb.append(sep2).append(group.toString()); + sep2 = ", "; + } + sb.append("]"); + } else { + sb.append(", groups: []"); + } + sb.append("}"); + + return sb.toString(); + } + + //return true if the groups still exist to get endorsement. + boolean ignoreList(Collection names) { + boolean ret = true; + HashSet bnames = new HashSet<>(names); + + for (SDGroup group : groups) { + if (!group.ignoreList(bnames)) { + ret = false; // group can no longer be satisfied. + } + } + return ret; + } + + boolean ignoreListSDEndorser(Collection names) { + boolean ret = true; + HashSet bnames = new HashSet<>(names); + + for (SDGroup group : groups) { + if (!group.ignoreListSDEndorser(bnames)) { + ret = false; // group can no longer be satisfied. + } + } + return ret; + } + + // endorsement has been meet. + boolean endorsedList(Collection sdEndorsers) { + int endorsementMeet = 0; + for (SDGroup group : groups) { + if (group.endorsedList(sdEndorsers)) { + ++endorsementMeet; + } + } + return endorsementMeet >= groups.size(); + } + + // Returns null when not meet and endorsers needed if it is. + Collection meetsEndorsmentPolicy(Set endpoints) { + Set ret = new HashSet<>(); + + for (SDGroup group : groups) { + Collection sdEndorsers = group.meetsEndorsmentPolicy(endpoints, null); + if (null == sdEndorsers) { + return null; // group was not satisfied + } + ret.addAll(sdEndorsers); // add all these endorsers. + } + + return ret; + } + + public Collection getSDLGroups() { + return new ArrayList<>(groups); + } + + public class SDGroup { + final int required; // the number that's needed for the group to be endorsed. + final List endorsers = new LinkedList<>(); + private final String name; // name of the groups - just for debug sake. + private int endorsed = 0; // number that have been now endorsed. + + { + SDLayout.this.groups.add(this); + } + + SDGroup(String name, int required, List endorsers) { + this.name = name; + this.required = required; + this.endorsers.addAll(endorsers); + } + + SDGroup(SDGroup group) { //copy constructor + name = group.name; + required = group.required; + endorsers.addAll(group.endorsers); + endorsed = 0; // on copy reset to no endorsements + } + + public int getStillRequired() { + return required - endorsed; + } + + public String getName() { + return name; + } + + public int getRequired() { + return required; + } + + public Collection getEndorsers() { + return new ArrayList<>(endorsers); + } + + //returns true if there are still sufficent endorsers for this group. + boolean ignoreList(Collection names) { + HashSet bnames = new HashSet<>(names); + endorsers.removeIf(endorser -> bnames.contains(endorser.getEndpoint())); + return endorsers.size() >= required; + } + + //returns true if there are still sufficent endorsers for this group. + boolean ignoreListSDEndorser(Collection sdEndorsers) { + HashSet bnames = new HashSet<>(sdEndorsers); + endorsers.removeIf(endorser -> bnames.contains(endorser)); + return endorsers.size() >= required; + } + + // retrun true if th endorsements have been meet. + boolean endorsedList(Collection sdEndorsers) { + //This is going to look odd so here goes: Service discovery can't guarantee the endpoint certs are valid + // and so there may be multiple endpoints with different MSP ids. However if we have gotten an + // endorsement from an endpoint that means it's been satisfied and can be removed. + + if (endorsed >= required) { + return true; + } + if (!sdEndorsers.isEmpty()) { + final Set enames = new HashSet<>(sdEndorsers.size()); + sdEndorsers.forEach(sdEndorser -> enames.add(sdEndorser.getEndpoint())); + + endorsers.removeIf(endorser -> { + if (enames.contains(endorser.getEndpoint())) { + endorsed = Math.min(required, endorsed++); + return true; // remove it. + } + return false; // needs to stay in the list. + }); + } + + return endorsed >= required; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(512); + sb.append("SDGroup: { name: ").append(name).append(", required: ").append(required); + + if (!endorsers.isEmpty()) { + sb.append(", endorsers: ["); + String sep2 = ""; + for (SDEndorser sdEndorser : endorsers) { + sb.append(sep2).append(sdEndorser.toString()); + sep2 = ", "; + } + sb.append("]"); + } else { + sb.append(", endorsers: []"); + } + sb.append("}"); + return sb.toString(); + } + + // Returns + Collection meetsEndorsmentPolicy(Set allEndorsed, Collection requiredYet) { + Set ret = new HashSet<>(this.endorsers.size()); + for (SDEndorser hasBeenEndorsed : allEndorsed) { + for (SDEndorser sdEndorser : endorsers) { + if (hasBeenEndorsed.equals(sdEndorser)) { + ret.add(sdEndorser); + if (ret.size() >= required) { + return ret; // got what we needed. + } + } + } + } + if (null != requiredYet) { + for (SDEndorser sdEndorser : endorsers) { + if (!allEndorsed.contains(sdEndorser)) { + requiredYet.add(sdEndorser); + } + } + } + return null; // group has not meet endorsement. + } + } + + void addGroup(String key, int required, List endorsers) { + new SDGroup(key, required, endorsers); + } + } + + public static class SDEndorserState { + private Collection sdEndorsers = new ArrayList<>(); + private SDLayout pickedLayout; + + public void setPickedEndorsers(Collection sdEndorsers) { + this.sdEndorsers = sdEndorsers; + } + + Collection getSdEndorsers() { + return sdEndorsers; + } + + public void setPickedLayout(SDLayout pickedLayout) { + this.pickedLayout = pickedLayout; + } + + public SDLayout getPickedLayout() { + return pickedLayout; + } + } + + public static class SDEndorser { + private List chaincodesList; + // private final Protocol.Peer proto; + private String endPoint = null; + private String name = null; + private String mspid; + private long ledgerHeight = -1L; + private final Collection tlsCerts; + private final Collection tlsIntermediateCerts; + private final boolean asLocalhost; + + SDEndorser() { // for testing only + tlsCerts = null; + tlsIntermediateCerts = null; + asLocalhost = false; + } + + SDEndorser(Protocol.Peer peerRet, Collection tlsCerts, Collection tlsIntermediateCerts, boolean asLocalhost) { + this.tlsCerts = tlsCerts; + this.tlsIntermediateCerts = tlsIntermediateCerts; + this.asLocalhost = asLocalhost; + + parseEndpoint(peerRet); + parseLedgerHeight(peerRet); + parseIdentity(peerRet); + } + + Collection getTLSCerts() { + return tlsCerts; + } + + Collection getTLSIntermediateCerts() { + return tlsIntermediateCerts; + } + + public String getName() { + return name; + } + + public String getEndpoint() { + return endPoint; + } + + public long getLedgerHeight() { + return ledgerHeight; + } + + private void parseIdentity(Protocol.Peer peerRet) { + try { + Identities.SerializedIdentity serializedIdentity = Identities.SerializedIdentity.parseFrom(peerRet.getIdentity()); + mspid = serializedIdentity.getMspid(); + } catch (InvalidProtocolBufferException e) { + throw new InvalidProtocolBufferRuntimeException(e); + } + } + + private String parseEndpoint(Protocol.Peer peerRet) throws InvalidProtocolBufferRuntimeException { + if (null == endPoint) { + try { + Message.Envelope membershipInfo = peerRet.getMembershipInfo(); + final ByteString membershipInfoPayloadBytes = membershipInfo.getPayload(); + final Message.GossipMessage gossipMessageMemberInfo = Message.GossipMessage.parseFrom(membershipInfoPayloadBytes); + + if (Message.GossipMessage.ContentCase.ALIVE_MSG.getNumber() != gossipMessageMemberInfo.getContentCase().getNumber()) { + throw new RuntimeException(format("Error %s", "bad")); + } + Message.AliveMessage aliveMsg = gossipMessageMemberInfo.getAliveMsg(); + name = aliveMsg.getMembership().getEndpoint(); + if (name != null) { + if (asLocalhost) { + endPoint = "localhost" + name.substring(name.lastIndexOf(':')); + } else { + endPoint = name.toLowerCase().trim(); //makes easier on comparing. + } + } + } catch (InvalidProtocolBufferException e) { + throw new InvalidProtocolBufferRuntimeException(e); + } + } + return endPoint; + } + + private long parseLedgerHeight(Protocol.Peer peerRet) throws InvalidProtocolBufferRuntimeException { + if (-1L == ledgerHeight) { + try { + Message.Envelope stateInfo = peerRet.getStateInfo(); + final Message.GossipMessage stateInfoGossipMessage = Message.GossipMessage.parseFrom(stateInfo.getPayload()); + Message.GossipMessage.ContentCase contentCase = stateInfoGossipMessage.getContentCase(); + if (contentCase.getNumber() != Message.GossipMessage.ContentCase.STATE_INFO.getNumber()) { + throw new RuntimeException("" + contentCase.getNumber()); + } + Message.StateInfo stateInfo1 = stateInfoGossipMessage.getStateInfo(); + ledgerHeight = stateInfo1.getProperties().getLedgerHeight(); + + this.chaincodesList = stateInfo1.getProperties().getChaincodesList(); + } catch (InvalidProtocolBufferException e) { + throw new InvalidProtocolBufferRuntimeException(e); + } + } + + return ledgerHeight; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + + if (!(obj instanceof SDEndorser)) { + return false; + } + SDEndorser other = (SDEndorser) obj; + return Objects.equals(mspid, other.getMspid()) && Objects.equals(endPoint, other.getEndpoint()); + } + + @Override + public int hashCode() { + return Objects.hash(mspid, endPoint); + } + + Set getChaincodeNames() { + if (chaincodesList == null) { + return Collections.emptySet(); + } + + HashSet ret = new HashSet<>(chaincodesList.size()); + + chaincodesList.forEach(chaincode -> ret.add(chaincode.getName())); + return ret; + } + + public String getMspid() { + return mspid; + } + + @Override + public String toString() { + return "SDEndorser-" + mspid + "-" + endPoint; + } + } + + private static List topNbyHeight(int required, List endorsers) { + ArrayList ret = new ArrayList<>(endorsers); + ret.sort(Comparator.comparingLong(SDEndorser::getLedgerHeight)); + return ret.subList(Math.max(ret.size() - required, 0), ret.size()); + } + + private ScheduledFuture seviceDiscovery = null; + + private static final int SERVICE_DISCOVER_FREQ_SECONDS = config.getServiceDiscoveryFreqSeconds(); + + void run() { + if (channel.isShutdown() || SERVICE_DISCOVER_FREQ_SECONDS < 1) { + return; + } + + if (seviceDiscovery == null) { + seviceDiscovery = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = Executors.defaultThreadFactory().newThread(r); + t.setDaemon(true); + return t; + }).scheduleAtFixedRate(() -> { + logger.debug(format("Channel %s starting service rediscovery after %d seconds.", channelName, SERVICE_DISCOVER_FREQ_SECONDS)); + fullNetworkDiscovery(true); + + }, SERVICE_DISCOVER_FREQ_SECONDS, SERVICE_DISCOVER_FREQ_SECONDS, TimeUnit.SECONDS); + } + } + + SDNetwork fullNetworkDiscovery(boolean force) { + if (channel.isShutdown()) { + return null; + } + logger.trace(format("Full network discovery force: %b", force)); + try { + SDNetwork osdNetwork = sdNetwork; + SDNetwork lsdNetwork = networkDiscovery(transactionContext.retryTransactionSameContext(), force); + if (channel.isShutdown() || null == lsdNetwork) { + return null; + } + + if (osdNetwork != lsdNetwork) { // means it changed. + final Set chaincodesNames = lsdNetwork.getChaincodesNames(); + List> lcc = new LinkedList<>(); + chaincodesNames.forEach(s -> { + List lc = new LinkedList<>(); + lc.add(new ServiceDiscoveryChaincodeCalls(s)); + lcc.add(lc); + }); + chaindcodeMap = discoverEndorserEndpoints(transactionContext.retryTransactionSameContext(), lcc); + if (channel.isShutdown()) { + return null; + } + + channel.sdUpdate(lsdNetwork); + } + + return lsdNetwork; + } catch (Exception e) { + logger.warn("Service discovery got error:" + e.getMessage(), e); + } finally { + logger.trace("Full network rediscovery completed."); + } + return null; + } + + void shutdown() { + logger.trace("Service discovery shutdown."); + try { + final ScheduledFuture lseviceDiscovery = seviceDiscovery; + seviceDiscovery = null; + if (null != lseviceDiscovery) { + lseviceDiscovery.cancel(true); + } + } catch (Exception e) { + logger.error(e); + //best effort. + } + } + + @Override + protected void finalize() throws Throwable { + shutdown(); + super.finalize(); + } + + public interface EndorsementSelector { + SDEndorserState endorserSelector(SDChaindcode sdChaindcode); + + EndorsementSelector ENDORSEMENT_SELECTION_RANDOM = ServiceDiscovery.ENDORSEMENT_SELECTION_RANDOM; + EndorsementSelector ENDORSEMENT_SELECTION_LEAST_REQUIRED_BLOCKHEIGHT = ServiceDiscovery.ENDORSEMENT_SELECTION_LEAST_REQUIRED_BLOCKHEIGHT; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `ltransactionContext.getIdentity()` could be null and is dereferenced at line 454. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Map ServiceDiscovery.discoverEndorserEndpoints(TransactionContext,LinkedList) + +### Procedure Id: +org.hyperledger.fabric.sdk.ServiceDiscovery.discoverEndorserEndpoints(org.hyperledger.fabric.sdk.tra.a24d66cdc1df4137709b32c8bc37fc30 + +### File: +src/main/java/org/hyperledger/fabric/sdk/ServiceDiscovery.java + +### Key: +ServiceDiscovery.java|discoverEndorserEndpoints|NULL_DEREFERENCE + +### Node Key: +98e48d8af36063b905de6168fc1ae17c + +### Hash: +5aa2d75cb683d372419fe617a06e7dd0 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9368/instruction.md b/inferredbugs-9368/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bb2859ca9cc22eb83bb055a24242d51f61d38a0f --- /dev/null +++ b/inferredbugs-9368/instruction.md @@ -0,0 +1,522 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fabric-sdk-java +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2016 IBM, DTCC, Fujitsu Australia Software Technology - All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.hyperledger.fabric.sdk; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Properties; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import io.netty.util.internal.StringUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hyperledger.fabric.protos.peer.EventsGrpc; +import org.hyperledger.fabric.protos.peer.PeerEvents; +import org.hyperledger.fabric.sdk.exception.CryptoException; +import org.hyperledger.fabric.sdk.exception.EventHubException; +import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; +import org.hyperledger.fabric.sdk.helper.Config; +import org.hyperledger.fabric.sdk.transaction.ProtoUtils; +import org.hyperledger.fabric.sdk.transaction.TransactionContext; + +import static java.lang.String.format; +import static org.hyperledger.fabric.sdk.helper.Utils.checkGrpcUrl; + +/** + * Class to manage fabric events. + *

    + * Feeds Channel event queues with events + */ + +public class EventHub implements Serializable { + private static final long serialVersionUID = 2882609588201108148L; + private static final Log logger = LogFactory.getLog(EventHub.class); + private static final Config config = Config.getConfig(); + private static final long EVENTHUB_CONNECTION_WAIT_TIME = config.getEventHubConnectionWaitTime(); + + private final transient ExecutorService executorService; + + private final String url; + private final String name; + private final Properties properties; + private transient ManagedChannel managedChannel; + private transient boolean connected = false; + private transient EventsGrpc.EventsStub events; + private transient StreamObserver sender; + /** + * Event queue for all events from eventhubs in the channel + */ + private transient Channel.ChannelEventQue eventQue; + private transient long connectedTime = 0L; // 0 := never connected + private transient boolean shutdown = false; + private Channel channel; + private transient TransactionContext transactionContext; + + /** + * Get disconnected time. + * + * @return Time in milli seconds disconnect occurred. Zero if never disconnected + */ + public long getDisconnectedTime() { + return disconnectedTime; + } + + private long disconnectedTime; + + /** + * Is event hub connected. + * + * @return boolean if true event hub is connected. + */ + public boolean isConnected() { + return connected; + } + + /** + * Get last connect time. + * + * @return Time in milli seconds the event hub last connected. Zero if never connected. + */ + public long getConnectedTime() { + return connectedTime; + } + + /** + * Get last attempt time to connect the event hub. + * + * @return Last attempt time to connect the event hub in milli seconds. Zero when never attempted. + */ + + public long getLastConnectedAttempt() { + return lastConnectedAttempt; + } + + private long lastConnectedAttempt; + + EventHub(String name, String grpcURL, ExecutorService executorService, Properties properties) throws InvalidArgumentException { + + Exception e = checkGrpcUrl(grpcURL); + if (e != null) { + throw new InvalidArgumentException("Bad event hub url.", e); + + } + + if (StringUtil.isNullOrEmpty(name)) { + throw new InvalidArgumentException("Invalid name for eventHub"); + } + + this.url = grpcURL; + this.name = name; + this.executorService = executorService; + this.properties = properties == null ? null : (Properties) properties.clone(); //keep our own copy. + } + + /** + * Create a new instance. + * + * @param name + * @param url + * @param properties + * @return + */ + + static EventHub createNewInstance(String name, String url, ExecutorService executorService, Properties properties) throws InvalidArgumentException { + return new EventHub(name, url, executorService, properties); + } + + /** + * Event hub name + * + * @return event hub name + */ + + public String getName() { + return name; + } + + /** + * Event hub properties + * + * @return Event hub properties + * @see HFClient#newEventHub(String, String, Properties) + */ + public Properties getProperties() { + return properties == null ? null : (Properties) properties.clone(); + } + + boolean connect() throws EventHubException { + + if (transactionContext == null) { + throw new EventHubException("Eventhub reconnect failed with no user context"); + } + + return connect(transactionContext); + + } + + private transient StreamObserver eventStream = null; // Saved here to avoid potential garbage collection + + synchronized boolean connect(final TransactionContext transactionContext) throws EventHubException { + if (connected) { + logger.warn(format("%s already connected.", toString())); + return true; + } + eventStream = null; + + final CountDownLatch finishLatch = new CountDownLatch(1); + + logger.debug(format("EventHub %s is connecting.", name)); + + lastConnectedAttempt = System.currentTimeMillis(); + + managedChannel = new Endpoint(url, properties).getChannelBuilder().build(); + + events = EventsGrpc.newStub(managedChannel); + + final ArrayList threw = new ArrayList<>(); + + final StreamObserver eventStreamLocal = new StreamObserver() { + @Override + public void onNext(PeerEvents.Event event) { + + logger.debug(format("EventHub %s got event type: %s", EventHub.this.name, event.getEventCase().name())); + + if (event.getEventCase() == PeerEvents.Event.EventCase.BLOCK) { + try { + eventQue.addBEvent(new BlockEvent(EventHub.this, event)); //add to channel queue + } catch (InvalidProtocolBufferException e) { + EventHubException eventHubException = new EventHubException(format("%s onNext error %s", this, e.getMessage()), e); + logger.error(eventHubException.getMessage()); + threw.add(eventHubException); + } + } else if (event.getEventCase() == PeerEvents.Event.EventCase.REGISTER) { + + connected = true; + connectedTime = System.currentTimeMillis(); + finishLatch.countDown(); + } + } + + @Override + public void onError(Throwable t) { + if (shutdown) { //IF we're shutdown don't try anything more. + logger.trace(format("%s was shutdown.", EventHub.this.toString())); + connected = false; + eventStream = null; + finishLatch.countDown(); + return; + } + + final boolean isTerminated = managedChannel.isTerminated(); + final boolean isChannelShutdown = managedChannel.isShutdown(); + + logger.error(format("%s terminated is %b shutdown is %b has error %s ", EventHub.this.toString(), isTerminated, isChannelShutdown, + t.getMessage()), new EventHubException(t)); + threw.add(t); + finishLatch.countDown(); + + // logger.error("Error in stream: " + t.getMessage(), new EventHubException(t)); + if (t instanceof StatusRuntimeException) { + StatusRuntimeException sre = (StatusRuntimeException) t; + Status sreStatus = sre.getStatus(); + logger.error(format("%s :StatusRuntimeException Status %s. Description %s ", EventHub.this, sreStatus + "", sreStatus.getDescription())); + if (sre.getStatus().getCode() == Status.Code.INTERNAL || sre.getStatus().getCode() == Status.Code.UNAVAILABLE) { + + connected = false; + eventStream = null; + disconnectedTime = System.currentTimeMillis(); + try { + if (!isChannelShutdown) { + managedChannel.shutdownNow(); + } + if (null != disconnectedHandler) { + try { + disconnectedHandler.disconnected(EventHub.this); + } catch (Exception e) { + logger.warn(format("Eventhub %s %s", EventHub.this.name, e.getMessage()), e); + eventQue.eventError(e); + } + } + } catch (Exception e) { + logger.warn(format("Eventhub %s Failed shutdown msg: %s", EventHub.this.name, e.getMessage()), e); + } + } + } + + } + + @Override + public void onCompleted() { + + logger.warn(format("Stream completed %s", EventHub.this.toString())); + finishLatch.countDown(); + + } + }; + + sender = events.chat(eventStreamLocal); + try { + blockListen(transactionContext); + } catch (CryptoException e) { + throw new EventHubException(e); + } + + try { + if (!finishLatch.await(EVENTHUB_CONNECTION_WAIT_TIME, TimeUnit.MILLISECONDS)) { + EventHubException evh = new EventHubException(format("EventHub %s failed to connect in %s ms.", name, EVENTHUB_CONNECTION_WAIT_TIME)); + logger.debug(evh.getMessage(), evh); + + throw evh; + } + logger.trace(format("Eventhub %s Done waiting for reply!", name)); + + } catch (InterruptedException e) { + logger.error(e); + } + + if (!threw.isEmpty()) { + eventStream = null; + connected = false; + Throwable t = threw.iterator().next(); + + EventHubException evh = new EventHubException(t.getMessage(), t); + logger.error(format("EventHub %s Error in stream. error: " + t.getMessage(), toString()), evh); + throw evh; + + } + + logger.debug(format("Eventhub %s connect is done with connect status: %b ", name, connected)); + + if (connected) { + eventStream = eventStreamLocal; + } + + return connected; + + } + + private void blockListen(TransactionContext transactionContext) throws CryptoException { + + this.transactionContext = transactionContext; + + PeerEvents.Register register = PeerEvents.Register.newBuilder() + .addEvents(PeerEvents.Interest.newBuilder().setEventType(PeerEvents.EventType.BLOCK).build()).build(); + ByteString blockEventByteString = PeerEvents.Event.newBuilder().setRegister(register) + .setCreator(transactionContext.getIdentity().toByteString()) + .setTimestamp(ProtoUtils.getCurrentFabricTimestamp()) + .build().toByteString(); + PeerEvents.SignedEvent signedBlockEvent = PeerEvents.SignedEvent.newBuilder() + .setEventBytes(blockEventByteString) + .setSignature(transactionContext.signByteString(blockEventByteString.toByteArray())) + .build(); + sender.onNext(signedBlockEvent); + } + + /** + * Get the GRPC URL used to connect. + * + * @return GRPC URL. + */ + public String getUrl() { + return url; + } + + /** + * Set the channel queue that will receive events + * + * @param eventQue + */ + void setEventQue(Channel.ChannelEventQue eventQue) { + this.eventQue = eventQue; + } + + @Override + public String toString() { + return "EventHub:" + getName(); + } + + public void shutdown() { + shutdown = true; + connected = false; + disconnectedHandler = null; + channel = null; + eventStream = null; + managedChannel.shutdownNow(); + } + + void setChannel(Channel channel) throws InvalidArgumentException { + if (channel == null) { + throw new InvalidArgumentException("setChannel Channel can not be null"); + } + + if (null != this.channel) { + throw new InvalidArgumentException(format("Can not add event hub %s to channel %s because it already belongs to channel %s.", + name, channel.getName(), this.channel.getName())); + } + + this.channel = channel; + } + + /** + * Eventhub disconnection notification interface + */ + public interface EventHubDisconnected { + + /** + * Called when a disconnect is detected. + * + * @param eventHub + * @throws EventHubException + */ + void disconnected(EventHub eventHub) throws EventHubException; + + } + + /** + * Default reconnect event hub implementation. Applications are free to replace + */ + + protected transient EventHubDisconnected disconnectedHandler = new EventHub.EventHubDisconnected() { + @Override + public synchronized void disconnected(final EventHub eventHub) throws EventHubException { + logger.info(format("Detected disconnect %s", eventHub.toString())); + + if (eventHub.connectedTime == 0) { //means event hub never connected + logger.error(format("%s failed on first connect no retries", eventHub.toString())); + + eventHub.setEventHubDisconnectedHandler(null); //don't try again + + //event hub never connected. + throw new EventHubException(format("%s never connected.", eventHub.toString())); + } + + executorService.execute(() -> { + + try { + Thread.sleep(500); + + if (eventHub.connect()) { + logger.info(format("Successful reconnect %s", eventHub.toString())); + } else { + logger.info(format("Failed reconnect %s", eventHub.toString())); + } + + } catch (Exception e) { + + logger.debug(format("Failed %s to reconnect. %s", toString(), e.getMessage())); + + } + + }); + + } + }; + + /** + * Set class to handle Event hub disconnects + * + * @param newEventHubDisconnectedHandler New handler to replace. If set to null no retry will take place. + * @return the old handler. + */ + + public EventHubDisconnected setEventHubDisconnectedHandler(EventHubDisconnected newEventHubDisconnectedHandler) { + EventHubDisconnected ret = disconnectedHandler; + disconnectedHandler = newEventHubDisconnectedHandler; + return ret; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `__new(org.hyperledger.fabric.sdk.Endpoint).getChannelBuilder()` could be null and is dereferenced at line 192. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean EventHub.connect(TransactionContext) + +### Procedure Id: +org.hyperledger.fabric.sdk.EventHub.connect(org.hyperledger.fabric.sdk.transaction.TransactionContex.2a93b47644826e03ed4e2ded4fd1746f + +### File: +src/main/java/org/hyperledger/fabric/sdk/EventHub.java + +### Key: +EventHub.java|connect|NULL_DEREFERENCE + +### Node Key: +4e40cf4b057cfc6102ca2104f1fe79e1 + +### Hash: +a6014e12d63eead4361da87f5551be12 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9411/instruction.md b/inferredbugs-9411/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6176507999650895f1b55bea8be9e2895285ff6d --- /dev/null +++ b/inferredbugs-9411/instruction.md @@ -0,0 +1,239 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** SonarTsPlugin +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.pablissimo.sonar; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.utils.System2; +import org.sonar.api.utils.TempFolder; +import org.sonar.api.utils.command.Command; +import org.sonar.api.utils.command.CommandExecutor; +import org.sonar.api.utils.command.StringStreamConsumer; + +public class TsLintExecutorImpl implements TsLintExecutor { + public static final int MAX_COMMAND_LENGTH = 4096; + private static final Logger LOG = LoggerFactory.getLogger(TsLintExecutorImpl.class); + + private boolean mustQuoteSpaceContainingPaths = false; + private TempFolder tempFolder; + + public TsLintExecutorImpl(System2 system, TempFolder tempFolder) { + this.mustQuoteSpaceContainingPaths = system.isOsWindows(); + this.tempFolder = tempFolder; + } + + private String preparePath(String path) { + if (path == null) { + return null; + } + else if (path.contains(" ") && this.mustQuoteSpaceContainingPaths) { + return '"' + path + '"'; + } + else { + return path; + } + } + + private Command getBaseCommand(TsLintExecutorConfig config, String tempPath) { + Command command = + Command + .create("node") + .addArgument(this.preparePath(config.getPathToTsLint())) + .addArgument("--format") + .addArgument("json"); + + String rulesDir = config.getRulesDir(); + if (rulesDir != null && rulesDir.length() > 0) { + command + .addArgument("--rules-dir") + .addArgument(this.preparePath(rulesDir)); + } + + if (tempPath != null && tempPath.length() > 0) { + command + .addArgument("--out") + .addArgument(this.preparePath(tempPath)); + } + + command + .addArgument("--config") + .addArgument(this.preparePath(config.getConfigFile())) + .setNewShell(false); + + return command; + } + + public List execute(TsLintExecutorConfig config, List files) { + if (config == null) { + throw new IllegalArgumentException("config"); + } + + if (files == null) { + throw new IllegalArgumentException("files"); + } + + // New up a command that's everything we need except the files to process + // We'll use this as our reference for chunking up files + File tslintOutputFile = this.tempFolder.newFile(); + String tslintOutputFilePath = tslintOutputFile.getAbsolutePath(); + + LOG.debug("Using a temporary path for TsLint output: " + tslintOutputFilePath); + + int baseCommandLength = getBaseCommand(config, tslintOutputFilePath).toCommandLine().length(); + int availableForBatching = MAX_COMMAND_LENGTH - baseCommandLength; + + List> batches = new ArrayList>(); + List currentBatch = new ArrayList(); + batches.add(currentBatch); + + int currentBatchLength = 0; + for (int i = 0; i < files.size(); i++) { + String nextPath = this.preparePath(files.get(i).trim()); + + // +1 for the space we'll be adding between filenames + if (currentBatchLength + nextPath.length() + 1 > availableForBatching) { + // Too long to add to this batch, create new + currentBatch = new ArrayList(); + currentBatchLength = 0; + batches.add(currentBatch); + } + + currentBatch.add(nextPath); + currentBatchLength += nextPath.length() + 1; + } + + LOG.debug("Split " + files.size() + " files into " + batches.size() + " batches for processing"); + + StringStreamConsumer stdOutConsumer = new StringStreamConsumer(); + StringStreamConsumer stdErrConsumer = new StringStreamConsumer(); + + List toReturn = new ArrayList(); + + for (int i = 0; i < batches.size(); i++) { + StringBuilder outputBuilder = new StringBuilder(); + + List thisBatch = batches.get(i); + + Command thisCommand = getBaseCommand(config, tslintOutputFilePath); + + for (int fileIndex = 0; fileIndex < thisBatch.size(); fileIndex++) { + thisCommand.addArgument(thisBatch.get(fileIndex)); + } + + LOG.debug("Executing TsLint with command: " + thisCommand.toCommandLine()); + + // Timeout is specified per file, not per batch (which can vary a lot) + // so multiply it up + this.createExecutor().execute(thisCommand, stdOutConsumer, stdErrConsumer, config.getTimeoutMs() * thisBatch.size()); + + try { + BufferedReader reader = this.getBufferedReaderForFile(tslintOutputFile); + + String str; + while ((str = reader.readLine()) != null) { + outputBuilder.append(str); + } + + reader.close(); + + toReturn.add(outputBuilder.toString()); + } + catch (IOException ex) { + LOG.error("Failed to re-read TsLint output from " + tslintOutputFilePath, ex); + } + } + + return toReturn; + } + + protected BufferedReader getBufferedReaderForFile(File file) throws IOException { + return new BufferedReader( + new InputStreamReader( + new FileInputStream(file), "UTF8")); + } + + protected CommandExecutor createExecutor() { + return CommandExecutor.create(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `getBufferedReaderForFile(...)` at line 136 is not released after line 147. +**Note**: potential exception at line 139 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List TsLintExecutorImpl.execute(TsLintExecutorConfig,List) + +### Procedure Id: +com.pablissimo.sonar.TsLintExecutorImpl.execute(com.pablissimo.sonar.TsLintExecutorConfig,java.util..64f93eeea025c4238165949390572c3c + +### File: +src/main/java/com/pablissimo/sonar/TsLintExecutorImpl.java + +### Key: +TsLintExecutorImpl.java|execute|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +9392dfa72c2dee3966196b2e6655be8a + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9416/instruction.md b/inferredbugs-9416/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dd6a73a4037ee8bd9d2e70680f3b767338cced6f --- /dev/null +++ b/inferredbugs-9416/instruction.md @@ -0,0 +1,485 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nutzboot +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nutz.boot; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; + +import org.nutz.boot.aware.AppContextAware; +import org.nutz.boot.aware.ClassLoaderAware; +import org.nutz.boot.aware.EnvHolderAware; +import org.nutz.boot.aware.IocAware; +import org.nutz.boot.aware.ResourceLoaderAware; +import org.nutz.boot.banner.SimpleBannerPrinter; +import org.nutz.boot.config.ConfigureLoader; +import org.nutz.boot.config.impl.PropertiesConfigureLoader; +import org.nutz.boot.env.SystemPropertiesEnvHolder; +import org.nutz.boot.ioc.IocLoaderProvider; +import org.nutz.boot.resource.ResourceLoader; +import org.nutz.boot.resource.impl.SimpleResourceLoader; +import org.nutz.boot.tools.PropDocReader; +import org.nutz.ioc.Ioc2; +import org.nutz.ioc.IocLoader; +import org.nutz.ioc.ObjectProxy; +import org.nutz.ioc.impl.NutIoc; +import org.nutz.ioc.loader.annotation.AnnotationIocLoader; +import org.nutz.ioc.loader.annotation.IocBean; +import org.nutz.ioc.loader.combo.ComboIocLoader; +import org.nutz.lang.Lang; +import org.nutz.lang.Mirror; +import org.nutz.lang.Stopwatch; +import org.nutz.lang.Streams; +import org.nutz.lang.Strings; +import org.nutz.lang.util.LifeCycle; +import org.nutz.log.Log; +import org.nutz.log.LogAdapter; +import org.nutz.log.Logs; +import org.nutz.mvc.annotation.IocBy; + +/** + * NutzBoot的主体 + * @author wendal + * + */ +public class NbApp extends Thread { + + /** + * 日志属性要等日志适配器准备好了才能加载,这里不可以使用Logs.get(); + */ + protected static Log log; + + /** + * 命令行参数 + */ + protected String[] args; + + /** + * 是否允许命令行下的 -Dxxx.xxx.xxx=转为配置参数 + */ + protected boolean allowCommandLineProperties = true; + + /** + * 是否打印配置文档 + */ + protected boolean printProcDoc; + + /** + * 主上下文 + */ + protected AppContext ctx; + + /** + * Starter共享的IocLoader + */ + protected AnnotationIocLoader starterIocLoader; + + /** + * Starter类列表 + */ + protected List> starterClasses; + + protected boolean prepared; + + protected Object lock = new Object(); + + /** + * 创建一个NbApp,把调用本构造方法的类作为mainClass + */ + public NbApp() { + ctx = AppContext.getDefault(); + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + /** + * 基于mainClass创建一个NbApp + * @param mainClass 主启动类 + */ + public NbApp(Class mainClass) { + ctx = AppContext.getDefault(); + setMainClass(mainClass); + } + + public NbApp(AppContext ctx) { + this.ctx = ctx; + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + public NbApp(AppContext ctx, Class mainClass) { + this.ctx = ctx; + setMainClass(mainClass); + } + + /** + * 设置命令行参数,可选 + */ + public NbApp setArgs(String[] args) { + this.args = args; + return this; + } + + /** + * 设置主启动类 + */ + public NbApp setMainClass(Class mainClass) { + this.ctx.setMainClass(mainClass); + return this; + } + + /** + * 是否允许从命令行读取配置信息, 例如 java -Dnutz.ioc.async.poolSize=128 xxx.jar + * @param flag 默认允许 + */ + public NbApp setAllowCommandLineProperties(boolean flag) { + this.allowCommandLineProperties = flag; + return this; + } + + /** + * 是否打印配置文档 + */ + public NbApp setPrintProcDoc(boolean printProcDoc) { + this.printProcDoc = printProcDoc; + return this; + } + + /** + * 获取全局上下文 + * @return + */ + public AppContext getAppContext() { + return ctx; + } + + public void run() { + try { + _run(); + } catch (Throwable e) { + Logs.get().error("something happen", e); + } + } + + /** + * 启动整个NbApp + */ + public void _run() throws Exception { + Stopwatch sw = Stopwatch.begin(); + + // 各种预备操作 + this.prepare(); + + if (printProcDoc) { + PropDocReader docReader = new PropDocReader(ctx); + docReader.load(); + Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); + } + + // 依次启动 + try { + ctx.init(); + + ctx.startServers(); + + if (ctx.getMainClass().getAnnotation(IocBean.class) != null) + ctx.getIoc().get(ctx.getMainClass()); + + sw.stop(); + log.infof("NB started : %sms", sw.du()); + synchronized (lock) { + lock.wait(); + } + } + catch (Throwable e) { + log.error("something happen!!", e); + } + // 收尾 + ctx.stopServers(); + ctx.depose(); + } + + public void shutdown() { + log.info("ok, shutting down ..."); + synchronized (lock) { + lock.notify(); + } + } + + /** + * 执行预备操作 + */ + public void prepare() throws Exception { + if (prepared) + return; + // 初始化上下文 + this.prepareBasic(); + + // 打印Banner,暂时不可配置具体的类 + new SimpleBannerPrinter().printBanner(ctx); + + // 配置信息要准备好 + this.prepareConfigureLoader(); + + // 创建Ioc容器 + prepareIoc(); + + // 加载各种starter + prepareStarterClassList(); + + // 生成Starter实例 + prepareStarterInstance(); + + prepared = true; + } + + public void prepareBasic() throws Exception { + // 检查ClassLoader的情况 + if (ctx.getClassLoader() == null) + ctx.setClassLoader(NbApp.class.getClassLoader()); + + if (ctx.getEnvHolder() == null) { + ctx.setEnvHolder(new SystemPropertiesEnvHolder()); + } + + // 看看日志应该用哪个 + String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); + if (!Strings.isBlank(logAdapter)) { + Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); + } + log = Logs.get(); + // 资源加载器 + if (ctx.getResourceLoader() == null) { + ResourceLoader resourceLoader = new SimpleResourceLoader(); + aware(resourceLoader); + ctx.setResourceLoader(resourceLoader); + } + } + + public void prepareConfigureLoader() throws Exception { + if (ctx.getConfigureLoader() == null) { + String cnfLoader = ctx.getEnvHolder().get("nutz.boot.base.ConfigureLoader"); + ConfigureLoader configureLoader; + if (Strings.isBlank(cnfLoader)) { + configureLoader = new PropertiesConfigureLoader(); + } else { + configureLoader = (ConfigureLoader) ctx.getClassLoader().loadClass(cnfLoader).newInstance(); + } + configureLoader.setCommandLineProperties(allowCommandLineProperties, args); + aware(configureLoader); + ctx.setConfigureLoader(configureLoader); + if (configureLoader instanceof LifeCycle) + ((LifeCycle) configureLoader).init(); + } + } + + public void prepareIoc() throws Exception { + if (ctx.getComboIocLoader() == null) { + int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); + List args = new ArrayList<>(); + args.add("*js"); + args.add("ioc/"); + args.add("*tx"); + args.add("*async"); + args.add(""+asyncPoolSize); + args.add("*anno"); + args.add(ctx.getPackage()); + IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); + if (iocBy != null) { + String[] tmp = iocBy.args(); + ArrayList _args = new ArrayList<>(); + for (int i=0;i 0) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + } + } + ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); + } + // 用于加载Starter的IocLoader + starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); + ctx.getComboIocLoader().addLoader(starterIocLoader); + if (ctx.getIoc() == null) { + ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); + } + // 把核心对象放进ioc容器 + if (!ctx.ioc.has("appContext")){ + Ioc2 ioc2 = (Ioc2)ctx.getIoc(); + ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx)); + ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConf())); + ioc2.getIocContext().save("app", "nbApp", new ObjectProxy(this)); + } + } + + public void prepareStarterClassList() throws Exception { + starterClasses = new ArrayList<>(); + HashSet classNames = new HashSet<>(); + Enumeration _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter"); + while (_en.hasMoreElements()) { + URL url = _en.nextElement(); + log.debug("Found " + url); + try (InputStream ins = url.openStream()) { + InputStreamReader reader = new InputStreamReader(ins); + String tmp = Streams.readAndClose(reader); + if (!Strings.isBlank(tmp)) { + for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) { + String className = _tmp.trim(); + if (!classNames.add(className)) + continue; + Class klass = ctx.getClassLoader().loadClass(className); + if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) { + starterIocLoader.addClass(klass); + } + starterClasses.add(klass); + } + } + } + } + } + + public void prepareStarterInstance() { + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + obj = Mirror.me(klass).born(); + } + else { + obj = ctx.getIoc().get(klass); + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + } + + protected void aware(Object obj) { + // 需要注入AppContext + if (obj instanceof AppContextAware) { + ((AppContextAware) obj).setAppContext(ctx); + } + // 需要注入ClassLoader + if (obj instanceof ClassLoaderAware) { + ((ClassLoaderAware) obj).setClassLoader(ctx.getClassLoader()); + } + // 需要注入EnvHolder + if (obj instanceof EnvHolderAware) { + ((EnvHolderAware) obj).setEnvHolder(ctx.getEnvHolder()); + } + // 需要注入ResourceLoader + if (obj instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) obj).setResourceLoader(ctx.getResourceLoader()); + } + // 需要注入Ioc + if (obj instanceof IocAware) { + ((IocAware) obj).setIoc(ctx.getIoc()); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.nutz.boot.NbApp.prepareIoc` reads without synchronization from `this.org.nutz.boot.NbApp.starterIocLoader`. Potentially races with write in method `NbApp._run()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NbApp.prepareIoc() + +### Procedure Id: +org.nutz.boot.NbApp.prepareIoc():void.674739fecc4139c35432600c7c9226d8 + +### File: +nutzboot-starter/src/main/java/org/nutz/boot/NbApp.java + +### Key: +NbApp.java|prepareIoc|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +8353578d7c9713ca82f14e937a651f6c + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9418/instruction.md b/inferredbugs-9418/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..344c49e733c63d8f7b16d38652c763ac065dd189 --- /dev/null +++ b/inferredbugs-9418/instruction.md @@ -0,0 +1,481 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nutzboot +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nutz.boot; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; + +import org.nutz.boot.aware.AppContextAware; +import org.nutz.boot.aware.ClassLoaderAware; +import org.nutz.boot.aware.EnvHolderAware; +import org.nutz.boot.aware.IocAware; +import org.nutz.boot.aware.ResourceLoaderAware; +import org.nutz.boot.banner.SimpleBannerPrinter; +import org.nutz.boot.config.ConfigureLoader; +import org.nutz.boot.config.impl.PropertiesConfigureLoader; +import org.nutz.boot.env.SystemPropertiesEnvHolder; +import org.nutz.boot.ioc.IocLoaderProvider; +import org.nutz.boot.resource.ResourceLoader; +import org.nutz.boot.resource.impl.SimpleResourceLoader; +import org.nutz.boot.tools.PropDocReader; +import org.nutz.ioc.Ioc2; +import org.nutz.ioc.IocLoader; +import org.nutz.ioc.ObjectProxy; +import org.nutz.ioc.impl.NutIoc; +import org.nutz.ioc.loader.annotation.AnnotationIocLoader; +import org.nutz.ioc.loader.annotation.IocBean; +import org.nutz.ioc.loader.combo.ComboIocLoader; +import org.nutz.lang.Lang; +import org.nutz.lang.Mirror; +import org.nutz.lang.Stopwatch; +import org.nutz.lang.Streams; +import org.nutz.lang.Strings; +import org.nutz.lang.util.LifeCycle; +import org.nutz.log.Log; +import org.nutz.log.LogAdapter; +import org.nutz.log.Logs; +import org.nutz.mvc.annotation.IocBy; + +/** + * NutzBoot的主体 + * @author wendal + * + */ +public class NbApp extends Thread { + + /** + * 日志属性要等日志适配器准备好了才能加载,这里不可以使用Logs.get(); + */ + protected static Log log; + + /** + * 命令行参数 + */ + protected String[] args; + + /** + * 主启动器类,必须设置 + */ + protected Class mainClass; + + /** + * 是否允许命令行下的 -Dxxx.xxx.xxx=转为配置参数 + */ + protected boolean allowCommandLineProperties = true; + + /** + * 是否打印配置文档 + */ + protected boolean printProcDoc; + + /** + * 主上下文 + */ + protected AppContext ctx; + + /** + * Starter共享的IocLoader + */ + protected AnnotationIocLoader starterIocLoader; + + /** + * Starter类列表 + */ + protected List> starterClasses; + + protected boolean prepared; + + protected Object lock = new Object(); + + /** + * 创建一个NbApp,把调用本构造方法的类作为mainClass + */ + public NbApp() { + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + /** + * 基于mainClass创建一个NbApp + * @param mainClass 主启动类 + */ + public NbApp(Class mainClass) { + this.mainClass = mainClass; + } + + /** + * 设置命令行参数,可选 + */ + public NbApp setArgs(String[] args) { + this.args = args; + return this; + } + + /** + * 设置主启动类 + */ + public NbApp setMainClass(Class mainClass) { + this.mainClass = mainClass; + return this; + } + + /** + * 是否允许从命令行读取配置信息, 例如 java -Dnutz.ioc.async.poolSize=128 xxx.jar + * @param flag 默认允许 + */ + public NbApp setAllowCommandLineProperties(boolean flag) { + this.allowCommandLineProperties = flag; + return this; + } + + /** + * 是否打印配置文档 + */ + public NbApp setPrintProcDoc(boolean printProcDoc) { + this.printProcDoc = printProcDoc; + return this; + } + + /** + * 获取全局上下文 + * @return + */ + public AppContext getAppContext() { + return ctx; + } + + public void run() { + try { + _run(); + } catch (Throwable e) { + Logs.get().error("something happen", e); + } + } + + /** + * 启动整个NbApp + */ + public void _run() throws Exception { + Stopwatch sw = Stopwatch.begin(); + + // 各种预备操作 + this.prepare(); + + if (printProcDoc) { + PropDocReader docReader = new PropDocReader(ctx); + docReader.load(); + Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); + } + + // 依次启动 + try { + ctx.init(); + + ctx.startServers(); + + if (mainClass.getAnnotation(IocBean.class) != null) + ctx.getIoc().get(mainClass); + + sw.stop(); + log.infof("NB started : %sms", sw.du()); + synchronized (lock) { + lock.wait(); + } + } + catch (Throwable e) { + log.error("something happen!!", e); + } + // 收尾 + ctx.stopServers(); + ctx.depose(); + } + + public void shutdown() { + log.info("ok, shutting down ..."); + synchronized (lock) { + lock.notify(); + } + } + + /** + * 执行预备操作 + */ + public void prepare() throws Exception { + if (prepared) + return; + // 初始化上下文 + this.prepareBasic(); + + // 打印Banner,暂时不可配置具体的类 + new SimpleBannerPrinter().printBanner(ctx); + + // 配置信息要准备好 + this.prepareConfigureLoader(); + + // 创建Ioc容器 + prepareIoc(); + + // 加载各种starter + prepareStarterClassList(); + + // 生成Starter实例 + prepareStarterInstance(); + + prepared = true; + } + + public void prepareBasic() throws Exception { + if (this.ctx == null) { + ctx = AppContext.getDefault(); + } + if (ctx.getMainClass() == null && mainClass != null) + ctx.setMainClass(mainClass); + // 检查ClassLoader的情况 + if (ctx.getClassLoader() == null) + ctx.setClassLoader(NbApp.class.getClassLoader()); + + if (ctx.getEnvHolder() == null) { + ctx.setEnvHolder(new SystemPropertiesEnvHolder()); + } + + // 看看日志应该用哪个 + String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); + if (!Strings.isBlank(logAdapter)) { + Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); + } + log = Logs.get(); + // 资源加载器 + if (ctx.getResourceLoader() == null) { + ResourceLoader resourceLoader = new SimpleResourceLoader(); + aware(resourceLoader); + ctx.setResourceLoader(resourceLoader); + } + } + + public void prepareConfigureLoader() throws Exception { + if (ctx.getConfigureLoader() == null) { + String cnfLoader = ctx.getEnvHolder().get("nutz.boot.base.ConfigureLoader"); + ConfigureLoader configureLoader; + if (Strings.isBlank(cnfLoader)) { + configureLoader = new PropertiesConfigureLoader(); + } else { + configureLoader = (ConfigureLoader) ctx.getClassLoader().loadClass(cnfLoader).newInstance(); + } + configureLoader.setCommandLineProperties(allowCommandLineProperties, args); + aware(configureLoader); + ctx.setConfigureLoader(configureLoader); + if (configureLoader instanceof LifeCycle) + ((LifeCycle) configureLoader).init(); + } + } + + public void prepareIoc() throws Exception { + if (ctx.getComboIocLoader() == null) { + int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); + List args = new ArrayList<>(); + args.add("*js"); + args.add("ioc/"); + args.add("*tx"); + args.add("*async"); + args.add(""+asyncPoolSize); + args.add("*anno"); + args.add(ctx.getPackage()); + IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); + if (iocBy != null) { + String[] tmp = iocBy.args(); + ArrayList _args = new ArrayList<>(); + for (int i=0;i 0) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + } + } + ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); + } + // 用于加载Starter的IocLoader + starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); + ctx.getComboIocLoader().addLoader(starterIocLoader); + if (ctx.getIoc() == null) { + ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); + } + // 把核心对象放进ioc容器 + if (!ctx.ioc.has("appContext")){ + Ioc2 ioc2 = (Ioc2)ctx.getIoc(); + ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx)); + ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConfigureLoader().get())); + } + } + + public void prepareStarterClassList() throws Exception { + starterClasses = new ArrayList<>(); + HashSet classNames = new HashSet<>(); + Enumeration _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter"); + while (_en.hasMoreElements()) { + URL url = _en.nextElement(); + log.debug("Found " + url); + try (InputStream ins = url.openStream()) { + InputStreamReader reader = new InputStreamReader(ins); + String tmp = Streams.readAndClose(reader); + if (!Strings.isBlank(tmp)) { + for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) { + String className = _tmp.trim(); + if (!classNames.add(className)) + continue; + Class klass = ctx.getClassLoader().loadClass(className); + if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) { + starterIocLoader.addClass(klass); + } + starterClasses.add(klass); + } + } + } + } + } + + public void prepareStarterInstance() { + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + obj = Mirror.me(klass).born(); + } + else { + obj = ctx.getIoc().get(klass); + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + } + + protected void aware(Object obj) { + // 需要注入AppContext + if (obj instanceof AppContextAware) { + ((AppContextAware) obj).setAppContext(ctx); + } + // 需要注入ClassLoader + if (obj instanceof ClassLoaderAware) { + ((ClassLoaderAware) obj).setClassLoader(ctx.getClassLoader()); + } + // 需要注入EnvHolder + if (obj instanceof EnvHolderAware) { + ((EnvHolderAware) obj).setEnvHolder(ctx.getEnvHolder()); + } + // 需要注入ResourceLoader + if (obj instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) obj).setResourceLoader(ctx.getResourceLoader()); + } + // 需要注入Ioc + if (obj instanceof IocAware) { + ((IocAware) obj).setIoc(ctx.getIoc()); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.nutz.boot.NbApp.prepareBasic` indirectly reads without synchronization from `this.org.nutz.boot.NbApp.ctx.org.nutz.boot.AppContext.classLoader`. Potentially races with write in method `NbApp._run()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +Note that the prefix path this.org.nutz.boot.NbApp.ctx has been contaminated during the execution, so the reported race on this.org.nutz.boot.NbApp.ctx.org.nutz.boot.AppContext.classLoader might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NbApp.prepareBasic() + +### Procedure Id: +org.nutz.boot.NbApp.prepareBasic():void.dd6da23e2d20c27b6fe908f129d9169b + +### File: +nutzboot-starter/src/main/java/org/nutz/boot/NbApp.java + +### Key: +NbApp.java|prepareBasic|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +98c7e67e2a8c0cd99e6c38dd5c7b3e1c + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9420/instruction.md b/inferredbugs-9420/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b231eaf620cf2886812e33c6672d179082214d42 --- /dev/null +++ b/inferredbugs-9420/instruction.md @@ -0,0 +1,481 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nutzboot +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nutz.boot; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; + +import org.nutz.boot.aware.AppContextAware; +import org.nutz.boot.aware.ClassLoaderAware; +import org.nutz.boot.aware.EnvHolderAware; +import org.nutz.boot.aware.IocAware; +import org.nutz.boot.aware.ResourceLoaderAware; +import org.nutz.boot.banner.SimpleBannerPrinter; +import org.nutz.boot.config.ConfigureLoader; +import org.nutz.boot.config.impl.PropertiesConfigureLoader; +import org.nutz.boot.env.SystemPropertiesEnvHolder; +import org.nutz.boot.ioc.IocLoaderProvider; +import org.nutz.boot.resource.ResourceLoader; +import org.nutz.boot.resource.impl.SimpleResourceLoader; +import org.nutz.boot.tools.PropDocReader; +import org.nutz.ioc.Ioc2; +import org.nutz.ioc.IocLoader; +import org.nutz.ioc.ObjectProxy; +import org.nutz.ioc.impl.NutIoc; +import org.nutz.ioc.loader.annotation.AnnotationIocLoader; +import org.nutz.ioc.loader.annotation.IocBean; +import org.nutz.ioc.loader.combo.ComboIocLoader; +import org.nutz.lang.Lang; +import org.nutz.lang.Mirror; +import org.nutz.lang.Stopwatch; +import org.nutz.lang.Streams; +import org.nutz.lang.Strings; +import org.nutz.lang.util.LifeCycle; +import org.nutz.log.Log; +import org.nutz.log.LogAdapter; +import org.nutz.log.Logs; +import org.nutz.mvc.annotation.IocBy; + +/** + * NutzBoot的主体 + * @author wendal + * + */ +public class NbApp extends Thread { + + /** + * 日志属性要等日志适配器准备好了才能加载,这里不可以使用Logs.get(); + */ + protected static Log log; + + /** + * 命令行参数 + */ + protected String[] args; + + /** + * 主启动器类,必须设置 + */ + protected Class mainClass; + + /** + * 是否允许命令行下的 -Dxxx.xxx.xxx=转为配置参数 + */ + protected boolean allowCommandLineProperties = true; + + /** + * 是否打印配置文档 + */ + protected boolean printProcDoc; + + /** + * 主上下文 + */ + protected AppContext ctx; + + /** + * Starter共享的IocLoader + */ + protected AnnotationIocLoader starterIocLoader; + + /** + * Starter类列表 + */ + protected List> starterClasses; + + protected boolean prepared; + + protected Object lock = new Object(); + + /** + * 创建一个NbApp,把调用本构造方法的类作为mainClass + */ + public NbApp() { + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + /** + * 基于mainClass创建一个NbApp + * @param mainClass 主启动类 + */ + public NbApp(Class mainClass) { + this.mainClass = mainClass; + } + + /** + * 设置命令行参数,可选 + */ + public NbApp setArgs(String[] args) { + this.args = args; + return this; + } + + /** + * 设置主启动类 + */ + public NbApp setMainClass(Class mainClass) { + this.mainClass = mainClass; + return this; + } + + /** + * 是否允许从命令行读取配置信息, 例如 java -Dnutz.ioc.async.poolSize=128 xxx.jar + * @param flag 默认允许 + */ + public NbApp setAllowCommandLineProperties(boolean flag) { + this.allowCommandLineProperties = flag; + return this; + } + + /** + * 是否打印配置文档 + */ + public NbApp setPrintProcDoc(boolean printProcDoc) { + this.printProcDoc = printProcDoc; + return this; + } + + /** + * 获取全局上下文 + * @return + */ + public AppContext getAppContext() { + return ctx; + } + + public void run() { + try { + _run(); + } catch (Throwable e) { + Logs.get().error("something happen", e); + } + } + + /** + * 启动整个NbApp + */ + public void _run() throws Exception { + Stopwatch sw = Stopwatch.begin(); + + // 各种预备操作 + this.prepare(); + + if (printProcDoc) { + PropDocReader docReader = new PropDocReader(ctx); + docReader.load(); + Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); + } + + // 依次启动 + try { + ctx.init(); + + ctx.startServers(); + + if (mainClass.getAnnotation(IocBean.class) != null) + ctx.getIoc().get(mainClass); + + sw.stop(); + log.infof("NB started : %sms", sw.du()); + synchronized (lock) { + lock.wait(); + } + } + catch (Throwable e) { + log.error("something happen!!", e); + } + // 收尾 + ctx.stopServers(); + ctx.depose(); + } + + public void shutdown() { + log.info("ok, shutting down ..."); + synchronized (lock) { + lock.notify(); + } + } + + /** + * 执行预备操作 + */ + public void prepare() throws Exception { + if (prepared) + return; + // 初始化上下文 + this.prepareBasic(); + + // 打印Banner,暂时不可配置具体的类 + new SimpleBannerPrinter().printBanner(ctx); + + // 配置信息要准备好 + this.prepareConfigureLoader(); + + // 创建Ioc容器 + prepareIoc(); + + // 加载各种starter + prepareStarterClassList(); + + // 生成Starter实例 + prepareStarterInstance(); + + prepared = true; + } + + public void prepareBasic() throws Exception { + if (this.ctx == null) { + ctx = AppContext.getDefault(); + } + if (ctx.getMainClass() == null && mainClass != null) + ctx.setMainClass(mainClass); + // 检查ClassLoader的情况 + if (ctx.getClassLoader() == null) + ctx.setClassLoader(NbApp.class.getClassLoader()); + + if (ctx.getEnvHolder() == null) { + ctx.setEnvHolder(new SystemPropertiesEnvHolder()); + } + + // 看看日志应该用哪个 + String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); + if (!Strings.isBlank(logAdapter)) { + Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); + } + log = Logs.get(); + // 资源加载器 + if (ctx.getResourceLoader() == null) { + ResourceLoader resourceLoader = new SimpleResourceLoader(); + aware(resourceLoader); + ctx.setResourceLoader(resourceLoader); + } + } + + public void prepareConfigureLoader() throws Exception { + if (ctx.getConfigureLoader() == null) { + String cnfLoader = ctx.getEnvHolder().get("nutz.boot.base.ConfigureLoader"); + ConfigureLoader configureLoader; + if (Strings.isBlank(cnfLoader)) { + configureLoader = new PropertiesConfigureLoader(); + } else { + configureLoader = (ConfigureLoader) ctx.getClassLoader().loadClass(cnfLoader).newInstance(); + } + configureLoader.setCommandLineProperties(allowCommandLineProperties, args); + aware(configureLoader); + ctx.setConfigureLoader(configureLoader); + if (configureLoader instanceof LifeCycle) + ((LifeCycle) configureLoader).init(); + } + } + + public void prepareIoc() throws Exception { + if (ctx.getComboIocLoader() == null) { + int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); + List args = new ArrayList<>(); + args.add("*js"); + args.add("ioc/"); + args.add("*tx"); + args.add("*async"); + args.add(""+asyncPoolSize); + args.add("*anno"); + args.add(ctx.getPackage()); + IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); + if (iocBy != null) { + String[] tmp = iocBy.args(); + ArrayList _args = new ArrayList<>(); + for (int i=0;i 0) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + } + } + ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); + } + // 用于加载Starter的IocLoader + starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); + ctx.getComboIocLoader().addLoader(starterIocLoader); + if (ctx.getIoc() == null) { + ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); + } + // 把核心对象放进ioc容器 + if (!ctx.ioc.has("appContext")){ + Ioc2 ioc2 = (Ioc2)ctx.getIoc(); + ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx)); + ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConfigureLoader().get())); + } + } + + public void prepareStarterClassList() throws Exception { + starterClasses = new ArrayList<>(); + HashSet classNames = new HashSet<>(); + Enumeration _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter"); + while (_en.hasMoreElements()) { + URL url = _en.nextElement(); + log.debug("Found " + url); + try (InputStream ins = url.openStream()) { + InputStreamReader reader = new InputStreamReader(ins); + String tmp = Streams.readAndClose(reader); + if (!Strings.isBlank(tmp)) { + for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) { + String className = _tmp.trim(); + if (!classNames.add(className)) + continue; + Class klass = ctx.getClassLoader().loadClass(className); + if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) { + starterIocLoader.addClass(klass); + } + starterClasses.add(klass); + } + } + } + } + } + + public void prepareStarterInstance() { + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + obj = Mirror.me(klass).born(); + } + else { + obj = ctx.getIoc().get(klass); + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + } + + protected void aware(Object obj) { + // 需要注入AppContext + if (obj instanceof AppContextAware) { + ((AppContextAware) obj).setAppContext(ctx); + } + // 需要注入ClassLoader + if (obj instanceof ClassLoaderAware) { + ((ClassLoaderAware) obj).setClassLoader(ctx.getClassLoader()); + } + // 需要注入EnvHolder + if (obj instanceof EnvHolderAware) { + ((EnvHolderAware) obj).setEnvHolder(ctx.getEnvHolder()); + } + // 需要注入ResourceLoader + if (obj instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) obj).setResourceLoader(ctx.getResourceLoader()); + } + // 需要注入Ioc + if (obj instanceof IocAware) { + ((IocAware) obj).setIoc(ctx.getIoc()); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.nutz.boot.NbApp.prepareBasic` indirectly writes to field `this.org.nutz.boot.NbApp.ctx.org.nutz.boot.AppContext.envHolder` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +Note that the prefix path this.org.nutz.boot.NbApp.ctx has been contaminated during the execution, so the reported race on this.org.nutz.boot.NbApp.ctx.org.nutz.boot.AppContext.envHolder might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NbApp.prepareBasic() + +### Procedure Id: +org.nutz.boot.NbApp.prepareBasic():void.dd6da23e2d20c27b6fe908f129d9169b + +### File: +nutzboot-starter/src/main/java/org/nutz/boot/NbApp.java + +### Key: +NbApp.java|prepareBasic|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +e76295e5b5c551be18c21a29c287b47e + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9427/instruction.md b/inferredbugs-9427/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5c708f7c11903123f95a8419699fe3fbde65d38f --- /dev/null +++ b/inferredbugs-9427/instruction.md @@ -0,0 +1,481 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nutzboot +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nutz.boot; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; + +import org.nutz.boot.aware.AppContextAware; +import org.nutz.boot.aware.ClassLoaderAware; +import org.nutz.boot.aware.EnvHolderAware; +import org.nutz.boot.aware.IocAware; +import org.nutz.boot.aware.ResourceLoaderAware; +import org.nutz.boot.banner.SimpleBannerPrinter; +import org.nutz.boot.config.ConfigureLoader; +import org.nutz.boot.config.impl.PropertiesConfigureLoader; +import org.nutz.boot.env.SystemPropertiesEnvHolder; +import org.nutz.boot.ioc.IocLoaderProvider; +import org.nutz.boot.resource.ResourceLoader; +import org.nutz.boot.resource.impl.SimpleResourceLoader; +import org.nutz.boot.tools.PropDocReader; +import org.nutz.ioc.Ioc2; +import org.nutz.ioc.IocLoader; +import org.nutz.ioc.ObjectProxy; +import org.nutz.ioc.impl.NutIoc; +import org.nutz.ioc.loader.annotation.AnnotationIocLoader; +import org.nutz.ioc.loader.annotation.IocBean; +import org.nutz.ioc.loader.combo.ComboIocLoader; +import org.nutz.lang.Lang; +import org.nutz.lang.Mirror; +import org.nutz.lang.Stopwatch; +import org.nutz.lang.Streams; +import org.nutz.lang.Strings; +import org.nutz.lang.util.LifeCycle; +import org.nutz.log.Log; +import org.nutz.log.LogAdapter; +import org.nutz.log.Logs; +import org.nutz.mvc.annotation.IocBy; + +/** + * NutzBoot的主体 + * @author wendal + * + */ +public class NbApp extends Thread { + + /** + * 日志属性要等日志适配器准备好了才能加载,这里不可以使用Logs.get(); + */ + protected static Log log; + + /** + * 命令行参数 + */ + protected String[] args; + + /** + * 主启动器类,必须设置 + */ + protected Class mainClass; + + /** + * 是否允许命令行下的 -Dxxx.xxx.xxx=转为配置参数 + */ + protected boolean allowCommandLineProperties = true; + + /** + * 是否打印配置文档 + */ + protected boolean printProcDoc; + + /** + * 主上下文 + */ + protected AppContext ctx; + + /** + * Starter共享的IocLoader + */ + protected AnnotationIocLoader starterIocLoader; + + /** + * Starter类列表 + */ + protected List> starterClasses; + + protected boolean prepared; + + protected Object lock = new Object(); + + /** + * 创建一个NbApp,把调用本构造方法的类作为mainClass + */ + public NbApp() { + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + /** + * 基于mainClass创建一个NbApp + * @param mainClass 主启动类 + */ + public NbApp(Class mainClass) { + this.mainClass = mainClass; + } + + /** + * 设置命令行参数,可选 + */ + public NbApp setArgs(String[] args) { + this.args = args; + return this; + } + + /** + * 设置主启动类 + */ + public NbApp setMainClass(Class mainClass) { + this.mainClass = mainClass; + return this; + } + + /** + * 是否允许从命令行读取配置信息, 例如 java -Dnutz.ioc.async.poolSize=128 xxx.jar + * @param flag 默认允许 + */ + public NbApp setAllowCommandLineProperties(boolean flag) { + this.allowCommandLineProperties = flag; + return this; + } + + /** + * 是否打印配置文档 + */ + public NbApp setPrintProcDoc(boolean printProcDoc) { + this.printProcDoc = printProcDoc; + return this; + } + + /** + * 获取全局上下文 + * @return + */ + public AppContext getAppContext() { + return ctx; + } + + public void run() { + try { + _run(); + } catch (Throwable e) { + Logs.get().error("something happen", e); + } + } + + /** + * 启动整个NbApp + */ + public void _run() throws Exception { + Stopwatch sw = Stopwatch.begin(); + + // 各种预备操作 + this.prepare(); + + if (printProcDoc) { + PropDocReader docReader = new PropDocReader(ctx); + docReader.load(); + Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); + } + + // 依次启动 + try { + ctx.init(); + + ctx.startServers(); + + if (mainClass.getAnnotation(IocBean.class) != null) + ctx.getIoc().get(mainClass); + + sw.stop(); + log.infof("NB started : %sms", sw.du()); + synchronized (lock) { + lock.wait(); + } + } + catch (Throwable e) { + log.error("something happen!!", e); + } + // 收尾 + ctx.stopServers(); + ctx.depose(); + } + + public void shutdown() { + log.info("ok, shutting down ..."); + synchronized (lock) { + lock.notify(); + } + } + + /** + * 执行预备操作 + */ + public void prepare() throws Exception { + if (prepared) + return; + // 初始化上下文 + this.prepareBasic(); + + // 打印Banner,暂时不可配置具体的类 + new SimpleBannerPrinter().printBanner(ctx); + + // 配置信息要准备好 + this.prepareConfigureLoader(); + + // 创建Ioc容器 + prepareIoc(); + + // 加载各种starter + prepareStarterClassList(); + + // 生成Starter实例 + prepareStarterInstance(); + + prepared = true; + } + + public void prepareBasic() throws Exception { + if (this.ctx == null) { + ctx = AppContext.getDefault(); + } + if (ctx.getMainClass() == null && mainClass != null) + ctx.setMainClass(mainClass); + // 检查ClassLoader的情况 + if (ctx.getClassLoader() == null) + ctx.setClassLoader(NbApp.class.getClassLoader()); + + if (ctx.getEnvHolder() == null) { + ctx.setEnvHolder(new SystemPropertiesEnvHolder()); + } + + // 看看日志应该用哪个 + String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); + if (!Strings.isBlank(logAdapter)) { + Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); + } + log = Logs.get(); + // 资源加载器 + if (ctx.getResourceLoader() == null) { + ResourceLoader resourceLoader = new SimpleResourceLoader(); + aware(resourceLoader); + ctx.setResourceLoader(resourceLoader); + } + } + + public void prepareConfigureLoader() throws Exception { + if (ctx.getConfigureLoader() == null) { + String cnfLoader = ctx.getEnvHolder().get("nutz.boot.base.ConfigureLoader"); + ConfigureLoader configureLoader; + if (Strings.isBlank(cnfLoader)) { + configureLoader = new PropertiesConfigureLoader(); + } else { + configureLoader = (ConfigureLoader) ctx.getClassLoader().loadClass(cnfLoader).newInstance(); + } + configureLoader.setCommandLineProperties(allowCommandLineProperties, args); + aware(configureLoader); + ctx.setConfigureLoader(configureLoader); + if (configureLoader instanceof LifeCycle) + ((LifeCycle) configureLoader).init(); + } + } + + public void prepareIoc() throws Exception { + if (ctx.getComboIocLoader() == null) { + int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); + List args = new ArrayList<>(); + args.add("*js"); + args.add("ioc/"); + args.add("*tx"); + args.add("*async"); + args.add(""+asyncPoolSize); + args.add("*anno"); + args.add(ctx.getPackage()); + IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); + if (iocBy != null) { + String[] tmp = iocBy.args(); + ArrayList _args = new ArrayList<>(); + for (int i=0;i 0) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + } + } + ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); + } + // 用于加载Starter的IocLoader + starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); + ctx.getComboIocLoader().addLoader(starterIocLoader); + if (ctx.getIoc() == null) { + ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); + } + // 把核心对象放进ioc容器 + if (!ctx.ioc.has("appContext")){ + Ioc2 ioc2 = (Ioc2)ctx.getIoc(); + ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx)); + ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConfigureLoader().get())); + } + } + + public void prepareStarterClassList() throws Exception { + starterClasses = new ArrayList<>(); + HashSet classNames = new HashSet<>(); + Enumeration _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter"); + while (_en.hasMoreElements()) { + URL url = _en.nextElement(); + log.debug("Found " + url); + try (InputStream ins = url.openStream()) { + InputStreamReader reader = new InputStreamReader(ins); + String tmp = Streams.readAndClose(reader); + if (!Strings.isBlank(tmp)) { + for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) { + String className = _tmp.trim(); + if (!classNames.add(className)) + continue; + Class klass = ctx.getClassLoader().loadClass(className); + if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) { + starterIocLoader.addClass(klass); + } + starterClasses.add(klass); + } + } + } + } + } + + public void prepareStarterInstance() { + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + obj = Mirror.me(klass).born(); + } + else { + obj = ctx.getIoc().get(klass); + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + } + + protected void aware(Object obj) { + // 需要注入AppContext + if (obj instanceof AppContextAware) { + ((AppContextAware) obj).setAppContext(ctx); + } + // 需要注入ClassLoader + if (obj instanceof ClassLoaderAware) { + ((ClassLoaderAware) obj).setClassLoader(ctx.getClassLoader()); + } + // 需要注入EnvHolder + if (obj instanceof EnvHolderAware) { + ((EnvHolderAware) obj).setEnvHolder(ctx.getEnvHolder()); + } + // 需要注入ResourceLoader + if (obj instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) obj).setResourceLoader(ctx.getResourceLoader()); + } + // 需要注入Ioc + if (obj instanceof IocAware) { + ((IocAware) obj).setIoc(ctx.getIoc()); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.nutz.boot.NbApp.prepareBasic` indirectly reads without synchronization from `this.org.nutz.boot.NbApp.ctx.org.nutz.boot.AppContext.resourceLoader`. Potentially races with write in method `NbApp._run()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +Note that the prefix path this.org.nutz.boot.NbApp.ctx has been contaminated during the execution, so the reported race on this.org.nutz.boot.NbApp.ctx.org.nutz.boot.AppContext.resourceLoader might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NbApp.prepareBasic() + +### Procedure Id: +org.nutz.boot.NbApp.prepareBasic():void.dd6da23e2d20c27b6fe908f129d9169b + +### File: +nutzboot-starter/src/main/java/org/nutz/boot/NbApp.java + +### Key: +NbApp.java|prepareBasic|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +f15599c81206ea7da9990fc08ec39f93 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9429/instruction.md b/inferredbugs-9429/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..617481a30fc8886cc1344b69c575f00f87b47598 --- /dev/null +++ b/inferredbugs-9429/instruction.md @@ -0,0 +1,580 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nutzboot +**Bug ID:** 26 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nutz.boot; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +import org.nutz.boot.aware.AppContextAware; +import org.nutz.boot.aware.ClassLoaderAware; +import org.nutz.boot.aware.EnvHolderAware; +import org.nutz.boot.aware.IocAware; +import org.nutz.boot.aware.ResourceLoaderAware; +import org.nutz.boot.banner.SimpleBannerPrinter; +import org.nutz.boot.config.ConfigureLoader; +import org.nutz.boot.config.impl.PropertiesConfigureLoader; +import org.nutz.boot.env.SystemPropertiesEnvHolder; +import org.nutz.boot.ioc.IocLoaderProvider; +import org.nutz.boot.metrics.impl.MemoryCounterService; +import org.nutz.boot.resource.ResourceLoader; +import org.nutz.boot.resource.impl.SimpleResourceLoader; +import org.nutz.boot.tools.NbAppEventListener; +import org.nutz.boot.tools.NbAppEventListener.EventType; +import org.nutz.boot.tools.PropDocReader; +import org.nutz.ioc.IocLoader; +import org.nutz.ioc.impl.NutIoc; +import org.nutz.ioc.loader.annotation.AnnotationIocLoader; +import org.nutz.ioc.loader.annotation.IocBean; +import org.nutz.ioc.loader.combo.ComboIocLoader; +import org.nutz.lang.Lang; +import org.nutz.lang.Mirror; +import org.nutz.lang.Stopwatch; +import org.nutz.lang.Streams; +import org.nutz.lang.Strings; +import org.nutz.lang.util.LifeCycle; +import org.nutz.log.Log; +import org.nutz.log.LogAdapter; +import org.nutz.log.Logs; +import org.nutz.mvc.Mvcs; +import org.nutz.mvc.annotation.IocBy; + +/** + * NutzBoot的主体 + * + * @author wendal + * + */ +public class NbApp extends Thread { + + /** + * 日志属性要等日志适配器准备好了才能加载,这里不可以使用Logs.get(); + */ + protected static Log log; + + /** + * 命令行参数 + */ + protected String[] args; + + /** + * 是否允许命令行下的 -Dxxx.xxx.xxx=转为配置参数 + */ + protected boolean allowCommandLineProperties = true; + + /** + * 是否打印配置文档 + */ + protected boolean printProcDoc; + + /** + * 主上下文 + */ + protected AppContext ctx; + + /** + * Starter共享的IocLoader + */ + protected AnnotationIocLoader starterIocLoader; + + /** + * Starter类列表 + */ + protected List> starterClasses; + + protected boolean prepared; + + protected Object lock = new Object(); + + protected List listeners = new LinkedList<>(); + + protected boolean started; + + /** + * 创建一个NbApp,把调用本构造方法的类作为mainClass + */ + public NbApp() { + ctx = AppContext.getDefault(); + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + /** + * 基于mainClass创建一个NbApp + * + * @param mainClass + * 主启动类 + */ + public NbApp(Class mainClass) { + ctx = AppContext.getDefault(); + setMainClass(mainClass); + } + + public NbApp(AppContext ctx) { + this.ctx = ctx; + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + public NbApp(AppContext ctx, Class mainClass) { + this.ctx = ctx; + setMainClass(mainClass); + } + + /** + * 设置命令行参数,可选 + */ + public NbApp setArgs(String[] args) { + this.args = args; + return this; + } + + /** + * 设置主启动类 + */ + public NbApp setMainClass(Class mainClass) { + this.ctx.setMainClass(mainClass); + return this; + } + + /** + * 是否允许从命令行读取配置信息, 例如 java -Dnutz.ioc.async.poolSize=128 xxx.jar + * + * @param flag + * 默认允许 + */ + public NbApp setAllowCommandLineProperties(boolean flag) { + this.allowCommandLineProperties = flag; + return this; + } + + /** + * 是否打印配置文档 + */ + public NbApp setPrintProcDoc(boolean printProcDoc) { + this.printProcDoc = printProcDoc; + return this; + } + + /** + * 获取全局上下文 + * + * @return + */ + public AppContext getAppContext() { + return ctx; + } + + public void run() { + try { + if (execute()) { + synchronized (lock) { + lock.wait(); + } + } + // 收尾 + _shutdown(); + } + catch (Throwable e) { + Logs.get().error("something happen", e); + } + } + + public boolean execute() { + Stopwatch sw = Stopwatch.begin(); + try { + // 各种预备操作 + listeners.forEach((listener)->listener.whenPrepare(this, EventType.before)); + this.prepare(); + listeners.forEach((listener)->listener.whenPrepare(this, EventType.after)); + + // 依次启动 + listeners.forEach((listener)->listener.whenInitAppContext(this, EventType.before)); + ctx.init(); + listeners.forEach((listener)->listener.whenInitAppContext(this, EventType.after)); + + listeners.forEach((listener)->listener.whenStartServers(this, EventType.before)); + ctx.startServers(); + listeners.forEach((listener)->listener.whenStartServers(this, EventType.after)); + + if (ctx.getMainClass().getAnnotation(IocBean.class) != null) + ctx.getIoc().get(ctx.getMainClass()); + + listeners.forEach((listener)->listener.afterAppStated(this)); + + sw.stop(); + log.infof("%s started : %sms", ctx.getConf().get("nutz.application.name", "NB"), sw.du()); + started = true; + return true; + } + catch (Throwable e) { + log.error("something happen!!", e); + return false; + } + } + + public void _shutdown() { + try { + ctx.stopServers(); + ctx.depose(); + } + catch (Exception e) { + throw Lang.wrapThrow(e); + } + } + + public void shutdown() { + log.info("ok, shutting down ..."); + if (lock == null) { + _shutdown(); + } + else { + synchronized (lock) { + lock.notify(); + } + } + } + + /** + * 执行预备操作 + */ + public void prepare() throws Exception { + if (prepared) + return; + // 初始化上下文 + listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before)); + this.prepareBasic(); + listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.after)); + + // 打印Banner,暂时不可配置具体的类 + new SimpleBannerPrinter().printBanner(ctx); + + // 配置信息要准备好 + + listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.before)); + this.prepareConfigureLoader(); + listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.after)); + + // 创建IocLoader体系 + listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.before)); + prepareIocLoader(); + listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.after)); + + // 加载各种starter + listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.before)); + prepareStarterClassList(); + listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.after)); + + // 打印配置文档 + if (printProcDoc) { + PropDocReader docReader = new PropDocReader(); + docReader.load(starterClasses); + Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); + } + + // 创建Ioc容器 + listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.before)); + prepareIoc(); + listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.after)); + + // 生成Starter实例 + listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.before)); + prepareStarterInstance(); + listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.after)); + + // 从Ioc容器检索Listener + listeners.addAll(ctx.getBeans(NbAppEventListener.class)); + + prepared = true; + } + + public void prepareBasic() throws Exception { + // 检查ClassLoader的情况 + if (ctx.getClassLoader() == null) + ctx.setClassLoader(NbApp.class.getClassLoader()); + + if (ctx.getEnvHolder() == null) { + ctx.setEnvHolder(new SystemPropertiesEnvHolder()); + } + + // 看看日志应该用哪个 + String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); + if (!Strings.isBlank(logAdapter)) { + Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); + } + log = Logs.get(); + // 资源加载器 + if (ctx.getResourceLoader() == null) { + ResourceLoader resourceLoader = new SimpleResourceLoader(); + aware(resourceLoader); + ctx.setResourceLoader(resourceLoader); + } + } + + public void prepareConfigureLoader() throws Exception { + if (ctx.getConfigureLoader() == null) { + ConfigureLoader configureLoader = null; + InputStream ins = ctx.getResourceLoader().get("META-INF/nutz/org.nutz.boot.config.ConfigureLoader"); + if (ins != null) { + String cnfLoader = new String(Streams.readBytes(ins)).trim(); + if (!Strings.isBlank(cnfLoader)) { + log.debugf("using %s as ConfigureLoader", cnfLoader); + configureLoader = (ConfigureLoader) ctx.getClassLoader().loadClass(cnfLoader).newInstance(); + } + } + if (configureLoader == null) { + configureLoader = new PropertiesConfigureLoader(); + } + configureLoader.setCommandLineProperties(allowCommandLineProperties, args); + aware(configureLoader); + ctx.setConfigureLoader(configureLoader); + if (configureLoader instanceof LifeCycle) + ((LifeCycle) configureLoader).init(); + } + } + + public void prepareIocLoader() throws Exception { + if (ctx.getComboIocLoader() == null) { + int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); + List args = new ArrayList<>(); + args.add("*js"); + args.add("ioc/"); + args.add("*tx"); + args.add("*async"); + args.add("" + asyncPoolSize); + args.add("*anno"); + args.add(ctx.getPackage()); + IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); + if (iocBy != null) { + String[] tmp = iocBy.args(); + ArrayList _args = new ArrayList<>(); + for (int i = 0; i < tmp.length; i++) { + if (tmp[i].startsWith("*")) { + if (!_args.isEmpty()) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + _args.clear(); + } + } + _args.add(tmp[i]); + } + if (_args.size() > 0) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + } + } + ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); + } + // 用于加载Starter的IocLoader + starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); + ctx.getComboIocLoader().addLoader(starterIocLoader); + } + + public void prepareStarterClassList() throws Exception { + starterClasses = new ArrayList<>(); + HashSet classNames = new HashSet<>(); + Enumeration _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter"); + while (_en.hasMoreElements()) { + URL url = _en.nextElement(); + log.debug("Found " + url); + try (InputStream ins = url.openStream()) { + InputStreamReader reader = new InputStreamReader(ins); + String tmp = Streams.readAndClose(reader); + if (!Strings.isBlank(tmp)) { + for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) { + String className = _tmp.trim(); + if (!classNames.add(className)) + continue; + Class klass = ctx.getClassLoader().loadClass(className); + if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) { + starterIocLoader.addClass(klass); + } + starterClasses.add(klass); + } + } + } + } + } + + public void prepareIoc() { + if (ctx.getIoc() == null) { + ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); + } + // 把核心对象放进ioc容器 + if (!ctx.ioc.has("appContext")) { + ctx.ioc.addBean("appContext", ctx); + ctx.ioc.addBean("conf", ctx.getConf()); + ctx.ioc.addBean("nbApp", this); + // 添加更多扩展bean + ctx.ioc.addBean("counterService", new MemoryCounterService()); + } + Mvcs.ctx().iocs.put("nutz", ctx.getIoc()); + } + + public void prepareStarterInstance() { + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + obj = Mirror.me(klass).born(); + } else { + continue; + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + continue; + } else { + obj = ctx.getIoc().get(klass); + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + } + + protected void aware(Object obj) { + // 需要注入AppContext + if (obj instanceof AppContextAware) { + ((AppContextAware) obj).setAppContext(ctx); + } + // 需要注入ClassLoader + if (obj instanceof ClassLoaderAware) { + ((ClassLoaderAware) obj).setClassLoader(ctx.getClassLoader()); + } + // 需要注入EnvHolder + if (obj instanceof EnvHolderAware) { + ((EnvHolderAware) obj).setEnvHolder(ctx.getEnvHolder()); + } + // 需要注入ResourceLoader + if (obj instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) obj).setResourceLoader(ctx.getResourceLoader()); + } + // 需要注入Ioc + if (obj instanceof IocAware) { + ((IocAware) obj).setIoc(ctx.getIoc()); + } + } + + public void setListener(NbAppEventListener listener) { + this.listeners.clear(); + addListener(listener); + } + + public void addListener(NbAppEventListener listener) { + this.listeners.add(listener); + } + + public boolean isStarted() { + return started; + } + + public void setMainPackage(String mainPackage) { + getAppContext().setMainPackage(mainPackage); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.nutz.boot.NbApp.prepare` indirectly reads without synchronization from `this.org.nutz.boot.NbApp.ctx.org.nutz.boot.AppContext.classLoader`. Potentially races with write in method `NbApp.run()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NbApp.prepare() + +### Procedure Id: +org.nutz.boot.NbApp.prepare():void.3497bd920679b1a589201156049c849c + +### File: +nutzboot-core/src/main/java/org/nutz/boot/NbApp.java + +### Key: +NbApp.java|prepare|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +4984fac0e2fcd338dd98d23360c0cf8f + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9442/instruction.md b/inferredbugs-9442/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..317dffead7e85946cb316f1033b46b25f8532fc4 --- /dev/null +++ b/inferredbugs-9442/instruction.md @@ -0,0 +1,481 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nutzboot +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nutz.boot; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; + +import org.nutz.boot.aware.AppContextAware; +import org.nutz.boot.aware.ClassLoaderAware; +import org.nutz.boot.aware.EnvHolderAware; +import org.nutz.boot.aware.IocAware; +import org.nutz.boot.aware.ResourceLoaderAware; +import org.nutz.boot.banner.SimpleBannerPrinter; +import org.nutz.boot.config.ConfigureLoader; +import org.nutz.boot.config.impl.PropertiesConfigureLoader; +import org.nutz.boot.env.SystemPropertiesEnvHolder; +import org.nutz.boot.ioc.IocLoaderProvider; +import org.nutz.boot.resource.ResourceLoader; +import org.nutz.boot.resource.impl.SimpleResourceLoader; +import org.nutz.boot.tools.PropDocReader; +import org.nutz.ioc.Ioc2; +import org.nutz.ioc.IocLoader; +import org.nutz.ioc.ObjectProxy; +import org.nutz.ioc.impl.NutIoc; +import org.nutz.ioc.loader.annotation.AnnotationIocLoader; +import org.nutz.ioc.loader.annotation.IocBean; +import org.nutz.ioc.loader.combo.ComboIocLoader; +import org.nutz.lang.Lang; +import org.nutz.lang.Mirror; +import org.nutz.lang.Stopwatch; +import org.nutz.lang.Streams; +import org.nutz.lang.Strings; +import org.nutz.lang.util.LifeCycle; +import org.nutz.log.Log; +import org.nutz.log.LogAdapter; +import org.nutz.log.Logs; +import org.nutz.mvc.annotation.IocBy; + +/** + * NutzBoot的主体 + * @author wendal + * + */ +public class NbApp extends Thread { + + /** + * 日志属性要等日志适配器准备好了才能加载,这里不可以使用Logs.get(); + */ + protected static Log log; + + /** + * 命令行参数 + */ + protected String[] args; + + /** + * 主启动器类,必须设置 + */ + protected Class mainClass; + + /** + * 是否允许命令行下的 -Dxxx.xxx.xxx=转为配置参数 + */ + protected boolean allowCommandLineProperties = true; + + /** + * 是否打印配置文档 + */ + protected boolean printProcDoc; + + /** + * 主上下文 + */ + protected AppContext ctx; + + /** + * Starter共享的IocLoader + */ + protected AnnotationIocLoader starterIocLoader; + + /** + * Starter类列表 + */ + protected List> starterClasses; + + protected boolean prepared; + + protected Object lock = new Object(); + + /** + * 创建一个NbApp,把调用本构造方法的类作为mainClass + */ + public NbApp() { + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + /** + * 基于mainClass创建一个NbApp + * @param mainClass 主启动类 + */ + public NbApp(Class mainClass) { + this.mainClass = mainClass; + } + + /** + * 设置命令行参数,可选 + */ + public NbApp setArgs(String[] args) { + this.args = args; + return this; + } + + /** + * 设置主启动类 + */ + public NbApp setMainClass(Class mainClass) { + this.mainClass = mainClass; + return this; + } + + /** + * 是否允许从命令行读取配置信息, 例如 java -Dnutz.ioc.async.poolSize=128 xxx.jar + * @param flag 默认允许 + */ + public NbApp setAllowCommandLineProperties(boolean flag) { + this.allowCommandLineProperties = flag; + return this; + } + + /** + * 是否打印配置文档 + */ + public NbApp setPrintProcDoc(boolean printProcDoc) { + this.printProcDoc = printProcDoc; + return this; + } + + /** + * 获取全局上下文 + * @return + */ + public AppContext getAppContext() { + return ctx; + } + + public void run() { + try { + _run(); + } catch (Throwable e) { + Logs.get().error("something happen", e); + } + } + + /** + * 启动整个NbApp + */ + public void _run() throws Exception { + Stopwatch sw = Stopwatch.begin(); + + // 各种预备操作 + this.prepare(); + + if (printProcDoc) { + PropDocReader docReader = new PropDocReader(ctx); + docReader.load(); + Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); + } + + // 依次启动 + try { + ctx.init(); + + ctx.startServers(); + + if (mainClass.getAnnotation(IocBean.class) != null) + ctx.getIoc().get(mainClass); + + sw.stop(); + log.infof("NB started : %sms", sw.du()); + synchronized (lock) { + lock.wait(); + } + } + catch (Throwable e) { + log.error("something happen!!", e); + } + // 收尾 + ctx.stopServers(); + ctx.depose(); + } + + public void shutdown() { + log.info("ok, shutting down ..."); + synchronized (lock) { + lock.notify(); + } + } + + /** + * 执行预备操作 + */ + public void prepare() throws Exception { + if (prepared) + return; + // 初始化上下文 + this.prepareBasic(); + + // 打印Banner,暂时不可配置具体的类 + new SimpleBannerPrinter().printBanner(ctx); + + // 配置信息要准备好 + this.prepareConfigureLoader(); + + // 创建Ioc容器 + prepareIoc(); + + // 加载各种starter + prepareStarterClassList(); + + // 生成Starter实例 + prepareStarterInstance(); + + prepared = true; + } + + public void prepareBasic() throws Exception { + if (this.ctx == null) { + ctx = AppContext.getDefault(); + } + if (ctx.getMainClass() == null && mainClass != null) + ctx.setMainClass(mainClass); + // 检查ClassLoader的情况 + if (ctx.getClassLoader() == null) + ctx.setClassLoader(NbApp.class.getClassLoader()); + + if (ctx.getEnvHolder() == null) { + ctx.setEnvHolder(new SystemPropertiesEnvHolder()); + } + + // 看看日志应该用哪个 + String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); + if (!Strings.isBlank(logAdapter)) { + Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); + } + log = Logs.get(); + // 资源加载器 + if (ctx.getResourceLoader() == null) { + ResourceLoader resourceLoader = new SimpleResourceLoader(); + aware(resourceLoader); + ctx.setResourceLoader(resourceLoader); + } + } + + public void prepareConfigureLoader() throws Exception { + if (ctx.getConfigureLoader() == null) { + String cnfLoader = ctx.getEnvHolder().get("nutz.boot.base.ConfigureLoader"); + ConfigureLoader configureLoader; + if (Strings.isBlank(cnfLoader)) { + configureLoader = new PropertiesConfigureLoader(); + } else { + configureLoader = (ConfigureLoader) ctx.getClassLoader().loadClass(cnfLoader).newInstance(); + } + configureLoader.setCommandLineProperties(allowCommandLineProperties, args); + aware(configureLoader); + ctx.setConfigureLoader(configureLoader); + if (configureLoader instanceof LifeCycle) + ((LifeCycle) configureLoader).init(); + } + } + + public void prepareIoc() throws Exception { + if (ctx.getComboIocLoader() == null) { + int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); + List args = new ArrayList<>(); + args.add("*js"); + args.add("ioc/"); + args.add("*tx"); + args.add("*async"); + args.add(""+asyncPoolSize); + args.add("*anno"); + args.add(ctx.getPackage()); + IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); + if (iocBy != null) { + String[] tmp = iocBy.args(); + ArrayList _args = new ArrayList<>(); + for (int i=0;i 0) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + } + } + ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); + } + // 用于加载Starter的IocLoader + starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); + ctx.getComboIocLoader().addLoader(starterIocLoader); + if (ctx.getIoc() == null) { + ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); + } + // 把核心对象放进ioc容器 + if (!ctx.ioc.has("appContext")){ + Ioc2 ioc2 = (Ioc2)ctx.getIoc(); + ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx)); + ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConfigureLoader().get())); + } + } + + public void prepareStarterClassList() throws Exception { + starterClasses = new ArrayList<>(); + HashSet classNames = new HashSet<>(); + Enumeration _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter"); + while (_en.hasMoreElements()) { + URL url = _en.nextElement(); + log.debug("Found " + url); + try (InputStream ins = url.openStream()) { + InputStreamReader reader = new InputStreamReader(ins); + String tmp = Streams.readAndClose(reader); + if (!Strings.isBlank(tmp)) { + for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) { + String className = _tmp.trim(); + if (!classNames.add(className)) + continue; + Class klass = ctx.getClassLoader().loadClass(className); + if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) { + starterIocLoader.addClass(klass); + } + starterClasses.add(klass); + } + } + } + } + } + + public void prepareStarterInstance() { + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + obj = Mirror.me(klass).born(); + } + else { + obj = ctx.getIoc().get(klass); + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + } + + protected void aware(Object obj) { + // 需要注入AppContext + if (obj instanceof AppContextAware) { + ((AppContextAware) obj).setAppContext(ctx); + } + // 需要注入ClassLoader + if (obj instanceof ClassLoaderAware) { + ((ClassLoaderAware) obj).setClassLoader(ctx.getClassLoader()); + } + // 需要注入EnvHolder + if (obj instanceof EnvHolderAware) { + ((EnvHolderAware) obj).setEnvHolder(ctx.getEnvHolder()); + } + // 需要注入ResourceLoader + if (obj instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) obj).setResourceLoader(ctx.getResourceLoader()); + } + // 需要注入Ioc + if (obj instanceof IocAware) { + ((IocAware) obj).setIoc(ctx.getIoc()); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.nutz.boot.NbApp.prepareBasic` indirectly writes to field `this.org.nutz.boot.NbApp.ctx.org.nutz.boot.AppContext.mainClass` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +Note that the prefix path this.org.nutz.boot.NbApp.ctx has been contaminated during the execution, so the reported race on this.org.nutz.boot.NbApp.ctx.org.nutz.boot.AppContext.mainClass might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NbApp.prepareBasic() + +### Procedure Id: +org.nutz.boot.NbApp.prepareBasic():void.dd6da23e2d20c27b6fe908f129d9169b + +### File: +nutzboot-starter/src/main/java/org/nutz/boot/NbApp.java + +### Key: +NbApp.java|prepareBasic|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +23227db03691157ee85c5fcb82ac79ed + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9444/instruction.md b/inferredbugs-9444/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7f0b74d12d16d7b527f91645328d872c2106d044 --- /dev/null +++ b/inferredbugs-9444/instruction.md @@ -0,0 +1,178 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nutzboot +**Bug ID:** 22 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nutz.boot.starter.beetlsql; + +import javax.sql.DataSource; + +import org.beetl.sql.core.ClasspathLoader; +import org.beetl.sql.core.ConnectionSource; +import org.beetl.sql.core.DefaultConnectionSource; +import org.beetl.sql.core.DefaultNameConversion; +import org.beetl.sql.core.Interceptor; +import org.beetl.sql.core.NameConversion; +import org.beetl.sql.core.SQLLoader; +import org.beetl.sql.core.SQLManager; +import org.beetl.sql.core.UnderlinedNameConversion; +import org.beetl.sql.core.db.AbstractDBStyle; +import org.beetl.sql.core.db.DBStyle; +import org.beetl.sql.ext.DebugInterceptor; +import org.nutz.boot.annotation.PropDoc; +import org.nutz.boot.starter.jdbc.DataSourceStarter; +import org.nutz.ioc.Ioc; +import org.nutz.ioc.impl.PropertiesProxy; +import org.nutz.ioc.loader.annotation.Inject; +import org.nutz.ioc.loader.annotation.IocBean; +import org.nutz.lang.Lang; +import org.nutz.resource.Scans; + +/** + * 封装BeetlSql的初始化逻辑 + * + * @author wendal(wendal1985@gmail.com) + * + */ +@IocBean +public class BeetlSqlStarter { + + protected static final String PRE = "beetlsql."; + + @PropDoc(group = "beetlsql", value = "数据库类型", defaultValue = "mysql", possible = { "mysql", "oracle", "h2", "db2", + "postgres", "sqlite", "sqlserver", "sqlserver2012" }) + public static final String PROP_DBSTYLE = PRE + "dbStyle"; + + @PropDoc(group = "beetlsql", value = "SQL目录", defaultValue = "/sqls/") + public static final String PROP_PATH = PRE + "path"; + + @PropDoc(group = "beetlsql", value = "命名转换方式", defaultValue = "default", possible = { "default", "under_lined" }) + public static final String PROP_NAME_CONVERSION = PRE + "nameconv"; + + @PropDoc(group = "beetlsql", value = "是否使用DebugInterceptor", defaultValue = "true") + public static final String PROP_DEBUG = PRE + "debug"; + + @PropDoc(group = "beetlsql", value = "是否启用Trans支持", defaultValue = "true") + public static final String PROP_TRANS = PRE + "trans"; + + @Inject("refer:$ioc") + protected Ioc ioc; + + @Inject + protected PropertiesProxy conf; + + @IocBean(name = "beetlsqlDBStyle") + public DBStyle createDBStyle() throws Exception { + String type = conf.check(PROP_DBSTYLE); + // DBStyle的实现类总是 XXXStyle风格的命名,但大小写不一,所以需要循环判断一下 + for (Class klass : Scans.me().scanPackage(AbstractDBStyle.class.getPackage().getName())) { + if (klass.getName().endsWith("Style")) { + String name = klass.getSimpleName(); + name = name.substring(0, name.length() - 5); + if (name.toLowerCase().equals(type)) + return (DBStyle) klass.newInstance(); + } + } + throw new RuntimeException("unsupport DBStyle=" + type); + } + + @IocBean(name = "beetlsqlConnectionSource") + public ConnectionSource createConnectionSource(@Inject DataSource dataSource) { + DataSource[] slaves = null; + if (Lang.loadClassQuite("org.nutz.boot.starter.jdbc.DataSourceStarter") != null) { + DataSource slaveDataSource = DataSourceStarter.getSlaveDataSource(ioc, conf); + if (slaveDataSource != null) + slaves = new DataSource[] {slaveDataSource}; + } + if (conf.getBoolean(PROP_TRANS, true)) { + // 默认事务管理,就是没有管理 + return new DefaultConnectionSource(dataSource, slaves); + } + // 支持 Trans.exec 或者 @Aop(TransAop.READ_COMMITTED) + return new NutzConnectionSource(dataSource, slaves); + } + + @IocBean(name = "beetlsqlManager") + public SQLManager creatSQLManager(@Inject("refer:beetlsqlDBStyle") DBStyle dbStyle, + @Inject("beetlsqlConnectionSource") ConnectionSource ds) { + // BeetlSql默认/sql/,但NutzBoot的约定是/sqls/,入乡随俗吧 + SQLLoader loader = new ClasspathLoader(conf.get(PROP_PATH, "/sqls/")); + // TODO 支持更多种类的NameConversion + NameConversion nameconv = "default".equals(conf.get(PROP_NAME_CONVERSION, "default")) + ? new DefaultNameConversion() + : new UnderlinedNameConversion(); + // 是否插入debug拦截器呢? 默认启用好了 + if (conf.getBoolean(PROP_DEBUG, true)) + return new SQLManager(dbStyle, loader, ds, nameconv, new Interceptor[] { new DebugInterceptor() }); + return new SQLManager(dbStyle, loader, ds, nameconv); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.nutz.boot.starter.jdbc.DataSourceStarter$DynaDataSourceSeletor` acquired by call to `getSlaveDataSource(...)` at line 78 is not released after line 84. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +ConnectionSource BeetlSqlStarter.createConnectionSource(DataSource) + +### Procedure Id: +org.nutz.boot.starter.beetlsql.BeetlSqlStarter.createConnectionSource(javax.sql.DataSource):org.beet.7b6d9d317317c3e6e1bf2cf7239f3e27 + +### File: +nutzboot-starter/nutzboot-starter-beetlsql/src/main/java/org/nutz/boot/starter/beetlsql/BeetlSqlStarter.java + +### Key: +BeetlSqlStarter.java|createConnectionSource|RESOURCE_LEAK + +### Node Key: +4d9751f8fbc003a7fa964f8d5794988b + +### Hash: +164258b27ba8f2e589ac801ae80b9320 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9445/instruction.md b/inferredbugs-9445/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5abaf28b634fd10bcc832dfaffb99b5b32ac3714 --- /dev/null +++ b/inferredbugs-9445/instruction.md @@ -0,0 +1,580 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nutzboot +**Bug ID:** 25 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nutz.boot; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +import org.nutz.boot.aware.AppContextAware; +import org.nutz.boot.aware.ClassLoaderAware; +import org.nutz.boot.aware.EnvHolderAware; +import org.nutz.boot.aware.IocAware; +import org.nutz.boot.aware.ResourceLoaderAware; +import org.nutz.boot.banner.SimpleBannerPrinter; +import org.nutz.boot.config.ConfigureLoader; +import org.nutz.boot.config.impl.PropertiesConfigureLoader; +import org.nutz.boot.env.SystemPropertiesEnvHolder; +import org.nutz.boot.ioc.IocLoaderProvider; +import org.nutz.boot.metrics.impl.MemoryCounterService; +import org.nutz.boot.resource.ResourceLoader; +import org.nutz.boot.resource.impl.SimpleResourceLoader; +import org.nutz.boot.tools.NbAppEventListener; +import org.nutz.boot.tools.NbAppEventListener.EventType; +import org.nutz.boot.tools.PropDocReader; +import org.nutz.ioc.IocLoader; +import org.nutz.ioc.impl.NutIoc; +import org.nutz.ioc.loader.annotation.AnnotationIocLoader; +import org.nutz.ioc.loader.annotation.IocBean; +import org.nutz.ioc.loader.combo.ComboIocLoader; +import org.nutz.lang.Lang; +import org.nutz.lang.Mirror; +import org.nutz.lang.Stopwatch; +import org.nutz.lang.Streams; +import org.nutz.lang.Strings; +import org.nutz.lang.util.LifeCycle; +import org.nutz.log.Log; +import org.nutz.log.LogAdapter; +import org.nutz.log.Logs; +import org.nutz.mvc.Mvcs; +import org.nutz.mvc.annotation.IocBy; + +/** + * NutzBoot的主体 + * + * @author wendal + * + */ +public class NbApp extends Thread { + + /** + * 日志属性要等日志适配器准备好了才能加载,这里不可以使用Logs.get(); + */ + protected static Log log; + + /** + * 命令行参数 + */ + protected String[] args; + + /** + * 是否允许命令行下的 -Dxxx.xxx.xxx=转为配置参数 + */ + protected boolean allowCommandLineProperties = true; + + /** + * 是否打印配置文档 + */ + protected boolean printProcDoc; + + /** + * 主上下文 + */ + protected AppContext ctx; + + /** + * Starter共享的IocLoader + */ + protected AnnotationIocLoader starterIocLoader; + + /** + * Starter类列表 + */ + protected List> starterClasses; + + protected boolean prepared; + + protected Object lock = new Object(); + + protected List listeners = new LinkedList<>(); + + protected boolean started; + + /** + * 创建一个NbApp,把调用本构造方法的类作为mainClass + */ + public NbApp() { + ctx = AppContext.getDefault(); + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + /** + * 基于mainClass创建一个NbApp + * + * @param mainClass + * 主启动类 + */ + public NbApp(Class mainClass) { + ctx = AppContext.getDefault(); + setMainClass(mainClass); + } + + public NbApp(AppContext ctx) { + this.ctx = ctx; + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + public NbApp(AppContext ctx, Class mainClass) { + this.ctx = ctx; + setMainClass(mainClass); + } + + /** + * 设置命令行参数,可选 + */ + public NbApp setArgs(String[] args) { + this.args = args; + return this; + } + + /** + * 设置主启动类 + */ + public NbApp setMainClass(Class mainClass) { + this.ctx.setMainClass(mainClass); + return this; + } + + /** + * 是否允许从命令行读取配置信息, 例如 java -Dnutz.ioc.async.poolSize=128 xxx.jar + * + * @param flag + * 默认允许 + */ + public NbApp setAllowCommandLineProperties(boolean flag) { + this.allowCommandLineProperties = flag; + return this; + } + + /** + * 是否打印配置文档 + */ + public NbApp setPrintProcDoc(boolean printProcDoc) { + this.printProcDoc = printProcDoc; + return this; + } + + /** + * 获取全局上下文 + * + * @return + */ + public AppContext getAppContext() { + return ctx; + } + + public void run() { + try { + if (execute()) { + synchronized (lock) { + lock.wait(); + } + } + // 收尾 + _shutdown(); + } + catch (Throwable e) { + Logs.get().error("something happen", e); + } + } + + public boolean execute() { + Stopwatch sw = Stopwatch.begin(); + try { + // 各种预备操作 + listeners.forEach((listener)->listener.whenPrepare(this, EventType.before)); + this.prepare(); + listeners.forEach((listener)->listener.whenPrepare(this, EventType.after)); + + // 依次启动 + listeners.forEach((listener)->listener.whenInitAppContext(this, EventType.before)); + ctx.init(); + listeners.forEach((listener)->listener.whenInitAppContext(this, EventType.after)); + + listeners.forEach((listener)->listener.whenStartServers(this, EventType.before)); + ctx.startServers(); + listeners.forEach((listener)->listener.whenStartServers(this, EventType.after)); + + if (ctx.getMainClass().getAnnotation(IocBean.class) != null) + ctx.getIoc().get(ctx.getMainClass()); + + listeners.forEach((listener)->listener.afterAppStated(this)); + + sw.stop(); + log.infof("%s started : %sms", ctx.getConf().get("nutz.application.name", "NB"), sw.du()); + started = true; + return true; + } + catch (Throwable e) { + log.error("something happen!!", e); + return false; + } + } + + public void _shutdown() { + try { + ctx.stopServers(); + ctx.depose(); + } + catch (Exception e) { + throw Lang.wrapThrow(e); + } + } + + public void shutdown() { + log.info("ok, shutting down ..."); + if (lock == null) { + _shutdown(); + } + else { + synchronized (lock) { + lock.notify(); + } + } + } + + /** + * 执行预备操作 + */ + public void prepare() throws Exception { + if (prepared) + return; + // 初始化上下文 + listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before)); + this.prepareBasic(); + listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.after)); + + // 打印Banner,暂时不可配置具体的类 + new SimpleBannerPrinter().printBanner(ctx); + + // 配置信息要准备好 + + listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.before)); + this.prepareConfigureLoader(); + listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.after)); + + // 创建IocLoader体系 + listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.before)); + prepareIocLoader(); + listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.after)); + + // 加载各种starter + listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.before)); + prepareStarterClassList(); + listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.after)); + + // 打印配置文档 + if (printProcDoc) { + PropDocReader docReader = new PropDocReader(); + docReader.load(starterClasses); + Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); + } + + // 创建Ioc容器 + listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.before)); + prepareIoc(); + listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.after)); + + // 生成Starter实例 + listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.before)); + prepareStarterInstance(); + listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.after)); + + // 从Ioc容器检索Listener + listeners.addAll(ctx.getBeans(NbAppEventListener.class)); + + prepared = true; + } + + public void prepareBasic() throws Exception { + // 检查ClassLoader的情况 + if (ctx.getClassLoader() == null) + ctx.setClassLoader(NbApp.class.getClassLoader()); + + if (ctx.getEnvHolder() == null) { + ctx.setEnvHolder(new SystemPropertiesEnvHolder()); + } + + // 看看日志应该用哪个 + String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); + if (!Strings.isBlank(logAdapter)) { + Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); + } + log = Logs.get(); + // 资源加载器 + if (ctx.getResourceLoader() == null) { + ResourceLoader resourceLoader = new SimpleResourceLoader(); + aware(resourceLoader); + ctx.setResourceLoader(resourceLoader); + } + } + + public void prepareConfigureLoader() throws Exception { + if (ctx.getConfigureLoader() == null) { + ConfigureLoader configureLoader = null; + InputStream ins = ctx.getResourceLoader().get("META-INF/nutz/org.nutz.boot.config.ConfigureLoader"); + if (ins != null) { + String cnfLoader = new String(Streams.readBytes(ins)).trim(); + if (!Strings.isBlank(cnfLoader)) { + log.debugf("using %s as ConfigureLoader", cnfLoader); + configureLoader = (ConfigureLoader) ctx.getClassLoader().loadClass(cnfLoader).newInstance(); + } + } + if (configureLoader == null) { + configureLoader = new PropertiesConfigureLoader(); + } + configureLoader.setCommandLineProperties(allowCommandLineProperties, args); + aware(configureLoader); + ctx.setConfigureLoader(configureLoader); + if (configureLoader instanceof LifeCycle) + ((LifeCycle) configureLoader).init(); + } + } + + public void prepareIocLoader() throws Exception { + if (ctx.getComboIocLoader() == null) { + int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); + List args = new ArrayList<>(); + args.add("*js"); + args.add("ioc/"); + args.add("*tx"); + args.add("*async"); + args.add("" + asyncPoolSize); + args.add("*anno"); + args.add(ctx.getPackage()); + IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); + if (iocBy != null) { + String[] tmp = iocBy.args(); + ArrayList _args = new ArrayList<>(); + for (int i = 0; i < tmp.length; i++) { + if (tmp[i].startsWith("*")) { + if (!_args.isEmpty()) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + _args.clear(); + } + } + _args.add(tmp[i]); + } + if (_args.size() > 0) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + } + } + ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); + } + // 用于加载Starter的IocLoader + starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); + ctx.getComboIocLoader().addLoader(starterIocLoader); + } + + public void prepareStarterClassList() throws Exception { + starterClasses = new ArrayList<>(); + HashSet classNames = new HashSet<>(); + Enumeration _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter"); + while (_en.hasMoreElements()) { + URL url = _en.nextElement(); + log.debug("Found " + url); + try (InputStream ins = url.openStream()) { + InputStreamReader reader = new InputStreamReader(ins); + String tmp = Streams.readAndClose(reader); + if (!Strings.isBlank(tmp)) { + for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) { + String className = _tmp.trim(); + if (!classNames.add(className)) + continue; + Class klass = ctx.getClassLoader().loadClass(className); + if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) { + starterIocLoader.addClass(klass); + } + starterClasses.add(klass); + } + } + } + } + } + + public void prepareIoc() { + if (ctx.getIoc() == null) { + ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); + } + // 把核心对象放进ioc容器 + if (!ctx.ioc.has("appContext")) { + ctx.ioc.addBean("appContext", ctx); + ctx.ioc.addBean("conf", ctx.getConf()); + ctx.ioc.addBean("nbApp", this); + // 添加更多扩展bean + ctx.ioc.addBean("counterService", new MemoryCounterService()); + } + Mvcs.ctx().iocs.put("nutz", ctx.getIoc()); + } + + public void prepareStarterInstance() { + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + obj = Mirror.me(klass).born(); + } else { + continue; + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + continue; + } else { + obj = ctx.getIoc().get(klass); + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + } + + protected void aware(Object obj) { + // 需要注入AppContext + if (obj instanceof AppContextAware) { + ((AppContextAware) obj).setAppContext(ctx); + } + // 需要注入ClassLoader + if (obj instanceof ClassLoaderAware) { + ((ClassLoaderAware) obj).setClassLoader(ctx.getClassLoader()); + } + // 需要注入EnvHolder + if (obj instanceof EnvHolderAware) { + ((EnvHolderAware) obj).setEnvHolder(ctx.getEnvHolder()); + } + // 需要注入ResourceLoader + if (obj instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) obj).setResourceLoader(ctx.getResourceLoader()); + } + // 需要注入Ioc + if (obj instanceof IocAware) { + ((IocAware) obj).setIoc(ctx.getIoc()); + } + } + + public void setListener(NbAppEventListener listener) { + this.listeners.clear(); + addListener(listener); + } + + public void addListener(NbAppEventListener listener) { + this.listeners.add(listener); + } + + public boolean isStarted() { + return started; + } + + public void setMainPackage(String mainPackage) { + getAppContext().setMainPackage(mainPackage); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.nutz.boot.NbApp.prepare` indirectly reads without synchronization from `this.org.nutz.boot.NbApp.ctx.org.nutz.boot.AppContext.resourceLoader`. Potentially races with write in method `NbApp.run()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NbApp.prepare() + +### Procedure Id: +org.nutz.boot.NbApp.prepare():void.3497bd920679b1a589201156049c849c + +### File: +nutzboot-core/src/main/java/org/nutz/boot/NbApp.java + +### Key: +NbApp.java|prepare|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +41aab7de1410eeaccb40e67d6dbb9516 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9472/instruction.md b/inferredbugs-9472/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0066d6b2a4f41eaafe20eb4f135ee7f13020c567 --- /dev/null +++ b/inferredbugs-9472/instruction.md @@ -0,0 +1,624 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** zalenium +**Bug ID:** 14 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.zalando.ep.zalenium.container.swarm; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Strings; +import com.spotify.docker.client.AnsiProgressHandler; +import com.spotify.docker.client.DefaultDockerClient; +import com.spotify.docker.client.DockerClient; +import com.spotify.docker.client.exceptions.DockerException; +import com.spotify.docker.client.messages.*; +import com.spotify.docker.client.messages.mount.Mount; +import com.spotify.docker.client.messages.swarm.*; +import de.zalando.ep.zalenium.container.ContainerClient; +import de.zalando.ep.zalenium.container.ContainerClientRegistration; +import de.zalando.ep.zalenium.container.ContainerCreationStatus; +import de.zalando.ep.zalenium.proxy.DockeredSeleniumStarter; +import de.zalando.ep.zalenium.util.Environment; +import de.zalando.ep.zalenium.util.GoogleAnalyticsApi; +import de.zalando.ep.zalenium.util.ZaleniumConfiguration; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.RandomStringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; + +import static com.spotify.docker.client.DockerClient.ListContainersParam.withStatusCreated; +import static com.spotify.docker.client.DockerClient.ListContainersParam.withStatusRunning; + +@SuppressWarnings("ConstantConditions") +public class SwarmContainerClient implements ContainerClient { + + private static final String ZALENIUM_SELENIUM_CONTAINER_CPU_LIMIT = "ZALENIUM_SELENIUM_CONTAINER_CPU_LIMIT"; + private static final String ZALENIUM_SELENIUM_CONTAINER_MEMORY_LIMIT = "ZALENIUM_SELENIUM_CONTAINER_MEMORY_LIMIT"; + + private static final String SWARM_EXEC_IMAGE = "datagridsys/skopos-plugin-swarm-exec:latest"; + + private static final Environment defaultEnvironment = new Environment(); + + private static Environment env = defaultEnvironment; + private static String seleniumContainerCpuLimit; + private static String seleniumContainerMemoryLimit; + private static String dockerHost; + private static AtomicBoolean environmentInitialised = new AtomicBoolean(false); + + static { + readConfigurationFromEnvVariables(); + } + + private final Logger logger = LoggerFactory.getLogger(SwarmContainerClient.class.getName()); + private final GoogleAnalyticsApi ga = new GoogleAnalyticsApi(); + private DockerClient dockerClient = new DefaultDockerClient(dockerHost); + private String nodeId; + private Map seleniumContainerLabels = new HashMap<>(); + private AtomicBoolean seleniumContainerLabelsChecked = new AtomicBoolean(false); + + private static void readConfigurationFromEnvVariables() { + + String cpuLimit = env.getEnvVariable(ZALENIUM_SELENIUM_CONTAINER_CPU_LIMIT); + setSeleniumContainerCpuLimit(cpuLimit); + + String memoryLimit = env.getEnvVariable(ZALENIUM_SELENIUM_CONTAINER_MEMORY_LIMIT); + setSeleniumContainerMemoryLimit(memoryLimit); + + String dockerHost = env.getStringEnvVariable("DOCKER_HOST", "unix:///var/run/docker.sock"); + setDockerHost(dockerHost); + } + + @VisibleForTesting + protected static void setEnv(final Environment env) { + SwarmContainerClient.env = env; + } + + private static void setDockerHost(String dockerHost) { + // https://github.com/spotify/docker-client/issues/946 + SwarmContainerClient.dockerHost = dockerHost.replace("tcp", "http"); + } + + private static String getSeleniumContainerCpuLimit() { + return seleniumContainerCpuLimit; + } + + private static void setSeleniumContainerCpuLimit(String seleniumContainerCpuLimit) { + SwarmContainerClient.seleniumContainerCpuLimit = seleniumContainerCpuLimit; + } + + private static String getSeleniumContainerMemoryLimit() { + return seleniumContainerMemoryLimit; + } + + private static void setSeleniumContainerMemoryLimit(String seleniumContainerMemoryLimit) { + SwarmContainerClient.seleniumContainerMemoryLimit = seleniumContainerMemoryLimit; + } + + public void setNodeId(String nodeId) { + this.nodeId = nodeId; + } + + private String getContainerId(URL remoteUrl) { + try { + List tasks = dockerClient.listTasks(); + for (Task task : tasks) { + for (NetworkAttachment networkAttachment : CollectionUtils.emptyIfNull(task.networkAttachments())) { + for (String address : networkAttachment.addresses()) { + if (address.startsWith(remoteUrl.getHost())) { + return task.status().containerStatus().containerId(); + } + } + } + } + } catch (DockerException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + } + + private String getContainerId(String containerName) { + final String containerNameSearch = containerName.contains("/") ? + containerName : String.format("/%s", containerName); + + List containerList = null; + try { + containerList = dockerClient.listContainers(withStatusRunning(), withStatusCreated()); + } catch (DockerException | InterruptedException e) { + logger.debug(nodeId + " Error while getting containerId", e); + ga.trackException(e); + } + + if (containerList != null) { + String containerByName = containerList.stream() + .filter(container -> containerNameSearch.equalsIgnoreCase(container.names().get(0))) + .findFirst().map(Container::id).orElse(containerName); + return containerByName != null ? containerByName : containerList.stream() + .filter(container -> container.names().get(0).contains(containerName)) + .findFirst().map(Container::id).orElse(containerName); + } else { + return containerName; + } + } + + public InputStream copyFiles(String containerId, String folderName) { + // TODO: Implement behaviour + return null; + } + + public void stopContainer(String containerId) { + try { + List tasks = dockerClient.listTasks(); + for (Task task : tasks) { + ContainerStatus containerStatus = task.status().containerStatus(); + if (containerStatus != null && containerStatus.containerId().equals(containerId)) { + String serviceId = task.serviceId(); + Service.Criteria criteria = Service.Criteria.builder() + .serviceId(serviceId) + .build(); + List services = dockerClient.listServices(criteria); + if (!CollectionUtils.isEmpty(services)) { + dockerClient.removeService(serviceId); + } + } + } + } catch (DockerException | InterruptedException e) { + logger.warn(nodeId + " Error while stopping the container", e); + ga.trackException(e); + } + } + + public void executeCommand(String containerId, String[] command, boolean waitForExecution) { + try { + List tasks = dockerClient.listTasks(); + + pullSwarmExecImage(); + + for (Task task : CollectionUtils.emptyIfNull(tasks)) { + ContainerStatus containerStatus = task.status().containerStatus(); + + if (containerStatus != null && containerStatus.containerId().equals(containerId)) { + startSwarmExecContainer(task, command, containerId); + return; + } + } + } catch (DockerException | InterruptedException e) { + logger.warn("Error while executing comman on container {}", containerId); + ga.trackException(e); + } + + logger.warn("Couldn't execute command on container {}", containerId); + } + + private void pullSwarmExecImage() { + try { + List images = dockerClient.listImages(DockerClient.ListImagesParam.byName(SWARM_EXEC_IMAGE)); + if (CollectionUtils.isEmpty(images)) { + dockerClient.pull(SWARM_EXEC_IMAGE, new AnsiProgressHandler()); + } + } catch (DockerException | InterruptedException e) { + logger.warn(nodeId + " Error while checking (and pulling) if the image is present", e); + ga.trackException(e); + } + } + + private void startSwarmExecContainer(Task task, String[] command, String containerId) throws DockerException, InterruptedException { + String taskId = task.id(); + + List binds = new ArrayList<>(); + binds.add("/var/run/docker.sock:/var/run/docker.sock"); + + HostConfig.Builder hostConfigBuilder = HostConfig.builder() + .autoRemove(true) + .appendBinds(binds); + + HostConfig hostConfig = hostConfigBuilder.build(); + + command[0] = "task-exec"; + command[1] = taskId; + + logger.debug("Executing command: {} - on Container: {}", + Arrays.toString(command), + containerId); + + ContainerConfig containerConfig = ContainerConfig.builder() + .image(SWARM_EXEC_IMAGE) + .hostConfig(hostConfig) + .cmd(command) + .build(); + + ContainerCreation containerCreation = dockerClient.createContainer(containerConfig); + + dockerClient.startContainer(containerCreation.id()); + } + + public String getLatestDownloadedImage(String imageName) { + // TODO: verify this is handled by docker + return imageName; + } + + public ContainerCreationStatus createContainer(String zaleniumContainerName, String image, Map envVars, + String nodePort) { + // TODO: is it meaningful to add labels to identify services/containers in the swarm? + + List flattenedEnvVars = envVars.entrySet().stream() + .map(e -> e.getKey() + "=" + e.getValue()) + .collect(Collectors.toList()); + final ContainerSpec containerSpec = buildContainerSpec(flattenedEnvVars, image); + + final TaskSpec taskSpec = buildTaskSpec(containerSpec); + + String noVncPort = envVars.get("NOVNC_PORT"); + final ServiceSpec serviceSpec = buildServiceSpec(taskSpec, nodePort, noVncPort); + + try { + ServiceCreateResponse service = dockerClient.createService(serviceSpec); + + TaskStatus taskStatus = waitForTaskStatus(service.id()); + + if (taskStatus != null) { + return getContainerCreationStatus(service.id(), nodePort); + } + } catch (DockerException | InterruptedException e) { + e.printStackTrace(); + } + + logger.debug("Something went wrong while creating service"); + return null; + } + + private ContainerSpec buildContainerSpec(List flattenedEnvVars, String image) { + final Mount.Builder mountBuilder = Mount.builder() + .source("/dev/shm") + .target("/dev/shm") + .type("bind"); + + final ContainerSpec.Builder containerSpecBuilder = ContainerSpec.builder() + .env(flattenedEnvVars) + .image(image) + .mounts(mountBuilder.build()); + + loadSeleniumContainerLabels(); + + if (seleniumContainerLabels.size() > 0) { + containerSpecBuilder.labels(seleniumContainerLabels); + } + + return containerSpecBuilder.build(); + } + + private TaskSpec buildTaskSpec(ContainerSpec containerSpec) { + final RestartPolicy restartPolicy = RestartPolicy.builder() + .condition("on-failure") + .build(); + + final List placementList = new ArrayList<>(); + + placementList.add("node.role==worker"); + + final Placement placement = Placement.create(placementList); + + Resources.Builder resourceBuilder = Resources.builder(); + String cpuLimit = getSeleniumContainerCpuLimit(); + String memLimit = getSeleniumContainerMemoryLimit(); + + if (!Strings.isNullOrEmpty(cpuLimit)) { + resourceBuilder.nanoCpus(Long.valueOf(cpuLimit)); + } + + if (!Strings.isNullOrEmpty(memLimit)) { + resourceBuilder.memoryBytes(Long.valueOf(memLimit)); + } + + ResourceRequirements resourceRequirements = ResourceRequirements.builder() + .limits(resourceBuilder.build()) + .build(); + + final TaskSpec.Builder taskSpecBuilder = TaskSpec.builder() + .resources(resourceRequirements) + .restartPolicy(restartPolicy) + .placement(placement) + .containerSpec(containerSpec); + + return taskSpecBuilder.build(); + } + + private ServiceSpec buildServiceSpec(TaskSpec taskSpec, String nodePort, String noVncPort) { + final PortConfig nodePortConfig = PortConfig.builder() + .targetPort(Integer.valueOf(nodePort)) + .publishedPort(Integer.valueOf(nodePort)) + .build(); + + final PortConfig noVncPortConfig = PortConfig.builder() + .targetPort(Integer.valueOf(noVncPort)) + .publishedPort(Integer.valueOf(noVncPort)) + .build(); + + final EndpointSpec.Builder endpointSpecBuilder = EndpointSpec.builder() + .addPort(nodePortConfig) + .addPort(noVncPortConfig); + + final NetworkAttachmentConfig networkAttachmentConfig = NetworkAttachmentConfig.builder() + .target(ZaleniumConfiguration.getSwarmOverlayNetwork()) + .build(); + + return ServiceSpec.builder() + .name(generateServiceName()) + .endpointSpec(endpointSpecBuilder.build()) + .networks(networkAttachmentConfig) + .taskTemplate(taskSpec) + .build(); + } + + private TaskStatus waitForTaskStatus(String serviceId) throws DockerException, InterruptedException { + return waitForTaskStatus(serviceId, 0); + } + + private TaskStatus waitForTaskStatus(String serviceId, int attempts) throws DockerException, InterruptedException { + int attemptsLimit = 100; + Thread.sleep(100); + String serviceName = dockerClient.inspectService(serviceId).spec().name(); + Task.Criteria criteria = Task.Criteria.builder().serviceName(serviceName).build(); + List tasks = dockerClient.listTasks(criteria); + Task task = null; + + if (!CollectionUtils.isEmpty(tasks)) { + task = tasks.get(0); + } + + if (task == null && attempts < attemptsLimit) { + return waitForTaskStatus(serviceId, attempts + 1); + } else { + ContainerStatus containerStatus = task.status().containerStatus(); + if (containerStatus == null) { + return waitForTaskStatus(serviceId, attempts + 1); + } + + logger.debug("container {} is ready", containerStatus.containerId()); + + return task.status(); + } + } + + private ContainerCreationStatus getContainerCreationStatus(String serviceId, String nodePort) throws DockerException, InterruptedException { + Service service = dockerClient.inspectService(serviceId); + Task.Criteria criteria = Task.Criteria.builder() + .serviceName(service.spec().name()) + .build(); + List tasks = dockerClient.listTasks(criteria); + for (Task task : tasks) { + if (task.serviceId().equals(serviceId)) { + ContainerStatus containerStatus = task.status().containerStatus(); + if (containerStatus != null) { + String containerId = containerStatus.containerId(); + String containerName = containerStatus.containerId(); + return new ContainerCreationStatus(true, containerName, containerId, nodePort); + } + } + } + + return null; + } + + private String generateServiceName() { + final String suffix = RandomStringUtils.randomAlphanumeric(6); + return String.format("node_%s", suffix); + } + + private void loadSeleniumContainerLabels() { + if (!this.seleniumContainerLabelsChecked.getAndSet(true)) { + String containerLabels = env.getStringEnvVariable("SELENIUM_CONTAINER_LABELS", ""); + if (containerLabels.length() == 0) { + return; + } + try { + for (String label : containerLabels.split(";")) { + String[] split = label.split("="); + seleniumContainerLabels.put(split[0], split[1]); + } + } catch (Exception e) { + logger.warn(nodeId + " Error while retrieving the added labels for the Selenium containers.", e); + ga.trackException(e); + } + } + } + + @Override + public void initialiseContainerEnvironment() { + if (!environmentInitialised.getAndSet(true)) { + // Delete any leftover services from a previous time + deleteSwarmServices(); + // Register a shutdown hook to cleanup pods + Runtime.getRuntime().addShutdownHook(new Thread(this::deleteSwarmServices, "SwarmContainerClient shutdown hook")); + } + } + + private void deleteSwarmServices() { + // TODO: Implement functionality + } + + @Override + public ContainerClientRegistration registerNode(String zaleniumContainerName, URL remoteHost) { + ContainerClientRegistration registration = new ContainerClientRegistration(); + + Integer noVncPort = remoteHost.getPort() + DockeredSeleniumStarter.NO_VNC_PORT_GAP; + + String containerId = this.getContainerId(remoteHost); + + if (containerId == null) { + logger.warn("No container id for {} - {}, can't register.", zaleniumContainerName, remoteHost.toExternalForm()); + } + + registration.setNoVncPort(noVncPort); + registration.setContainerId(containerId); + registration.setIpAddress(remoteHost.getHost()); + return registration; + } + + @Override + public String getContainerIp(String containerName) { + String containerId = this.getContainerId(containerName); + + if (containerId == null) { + logger.warn("Failed to get id of container: {} ", containerName); + return null; + } + + try { + List tasks = dockerClient.listTasks(); + String swarmOverlayNetwork = ZaleniumConfiguration.getSwarmOverlayNetwork(); + for (Task task : tasks) { + ContainerStatus containerStatus = task.status().containerStatus(); + if (containerStatus != null) { + if (containerStatus.containerId().equals(containerId)) { + for (NetworkAttachment networkAttachment : CollectionUtils.emptyIfNull(task.networkAttachments())) { + if (networkAttachment.network().spec().name().equals(swarmOverlayNetwork)) { + String cidrSuffix = "/\\d+$"; + return networkAttachment.addresses().get(0).replaceAll(cidrSuffix, ""); + } + } + } + } + } + } catch (DockerException | InterruptedException e) { + logger.debug(nodeId + " Error while getting the container IP.", e); + ga.trackException(e); + } + + logger.warn("Failed to get ip of container: {}", containerName); + return null; + } + + @Override + public boolean isReady(ContainerCreationStatus container) { + String containerIp = this.getContainerIp(container.getContainerName()); + if (containerIp != null) { + try { + URL statusUrl = new URL(String.format("http://%s:%s/wd/hub/status", containerIp, container.getNodePort())); + String status = IOUtils.toString(statusUrl, StandardCharsets.UTF_8); + String successMessage = "\"Node is running\""; + if (status.contains(successMessage)) { + return true; + } + } catch (IOException e) { + logger.debug("Error while getting node status, probably the node is still starting up...", e); + } + } + return false; + } + + @Override + public boolean isTerminated(ContainerCreationStatus container) { + try { + List termStates = Arrays.asList("complete", "failed", "shutdown", "rejected", "orphaned", "removed"); + String containerId = container.getContainerId(); + List tasks = dockerClient.listTasks(); + boolean containerExists = tasks.stream().anyMatch(task -> { + ContainerStatus containerStatus = task.status().containerStatus(); + return containerStatus != null && containerStatus.containerId().equals(containerId); + }); + + if (!containerExists) { + logger.info("Container {} has no corresponding task - flagging it as terminated", container); + return true; + } else { + return tasks.stream().anyMatch(task -> { + ContainerStatus containerStatus = task.status().containerStatus(); + boolean hasTerminalState = termStates.contains(task.status().state()); + boolean isContainer = containerStatus != null && containerStatus.containerId().equals(containerId); + boolean isTerminated = isContainer && hasTerminalState; + + if (isTerminated) { + logger.info("State of Container {} is {} - flagging it as terminated", + container.getContainerId(), + task.status().state()); + } + + return isTerminated; + }); + } + } catch (DockerException | InterruptedException e) { + logger.warn("Failed to fetch container status [" + container.getContainerId() + "].", e); + return false; + } + } +} + + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `containerStatus.containerId()` at line 477. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String SwarmContainerClient.getContainerIp(String) + +### Procedure Id: +de.zalando.ep.zalenium.container.swarm.SwarmContainerClient.getContainerIp(java.lang.String):java.la.b3196ce320e791b25607a27c8ba759ad + +### File: +src/main/java/de/zalando/ep/zalenium/container/swarm/SwarmContainerClient.java + +### Key: +SwarmContainerClient.java|getContainerIp|NULL_DEREFERENCE + +### Node Key: +7e9fc31bc469440d6384630f8b346526 + +### Hash: +dbc8ddfcb2a81087d27ff6601b518b9b + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9480/instruction.md b/inferredbugs-9480/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..420d834d9baeb3e367b19e7c715101f94068d1c7 --- /dev/null +++ b/inferredbugs-9480/instruction.md @@ -0,0 +1,113 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** niubi-job +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2002-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.zuoxiaolong.niubi.job.examples; + +import com.zuoxiaolong.niubi.job.cluster.node.StandbyNode; +import com.zuoxiaolong.niubi.job.scheduler.node.Node; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * @author Xiaolong Zuo + * @since 16/1/9 15:08 + */ +public class StandbyNodeTest { + + @org.junit.Test + public void test() throws InterruptedException, IOException { + Node node = new StandbyNode("localhost:2181,localhost:3181,localhost:4181", "http://localhost:8080/job"); + node.join(); + new BufferedReader(new InputStreamReader(System.in)).readLine(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.curator.framework.recipes.cache.PathChildrenCache` acquired by call to `StandbyNode(...)` at line 34 is not released after line 35. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void StandbyNodeTest.test() + +### Procedure Id: +com.zuoxiaolong.niubi.job.examples.StandbyNodeTest.test():void.92351daf9a3f4e88243bb02d5d30849d + +### File: +niubi-job-examples/src/test/java/com/zuoxiaolong/niubi/job/examples/StandbyNodeTest.java + +### Key: +StandbyNodeTest.java|test|RESOURCE_LEAK + +### Node Key: +da745a12a141ace2ebc92b29fe00e65f + +### Hash: +e69cc42301dcf63350d3ec4852562cdf + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9481/instruction.md b/inferredbugs-9481/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..03c754b306f490e14485ed754c278a1e82c71e5a --- /dev/null +++ b/inferredbugs-9481/instruction.md @@ -0,0 +1,232 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** craft-atom +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.craft.atom.util; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * Io Util class + * + * @author Frank Hu + * @version 1.0, 2009-9-1 + */ +public class FileUtil { + + private static final int BUFFER_SIZE = 16 * 1024; + + private FileUtil() { + throw new UnsupportedOperationException(); + } + + /** + * Read input stream as bytes + * + * @param inputStream + * @return + * @throws IOException + */ + public static byte[] readInputStream(InputStream inputStream) throws IOException { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[16 * 1024]; + + int bytesRead = inputStream.read(buffer); + while (bytesRead != -1) { + outputStream.write(buffer, 0, bytesRead); + bytesRead = inputStream.read(buffer); + } + + return outputStream.toByteArray(); + } + + /** + * Read a file as string + * + * @param filePath + * @return + * @throws IOException + */ + public static String readFileAsString(String filePath) throws IOException { + byte[] buffer = new byte[(int) getFile(filePath).length()]; + BufferedInputStream inputStream = null; + try { + inputStream = new BufferedInputStream(new FileInputStream(getFile(filePath))); + inputStream.read(buffer); + } finally { + inputStream.close(); + } + return new String(buffer); + } + + /** + * Write string to a file + * + * @param content + * @param filePath + * @throws Exception + */ + public static void writeStringToFile(String content, String filePath) + throws Exception { + BufferedOutputStream outputStream = null; + try { + outputStream = new BufferedOutputStream(new FileOutputStream(getFile(filePath))); + outputStream.write(content.getBytes()); + outputStream.flush(); + } finally { + outputStream.close(); + } + } + + /** + * Get file from a file path. + * + * @param filePath + * @return + * @throws IOException + */ + public static File getFile(String filePath) throws IOException { + return new File(filePath); + } + + /** + * Copy a file + * + * @param src + * @param dst + * @throws IOException + */ + public static void copy(File src, File dst) throws IOException { + InputStream in = null; + OutputStream out = null; + try { + in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); + out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); + byte[] buffer = new byte[BUFFER_SIZE]; + while (in.read(buffer) > 0) { + out.write(buffer); + } + } finally { + if (null != in) { + in.close(); + } + if (null != out) { + out.close(); + } + } + } + + /** + * Get a file suffix name + * + * @param file + * @return + */ + public static String suffix(File file) { + String name = file.getName(); + int pos = name.lastIndexOf("."); + return name.substring(pos); + } + + /** + * Get a file suffix name + * + * @param file + * @return + */ + public static String suffix(String fileName) { + int pos = fileName.lastIndexOf("."); + return fileName.substring(pos); + } + + /** + * Delete a file according to a file path + * + * @param filePath + * @return + * @throws IOException + */ + public static boolean delete(String filePath) throws IOException { + File file = getFile(filePath); + return file.delete(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `inputStream` last assigned on line 56 could be null and is dereferenced at line 61. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String FileUtil.readFileAsString(String) + +### Procedure Id: +org.craft.atom.util.FileUtil.readFileAsString(java.lang.String):java.lang.String.8936fac3e93f64e51ee502846f9c640e + +### File: +craft-atom-util/src/main/java/org/craft/atom/util/FileUtil.java + +### Key: +FileUtil.java|readFileAsString|NULL_DEREFERENCE + +### Node Key: +5aca16f4905ed8a604b17a95d9409de0 + +### Hash: +2221d8090f8f6960683a0db27e919700 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9486/instruction.md b/inferredbugs-9486/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6236f4d6107224d2aca9e35b834113ae812dd5d9 --- /dev/null +++ b/inferredbugs-9486/instruction.md @@ -0,0 +1,268 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jpmml-sklearn +**Bug ID:** 32 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2016 Villu Ruusmann + * + * This file is part of JPMML-SkLearn + * + * JPMML-SkLearn is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * JPMML-SkLearn 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with JPMML-SkLearn. If not, see . + */ +package sklearn.pipeline; + +import java.util.List; + +import org.dmg.pmml.DataType; +import org.dmg.pmml.MiningFunction; +import org.dmg.pmml.Model; +import org.dmg.pmml.OpType; +import org.jpmml.converter.Feature; +import org.jpmml.converter.Schema; +import org.jpmml.sklearn.ClassDictUtil; +import org.jpmml.sklearn.SkLearnEncoder; +import org.jpmml.sklearn.TupleUtil; +import sklearn.Estimator; +import sklearn.EstimatorUtil; +import sklearn.HasClasses; +import sklearn.HasNumberOfFeatures; +import sklearn.Transformer; +import sklearn.TransformerUtil; + +public class Pipeline extends Estimator implements HasClasses { + + public Pipeline(String module, String name){ + super(module, name); + } + + @Override + public MiningFunction getMiningFunction(){ + Estimator estimator = getEstimator(); + + return estimator.getMiningFunction(); + } + + @Override + public boolean isSupervised(){ + Estimator estimator = getEstimator(); + + return estimator.isSupervised(); + } + + @Override + public int getNumberOfFeatures(){ + List transformers = getTransformers(); + Estimator estimator = getEstimator(); + + for(Transformer transformer : transformers){ + + if(transformer instanceof HasNumberOfFeatures){ + HasNumberOfFeatures hasNumberOfFeatures = (HasNumberOfFeatures)transformer; + + return hasNumberOfFeatures.getNumberOfFeatures(); + } + } + + return estimator.getNumberOfFeatures(); + } + + @Override + public OpType getOpType(){ + List transformers = getTransformers(); + Estimator estimator = getEstimator(); + + for(Transformer transformer : transformers){ + OpType opType = transformer.getOpType(); + + if(opType != null){ + return opType; + } + } + + return estimator.getOpType(); + } + + @Override + public DataType getDataType(){ + List transformers = getTransformers(); + Estimator estimator = getEstimator(); + + for(Transformer transformer : transformers){ + DataType dataType = transformer.getDataType(); + + if(dataType != null){ + return dataType; + } + } + + return estimator.getDataType(); + } + + @Override + public List getClasses(){ + Estimator estimator = getEstimator(); + + return EstimatorUtil.getClasses(estimator); + } + + @Override + public Model encodeModel(Schema schema){ + throw new UnsupportedOperationException(); + } + + @Override + public Model encodeModel(Schema schema, SkLearnEncoder encoder){ + List transformers = getTransformers(); + Estimator estimator = getEstimator(); + + if(transformers.size() > 0){ + List ids = encoder.getIds(); + List features = encoder.getFeatures(); + + for(Transformer transformer : transformers){ + + if(transformer instanceof HasNumberOfFeatures){ + HasNumberOfFeatures hasNumberOfFeatures = (HasNumberOfFeatures)transformer; + + int numberOfFeatures = hasNumberOfFeatures.getNumberOfFeatures(); + if(numberOfFeatures > -1){ + ClassDictUtil.checkSize(numberOfFeatures, ids, features); + } + } + + for(Feature feature : features){ + encoder.updateType(feature.getName(), transformer.getOpType(), transformer.getDataType()); + } + + features = transformer.encodeFeatures(ids, features, encoder); + } + + schema = new Schema(schema.getLabel(), features); + } + + List features = schema.getFeatures(); + + int numberOfFeatures = estimator.getNumberOfFeatures(); + if(numberOfFeatures > -1){ + ClassDictUtil.checkSize(numberOfFeatures, features); + } + + return estimator.encodeModel(schema, encoder); + } + + public List getTransformers(){ + List transformerSteps = getTransformerSteps(); + + return TransformerUtil.asTransformerList(TupleUtil.extractElementList(transformerSteps, 1)); + } + + public List getTransformerSteps(){ + List steps = getSteps(); + + if(steps.size() < 1){ + throw new IllegalArgumentException("Missing estimator step"); + } + + return steps.subList(0, steps.size() - 1); + } + + public Estimator getEstimator(){ + Object[] estimatorStep = getEstimatorStep(); + + return EstimatorUtil.asEstimator(TupleUtil.extractElement(estimatorStep, 1)); + } + + protected Object[] getEstimatorStep(){ + List steps = getSteps(); + + if(steps.size() < 1){ + throw new IllegalArgumentException("Missing estimator step"); + } + + return steps.get(steps.size() - 1); + } + + public List getSteps(){ + return (List)get("steps"); + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `steps` last assigned on line 183 could be null and is dereferenced at line 185. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +java.lang.Object[] Pipeline.getEstimatorStep() + +### Procedure Id: +sklearn.pipeline.Pipeline.getEstimatorStep():java.lang.Object[].2ee963bab4fb91a740ac05d4ddce8e40 + +### File: +src/main/java/sklearn/pipeline/Pipeline.java + +### Key: +Pipeline.java|getEstimatorStep|NULL_DEREFERENCE + +### Node Key: +18086a76ec6f499138a84f176568ec09 + +### Hash: +11d126c375f8b0b463a922f3e8a34efe + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9488/instruction.md b/inferredbugs-9488/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..69d3cedc6933d40360a8135a60d7685b1a043022 --- /dev/null +++ b/inferredbugs-9488/instruction.md @@ -0,0 +1,215 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jpmml-sklearn +**Bug ID:** 34 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2016 Villu Ruusmann + * + * This file is part of JPMML-SkLearn + * + * JPMML-SkLearn is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * JPMML-SkLearn 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with JPMML-SkLearn. If not, see . + */ +package sklearn.pipeline; + +import java.util.List; + +import org.dmg.pmml.DataType; +import org.dmg.pmml.OpType; +import org.jpmml.converter.Feature; +import org.jpmml.sklearn.ClassDictUtil; +import org.jpmml.sklearn.SkLearnEncoder; +import org.jpmml.sklearn.TupleUtil; +import sklearn.Estimator; +import sklearn.EstimatorUtil; +import sklearn.HasNumberOfFeatures; +import sklearn.Transformer; +import sklearn.TransformerUtil; + +public class Pipeline extends Transformer { + + private boolean flexible = false; + + + public Pipeline(){ + this("sklearn.pipeline", "Pipeline"); + } + + public Pipeline(String module, String name){ + this(module, name, false); + } + + protected Pipeline(String module, String name, boolean flexible){ + super(module, name); + + setFlexible(flexible); + } + + @Override + public OpType getOpType(){ + List transformers = getTransformers(); + + for(Transformer transformer : transformers){ + return transformer.getOpType(); + } + + throw new IllegalArgumentException(); + } + + @Override + public DataType getDataType(){ + List transformers = getTransformers(); + + for(Transformer transformer : transformers){ + return transformer.getDataType(); + } + + throw new IllegalArgumentException(); + } + + @Override + public List encodeFeatures(List features, SkLearnEncoder encoder){ + List transformers = getTransformers(); + + for(Transformer transformer : transformers){ + + if(transformer instanceof HasNumberOfFeatures){ + HasNumberOfFeatures hasNumberOfFeatures = (HasNumberOfFeatures)transformer; + + int numberOfFeatures = hasNumberOfFeatures.getNumberOfFeatures(); + if(numberOfFeatures > -1){ + ClassDictUtil.checkSize(numberOfFeatures, features); + } + } + + encoder.updateFeatures(features, transformer); + + features = transformer.encodeFeatures(features, encoder); + } + + return features; + } + + public List getTransformers(){ + List steps = getSteps(); + boolean flexible = isFlexible(); + + if(flexible && steps.size() > 0){ + Estimator estimator = getEstimator(); + + if(estimator != null){ + steps = steps.subList(0, steps.size() - 1); + } + } + + return TransformerUtil.asTransformerList(TupleUtil.extractElementList(steps, 1)); + } + + public Estimator getEstimator(){ + List steps = getSteps(); + boolean flexible = isFlexible(); + + if(flexible && steps.size() > 0){ + Object lastStep = TupleUtil.extractElement(steps.get(steps.size() - 1), 1); + + try { + return EstimatorUtil.asEstimator(lastStep); + } catch(IllegalArgumentException iae){ + // Ignored + } + } + + return null; + } + + public List getSteps(){ + return (List)get("steps"); + } + + private boolean isFlexible(){ + return this.flexible; + } + + private void setFlexible(boolean flexible){ + this.flexible = flexible; + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `steps` last assigned on line 100 could be null and is dereferenced at line 103. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List Pipeline.getTransformers() + +### Procedure Id: +sklearn.pipeline.Pipeline.getTransformers():java.util.List.98d0f51c77c0e7d38d958ad99a429640 + +### File: +src/main/java/sklearn/pipeline/Pipeline.java + +### Key: +Pipeline.java|getTransformers|NULL_DEREFERENCE + +### Node Key: +0d5a2f2639f34d56cc8af6d106187976 + +### Hash: +18df2b64d83e65d096136bc7c1a335e6 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9489/instruction.md b/inferredbugs-9489/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5d05de0e120e4e62c842b4b05708e9865a8b7d4c --- /dev/null +++ b/inferredbugs-9489/instruction.md @@ -0,0 +1,218 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jpmml-sklearn +**Bug ID:** 33 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2015 Villu Ruusmann + * + * This file is part of JPMML-SkLearn + * + * JPMML-SkLearn is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * JPMML-SkLearn 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with JPMML-SkLearn. If not, see . + */ +package sklearn_pandas; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import com.google.common.base.Function; +import com.google.common.collect.Lists; +import net.razorvine.pickle.objects.ClassDict; +import org.dmg.pmml.DataField; +import org.dmg.pmml.FieldName; +import org.jpmml.converter.Feature; +import org.jpmml.converter.WildcardFeature; +import org.jpmml.sklearn.ClassDictUtil; +import org.jpmml.sklearn.SkLearnEncoder; +import org.jpmml.sklearn.TupleUtil; +import sklearn.Transformer; + +public class DataFrameMapper extends ClassDict { + + public DataFrameMapper(String module, String name){ + super(module, name); + } + + public void encodeFeatures(SkLearnEncoder encoder){ + List steps = getFeatures(); + + for(int row = 0; row < steps.size(); row++){ + Object[] step = steps.get(row); + + List ids = new ArrayList<>(); + List features = new ArrayList<>(); + + List names = getNameList(step); + for(String name : names){ + ids.add(name); + + DataField dataField = encoder.createDataField(FieldName.create(name)); + + Feature feature = new WildcardFeature(encoder, dataField); + + features.add(feature); + } + + List transformers = getTransformerList(step); + for(int column = 0; column < transformers.size(); column++){ + Transformer transformer = transformers.get(column); + + for(Feature feature : features){ + encoder.updateType(feature.getName(), transformer.getOpType(), transformer.getDataType()); + } + + features = transformer.encodeFeatures(ids, features, encoder); + } + + encoder.addRow(ids, features); + } + } + + public List getFeatures(){ + return (List)get("features"); + } + + static + private List getNameList(Object[] feature){ + Function function = new Function(){ + + @Override + public String apply(Object object){ + + if(object instanceof String){ + return (String)object; + } + + throw new IllegalArgumentException("The key object (" + ClassDictUtil.formatClass(object) + ") is not a String"); + } + }; + + try { + if(feature[0] instanceof List){ + return new ArrayList<>(Lists.transform(((List)feature[0]), function)); + } + + return Collections.singletonList(function.apply(feature[0])); + } catch(RuntimeException re){ + throw new IllegalArgumentException("Invalid mapping key", re); + } + } + + static + private List getTransformerList(Object[] feature){ + Function function = new Function(){ + + @Override + public Transformer apply(Object object){ + + if(object instanceof Transformer){ + return (Transformer)object; + } + + throw new IllegalArgumentException("The value object (" + ClassDictUtil.formatClass(object) + ") is not a Transformer or is not a supported Transformer subclass"); + } + }; + + try { + if(feature[1] == null){ + return Collections.emptyList(); + } // End if + + if(feature[1] instanceof TransformerPipeline){ + TransformerPipeline transformerPipeline = (TransformerPipeline)feature[1]; + + List steps = transformerPipeline.getSteps(); + + return new ArrayList<>(Lists.transform((List)TupleUtil.extractElementList(steps, 1), function)); + } // End if + + if(feature[1] instanceof List){ + return new ArrayList<>(Lists.transform((List)feature[1], function)); + } + + return Collections.singletonList(function.apply(feature[1])); + } catch(RuntimeException re){ + throw new IllegalArgumentException("Invalid mapping value", re); + } + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `steps` last assigned on line 44 could be null and is dereferenced at line 46. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DataFrameMapper.encodeFeatures(SkLearnEncoder) + +### Procedure Id: +sklearn_pandas.DataFrameMapper.encodeFeatures(org.jpmml.sklearn.SkLearnEncoder):void.f0cdc0b7e20fd6a37b2109cfb89bf044 + +### File: +src/main/java/sklearn_pandas/DataFrameMapper.java + +### Key: +DataFrameMapper.java|encodeFeatures|NULL_DEREFERENCE + +### Node Key: +19825d0378afc178d9a3b0dbf0e73dbf + +### Hash: +d55deac81f47684cbacb94e50efa12b0 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9501/instruction.md b/inferredbugs-9501/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8d6a6cca26464598c42fc780dfd8dc9b6c6f891a --- /dev/null +++ b/inferredbugs-9501/instruction.md @@ -0,0 +1,185 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jpmml-sklearn +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2015 Villu Ruusmann + * + * This file is part of JPMML-SkLearn + * + * JPMML-SkLearn is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * JPMML-SkLearn 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with JPMML-SkLearn. If not, see . + */ +package org.jpmml.sklearn; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +import joblib.NDArrayWrapper; +import net.razorvine.pickle.objects.ClassDict; +import numpy.core.NDArray; +import numpy.core.Scalar; + +public class ClassDictUtil { + + private ClassDictUtil(){ + } + + static + public List getArray(ClassDict dict, String name){ + Object object = dict.get(name); + + if(object instanceof NDArrayWrapper){ + NDArrayWrapper array = (NDArrayWrapper)object; + + Object content = array.getContent(); + + return toArray(content); + } else + + if(object instanceof Scalar){ + Scalar scalar = (Scalar)object; + + Object data = scalar.getData(); + + return Collections.singletonList(data); + } + + throw new IllegalArgumentException(); + } + + static + public List getArray(ClassDict dict, String name, String key){ + NDArrayWrapper nodes = (NDArrayWrapper)dict.get(name); + + Map content = (Map)nodes.getContent(); + + return toArray(content.get(key)); + } + + static + private List toArray(Object object){ + + if(object instanceof NDArray){ + NDArray ndarray = (NDArray)object; + + return ndarray.getData(); + } + + return (List)object; + } + + static + public String toString(ClassDict dict){ + StringBuffer sb = new StringBuffer(); + + sb.append("\n{\n"); + + String sep = ""; + + List> entries = new ArrayList<>(dict.entrySet()); + + Comparator> comparator = new Comparator>(){ + + @Override + public int compare(Map.Entry left, Map.Entry right){ + return (left.getKey()).compareToIgnoreCase(right.getKey()); + } + }; + Collections.sort(entries, comparator); + + for(Map.Entry entry : entries){ + sb.append(sep); + + sep = "\n"; + + sb.append("\t" + entry.getKey() + "=" + entry.getValue() + ("/*" + (entry.getValue() != null ? entry.getValue().getClass() : "N/A") + "*/")); + } + + sb.append("\n}\n"); + + return sb.toString(); + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `nodes` last assigned on line 62 could be null and is dereferenced at line 64. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List ClassDictUtil.getArray(ClassDict,String,String) + +### Procedure Id: +org.jpmml.sklearn.ClassDictUtil.getArray(net.razorvine.pickle.objects.ClassDict,java.lang.String,jav.4136e1e595eb65435c20c305319945ac + +### File: +src/main/java/org/jpmml/sklearn/ClassDictUtil.java + +### Key: +ClassDictUtil.java|getArray|NULL_DEREFERENCE + +### Node Key: +88a9d456c6c70359cc9430e108e79cdb + +### Hash: +1be21550c6728b18093161590cf91d2d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9506/instruction.md b/inferredbugs-9506/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d6b0d2f765e9a3694edab1aead98f34283adb1a9 --- /dev/null +++ b/inferredbugs-9506/instruction.md @@ -0,0 +1,148 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jpmml-sklearn +**Bug ID:** 21 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2016 Villu Ruusmann + * + * This file is part of JPMML-SkLearn + * + * JPMML-SkLearn is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * JPMML-SkLearn 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with JPMML-SkLearn. If not, see . + */ +package sklearn.neural_network; + +import java.util.List; + +import numpy.core.NDArray; +import numpy.core.NDArrayUtil; +import org.dmg.pmml.MiningFunctionType; +import org.dmg.pmml.NeuralNetwork; +import org.dmg.pmml.Output; +import org.jpmml.sklearn.Schema; +import sklearn.Classifier; +import sklearn.EstimatorUtil; + +public class MLPClassifier extends Classifier { + + public MLPClassifier(String module, String name){ + super(module, name); + } + + @Override + public int getNumberOfFeatures(){ + List coefs = getCoefs(); + + NDArray input = (NDArray)coefs.get(0); + + int[] shape = NDArrayUtil.getShape(input); + + return shape[0]; + } + + @Override + public NeuralNetwork encodeModel(Schema schema){ + String activation = getActivation(); + + List coefs = getCoefs(); + List intercepts = getIntercepts(); + + Output output = EstimatorUtil.encodeClassifierOutput(schema); + + NeuralNetwork neuralNetwork = NeuralNetworkUtil.encodeNeuralNetwork(MiningFunctionType.CLASSIFICATION, activation, coefs, intercepts, schema) + .setOutput(output); + + return neuralNetwork; + } + + public String getActivation(){ + return (String)get("activation"); + } + + public List getCoefs(){ + return (List)get("coefs_"); + } + + public List getIntercepts(){ + return (List)get("intercepts_"); + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `coefs` last assigned on line 40 could be null and is dereferenced at line 42. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int MLPClassifier.getNumberOfFeatures() + +### Procedure Id: +sklearn.neural_network.MLPClassifier.getNumberOfFeatures():int.1a119451c14dfbb7f00cfbfb6d1f9b94 + +### File: +src/main/java/sklearn/neural_network/MLPClassifier.java + +### Key: +MLPClassifier.java|getNumberOfFeatures|NULL_DEREFERENCE + +### Node Key: +98e48d8af36063b905de6168fc1ae17c + +### Hash: +cb10330b0a143b5c519ffa69590b8015 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9537/instruction.md b/inferredbugs-9537/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c1cb0c2f73a8e8f9a6ab8da94ed43a892bf04863 --- /dev/null +++ b/inferredbugs-9537/instruction.md @@ -0,0 +1,2023 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** hazelcast +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2007-2008, Hazel Ltd. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.hazelcast.impl; + +import com.hazelcast.core.EntryEvent; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.impl.BlockingQueueManager.Q.ScheduledOfferAction; +import com.hazelcast.impl.BlockingQueueManager.Q.ScheduledPollAction; +import com.hazelcast.impl.ClusterManager.AbstractRemotelyProcessable; +import com.hazelcast.impl.Config.QConfig; +import static com.hazelcast.impl.Constants.BlockingQueueOperations.*; +import static com.hazelcast.impl.Constants.Objects.OBJECT_NULL; +import com.hazelcast.nio.Address; +import static com.hazelcast.nio.BufferUtil.*; +import com.hazelcast.nio.Data; +import com.hazelcast.nio.DataSerializable; +import com.hazelcast.nio.PacketQueue; +import com.hazelcast.nio.PacketQueue.Packet; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.*; + +class BlockingQueueManager extends BaseManager { + private final Request remoteReq = new Request(); + private final static BlockingQueueManager instance = new BlockingQueueManager(); + private final Map mapQueues = new HashMap(10); + private final Map> mapTxnPolledElements = new HashMap>(10); + private static final int BLOCK_SIZE = 1000; + private int nextIndex = 0; + + private BlockingQueueManager() { + ClusterService.get().registerPacketProcessor(OP_B_POLL, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + try { + handlePoll(packet); + } catch (Throwable t) { + Request req = new Request(); + req.setFromPacket(packet); + printState(req, false, packet.conn.getEndPoint(), 1); + t.printStackTrace(); + } + } + }); + ClusterService.get().registerPacketProcessor(OP_B_OFFER, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleOffer(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_BACKUP_ADD, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleBackup(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_BACKUP_REMOVE, new PacketProcessor() { + public void process(Packet packet) { + handleBackup(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_PUBLISH, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handlePublish(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_ADD_TOPIC_LISTENER, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleAddTopicListener(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_SIZE, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleSize(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_PEEK, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handlePoll(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_READ, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleRead(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_REMOVE, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleRemove(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_TXN_BACKUP_POLL, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleTxnBackupPoll(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_TXN_COMMIT, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleTxnCommit(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_ADD_BLOCK, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleAddBlock(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_REMOVE_BLOCK, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleRemoveBlock(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_FULL_BLOCK, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleFullBlock(packet); + } + }); + + } + + public static BlockingQueueManager get() { + return instance; + } + + class BlockBackupSyncRunner implements Runnable { + final BlockBackupSync blockSync; + + public BlockBackupSyncRunner(BlockBackupSync blockSync) { + this.blockSync = blockSync; + } + + public void run() { + while (!blockSync.done) { + try { + synchronized (blockSync) { + enqueueAndReturn(blockSync); + blockSync.wait(); + } + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + class BlockBackupSync implements Processable { + final Block block; + final Q q; + int index = 0; + final int indexUpto; + volatile boolean done = false; + + public BlockBackupSync(Q q, Block block, int indexUpto) { + super(); + this.q = q; + this.block = block; + this.indexUpto = indexUpto; + } + + public void process() { + Data data = next(); + if (data != null && data.size() != 0) { + q.sendBackup(true, thisAddress, data, block.blockId, index); + index++; + if (index > indexUpto) { + done = true; + } + } else { + done = true; + } + synchronized (BlockBackupSync.this) { + BlockBackupSync.this.notify(); + } + } + + private Data next() { + while (true) { + Data data = block.get(index); + if (data != null) { + return data; + } + index++; + if (index > indexUpto) + return null; + if (index >= BLOCK_SIZE) + return null; + } + } + } + + void syncForDead(Address addressDead) { + MemberImpl member = getNextMemberBeforeSync(addressDead, true, 1); + if (DEBUG) { + log(addressDead + " is dead and its backup was " + member); + } + Address addressNewOwner = (member == null) ? thisAddress : member.getAddress(); + + Collection queues = mapQueues.values(); + for (Q q : queues) { + List lsBlocks = q.lsBlocks; + for (Block block : lsBlocks) { + if (block.address.equals(addressDead)) { + // set the new owner + block.address = addressNewOwner; + block.resetAddIndex(); + if (lsMembers.size() > 1) { + if (addressNewOwner.equals(thisAddress)) { + // I am the new owner so backup to next member + int indexUpto = block.size() - 1; + if (DEBUG) { + log("IndexUpto " + indexUpto); + } + if (indexUpto > -1) { + executeLocally(new BlockBackupSyncRunner(new BlockBackupSync(q, block, + indexUpto))); + } + } + } + } else if (block.address.equals(thisAddress)) { + // If I am/was the owner of this block + // did my backup change.. + // if so backup to the new next + if (lsMembers.size() > 1) { + MemberImpl memberBackupWas = getNextMemberBeforeSync(thisAddress, true, 1); + if (memberBackupWas == null + || memberBackupWas.getAddress().equals(addressDead)) { + int indexUpto = block.size() - 1; + if (indexUpto > -1) { + executeLocally(new BlockBackupSyncRunner(new BlockBackupSync(q, block, + indexUpto))); + } + } + } + } + } + // packetalidate the dead member's scheduled actions + List scheduledPollActions = q.lsScheduledPollActions; + for (ScheduledPollAction scheduledAction : scheduledPollActions) { + if (addressDead.equals(scheduledAction.request.caller)) { + scheduledAction.setValid(false); + ClusterManager.get().deregisterScheduledAction(scheduledAction); + } + } + List scheduledOfferActions = q.lsScheduledOfferActions; + for (ScheduledOfferAction scheduledAction : scheduledOfferActions) { + if (addressDead.equals(scheduledAction.request.caller)) { + scheduledAction.setValid(false); + ClusterManager.get().deregisterScheduledAction(scheduledAction); + } + } + } + doResetBlockSizes(); + } + + public void syncForAdd() { + if (isMaster()) { + Collection queues = mapQueues.values(); + for (Q q : queues) { + List lsBlocks = q.lsBlocks; + for (Block block : lsBlocks) { + int fullBlockId = -1; + if (block.isFull()) { + fullBlockId = block.blockId; + } + sendAddBlockMessageToOthers(block, fullBlockId, null, true); + } + } + } + Collection queues = mapQueues.values(); + for (Q q : queues) { + List lsBlocks = q.lsBlocks; + for (Block block : lsBlocks) { + if (block.address.equals(thisAddress)) { + // If I am/was the owner of this block + // did my backup change.. + // if so backup to the new next + if (lsMembers.size() > 1) { + MemberImpl memberBackupWas = getNextMemberBeforeSync(thisAddress, true, 1); + MemberImpl memberBackupIs = getNextMemberAfter(thisAddress, true, 1); + if (memberBackupWas == null || !memberBackupWas.equals(memberBackupIs)) { + if (DEBUG) { + log("Backup changed!!! so backing up to " + memberBackupIs); + } + int indexUpto = block.size() - 1; + if (indexUpto > -1) { + executeLocally(new BlockBackupSyncRunner(new BlockBackupSync(q, block, + indexUpto))); + } + } + } + } + } + } + doResetBlockSizes(); + } + + void doResetBlockSizes() { + Collection queues = mapQueues.values(); + for (Q q : queues) { + // q.printStack(); + List lsBlocks = q.lsBlocks; + int size = 0; + for (Block block : lsBlocks) { + if (block.address.equals(thisAddress)) { + size += block.size(); + } + } + q.size = size; + } + } + + final void handleSize(PacketQueue.Packet packet) { + Q q = getQ(packet.name); + packet.longValue = q.size; + sendResponse(packet); + } + + @Override + final void handleListenerRegisterations(boolean add, String name, Data key, Address address, + boolean includeValue) { + Q q = getQ(name); + if (add) { + q.addListener(address, includeValue); + } else { + q.removeListener(address); + } + } + + final void handleTxnBackupPoll(PacketQueue.Packet packet) { + doTxnBackupPoll(packet.txnId, doTake(packet.value)); + } + + final void handleTxnCommit(PacketQueue.Packet packet) { + mapTxnPolledElements.remove(packet.txnId); + } + + final void doTxnBackupPoll(long txnId, Data value) { + List lsTxnPolledElements = mapTxnPolledElements.get(txnId); + if (lsTxnPolledElements == null) { + lsTxnPolledElements = new ArrayList(1); + mapTxnPolledElements.put(txnId, lsTxnPolledElements); + } + lsTxnPolledElements.add(value); + } + + final void handleBackup(PacketQueue.Packet packet) { + try { + String name = packet.name; + int blockId = packet.blockId; + Q q = getQ(name); + if (packet.operation == OP_B_BACKUP_ADD) { + Data data = doTake(packet.value); + q.doBackup(true, data, blockId, (int) packet.longValue); + } else if (packet.operation == OP_B_BACKUP_REMOVE) { + q.doBackup(false, null, blockId, 0); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + packet.returnToContainer(); + } + } + + final void handleRemoveBlock(PacketQueue.Packet packet) { + try { + BlockUpdate addRemove = (BlockUpdate) ThreadContext.get().toObject(packet.value); + String name = packet.name; + Q q = getQ(name); + doRemoveBlock(q, packet.conn.getEndPoint(), addRemove.removeBlockId); + } catch (Exception e) { + e.printStackTrace(); + } finally { + packet.returnToContainer(); + } + } + + public void doRemoveBlock(Q q, Address originalRemover, int blockId) { + Block blockRemoved = q.removeBlock(blockId); + if (isMaster()) { + sendAddBlockMessageToOthers(q.name, null, blockId, -1, originalRemover, false); + } + + } + + final void handleFullBlock(PacketQueue.Packet packet) { + if (isMaster()) { + String name = packet.name; + Q q = getQ(name); + doFullBlock(q, packet.blockId, packet.conn.getEndPoint()); + } + packet.returnToContainer(); + } + + final void doFullBlock(Q q, int fullBlockId, Address originalFuller) { + int blockId = q.getLatestAddedBlock() + 1; + Address target = nextTarget(); + Block newBlock = setFullAndCreateNewBlock(q, fullBlockId, target, blockId); + if (newBlock != null) { + sendAddBlockMessageToOthers(newBlock, fullBlockId, originalFuller, true); + } + } + + final void handleAddBlock(PacketQueue.Packet packet) { + try { + BlockUpdate addRemove = (BlockUpdate) ThreadContext.get().toObject(packet.value); + String name = packet.name; + int blockId = addRemove.addBlockId; + Address addressOwner = addRemove.addAddress; + Q q = getQ(name); + setFullAndCreateNewBlock(q, addRemove.fullBlockId, addressOwner, blockId); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + packet.returnToContainer(); + } + } + + Block setFullAndCreateNewBlock(Q q, int fullBlockId, Address newBlockOwner, int newBlockId) { + List lsBlocks = q.lsBlocks; + boolean exist = false; + for (Block block : lsBlocks) { + if (block.blockId == newBlockId) { + exist = true; + } + } + Block newBlock = null; + if (!exist) { + newBlock = q.createBlock(newBlockOwner, newBlockId); + q.addBlock(newBlock); + } + if (fullBlockId != -1) { + q.setBlockFull(fullBlockId); + } + return newBlock; + } + + final void handleOffer(PacketQueue.Packet packet) { + if (rightRemoteOfferTarget(packet)) { + remoteReq.setFromPacket(packet); + doOffer(remoteReq); + packet.longValue = remoteReq.longValue; + if (!remoteReq.scheduled) { + if (remoteReq.response == Boolean.TRUE) { + sendResponse(packet); + } else { + sendResponseFailure(packet); + } + } else { + packet.returnToContainer(); + } + remoteReq.reset(); + } + } + + final void handlePublish(Packet packet) { + if (rightRemoteOfferTarget(packet)) { + remoteReq.setFromPacket(packet); + doPublish(remoteReq); + packet.longValue = remoteReq.longValue; + if (!remoteReq.scheduled) { + if (remoteReq.response == Boolean.TRUE) { + sendResponse(packet); + } else { + sendResponseFailure(packet); + } + } else { + packet.returnToContainer(); + } + remoteReq.reset(); + } + } + + final void handleAddTopicListener(PacketQueue.Packet packet) { + if (rightRemoteOfferTarget(packet)) { + remoteReq.setFromPacket(packet); + doAddTopicListener(remoteReq); + packet.longValue = remoteReq.longValue; + sendResponse(packet); + remoteReq.reset(); + } + } + + final boolean rightRemoteOfferTarget(PacketQueue.Packet packet) { + Q q = getQ(packet.name); + if (q.blCurrentPut == null) { + q.setCurrentPut(); + } + boolean invalid = false; + if (packet.blockId != q.blCurrentPut.blockId) { + if (packet.blockId > q.blCurrentPut.blockId) { + int size = q.lsBlocks.size(); + for (int i = 0; i < size; i++) { + Block block = q.lsBlocks.get(i); + if (block.blockId == packet.blockId) { + if (thisAddress.equals(block.address)) { + q.blCurrentPut = block; + } + } + } + } else { + invalid = true; + } + } + if (q.blCurrentPut.isFull() || !thisAddress.equals(q.blCurrentPut.address)) { + invalid = true; + } + if (invalid) { + sendRedoResponse(packet); + } + return (!invalid); + } + + boolean rightRemotePollTarget(Packet packet) { + Q q = getQ(packet.name); + if (q.blCurrentTake == null) { + q.setCurrentTake(); + } + boolean invalid = false; + if (packet.blockId != q.blCurrentTake.blockId) { + if (packet.blockId > q.blCurrentTake.blockId) { + int size = q.lsBlocks.size(); + for (int i = 0; i < size; i++) { + Block block = q.lsBlocks.get(i); + if (block.blockId == packet.blockId) { + if (thisAddress.equals(block.address)) { + q.blCurrentTake = block; + } + } + } + } else { + invalid = true; + } + } + if ((q.blCurrentTake.size() == 0 && q.blCurrentTake.isFull()) + || !thisAddress.equals(q.blCurrentTake.address)) { + invalid = true; + } + if (invalid) { + sendRedoResponse(packet); + } + return (!invalid); + } + + final void handlePoll(PacketQueue.Packet packet) { + if (rightRemotePollTarget(packet)) { + remoteReq.setFromPacket(packet); + doPoll(remoteReq); + if (!remoteReq.scheduled) { + Data oldValue = (Data) remoteReq.response; + if (oldValue != null && oldValue.size() > 0) { + doSet(oldValue, packet.value); + } + sendResponse(packet); + } else { + packet.returnToContainer(); + } + remoteReq.reset(); + } + } + + final void handleRead(PacketQueue.Packet packet) { + Q q = getQ(packet.name); + q.read(packet); + } + + final void handleRemove(PacketQueue.Packet packet) { + Q q = getQ(packet.name); + q.remove(packet); + } + + final Address nextTarget() { + int size = lsMembers.size(); + int index = nextIndex++ % size; + if (nextIndex >= size) { + nextIndex = 0; + } + return lsMembers.get(index).getAddress(); + } + + public Q getQ(String name) { + if (name == null) + return null; + Q q = mapQueues.get(name); + if (q == null) { + q = new Q(name); + mapQueues.put(name, q); + } + return q; + } + + public class CommitPoll extends AbstractCall { + volatile long txnId = -1; + String name = null; + + public int getOperation() { + return OP_B_TXN_COMMIT; + } + + public void commitPoll(String name) { + this.name = name; + this.txnId = ThreadContext.get().getTxnId(); + enqueueAndReturn(this); + } + + public void handleResponse(PacketQueue.Packet packet) { + } + + public void process() { + MemberImpl nextMember = getNextMemberAfter(thisAddress, true, 1); + if (nextMember != null) { + Address next = nextMember.getAddress(); + PacketQueue.Packet packet = obtainPacket(); + packet.name = name; + packet.operation = getOperation(); + packet.txnId = txnId; + boolean sent = send(packet, next); + if (!sent) { + packet.returnToContainer(); + } + } + } + } + + class QDestroy { + public void destroy(String name) { + sendProcessableToAll(new Destroy(name), true); + } + } + + public void destroy(String name) { + mapQueues.remove(name); + } + + public class Size extends AbstractCall { + String name = null; + int total = 0; + int numberOfResponses = 0; + int numberOfExpectedResponses = 1; + + public int getSize(String name) { + this.name = name; + synchronized (this) { + try { + enqueueAndReturn(this); + wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + return total; + } + + @Override + public void onDisconnect(Address dead) { + redo(); + } + + public void reset() { + total = 0; + numberOfResponses = 0; + numberOfExpectedResponses = 0; + } + + public void handleResponse(PacketQueue.Packet packet) { + total += (int) packet.longValue; + packet.returnToContainer(); + numberOfResponses++; + if (numberOfResponses >= numberOfExpectedResponses) { + removeCall(getId()); + synchronized (this) { + notify(); + } + } + } + + public void process() { + reset(); + Q q = getQ(name); + if (DEBUG) { + q.printStack(); + } + total += q.size; + numberOfResponses = 1; + if (lsMembers.size() > 1) { + addCall(this); + numberOfExpectedResponses = lsMembers.size(); + for (MemberImpl member : lsMembers) { + if (!member.localMember()) { + PacketQueue.Packet packet = obtainPacket(); + packet.name = name; + packet.operation = getOperation(); + packet.callId = getId(); + packet.timeout = 0; + boolean sent = send(packet, member.getAddress()); + if (!sent) { + packet.returnToContainer(); + redo(); + } + } + } + } else { + synchronized (this) { + this.notify(); + } + } + } + + public int getOperation() { + return OP_B_SIZE; + } + } + + class QIterator implements Iterator, Processable { + + volatile String name; + volatile List blocks = null; + int currentBlockId = -1; + int currentIndex = -1; + Object next = null; + boolean hasNextCalled = false; + + public void set(String name) { + synchronized (QIterator.this) { + this.name = name; + enqueueAndReturn(QIterator.this); + try { + QIterator.this.wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + public void process() { + Q q = getQ(name); + List lsBlocks = q.lsBlocks; + blocks = new ArrayList(lsBlocks.size()); + for (Block block : lsBlocks) { + blocks.add(block.blockId); + } + synchronized (QIterator.this) { + QIterator.this.notify(); + } + } + + public boolean hasNext() { + next = null; + while (next == null) { + boolean canRead = setNextBlock(); + // System.out.println(currentBlockId + " Can read " + canRead); + if (!canRead) + return false; + Read read = new Read(); + next = read.read(name, currentBlockId, currentIndex); + // System.out.println(currentIndex + " Next " + next); + if (next == null) { + currentIndex = -1; + } else { + currentIndex = read.readIndex; + currentIndex++; + } + } + hasNextCalled = true; + return true; + } + + boolean setNextBlock() { + if (currentIndex == -1 || currentIndex >= BLOCK_SIZE) { + if (blocks.size() == 0) { + return false; + } else { + currentBlockId = blocks.remove(0); + currentIndex = 0; + return true; + } + } + return true; + } + + public E next() { + if (!hasNextCalled) { + boolean hasNext = hasNext(); + if (!hasNext) { + return null; + } + } + if (next != null) { + hasNextCalled = false; + } + return (E) next; + } + + public void remove() { + } + + } + + public class Remove extends QueueBasedCall { + String name; + int blockId; + int index; + + public Object remove(String name, int blockId, int index) { + this.name = name; + this.blockId = blockId; + this.index = index; + enqueueAndReturn(this); + Object result; + try { + result = responses.take(); + if (result == OBJECT_NULL) + return null; + else { + return ThreadContext.get().toObject((Data) result); + } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + void setResponse() { + responses.add(OBJECT_NULL); + } + + public void handleResponse(PacketQueue.Packet packet) { + setResponse(); + packet.returnToContainer(); + } + + @Override + public void onDisconnect(Address dead) { + process(); + } + + public void process() { + addCall(this); + Q q = getQ(name); + + Address target = q.getBlockOwner(blockId); + if (target == null) { + responses.add(OBJECT_NULL); + } else if (target.equals(thisAddress)) { + q.remove(this); + } else { + Packet packet = obtainPacket(); + packet.name = name; + packet.operation = getOperation(); + packet.callId = getId(); + packet.blockId = blockId; + packet.timeout = 0; + packet.longValue = index; + boolean sent = false; + if (target != null) { + sent = send(packet, target); + } + if (target == null || !sent) { + packet.returnToContainer(); + responses.add(OBJECT_NULL); + } + } + } + + public int getOperation() { + return OP_B_REMOVE; + } + + } + + public class Read extends QueueBasedCall { + String name; + int blockId; + int index; + int readIndex = 0; + + public Object read(String name, int blockId, int index) { + this.name = name; + this.blockId = blockId; + this.index = index; + enqueueAndReturn(this); + Object result; + try { + result = responses.take(); + if (result == OBJECT_NULL) + return null; + else { + return ThreadContext.get().toObject((Data) result); + } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + void setResponse(Data value, int index) { + responses.clear(); + readIndex = index; + responses.add((value == null) ? OBJECT_NULL : value); + } + + public void handleResponse(PacketQueue.Packet packet) { + Data value = doTake(packet.value); + int indexRead = (int) packet.longValue; + setResponse(value, indexRead); + removeCall(getId()); + packet.returnToContainer(); + } + + @Override + public void onDisconnect(Address dead) { + removeCall(getId()); + enqueueAndReturn(Read.this); + } + + public void process() { + responses.clear(); + Q q = getQ(name); + Address target = q.getBlockOwner(blockId); + if (target == null) { + responses.add(OBJECT_NULL); + } else if (target.equals(thisAddress)) { + q.read(this); + } else { + addCall(this); + PacketQueue.Packet packet = obtainPacket(); + packet.name = name; + packet.operation = getOperation(); + packet.callId = getId(); + packet.blockId = blockId; + packet.timeout = 0; + packet.longValue = index; + boolean sent = send(packet, target); + if (!sent) { + packet.returnToContainer(); + onDisconnect(target); + } + } + } + + public int getOperation() { + return OP_B_READ; + } + + } + + class AddTopicListener extends LongOp { + public Long add(String name, Object value, long timeout, long txnId) { + return (Long) objectCall(OP_B_ADD_TOPIC_LISTENER, name, null, value, timeout, txnId, -1); + } + + @Override + void setTarget() { + target = getTargetForOffer(request); + } + + @Override + void doLocalOp() { + doAddTopicListener(request); + setResult(Long.valueOf(request.recordId)); + } + } + + class Offer extends BooleanOp { + + int doCount = 1; + + public boolean publish(String name, Object value, long timeout, long txnId) { + return booleanCall(OP_B_PUBLISH, name, null, value, timeout, txnId, -1); + } + + public boolean offer(String name, Object value, long timeout, long txnId) { + return booleanCall(OP_B_OFFER, name, null, value, timeout, txnId, -1); + } + + @Override + void handleNoneRedoResponse(PacketQueue.Packet packet) { + if (request.operation == OP_B_OFFER + && packet.responseType == ResponseTypes.RESPONSE_SUCCESS) { + if (!zeroBackup) { + if (getPreviousMemberBefore(thisAddress, true, 1).getAddress().equals( + packet.conn.getEndPoint())) { + int itemIndex = (int) packet.longValue; + if (itemIndex != -1) { + Q q = getQ(request.name); + if (request.value == null || request.value.size() == 0) { + throw new RuntimeException("Invalid data " + request.value); + } + q.doBackup(true, request.value, request.blockId, (int) packet.longValue); + } + } + } + } + super.handleNoneRedoResponse(packet); + } + + @Override + public void process() { + if (doCount++ % 4 == 0) { + printState(request, true, target, doCount); + + } + super.process(); + } + + @Override + void setTarget() { + target = getTargetForOffer(request); + } + + @Override + void doLocalOp() { + if (request.operation == OP_B_OFFER) { + doOffer(request); + if (!request.scheduled) { + setResult(request.response); + } + } else { + doPublish(request); + setResult(request.response); + } + } + } + + public Address getTargetForOffer(Request request) { + Address target = null; + Q q = getQ(request.name); + Block block = q.getCurrentPutBlock(); + if (block == null) { + target = getMasterAddress(); + request.blockId = 0; + } else { + target = block.address; + request.blockId = block.blockId; + } + return target; + } + + class Poll extends TargetAwareOp { + + public Object peek(String name) { + return objectCall(OP_B_PEEK, name, null, null, 0, -1, -1); + } + + public Object poll(String name, long timeout) { + return objectCall(OP_B_POLL, name, null, null, timeout, -1, -1); + } + + @Override + void setTarget() { + Q q = getQ(request.name); + Block takeBlock = q.getCurrentTakeBlock(); + if (takeBlock == null) { + target = getMasterAddress(); + request.blockId = 0; + } else { + target = takeBlock.address; + request.blockId = takeBlock.blockId; + } + } + + @Override + void doLocalOp() { + doPoll(request); + if (!request.scheduled) { + setResult(request.response); + } + } + + @Override + void handleNoneRedoResponse(PacketQueue.Packet packet) { + if (request.operation == OP_B_POLL + && packet.responseType == ResponseTypes.RESPONSE_SUCCESS) { + if (!zeroBackup) { + if (getPreviousMemberBefore(thisAddress, true, 1).getAddress().equals( + packet.conn.getEndPoint())) { + if (packet.value != null) { + Q q = getQ(packet.name); + q.doBackup(false, null, request.blockId, 0); + } + } + } + } + super.handleNoneRedoResponse(packet); + } + } + + void doAddTopicListener(Request req) { + for (MemberImpl member : lsMembers) { + if (member.localMember()) { + handleListenerRegisterations(true, req.name, req.key, req.caller, true); + } else if (!member.getAddress().equals(req.caller)) { + sendProcessableTo(new TopicListenerRegistration(req.name, true, req.caller), member + .getAddress()); + } + } + Q q = getQ(req.name); + if (q.blCurrentPut == null) { + q.setCurrentPut(); + } + req.recordId = q.getRecordId(q.blCurrentPut.blockId, q.blCurrentPut.addIndex); + } + + public static class TopicListenerRegistration extends AbstractRemotelyProcessable { + String name = null; + boolean add = true; + Address listenerAddress = null; + + public TopicListenerRegistration() { + } + + public TopicListenerRegistration(String name, boolean add, Address listenerAddress) { + super(); + this.name = name; + this.add = add; + this.listenerAddress = listenerAddress; + } + + @Override + public void readData(DataInput in) throws IOException { + add = in.readBoolean(); + listenerAddress = new Address(); + listenerAddress.readData(in); + name = in.readUTF(); + } + + @Override + public void writeData(DataOutput out) throws IOException { + out.writeBoolean(add); + listenerAddress.writeData(out); + out.writeUTF(name); + } + + public void process() { + ListenerManager.get().handleListenerRegisterations(true, name, null, listenerAddress, + true); + } + + } + + void printState(Request request, boolean local, Address address, int doCount) { + Q q = getQ(request.name); + q.printStack(); + System.out.println(local + " ===== CurrentRequest === " + doCount); + System.out.println("blockId: " + request.blockId); + System.out.println("operation: " + request.operation); + System.out.println("version: " + request.version); + System.out.println("timeout: " + request.timeout); + System.out.println("target: " + address); + System.out.println("=========== DONE ======="); + } + + void doPublish(Request req) { + Q q = getQ(req.name); + if (q.blCurrentPut == null) { + q.setCurrentPut(); + } + int index = q.publish(req); + req.longValue = index; + req.response = Boolean.TRUE; + } + + void doOffer(Request req) { + Q q = getQ(req.name); + if (q.blCurrentPut == null) { + q.setCurrentPut(); + } + if (q.size >= q.maxSizePerJVM) { + if (req.hasEnoughTimeToSchedule()) { + req.scheduled = true; + final Request reqScheduled = (req.local) ? req : req.hardCopy(); + if (reqScheduled.local) { + if (reqScheduled.attachment == null) { + throw new RuntimeException("Scheduled local but attachement is null"); + } + } + q.scheduleOffer(reqScheduled); + } else { + req.response = Boolean.FALSE; + } + return; + } + q.offer(req); + req.value = null; + req.response = Boolean.TRUE; + } + + void doPoll(final Request req) { + Q q = getQ(req.name); + if (q.blCurrentTake == null) { + q.setCurrentTake(); + } + if (q.blCurrentTake.size() == 0) { + if (req.hasEnoughTimeToSchedule()) { + req.scheduled = true; + final Request reqScheduled = (req.local) ? req : req.hardCopy(); + if (reqScheduled.local) { + if (reqScheduled.attachment == null) { + throw new RuntimeException("Scheduled local but attachement is null"); + } + } + q.schedulePoll(reqScheduled); + } else { + req.response = null; + } + return; + } + Data value = null; + if (req.operation == OP_B_PEEK) { + value = q.peek(); + } else { + value = q.poll(req); + } + req.response = value; + } + + public void sendAddBlockMessageToOthers(Block block, int fullBlockId, Address except, + boolean add) { + sendAddBlockMessageToOthers(block.name, block.address, block.blockId, fullBlockId, except, add); + } + + public void sendAddBlockMessageToOthers(String name, Address addAddress, int blockId, int fullBlockId, Address except, + boolean add) { + int operation = OP_B_ADD_BLOCK; + if (!add) { + operation = OP_B_REMOVE_BLOCK; + } + if (lsMembers.size() > 1) { + int addBlockId = -1; + int removeBlockId = -1; + if (add) { + addBlockId = blockId; + except = null; + } else { + removeBlockId = blockId; + } + BlockUpdate addRemove = new BlockUpdate(addAddress, addBlockId, fullBlockId, + removeBlockId); + for (MemberImpl member : lsMembers) { + if (!member.localMember()) { + Address dest = member.getAddress(); + if (!dest.equals(except)) { + send(name, operation, addRemove, dest); + } + } + } + } + } + + public void sendFullMessage(Block block) { + try { + PacketQueue.Packet packet = PacketQueue.get().obtainPacket(); + packet.set(block.name, OP_B_FULL_BLOCK, null, null); + packet.blockId = block.blockId; + Address master = getMasterAddress(); + boolean sent = send(packet, master); + if (!sent) + packet.returnToContainer(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public class Q { + String name; + int size = 0; + List lsBlocks = new ArrayList(10); + Block blCurrentPut = null; + Block blCurrentTake = null; + int latestAddedBlock = -1; + + List lsScheduledPollActions = new ArrayList(100); + List lsScheduledOfferActions = new ArrayList( + 100); + int maxSizePerJVM = Integer.MAX_VALUE; + + Map mapListeners = new HashMap(1); + boolean keepValues = true; + + long maxAge = Long.MAX_VALUE; + + public Q(String name) { + if (name.startsWith("q:t:")) { + keepValues = false; + } else { + QConfig qconfig = Config.get().getQConfig(name.substring(2)); + if (qconfig != null) { + maxSizePerJVM = qconfig.maxSizePerJVM; + log("qConfig " + qconfig.maxSizePerJVM); + } + } + this.name = name; + Address master = getMasterAddress(); + if (master.isThisAddress()) { + Block block = createBlock(master, 0); + addBlock(block); + sendAddBlockMessageToOthers(block, -1, null, true); + for (int i = 0; i < 9; i++) { + int blockId = i + 1; + Address target = nextTarget(); + block = createBlock(target, blockId); + addBlock(block); + sendAddBlockMessageToOthers(block, -1, null, true); + } + } + } + + public Block createBlock(Address address, int blockId) { + return new Block(address, blockId, maxAge, name, keepValues); + } + + public Address getBlockOwner(int blockId) { + for (Block block : lsBlocks) { + if (block.blockId == blockId) + return block.address; + } + return null; + } + + public void addListener(Address address, boolean includeValue) { + mapListeners.put(address, includeValue); + } + + public void removeListener(Address address) { + mapListeners.remove(address); + } + + public void scheduleOffer(Request request) { + ScheduledOfferAction action = new ScheduledOfferAction(request); + lsScheduledOfferActions.add(action); + ClusterManager.get().registerScheduledAction(action); + + } + + public void schedulePoll(Request request) { + ScheduledPollAction action = new ScheduledPollAction(request); + lsScheduledPollActions.add(action); + ClusterManager.get().registerScheduledAction(action); + } + + public class ScheduledPollAction extends ScheduledAction { + + public ScheduledPollAction(Request request) { + super(request); + } + + @Override + public boolean consume() { + Q q = getQ(request.name); + Block currentTakeBlock = q.getCurrentTakeBlock(); + valid = (currentTakeBlock.blockId == request.blockId) + && thisAddress.equals(currentTakeBlock.address) + && currentTakeBlock.size() > 0; + if (valid) { + Data value = poll(request); + request.response = value; + request.key = null; + request.value = null; + returnScheduledAsSuccess(request); + return true; + } else { + onExpire(); + return false; + } + } + + @Override + public void onExpire() { + request.response = null; + request.key = null; + request.value = null; + returnScheduledAsSuccess(request); + } + } + + public class ScheduledOfferAction extends ScheduledAction { + + public ScheduledOfferAction(Request request) { + super(request); + } + + @Override + public boolean consume() { + // didn't expire but is it valid? + Q q = getQ(request.name); + Block currentPutBlock = q.getCurrentPutBlock(); + valid = (currentPutBlock.blockId == request.blockId) + && thisAddress.equals(currentPutBlock.address) + && !currentPutBlock.isFull(); + if (valid) { + offer(request); + request.response = Boolean.TRUE; + request.key = null; + request.value = null; + returnScheduledAsBoolean(request); + return true; + } else { + onExpire(); + return false; + } + } + + @Override + public void onExpire() { + request.response = Boolean.FALSE; + returnScheduledAsBoolean(request); + } + } + + public Block getBlock(int blockId) { + int size = lsBlocks.size(); + for (int i = 0; i < size; i++) { + Block block = lsBlocks.get(i); + if (block.blockId == blockId) { + return block; + } + } + return null; + } + + public void setBlockFull(int fullBlockId) { + // System.out.println("FULL block " + fullBlockId); + if (blCurrentPut != null && blCurrentPut.blockId == fullBlockId) { + blCurrentPut.setFull(true); + blCurrentPut = null; + } + if (blCurrentTake != null && blCurrentTake.blockId == fullBlockId) { + blCurrentTake.setFull(true); + } + int size = lsBlocks.size(); + for (int i = 0; i < size; i++) { + Block block = lsBlocks.get(i); + if (block.blockId == fullBlockId) { + block.setFull(true); + blCurrentPut = null; + return; + } + } + } + + public Block removeBlock(int blockId) { + try { + if (blCurrentPut != null && blCurrentPut.blockId == blockId) { + blCurrentPut = null; + } + + if (blCurrentTake != null && blCurrentTake.blockId == blockId) { + blCurrentTake = null; + } + int size = lsBlocks.size(); + for (int i = 0; i < size; i++) { + Block b = lsBlocks.get(i); + if (b.blockId == blockId) { + blCurrentTake = null; + return lsBlocks.remove(i); + } + } + return null; + } finally { + if (blCurrentPut == null) { + setCurrentPut(); + } + } + } + + public void addBlock(Block newBlock) { + lsBlocks.add(newBlock); + latestAddedBlock = Math.max(newBlock.blockId, latestAddedBlock); + // System.out.println("Adding newBlock " + newBlock); + // printStack(); + } + + int getLatestAddedBlock() { + return latestAddedBlock; + } + + public Block getCurrentPutBlock() { + if (blCurrentPut == null) { + setCurrentPut(); + } + return blCurrentPut; + } + + Block getCurrentTakeBlock() { + if (blCurrentTake == null) { + if (lsBlocks.size() == 0) { + return null; + } + blCurrentTake = lsBlocks.get(0); + } + return blCurrentTake; + } + + public void setCurrentTake() { + if (blCurrentTake == null) { + blCurrentTake = lsBlocks.get(0); + // System.out.println("CurrentTake : " + blCurrentTake); + } + } + + void remove(Remove remove) { + Block block = getBlock(remove.blockId); + if (block != null) { + block.remove(remove.index); + } + remove.setResponse(); + } + + void remove(PacketQueue.Packet packet) { + int index = (int) packet.longValue; + int blockId = packet.blockId; + Block block = getBlock(blockId); + packet.longValue = -1; + if (block != null) { + block.remove(index); + } + sendResponse(packet); + } + + void read(Read read) { + Block block = getBlock(read.blockId); + if (block == null) { + read.setResponse(null, -1); + return; + } + for (int i = read.index; i < BLOCK_SIZE; i++) { + Data data = block.get(i); + if (data != null) { + Data value = ThreadContext.get().hardCopy(data); + read.setResponse(value, i); + return; + } + } + read.setResponse(null, -1); + } + + void read(PacketQueue.Packet packet) { + int index = (int) packet.longValue; + int blockId = packet.blockId; + Block block = getBlock(blockId); + packet.longValue = -1; + if (block != null) { + blockLoop: + for (int i = index; i < BLOCK_SIZE; i++) { + Data data = block.get(i); + if (data != null) { + doHardCopy(data, packet.value); + packet.longValue = i; + break blockLoop; + } + } + } + sendResponse(packet); + } + + void doFireEntryEvent(boolean add, Data value, long recordId) { + if (mapListeners.size() == 0) + return; + if (add) { + fireMapEvent(mapListeners, name, EntryEvent.TYPE_ADDED, value); + } else { + fireMapEvent(mapListeners, name, EntryEvent.TYPE_REMOVED, value); + } + } + + long getRecordId(int blockId, int addIndex) { + return (blockId * BLOCK_SIZE) + addIndex; + } + + int publish(Request req) { + int addIndex = blCurrentPut.add(req.value); + long recordId = getRecordId(blCurrentPut.blockId, addIndex); + doFireEntryEvent(true, req.value, recordId); + if (blCurrentPut.isFull()) { + fireBlockFullEvent(blCurrentPut); + blCurrentPut = null; + setCurrentPut(); + } + return addIndex; + } + + int offer(Request req) { + try { + int addIndex = blCurrentPut.add(req.value); + long recordId = getRecordId(blCurrentPut.blockId, addIndex); + req.recordId = recordId; + doFireEntryEvent(true, req.value, recordId); + size++; + sendBackup(true, req.caller, req.value, blCurrentPut.blockId, addIndex); + req.longValue = addIndex; + if (blCurrentPut.isFull()) { + fireBlockFullEvent(blCurrentPut); + blCurrentPut = null; + setCurrentPut(); + } + return addIndex; + } finally { + boolean consumed = false; + while (!consumed && lsScheduledPollActions.size() > 0) { + ScheduledAction pollAction = lsScheduledPollActions.remove(0); + ClusterManager.get().deregisterScheduledAction(pollAction); + if (pollAction.expired()) { + pollAction.onExpire(); + } else { + consumed = pollAction.consume(); + } + } + } + } + + public Data poll(Request request) { + try { + setCurrentTake(); + Data value = blCurrentTake.remove(); + if (request.txnId != -1) { + MemberImpl backup = null; + if (request.caller.equals(thisAddress)) { + backup = getNextMemberAfter(thisAddress, true, 1); + } else { + backup = getNextMemberAfter(request.caller, true, 1); + } + if (backup != null) { + if (backup.getAddress().equals(thisAddress)) { + doTxnBackupPoll(request.txnId, value); + } else { + sendTxnBackup(backup.getAddress(), value, request.txnId); + } + } + } + size--; + long recordId = getRecordId(blCurrentTake.blockId, blCurrentTake.removeIndex); + request.recordId = recordId; + doFireEntryEvent(false, value, recordId); + + sendBackup(false, request.caller, null, blCurrentTake.blockId, 0); + if (blCurrentTake.size() == 0 && blCurrentTake.isFull()) { + fireBlockRemoveEvent(blCurrentTake); + blCurrentTake = null; + } + return value; + } finally { + boolean consumed = false; + while (!consumed && lsScheduledOfferActions.size() > 0) { + ScheduledOfferAction offerAction = lsScheduledOfferActions.remove(0); + ClusterManager.get().deregisterScheduledAction(offerAction); + if (offerAction.expired()) { + offerAction.onExpire(); + } else { + consumed = offerAction.consume(); + } + } + } + + } + + public Data peek() { + setCurrentTake(); + if (blCurrentTake == null) + return null; + Data value = blCurrentTake.peek(); + if (value == null) { + return null; + } + return ThreadContext.get().hardCopy(value); + } + + boolean doBackup(boolean add, Data data, int blockId, int addIndex) { + if (zeroBackup) return true; + Block block = getBlock(blockId); + if (block == null) + return false; + if (block.address.equals(thisAddress)) { + return false; + } + if (add) { + boolean added = block.add(addIndex, data); + return true; + } else { + if (block.size() > 0) { + block.remove(); + } else { + return false; + } + } + return true; + } + + boolean sendTxnBackup(Address address, Data value, long txnId) { + if (zeroBackup) return true; + PacketQueue.Packet packet = obtainPacket(name, null, value, OP_B_TXN_BACKUP_POLL, 0); + packet.txnId = txnId; + boolean sent = send(packet, address); + if (!sent) { + packet.returnToContainer(); + } + return sent; + } + + boolean sendBackup(boolean add, Address packetoker, Data data, int blockId, int addIndex) { + if (zeroBackup) + return true; + if (addIndex == -1) + throw new RuntimeException("addIndex cannot be -1"); + if (lsMembers.size() > 1) { + if (getNextMemberAfter(thisAddress, true, 1).getAddress().equals(packetoker)) { + return true; + } + int operation = OP_B_BACKUP_REMOVE; + if (add) { + operation = OP_B_BACKUP_ADD; + data = doHardCopy(data); + } + PacketQueue.Packet packet = obtainPacket(name, null, data, operation, 0); + packet.blockId = blockId; + packet.longValue = addIndex; + boolean sent = send(packet, getNextMemberAfter(thisAddress, true, 1).getAddress()); + if (!sent) { + packet.returnToContainer(); + } + return sent; + } else { + return true; + } + } + + void fireBlockRemoveEvent(Block block) { + if (isMaster()) { + doRemoveBlock(Q.this, null, block.blockId); + } else { + removeBlock(block.blockId); + sendAddBlockMessageToOthers(block, -1, null, false); + } + } + + void fireBlockFullEvent(Block block) { + if (isMaster()) { + doFullBlock(Q.this, block.blockId, null); + } else { + sendFullMessage(block); + } + } + + void setCurrentPut() { + int size = lsBlocks.size(); + for (int i = 0; i < size; i++) { + Block block = lsBlocks.get(i); + // System.out.println("setCurrentPut check " + block); + if (!block.isFull()) { + blCurrentPut = block; + // System.out.println("Setting..currentPut " + + // blCurrentPut); + return; + } + } + } + + void printStack() { + System.out.println("========================="); + System.out.println(Hazelcast.getCluster()); + System.out.println("== " + thisAddress + " =="); + for (Block block : lsBlocks) { + System.out.println(block); + } + System.out.println("--------------------"); + System.out.println("CurrenTake " + blCurrentTake); + System.out.println("CurrentPut " + blCurrentPut); + System.out.println("== " + new Date() + " =="); + } + } + + class Block { + final int blockId; + final String name; + Address address; + int addIndex = 0; + int removeIndex = 0; + Data[] values = null; + int size = 0; + boolean full = false; + final long maxAge; + + public Block(Address address, int blockId, long maxAge, String name, boolean keepValues) { + super(); + this.address = address; + this.blockId = blockId; + this.maxAge = maxAge; + this.name = name; + if (keepValues) + values = new Data[BLOCK_SIZE]; + } + + public Data peek() { + for (int i = removeIndex; i < BLOCK_SIZE; i++) { + if (values[i] != null) { + Data value = values[i]; + removeIndex = i; + return value; + } + } + return null; + } + + public Data get(int index) { + return values[index]; + } + + void resetAddIndex() { + int index = BLOCK_SIZE - 1; + while (index > 0) { + if (values[index] != null) { + addIndex = index + 1; + if (addIndex >= BLOCK_SIZE) { + full = true; + } + return; + } + index--; + } + index = 0; + } + + public int add(Data data) { + if (values != null) { + if (values[addIndex] != null) + return -1; + values[addIndex] = data; + } + size++; + int addedCurrentIndex = addIndex; + addIndex++; + if (addIndex >= BLOCK_SIZE) { + full = true; + } + return addedCurrentIndex; + } + + public boolean add(int index, Data data) { + if (values[index] != null) + return false; + values[index] = data; + size++; + return true; + } + + boolean isFull() { + return full; + } + + public void setFull(boolean full) { + this.full = full; + } + + public Data remove(int index) { + Data value = values[index]; + values[index] = null; + if (value != null) + size--; + return value; + } + + public boolean readyToPoll() { + for (int i = removeIndex; i < BLOCK_SIZE; i++) { + if (values[i] != null) { + Data value = values[i]; + long age = System.currentTimeMillis() - value.createDate; + if (age > maxAge) { + values[i] = null; + size--; + } else { + return true; + } + } + } + return false; + } + + public Data remove() { + for (int i = removeIndex; i < BLOCK_SIZE; i++) { + if (values[i] != null) { + Data value = values[i]; + values[i] = null; + size--; + removeIndex = i; + return value; + } + } + return null; + } + + public int size() { + return size; + } + + @Override + public String toString() { + return "Block [" + blockId + "] full=" + isFull() + ", size=" + size() + ", " + address; + } + } + + public static class BlockUpdate implements DataSerializable { + int addBlockId = -1; + int removeBlockId = -1; + int fullBlockId = -1; + Address addAddress = null; + + public BlockUpdate(Address addAddress, int addBlockId, int fullBlockId, int removeBlockId) { + this.addAddress = addAddress; + this.addBlockId = addBlockId; + this.fullBlockId = fullBlockId; + this.removeBlockId = removeBlockId; + } + + public BlockUpdate() { + } + + public void readData(DataInput in) throws IOException { + addBlockId = in.readInt(); + removeBlockId = in.readInt(); + fullBlockId = in.readInt(); + if (addBlockId != -1) { + addAddress = new Address(); + addAddress.readData(in); + } + } + + public void writeData(DataOutput out) throws IOException { + out.writeInt(addBlockId); + out.writeInt(removeBlockId); + out.writeInt(fullBlockId); + if (addBlockId != -1) { + addAddress.writeData(out); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `q` last assigned on line 1168 could be null and is dereferenced at line 1169. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BlockingQueueManager.doPublish(BaseManager$Request) + +### Procedure Id: +com.hazelcast.impl.BlockingQueueManager.doPublish(com.hazelcast.impl.BaseManager$Request):void.0f4e7521c0704cea697a88a39db92c16 + +### File: +src/com/hazelcast/impl/BlockingQueueManager.java + +### Key: +BlockingQueueManager.java|doPublish|NULL_DEREFERENCE + +### Node Key: +10ce9bc2f8f654d9238ee775756a456c + +### Hash: +8a138a1159a915de22090dbca0ba3506 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9539/instruction.md b/inferredbugs-9539/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d6e1097c4daf07c142b7ad81446ca076aa7a90b6 --- /dev/null +++ b/inferredbugs-9539/instruction.md @@ -0,0 +1,2023 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** hazelcast +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2007-2008, Hazel Ltd. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.hazelcast.impl; + +import com.hazelcast.core.EntryEvent; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.impl.BlockingQueueManager.Q.ScheduledOfferAction; +import com.hazelcast.impl.BlockingQueueManager.Q.ScheduledPollAction; +import com.hazelcast.impl.ClusterManager.AbstractRemotelyProcessable; +import com.hazelcast.impl.Config.QConfig; +import static com.hazelcast.impl.Constants.BlockingQueueOperations.*; +import static com.hazelcast.impl.Constants.Objects.OBJECT_NULL; +import com.hazelcast.nio.Address; +import static com.hazelcast.nio.BufferUtil.*; +import com.hazelcast.nio.Data; +import com.hazelcast.nio.DataSerializable; +import com.hazelcast.nio.PacketQueue; +import com.hazelcast.nio.PacketQueue.Packet; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.*; + +class BlockingQueueManager extends BaseManager { + private final Request remoteReq = new Request(); + private final static BlockingQueueManager instance = new BlockingQueueManager(); + private final Map mapQueues = new HashMap(10); + private final Map> mapTxnPolledElements = new HashMap>(10); + private static final int BLOCK_SIZE = 1000; + private int nextIndex = 0; + + private BlockingQueueManager() { + ClusterService.get().registerPacketProcessor(OP_B_POLL, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + try { + handlePoll(packet); + } catch (Throwable t) { + Request req = new Request(); + req.setFromPacket(packet); + printState(req, false, packet.conn.getEndPoint(), 1); + t.printStackTrace(); + } + } + }); + ClusterService.get().registerPacketProcessor(OP_B_OFFER, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleOffer(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_BACKUP_ADD, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleBackup(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_BACKUP_REMOVE, new PacketProcessor() { + public void process(Packet packet) { + handleBackup(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_PUBLISH, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handlePublish(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_ADD_TOPIC_LISTENER, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleAddTopicListener(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_SIZE, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleSize(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_PEEK, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handlePoll(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_READ, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleRead(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_REMOVE, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleRemove(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_TXN_BACKUP_POLL, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleTxnBackupPoll(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_TXN_COMMIT, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleTxnCommit(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_ADD_BLOCK, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleAddBlock(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_REMOVE_BLOCK, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleRemoveBlock(packet); + } + }); + ClusterService.get().registerPacketProcessor(OP_B_FULL_BLOCK, new PacketProcessor() { + public void process(PacketQueue.Packet packet) { + handleFullBlock(packet); + } + }); + + } + + public static BlockingQueueManager get() { + return instance; + } + + class BlockBackupSyncRunner implements Runnable { + final BlockBackupSync blockSync; + + public BlockBackupSyncRunner(BlockBackupSync blockSync) { + this.blockSync = blockSync; + } + + public void run() { + while (!blockSync.done) { + try { + synchronized (blockSync) { + enqueueAndReturn(blockSync); + blockSync.wait(); + } + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + class BlockBackupSync implements Processable { + final Block block; + final Q q; + int index = 0; + final int indexUpto; + volatile boolean done = false; + + public BlockBackupSync(Q q, Block block, int indexUpto) { + super(); + this.q = q; + this.block = block; + this.indexUpto = indexUpto; + } + + public void process() { + Data data = next(); + if (data != null && data.size() != 0) { + q.sendBackup(true, thisAddress, data, block.blockId, index); + index++; + if (index > indexUpto) { + done = true; + } + } else { + done = true; + } + synchronized (BlockBackupSync.this) { + BlockBackupSync.this.notify(); + } + } + + private Data next() { + while (true) { + Data data = block.get(index); + if (data != null) { + return data; + } + index++; + if (index > indexUpto) + return null; + if (index >= BLOCK_SIZE) + return null; + } + } + } + + void syncForDead(Address addressDead) { + MemberImpl member = getNextMemberBeforeSync(addressDead, true, 1); + if (DEBUG) { + log(addressDead + " is dead and its backup was " + member); + } + Address addressNewOwner = (member == null) ? thisAddress : member.getAddress(); + + Collection queues = mapQueues.values(); + for (Q q : queues) { + List lsBlocks = q.lsBlocks; + for (Block block : lsBlocks) { + if (block.address.equals(addressDead)) { + // set the new owner + block.address = addressNewOwner; + block.resetAddIndex(); + if (lsMembers.size() > 1) { + if (addressNewOwner.equals(thisAddress)) { + // I am the new owner so backup to next member + int indexUpto = block.size() - 1; + if (DEBUG) { + log("IndexUpto " + indexUpto); + } + if (indexUpto > -1) { + executeLocally(new BlockBackupSyncRunner(new BlockBackupSync(q, block, + indexUpto))); + } + } + } + } else if (block.address.equals(thisAddress)) { + // If I am/was the owner of this block + // did my backup change.. + // if so backup to the new next + if (lsMembers.size() > 1) { + MemberImpl memberBackupWas = getNextMemberBeforeSync(thisAddress, true, 1); + if (memberBackupWas == null + || memberBackupWas.getAddress().equals(addressDead)) { + int indexUpto = block.size() - 1; + if (indexUpto > -1) { + executeLocally(new BlockBackupSyncRunner(new BlockBackupSync(q, block, + indexUpto))); + } + } + } + } + } + // packetalidate the dead member's scheduled actions + List scheduledPollActions = q.lsScheduledPollActions; + for (ScheduledPollAction scheduledAction : scheduledPollActions) { + if (addressDead.equals(scheduledAction.request.caller)) { + scheduledAction.setValid(false); + ClusterManager.get().deregisterScheduledAction(scheduledAction); + } + } + List scheduledOfferActions = q.lsScheduledOfferActions; + for (ScheduledOfferAction scheduledAction : scheduledOfferActions) { + if (addressDead.equals(scheduledAction.request.caller)) { + scheduledAction.setValid(false); + ClusterManager.get().deregisterScheduledAction(scheduledAction); + } + } + } + doResetBlockSizes(); + } + + public void syncForAdd() { + if (isMaster()) { + Collection queues = mapQueues.values(); + for (Q q : queues) { + List lsBlocks = q.lsBlocks; + for (Block block : lsBlocks) { + int fullBlockId = -1; + if (block.isFull()) { + fullBlockId = block.blockId; + } + sendAddBlockMessageToOthers(block, fullBlockId, null, true); + } + } + } + Collection queues = mapQueues.values(); + for (Q q : queues) { + List lsBlocks = q.lsBlocks; + for (Block block : lsBlocks) { + if (block.address.equals(thisAddress)) { + // If I am/was the owner of this block + // did my backup change.. + // if so backup to the new next + if (lsMembers.size() > 1) { + MemberImpl memberBackupWas = getNextMemberBeforeSync(thisAddress, true, 1); + MemberImpl memberBackupIs = getNextMemberAfter(thisAddress, true, 1); + if (memberBackupWas == null || !memberBackupWas.equals(memberBackupIs)) { + if (DEBUG) { + log("Backup changed!!! so backing up to " + memberBackupIs); + } + int indexUpto = block.size() - 1; + if (indexUpto > -1) { + executeLocally(new BlockBackupSyncRunner(new BlockBackupSync(q, block, + indexUpto))); + } + } + } + } + } + } + doResetBlockSizes(); + } + + void doResetBlockSizes() { + Collection queues = mapQueues.values(); + for (Q q : queues) { + // q.printStack(); + List lsBlocks = q.lsBlocks; + int size = 0; + for (Block block : lsBlocks) { + if (block.address.equals(thisAddress)) { + size += block.size(); + } + } + q.size = size; + } + } + + final void handleSize(PacketQueue.Packet packet) { + Q q = getQ(packet.name); + packet.longValue = q.size; + sendResponse(packet); + } + + @Override + final void handleListenerRegisterations(boolean add, String name, Data key, Address address, + boolean includeValue) { + Q q = getQ(name); + if (add) { + q.addListener(address, includeValue); + } else { + q.removeListener(address); + } + } + + final void handleTxnBackupPoll(PacketQueue.Packet packet) { + doTxnBackupPoll(packet.txnId, doTake(packet.value)); + } + + final void handleTxnCommit(PacketQueue.Packet packet) { + mapTxnPolledElements.remove(packet.txnId); + } + + final void doTxnBackupPoll(long txnId, Data value) { + List lsTxnPolledElements = mapTxnPolledElements.get(txnId); + if (lsTxnPolledElements == null) { + lsTxnPolledElements = new ArrayList(1); + mapTxnPolledElements.put(txnId, lsTxnPolledElements); + } + lsTxnPolledElements.add(value); + } + + final void handleBackup(PacketQueue.Packet packet) { + try { + String name = packet.name; + int blockId = packet.blockId; + Q q = getQ(name); + if (packet.operation == OP_B_BACKUP_ADD) { + Data data = doTake(packet.value); + q.doBackup(true, data, blockId, (int) packet.longValue); + } else if (packet.operation == OP_B_BACKUP_REMOVE) { + q.doBackup(false, null, blockId, 0); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + packet.returnToContainer(); + } + } + + final void handleRemoveBlock(PacketQueue.Packet packet) { + try { + BlockUpdate addRemove = (BlockUpdate) ThreadContext.get().toObject(packet.value); + String name = packet.name; + Q q = getQ(name); + doRemoveBlock(q, packet.conn.getEndPoint(), addRemove.removeBlockId); + } catch (Exception e) { + e.printStackTrace(); + } finally { + packet.returnToContainer(); + } + } + + public void doRemoveBlock(Q q, Address originalRemover, int blockId) { + Block blockRemoved = q.removeBlock(blockId); + if (isMaster()) { + sendAddBlockMessageToOthers(q.name, null, blockId, -1, originalRemover, false); + } + + } + + final void handleFullBlock(PacketQueue.Packet packet) { + if (isMaster()) { + String name = packet.name; + Q q = getQ(name); + doFullBlock(q, packet.blockId, packet.conn.getEndPoint()); + } + packet.returnToContainer(); + } + + final void doFullBlock(Q q, int fullBlockId, Address originalFuller) { + int blockId = q.getLatestAddedBlock() + 1; + Address target = nextTarget(); + Block newBlock = setFullAndCreateNewBlock(q, fullBlockId, target, blockId); + if (newBlock != null) { + sendAddBlockMessageToOthers(newBlock, fullBlockId, originalFuller, true); + } + } + + final void handleAddBlock(PacketQueue.Packet packet) { + try { + BlockUpdate addRemove = (BlockUpdate) ThreadContext.get().toObject(packet.value); + String name = packet.name; + int blockId = addRemove.addBlockId; + Address addressOwner = addRemove.addAddress; + Q q = getQ(name); + setFullAndCreateNewBlock(q, addRemove.fullBlockId, addressOwner, blockId); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + packet.returnToContainer(); + } + } + + Block setFullAndCreateNewBlock(Q q, int fullBlockId, Address newBlockOwner, int newBlockId) { + List lsBlocks = q.lsBlocks; + boolean exist = false; + for (Block block : lsBlocks) { + if (block.blockId == newBlockId) { + exist = true; + } + } + Block newBlock = null; + if (!exist) { + newBlock = q.createBlock(newBlockOwner, newBlockId); + q.addBlock(newBlock); + } + if (fullBlockId != -1) { + q.setBlockFull(fullBlockId); + } + return newBlock; + } + + final void handleOffer(PacketQueue.Packet packet) { + if (rightRemoteOfferTarget(packet)) { + remoteReq.setFromPacket(packet); + doOffer(remoteReq); + packet.longValue = remoteReq.longValue; + if (!remoteReq.scheduled) { + if (remoteReq.response == Boolean.TRUE) { + sendResponse(packet); + } else { + sendResponseFailure(packet); + } + } else { + packet.returnToContainer(); + } + remoteReq.reset(); + } + } + + final void handlePublish(Packet packet) { + if (rightRemoteOfferTarget(packet)) { + remoteReq.setFromPacket(packet); + doPublish(remoteReq); + packet.longValue = remoteReq.longValue; + if (!remoteReq.scheduled) { + if (remoteReq.response == Boolean.TRUE) { + sendResponse(packet); + } else { + sendResponseFailure(packet); + } + } else { + packet.returnToContainer(); + } + remoteReq.reset(); + } + } + + final void handleAddTopicListener(PacketQueue.Packet packet) { + if (rightRemoteOfferTarget(packet)) { + remoteReq.setFromPacket(packet); + doAddTopicListener(remoteReq); + packet.longValue = remoteReq.longValue; + sendResponse(packet); + remoteReq.reset(); + } + } + + final boolean rightRemoteOfferTarget(PacketQueue.Packet packet) { + Q q = getQ(packet.name); + if (q.blCurrentPut == null) { + q.setCurrentPut(); + } + boolean invalid = false; + if (packet.blockId != q.blCurrentPut.blockId) { + if (packet.blockId > q.blCurrentPut.blockId) { + int size = q.lsBlocks.size(); + for (int i = 0; i < size; i++) { + Block block = q.lsBlocks.get(i); + if (block.blockId == packet.blockId) { + if (thisAddress.equals(block.address)) { + q.blCurrentPut = block; + } + } + } + } else { + invalid = true; + } + } + if (q.blCurrentPut.isFull() || !thisAddress.equals(q.blCurrentPut.address)) { + invalid = true; + } + if (invalid) { + sendRedoResponse(packet); + } + return (!invalid); + } + + boolean rightRemotePollTarget(Packet packet) { + Q q = getQ(packet.name); + if (q.blCurrentTake == null) { + q.setCurrentTake(); + } + boolean invalid = false; + if (packet.blockId != q.blCurrentTake.blockId) { + if (packet.blockId > q.blCurrentTake.blockId) { + int size = q.lsBlocks.size(); + for (int i = 0; i < size; i++) { + Block block = q.lsBlocks.get(i); + if (block.blockId == packet.blockId) { + if (thisAddress.equals(block.address)) { + q.blCurrentTake = block; + } + } + } + } else { + invalid = true; + } + } + if ((q.blCurrentTake.size() == 0 && q.blCurrentTake.isFull()) + || !thisAddress.equals(q.blCurrentTake.address)) { + invalid = true; + } + if (invalid) { + sendRedoResponse(packet); + } + return (!invalid); + } + + final void handlePoll(PacketQueue.Packet packet) { + if (rightRemotePollTarget(packet)) { + remoteReq.setFromPacket(packet); + doPoll(remoteReq); + if (!remoteReq.scheduled) { + Data oldValue = (Data) remoteReq.response; + if (oldValue != null && oldValue.size() > 0) { + doSet(oldValue, packet.value); + } + sendResponse(packet); + } else { + packet.returnToContainer(); + } + remoteReq.reset(); + } + } + + final void handleRead(PacketQueue.Packet packet) { + Q q = getQ(packet.name); + q.read(packet); + } + + final void handleRemove(PacketQueue.Packet packet) { + Q q = getQ(packet.name); + q.remove(packet); + } + + final Address nextTarget() { + int size = lsMembers.size(); + int index = nextIndex++ % size; + if (nextIndex >= size) { + nextIndex = 0; + } + return lsMembers.get(index).getAddress(); + } + + public Q getQ(String name) { + if (name == null) + return null; + Q q = mapQueues.get(name); + if (q == null) { + q = new Q(name); + mapQueues.put(name, q); + } + return q; + } + + public class CommitPoll extends AbstractCall { + volatile long txnId = -1; + String name = null; + + public int getOperation() { + return OP_B_TXN_COMMIT; + } + + public void commitPoll(String name) { + this.name = name; + this.txnId = ThreadContext.get().getTxnId(); + enqueueAndReturn(this); + } + + public void handleResponse(PacketQueue.Packet packet) { + } + + public void process() { + MemberImpl nextMember = getNextMemberAfter(thisAddress, true, 1); + if (nextMember != null) { + Address next = nextMember.getAddress(); + PacketQueue.Packet packet = obtainPacket(); + packet.name = name; + packet.operation = getOperation(); + packet.txnId = txnId; + boolean sent = send(packet, next); + if (!sent) { + packet.returnToContainer(); + } + } + } + } + + class QDestroy { + public void destroy(String name) { + sendProcessableToAll(new Destroy(name), true); + } + } + + public void destroy(String name) { + mapQueues.remove(name); + } + + public class Size extends AbstractCall { + String name = null; + int total = 0; + int numberOfResponses = 0; + int numberOfExpectedResponses = 1; + + public int getSize(String name) { + this.name = name; + synchronized (this) { + try { + enqueueAndReturn(this); + wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + return total; + } + + @Override + public void onDisconnect(Address dead) { + redo(); + } + + public void reset() { + total = 0; + numberOfResponses = 0; + numberOfExpectedResponses = 0; + } + + public void handleResponse(PacketQueue.Packet packet) { + total += (int) packet.longValue; + packet.returnToContainer(); + numberOfResponses++; + if (numberOfResponses >= numberOfExpectedResponses) { + removeCall(getId()); + synchronized (this) { + notify(); + } + } + } + + public void process() { + reset(); + Q q = getQ(name); + if (DEBUG) { + q.printStack(); + } + total += q.size; + numberOfResponses = 1; + if (lsMembers.size() > 1) { + addCall(this); + numberOfExpectedResponses = lsMembers.size(); + for (MemberImpl member : lsMembers) { + if (!member.localMember()) { + PacketQueue.Packet packet = obtainPacket(); + packet.name = name; + packet.operation = getOperation(); + packet.callId = getId(); + packet.timeout = 0; + boolean sent = send(packet, member.getAddress()); + if (!sent) { + packet.returnToContainer(); + redo(); + } + } + } + } else { + synchronized (this) { + this.notify(); + } + } + } + + public int getOperation() { + return OP_B_SIZE; + } + } + + class QIterator implements Iterator, Processable { + + volatile String name; + volatile List blocks = null; + int currentBlockId = -1; + int currentIndex = -1; + Object next = null; + boolean hasNextCalled = false; + + public void set(String name) { + synchronized (QIterator.this) { + this.name = name; + enqueueAndReturn(QIterator.this); + try { + QIterator.this.wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + public void process() { + Q q = getQ(name); + List lsBlocks = q.lsBlocks; + blocks = new ArrayList(lsBlocks.size()); + for (Block block : lsBlocks) { + blocks.add(block.blockId); + } + synchronized (QIterator.this) { + QIterator.this.notify(); + } + } + + public boolean hasNext() { + next = null; + while (next == null) { + boolean canRead = setNextBlock(); + // System.out.println(currentBlockId + " Can read " + canRead); + if (!canRead) + return false; + Read read = new Read(); + next = read.read(name, currentBlockId, currentIndex); + // System.out.println(currentIndex + " Next " + next); + if (next == null) { + currentIndex = -1; + } else { + currentIndex = read.readIndex; + currentIndex++; + } + } + hasNextCalled = true; + return true; + } + + boolean setNextBlock() { + if (currentIndex == -1 || currentIndex >= BLOCK_SIZE) { + if (blocks.size() == 0) { + return false; + } else { + currentBlockId = blocks.remove(0); + currentIndex = 0; + return true; + } + } + return true; + } + + public E next() { + if (!hasNextCalled) { + boolean hasNext = hasNext(); + if (!hasNext) { + return null; + } + } + if (next != null) { + hasNextCalled = false; + } + return (E) next; + } + + public void remove() { + } + + } + + public class Remove extends QueueBasedCall { + String name; + int blockId; + int index; + + public Object remove(String name, int blockId, int index) { + this.name = name; + this.blockId = blockId; + this.index = index; + enqueueAndReturn(this); + Object result; + try { + result = responses.take(); + if (result == OBJECT_NULL) + return null; + else { + return ThreadContext.get().toObject((Data) result); + } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + void setResponse() { + responses.add(OBJECT_NULL); + } + + public void handleResponse(PacketQueue.Packet packet) { + setResponse(); + packet.returnToContainer(); + } + + @Override + public void onDisconnect(Address dead) { + process(); + } + + public void process() { + addCall(this); + Q q = getQ(name); + + Address target = q.getBlockOwner(blockId); + if (target == null) { + responses.add(OBJECT_NULL); + } else if (target.equals(thisAddress)) { + q.remove(this); + } else { + Packet packet = obtainPacket(); + packet.name = name; + packet.operation = getOperation(); + packet.callId = getId(); + packet.blockId = blockId; + packet.timeout = 0; + packet.longValue = index; + boolean sent = false; + if (target != null) { + sent = send(packet, target); + } + if (target == null || !sent) { + packet.returnToContainer(); + responses.add(OBJECT_NULL); + } + } + } + + public int getOperation() { + return OP_B_REMOVE; + } + + } + + public class Read extends QueueBasedCall { + String name; + int blockId; + int index; + int readIndex = 0; + + public Object read(String name, int blockId, int index) { + this.name = name; + this.blockId = blockId; + this.index = index; + enqueueAndReturn(this); + Object result; + try { + result = responses.take(); + if (result == OBJECT_NULL) + return null; + else { + return ThreadContext.get().toObject((Data) result); + } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + void setResponse(Data value, int index) { + responses.clear(); + readIndex = index; + responses.add((value == null) ? OBJECT_NULL : value); + } + + public void handleResponse(PacketQueue.Packet packet) { + Data value = doTake(packet.value); + int indexRead = (int) packet.longValue; + setResponse(value, indexRead); + removeCall(getId()); + packet.returnToContainer(); + } + + @Override + public void onDisconnect(Address dead) { + removeCall(getId()); + enqueueAndReturn(Read.this); + } + + public void process() { + responses.clear(); + Q q = getQ(name); + Address target = q.getBlockOwner(blockId); + if (target == null) { + responses.add(OBJECT_NULL); + } else if (target.equals(thisAddress)) { + q.read(this); + } else { + addCall(this); + PacketQueue.Packet packet = obtainPacket(); + packet.name = name; + packet.operation = getOperation(); + packet.callId = getId(); + packet.blockId = blockId; + packet.timeout = 0; + packet.longValue = index; + boolean sent = send(packet, target); + if (!sent) { + packet.returnToContainer(); + onDisconnect(target); + } + } + } + + public int getOperation() { + return OP_B_READ; + } + + } + + class AddTopicListener extends LongOp { + public Long add(String name, Object value, long timeout, long txnId) { + return (Long) objectCall(OP_B_ADD_TOPIC_LISTENER, name, null, value, timeout, txnId, -1); + } + + @Override + void setTarget() { + target = getTargetForOffer(request); + } + + @Override + void doLocalOp() { + doAddTopicListener(request); + setResult(Long.valueOf(request.recordId)); + } + } + + class Offer extends BooleanOp { + + int doCount = 1; + + public boolean publish(String name, Object value, long timeout, long txnId) { + return booleanCall(OP_B_PUBLISH, name, null, value, timeout, txnId, -1); + } + + public boolean offer(String name, Object value, long timeout, long txnId) { + return booleanCall(OP_B_OFFER, name, null, value, timeout, txnId, -1); + } + + @Override + void handleNoneRedoResponse(PacketQueue.Packet packet) { + if (request.operation == OP_B_OFFER + && packet.responseType == ResponseTypes.RESPONSE_SUCCESS) { + if (!zeroBackup) { + if (getPreviousMemberBefore(thisAddress, true, 1).getAddress().equals( + packet.conn.getEndPoint())) { + int itemIndex = (int) packet.longValue; + if (itemIndex != -1) { + Q q = getQ(request.name); + if (request.value == null || request.value.size() == 0) { + throw new RuntimeException("Invalid data " + request.value); + } + q.doBackup(true, request.value, request.blockId, (int) packet.longValue); + } + } + } + } + super.handleNoneRedoResponse(packet); + } + + @Override + public void process() { + if (doCount++ % 4 == 0) { + printState(request, true, target, doCount); + + } + super.process(); + } + + @Override + void setTarget() { + target = getTargetForOffer(request); + } + + @Override + void doLocalOp() { + if (request.operation == OP_B_OFFER) { + doOffer(request); + if (!request.scheduled) { + setResult(request.response); + } + } else { + doPublish(request); + setResult(request.response); + } + } + } + + public Address getTargetForOffer(Request request) { + Address target = null; + Q q = getQ(request.name); + Block block = q.getCurrentPutBlock(); + if (block == null) { + target = getMasterAddress(); + request.blockId = 0; + } else { + target = block.address; + request.blockId = block.blockId; + } + return target; + } + + class Poll extends TargetAwareOp { + + public Object peek(String name) { + return objectCall(OP_B_PEEK, name, null, null, 0, -1, -1); + } + + public Object poll(String name, long timeout) { + return objectCall(OP_B_POLL, name, null, null, timeout, -1, -1); + } + + @Override + void setTarget() { + Q q = getQ(request.name); + Block takeBlock = q.getCurrentTakeBlock(); + if (takeBlock == null) { + target = getMasterAddress(); + request.blockId = 0; + } else { + target = takeBlock.address; + request.blockId = takeBlock.blockId; + } + } + + @Override + void doLocalOp() { + doPoll(request); + if (!request.scheduled) { + setResult(request.response); + } + } + + @Override + void handleNoneRedoResponse(PacketQueue.Packet packet) { + if (request.operation == OP_B_POLL + && packet.responseType == ResponseTypes.RESPONSE_SUCCESS) { + if (!zeroBackup) { + if (getPreviousMemberBefore(thisAddress, true, 1).getAddress().equals( + packet.conn.getEndPoint())) { + if (packet.value != null) { + Q q = getQ(packet.name); + q.doBackup(false, null, request.blockId, 0); + } + } + } + } + super.handleNoneRedoResponse(packet); + } + } + + void doAddTopicListener(Request req) { + for (MemberImpl member : lsMembers) { + if (member.localMember()) { + handleListenerRegisterations(true, req.name, req.key, req.caller, true); + } else if (!member.getAddress().equals(req.caller)) { + sendProcessableTo(new TopicListenerRegistration(req.name, true, req.caller), member + .getAddress()); + } + } + Q q = getQ(req.name); + if (q.blCurrentPut == null) { + q.setCurrentPut(); + } + req.recordId = q.getRecordId(q.blCurrentPut.blockId, q.blCurrentPut.addIndex); + } + + public static class TopicListenerRegistration extends AbstractRemotelyProcessable { + String name = null; + boolean add = true; + Address listenerAddress = null; + + public TopicListenerRegistration() { + } + + public TopicListenerRegistration(String name, boolean add, Address listenerAddress) { + super(); + this.name = name; + this.add = add; + this.listenerAddress = listenerAddress; + } + + @Override + public void readData(DataInput in) throws IOException { + add = in.readBoolean(); + listenerAddress = new Address(); + listenerAddress.readData(in); + name = in.readUTF(); + } + + @Override + public void writeData(DataOutput out) throws IOException { + out.writeBoolean(add); + listenerAddress.writeData(out); + out.writeUTF(name); + } + + public void process() { + ListenerManager.get().handleListenerRegisterations(true, name, null, listenerAddress, + true); + } + + } + + void printState(Request request, boolean local, Address address, int doCount) { + Q q = getQ(request.name); + q.printStack(); + System.out.println(local + " ===== CurrentRequest === " + doCount); + System.out.println("blockId: " + request.blockId); + System.out.println("operation: " + request.operation); + System.out.println("version: " + request.version); + System.out.println("timeout: " + request.timeout); + System.out.println("target: " + address); + System.out.println("=========== DONE ======="); + } + + void doPublish(Request req) { + Q q = getQ(req.name); + if (q.blCurrentPut == null) { + q.setCurrentPut(); + } + int index = q.publish(req); + req.longValue = index; + req.response = Boolean.TRUE; + } + + void doOffer(Request req) { + Q q = getQ(req.name); + if (q.blCurrentPut == null) { + q.setCurrentPut(); + } + if (q.size >= q.maxSizePerJVM) { + if (req.hasEnoughTimeToSchedule()) { + req.scheduled = true; + final Request reqScheduled = (req.local) ? req : req.hardCopy(); + if (reqScheduled.local) { + if (reqScheduled.attachment == null) { + throw new RuntimeException("Scheduled local but attachement is null"); + } + } + q.scheduleOffer(reqScheduled); + } else { + req.response = Boolean.FALSE; + } + return; + } + q.offer(req); + req.value = null; + req.response = Boolean.TRUE; + } + + void doPoll(final Request req) { + Q q = getQ(req.name); + if (q.blCurrentTake == null) { + q.setCurrentTake(); + } + if (q.blCurrentTake.size() == 0) { + if (req.hasEnoughTimeToSchedule()) { + req.scheduled = true; + final Request reqScheduled = (req.local) ? req : req.hardCopy(); + if (reqScheduled.local) { + if (reqScheduled.attachment == null) { + throw new RuntimeException("Scheduled local but attachement is null"); + } + } + q.schedulePoll(reqScheduled); + } else { + req.response = null; + } + return; + } + Data value = null; + if (req.operation == OP_B_PEEK) { + value = q.peek(); + } else { + value = q.poll(req); + } + req.response = value; + } + + public void sendAddBlockMessageToOthers(Block block, int fullBlockId, Address except, + boolean add) { + sendAddBlockMessageToOthers(block.name, block.address, block.blockId, fullBlockId, except, add); + } + + public void sendAddBlockMessageToOthers(String name, Address addAddress, int blockId, int fullBlockId, Address except, + boolean add) { + int operation = OP_B_ADD_BLOCK; + if (!add) { + operation = OP_B_REMOVE_BLOCK; + } + if (lsMembers.size() > 1) { + int addBlockId = -1; + int removeBlockId = -1; + if (add) { + addBlockId = blockId; + except = null; + } else { + removeBlockId = blockId; + } + BlockUpdate addRemove = new BlockUpdate(addAddress, addBlockId, fullBlockId, + removeBlockId); + for (MemberImpl member : lsMembers) { + if (!member.localMember()) { + Address dest = member.getAddress(); + if (!dest.equals(except)) { + send(name, operation, addRemove, dest); + } + } + } + } + } + + public void sendFullMessage(Block block) { + try { + PacketQueue.Packet packet = PacketQueue.get().obtainPacket(); + packet.set(block.name, OP_B_FULL_BLOCK, null, null); + packet.blockId = block.blockId; + Address master = getMasterAddress(); + boolean sent = send(packet, master); + if (!sent) + packet.returnToContainer(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public class Q { + String name; + int size = 0; + List lsBlocks = new ArrayList(10); + Block blCurrentPut = null; + Block blCurrentTake = null; + int latestAddedBlock = -1; + + List lsScheduledPollActions = new ArrayList(100); + List lsScheduledOfferActions = new ArrayList( + 100); + int maxSizePerJVM = Integer.MAX_VALUE; + + Map mapListeners = new HashMap(1); + boolean keepValues = true; + + long maxAge = Long.MAX_VALUE; + + public Q(String name) { + if (name.startsWith("q:t:")) { + keepValues = false; + } else { + QConfig qconfig = Config.get().getQConfig(name.substring(2)); + if (qconfig != null) { + maxSizePerJVM = qconfig.maxSizePerJVM; + log("qConfig " + qconfig.maxSizePerJVM); + } + } + this.name = name; + Address master = getMasterAddress(); + if (master.isThisAddress()) { + Block block = createBlock(master, 0); + addBlock(block); + sendAddBlockMessageToOthers(block, -1, null, true); + for (int i = 0; i < 9; i++) { + int blockId = i + 1; + Address target = nextTarget(); + block = createBlock(target, blockId); + addBlock(block); + sendAddBlockMessageToOthers(block, -1, null, true); + } + } + } + + public Block createBlock(Address address, int blockId) { + return new Block(address, blockId, maxAge, name, keepValues); + } + + public Address getBlockOwner(int blockId) { + for (Block block : lsBlocks) { + if (block.blockId == blockId) + return block.address; + } + return null; + } + + public void addListener(Address address, boolean includeValue) { + mapListeners.put(address, includeValue); + } + + public void removeListener(Address address) { + mapListeners.remove(address); + } + + public void scheduleOffer(Request request) { + ScheduledOfferAction action = new ScheduledOfferAction(request); + lsScheduledOfferActions.add(action); + ClusterManager.get().registerScheduledAction(action); + + } + + public void schedulePoll(Request request) { + ScheduledPollAction action = new ScheduledPollAction(request); + lsScheduledPollActions.add(action); + ClusterManager.get().registerScheduledAction(action); + } + + public class ScheduledPollAction extends ScheduledAction { + + public ScheduledPollAction(Request request) { + super(request); + } + + @Override + public boolean consume() { + Q q = getQ(request.name); + Block currentTakeBlock = q.getCurrentTakeBlock(); + valid = (currentTakeBlock.blockId == request.blockId) + && thisAddress.equals(currentTakeBlock.address) + && currentTakeBlock.size() > 0; + if (valid) { + Data value = poll(request); + request.response = value; + request.key = null; + request.value = null; + returnScheduledAsSuccess(request); + return true; + } else { + onExpire(); + return false; + } + } + + @Override + public void onExpire() { + request.response = null; + request.key = null; + request.value = null; + returnScheduledAsSuccess(request); + } + } + + public class ScheduledOfferAction extends ScheduledAction { + + public ScheduledOfferAction(Request request) { + super(request); + } + + @Override + public boolean consume() { + // didn't expire but is it valid? + Q q = getQ(request.name); + Block currentPutBlock = q.getCurrentPutBlock(); + valid = (currentPutBlock.blockId == request.blockId) + && thisAddress.equals(currentPutBlock.address) + && !currentPutBlock.isFull(); + if (valid) { + offer(request); + request.response = Boolean.TRUE; + request.key = null; + request.value = null; + returnScheduledAsBoolean(request); + return true; + } else { + onExpire(); + return false; + } + } + + @Override + public void onExpire() { + request.response = Boolean.FALSE; + returnScheduledAsBoolean(request); + } + } + + public Block getBlock(int blockId) { + int size = lsBlocks.size(); + for (int i = 0; i < size; i++) { + Block block = lsBlocks.get(i); + if (block.blockId == blockId) { + return block; + } + } + return null; + } + + public void setBlockFull(int fullBlockId) { + // System.out.println("FULL block " + fullBlockId); + if (blCurrentPut != null && blCurrentPut.blockId == fullBlockId) { + blCurrentPut.setFull(true); + blCurrentPut = null; + } + if (blCurrentTake != null && blCurrentTake.blockId == fullBlockId) { + blCurrentTake.setFull(true); + } + int size = lsBlocks.size(); + for (int i = 0; i < size; i++) { + Block block = lsBlocks.get(i); + if (block.blockId == fullBlockId) { + block.setFull(true); + blCurrentPut = null; + return; + } + } + } + + public Block removeBlock(int blockId) { + try { + if (blCurrentPut != null && blCurrentPut.blockId == blockId) { + blCurrentPut = null; + } + + if (blCurrentTake != null && blCurrentTake.blockId == blockId) { + blCurrentTake = null; + } + int size = lsBlocks.size(); + for (int i = 0; i < size; i++) { + Block b = lsBlocks.get(i); + if (b.blockId == blockId) { + blCurrentTake = null; + return lsBlocks.remove(i); + } + } + return null; + } finally { + if (blCurrentPut == null) { + setCurrentPut(); + } + } + } + + public void addBlock(Block newBlock) { + lsBlocks.add(newBlock); + latestAddedBlock = Math.max(newBlock.blockId, latestAddedBlock); + // System.out.println("Adding newBlock " + newBlock); + // printStack(); + } + + int getLatestAddedBlock() { + return latestAddedBlock; + } + + public Block getCurrentPutBlock() { + if (blCurrentPut == null) { + setCurrentPut(); + } + return blCurrentPut; + } + + Block getCurrentTakeBlock() { + if (blCurrentTake == null) { + if (lsBlocks.size() == 0) { + return null; + } + blCurrentTake = lsBlocks.get(0); + } + return blCurrentTake; + } + + public void setCurrentTake() { + if (blCurrentTake == null) { + blCurrentTake = lsBlocks.get(0); + // System.out.println("CurrentTake : " + blCurrentTake); + } + } + + void remove(Remove remove) { + Block block = getBlock(remove.blockId); + if (block != null) { + block.remove(remove.index); + } + remove.setResponse(); + } + + void remove(PacketQueue.Packet packet) { + int index = (int) packet.longValue; + int blockId = packet.blockId; + Block block = getBlock(blockId); + packet.longValue = -1; + if (block != null) { + block.remove(index); + } + sendResponse(packet); + } + + void read(Read read) { + Block block = getBlock(read.blockId); + if (block == null) { + read.setResponse(null, -1); + return; + } + for (int i = read.index; i < BLOCK_SIZE; i++) { + Data data = block.get(i); + if (data != null) { + Data value = ThreadContext.get().hardCopy(data); + read.setResponse(value, i); + return; + } + } + read.setResponse(null, -1); + } + + void read(PacketQueue.Packet packet) { + int index = (int) packet.longValue; + int blockId = packet.blockId; + Block block = getBlock(blockId); + packet.longValue = -1; + if (block != null) { + blockLoop: + for (int i = index; i < BLOCK_SIZE; i++) { + Data data = block.get(i); + if (data != null) { + doHardCopy(data, packet.value); + packet.longValue = i; + break blockLoop; + } + } + } + sendResponse(packet); + } + + void doFireEntryEvent(boolean add, Data value, long recordId) { + if (mapListeners.size() == 0) + return; + if (add) { + fireMapEvent(mapListeners, name, EntryEvent.TYPE_ADDED, value); + } else { + fireMapEvent(mapListeners, name, EntryEvent.TYPE_REMOVED, value); + } + } + + long getRecordId(int blockId, int addIndex) { + return (blockId * BLOCK_SIZE) + addIndex; + } + + int publish(Request req) { + int addIndex = blCurrentPut.add(req.value); + long recordId = getRecordId(blCurrentPut.blockId, addIndex); + doFireEntryEvent(true, req.value, recordId); + if (blCurrentPut.isFull()) { + fireBlockFullEvent(blCurrentPut); + blCurrentPut = null; + setCurrentPut(); + } + return addIndex; + } + + int offer(Request req) { + try { + int addIndex = blCurrentPut.add(req.value); + long recordId = getRecordId(blCurrentPut.blockId, addIndex); + req.recordId = recordId; + doFireEntryEvent(true, req.value, recordId); + size++; + sendBackup(true, req.caller, req.value, blCurrentPut.blockId, addIndex); + req.longValue = addIndex; + if (blCurrentPut.isFull()) { + fireBlockFullEvent(blCurrentPut); + blCurrentPut = null; + setCurrentPut(); + } + return addIndex; + } finally { + boolean consumed = false; + while (!consumed && lsScheduledPollActions.size() > 0) { + ScheduledAction pollAction = lsScheduledPollActions.remove(0); + ClusterManager.get().deregisterScheduledAction(pollAction); + if (pollAction.expired()) { + pollAction.onExpire(); + } else { + consumed = pollAction.consume(); + } + } + } + } + + public Data poll(Request request) { + try { + setCurrentTake(); + Data value = blCurrentTake.remove(); + if (request.txnId != -1) { + MemberImpl backup = null; + if (request.caller.equals(thisAddress)) { + backup = getNextMemberAfter(thisAddress, true, 1); + } else { + backup = getNextMemberAfter(request.caller, true, 1); + } + if (backup != null) { + if (backup.getAddress().equals(thisAddress)) { + doTxnBackupPoll(request.txnId, value); + } else { + sendTxnBackup(backup.getAddress(), value, request.txnId); + } + } + } + size--; + long recordId = getRecordId(blCurrentTake.blockId, blCurrentTake.removeIndex); + request.recordId = recordId; + doFireEntryEvent(false, value, recordId); + + sendBackup(false, request.caller, null, blCurrentTake.blockId, 0); + if (blCurrentTake.size() == 0 && blCurrentTake.isFull()) { + fireBlockRemoveEvent(blCurrentTake); + blCurrentTake = null; + } + return value; + } finally { + boolean consumed = false; + while (!consumed && lsScheduledOfferActions.size() > 0) { + ScheduledOfferAction offerAction = lsScheduledOfferActions.remove(0); + ClusterManager.get().deregisterScheduledAction(offerAction); + if (offerAction.expired()) { + offerAction.onExpire(); + } else { + consumed = offerAction.consume(); + } + } + } + + } + + public Data peek() { + setCurrentTake(); + if (blCurrentTake == null) + return null; + Data value = blCurrentTake.peek(); + if (value == null) { + return null; + } + return ThreadContext.get().hardCopy(value); + } + + boolean doBackup(boolean add, Data data, int blockId, int addIndex) { + if (zeroBackup) return true; + Block block = getBlock(blockId); + if (block == null) + return false; + if (block.address.equals(thisAddress)) { + return false; + } + if (add) { + boolean added = block.add(addIndex, data); + return true; + } else { + if (block.size() > 0) { + block.remove(); + } else { + return false; + } + } + return true; + } + + boolean sendTxnBackup(Address address, Data value, long txnId) { + if (zeroBackup) return true; + PacketQueue.Packet packet = obtainPacket(name, null, value, OP_B_TXN_BACKUP_POLL, 0); + packet.txnId = txnId; + boolean sent = send(packet, address); + if (!sent) { + packet.returnToContainer(); + } + return sent; + } + + boolean sendBackup(boolean add, Address packetoker, Data data, int blockId, int addIndex) { + if (zeroBackup) + return true; + if (addIndex == -1) + throw new RuntimeException("addIndex cannot be -1"); + if (lsMembers.size() > 1) { + if (getNextMemberAfter(thisAddress, true, 1).getAddress().equals(packetoker)) { + return true; + } + int operation = OP_B_BACKUP_REMOVE; + if (add) { + operation = OP_B_BACKUP_ADD; + data = doHardCopy(data); + } + PacketQueue.Packet packet = obtainPacket(name, null, data, operation, 0); + packet.blockId = blockId; + packet.longValue = addIndex; + boolean sent = send(packet, getNextMemberAfter(thisAddress, true, 1).getAddress()); + if (!sent) { + packet.returnToContainer(); + } + return sent; + } else { + return true; + } + } + + void fireBlockRemoveEvent(Block block) { + if (isMaster()) { + doRemoveBlock(Q.this, null, block.blockId); + } else { + removeBlock(block.blockId); + sendAddBlockMessageToOthers(block, -1, null, false); + } + } + + void fireBlockFullEvent(Block block) { + if (isMaster()) { + doFullBlock(Q.this, block.blockId, null); + } else { + sendFullMessage(block); + } + } + + void setCurrentPut() { + int size = lsBlocks.size(); + for (int i = 0; i < size; i++) { + Block block = lsBlocks.get(i); + // System.out.println("setCurrentPut check " + block); + if (!block.isFull()) { + blCurrentPut = block; + // System.out.println("Setting..currentPut " + + // blCurrentPut); + return; + } + } + } + + void printStack() { + System.out.println("========================="); + System.out.println(Hazelcast.getCluster()); + System.out.println("== " + thisAddress + " =="); + for (Block block : lsBlocks) { + System.out.println(block); + } + System.out.println("--------------------"); + System.out.println("CurrenTake " + blCurrentTake); + System.out.println("CurrentPut " + blCurrentPut); + System.out.println("== " + new Date() + " =="); + } + } + + class Block { + final int blockId; + final String name; + Address address; + int addIndex = 0; + int removeIndex = 0; + Data[] values = null; + int size = 0; + boolean full = false; + final long maxAge; + + public Block(Address address, int blockId, long maxAge, String name, boolean keepValues) { + super(); + this.address = address; + this.blockId = blockId; + this.maxAge = maxAge; + this.name = name; + if (keepValues) + values = new Data[BLOCK_SIZE]; + } + + public Data peek() { + for (int i = removeIndex; i < BLOCK_SIZE; i++) { + if (values[i] != null) { + Data value = values[i]; + removeIndex = i; + return value; + } + } + return null; + } + + public Data get(int index) { + return values[index]; + } + + void resetAddIndex() { + int index = BLOCK_SIZE - 1; + while (index > 0) { + if (values[index] != null) { + addIndex = index + 1; + if (addIndex >= BLOCK_SIZE) { + full = true; + } + return; + } + index--; + } + index = 0; + } + + public int add(Data data) { + if (values != null) { + if (values[addIndex] != null) + return -1; + values[addIndex] = data; + } + size++; + int addedCurrentIndex = addIndex; + addIndex++; + if (addIndex >= BLOCK_SIZE) { + full = true; + } + return addedCurrentIndex; + } + + public boolean add(int index, Data data) { + if (values[index] != null) + return false; + values[index] = data; + size++; + return true; + } + + boolean isFull() { + return full; + } + + public void setFull(boolean full) { + this.full = full; + } + + public Data remove(int index) { + Data value = values[index]; + values[index] = null; + if (value != null) + size--; + return value; + } + + public boolean readyToPoll() { + for (int i = removeIndex; i < BLOCK_SIZE; i++) { + if (values[i] != null) { + Data value = values[i]; + long age = System.currentTimeMillis() - value.createDate; + if (age > maxAge) { + values[i] = null; + size--; + } else { + return true; + } + } + } + return false; + } + + public Data remove() { + for (int i = removeIndex; i < BLOCK_SIZE; i++) { + if (values[i] != null) { + Data value = values[i]; + values[i] = null; + size--; + removeIndex = i; + return value; + } + } + return null; + } + + public int size() { + return size; + } + + @Override + public String toString() { + return "Block [" + blockId + "] full=" + isFull() + ", size=" + size() + ", " + address; + } + } + + public static class BlockUpdate implements DataSerializable { + int addBlockId = -1; + int removeBlockId = -1; + int fullBlockId = -1; + Address addAddress = null; + + public BlockUpdate(Address addAddress, int addBlockId, int fullBlockId, int removeBlockId) { + this.addAddress = addAddress; + this.addBlockId = addBlockId; + this.fullBlockId = fullBlockId; + this.removeBlockId = removeBlockId; + } + + public BlockUpdate() { + } + + public void readData(DataInput in) throws IOException { + addBlockId = in.readInt(); + removeBlockId = in.readInt(); + fullBlockId = in.readInt(); + if (addBlockId != -1) { + addAddress = new Address(); + addAddress.readData(in); + } + } + + public void writeData(DataOutput out) throws IOException { + out.writeInt(addBlockId); + out.writeInt(removeBlockId); + out.writeInt(fullBlockId); + if (addBlockId != -1) { + addAddress.writeData(out); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `q` last assigned on line 1111 could be null and is dereferenced at line 1112. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BlockingQueueManager.doAddTopicListener(BaseManager$Request) + +### Procedure Id: +com.hazelcast.impl.BlockingQueueManager.doAddTopicListener(com.hazelcast.impl.BaseManager$Request):v.9e2508c74c4cfe2fb2c3f2f18dbe8fa6 + +### File: +src/com/hazelcast/impl/BlockingQueueManager.java + +### Key: +BlockingQueueManager.java|doAddTopicListener|NULL_DEREFERENCE + +### Node Key: +510e2794ba6fd271f78b050b192e3038 + +### Hash: +30affe1e330f991e35ca18cb3af91547 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9612/instruction.md b/inferredbugs-9612/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..90a8344bdab50eb7effa668c7e23e77aa263bc24 --- /dev/null +++ b/inferredbugs-9612/instruction.md @@ -0,0 +1,358 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 36 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.manager.zk; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.io.ByteArrayInputStream; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.I0Itec.zkclient.exception.ZkMarshallingError; +import org.I0Itec.zkclient.serialize.ZkSerializer; +import org.apache.helix.HelixException; +import org.apache.helix.ZNRecord; +import org.apache.log4j.Logger; +import org.codehaus.jackson.JsonFactory; +import org.codehaus.jackson.JsonGenerator; +import org.codehaus.jackson.JsonParser; +import org.codehaus.jackson.JsonToken; +import org.restlet.engine.util.Base64; + + +public class ZNRecordStreamingSerializer implements ZkSerializer { + private static Logger LOG = Logger.getLogger(ZNRecordStreamingSerializer.class); + + private static int getListFieldBound(ZNRecord record) { + int max = Integer.MAX_VALUE; + if (record.getSimpleFields().containsKey(ZNRecord.LIST_FIELD_BOUND)) { + String maxStr = record.getSimpleField(ZNRecord.LIST_FIELD_BOUND); + try { + max = Integer.parseInt(maxStr); + } catch (Exception e) { + LOG.error("IllegalNumberFormat for list field bound: " + maxStr); + } + } + return max; + } + + @Override + public byte[] serialize(Object data) throws ZkMarshallingError { + if (!(data instanceof ZNRecord)) { + // null is NOT an instance of any class + LOG.error("Input object must be of type ZNRecord but it is " + data + + ". Will not write to zk"); + throw new HelixException("Input object is not of type ZNRecord (was " + data + ")"); + } + + // apply retention policy on list field + ZNRecord record = (ZNRecord) data; + int max = getListFieldBound(record); + if (max < Integer.MAX_VALUE) { + Map> listMap = record.getListFields(); + for (String key : listMap.keySet()) { + List list = listMap.get(key); + if (list.size() > max) { + listMap.put(key, list.subList(0, max)); + } + } + } + + StringWriter sw = new StringWriter(); + try { + JsonFactory f = new JsonFactory(); + JsonGenerator g = f.createJsonGenerator(sw); + + g.writeStartObject(); + + // write id field + g.writeRaw("\n "); + g.writeStringField("id", record.getId()); + + // write simepleFields + g.writeRaw("\n "); + g.writeObjectFieldStart("simpleFields"); + for (String key : record.getSimpleFields().keySet()) { + g.writeRaw("\n "); + g.writeStringField(key, record.getSimpleField(key)); + } + g.writeRaw("\n "); + g.writeEndObject(); // for simpleFields + + // write listFields + g.writeRaw("\n "); + g.writeObjectFieldStart("listFields"); + for (String key : record.getListFields().keySet()) { + // g.writeStringField(key, record.getListField(key).toString()); + + // g.writeObjectFieldStart(key); + g.writeRaw("\n "); + g.writeArrayFieldStart(key); + List list = record.getListField(key); + for (String listValue : list) { + g.writeString(listValue); + } + // g.writeEndObject(); + g.writeEndArray(); + + } + g.writeRaw("\n "); + g.writeEndObject(); // for listFields + + // write mapFields + g.writeRaw("\n "); + g.writeObjectFieldStart("mapFields"); + for (String key : record.getMapFields().keySet()) { + // g.writeStringField(key, record.getMapField(key).toString()); + g.writeRaw("\n "); + g.writeObjectFieldStart(key); + Map map = record.getMapField(key); + for (String mapKey : map.keySet()) { + g.writeRaw("\n "); + g.writeStringField(mapKey, map.get(mapKey)); + } + g.writeRaw("\n "); + g.writeEndObject(); + + } + g.writeRaw("\n "); + g.writeEndObject(); // for mapFields + + byte[] rawPayload = record.getRawPayload(); + if (rawPayload != null && rawPayload.length > 0) { + // write rawPayload + g.writeRaw("\n "); + g.writeStringField("rawPayload", Base64.encode(rawPayload, false)); + } + + g.writeRaw("\n"); + g.writeEndObject(); // for whole znrecord + + // important: will force flushing of output, close underlying output + // stream + g.close(); + } catch (Exception e) { + LOG.error("Exception during data serialization. Will not write to zk. Data (first 1k): " + + sw.toString().substring(0, 1024), e); + throw new HelixException(e); + } + + // check size + if (sw.toString().getBytes().length > ZNRecord.SIZE_LIMIT) { + LOG.error("Data size larger than 1M, ZNRecord.id: " + record.getId() + + ". Will not write to zk. Data (first 1k): " + sw.toString().substring(0, 1024)); + throw new HelixException("Data size larger than 1M, ZNRecord.id: " + record.getId()); + } + + return sw.toString().getBytes(); + } + + @Override + public Object deserialize(byte[] bytes) throws ZkMarshallingError { + if (bytes == null || bytes.length == 0) { + LOG.error("ZNode is empty."); + return null; + } + + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + ZNRecord record = null; + + try { + JsonFactory f = new JsonFactory(); + JsonParser jp = f.createJsonParser(bais); + + jp.nextToken(); // will return JsonToken.START_OBJECT (verify?) + while (jp.nextToken() != JsonToken.END_OBJECT) { + String fieldname = jp.getCurrentName(); + jp.nextToken(); // move to value, or START_OBJECT/START_ARRAY + if ("id".equals(fieldname)) { + // contains an object + record = new ZNRecord(jp.getText()); + } else if ("simpleFields".equals(fieldname)) { + while (jp.nextToken() != JsonToken.END_OBJECT) { + String key = jp.getCurrentName(); + jp.nextToken(); // move to value + record.setSimpleField(key, jp.getText()); + } + } else if ("mapFields".equals(fieldname)) { + // user.setVerified(jp.getCurrentToken() == JsonToken.VALUE_TRUE); + while (jp.nextToken() != JsonToken.END_OBJECT) { + String key = jp.getCurrentName(); + record.setMapField(key, new TreeMap()); + jp.nextToken(); // move to value + + while (jp.nextToken() != JsonToken.END_OBJECT) { + String mapKey = jp.getCurrentName(); + jp.nextToken(); // move to value + record.getMapField(key).put(mapKey, jp.getText()); + } + } + + } else if ("listFields".equals(fieldname)) { + // user.setUserImage(jp.getBinaryValue()); + while (jp.nextToken() != JsonToken.END_OBJECT) { + String key = jp.getCurrentName(); + record.setListField(key, new ArrayList()); + jp.nextToken(); // move to value + while (jp.nextToken() != JsonToken.END_ARRAY) { + record.getListField(key).add(jp.getText()); + } + + } + + } else if ("rawPayload".equals(fieldname)) { + record.setRawPayload(Base64.decode(jp.getText())); + } else { + throw new IllegalStateException("Unrecognized field '" + fieldname + "'!"); + } + } + jp.close(); // ensure resources get cleaned up timely and properly + } catch (Exception e) { + LOG.error("Exception during deserialization of bytes: " + new String(bytes), e); + } + + return record; + } + + public static void main(String[] args) { + ZNRecord record = new ZNRecord("record"); + final int recordSize = 10; + for (int i = 0; i < recordSize; i++) { + record.setSimpleField("" + i, "" + i); + record.setListField("" + i, new ArrayList()); + for (int j = 0; j < recordSize; j++) { + record.getListField("" + i).add("" + j); + } + + record.setMapField("" + i, new TreeMap()); + for (int j = 0; j < recordSize; j++) { + record.getMapField("" + i).put("" + j, "" + j); + } + } + + ZNRecordStreamingSerializer serializer = new ZNRecordStreamingSerializer(); + byte[] bytes = serializer.serialize(record); + System.out.println(new String(bytes)); + ZNRecord record2 = (ZNRecord) serializer.deserialize(bytes); + System.out.println(record2); + + long start = System.currentTimeMillis(); + for (int i = 0; i < 100; i++) { + bytes = serializer.serialize(record); + // System.out.println(new String(bytes)); + record2 = (ZNRecord) serializer.deserialize(bytes); + // System.out.println(record2); + } + long end = System.currentTimeMillis(); + System.out.println("ZNRecordStreamingSerializer time used: " + (end - start)); + + ZNRecordSerializer serializer2 = new ZNRecordSerializer(); + bytes = serializer2.serialize(record); + // System.out.println(new String(bytes)); + record2 = (ZNRecord) serializer2.deserialize(bytes); + // System.out.println(record2); + + start = System.currentTimeMillis(); + for (int i = 0; i < 100; i++) { + bytes = serializer2.serialize(record); + // System.out.println(new String(bytes)); + record2 = (ZNRecord) serializer2.deserialize(bytes); + // System.out.println(record2); + } + end = System.currentTimeMillis(); + System.out.println("ZNRecordSerializer time used: " + (end - start)); + + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `record` last assigned on line 176 could be null and is dereferenced at line 213. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object ZNRecordStreamingSerializer.deserialize(byte[]) + +### Procedure Id: +org.apache.helix.manager.zk.ZNRecordStreamingSerializer.deserialize(byte[]):java.lang.Object.cdedc9809357a72edb66d8f57e43b2da + +### File: +helix-core/src/main/java/org/apache/helix/manager/zk/ZNRecordStreamingSerializer.java + +### Key: +ZNRecordStreamingSerializer.java|deserialize|NULL_DEREFERENCE + +### Node Key: +477eb785f049cce5d0732232a55a5cf0 + +### Hash: +56aacf463a17e67f4af9b283f3a4c931 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9615/instruction.md b/inferredbugs-9615/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..78e3e633b8d9dadbac756346c7f4440208aa4bc5 --- /dev/null +++ b/inferredbugs-9615/instruction.md @@ -0,0 +1,366 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 62 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.manager.zk; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.lang.management.ManagementFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import javax.management.MBeanServer; +import javax.management.ObjectName; + +import org.I0Itec.zkclient.IZkDataListener; +import org.I0Itec.zkclient.IZkStateListener; +import org.I0Itec.zkclient.ZkConnection; +import org.apache.helix.HelixException; +import org.apache.helix.ZNRecord; +import org.apache.helix.ZkUnitTestBase; +import org.apache.helix.monitoring.mbeans.MBeanRegistrar; +import org.apache.helix.monitoring.mbeans.MonitorDomainNames; +import org.apache.helix.monitoring.mbeans.ZkClientMonitor; +import org.apache.helix.monitoring.mbeans.ZkClientPathMonitor; +import org.apache.log4j.Logger; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.Watcher.Event.KeeperState; +import org.apache.zookeeper.ZooKeeper; +import org.apache.zookeeper.data.Stat; +import org.testng.Assert; +import org.testng.AssertJUnit; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class TestZkClient extends ZkUnitTestBase { + private static Logger LOG = Logger.getLogger(TestZkClient.class); + + ZkClient _zkClient; + + @BeforeClass + public void beforeClass() { + _zkClient = new ZkClient(ZK_ADDR); + _zkClient.setZkSerializer(new ZNRecordSerializer()); + } + + @AfterClass + public void afterClass() { + _zkClient.close(); + } + + @Test() + void testGetStat() { + String path = "/tmp/getStatTest"; + _zkClient.deleteRecursive(path); + + Stat stat, newStat; + stat = _zkClient.getStat(path); + AssertJUnit.assertNull(stat); + _zkClient.createPersistent(path, true); + + stat = _zkClient.getStat(path); + AssertJUnit.assertNotNull(stat); + + newStat = _zkClient.getStat(path); + AssertJUnit.assertEquals(stat, newStat); + + _zkClient.writeData(path, new ZNRecord("Test")); + newStat = _zkClient.getStat(path); + AssertJUnit.assertNotSame(stat, newStat); + } + + @Test() + void testSessionExpire() throws Exception { + IZkStateListener listener = new IZkStateListener() { + + @Override + public void handleStateChanged(KeeperState state) throws Exception { + System.out.println("In Old connection New state " + state); + } + + @Override + public void handleNewSession() throws Exception { + System.out.println("In Old connection New session"); + } + + @Override + public void handleSessionEstablishmentError(Throwable var1) throws Exception { + } + }; + + _zkClient.subscribeStateChanges(listener); + ZkConnection connection = ((ZkConnection) _zkClient.getConnection()); + ZooKeeper zookeeper = connection.getZookeeper(); + System.out.println("old sessionId= " + zookeeper.getSessionId()); + Watcher watcher = new Watcher() { + @Override + public void process(WatchedEvent event) { + System.out.println("In New connection In process event:" + event); + } + }; + ZooKeeper newZookeeper = + new ZooKeeper(connection.getServers(), zookeeper.getSessionTimeout(), watcher, + zookeeper.getSessionId(), zookeeper.getSessionPasswd()); + Thread.sleep(3000); + System.out.println("New sessionId= " + newZookeeper.getSessionId()); + Thread.sleep(3000); + newZookeeper.close(); + Thread.sleep(10000); + connection = ((ZkConnection) _zkClient.getConnection()); + zookeeper = connection.getZookeeper(); + System.out.println("After session expiry sessionId= " + zookeeper.getSessionId()); + } + + @Test(expectedExceptions = HelixException.class, expectedExceptionsMessageRegExp = "Data size larger than 1M.*") + void testDataSizeLimit() { + ZNRecord data = new ZNRecord(new String(new char[1024 * 1024])); + _zkClient.writeData("/test", data, -1); + } + + @Test + public void testZkClientMonitor() throws Exception { + final String TEST_TAG = "test_monitor"; + final String TEST_KEY = "test_key"; + final String TEST_DATA = "testData"; + final String TEST_ROOT = "/my_cluster/IDEALSTATES"; + final String TEST_NODE = "/test_zkclient_monitor"; + final String TEST_PATH = TEST_ROOT + TEST_NODE; + + ZkClient zkClient = new ZkClient(ZK_ADDR, TEST_TAG, TEST_KEY); + + final long TEST_DATA_SIZE = zkClient.serialize(TEST_DATA, TEST_PATH).length; + + if (_zkClient.exists(TEST_PATH)) { + _zkClient.delete(TEST_PATH); + } + if (!_zkClient.exists(TEST_ROOT)) { + _zkClient.createPersistent(TEST_ROOT, true); + } + + MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); + + ObjectName name = MBeanRegistrar + .buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE, + TEST_TAG, ZkClientMonitor.MONITOR_KEY, TEST_KEY); + ObjectName rootname = MBeanRegistrar + .buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE, + TEST_TAG, ZkClientMonitor.MONITOR_KEY, TEST_KEY, ZkClientPathMonitor.MONITOR_PATH, + "Root"); + ObjectName idealStatename = MBeanRegistrar + .buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE, + TEST_TAG, ZkClientMonitor.MONITOR_KEY, TEST_KEY, ZkClientPathMonitor.MONITOR_PATH, + "IdealStates"); + Assert.assertTrue(beanServer.isRegistered(rootname)); + Assert.assertTrue(beanServer.isRegistered(idealStatename)); + + // Test exists + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadMaxLatencyGauge"), 0); + zkClient.exists(TEST_ROOT); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 1); + Assert.assertTrue((long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter") >= 0); + Assert.assertTrue((long) beanServer.getAttribute(rootname, "ReadMaxLatencyGauge") >= 0); + + // Test create + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteBytesCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteBytesCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteTotalLatencyCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteMaxLatencyGauge"), 0); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteTotalLatencyCounter"), + 0); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteMaxLatencyGauge"), 0); + zkClient.create(TEST_PATH, TEST_DATA, CreateMode.PERSISTENT); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteCounter"), 1); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteBytesCounter"), + TEST_DATA_SIZE); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteCounter"), 1); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteBytesCounter"), + TEST_DATA_SIZE); + long origWriteTotalLatencyCounter = + (long) beanServer.getAttribute(rootname, "WriteTotalLatencyCounter"); + Assert.assertTrue(origWriteTotalLatencyCounter >= 0); + Assert.assertTrue((long) beanServer.getAttribute(rootname, "WriteMaxLatencyGauge") >= 0); + long origIdealStatesWriteTotalLatencyCounter = + (long) beanServer.getAttribute(idealStatename, "WriteTotalLatencyCounter"); + Assert.assertTrue(origIdealStatesWriteTotalLatencyCounter >= 0); + Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "WriteMaxLatencyGauge") >= 0); + + // Test read + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 1); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), 0); + long origReadTotalLatencyCounter = + (long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter"); + long origIdealStatesReadTotalLatencyCounter = + (long) beanServer.getAttribute(idealStatename, "ReadTotalLatencyCounter"); + Assert.assertEquals(origIdealStatesReadTotalLatencyCounter, 0); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadMaxLatencyGauge"), 0); + zkClient.readData(TEST_PATH, new Stat()); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 2); + Assert + .assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), TEST_DATA_SIZE); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 1); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), + TEST_DATA_SIZE); + Assert.assertTrue((long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter") + >= origReadTotalLatencyCounter); + Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "ReadTotalLatencyCounter") + >= origIdealStatesReadTotalLatencyCounter); + Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "ReadMaxLatencyGauge") >= 0); + zkClient.getChildren(TEST_PATH); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 3); + Assert + .assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), TEST_DATA_SIZE); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 2); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), + TEST_DATA_SIZE); + zkClient.getStat(TEST_PATH); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 4); + Assert + .assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), TEST_DATA_SIZE); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 3); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), + TEST_DATA_SIZE); + zkClient.readDataAndStat(TEST_PATH, new Stat(), true); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 5); + + ZkAsyncCallbacks.ExistsCallbackHandler callbackHandler = + new ZkAsyncCallbacks.ExistsCallbackHandler(); + zkClient.asyncExists(TEST_PATH, callbackHandler); + callbackHandler.waitForSuccess(); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 6); + + // Test write + zkClient.writeData(TEST_PATH, TEST_DATA); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteCounter"), 2); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteBytesCounter"), + TEST_DATA_SIZE * 2); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteCounter"), 2); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteBytesCounter"), + TEST_DATA_SIZE * 2); + Assert.assertTrue((long) beanServer.getAttribute(rootname, "WriteTotalLatencyCounter") + >= origWriteTotalLatencyCounter); + Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "WriteTotalLatencyCounter") + >= origIdealStatesWriteTotalLatencyCounter); + + // Test data change count + final Lock lock = new ReentrantLock(); + final Condition callbackFinish = lock.newCondition(); + zkClient.subscribeDataChanges(TEST_PATH, new IZkDataListener() { + @Override + public void handleDataChange(String dataPath, Object data) throws Exception { + } + + @Override + public void handleDataDeleted(String dataPath) throws Exception { + lock.lock(); + try { + callbackFinish.signal(); + } finally { + lock.unlock(); + } + } + }); + lock.lock(); + _zkClient.delete(TEST_PATH); + Assert.assertTrue(callbackFinish.await(10, TimeUnit.SECONDS)); + Assert.assertEquals((long) beanServer.getAttribute(name, "DataChangeEventCounter"), 1); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.apache.helix.manager.zk.TestZkClient.testZkClientMonitor` indirectly writes to field `zkClientPathMonitor.org.apache.helix.monitoring.mbeans.ZkClientPathMonitor._lastResetTime` outside of synchronization. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestZkClient.testZkClientMonitor() + +### Procedure Id: +org.apache.helix.manager.zk.TestZkClient.testZkClientMonitor():void.b03bc7d2192d1e78c498ad16ec5c64a7 + +### File: +helix-core/src/test/java/org/apache/helix/manager/zk/TestZkClient.java + +### Key: +TestZkClient.java|testZkClientMonitor|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +f032fa0b4250cc35eecf292a4eb0c7a9 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9623/instruction.md b/inferredbugs-9623/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0defa7cc7f2c4d3384b2294be72a5cef484b522a --- /dev/null +++ b/inferredbugs-9623/instruction.md @@ -0,0 +1,366 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 63 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.manager.zk; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.lang.management.ManagementFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import javax.management.MBeanServer; +import javax.management.ObjectName; + +import org.I0Itec.zkclient.IZkDataListener; +import org.I0Itec.zkclient.IZkStateListener; +import org.I0Itec.zkclient.ZkConnection; +import org.apache.helix.HelixException; +import org.apache.helix.ZNRecord; +import org.apache.helix.ZkUnitTestBase; +import org.apache.helix.monitoring.mbeans.MBeanRegistrar; +import org.apache.helix.monitoring.mbeans.MonitorDomainNames; +import org.apache.helix.monitoring.mbeans.ZkClientMonitor; +import org.apache.helix.monitoring.mbeans.ZkClientPathMonitor; +import org.apache.log4j.Logger; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.Watcher.Event.KeeperState; +import org.apache.zookeeper.ZooKeeper; +import org.apache.zookeeper.data.Stat; +import org.testng.Assert; +import org.testng.AssertJUnit; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class TestZkClient extends ZkUnitTestBase { + private static Logger LOG = Logger.getLogger(TestZkClient.class); + + ZkClient _zkClient; + + @BeforeClass + public void beforeClass() { + _zkClient = new ZkClient(ZK_ADDR); + _zkClient.setZkSerializer(new ZNRecordSerializer()); + } + + @AfterClass + public void afterClass() { + _zkClient.close(); + } + + @Test() + void testGetStat() { + String path = "/tmp/getStatTest"; + _zkClient.deleteRecursive(path); + + Stat stat, newStat; + stat = _zkClient.getStat(path); + AssertJUnit.assertNull(stat); + _zkClient.createPersistent(path, true); + + stat = _zkClient.getStat(path); + AssertJUnit.assertNotNull(stat); + + newStat = _zkClient.getStat(path); + AssertJUnit.assertEquals(stat, newStat); + + _zkClient.writeData(path, new ZNRecord("Test")); + newStat = _zkClient.getStat(path); + AssertJUnit.assertNotSame(stat, newStat); + } + + @Test() + void testSessionExpire() throws Exception { + IZkStateListener listener = new IZkStateListener() { + + @Override + public void handleStateChanged(KeeperState state) throws Exception { + System.out.println("In Old connection New state " + state); + } + + @Override + public void handleNewSession() throws Exception { + System.out.println("In Old connection New session"); + } + + @Override + public void handleSessionEstablishmentError(Throwable var1) throws Exception { + } + }; + + _zkClient.subscribeStateChanges(listener); + ZkConnection connection = ((ZkConnection) _zkClient.getConnection()); + ZooKeeper zookeeper = connection.getZookeeper(); + System.out.println("old sessionId= " + zookeeper.getSessionId()); + Watcher watcher = new Watcher() { + @Override + public void process(WatchedEvent event) { + System.out.println("In New connection In process event:" + event); + } + }; + ZooKeeper newZookeeper = + new ZooKeeper(connection.getServers(), zookeeper.getSessionTimeout(), watcher, + zookeeper.getSessionId(), zookeeper.getSessionPasswd()); + Thread.sleep(3000); + System.out.println("New sessionId= " + newZookeeper.getSessionId()); + Thread.sleep(3000); + newZookeeper.close(); + Thread.sleep(10000); + connection = ((ZkConnection) _zkClient.getConnection()); + zookeeper = connection.getZookeeper(); + System.out.println("After session expiry sessionId= " + zookeeper.getSessionId()); + } + + @Test(expectedExceptions = HelixException.class, expectedExceptionsMessageRegExp = "Data size larger than 1M.*") + void testDataSizeLimit() { + ZNRecord data = new ZNRecord(new String(new char[1024 * 1024])); + _zkClient.writeData("/test", data, -1); + } + + @Test + public void testZkClientMonitor() throws Exception { + final String TEST_TAG = "test_monitor"; + final String TEST_KEY = "test_key"; + final String TEST_DATA = "testData"; + final String TEST_ROOT = "/my_cluster/IDEALSTATES"; + final String TEST_NODE = "/test_zkclient_monitor"; + final String TEST_PATH = TEST_ROOT + TEST_NODE; + + ZkClient zkClient = new ZkClient(ZK_ADDR, TEST_TAG, TEST_KEY); + + final long TEST_DATA_SIZE = zkClient.serialize(TEST_DATA, TEST_PATH).length; + + if (_zkClient.exists(TEST_PATH)) { + _zkClient.delete(TEST_PATH); + } + if (!_zkClient.exists(TEST_ROOT)) { + _zkClient.createPersistent(TEST_ROOT, true); + } + + MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); + + ObjectName name = MBeanRegistrar + .buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE, + TEST_TAG, ZkClientMonitor.MONITOR_KEY, TEST_KEY); + ObjectName rootname = MBeanRegistrar + .buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE, + TEST_TAG, ZkClientMonitor.MONITOR_KEY, TEST_KEY, ZkClientPathMonitor.MONITOR_PATH, + "Root"); + ObjectName idealStatename = MBeanRegistrar + .buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE, + TEST_TAG, ZkClientMonitor.MONITOR_KEY, TEST_KEY, ZkClientPathMonitor.MONITOR_PATH, + "IdealStates"); + Assert.assertTrue(beanServer.isRegistered(rootname)); + Assert.assertTrue(beanServer.isRegistered(idealStatename)); + + // Test exists + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadMaxLatencyGauge"), 0); + zkClient.exists(TEST_ROOT); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 1); + Assert.assertTrue((long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter") >= 0); + Assert.assertTrue((long) beanServer.getAttribute(rootname, "ReadMaxLatencyGauge") >= 0); + + // Test create + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteBytesCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteBytesCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteTotalLatencyCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteMaxLatencyGauge"), 0); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteTotalLatencyCounter"), + 0); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteMaxLatencyGauge"), 0); + zkClient.create(TEST_PATH, TEST_DATA, CreateMode.PERSISTENT); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteCounter"), 1); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteBytesCounter"), + TEST_DATA_SIZE); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteCounter"), 1); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteBytesCounter"), + TEST_DATA_SIZE); + long origWriteTotalLatencyCounter = + (long) beanServer.getAttribute(rootname, "WriteTotalLatencyCounter"); + Assert.assertTrue(origWriteTotalLatencyCounter >= 0); + Assert.assertTrue((long) beanServer.getAttribute(rootname, "WriteMaxLatencyGauge") >= 0); + long origIdealStatesWriteTotalLatencyCounter = + (long) beanServer.getAttribute(idealStatename, "WriteTotalLatencyCounter"); + Assert.assertTrue(origIdealStatesWriteTotalLatencyCounter >= 0); + Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "WriteMaxLatencyGauge") >= 0); + + // Test read + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 1); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 0); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), 0); + long origReadTotalLatencyCounter = + (long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter"); + long origIdealStatesReadTotalLatencyCounter = + (long) beanServer.getAttribute(idealStatename, "ReadTotalLatencyCounter"); + Assert.assertEquals(origIdealStatesReadTotalLatencyCounter, 0); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadMaxLatencyGauge"), 0); + zkClient.readData(TEST_PATH, new Stat()); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 2); + Assert + .assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), TEST_DATA_SIZE); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 1); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), + TEST_DATA_SIZE); + Assert.assertTrue((long) beanServer.getAttribute(rootname, "ReadTotalLatencyCounter") + >= origReadTotalLatencyCounter); + Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "ReadTotalLatencyCounter") + >= origIdealStatesReadTotalLatencyCounter); + Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "ReadMaxLatencyGauge") >= 0); + zkClient.getChildren(TEST_PATH); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 3); + Assert + .assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), TEST_DATA_SIZE); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 2); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), + TEST_DATA_SIZE); + zkClient.getStat(TEST_PATH); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 4); + Assert + .assertEquals((long) beanServer.getAttribute(rootname, "ReadBytesCounter"), TEST_DATA_SIZE); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadCounter"), 3); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "ReadBytesCounter"), + TEST_DATA_SIZE); + zkClient.readDataAndStat(TEST_PATH, new Stat(), true); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 5); + + ZkAsyncCallbacks.ExistsCallbackHandler callbackHandler = + new ZkAsyncCallbacks.ExistsCallbackHandler(); + zkClient.asyncExists(TEST_PATH, callbackHandler); + callbackHandler.waitForSuccess(); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "ReadCounter"), 6); + + // Test write + zkClient.writeData(TEST_PATH, TEST_DATA); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteCounter"), 2); + Assert.assertEquals((long) beanServer.getAttribute(rootname, "WriteBytesCounter"), + TEST_DATA_SIZE * 2); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteCounter"), 2); + Assert.assertEquals((long) beanServer.getAttribute(idealStatename, "WriteBytesCounter"), + TEST_DATA_SIZE * 2); + Assert.assertTrue((long) beanServer.getAttribute(rootname, "WriteTotalLatencyCounter") + >= origWriteTotalLatencyCounter); + Assert.assertTrue((long) beanServer.getAttribute(idealStatename, "WriteTotalLatencyCounter") + >= origIdealStatesWriteTotalLatencyCounter); + + // Test data change count + final Lock lock = new ReentrantLock(); + final Condition callbackFinish = lock.newCondition(); + zkClient.subscribeDataChanges(TEST_PATH, new IZkDataListener() { + @Override + public void handleDataChange(String dataPath, Object data) throws Exception { + } + + @Override + public void handleDataDeleted(String dataPath) throws Exception { + lock.lock(); + try { + callbackFinish.signal(); + } finally { + lock.unlock(); + } + } + }); + lock.lock(); + _zkClient.delete(TEST_PATH); + Assert.assertTrue(callbackFinish.await(10, TimeUnit.SECONDS)); + Assert.assertEquals((long) beanServer.getAttribute(name, "DataChangeEventCounter"), 1); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.helix.manager.zk.TestZkClient.testZkClientMonitor` indirectly reads with synchronization from `zkClientPathMonitor.org.apache.helix.monitoring.mbeans.ZkClientPathMonitor._lastResetTime`. Potentially races with unsynchronized write in method `TestZkClient.testZkClientMonitor()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestZkClient.testZkClientMonitor() + +### Procedure Id: +org.apache.helix.manager.zk.TestZkClient.testZkClientMonitor():void.b03bc7d2192d1e78c498ad16ec5c64a7 + +### File: +helix-core/src/test/java/org/apache/helix/manager/zk/TestZkClient.java + +### Key: +TestZkClient.java|testZkClientMonitor|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +596f1d7c04abb9cf907104918e905876 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9624/instruction.md b/inferredbugs-9624/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..356f46abcd2835f0f4ebda119b0571dbc5047a97 --- /dev/null +++ b/inferredbugs-9624/instruction.md @@ -0,0 +1,376 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 64 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.controller.stages; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import org.apache.helix.*; +import org.apache.helix.PropertyKey.Builder; +import org.apache.helix.ZNRecordDelta.MergeOperation; +import org.apache.helix.controller.LogUtil; +import org.apache.helix.controller.pipeline.AbstractAsyncBaseStage; +import org.apache.helix.controller.pipeline.AsyncWorkerType; +import org.apache.helix.controller.pipeline.StageException; +import org.apache.helix.manager.zk.DefaultSchedulerMessageHandlerFactory; +import org.apache.helix.model.*; +import org.apache.helix.model.Message.MessageType; +import org.apache.helix.monitoring.mbeans.ClusterStatusMonitor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.*; + +public class ExternalViewComputeStage extends AbstractAsyncBaseStage { + private static Logger LOG = LoggerFactory.getLogger(ExternalViewComputeStage.class); + + @Override + public AsyncWorkerType getAsyncWorkerType() { + return AsyncWorkerType.ExternalViewComputeWorker; + } + + @Override + public void execute(final ClusterEvent event) throws Exception { + _eventId = event.getEventId(); + HelixManager manager = event.getAttribute(AttributeName.helixmanager.name()); + Map resourceMap = event.getAttribute(AttributeName.RESOURCES.name()); + ClusterDataCache cache = event.getAttribute(AttributeName.ClusterDataCache.name()); + + if (manager == null || resourceMap == null || cache == null) { + throw new StageException("Missing attributes in event:" + event + + ". Requires ClusterManager|RESOURCES|DataCache"); + } + + HelixDataAccessor dataAccessor = manager.getHelixDataAccessor(); + PropertyKey.Builder keyBuilder = dataAccessor.keyBuilder(); + + CurrentStateOutput currentStateOutput = + event.getAttribute(AttributeName.CURRENT_STATE.name()); + + List newExtViews = new ArrayList<>(); + + Map curExtViews = cache.getExternalViews(); + + for (String resourceName : resourceMap.keySet()) { + ExternalView view = new ExternalView(resourceName); + // view.setBucketSize(currentStateOutput.getBucketSize(resourceName)); + // if resource ideal state has bucket size, set it + // otherwise resource has been dropped, use bucket size from current state instead + Resource resource = resourceMap.get(resourceName); + if (resource.getBucketSize() > 0) { + view.setBucketSize(resource.getBucketSize()); + } else { + view.setBucketSize(currentStateOutput.getBucketSize(resourceName)); + } + + int totalPendingMessageCount = 0; + + for (Partition partition : resource.getPartitions()) { + Map currentStateMap = + currentStateOutput.getCurrentStateMap(resourceName, partition); + if (currentStateMap != null && currentStateMap.size() > 0) { + // Set disabledInstances + // = cache.getDisabledInstancesForResource(resource.toString()); + for (String instance : currentStateMap.keySet()) { + // if (!disabledInstances.contains(instance)) + // { + view.setState(partition.getPartitionName(), instance, currentStateMap.get(instance)); + // } + } + } + totalPendingMessageCount += + currentStateOutput.getPendingMessageMap(resource.getResourceName(), partition).size(); + } + + // Update cluster status monitor mbean + IdealState idealState = cache.getIdealState(resourceName); + if (!cache.isTaskCache()) { + ResourceConfig resourceConfig = cache.getResourceConfig(resourceName); + ClusterStatusMonitor clusterStatusMonitor = + event.getAttribute(AttributeName.clusterStatusMonitor.name()); + if (clusterStatusMonitor != null) { + if (idealState != null && (resourceConfig == null || !resourceConfig + .isMonitoringDisabled())) { + if (!idealState.getStateModelDefRef() + .equalsIgnoreCase(DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE)) { + StateModelDefinition stateModelDef = + cache.getStateModelDef(idealState.getStateModelDefRef()); + clusterStatusMonitor + .setResourceStatus(view, cache.getIdealState(view.getResourceName()), + stateModelDef); + clusterStatusMonitor + .updatePendingMessages(resource.getResourceName(), totalPendingMessageCount); + } + } else { + // Drop the metrics if the resource is dropped, or the MonitorDisabled is changed to true. + clusterStatusMonitor.unregisterResource(view.getResourceName()); + } + } + } + ExternalView curExtView = curExtViews.get(resourceName); + // copy simplefields from IS, in cases where IS is deleted copy it from existing ExternalView + if (idealState != null) { + view.getRecord().getSimpleFields().putAll(idealState.getRecord().getSimpleFields()); + } else if (curExtView != null) { + view.getRecord().getSimpleFields().putAll(curExtView.getRecord().getSimpleFields()); + } + + // compare the new external view with current one, set only on different + if (curExtView == null || !curExtView.getRecord().equals(view.getRecord())) { + // Add external view to the list which will be written to ZK later. + newExtViews.add(view); + + // For SCHEDULER_TASK_RESOURCE resource group (helix task queue), we need to find out which + // task partitions are finished (COMPLETED or ERROR), update the status update of the original + // scheduler message, and then remove the partitions from the ideal state + if (idealState != null + && idealState.getStateModelDefRef().equalsIgnoreCase( + DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE)) { + updateScheduledTaskStatus(view, manager, idealState); + } + } + } + + List externalviewsToRemove = new ArrayList<>(); + // TODO: consider not setting the externalview of SCHEDULER_TASK_QUEUE at all. + // Are there any entity that will be interested in its change? + + // For the resource with DisableExternalView option turned on in IdealState + // We will not actually create or write the externalView to ZooKeeper. + List keys = new ArrayList<>(); + for(Iterator it = newExtViews.iterator(); it.hasNext(); ) { + ExternalView view = it.next(); + String resourceName = view.getResourceName(); + IdealState idealState = cache.getIdealState(resourceName); + if (idealState != null && idealState.isExternalViewDisabled()) { + it.remove(); + // remove the external view if the external view exists + if (curExtViews.containsKey(resourceName)) { + LogUtil + .logInfo(LOG, _eventId, "Remove externalView for resource: " + resourceName); + dataAccessor.removeProperty(keyBuilder.externalView(resourceName)); + externalviewsToRemove.add(resourceName); + } + } else { + keys.add(keyBuilder.externalView(resourceName)); + } + } + + // add/update external-views + if (newExtViews.size() > 0) { + dataAccessor.setChildren(keys, newExtViews); + cache.updateExternalViews(newExtViews); + } + + // remove dead external-views + for (String resourceName : curExtViews.keySet()) { + if (!resourceMap.keySet().contains(resourceName)) { + LogUtil.logInfo(LOG, _eventId, "Remove externalView for resource: " + resourceName); + dataAccessor.removeProperty(keyBuilder.externalView(resourceName)); + externalviewsToRemove.add(resourceName); + } + } + cache.removeExternalViews(externalviewsToRemove); + } + + private void updateScheduledTaskStatus(ExternalView ev, HelixManager manager, + IdealState taskQueueIdealState) { + HelixDataAccessor accessor = manager.getHelixDataAccessor(); + ZNRecord finishedTasks = new ZNRecord(ev.getResourceName()); + + // Place holder for finished partitions + Map emptyMap = new HashMap(); + List emptyList = new LinkedList(); + + Map controllerMsgIdCountMap = new HashMap(); + Map> controllerMsgUpdates = + new HashMap>(); + + Builder keyBuilder = accessor.keyBuilder(); + + for (String taskPartitionName : ev.getPartitionSet()) { + for (String taskState : ev.getStateMap(taskPartitionName).values()) { + if (taskState.equalsIgnoreCase(HelixDefinedState.ERROR.toString()) || taskState + .equalsIgnoreCase("COMPLETED")) { + LogUtil.logInfo(LOG, _eventId, taskPartitionName + " finished as " + taskState); + finishedTasks.getListFields().put(taskPartitionName, emptyList); + finishedTasks.getMapFields().put(taskPartitionName, emptyMap); + + // Update original scheduler message status update + if (taskQueueIdealState.getRecord().getMapField(taskPartitionName) != null) { + String controllerMsgId = taskQueueIdealState.getRecord().getMapField(taskPartitionName) + .get(DefaultSchedulerMessageHandlerFactory.CONTROLLER_MSG_ID); + if (controllerMsgId != null) { + LogUtil.logInfo(LOG, _eventId, + taskPartitionName + " finished with controllerMsg " + controllerMsgId); + if (!controllerMsgUpdates.containsKey(controllerMsgId)) { + controllerMsgUpdates.put(controllerMsgId, new HashMap()); + } + controllerMsgUpdates.get(controllerMsgId).put(taskPartitionName, taskState); + } + } + } + } + } + // fill the controllerMsgIdCountMap + for (String taskId : taskQueueIdealState.getPartitionSet()) { + String controllerMsgId = + taskQueueIdealState.getRecord().getMapField(taskId) + .get(DefaultSchedulerMessageHandlerFactory.CONTROLLER_MSG_ID); + if (controllerMsgId != null) { + if (!controllerMsgIdCountMap.containsKey(controllerMsgId)) { + controllerMsgIdCountMap.put(controllerMsgId, 0); + } + controllerMsgIdCountMap.put(controllerMsgId, + (controllerMsgIdCountMap.get(controllerMsgId) + 1)); + } + } + + if (controllerMsgUpdates.size() > 0) { + for (String controllerMsgId : controllerMsgUpdates.keySet()) { + PropertyKey controllerStatusUpdateKey = + keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), controllerMsgId); + StatusUpdate controllerStatusUpdate = accessor.getProperty(controllerStatusUpdateKey); + for (String taskPartitionName : controllerMsgUpdates.get(controllerMsgId).keySet()) { + Map result = new HashMap(); + result.put("Result", controllerMsgUpdates.get(controllerMsgId).get(taskPartitionName)); + controllerStatusUpdate.getRecord().setMapField( + "MessageResult " + + taskQueueIdealState.getRecord().getMapField(taskPartitionName) + .get(Message.Attributes.TGT_NAME.toString()) + + " " + + taskPartitionName + + " " + + taskQueueIdealState.getRecord().getMapField(taskPartitionName) + .get(Message.Attributes.MSG_ID.toString()), result); + } + // All done for the scheduled tasks that came from controllerMsgId, add summary for it + Integer controllerMsgIdCount = controllerMsgIdCountMap.get(controllerMsgId); + if (controllerMsgIdCount != null + && controllerMsgUpdates.get(controllerMsgId).size() == controllerMsgIdCount.intValue()) { + int finishedTasksNum = 0; + int completedTasksNum = 0; + for (String key : controllerStatusUpdate.getRecord().getMapFields().keySet()) { + if (key.startsWith("MessageResult ")) { + finishedTasksNum++; + } + if (controllerStatusUpdate.getRecord().getMapField(key).get("Result") != null) { + if (controllerStatusUpdate.getRecord().getMapField(key).get("Result") + .equalsIgnoreCase("COMPLETED")) { + completedTasksNum++; + } + } + } + Map summary = new TreeMap(); + summary.put("TotalMessages:", "" + finishedTasksNum); + summary.put("CompletedMessages", "" + completedTasksNum); + + controllerStatusUpdate.getRecord().setMapField("Summary", summary); + } + // Update the statusUpdate of controllerMsgId + accessor.updateProperty(controllerStatusUpdateKey, controllerStatusUpdate); + } + } + + if (finishedTasks.getListFields().size() > 0) { + ZNRecordDelta znDelta = new ZNRecordDelta(finishedTasks, MergeOperation.SUBTRACT); + List deltaList = new LinkedList(); + deltaList.add(znDelta); + IdealState delta = new IdealState(taskQueueIdealState.getResourceName()); + delta.setDeltaList(deltaList); + + // Remove the finished (COMPLETED or ERROR) tasks from the SCHEDULER_TASK_RESOURCE idealstate + keyBuilder = accessor.keyBuilder(); + accessor.updateProperty(keyBuilder.idealStates(taskQueueIdealState.getResourceName()), delta); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `currentStateOutput` last assigned on line 62 could be null and is dereferenced at line 77. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExternalViewComputeStage.execute(ClusterEvent) + +### Procedure Id: +org.apache.helix.controller.stages.ExternalViewComputeStage.execute(org.apache.helix.controller.stag.3b7620876e414c1dcc1327121b592176 + +### File: +helix-core/src/main/java/org/apache/helix/controller/stages/ExternalViewComputeStage.java + +### Key: +ExternalViewComputeStage.java|execute|NULL_DEREFERENCE + +### Node Key: +d2a1f5a2f88904bf44b9c7c6c658180d + +### Hash: +45e7680d33c08184bb268da5adff3977 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9640/instruction.md b/inferredbugs-9640/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f65d78c54b444fc114e0ba6d73e97a68ab959cb6 --- /dev/null +++ b/inferredbugs-9640/instruction.md @@ -0,0 +1,423 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 85 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.rest.server; + + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.helix.BaseDataAccessor; +import org.apache.helix.ConfigAccessor; +import org.apache.helix.HelixAdmin; +import org.apache.helix.HelixDataAccessor; +import org.apache.helix.HelixException; +import org.apache.helix.InstanceType; +import org.apache.helix.SystemPropertyKeys; +import org.apache.helix.manager.zk.ByteArraySerializer; +import org.apache.helix.manager.zk.ZKHelixAdmin; +import org.apache.helix.manager.zk.ZKHelixDataAccessor; +import org.apache.helix.manager.zk.ZkBaseDataAccessor; +import org.apache.helix.msdcommon.exception.InvalidRoutingDataException; +import org.apache.helix.rest.metadatastore.ZkMetadataStoreDirectory; +import org.apache.helix.task.TaskDriver; +import org.apache.helix.tools.ClusterSetup; +import org.apache.helix.zookeeper.api.client.HelixZkClient; +import org.apache.helix.zookeeper.api.client.RealmAwareZkClient; +import org.apache.helix.zookeeper.constant.RoutingDataReaderType; +import org.apache.helix.zookeeper.datamodel.ZNRecord; +import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; +import org.apache.helix.zookeeper.impl.client.FederatedZkClient; +import org.apache.helix.zookeeper.impl.client.ZkClient; +import org.apache.helix.zookeeper.impl.factory.DedicatedZkClientFactory; +import org.apache.helix.zookeeper.impl.factory.SharedZkClientFactory; +import org.apache.helix.zookeeper.routing.RoutingDataManager; +import org.apache.helix.zookeeper.zkclient.IZkChildListener; +import org.apache.helix.zookeeper.zkclient.IZkDataListener; +import org.apache.helix.zookeeper.zkclient.IZkStateListener; +import org.apache.zookeeper.Watcher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class ServerContext implements IZkDataListener, IZkChildListener, IZkStateListener { + private static final Logger LOG = LoggerFactory.getLogger(ServerContext.class); + + private final String _zkAddr; + private boolean _isMultiZkEnabled; + private final String _msdsEndpoint; + private volatile RealmAwareZkClient _zkClient; + + private volatile ZKHelixAdmin _zkHelixAdmin; + private volatile ClusterSetup _clusterSetup; + private volatile ConfigAccessor _configAccessor; + // A lazily-initialized base data accessor that reads/writes byte array to ZK + // TODO: Only read (deserialize) is supported at this time. This baseDataAccessor should support write (serialize) as needs arise + private volatile ZkBaseDataAccessor _byteArrayZkBaseDataAccessor; + // 1 Cluster name will correspond to 1 helix data accessor + private final Map _helixDataAccessorPool; + // 1 Cluster name will correspond to 1 task driver + private final Map _taskDriverPool; + + /** + * Multi-ZK support + */ + private ZkMetadataStoreDirectory _zkMetadataStoreDirectory; + // Create a dedicated ZkClient for listening to data changes in routing data + private RealmAwareZkClient _zkClientForListener; + + public ServerContext(String zkAddr) { + this(zkAddr, false, null); + } + + /** + * Initializes a ServerContext for this namespace. + * @param zkAddr routing ZK address (on multi-zk mode) + * @param isMultiZkEnabled boolean flag for whether multi-zk mode is enabled + * @param msdsEndpoint if given, this server context will try to read routing data from this MSDS. + */ + public ServerContext(String zkAddr, boolean isMultiZkEnabled, String msdsEndpoint) { + _zkAddr = zkAddr; + _isMultiZkEnabled = isMultiZkEnabled; + _msdsEndpoint = msdsEndpoint; // only applicable on multi-zk mode + + // We should NOT initiate _zkClient and anything that depends on _zkClient in + // constructor, as it is reasonable to start up HelixRestServer first and then + // ZooKeeper. In this case, initializing _zkClient will fail and HelixRestServer + // cannot be started correctly. + _helixDataAccessorPool = new ConcurrentHashMap<>(); + _taskDriverPool = new ConcurrentHashMap<>(); + + // Initialize the singleton ZkMetadataStoreDirectory instance to allow it to be closed later + _zkMetadataStoreDirectory = ZkMetadataStoreDirectory.getInstance(); + } + + public RealmAwareZkClient getRealmAwareZkClient() { + if (_zkClient == null) { + synchronized (this) { + if (_zkClient == null) { + // If the multi ZK config is enabled, use FederatedZkClient on multi-realm mode + if (_isMultiZkEnabled || Boolean + .parseBoolean(System.getProperty(SystemPropertyKeys.MULTI_ZK_ENABLED))) { + try { + // Make sure the ServerContext is subscribed to routing data change so that it knows + // when to reset ZkClient and Helix APIs + if (_zkClientForListener == null) { + _zkClientForListener = DedicatedZkClientFactory.getInstance() + .buildZkClient(new HelixZkClient.ZkConnectionConfig(_zkAddr), + new HelixZkClient.ZkClientConfig() + .setZkSerializer(new ZNRecordSerializer())); + } + // Refresh data subscription + _zkClientForListener.unsubscribeAll(); + _zkClientForListener.subscribeRoutingDataChanges(this, this); + LOG.info("ServerContext: subscribed to routing data in routing ZK at {}!", _zkAddr); + + RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder connectionConfigBuilder = + new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder(); + // If MSDS endpoint is set for this namespace, use that instead. + if (_msdsEndpoint != null && !_msdsEndpoint.isEmpty()) { + connectionConfigBuilder.setRoutingDataSourceEndpoint(_msdsEndpoint) + .setRoutingDataSourceType(RoutingDataReaderType.HTTP.name()); + } + _zkClient = new FederatedZkClient(connectionConfigBuilder.build(), + new RealmAwareZkClient.RealmAwareZkClientConfig() + .setZkSerializer(new ZNRecordSerializer())); + LOG.info("ServerContext: FederatedZkClient created successfully!"); + } catch (InvalidRoutingDataException | IllegalStateException e) { + throw new HelixException("Failed to create FederatedZkClient!", e); + } + } else { + // If multi ZK config is not set, just connect to the ZK address given + HelixZkClient.ZkClientConfig clientConfig = new HelixZkClient.ZkClientConfig(); + clientConfig.setZkSerializer(new ZNRecordSerializer()); + _zkClient = SharedZkClientFactory.getInstance() + .buildZkClient(new HelixZkClient.ZkConnectionConfig(_zkAddr), clientConfig); + } + } + } + } + return _zkClient; + } + + @Deprecated + public ZkClient getZkClient() { + return (ZkClient) getRealmAwareZkClient(); + } + + public HelixAdmin getHelixAdmin() { + if (_zkHelixAdmin == null) { + synchronized (this) { + if (_zkHelixAdmin == null) { + _zkHelixAdmin = new ZKHelixAdmin(getRealmAwareZkClient()); + } + } + } + return _zkHelixAdmin; + } + + public ClusterSetup getClusterSetup() { + if (_clusterSetup == null) { + synchronized (this) { + if (_clusterSetup == null) { + _clusterSetup = new ClusterSetup(getRealmAwareZkClient(), getHelixAdmin()); + } + } + } + return _clusterSetup; + } + + public TaskDriver getTaskDriver(String clusterName) { + TaskDriver taskDriver = _taskDriverPool.get(clusterName); + if (taskDriver == null) { + synchronized (this) { + if (!_taskDriverPool.containsKey(clusterName)) { + _taskDriverPool.put(clusterName, new TaskDriver(getRealmAwareZkClient(), clusterName)); + } + taskDriver = _taskDriverPool.get(clusterName); + } + } + return taskDriver; + } + + public ConfigAccessor getConfigAccessor() { + if (_configAccessor == null) { + synchronized (this) { + if (_configAccessor == null) { + _configAccessor = new ConfigAccessor(getRealmAwareZkClient()); + } + } + } + return _configAccessor; + } + + public HelixDataAccessor getDataAccessor(String clusterName) { + HelixDataAccessor dataAccessor = _helixDataAccessorPool.get(clusterName); + if (dataAccessor == null) { + synchronized (this) { + if (!_helixDataAccessorPool.containsKey(clusterName)) { + ZkBaseDataAccessor baseDataAccessor = + new ZkBaseDataAccessor<>(getRealmAwareZkClient()); + _helixDataAccessorPool.put(clusterName, + new ZKHelixDataAccessor(clusterName, InstanceType.ADMINISTRATOR, baseDataAccessor)); + } + dataAccessor = _helixDataAccessorPool.get(clusterName); + } + } + return dataAccessor; + } + + /** + * Returns a lazily-instantiated ZkBaseDataAccessor for the byte array type. + * @return + */ + public BaseDataAccessor getByteArrayZkBaseDataAccessor() { + if (_byteArrayZkBaseDataAccessor == null) { + synchronized (this) { + if (_byteArrayZkBaseDataAccessor == null) { + _byteArrayZkBaseDataAccessor = + new ZkBaseDataAccessor<>(_zkAddr, new ByteArraySerializer()); + } + } + } + return _byteArrayZkBaseDataAccessor; + } + + public void close() { + if (_zkClient != null) { + _zkClient.close(); + } + if (_zkMetadataStoreDirectory != null) { + _zkMetadataStoreDirectory.close(); + } + if (_zkClientForListener != null) { + _zkClientForListener.close(); + } + } + + @Override + public void handleChildChange(String parentPath, List currentChilds) { + if (_zkClientForListener == null || _zkClientForListener.isClosed()) { + return; + } + // Resubscribe + _zkClientForListener.unsubscribeAll(); + _zkClientForListener.subscribeRoutingDataChanges(this, this); + resetZkResources(); + } + + @Override + public void handleDataChange(String dataPath, Object data) { + if (_zkClientForListener == null || _zkClientForListener.isClosed()) { + return; + } + resetZkResources(); + } + + @Override + public void handleDataDeleted(String dataPath) { + if (_zkClientForListener == null || _zkClientForListener.isClosed()) { + return; + } + // Resubscribe + _zkClientForListener.unsubscribeAll(); + _zkClientForListener.subscribeRoutingDataChanges(this, this); + resetZkResources(); + } + + @Override + public void handleStateChanged(Watcher.Event.KeeperState state) { + if (_zkClientForListener == null || _zkClientForListener.isClosed()) { + return; + } + // Resubscribe + _zkClientForListener.unsubscribeAll(); + _zkClientForListener.subscribeRoutingDataChanges(this, this); + resetZkResources(); + } + + @Override + public void handleNewSession(String sessionId) { + if (_zkClientForListener == null || _zkClientForListener.isClosed()) { + return; + } + // Resubscribe + _zkClientForListener.unsubscribeAll(); + _zkClientForListener.subscribeRoutingDataChanges(this, this); + resetZkResources(); + } + + @Override + public void handleSessionEstablishmentError(Throwable error) { + if (_zkClientForListener == null || _zkClientForListener.isClosed()) { + return; + } + // Resubscribe + _zkClientForListener.unsubscribeAll(); + _zkClientForListener.subscribeRoutingDataChanges(this, this); + resetZkResources(); + } + + /** + * Resets all internally cached routing data by closing and nullifying the ZkClient and Helix APIs. + * This is okay because routing data update should be infrequent. + */ + private void resetZkResources() { + synchronized (this) { + LOG.info("ServerContext: Resetting ZK resources due to routing data change! Routing ZK: {}", + _zkAddr); + try { + // Reset RoutingDataManager's cache + RoutingDataManager.getInstance().reset(); + // All Helix APIs will be closed implicitly because ZkClient is closed + if (_zkClient != null && !_zkClient.isClosed()) { + _zkClient.close(); + } + if (_byteArrayZkBaseDataAccessor != null) { + _byteArrayZkBaseDataAccessor.close(); + } + _zkClient = null; + _zkHelixAdmin = null; + _clusterSetup = null; + _configAccessor = null; + _byteArrayZkBaseDataAccessor = null; + _helixDataAccessorPool.clear(); + _taskDriverPool.clear(); + } catch (Exception e) { + LOG.error("Failed to reset ZkClient and Helix APIs in ServerContext!", e); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.helix.rest.server.ServerContext.handleChildChange` reads without synchronization from `this.org.apache.helix.rest.server.ServerContext._zkClientForListener`. Potentially races with write in method `ServerContext.getTaskDriver(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ServerContext.handleChildChange(String,List) + +### Procedure Id: +org.apache.helix.rest.server.ServerContext.handleChildChange(java.lang.String,java.util.List):void.864915c1d519544d0b5b12228f7c205e + +### File: +helix-rest/src/main/java/org/apache/helix/rest/server/ServerContext.java + +### Key: +ServerContext.java|handleChildChange|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +767f37bcfe2ff61fb7087377afb965b1 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9647/instruction.md b/inferredbugs-9647/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b5a04082497d00a9dbab1d376ce1093fe6ff164e --- /dev/null +++ b/inferredbugs-9647/instruction.md @@ -0,0 +1,577 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 78 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.controller.stages; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; + +import javax.management.JMException; +import org.apache.helix.HelixException; +import org.apache.helix.HelixManager; +import org.apache.helix.HelixRebalanceException; +import org.apache.helix.controller.LogUtil; +import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider; +import org.apache.helix.controller.pipeline.AbstractBaseStage; +import org.apache.helix.controller.pipeline.StageException; +import org.apache.helix.controller.rebalancer.AutoRebalancer; +import org.apache.helix.controller.rebalancer.CustomRebalancer; +import org.apache.helix.controller.rebalancer.MaintenanceRebalancer; +import org.apache.helix.controller.rebalancer.Rebalancer; +import org.apache.helix.controller.rebalancer.SemiAutoRebalancer; +import org.apache.helix.controller.rebalancer.internal.MappingCalculator; +import org.apache.helix.controller.rebalancer.waged.WagedRebalancer; +import org.apache.helix.monitoring.metrics.MetricCollector; +import org.apache.helix.monitoring.metrics.WagedRebalancerMetricCollector; +import org.apache.helix.model.ClusterConfig; +import org.apache.helix.model.IdealState; +import org.apache.helix.model.InstanceConfig; +import org.apache.helix.model.MaintenanceSignal; +import org.apache.helix.model.Partition; +import org.apache.helix.model.Resource; +import org.apache.helix.model.ResourceAssignment; +import org.apache.helix.model.StateModelDefinition; +import org.apache.helix.monitoring.mbeans.ClusterStatusMonitor; +import org.apache.helix.monitoring.mbeans.ResourceMonitor; +import org.apache.helix.task.TaskConstants; +import org.apache.helix.util.HelixUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * For partition compute best possible (instance,state) pair based on + * IdealState,StateModel,LiveInstance + */ +public class BestPossibleStateCalcStage extends AbstractBaseStage { + private static final Logger logger = + LoggerFactory.getLogger(BestPossibleStateCalcStage.class.getName()); + // Create a ThreadLocal of MetricCollector. Metrics could only be updated by the controller thread only. + private static final ThreadLocal METRIC_COLLECTOR_THREAD_LOCAL = new ThreadLocal<>(); + + @Override + public void process(ClusterEvent event) throws Exception { + _eventId = event.getEventId(); + CurrentStateOutput currentStateOutput = event.getAttribute(AttributeName.CURRENT_STATE.name()); + final Map resourceMap = + event.getAttribute(AttributeName.RESOURCES_TO_REBALANCE.name()); + final ClusterStatusMonitor clusterStatusMonitor = + event.getAttribute(AttributeName.clusterStatusMonitor.name()); + ResourceControllerDataProvider cache = + event.getAttribute(AttributeName.ControllerDataProvider.name()); + + if (currentStateOutput == null || resourceMap == null || cache == null) { + throw new StageException( + "Missing attributes in event:" + event + ". Requires CURRENT_STATE|RESOURCES|DataCache"); + } + + final BestPossibleStateOutput bestPossibleStateOutput = + compute(event, resourceMap, currentStateOutput); + event.addAttribute(AttributeName.BEST_POSSIBLE_STATE.name(), bestPossibleStateOutput); + + final Map instanceConfigMap = cache.getInstanceConfigMap(); + final Map stateModelDefMap = cache.getStateModelDefMap(); + asyncExecute(cache.getAsyncTasksThreadPool(), new Callable() { + @Override + public Object call() { + try { + if (clusterStatusMonitor != null) { + clusterStatusMonitor + .setPerInstanceResourceStatus(bestPossibleStateOutput, instanceConfigMap, + resourceMap, stateModelDefMap); + } + } catch (Exception e) { + LogUtil.logError(logger, _eventId, "Could not update cluster status metrics!", e); + } + return null; + } + }); + } + + private BestPossibleStateOutput compute(ClusterEvent event, Map resourceMap, + CurrentStateOutput currentStateOutput) { + ResourceControllerDataProvider cache = + event.getAttribute(AttributeName.ControllerDataProvider.name()); + BestPossibleStateOutput output = new BestPossibleStateOutput(); + + HelixManager helixManager = event.getAttribute(AttributeName.helixmanager.name()); + ClusterStatusMonitor clusterStatusMonitor = + event.getAttribute(AttributeName.clusterStatusMonitor.name()); + + // Check whether the offline/disabled instance count in the cluster reaches the set limit, + // if yes, pause the rebalancer. + boolean isValid = + validateOfflineInstancesLimit(cache, event.getAttribute(AttributeName.helixmanager.name())); + + final List failureResources = new ArrayList<>(); + + Map calculatedResourceMap = + computeResourceBestPossibleStateWithWagedRebalancer(cache, currentStateOutput, helixManager, + resourceMap, output, failureResources); + + Map remainingResourceMap = new HashMap<>(resourceMap); + remainingResourceMap.keySet().removeAll(calculatedResourceMap.keySet()); + + // Fallback to the original single resource rebalancer calculation. + // This is required because we support mixed cluster that uses both WAGED rebalancer and the + // older rebalancers. + Iterator itr = remainingResourceMap.values().iterator(); + while (itr.hasNext()) { + Resource resource = itr.next(); + boolean result = false; + try { + result = computeSingleResourceBestPossibleState(event, cache, currentStateOutput, resource, + output); + } catch (HelixException ex) { + LogUtil.logError(logger, _eventId, String + .format("Exception when calculating best possible states for %s", + resource.getResourceName()), ex); + + } + if (!result) { + failureResources.add(resource.getResourceName()); + LogUtil.logWarn(logger, _eventId, String + .format("Failed to calculate best possible states for %s", resource.getResourceName())); + } + } + + // Check and report if resource rebalance has failure + updateRebalanceStatus(!isValid || !failureResources.isEmpty(), failureResources, helixManager, + cache, clusterStatusMonitor, String + .format("Failed to calculate best possible states for %d resources.", + failureResources.size())); + + return output; + } + + private void updateRebalanceStatus(final boolean hasFailure, final List failedResources, + final HelixManager helixManager, final ResourceControllerDataProvider cache, + final ClusterStatusMonitor clusterStatusMonitor, final String errorMessage) { + asyncExecute(cache.getAsyncTasksThreadPool(), new Callable() { + @Override + public Object call() { + try { + if (hasFailure) { + /* TODO Enable this update when we resolve ZK server load issue. This will cause extra write to ZK. + if (_statusUpdateUtil != null) { + _statusUpdateUtil + .logError(StatusUpdateUtil.ErrorType.RebalanceResourceFailure, this.getClass(), + errorMessage, helixManager); + } + */ + LogUtil.logWarn(logger, _eventId, errorMessage); + } + if (clusterStatusMonitor != null) { + clusterStatusMonitor.setRebalanceFailureGauge(hasFailure); + clusterStatusMonitor.setResourceRebalanceStates(failedResources, + ResourceMonitor.RebalanceStatus.BEST_POSSIBLE_STATE_CAL_FAILED); + } + } catch (Exception e) { + LogUtil.logError(logger, _eventId, "Could not update cluster status!", e); + } + return null; + } + }); + } + + // Check whether the offline/disabled instance count in the cluster reaches the set limit, + // if yes, pause the rebalancer, and throw exception to terminate rebalance cycle. + private boolean validateOfflineInstancesLimit(final ResourceControllerDataProvider cache, + final HelixManager manager) { + int maxOfflineInstancesAllowed = cache.getClusterConfig().getMaxOfflineInstancesAllowed(); + if (maxOfflineInstancesAllowed >= 0) { + int offlineCount = cache.getAllInstances().size() - cache.getEnabledLiveInstances().size(); + if (offlineCount > maxOfflineInstancesAllowed) { + String errMsg = String.format( + "Offline Instances count %d greater than allowed count %d. Stop rebalance and put the cluster %s into maintenance mode.", + offlineCount, maxOfflineInstancesAllowed, cache.getClusterName()); + if (manager != null) { + if (manager.getHelixDataAccessor() + .getProperty(manager.getHelixDataAccessor().keyBuilder().maintenance()) == null) { + manager.getClusterManagmentTool() + .autoEnableMaintenanceMode(manager.getClusterName(), true, errMsg, + MaintenanceSignal.AutoTriggerReason.MAX_OFFLINE_INSTANCES_EXCEEDED); + LogUtil.logWarn(logger, _eventId, errMsg); + } + } else { + LogUtil.logError(logger, _eventId, "Failed to put cluster " + cache.getClusterName() + + " into maintenance mode, HelixManager is not set!"); + } + return false; + } + } + return true; + } + + /** + * Rebalance with the WAGED rebalancer + * The rebalancer only calculates the new ideal assignment for all the resources that are + * configured to use the WAGED rebalancer. + * + * @param cache Cluster data cache. + * @param currentStateOutput The current state information. + * @param helixManager + * @param resourceMap The complete resource map. The method will filter the map for the compatible resources. + * @param output The best possible state output. + * @param failureResources The failure records that will be updated if any resource cannot be computed. + * @return The map of all the calculated resources. + */ + private Map computeResourceBestPossibleStateWithWagedRebalancer( + ResourceControllerDataProvider cache, CurrentStateOutput currentStateOutput, + HelixManager helixManager, Map resourceMap, BestPossibleStateOutput output, + List failureResources) { + if (cache.isMaintenanceModeEnabled()) { + // The WAGED rebalancer won't be used while maintenance mode is enabled. + return Collections.emptyMap(); + } + + // Find the compatible resources: 1. FULL_AUTO 2. Configured to use the WAGED rebalancer + Map wagedRebalancedResourceMap = + resourceMap.entrySet().stream().filter(resourceEntry -> { + IdealState is = cache.getIdealState(resourceEntry.getKey()); + return is != null && is.getRebalanceMode().equals(IdealState.RebalanceMode.FULL_AUTO) + && WagedRebalancer.class.getName().equals(is.getRebalancerClassName()); + }).collect(Collectors.toMap(resourceEntry -> resourceEntry.getKey(), + resourceEntry -> resourceEntry.getValue())); + + Map newIdealStates = new HashMap<>(); + + // Init rebalancer with the rebalance preferences. + Map preferences = + cache.getClusterConfig().getGlobalRebalancePreference(); + + if (METRIC_COLLECTOR_THREAD_LOCAL.get() == null) { + try { + // If HelixManager is null, we just pass in null for MetricCollector so that a + // non-functioning WagedRebalancerMetricCollector would be created in WagedRebalancer's + // constructor. This is to handle two cases: 1. HelixManager is null for non-testing cases - + // in this case, WagedRebalancer will not read/write to metadata store and just use + // CurrentState-based rebalancing. 2. Tests that require instrumenting the rebalancer for + // verifying whether the cluster has converged. + METRIC_COLLECTOR_THREAD_LOCAL.set(helixManager == null ? null + : new WagedRebalancerMetricCollector(helixManager.getClusterName())); + } catch (JMException e) { + LogUtil.logWarn(logger, _eventId, String.format( + "MetricCollector instantiation failed! WagedRebalancer will not emit metrics due to JMException %s", + e)); + } + } + + // TODO avoid creating the rebalancer on every rebalance call for performance enhancement + WagedRebalancer wagedRebalancer = + new WagedRebalancer(helixManager, preferences, METRIC_COLLECTOR_THREAD_LOCAL.get()); + try { + newIdealStates.putAll(wagedRebalancer.computeNewIdealStates(cache, wagedRebalancedResourceMap, + currentStateOutput)); + } catch (HelixRebalanceException ex) { + // Note that unlike the legacy rebalancer, the WAGED rebalance won't return partial result. + // Since it calculates for all the eligible resources globally, a partial result is invalid. + // TODO propagate the rebalancer failure information to updateRebalanceStatus for monitoring. + LogUtil.logError(logger, _eventId, + String.format( + "Failed to calculate the new Ideal States using the rebalancer %s due to %s", + wagedRebalancer.getClass().getSimpleName(), ex.getFailureType()), + ex); + } finally { + wagedRebalancer.close(); + } + Iterator itr = wagedRebalancedResourceMap.values().iterator(); + while (itr.hasNext()) { + Resource resource = itr.next(); + IdealState is = newIdealStates.get(resource.getResourceName()); + // Check if the WAGED rebalancer has calculated the result for this resource or not. + if (is != null && checkBestPossibleStateCalculation(is)) { + // The WAGED rebalancer calculates a valid result, record in the output + updateBestPossibleStateOutput(output, resource, is); + } else { + failureResources.add(resource.getResourceName()); + LogUtil.logWarn(logger, _eventId, String + .format("Failed to calculate best possible states for %s.", + resource.getResourceName())); + } + } + return wagedRebalancedResourceMap; + } + + private void updateBestPossibleStateOutput(BestPossibleStateOutput output, Resource resource, + IdealState computedIdealState) { + output.setPreferenceLists(resource.getResourceName(), computedIdealState.getPreferenceLists()); + for (Partition partition : resource.getPartitions()) { + Map newStateMap = + computedIdealState.getInstanceStateMap(partition.getPartitionName()); + output.setState(resource.getResourceName(), partition, newStateMap); + } + } + + private boolean computeSingleResourceBestPossibleState(ClusterEvent event, + ResourceControllerDataProvider cache, CurrentStateOutput currentStateOutput, + Resource resource, BestPossibleStateOutput output) { + // for each ideal state + // read the state model def + // for each resource + // get the preference list + // for each instanceName check if its alive then assign a state + + String resourceName = resource.getResourceName(); + LogUtil.logDebug(logger, _eventId, "Processing resource:" + resourceName); + // Ideal state may be gone. In that case we need to get the state model name + // from the current state + IdealState idealState = cache.getIdealState(resourceName); + if (idealState == null) { + // if ideal state is deleted, use an empty one + LogUtil.logInfo(logger, _eventId, "resource:" + resourceName + " does not exist anymore"); + idealState = new IdealState(resourceName); + idealState.setStateModelDefRef(resource.getStateModelDefRef()); + } + + // Skip resources are tasks for regular pipeline + if (idealState.getStateModelDefRef().equals(TaskConstants.STATE_MODEL_NAME)) { + LogUtil.logWarn(logger, _eventId, String + .format("Resource %s should not be processed by %s pipeline", resourceName, + cache.getPipelineName())); + return false; + } + + Rebalancer rebalancer = + getRebalancer(idealState, resourceName, cache.isMaintenanceModeEnabled()); + MappingCalculator mappingCalculator = + getMappingCalculator(rebalancer, resourceName); + + if (rebalancer == null || mappingCalculator == null) { + LogUtil.logError(logger, _eventId, "Error computing assignment for resource " + resourceName + + ". no rebalancer found. rebalancer: " + rebalancer + " mappingCalculator: " + + mappingCalculator); + } + + if (rebalancer != null && mappingCalculator != null) { + ResourceAssignment partitionStateAssignment = null; + try { + HelixManager manager = event.getAttribute(AttributeName.helixmanager.name()); + rebalancer.init(manager); + idealState = + rebalancer.computeNewIdealState(resourceName, idealState, currentStateOutput, cache); + + output.setPreferenceLists(resourceName, idealState.getPreferenceLists()); + + // Use the internal MappingCalculator interface to compute the final assignment + // The next release will support rebalancers that compute the mapping from start to finish + partitionStateAssignment = mappingCalculator + .computeBestPossiblePartitionState(cache, idealState, resource, currentStateOutput); + + if (partitionStateAssignment == null) { + LogUtil.logWarn(logger, _eventId, + "PartitionStateAssignment is null, resource: " + resourceName); + return false; + } + + for (Partition partition : resource.getPartitions()) { + Map newStateMap = partitionStateAssignment.getReplicaMap(partition); + output.setState(resourceName, partition, newStateMap); + } + + // Check if calculation is done successfully + return checkBestPossibleStateCalculation(idealState); + } catch (HelixException e) { + // No eligible instance is found. + LogUtil.logError(logger, _eventId, e.getMessage()); + } catch (Exception e) { + LogUtil.logError(logger, _eventId, + "Error computing assignment for resource " + resourceName + ". Skipping." , e); + } + } + // Exception or rebalancer is not found + return false; + } + + private boolean checkBestPossibleStateCalculation(IdealState idealState) { + // If replicas is 0, indicate the resource is not fully initialized or ready to be rebalanced + if (idealState.getRebalanceMode() == IdealState.RebalanceMode.FULL_AUTO && !idealState + .getReplicas().equals("0")) { + Map> preferenceLists = idealState.getPreferenceLists(); + if (preferenceLists == null || preferenceLists.isEmpty()) { + return false; + } + int emptyListCount = 0; + for (List preferenceList : preferenceLists.values()) { + if (preferenceList.isEmpty()) { + emptyListCount++; + } + } + // If all lists are empty, rebalance fails completely + return emptyListCount != preferenceLists.values().size(); + } else { + // For non FULL_AUTO RebalanceMode, rebalancing is not controlled by Helix + return true; + } + } + + private Rebalancer getCustomizedRebalancer( + String rebalancerClassName, String resourceName) { + Rebalancer customizedRebalancer = null; + if (rebalancerClassName != null) { + if (logger.isDebugEnabled()) { + LogUtil.logDebug(logger, _eventId, + "resource " + resourceName + " use idealStateRebalancer " + rebalancerClassName); + } + try { + customizedRebalancer = Rebalancer.class + .cast(HelixUtil.loadClass(getClass(), rebalancerClassName).newInstance()); + } catch (Exception e) { + LogUtil.logError(logger, _eventId, + "Exception while invoking custom rebalancer class:" + rebalancerClassName, e); + } + } + return customizedRebalancer; + } + + private Rebalancer getRebalancer(IdealState idealState, + String resourceName, boolean isMaintenanceModeEnabled) { + Rebalancer rebalancer = null; + switch (idealState.getRebalanceMode()) { + case FULL_AUTO: + if (isMaintenanceModeEnabled) { + rebalancer = new MaintenanceRebalancer(); + } else { + Rebalancer customizedRebalancer = + getCustomizedRebalancer(idealState.getRebalancerClassName(), resourceName); + if (customizedRebalancer != null) { + rebalancer = customizedRebalancer; + } else { + rebalancer = new AutoRebalancer(); + } + } + break; + case SEMI_AUTO: + rebalancer = new SemiAutoRebalancer<>(); + break; + case CUSTOMIZED: + rebalancer = new CustomRebalancer(); + break; + case USER_DEFINED: + case TASK: + rebalancer = getCustomizedRebalancer(idealState.getRebalancerClassName(), resourceName); + break; + default: + LogUtil.logError(logger, _eventId, + "Fail to find the rebalancer, invalid rebalance mode " + idealState.getRebalanceMode()); + break; + } + return rebalancer; + } + + private MappingCalculator getMappingCalculator( + Rebalancer rebalancer, String resourceName) { + MappingCalculator mappingCalculator = null; + + if (rebalancer != null) { + try { + mappingCalculator = MappingCalculator.class.cast(rebalancer); + } catch (ClassCastException e) { + LogUtil.logWarn(logger, _eventId, + "Rebalancer does not have a mapping calculator, defaulting to SEMI_AUTO, resource: " + + resourceName); + } + } + if (mappingCalculator == null) { + mappingCalculator = new SemiAutoRebalancer<>(); + } + + return mappingCalculator; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.helix.manager.zk.ZkBucketDataAccessor` acquired by call to `WagedRebalancer(...)` at line 283 is not released after line 297. +**Note**: potential exception at line 285 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Map BestPossibleStateCalcStage.computeResourceBestPossibleStateWithWagedRebalancer(ResourceControllerDataProvider,CurrentStateOutput,HelixManager,Map,BestPossibleStateOutput,List) + +### Procedure Id: +org.apache.helix.controller.stages.BestPossibleStateCalcStage.computeResourceBestPossibleStateWithWa.d368062e5cc2e2d2d2217eeab7039121 + +### File: +helix-core/src/main/java/org/apache/helix/controller/stages/BestPossibleStateCalcStage.java + +### Key: +BestPossibleStateCalcStage.java|computeResourceBestPossibleStateWithWagedRebalancer|RESOURCE_LEAK + +### Node Key: +fdceee6316806f0a2625382fbfd798af + +### Hash: +0740a780acb21044654b5b99d437fd82 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9648/instruction.md b/inferredbugs-9648/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..44c5ee9f56ea50bd392ecf25f21ba40abc87ccfb --- /dev/null +++ b/inferredbugs-9648/instruction.md @@ -0,0 +1,130 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.linkedin.clustermanager.controller.stages; + +import java.util.Map; + +import org.apache.log4j.Logger; + +import com.linkedin.clustermanager.ClusterDataAccessor; +import com.linkedin.clustermanager.ClusterManager; +import com.linkedin.clustermanager.ZNRecord; +import com.linkedin.clustermanager.ClusterDataAccessor.ClusterPropertyType; +import com.linkedin.clustermanager.model.ExternalView; +import com.linkedin.clustermanager.model.ResourceGroup; +import com.linkedin.clustermanager.model.ResourceKey; +import com.linkedin.clustermanager.pipeline.AbstractBaseStage; +import com.linkedin.clustermanager.pipeline.StageException; + +public class ExternalViewComputeStage extends AbstractBaseStage +{ + private static Logger log = Logger.getLogger(ExternalViewComputeStage.class); + + @Override + public void process(ClusterEvent event) throws Exception + { + ClusterManager manager = event.getAttribute("clustermanager"); + if (manager == null) + { + throw new StageException("ClusterManager attribute value is null"); + } + log.info("START ExternalViewComputeStage.process()"); + ClusterDataAccessor dataAccessor = manager.getDataAccessor(); + Map resourceGroupMap = event + .getAttribute(AttributeName.RESOURCE_GROUPS.toString()); + CurrentStateOutput currentStateOutput = event + .getAttribute(AttributeName.CURRENT_STATE.toString()); + for (String resourceGroupName : resourceGroupMap.keySet()) + { + ZNRecord viewRecord = new ZNRecord(); + viewRecord.setId(resourceGroupName); + ExternalView view = new ExternalView(viewRecord); + ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName); + for (ResourceKey resource : resourceGroup.getResourceKeys()) + { + Map currentStateMap = currentStateOutput + .getCurrentStateMap(resourceGroupName, resource); + if (currentStateMap != null && currentStateMap.size() > 0) + { + view.setStateMap(resource.getResourceKeyName(), currentStateMap); + } + } + dataAccessor.setClusterProperty(ClusterPropertyType.EXTERNALVIEW, + resourceGroupName, view.getRecord()); + } + log.info("START ExternalViewComputeStage.process()"); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `resourceGroupMap` last assigned on line 32 could be null and is dereferenced at line 35. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExternalViewComputeStage.process(ClusterEvent) + +### Procedure Id: +com.linkedin.clustermanager.controller.stages.ExternalViewComputeStage.process(com.linkedin.clusterm.ffc76ee51aa65ed7f640a687163430f2 + +### File: +cluster-manager-core/src/main/java/com/linkedin/clustermanager/controller/stages/ExternalViewComputeStage.java + +### Key: +ExternalViewComputeStage.java|process|NULL_DEREFERENCE + +### Node Key: +75a3105ef036e14d28c2a0df35d92164 + +### Hash: +991be952079afdc7a41751f131ad361f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9649/instruction.md b/inferredbugs-9649/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7ad56ce65071d2c264c7a36dd44146adac474b24 --- /dev/null +++ b/inferredbugs-9649/instruction.md @@ -0,0 +1,188 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.linkedin.clustermanager.controller.stages; + +import java.util.List; +import java.util.Map; + +import com.linkedin.clustermanager.model.CurrentState; +import com.linkedin.clustermanager.model.LiveInstance; +import com.linkedin.clustermanager.model.Message; +import com.linkedin.clustermanager.model.Message.MessageType; +import com.linkedin.clustermanager.model.ResourceGroup; +import com.linkedin.clustermanager.model.ResourceKey; +import com.linkedin.clustermanager.pipeline.AbstractBaseStage; + +/** + * For each LiveInstances select currentState and message whose sessionId + * matches sessionId from LiveInstance Get ResourceKey,State for all the + * resources computed in previous State [ResourceComputationStage] + * + * @author kgopalak + * + */ +public class CurrentStateComputationStage extends AbstractBaseStage +{ + @Override + public void process(ClusterEvent event) throws Exception + { + ClusterDataCache cache = event.getAttribute("ClusterDataCache"); + + Map liveInstances = cache.getLiveInstances(); + CurrentStateOutput currentStateOutput = new CurrentStateOutput(); + Map resourceGroupMap = event + .getAttribute(AttributeName.RESOURCE_GROUPS.toString()); + + for (LiveInstance instance : liveInstances.values()) + { + String instanceName = instance.getInstanceName(); + List instanceMessages; + instanceMessages = cache.getMessages(instanceName); + for (Message message : instanceMessages) + { + if (!MessageType.STATE_TRANSITION.toString().equalsIgnoreCase( + message.getMsgType())) + { + continue; + } + if (!instance.getSessionId().equals(message.getTgtSessionId())) + { + continue; + } + String resourceGroupName = message.getResourceGroupName(); + ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName); + if (resourceGroup == null) + { + continue; + } + ResourceKey resourceKey = resourceGroup.getResourceKey(message + .getResourceKey()); + if (resourceKey != null) + { + currentStateOutput.setPendingState(resourceGroupName, resourceKey, + instanceName, message.getToState()); + } else + { + // log + } + } + } + for (LiveInstance instance : liveInstances.values()) + { + String instanceName = instance.getInstanceName(); + + String clientSessionId = instance.getSessionId(); + Map currentStateMap = cache.getCurrentState(instanceName, clientSessionId); + for (CurrentState currentState : currentStateMap.values()) + { + + if (!instance.getSessionId().equals(currentState.getSessionId())) + { + continue; + } + String resourceGroupName = currentState.getResourceGroupName(); + String stateModelDefName = currentState.getStateModelDefRef(); + ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName); + if (resourceGroup == null) + { + continue; + } + if (stateModelDefName != null) + { + currentStateOutput.setResourceGroupStateModelDef(resourceGroupName, + stateModelDefName); + } + Map resourceKeyStateMap = currentState + .getResourceKeyStateMap(); + for (String resourceKeyStr : resourceKeyStateMap.keySet()) + { + ResourceKey resourceKey = resourceGroup + .getResourceKey(resourceKeyStr); + if (resourceKey != null) + { + currentStateOutput.setCurrentState(resourceGroupName, resourceKey, + instanceName, currentState.getState(resourceKeyStr)); + + } else + { + // log + } + } + } + } + event.addAttribute(AttributeName.CURRENT_STATE.toString(), + currentStateOutput); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `cache` last assigned on line 27 could be null and is dereferenced at line 29. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CurrentStateComputationStage.process(ClusterEvent) + +### Procedure Id: +com.linkedin.clustermanager.controller.stages.CurrentStateComputationStage.process(com.linkedin.clus.8e278580a0ce523d401fca83c3b78f64 + +### File: +cluster-manager-core/src/main/java/com/linkedin/clustermanager/controller/stages/CurrentStateComputationStage.java + +### Key: +CurrentStateComputationStage.java|process|NULL_DEREFERENCE + +### Node Key: +6f60fb7cb2d7b2c9393d1f5f9c08da7d + +### Hash: +362360a866900bc2e02483dc322c4054 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9670/instruction.md b/inferredbugs-9670/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a29b6bc5607724356f7e3b80f572043a7211a894 --- /dev/null +++ b/inferredbugs-9670/instruction.md @@ -0,0 +1,266 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 20 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Oshi (https://github.com/dblock/oshi) + * + * Copyright (c) 2010 - 2016 The Oshi Project Team + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Maintainers: + * dblock[at]dblock[dot]org + * widdis[at]gmail[dot]com + * enrico.bianchi[at]gmail[dot]com + * + * Contributors: + * https://github.com/dblock/oshi/graphs/contributors + */ +package oshi.hardware.platform.mac; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import oshi.hardware.UsbDevice; +import oshi.hardware.common.AbstractUsbDevice; +import oshi.util.ExecutingCommand; + +public class MacUsbDevice extends AbstractUsbDevice { + + private static final long serialVersionUID = 1L; + + private static final Pattern XML_STRING = Pattern.compile("(.*?)"); + + public MacUsbDevice(String name, String vendor, String serialNumber, UsbDevice[] connectedDevices) { + super(name, vendor, serialNumber, connectedDevices); + } + + /** + * {@inheritDoc} + */ + public static UsbDevice[] getUsbDevices() { + // Get heirarchical list of USB devices + List xml = ExecutingCommand.runNative("system_profiler SPUSBDataType -xml"); + // Look for _items which prcedes ... + // Each pair of ... following is a USB device/hub + List items = new ArrayList<>(); + boolean copy = false; + int indent = 0; + for (String s : xml) { + s = s.trim(); + // Read until _items + if (!copy && s.equals("_items")) { + copy = true; + continue; + } + // If we've fond items indent with each tag and copy over + // everything with indent > 0. + if (copy) { + if (s.equals("")) { + if (--indent == 0) { + copy = false; + continue; + } + } + if (indent > 0) { + items.add(s); + } + if (s.equals("")) { + indent++; + } + } + } + // Items now contains 0 or more sets of ... + return getUsbDevices(items); + } + + /** + * Parses a list of xml into USB devices + * + * @param items + * A list of XML beginning containing 0 or more ... + * entries corresponding to USB buses, hubs, or devices + * @return An array of usb devices corresponding to the entries + */ + private static UsbDevice[] getUsbDevices(List items) { + List usbDevices = new ArrayList(); + List item = new ArrayList<>(); + // Separate out item between each pair of ... tags + int indent = 0; + for (String s : items) { + if (s.equals("")) { + // If this is the final closing tag, add the singular device + // we've been accumulating in the item list + if (--indent == 0) { + usbDevices.add(getUsbDevice(item)); + item.clear(); + continue; + } + } + if (indent > 0) { + item.add(s); + } + if (s.equals("")) { + indent++; + } + } + return usbDevices.toArray(new UsbDevice[usbDevices.size()]); + } + + /** + * Parses a list of xml (selected from inside ... tags) into a + * USB device + * + * @param data + * A list of XML beginning containing an XML entry corresponding + * to a USB bus, hub, or device + * @return A usb device corresponding to the entry + */ + private static UsbDevice getUsbDevice(List data) { + String name = ""; + boolean readName = false; + String vendor = ""; + boolean readVendor = false; + String serialNumber = ""; + boolean readSerialNumber = false; + List nested = new ArrayList<>(); + boolean readNested = false; + int indent = 0; + for (String s : data) { + if (readName) { + name = parseXmlString(s); + readName = false; + continue; + } else if (readVendor) { + vendor = parseXmlString(s); + readVendor = false; + continue; + } else if (readSerialNumber) { + serialNumber = parseXmlString(s); + readSerialNumber = false; + continue; + } + if (s.equals("") || s.equals("")) { + if (--indent == 0) { + readNested = false; + continue; + } + } + if (readNested && indent > 0) { + nested.add(s); + } + if (s.equals("") || s.equals("")) { + indent++; + } + if (indent == 0) { + switch (s) { + case "_name": + readName = true; + break; + case "manufacturer": + readVendor = true; + break; + case "serial_num": + readSerialNumber = true; + break; + case "_items": + readNested = true; + break; + default: + } + } + } + return new MacUsbDevice(name, vendor, serialNumber, getUsbDevices(nested)); + } + + /** + * Get the string between tags + * + * @param s + * A string between ... tags + * @return The string + */ + private static String parseXmlString(String s) { + Matcher matcher = XML_STRING.matcher(s); + if (matcher.find()) { + return matcher.group(1); + } + return ""; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `xml` last assigned on line 45 could be null and is dereferenced at line 51. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +oshi.hardware.UsbDevice[] MacUsbDevice.getUsbDevices() + +### Procedure Id: +oshi.hardware.platform.mac.MacUsbDevice.getUsbDevices():oshi.hardware.UsbDevice[].41407bebeac17284e6cb15fdddcffe29 + +### File: +src/main/java/oshi/hardware/platform/mac/MacUsbDevice.java + +### Key: +MacUsbDevice.java|getUsbDevices|NULL_DEREFERENCE + +### Node Key: +eae2ee1cdadb82e549c2a1b7c9bd0e3a + +### Hash: +bca5439291cd35c0629ab77d249f9f86 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9671/instruction.md b/inferredbugs-9671/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4bd3f3d6ffd6809ea7f6ad3761fb3224bed823f2 --- /dev/null +++ b/inferredbugs-9671/instruction.md @@ -0,0 +1,184 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Oshi (https://github.com/dblock/oshi) + * + * Copyright (c) 2010 - 2016 The Oshi Project Team + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Maintainers: + * dblock[at]dblock[dot]org + * widdis[at]gmail[dot]com + * enrico.bianchi[at]gmail[dot]com + * + * Contributors: + * https://github.com/dblock/oshi/graphs/contributors + */ +package oshi.hardware.platform.windows; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import oshi.hardware.UsbDevice; +import oshi.hardware.common.AbstractUsbDevice; +import oshi.util.ParseUtil; +import oshi.util.platform.windows.WmiUtil; + +public class WindowsUsbDevice extends AbstractUsbDevice { + + private static final long serialVersionUID = 1L; + + public WindowsUsbDevice(String name, String vendor, String serialNumber, UsbDevice[] connectedDevices) { + super(name, vendor, serialNumber, connectedDevices); + } + + /** + * {@inheritDoc} + */ + public static UsbDevice[] getUsbDevices() { + List usbDevices = new ArrayList(); + + // Store map of pnpID to name, Manufacturer, serial + Map nameMap = new HashMap<>(); + Map vendorMap = new HashMap<>(); + Map serialMap = new HashMap<>(); + + Map> usbMap = WmiUtil.selectStringsFrom(null, "Win32_PnPEntity", + "Name,Manufacturer,PnPDeviceID", null); + for (int i = 0; i < usbMap.get("Name").size(); i++) { + String pnpDeviceID = usbMap.get("PnPDeviceID").get(i); + nameMap.put(pnpDeviceID, usbMap.get("Name").get(i)); + if (usbMap.get("Manufacturer").get(i).length() > 0) { + vendorMap.put(pnpDeviceID, usbMap.get("Manufacturer").get(i)); + } + String serialNumber = ""; + // Format: USB\VID_203A&PID_FFF9&MI_00\6&18C4CF61&0&0000 + // Split by \ to get bus type (USB), VendorID/ProductID/Model + // Last field contains Serial # in hex as 2nd split by + // ampersands + String[] idSplit = pnpDeviceID.split("\\\\"); + if (idSplit.length > 2) { + idSplit = idSplit[2].split("&"); + if (idSplit.length > 3) { + serialNumber = idSplit[1]; + } + } + if (serialNumber.length() > 0) { + serialMap.put(pnpDeviceID, serialNumber); + } + } + + // Get serial # of disk drives (may overwrite previous, that's OK) + usbMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "PNPDeviceID,SerialNumber", null); + for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) { + serialMap.put(usbMap.get("PNPDeviceID").get(i), + ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i))); + } + usbMap = WmiUtil.selectStringsFrom(null, "Win32_PhysicalMedia", "PNPDeviceID,SerialNumber", null); + for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) { + serialMap.put(usbMap.get("PNPDeviceID").get(i), + ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i))); + } + + // Finally, prepare final list for output + // Start with controllers + usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBController", "PNPDeviceID", null); + List pnpDeviceIDs = usbMap.get("PNPDeviceID"); + // Add any hubs + usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBHub", "PNPDeviceID", null); + pnpDeviceIDs.addAll(usbMap.get("PNPDeviceID")); + // Add any stray USB devices in the list + for (String pnpDeviceID : nameMap.keySet().stream().sorted().collect(Collectors.toList())) { + if (pnpDeviceID.startsWith("USB\\") && !pnpDeviceIDs.contains(pnpDeviceID)) { + pnpDeviceIDs.add(pnpDeviceID); + } + } + + for (String pnpDeviceID : pnpDeviceIDs) { + usbDevices.add( + new WindowsUsbDevice(nameMap.getOrDefault(pnpDeviceID, ""), vendorMap.getOrDefault(pnpDeviceID, ""), + serialMap.getOrDefault(pnpDeviceID, ""), new WindowsUsbDevice[0])); + } + + return usbDevices.toArray(new UsbDevice[usbDevices.size()]); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `pnpDeviceIDs` last assigned on line 91 could be null and is dereferenced at line 94. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +oshi.hardware.UsbDevice[] WindowsUsbDevice.getUsbDevices() + +### Procedure Id: +oshi.hardware.platform.windows.WindowsUsbDevice.getUsbDevices():oshi.hardware.UsbDevice[].a7bf038a3b11066a6bbcb92659f282b6 + +### File: +src/main/java/oshi/hardware/platform/windows/WindowsUsbDevice.java + +### Key: +WindowsUsbDevice.java|getUsbDevices|NULL_DEREFERENCE + +### Node Key: +fe32ac8446974b9ec9784530b0625ab0 + +### Hash: +cf67d4713f518023f924f82460456a58 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9676/instruction.md b/inferredbugs-9676/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5e0cc94a99e98bb7bfb88b1282aecf1cae7cdc00 --- /dev/null +++ b/inferredbugs-9676/instruction.md @@ -0,0 +1,577 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 29 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Oshi (https://github.com/dblock/oshi) + * + * Copyright (c) 2010 - 2016 The Oshi Project Team + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Maintainers: + * dblock[at]dblock[dot]org + * widdis[at]gmail[dot]com + * enrico.bianchi[at]gmail[dot]com + * + * Contributors: + * https://github.com/dblock/oshi/graphs/contributors + */ +package oshi.util.platform.windows; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import com.sun.jna.platform.win32.OleAuto; +import com.sun.jna.platform.win32.Variant.VARIANT; +import com.sun.jna.platform.win32.WTypes.BSTR; +import com.sun.jna.platform.win32.WinNT.HRESULT; +import com.sun.jna.platform.win32.COM.COMUtils; +import com.sun.jna.ptr.LongByReference; +import com.sun.jna.ptr.PointerByReference; + +import oshi.jna.platform.windows.Ole32; +import oshi.jna.platform.windows.COM.EnumWbemClassObject; +import oshi.jna.platform.windows.COM.WbemClassObject; +import oshi.jna.platform.windows.COM.WbemLocator; +import oshi.jna.platform.windows.COM.WbemServices; +import oshi.util.ParseUtil; + +/** + * Provides access to WMI queries + * + * @author widdis[at]gmail[dot]com + */ +public class WmiUtil { + private static final Logger LOG = LoggerFactory.getLogger(WmiUtil.class); + + public static final String DEFAULT_NAMESPACE = "ROOT\\CIMV2"; + + private static boolean securityInitialized = false; + + /** + * Enum for WMI queries for proper parsing from the returned VARIANT + */ + public enum ValueType { + STRING, UINT32, FLOAT, DATETIME + } + + /** + * For WMI queries requiring array input + */ + private static ValueType[] STRING_TYPE = { ValueType.STRING }; + private static ValueType[] UINT32_TYPE = { ValueType.UINT32 }; + private static ValueType[] FLOAT_TYPE = { ValueType.FLOAT }; + + /** + * Get a single Unsigned Integer value from WMI (as Long) + * + * @param namespace + * The namespace or null to use the default + * @param wmiClass + * The class to query + * @param property + * The property whose value to return + * @param whereClause + * A WQL where clause matching properties and keywords + * @return A Long containing the value of the requested property + */ + public static Long selectUint32From(String namespace, String wmiClass, String property, String whereClause) { + Map> result = queryWMI(namespace == null ? DEFAULT_NAMESPACE : namespace, property, + wmiClass, whereClause, UINT32_TYPE); + if (result.containsKey(property) && !result.get(property).isEmpty()) { + return (Long) result.get(property).get(0); + } + return 0L; + } + + /** + * Get multiple Unsigned Integer values from WMI (as Longs) + * + * @param namespace + * The namespace or null to use the default + * @param wmiClass + * The class to query + * @param properties + * A comma delimited list of properties whose value to return + * @param whereClause + * A WQL where clause matching properties and keywords + * @return A map, with each property as the key, containing Longs with the + * value of the requested properties. Each list's order corresponds + * to other lists. + */ + public static Map> selectUint32sFrom(String namespace, String wmiClass, String properties, + String whereClause) { + Map> result = queryWMI(namespace == null ? DEFAULT_NAMESPACE : namespace, properties, + wmiClass, whereClause, UINT32_TYPE); + HashMap> longMap = new HashMap<>(); + for (String key : result.keySet()) { + ArrayList longList = new ArrayList<>(); + for (Object obj : result.get(key)) { + longList.add((Long) obj); + } + longMap.put(key, longList); + } + return longMap; + } + + /** + * Get a single Float value from WMI + * + * @param namespace + * The namespace or null to use the default + * @param wmiClass + * The class to query + * @param property + * The property whose value to return + * @param whereClause + * A WQL where clause matching properties and keywords + * @return A Float containing the value of the requested property + */ + public static Float selectFloatFrom(String namespace, String wmiClass, String property, String whereClause) { + Map> result = queryWMI(namespace == null ? DEFAULT_NAMESPACE : namespace, property, + wmiClass, whereClause, FLOAT_TYPE); + if (result.containsKey(property) && !result.get(property).isEmpty()) { + return (Float) result.get(property).get(0); + } + return 0f; + } + + /** + * Get multiple Float values from WMI + * + * @param namespace + * The namespace or null to use the default + * @param wmiClass + * The class to query + * @param properties + * A comma delimited list of properties whose value to return + * @param whereClause + * A WQL where clause matching properties and keywords + * @return A map, with each property as the key, containing Floats with the + * value of the requested properties. Each list's order corresponds + * to other lists. + */ + public static Map> selectFloatsFrom(String namespace, String wmiClass, String properties, + String whereClause) { + Map> result = queryWMI(namespace == null ? DEFAULT_NAMESPACE : namespace, properties, + wmiClass, whereClause, FLOAT_TYPE); + HashMap> floatMap = new HashMap<>(); + for (String key : result.keySet()) { + ArrayList floatList = new ArrayList<>(); + for (Object obj : result.get(key)) { + floatList.add((Float) obj); + } + floatMap.put(key, floatList); + } + return floatMap; + } + + /** + * Get a single String value from WMI + * + * @param namespace + * The namespace or null to use the default + * @param wmiClass + * The class to query + * @param property + * The property whose value to return + * @param whereClause + * A WQL where clause matching properties and keywords + * @return A string containing the value of the requested property + */ + public static String selectStringFrom(String namespace, String wmiClass, String property, String whereClause) { + Map> result = queryWMI(namespace == null ? DEFAULT_NAMESPACE : namespace, property, + wmiClass, whereClause, STRING_TYPE); + if (result.containsKey(property) && !result.get(property).isEmpty()) { + return (String) result.get(property).get(0); + } + return ""; + } + + /** + * Get multiple String values from WMI + * + * @param namespace + * The namespace or null to use the default + * @param wmiClass + * The class to query + * @param properties + * A comma delimited list of properties whose value to return + * @param whereClause + * A WQL where clause matching properties and keywords + * @return A map, with each property as the key, containing strings with the + * value of the requested properties. Each list's order corresponds + * to other lists. + */ + public static Map> selectStringsFrom(String namespace, String wmiClass, String properties, + String whereClause) { + Map> result = queryWMI(namespace == null ? DEFAULT_NAMESPACE : namespace, properties, + wmiClass, whereClause, STRING_TYPE); + HashMap> strMap = new HashMap<>(); + for (String key : result.keySet()) { + ArrayList strList = new ArrayList<>(); + for (Object obj : result.get(key)) { + strList.add((String) obj); + } + strMap.put(key, strList); + } + return strMap; + } + + /** + * Get multiple individually typed values from WMI + * + * @param namespace + * The namespace or null to use the default + * @param wmiClass + * The class to query + * @param properties + * A comma delimited list of properties whose value to return + * @param whereClause + * A WQL where clause matching properties and keywords + * @param propertyTypes + * An array of types corresponding to the properties, or a single + * element array + * @return A map, with each property as the key, containing Objects with the + * value of the requested properties. Each list's order corresponds + * to other lists. The type of the objects is identified by the + * propertyTypes array. If only one propertyType is given, all + * Objects will have that type. It is the responsibility of the + * caller to cast the returned objects. + */ + public static Map> selectObjectsFrom(String namespace, String wmiClass, String properties, + String whereClause, ValueType[] propertyTypes) { + Map> result = queryWMI(namespace == null ? DEFAULT_NAMESPACE : namespace, properties, + wmiClass, whereClause, propertyTypes); + return result; + } + + /** + * Query WMI for values + * + * @param namespace + * The namespace to query + * @param properties + * A single property or comma-delimited list of properties to + * enumerate + * @param wmiClass + * The WMI class to query + * @param propertyTypes + * An array corresponding to the properties, containing the type + * of data being queried, to control how VARIANT is parsed + * @return A map, with the string value of each property as the key, + * containing a list of Objects which can be cast appropriately per + * valType. The order of objects in each list corresponds to the + * other lists. + */ + private static Map> queryWMI(String namespace, String properties, String wmiClass, + String whereClause, ValueType[] propertyTypes) { + // Set up empty map + Map> values = new HashMap<>(); + String[] props = properties.split(","); + for (int i = 0; i < props.length; i++) { + values.put(props[i], new ArrayList()); + } + + // Initialize COM + if (!initCOM()) { + Ole32.INSTANCE.CoUninitialize(); + return values; + } + + PointerByReference pSvc = new PointerByReference(); + if (!connectServer(namespace, pSvc)) { + Ole32.INSTANCE.CoUninitialize(); + return values; + } + WbemServices svc = new WbemServices(pSvc.getValue()); + + PointerByReference pEnumerator = new PointerByReference(); + if (!selectProperties(svc, pEnumerator, properties, wmiClass, whereClause)) { + svc.Release(); + Ole32.INSTANCE.CoUninitialize(); + return values; + } + EnumWbemClassObject enumerator = new EnumWbemClassObject(pEnumerator.getValue()); + + enumerateProperties(values, enumerator, props, propertyTypes); + + // Cleanup + enumerator.Release(); + svc.Release(); + Ole32.INSTANCE.CoUninitialize(); + return values; + } + + /* + * Below methods ported from: Getting WMI Data from Local Computer + * https://msdn.microsoft.com/en-us/library/aa390423(v=VS.85).aspx + * + * Steps 1 - 7 correspond to the above link. + */ + /** + * Initializes COM library and sets security to impersonate the local user + * + * @return true if COM successfull initialized + */ + private static boolean initCOM() { + // Step 1: -------------------------------------------------- + // Initialize COM. ------------------------------------------ + HRESULT hres = Ole32.INSTANCE.CoInitializeEx(null, Ole32.COINIT_MULTITHREADED); + if (COMUtils.FAILED(hres)) { + LOG.error(String.format("Failed to initialize COM library. Error code = 0x%08x", hres.intValue())); + return false; + } + if (securityInitialized) { + // Only run CoInitializeSecuirty once + return true; + } + // Step 2: -------------------------------------------------- + // Set general COM security levels -------------------------- + hres = Ole32.INSTANCE.CoInitializeSecurity(null, new NativeLong(-1), null, null, + Ole32.RPC_C_AUTHN_LEVEL_DEFAULT, Ole32.RPC_C_IMP_LEVEL_IMPERSONATE, null, Ole32.EOAC_NONE, null); + if (COMUtils.FAILED(hres) && hres.intValue() != Ole32.RPC_E_TOO_LATE) { + LOG.error(String.format("Failed to initialize security. Error code = 0x%08x", hres.intValue())); + Ole32.INSTANCE.CoUninitialize(); + return false; + } + securityInitialized = true; + return true; + } + + /** + * Obtains a locator to the WMI server and connects to the specified + * namespace + * + * @param namespace + * The namespace to connect to + * @param pSvc + * A pointer to receive an indirect to the WMI service + * @return true if successful; pSvc will contain an indirect pointer to the + * WMI service for future IWbemServices calls + */ + private static boolean connectServer(String namespace, PointerByReference pSvc) { + // Step 3: --------------------------------------------------- + // Obtain the initial locator to WMI ------------------------- + WbemLocator loc = WbemLocator.create(); + if (loc == null) { + return false; + } + // Step 4: ----------------------------------------------------- + // Connect to WMI through the IWbemLocator::ConnectServer method + // Connect to the namespace with the current user and obtain pointer + // pSvc to make IWbemServices calls. + HRESULT hres = loc.ConnectServer(new BSTR(namespace), null, null, null, null, null, null, pSvc); + if (COMUtils.FAILED(hres)) { + LOG.error(String.format("Could not connect to namespace %s. Error code = 0x%08x", namespace, + hres.intValue())); + loc.Release(); + Ole32.INSTANCE.CoUninitialize(); + return false; + } + LOG.debug("Connected to {} WMI namespace", namespace); + loc.Release(); + + // Step 5: -------------------------------------------------- + // Set security levels on the proxy ------------------------- + hres = Ole32.INSTANCE.CoSetProxyBlanket(pSvc.getValue(), Ole32.RPC_C_AUTHN_WINNT, Ole32.RPC_C_AUTHZ_NONE, null, + Ole32.RPC_C_AUTHN_LEVEL_CALL, Ole32.RPC_C_IMP_LEVEL_IMPERSONATE, null, Ole32.EOAC_NONE); + if (COMUtils.FAILED(hres)) { + LOG.error(String.format("Could not set proxy blanket. Error code = 0x%08x", hres.intValue())); + new WbemServices(pSvc.getValue()).Release(); + Ole32.INSTANCE.CoUninitialize(); + return false; + } + return true; + } + + /** + * Selects properties from WMI. Returns immediately, even while results are + * being retrieved; results may begun to be enumerated in the forward + * direction only. + * + * @param svc + * A WbemServices object to make the calls + * @param pEnumerator + * An enumerator to receive the results of the query + * @param properties + * A comma separated list of properties to query + * @param wmiClass + * The WMI class to query + * @param whereClause + * A WHERE clause to narrow the query + * @return True if successful. The enumerator will allow enumeration of + * results of the query + */ + private static boolean selectProperties(WbemServices svc, PointerByReference pEnumerator, String properties, + String wmiClass, String whereClause) { + // Step 6: -------------------------------------------------- + // Use the IWbemServices pointer to make requests of WMI ---- + String query = String.format("SELECT %s FROM %s %s", properties, wmiClass, + whereClause != null ? whereClause : ""); + LOG.debug("Query: {}", query); + HRESULT hres = svc.ExecQuery(new BSTR("WQL"), new BSTR(query), + new NativeLong( + EnumWbemClassObject.WBEM_FLAG_FORWARD_ONLY | EnumWbemClassObject.WBEM_FLAG_RETURN_IMMEDIATELY), + null, pEnumerator); + if (COMUtils.FAILED(hres)) { + LOG.error(String.format("Query '%s' failed. Error code = 0x%08x", query, hres.intValue())); + svc.Release(); + Ole32.INSTANCE.CoUninitialize(); + return false; + } + return true; + } + + /** + * Enumerate the results of a WMI query. This method is called while results + * are still being retrieved and may iterate in the forward direction only. + * + * @param values + * A map to hold the results of the query using the property as + * the key, and placing each enumerated result in a + * (common-index) list for each property + * @param enumerator + * The enumerator with the results + * @param properties + * Comma-delimited list of properties to retrieve + * @param propertyTypes + * An array of property types matching the properties or a single + * property type which will be used for all properties + */ + private static void enumerateProperties(Map> values, EnumWbemClassObject enumerator, + String[] properties, ValueType[] propertyTypes) { + if (propertyTypes.length > 1 && properties.length != propertyTypes.length) { + throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size."); + } + // Step 7: ------------------------------------------------- + // Get the data from the query in step 6 ------------------- + PointerByReference pclsObj = new PointerByReference(); + LongByReference uReturn = new LongByReference(0L); + while (enumerator.getPointer() != Pointer.NULL) { + HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1), + pclsObj, uReturn); + // Requested 1; if 0 objects returned, we're done + if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) { + // Enumerator will be released by calling method so no need to + // release it here. + return; + } + VARIANT.ByReference vtProp = new VARIANT.ByReference(); + + // Get the value of the properties + WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue()); + for (int p = 0; p < properties.length; p++) { + String property = properties[p]; + hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null); + + ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0]; + switch (propertyType) { + // WMI Longs will return as strings + case STRING: + values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue()); + break; + // WMI Uint32s will return as longs + case UINT32: // WinDef.LONG TODO improve in JNA 4.3 + values.get(property) + .add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue()); + break; + case FLOAT: + values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue()); + break; + case DATETIME: + // Read a string in format 20160513072950.782000-420 and + // parse to a long representing ms since eopch + values.get(property).add(ParseUtil.cimDateTimeToMillis(vtProp.stringValue())); + break; + default: + // Should never get here! If you get this exception you've + // added something to the enum without adding it here. Tsk. + throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString()); + } + OleAuto.INSTANCE.VariantClear(vtProp.getPointer()); + } + clsObj.Release(); + } + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `$T1_339` last assigned on line 487 could be null and is dereferenced at line 487. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void WmiUtil.enumerateProperties(HashMap,EnumWbemClassObject,java.lang.String[],oshi.util.platform.windows.WmiUtil$ValueType[]) + +### Procedure Id: +oshi.util.platform.windows.WmiUtil.enumerateProperties(java.util.HashMap,oshi.jna.platform.windows.C.5f6d66bc2e64d1f4d951514562ae9e5b + +### File: +oshi-core/src/main/java/oshi/util/platform/windows/WmiUtil.java + +### Key: +WmiUtil.java|enumerateProperties|NULL_DEREFERENCE + +### Node Key: +df64850a52332193bad448f8258efd03 + +### Hash: +9f2ca014e0532b2e6caed858e0e0207f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9677/instruction.md b/inferredbugs-9677/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..deda8ae894c489ce75d92613c4f72c0836ab00e6 --- /dev/null +++ b/inferredbugs-9677/instruction.md @@ -0,0 +1,314 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Oshi (https://github.com/dblock/oshi) + * + * Copyright (c) 2010 - 2016 The Oshi Project Team + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Maintainers: + * dblock[at]dblock[dot]org + * widdis[at]gmail[dot]com + * + * Contributors: + * https://github.com/dblock/oshi/graphs/contributors + */ +package oshi.hardware.platform.mac; + +import java.util.ArrayList; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.sun.jna.Native; +import com.sun.jna.platform.mac.SystemB.HostCpuLoadInfo; +import com.sun.jna.ptr.IntByReference; +import com.sun.jna.ptr.PointerByReference; + +import oshi.hardware.common.AbstractCentralProcessor; +import oshi.jna.platform.mac.SystemB; +import oshi.jna.platform.mac.SystemB.ProcTaskInfo; +import oshi.jna.platform.mac.SystemB.Timeval; +import oshi.util.ExecutingCommand; +import oshi.util.FormatUtil; +import oshi.util.platform.mac.SysctlUtil; + +/** + * A CPU. + * + * @author alessandro[at]perucchi[dot]org + * @author alessio.fachechi[at]gmail[dot]com + * @author widdis[at]gmail[dot]com + */ +public class MacCentralProcessor extends AbstractCentralProcessor { + private static final Logger LOG = LoggerFactory.getLogger(MacCentralProcessor.class); + + private int maxProc = 1024; + + /** + * Create a Processor + */ + public MacCentralProcessor() { + // Initialize class variables + initVars(); + // Initialize tick arrays + initTicks(); + // Set max processes + this.maxProc = SysctlUtil.sysctl("kern.maxproc", 0x1000); + + LOG.debug("Initialized Processor"); + } + + private void initVars() { + setVendor(SysctlUtil.sysctl("machdep.cpu.vendor", "")); + setName(SysctlUtil.sysctl("machdep.cpu.brand_string", "")); + setCpu64(SysctlUtil.sysctl("hw.cpu64bit_capable", 0) != 0); + int i = SysctlUtil.sysctl("machdep.cpu.stepping", -1); + setStepping(i < 0 ? "" : Integer.toString(i)); + i = SysctlUtil.sysctl("machdep.cpu.model", -1); + setModel(i < 0 ? "" : Integer.toString(i)); + i = SysctlUtil.sysctl("machdep.cpu.family", -1); + setFamily(i < 0 ? "" : Integer.toString(i)); + } + + /** + * Updates logical and physical processor counts from sysctl calls + */ + protected void calculateProcessorCounts() { + this.logicalProcessorCount = SysctlUtil.sysctl("hw.logicalcpu", 1); + this.physicalProcessorCount = SysctlUtil.sysctl("hw.physicalcpu", 1); + } + + /** + * {@inheritDoc} + */ + @Override + public long[] getSystemCpuLoadTicks() { + long[] ticks = new long[curTicks.length]; + int machPort = SystemB.INSTANCE.mach_host_self(); + HostCpuLoadInfo cpuLoadInfo = new HostCpuLoadInfo(); + if (0 != SystemB.INSTANCE.host_statistics(machPort, SystemB.HOST_CPU_LOAD_INFO, cpuLoadInfo, + new IntByReference(cpuLoadInfo.size()))) { + LOG.error("Failed to get System CPU ticks. Error code: " + Native.getLastError()); + return ticks; + } + // Switch order to match linux + ticks[0] = cpuLoadInfo.cpu_ticks[SystemB.CPU_STATE_USER]; + ticks[1] = cpuLoadInfo.cpu_ticks[SystemB.CPU_STATE_NICE]; + ticks[2] = cpuLoadInfo.cpu_ticks[SystemB.CPU_STATE_SYSTEM]; + ticks[3] = cpuLoadInfo.cpu_ticks[SystemB.CPU_STATE_IDLE]; + return ticks; + } + + /** + * {@inheritDoc} + */ + @Override + public long getSystemIOWaitTicks() { + // Data not available on OS X + return 0; + } + + /** + * {@inheritDoc} + */ + @Override + public long[] getSystemIrqTicks() { + // Data not available on OS X + return new long[2]; + }; + + /** + * {@inheritDoc} + */ + @Override + public double[] getSystemLoadAverage(int nelem) { + if (nelem < 1) { + throw new IllegalArgumentException("Must include at least one element."); + } + if (nelem > 3) { + LOG.warn("Max elements of SystemLoadAverage is 3. " + nelem + " specified. Ignoring extra."); + nelem = 3; + } + double[] average = new double[nelem]; + int retval = SystemB.INSTANCE.getloadavg(average, nelem); + if (retval < nelem) { + for (int i = Math.max(retval, 0); i < average.length; i++) { + average[i] = -1d; + } + } + return average; + } + + /** + * {@inheritDoc} + */ + @Override + public long[][] getProcessorCpuLoadTicks() { + long[][] ticks = new long[logicalProcessorCount][4]; + + int machPort = SystemB.INSTANCE.mach_host_self(); + + IntByReference procCount = new IntByReference(); + PointerByReference procCpuLoadInfo = new PointerByReference(); + IntByReference procInfoCount = new IntByReference(); + if (0 != SystemB.INSTANCE.host_processor_info(machPort, SystemB.PROCESSOR_CPU_LOAD_INFO, procCount, + procCpuLoadInfo, procInfoCount)) { + LOG.error("Failed to update CPU Load. Error code: " + Native.getLastError()); + return ticks; + } + + int[] cpuTicks = procCpuLoadInfo.getValue().getIntArray(0, procInfoCount.getValue()); + for (int cpu = 0; cpu < procCount.getValue(); cpu++) { + for (int j = 0; j < 4; j++) { + int offset = cpu * SystemB.CPU_STATE_MAX; + ticks[cpu][0] = FormatUtil.getUnsignedInt(cpuTicks[offset + SystemB.CPU_STATE_USER]); + ticks[cpu][1] = FormatUtil.getUnsignedInt(cpuTicks[offset + SystemB.CPU_STATE_NICE]); + ticks[cpu][2] = FormatUtil.getUnsignedInt(cpuTicks[offset + SystemB.CPU_STATE_SYSTEM]); + ticks[cpu][3] = FormatUtil.getUnsignedInt(cpuTicks[offset + SystemB.CPU_STATE_IDLE]); + } + } + return ticks; + } + + /** + * {@inheritDoc} + */ + @Override + public long getSystemUptime() { + Timeval tv = new Timeval(); + if (!SysctlUtil.sysctl("kern.boottime", tv)) { + return 0L; + } + // tv now points to a 16-bit timeval structure for boot time. + // First 8 bytes are seconds, second 8 bytes are microseconds (ignore) + return System.currentTimeMillis() / 1000 - tv.tv_sec; + } + + /** + * {@inheritDoc} + */ + @Override + public String getSystemSerialNumber() { + if (this.cpuSerialNumber == null) { + ArrayList hwInfo = ExecutingCommand.runNative("system_profiler SPHardwareDataType"); + // Mavericks and later + for (String checkLine : hwInfo) { + if (checkLine.contains("Serial Number (system)")) { + String[] snSplit = checkLine.split("\\s+"); + this.cpuSerialNumber = snSplit[snSplit.length - 1]; + break; + } + } + // Panther and later + if (this.cpuSerialNumber == null) { + for (String checkLine : hwInfo) { + if (checkLine.contains("r (system)")) { + String[] snSplit = checkLine.split("\\s+"); + this.cpuSerialNumber = snSplit[snSplit.length - 1]; + break; + } + } + } + if (this.cpuSerialNumber == null) { + this.cpuSerialNumber = "unknown"; + } + } + return this.cpuSerialNumber; + } + + @Override + public int getProcessCount() { + return SystemB.INSTANCE.proc_listpids(SystemB.PROC_ALL_PIDS, 0, null, 0) / SystemB.INT_SIZE; + } + + @Override + public int getThreadCount() { + int[] pids = new int[this.maxProc]; + int numberOfProcesses = SystemB.INSTANCE.proc_listpids(SystemB.PROC_ALL_PIDS, 0, pids, pids.length) + / SystemB.INT_SIZE; + int numberOfThreads = 0; + ProcTaskInfo taskInfo = new ProcTaskInfo(); + for (int i = 0; i < numberOfProcesses; i++) { + SystemB.INSTANCE.proc_pidinfo(pids[i], SystemB.PROC_PIDTASKINFO, 0, taskInfo, taskInfo.size()); + numberOfThreads += taskInfo.pti_threadnum; + } + return numberOfThreads; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `hwInfo` last assigned on line 196 could be null and is dereferenced at line 198. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String MacCentralProcessor.getSystemSerialNumber() + +### Procedure Id: +oshi.hardware.platform.mac.MacCentralProcessor.getSystemSerialNumber():java.lang.String.26a775fbad27ee1d9867a6a7e4b2366b + +### File: +src/main/java/oshi/hardware/platform/mac/MacCentralProcessor.java + +### Key: +MacCentralProcessor.java|getSystemSerialNumber|NULL_DEREFERENCE + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +df59744826b72acc0640f6ff3318facb + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9678/instruction.md b/inferredbugs-9678/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..320a0a6155683dfbcd3557831cd72293208f9beb --- /dev/null +++ b/inferredbugs-9678/instruction.md @@ -0,0 +1,315 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 42 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Oshi (https://github.com/oshi/oshi) + * + * Copyright (c) 2010 - 2018 The Oshi Project Team + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Maintainers: + * dblock[at]dblock[dot]org + * widdis[at]gmail[dot]com + * enrico.bianchi[at]gmail[dot]com + * + * Contributors: + * https://github.com/oshi/oshi/graphs/contributors + */ +package oshi.software.os.windows; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.sun.jna.platform.win32.Kernel32; //NOSONAR +import com.sun.jna.platform.win32.WinNT; + +import oshi.software.os.FileSystem; +import oshi.software.os.OSFileStore; +import oshi.util.ParseUtil; +import oshi.util.platform.windows.PdhUtil; +import oshi.util.platform.windows.WmiUtil; + +/** + * The Windows File System contains {@link OSFileStore}s which are a storage + * pool, device, partition, volume, concrete file system or other implementation + * specific means of file storage. In Windows, these are represented by a drive + * letter, e.g., "A:\" and "C:\" + * + * @author enrico[dot]bianchi[at]gmail[dot]com + */ +public class WindowsFileSystem implements FileSystem { + + private static final long serialVersionUID = 1L; + + private static final int BUFSIZE = 255; + + private static final int SEM_FAILCRITICALERRORS = 0x0001; + + private static final String HANDLE_COUNT_COUNTER = "\\Process(_Total)\\Handle Count"; + + public WindowsFileSystem() { + // Set error mode to fail rather than prompt for FLoppy/CD-Rom + Kernel32.INSTANCE.SetErrorMode(SEM_FAILCRITICALERRORS); + } + + /** + * Gets File System Information. + * + * @return An array of {@link OSFileStore} objects representing mounted + * volumes. May return disconnected volumes with + * {@link OSFileStore#getTotalSpace()} = 0. + */ + @Override + public OSFileStore[] getFileStores() { + // Create list to hold results + ArrayList result; + + // Begin with all the local volumes + result = getLocalVolumes(); + + // Build a map of existing mount point to OSFileStore + Map volumeMap = new HashMap<>(); + for (OSFileStore volume : result) { + volumeMap.put(volume.getMount(), volume); + } + + // Iterate through volumes in WMI and update description (if it exists) + // or add new if it doesn't (expected for network drives) + for (OSFileStore wmiVolume : getWmiVolumes()) { + if (volumeMap.containsKey(wmiVolume.getMount())) { + // If the volume is already in our list, update the name field + // using WMI's more verbose name + volumeMap.get(wmiVolume.getMount()).setName(wmiVolume.getName()); + } else { + // Otherwise add the new volume in its entirety + result.add(wmiVolume); + } + } + return result.toArray(new OSFileStore[result.size()]); + } + + /** + * Private method for getting all mounted local drives. + * + * @return A list of {@link OSFileStore} objects representing all local + * mounted volumes + */ + private ArrayList getLocalVolumes() { + ArrayList fs; + String volume; + String strFsType; + String strName; + String strMount; + WinNT.HANDLE hVol; + WinNT.LARGE_INTEGER userFreeBytes; + WinNT.LARGE_INTEGER totalBytes; + WinNT.LARGE_INTEGER systemFreeBytes; + boolean retVal; + char[] aVolume; + char[] fstype; + char[] name; + char[] mount; + + fs = new ArrayList<>(); + aVolume = new char[BUFSIZE]; + + hVol = Kernel32.INSTANCE.FindFirstVolume(aVolume, BUFSIZE); + if (hVol == WinNT.INVALID_HANDLE_VALUE) { + return fs; + } + + while (true) { + fstype = new char[16]; + name = new char[BUFSIZE]; + mount = new char[BUFSIZE]; + + userFreeBytes = new WinNT.LARGE_INTEGER(0L); + totalBytes = new WinNT.LARGE_INTEGER(0L); + systemFreeBytes = new WinNT.LARGE_INTEGER(0L); + + volume = new String(aVolume).trim(); + Kernel32.INSTANCE.GetVolumeInformation(volume, name, BUFSIZE, null, null, null, fstype, 16); + Kernel32.INSTANCE.GetVolumePathNamesForVolumeName(volume, mount, BUFSIZE, null); + Kernel32.INSTANCE.GetDiskFreeSpaceEx(volume, userFreeBytes, totalBytes, systemFreeBytes); + + strMount = new String(mount).trim(); + strName = new String(name).trim(); + strFsType = new String(fstype).trim(); + // Parse uuid from volume name + String uuid = ParseUtil.parseUuidOrDefault(volume, ""); + + if (!strMount.isEmpty()) { + // Volume is mounted + fs.add(new OSFileStore(String.format("%s (%s)", strName, strMount), volume, strMount, + getDriveType(strMount), strFsType, uuid, systemFreeBytes.getValue(), totalBytes.getValue())); + } + retVal = Kernel32.INSTANCE.FindNextVolume(hVol, aVolume, BUFSIZE); + if (!retVal) { + Kernel32.INSTANCE.FindVolumeClose(hVol); + break; + } + } + + return fs; + } + + /** + * Private method for getting logical drives listed in WMI. + * + * @return A list of {@link OSFileStore} objects representing all network + * mounted volumes + */ + private List getWmiVolumes() { + Map> drives; + List fs; + String volume; + long free; + long total; + + fs = new ArrayList<>(); + + drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk", + "Name,Description,ProviderName,FileSystem,Freespace,Size", null); + + for (int i = 0; i < drives.get("Name").size(); i++) { + free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L); + total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L); + String description = drives.get("Description").get(i); + + long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType", + "WHERE Name = '" + drives.get("Name").get(i) + "'"); + if (type != 4) { + char[] chrVolume = new char[BUFSIZE]; + Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume, + BUFSIZE); + volume = new String(chrVolume).trim(); + } else { + volume = drives.get("ProviderName").get(i); + String[] split = volume.split("\\\\"); + if (split.length > 1 && split[split.length - 1].length() > 0) { + description = split[split.length - 1]; + } + } + + fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume, + drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)), + drives.get("FileSystem").get(i), "", free, total)); + } + return fs; + } + + /** + * Private method for getting mounted drive type. + * + * @param drive + * Mounted drive + * @return A drive type description + */ + private String getDriveType(String drive) { + switch (Kernel32.INSTANCE.GetDriveType(drive)) { + case 2: + return "Removable drive"; + case 3: + return "Fixed drive"; + case 4: + return "Network drive"; + case 5: + return "CD-ROM"; + case 6: + return "RAM drive"; + default: + return "Unknown drive type"; + } + } + + @Override + public long getOpenFileDescriptors() { + if (!PdhUtil.isCounter(HANDLE_COUNT_COUNTER)) { + PdhUtil.addCounter(HANDLE_COUNT_COUNTER); + } + return PdhUtil.queryCounter(HANDLE_COUNT_COUNTER); + } + + @Override + public long getMaxFileDescriptors() { + // There is a theoretical limit of 65,536 user handles per session. + return 65536L; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `drives.get("ProviderName")` could be null and is dereferenced at line 190. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List WindowsFileSystem.getWmiVolumes() + +### Procedure Id: +oshi.software.os.windows.WindowsFileSystem.getWmiVolumes():java.util.List.1bc854c492ac8b9ae6e881d4b1a6b299 + +### File: +oshi-core/src/main/java/oshi/software/os/windows/WindowsFileSystem.java + +### Key: +WindowsFileSystem.java|getWmiVolumes|NULL_DEREFERENCE + +### Node Key: +ea7038770fb5c2885e81ef03bc5c8fa8 + +### Hash: +f8886b958c27dea1484d420f2abcbc4e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9682/instruction.md b/inferredbugs-9682/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..003c185fe35f7abc029bcb7cae0eeb7f1c8a2686 --- /dev/null +++ b/inferredbugs-9682/instruction.md @@ -0,0 +1,189 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 17 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Oshi (https://github.com/dblock/oshi) + * + * Copyright (c) 2010 - 2016 The Oshi Project Team + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Maintainers: + * dblock[at]dblock[dot]org + * widdis[at]gmail[dot]com + * + * Contributors: + * https://github.com/dblock/oshi/graphs/contributors + */ +package oshi.software.os.mac; + +import java.io.File; +import java.io.IOException; +import java.nio.file.FileStore; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +import javax.swing.filechooser.FileSystemView; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import oshi.jna.platform.mac.SystemB; +import oshi.jna.platform.mac.SystemB.Statfs; +import oshi.software.common.AbstractFileSystem; +import oshi.software.os.OSFileStore; + +/** + * The Mac File System contains {@link OSFileStore}s which are a storage pool, + * device, partition, volume, concrete file system or other implementation + * specific means of file storage. In Mac OS X, these are found in the /Volumes + * directory. + * + * @author widdis[at]gmail[dot]com + */ +public class MacFileSystem extends AbstractFileSystem { + + private static final Logger LOG = LoggerFactory.getLogger(MacFileSystem.class); + + // Regexp matcher for /dev/disk1 etc. + private static final Pattern localDisk = Pattern.compile("/dev/disk\\d"); + + /** + * Gets File System Information. + * + * @return An array of {@link OSFileStore} objects representing mounted + * volumes. May return disconnected volumes with + * {@link OSFileStore#getTotalSpace()} = 0. + */ + public OSFileStore[] getFileStores() { + // Use getfsstat to map filesystem paths to types + Map fstype = new HashMap<>(); + // Query with null to get total # required + int numfs = SystemB.INSTANCE.getfsstat64(null, 0, 0); + if (numfs > 0) { + // Create array to hold results + Statfs[] fs = new Statfs[numfs]; + // Fill array with results + numfs = SystemB.INSTANCE.getfsstat64(fs, numfs * (new Statfs()).size(), SystemB.MNT_NOWAIT); + for (int f = 0; f < numfs; f++) { + // Mount to name will match canonical path. + // Byte arrays are null-terminated strings + fstype.put(new String(fs[f].f_mntonname).trim(), new String(fs[f].f_fstypename).trim()); + } + } + // Now list file systems + List fsList = new ArrayList<>(); + FileSystemView fsv = FileSystemView.getFileSystemView(); + // Mac file systems are mounted in /Volumes + File volumes = new File("/Volumes"); + if (volumes != null) { + for (File f : volumes.listFiles()) { + // Everyone hates DS Store + if (f.getName().endsWith(".DS_Store")) { + continue; + } + String name = fsv.getSystemDisplayName(f); + String description = "Volume"; + String type = "unknown"; + try { + String cp = f.getCanonicalPath(); + if (cp.equals("/")) + name = name + " (/)"; + FileStore fs = Files.getFileStore(f.toPath()); + if (localDisk.matcher(fs.name()).matches()) { + description = "Local Disk"; + } + if (fs.name().startsWith("localhost:") || fs.name().startsWith("//")) { + description = "Network Drive"; + } + if (fstype.containsKey(cp)) { + type = fstype.get(cp); + } + } catch (IOException e) { + LOG.trace("", e); + continue; + } + fsList.add(new OSFileStore(name, description, type, f.getUsableSpace(), f.getTotalSpace())); + } + } + return fsList.toArray(new OSFileStore[fsList.size()]); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `volumes.listFiles()` could be null and is dereferenced at line 84. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +oshi.software.os.OSFileStore[] MacFileSystem.getFileStores() + +### Procedure Id: +oshi.software.os.mac.MacFileSystem.getFileStores():oshi.software.os.OSFileStore[].ceb3d93a281d82660baa8bbd773535ea + +### File: +src/main/java/oshi/software/os/mac/MacFileSystem.java + +### Key: +MacFileSystem.java|getFileStores|NULL_DEREFERENCE + +### Node Key: +24ee14a57e8a90ab88fc833015223ecd + +### Hash: +a0f78a5edc15463fc3941dec07b4c3e2 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9683/instruction.md b/inferredbugs-9683/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..323f82371d9843d30e5927709fb5fba46b43ff0e --- /dev/null +++ b/inferredbugs-9683/instruction.md @@ -0,0 +1,125 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * + */ +package oshi.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; + +/** + * @author alessandro[at]perucchi[dot]org + */ + +public class ExecutingCommand { + public static ArrayList runNative(String cmdToRun) { + Process p = null; + try { + p = Runtime.getRuntime().exec(cmdToRun); + p.waitFor(); + } catch (IOException e) { + return null; + } catch (InterruptedException e) { + return null; + } + + BufferedReader reader = new BufferedReader(new InputStreamReader( + p.getInputStream())); + String line = ""; + ArrayList sa = new ArrayList(); + try { + while ((line = reader.readLine()) != null) { + sa.add(line); + } + } catch (IOException e) { + return null; + } + return sa; + } + + public static String getFirstAnswer(String cmd2launch) { + ArrayList sa = ExecutingCommand + .runNative(cmd2launch); + + if (sa != null) + return sa.get(0); + else + return null; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.lang.Process` acquired to `p` by call to `exec(...)` at line 19 is not released after line 28. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +ArrayList ExecutingCommand.runNative(String) + +### Procedure Id: +oshi.util.ExecutingCommand.runNative(java.lang.String):java.util.ArrayList.b507e4ca6f09d011711a4ea8f149d42c + +### File: +src/main/java/oshi/util/ExecutingCommand.java + +### Key: +ExecutingCommand.java|runNative|RESOURCE_LEAK + +### Node Key: +3451cb93d845d85a147a6855623bf280 + +### Hash: +cc6556da7d4426a541049da8d057d75e + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9684/instruction.md b/inferredbugs-9684/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2093cbf5dc2775db849d5d82b807fe5e39b3ed30 --- /dev/null +++ b/inferredbugs-9684/instruction.md @@ -0,0 +1,276 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Oshi (https://github.com/dblock/oshi) + * + * Copyright (c) 2010 - 2016 The Oshi Project Team + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * dblock[at]dblock[dot]org + * alessandro[at]perucchi[dot]org + * widdis[at]gmail[dot]com + * https://github.com/dblock/oshi/graphs/contributors + */ +package oshi.hardware.platform.windows; + +import java.util.ArrayList; + +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonBuilderFactory; +import javax.json.JsonObject; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import oshi.hardware.Sensors; +import oshi.json.NullAwareJsonObjectBuilder; +import oshi.util.ExecutingCommand; + +public class WindowsSensors implements Sensors { + private static final Logger LOG = LoggerFactory.getLogger(WindowsSensors.class); + + private JsonBuilderFactory jsonFactory = Json.createBuilderFactory(null); + + @Override + public double getCpuTemperature() { + ArrayList hwInfo = ExecutingCommand.runNative("wmic Temperature get CurrentReading"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { + continue; + } else { + // If successful this line is in tenths of degrees Kelvin + try { + int tempK = Integer.parseInt(checkLine.trim()); + if (tempK > 0) { + return (tempK - 2715) / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + // Above query failed, try something else + hwInfo = ExecutingCommand + .runNative("wmic /namespace:\\\\root\\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currenttemperature")) { + continue; + } else { + // If successful this line is in tenths of degrees Kelvin + try { + int tempK = Integer.parseInt(checkLine.trim()); + if (tempK > 0) { + return (tempK - 2715) / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + // Above query failed, try something else + hwInfo = ExecutingCommand + .runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_TemperatureProbe get CurrentReading"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { + continue; + } else { + // If successful this line is in tenths of degrees Kelvin + try { + int tempK = Integer.parseInt(checkLine.trim()); + if (tempK > 0) { + return (tempK - 2715) / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + return 0d; + } + + @Override + public int[] getFanSpeeds() { + int[] fanSpeeds = new int[1]; + ArrayList hwInfo = ExecutingCommand + .runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Fan get DesiredSpeed"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("desiredspeed")) { + continue; + } else { + // If successful + try { + int rpm = Integer.parseInt(checkLine.trim()); + // Check if 8th bit (of 16 bit number) is set + if (rpm > 0) { + fanSpeeds[0] = rpm; + return fanSpeeds; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + return fanSpeeds; + } + + @Override + public double getCpuVoltage() { + ArrayList hwInfo = ExecutingCommand.runNative("wmic cpu get CurrentVoltage"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentvoltage")) { + continue; + } else { + // If successful this line is in tenths of volts + try { + int decivolts = Integer.parseInt(checkLine.trim()); + if (decivolts > 0) { + return decivolts / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + // Above query failed, try something else + hwInfo = ExecutingCommand.runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Processor get CurrentVoltage"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { + continue; + } else { + // If successful: + // If the eighth bit is set, bits 0-6 contain the voltage + // multiplied by 10. If the eighth bit is not set, then the bit + // setting in VoltageCaps represents the voltage value. + try { + int decivolts = Integer.parseInt(checkLine.trim()); + // Check if 8th bit (of 16 bit number) is set + if ((decivolts & 0x80) > 0 && decivolts > 0) { + return decivolts / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + // Above query failed, try something else + hwInfo = ExecutingCommand.runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Processor get VoltageCaps"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { + continue; + } else { + // If successful: + // Bits 0-3 of the field represent specific voltages that the + // processor socket can accept. + try { + int voltagebits = Integer.parseInt(checkLine.trim()); + // Return appropriate voltage + if ((voltagebits & 0x1) > 0) { + return 5.0; + } else if ((voltagebits & 0x2) > 0) { + return 3.3; + } else if ((voltagebits & 0x4) > 0) { + return 2.9; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + return 0d; + } + + @Override + public JsonObject toJSON() { + JsonArrayBuilder fanSpeedsArrayBuilder = jsonFactory.createArrayBuilder(); + for (int speed : getFanSpeeds()) { + fanSpeedsArrayBuilder.add(speed); + } + return NullAwareJsonObjectBuilder.wrap(jsonFactory.createObjectBuilder()).add("cpuTemperature", getCpuTemperature()) + .add("fanSpeeds", fanSpeedsArrayBuilder.build()).add("cpuVoltage", getCpuVoltage()).build(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `hwInfo` last assigned on line 102 could be null and is dereferenced at line 103. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int[] WindowsSensors.getFanSpeeds() + +### Procedure Id: +oshi.hardware.platform.windows.WindowsSensors.getFanSpeeds():int[].36294be608ec6758b5d80a009b04fa08 + +### File: +src/main/java/oshi/hardware/platform/windows/WindowsSensors.java + +### Key: +WindowsSensors.java|getFanSpeeds|NULL_DEREFERENCE + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +a5ddaf5bd77018bb06401ff7275cedb8 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9685/instruction.md b/inferredbugs-9685/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..de437ef224ce7dcac49c2c42d5bcbe5b0e25d661 --- /dev/null +++ b/inferredbugs-9685/instruction.md @@ -0,0 +1,278 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 19 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Oshi (https://github.com/dblock/oshi) + * + * Copyright (c) 2010 - 2016 The Oshi Project Team + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Maintainers: + * dblock[at]dblock[dot]org + * widdis[at]gmail[dot]com + * enrico.bianchi[at]gmail[dot]com + * + * Contributors: + * https://github.com/dblock/oshi/graphs/contributors + */ +package oshi.hardware.platform.windows; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import oshi.hardware.UsbDevice; +import oshi.hardware.common.AbstractUsbDevice; +import oshi.util.ExecutingCommand; +import oshi.util.ParseUtil; +import oshi.util.platform.windows.WmiUtil; + +public class WindowsUsbDevice extends AbstractUsbDevice { + + private static final long serialVersionUID = 1L; + + public WindowsUsbDevice(String name, String vendor, String serialNumber, UsbDevice[] connectedDevices) { + super(name, vendor, serialNumber, connectedDevices); + } + + /* + * Maps to store information using PNPDeviceID as the key + */ + private static Map nameMap = new HashMap<>(); + private static Map vendorMap = new HashMap<>(); + private static Map serialMap = new HashMap<>(); + private static Map> hubMap = new HashMap<>(); + + /** + * {@inheritDoc} + */ + public static UsbDevice[] getUsbDevices() { + // Start by collecting information for all PNP devices. While in theory + // these could be individually queried with a WHERE clause, grabbing + // them all up front incurs minimal memory overhead in exchange for + // faster access later + + // Clear maps + nameMap.clear(); + vendorMap.clear(); + serialMap.clear(); + + // Query Win32_PnPEntity to populate the maps + Map> usbMap = WmiUtil.selectStringsFrom(null, "Win32_PnPEntity", + "Name,Manufacturer,PnPDeviceID", null); + for (int i = 0; i < usbMap.get("Name").size(); i++) { + String pnpDeviceID = usbMap.get("PnPDeviceID").get(i); + nameMap.put(pnpDeviceID, usbMap.get("Name").get(i)); + if (usbMap.get("Manufacturer").get(i).length() > 0) { + vendorMap.put(pnpDeviceID, usbMap.get("Manufacturer").get(i)); + } + String serialNumber = ""; + // PNPDeviceID: USB\VID_203A&PID_FFF9&MI_00\6&18C4CF61&0&0000 + // Split by \ to get bus type (USB), VendorID/ProductID, other info + // As a temporary hack for a serial number, use last \-split field + // using 2nd &-split field if 4 fields + String[] idSplit = pnpDeviceID.split("\\\\"); + if (idSplit.length > 2) { + idSplit = idSplit[2].split("&"); + if (idSplit.length > 3) { + serialNumber = idSplit[1]; + } + } + if (serialNumber.length() > 0) { + serialMap.put(pnpDeviceID, serialNumber); + } + } + + // Disk drives or other physical media have a better way of getting + // serial number. Grab these and overwrite the temporary serial number + // assigned above if necessary + usbMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "PNPDeviceID,SerialNumber", null); + for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) { + serialMap.put(usbMap.get("PNPDeviceID").get(i), + ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i))); + } + usbMap = WmiUtil.selectStringsFrom(null, "Win32_PhysicalMedia", "PNPDeviceID,SerialNumber", null); + for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) { + serialMap.put(usbMap.get("PNPDeviceID").get(i), + ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i))); + } + + // Some USB Devices are hubs to which other devices connect. Knowing + // which ones are hubs will help later when walking the device tree + usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBHub", "PNPDeviceID", null); + List usbHubs = usbMap.get("PNPDeviceID"); + + // Now build the hub map linking USB devices with their parent hub. + // At the top of the device tree are USB Controllers. All USB hubs and + // devices descend from these. Because this query returns pointers it's + // just not practical to try to query via COM so we use a command line + // in order to get USB devices in a text format + ArrayList links = ExecutingCommand + .runNative("wmic path Win32_USBControllerDevice GET Antecedent,Dependent"); + // This iteration actually walks the device tree in order so while the + // antecedent of all USB devices is its controller, we know that if a + // device is not a hub that the last hub listed is its parent + // Devices with PNPDeviceID containing "ROOTHUB" are special and will be + // parents of the next item(s) + // This won't id chained hubs (other than the root hub) but is a quick + // hack rather than walking the entire device tree using the SetupDI API + // and good enough since exactly how a USB device is connected is + // theoretically transparent to the user + hubMap.clear(); + String currentHub = null; + String rootHub = null; + for (String s : links) { + String[] split = s.split("\\s+"); + if (split.length < 2) { + continue; + } + String antecedent = getId(split[0]); + String dependent = getId(split[1]); + // Ensure initial defaults are sane if something goes wrong + if (currentHub == null || rootHub == null) { + currentHub = antecedent; + rootHub = antecedent; + } + String parent; + if (dependent.contains("ROOT_HUB")) { + // This is a root hub, assign controller as parent; + parent = antecedent; + rootHub = dependent; + currentHub = dependent; + } else if (usbHubs.contains(dependent)) { + // This is a hub, assign parent as root hub + if (rootHub == null) { + rootHub = antecedent; + } + parent = rootHub; + currentHub = dependent; + } else { + // This is not a hub, assign parent as previous hub + if (currentHub == null) { + currentHub = antecedent; + } + parent = currentHub; + } + // Finally add the parent/child linkage to the map + if (!hubMap.containsKey(parent)) { + hubMap.put(parent, new ArrayList()); + } + hubMap.get(parent).add(dependent); + } + + // Finally we simply get the device IDs of the USB Controllers. These + // will recurse downward to devices as needed + usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBController", "PNPDeviceID", null); + List controllerDevices = new ArrayList(); + for (String controllerDeviceID : usbMap.get("PNPDeviceID")) { + controllerDevices.add(getDeviceAndChildren(controllerDeviceID)); + } + return controllerDevices.toArray(new UsbDevice[controllerDevices.size()]); + } + + /** + * Recursively creates WindowsUsbDevices by fetching information from maps + * to populate fields + * + * @param hubDeviceID + * The PNPdeviceID of this device. + * @return A WindowsUsbDevice corresponding to this deviceID + */ + private static WindowsUsbDevice getDeviceAndChildren(String hubDeviceID) { + List pnpDeviceIDs = hubMap.getOrDefault(hubDeviceID, new ArrayList<>()); + List usbDevices = new ArrayList<>(); + for (String pnpDeviceID : pnpDeviceIDs) { + usbDevices.add(getDeviceAndChildren(pnpDeviceID)); + } + return new WindowsUsbDevice(nameMap.getOrDefault(hubDeviceID, ""), vendorMap.getOrDefault(hubDeviceID, ""), + serialMap.getOrDefault(hubDeviceID, ""), usbDevices.toArray(new UsbDevice[usbDevices.size()])); + } + + /** + * Parses DeviceID from CIM_USBController text + * + * @param string + * Text of form (stuff)DeviceID="(ID)" + * @return The parsed device ID + */ + private static String getId(String s) { + String[] split = s.split("\""); + return split.length < 2 ? "" : split[1]; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `links` last assigned on line 113 could be null and is dereferenced at line 126. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +oshi.hardware.UsbDevice[] WindowsUsbDevice.getUsbDevices() + +### Procedure Id: +oshi.hardware.platform.windows.WindowsUsbDevice.getUsbDevices():oshi.hardware.UsbDevice[].a7bf038a3b11066a6bbcb92659f282b6 + +### File: +src/main/java/oshi/hardware/platform/windows/WindowsUsbDevice.java + +### Key: +WindowsUsbDevice.java|getUsbDevices|NULL_DEREFERENCE + +### Node Key: +eae2ee1cdadb82e549c2a1b7c9bd0e3a + +### Hash: +9c8b4f3ceaab94fe823a14a424368dd1 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9733/instruction.md b/inferredbugs-9733/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2d29cada11f000311b23c82213845995e05841dd --- /dev/null +++ b/inferredbugs-9733/instruction.md @@ -0,0 +1,1179 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jboss-modules +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * JBoss, Home of Professional Open Source. + * Copyright 2010, Red Hat, Inc., and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This 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 software 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 software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.jboss.modules; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.net.URL; +import java.net.URLConnection; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.ServiceLoader; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; + +import org.jboss.modules.filter.PathFilter; +import org.jboss.modules.filter.PathFilters; +import org.jboss.modules.log.ModuleLogger; +import org.jboss.modules.log.NoopModuleLogger; + +import __redirected.__JAXPRedirected; + +import static org.jboss.modules.Linkage.State.*; + +/** + * A module is a unit of classes and other resources, along with the specification of what is imported and exported + * by this module from and to other modules. Modules are created by {@link ModuleLoader}s which build modules from + * various configuration information and resource roots. + * + * @author David M. Lloyd + * @author John Bailey + * @author Flavia Rainone + * @author Jason T. Greene + * @author thomas.diesler@jboss.com + * + * @apiviz.landmark +*/ +public final class Module { + + private static final AtomicReference BOOT_MODULE_LOADER = new AtomicReference(); + + static { + AccessController.doPrivileged(new PrivilegedAction() { + public Void run() { + try { + URL.setURLStreamHandlerFactory(new ModularURLStreamHandlerFactory()); + } catch (Throwable t) { + // todo log a warning or something + } + try { + URLConnection.setContentHandlerFactory(new ModularContentHandlerFactory()); + } catch (Throwable t) { + // todo log a warning or something + } + + __JAXPRedirected.initAll(); + + return null; + } + }); + + final String pkgsString = AccessController.doPrivileged(new PropertyReadAction("jboss.modules.system.pkgs")); + final List list = new ArrayList(); + list.add("java."); + list.add("sun.reflect."); + list.add("__redirected."); + if (pkgsString != null) { + int i; + int nc = -1; + do { + i = nc + 1; + nc = pkgsString.indexOf(',', i); + String part; + if (nc == -1) { + part = pkgsString.substring(i).trim(); + } else { + part = pkgsString.substring(i, nc).trim(); + } + if (part.length() > 0) { + list.add((part + ".").intern()); + } + } while (nc != -1); + } + systemPackages = list.toArray(list.toArray(new String[list.size()])); + final ListIterator iterator = list.listIterator(); + // http://youtrack.jetbrains.net/issue/IDEA-72097 + //noinspection WhileLoopReplaceableByForEach + while (iterator.hasNext()) { + iterator.set(iterator.next().replace('.', '/')); + } + systemPaths = list.toArray(list.toArray(new String[list.size()])); + } + + // static properties + + static final String[] systemPackages; + static final String[] systemPaths; + + /** + * The system-wide module logger, which may be changed via {@link #setModuleLogger(org.jboss.modules.log.ModuleLogger)}. + */ + static volatile ModuleLogger log = NoopModuleLogger.getInstance(); + + // immutable properties + + /** + * The identifier of this module. + */ + private final ModuleIdentifier identifier; + /** + * The name of the main class, if any (may be {@code null}). + */ + private final String mainClassName; + /** + * The module class loader for this module. + */ + private final ModuleClassLoader moduleClassLoader; + /** + * The module loader which created this module. + */ + private final ModuleLoader moduleLoader; + /** + * This reference exists solely to prevent the {@code FutureModule} from getting GC'd prematurely. + */ + @SuppressWarnings({ "unused" }) + private final Object myKey; + /** + * The fallback local loader, if any is defined. + */ + private final LocalLoader fallbackLoader; + + // mutable properties + + /** + * The linkage state. + */ + private volatile Linkage linkage = Linkage.NONE; + + // private constants + + private static final RuntimePermission GET_CLASS_LOADER = new RuntimePermission("getClassLoader"); + private static final RuntimePermission GET_BOOT_MODULE_LOADER = new RuntimePermission("getBootModuleLoader"); + private static final RuntimePermission ACCESS_MODULE_LOGGER = new RuntimePermission("accessModuleLogger"); + private static final RuntimePermission ADD_CONTENT_HANDLER_FACTORY = new RuntimePermission("addContentHandlerFactory"); + private static final RuntimePermission ADD_URL_STREAM_HANDLER_FACTORY = new RuntimePermission("addURLStreamHandlerFactory"); + + /** + * Construct a new instance from a module specification. + * + * @param spec the module specification + * @param moduleLoader the module loader + * @param myKey the key to keep a strong reference to + */ + Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) { + this.moduleLoader = moduleLoader; + this.myKey = myKey; + + // Initialize state from the spec. + identifier = spec.getModuleIdentifier(); + mainClassName = spec.getMainClass(); + fallbackLoader = spec.getFallbackLoader(); + //noinspection ThisEscapedInObjectConstruction + final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); + final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); + ModuleClassLoader moduleClassLoader = null; + if (factory != null) moduleClassLoader = factory.create(configuration); + if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); + this.moduleClassLoader = moduleClassLoader; + } + + LocalLoader getFallbackLoader() { + return fallbackLoader; + } + + Dependency[] getDependencies() { + return linkage.getSourceList(); + } + + ModuleClassLoader getClassLoaderPrivate() { + return moduleClassLoader; + } + + /** + * Get an exported resource from a specific root in this module. + * + * @param rootPath the module root to search + * @param resourcePath the path of the resource + * @return the resource + */ + public Resource getExportedResource(final String rootPath, final String resourcePath) { + return moduleClassLoader.loadResourceLocal(rootPath, resourcePath); + } + + /** + * Run a module's main class, if any. + * + * @param args the arguments to pass + * @throws NoSuchMethodException if there is no main method + * @throws InvocationTargetException if the main method failed + * @throws ClassNotFoundException if the main class is not found + */ + public void run(final String[] args) throws NoSuchMethodException, InvocationTargetException, ClassNotFoundException { + try { + if (mainClassName == null) { + throw new NoSuchMethodException("No main class defined for " + this); + } + final Class mainClass = moduleClassLoader.loadClass(mainClassName); + final Method mainMethod = mainClass.getMethod("main", String[].class); + final int modifiers = mainMethod.getModifiers(); + if (! Modifier.isStatic(modifiers)) { + throw new NoSuchMethodException("Main method is not static for " + this); + } + final ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(moduleClassLoader); + // ignore the return value + mainMethod.invoke(null, new Object[] {args}); + } finally { + Thread.currentThread().setContextClassLoader(previousClassLoader); + } + } catch (IllegalAccessException e) { + // unexpected; should be public + throw new IllegalAccessError(e.getMessage()); + } + } + + /** + * Get this module's identifier. + * + * @return the identifier + */ + public ModuleIdentifier getIdentifier() { + return identifier; + } + + /** + * Get the module loader which created this module. + * + * @return the module loader of this module + */ + public ModuleLoader getModuleLoader() { + return moduleLoader; + } + + /** + * Load a service loader from this module. + * + * @param serviceType the service type class + * @param the service type + * @return the service loader + */ + public ServiceLoader loadService(Class serviceType) { + return ServiceLoader.load(serviceType, moduleClassLoader); + } + + /** + * Load a service loader from a module in the caller's module loader. The caller's + * module loader refers to the loader of the module of the class that calls this method. + * Note that {@link #loadService(Class)} is more efficient since it does not need to crawl + * the stack. + * + * @param the the service type + * @param identifier the module identifier containing the service loader + * @param serviceType the service type class + * @return the loaded service from the caller's module + * @throws ModuleLoadException if the named module failed to load + */ + public static ServiceLoader loadServiceFromCallerModuleLoader(ModuleIdentifier identifier, Class serviceType) throws ModuleLoadException { + return getCallerModuleLoader().loadModule(identifier).loadService(serviceType); + } + + /** + * Get the class loader for a module. The class loader can be used to access non-exported classes and + * resources of the module. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("getClassLoader") permission to verify access to the class loader. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @return the module class loader + */ + public ModuleClassLoader getClassLoader() { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(GET_CLASS_LOADER); + } + return moduleClassLoader; + } + + /** + * Get all the paths exported by this module. + * + * @return the paths that are exported by this module + */ + public Set getExportedPaths() { + return Collections.unmodifiableSet(getPathsUnchecked(true).keySet()); + } + + /** + * Get the module for a loaded class, or {@code null} if the class did not come from any module. + * + * @param clazz the class + * @return the module it came from + */ + public static Module forClass(Class clazz) { + final ClassLoader cl = clazz.getClassLoader(); + return forClassLoader(cl, false); + } + + /** + * Get the module for a class loader, or {@code null} if the class loader is not associated with any module. If + * the class loader is unknown, it is possible to check the parent class loader up the chain, and so on until a module is found. + * + * @param cl the class loader + * @param search {@code true} to search up the delegation chain + * @return the associated module + */ + public static Module forClassLoader(ClassLoader cl, boolean search) { + if (cl instanceof ModuleClassLoader) { + return ((ModuleClassLoader) cl).getModule(); + } else if (search) { + return forClassLoader(cl.getParent(), true); + } else { + return null; + } + } + + /** + * Gets the boot module loader. The boot module loader is the + * initial loader that is established by the module framework. It typically + * is based off of the environmental module path unless it is overridden by + * specifying a different class name for the {@code boot.module.loader} system + * property. + * + * @return the boot module loader + */ + public static ModuleLoader getBootModuleLoader() { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(GET_BOOT_MODULE_LOADER); + } + ModuleLoader loader; + while ((loader = BOOT_MODULE_LOADER.get()) == null) { + loader = DefaultBootModuleLoaderHolder.INSTANCE; + if (BOOT_MODULE_LOADER.compareAndSet(null, loader)) { + break; + } + // get it again + } + return loader; + } + + static void initBootModuleLoader(ModuleLoader loader) { + BOOT_MODULE_LOADER.set(loader); + } + + /** + * Gets the current module loader. The current module loader is the + * loader of the module from the calling class. Note that this method + * must crawl the stack to determine this, so other mechanisms are more + * efficient. + * + * @return the current module loader, or {@code null} if this method is called outside of a module + */ + public static ModuleLoader getCallerModuleLoader() { + Module callerModule = getCallerModule(); + return callerModule == null ? null : callerModule.getModuleLoader(); + } + + /** + * Get the current thread's context module loader. This loader is the one which defined the module + * whose class loader is, or is a parent of, the thread's current context class loader. If there is none, + * then {@code null} is returned. + * + * @return the module loader, or {@code null} if none is set + */ + public static ModuleLoader getContextModuleLoader() { + return Module.forClassLoader(Thread.currentThread().getContextClassLoader(), true).getModuleLoader(); + } + + /** + * Get a module from the current module loader. Note that this must crawl the + * stack to determine this, so other mechanisms are more efficient. + * @see #getCallerModuleLoader() + * + * @param identifier the module identifier + * @return the module + * @throws ModuleLoadException if the module could not be loaded + */ + public static Module getModuleFromCallerModuleLoader(final ModuleIdentifier identifier) throws ModuleLoadException { + return getCallerModuleLoader().loadModule(identifier); + } + + /** + * Get the caller's module. The caller's module is the module containing the method that calls this + * method. Note that this method crawls the stack so other ways of obtaining the + * module are more efficient. + * + * @return the current module + */ + public static Module getCallerModule() { + return forClass(CallerContext.getCallingClass()); + } + + /** + * Get the module with the given identifier from the module loader used by this module. + * + * @param identifier the module identifier + * @return the module + * @throws ModuleLoadException if an error occurs + */ + public Module getModule(final ModuleIdentifier identifier) throws ModuleLoadException { + return moduleLoader.loadModule(identifier); + } + + /** + * Load a class from a module in the system module loader. + * + * @see #getBootModuleLoader() + * + * @param moduleIdentifier the identifier of the module from which the class + * should be loaded + * @param className the class name to load + * @return the class + * @throws ModuleLoadException if the module could not be loaded + * @throws ClassNotFoundException if the class could not be loaded + */ + public static Class loadClassFromBootModuleLoader(final ModuleIdentifier moduleIdentifier, final String className) + throws ModuleLoadException, ClassNotFoundException { + return Class.forName(className, true, getBootModuleLoader().loadModule(moduleIdentifier).getClassLoader()); + } + + /** + * Load a class from a module in the caller's module loader. + * + * @see #getCallerModuleLoader() + * + * @param moduleIdentifier the identifier of the module from which the class + * should be loaded + * @param className the class name to load + * @return the class + * @throws ModuleLoadException if the module could not be loaded + * @throws ClassNotFoundException if the class could not be loaded + */ + public static Class loadClassFromCallerModuleLoader(final ModuleIdentifier moduleIdentifier, final String className) + throws ModuleLoadException, ClassNotFoundException { + return Class.forName(className, true, getModuleFromCallerModuleLoader(moduleIdentifier).getClassLoader()); + } + + /** + * Load a class from a local loader. + * + * @param className the class name + * @param exportsOnly {@code true} to only load if the class is exported, {@code false} to load any class + * @param resolve {@code true} to resolve the class after definition + * @return the class + */ + Class loadModuleClass(final String className, final boolean exportsOnly, final boolean resolve) { + for (String s : systemPackages) { + if (className.startsWith(s)) { + try { + return moduleClassLoader.loadClass(className, resolve); + } catch (ClassNotFoundException e) { + return null; + } + } + } + final String path = pathOfClass(className); + final Map> paths = getPathsUnchecked(exportsOnly); + final List loaders = paths.get(path); + if (loaders != null) { + Class clazz; + for (LocalLoader loader : loaders) { + clazz = loader.loadClassLocal(className, resolve); + if (clazz != null) { + return clazz; + } + } + } + final LocalLoader fallbackLoader = this.fallbackLoader; + if (fallbackLoader != null) { + return fallbackLoader.loadClassLocal(className, resolve); + } + return null; + } + + /** + * Load a resource from a local loader. + * + * @param name the resource name + * @param exportsOnly {@code true} to only consider exported resources + * @return the resource URL, or {@code null} if not found + */ + URL getResource(final String name, final boolean exportsOnly) { + final String canonPath = PathUtils.canonicalize(name); + for (String s : Module.systemPaths) { + if (canonPath.startsWith(s)) { + return moduleClassLoader.getResource(canonPath); + } + } + log.trace("Attempting to find resource %s in %s", canonPath, this); + final String path = pathOf(canonPath); + final Map> paths = getPathsUnchecked(exportsOnly); + final List loaders = paths.get(path); + if (loaders != null) { + for (LocalLoader loader : loaders) { + final List resourceList = loader.loadResourceLocal(canonPath); + for (Resource resource : resourceList) { + return resource.getURL(); + } + } + } + final LocalLoader fallbackLoader = this.fallbackLoader; + if (fallbackLoader != null) { + final List resourceList = fallbackLoader.loadResourceLocal(canonPath); + for (Resource resource : resourceList) { + return resource.getURL(); + } + } + return null; + } + + /** + * Load all resources of a given name from a local loader. + * + * @param name the resource name + * @param exportsOnly {@code true} to only consider exported resources + * @return the enumeration of all the matching resource URLs (may be empty) + */ + Enumeration getResources(final String name, final boolean exportsOnly) { + final String canonPath = PathUtils.canonicalize(name); + for (String s : Module.systemPaths) { + if (canonPath.startsWith(s)) { + try { + return moduleClassLoader.getResources(canonPath); + } catch (IOException e) { + return ConcurrentClassLoader.EMPTY_ENUMERATION; + } + } + } + log.trace("Attempting to find all resources %s in %s", canonPath, this); + final String path = pathOf(canonPath); + final Map> paths = getPathsUnchecked(exportsOnly); + final List loaders = paths.get(path); + + final List list = new ArrayList(); + if (loaders != null) { + for (LocalLoader loader : loaders) { + final List resourceList = loader.loadResourceLocal(canonPath); + for (Resource resource : resourceList) { + list.add(resource.getURL()); + } + } + } + final LocalLoader fallbackLoader = this.fallbackLoader; + if (fallbackLoader != null) { + final List resourceList = fallbackLoader.loadResourceLocal(canonPath); + for (Resource resource : resourceList) { + list.add(resource.getURL()); + } + } + + return list.size() == 0 ? ConcurrentClassLoader.EMPTY_ENUMERATION : Collections.enumeration(list); + } + + /** + * Get an exported resource URL. + * + * @param name the resource name + * @return the resource, or {@code null} if it was not found + */ + public URL getExportedResource(final String name) { + return getResource(name, true); + } + + /** + * Get all exported resource URLs for a resource name. + * + * @param name the resource name + * @return the resource URLs + */ + public Enumeration getExportedResources(final String name) { + return getResources(name, true); + } + + /** + * Get the path name of a class. + * + * @param className the binary name of the class + * @return the parent path + */ + static String pathOfClass(final String className) { + final String resourceName = className.replace('.', '/'); + final String path; + final int idx = resourceName.lastIndexOf('/'); + if (idx > -1) { + path = resourceName.substring(0, idx); + } else { + path = ""; + } + return path; + } + + /** + * Get the path name of a resource. + * + * @param resourceName the resource name + * @return the parent path + */ + static String pathOf(final String resourceName) { + final String path; + if (resourceName.indexOf('/') == 0) { + return pathOf(resourceName.substring(1)); + } + final int idx = resourceName.lastIndexOf('/'); + if (idx > -1) { + path = resourceName.substring(0, idx); + } else { + path = ""; + } + return path; + } + + /** + * Get the file name of a class. + * + * @param className the class name + * @return the name of the corresponding class file + */ + static String fileNameOfClass(final String className) { + return className.replace('.', '/') + ".class"; + } + + /** + * Get the string representation of this module. + * + * @return the string representation + */ + @Override + public String toString() { + return "Module \"" + identifier + "\"" + " from " + moduleLoader.toString(); + } + + /** + * Get the logger used by the module system. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("accessModuleLogger") permission to verify access to the module logger. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @return the module logger + */ + public static ModuleLogger getModuleLogger() { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(ACCESS_MODULE_LOGGER); + } + return log; + } + + /** + * Change the logger used by the module system. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("accessModuleLogger") permission to verify access to the module logger. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @param logger the new logger, must not be {@code null} + */ + public static void setModuleLogger(final ModuleLogger logger) { + if (logger == null) { + throw new IllegalArgumentException("logger is null"); + } + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(ACCESS_MODULE_LOGGER); + } + logger.greeting(); + log = logger; + } + + /** + * Return the start time in millis when Module.class was loaded. + * + * @return start time of Module.class load + */ + public static long getStartTime() { + return StartTimeHolder.START_TIME; + } + + /** + * Register an additional module which contains content handlers. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("addContentHandlerFactory") permission to verify access. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @param module the module to add + */ + public static void registerContentHandlerFactoryModule(Module module) { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(ADD_CONTENT_HANDLER_FACTORY); + } + ModularContentHandlerFactory.addHandlerModule(module); + } + + /** + * Register an additional module which contains URL handlers. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("addURLStreamHandlerFactory") permission to verify access. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @param module the module to add + */ + public static void registerURLStreamHandlerFactoryModule(Module module) { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(ADD_URL_STREAM_HANDLER_FACTORY); + } + ModularURLStreamHandlerFactory.addHandlerModule(module); + } + + // Linking and resolution + + static final class Visited { + private final Module module; + private final FastCopyHashSet filters; + private final int hashCode; + + Visited(final Module module, final FastCopyHashSet filters) { + this.module = module; + this.filters = filters; + hashCode = filters.hashCode() * 13 + module.hashCode(); + } + + public int hashCode() { + return hashCode; + } + + public boolean equals(Object other) { + return other instanceof Visited && equals((Visited)other); + } + + public boolean equals(Visited other) { + return this == other || other != null && module == other.module && filters.equals(other.filters); + } + } + + long addPaths(Dependency[] dependencies, Map> map, FastCopyHashSet filterStack, Set visited) throws ModuleLoadException { + long subtract = 0L; + moduleLoader.incScanCount(); + for (Dependency dependency : dependencies) { + if (dependency instanceof ModuleDependency) { + final ModuleDependency moduleDependency = (ModuleDependency) dependency; + final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); + final ModuleIdentifier id = moduleDependency.getIdentifier(); + final Module module; + + try { + long pauseStart = Metrics.getCurrentCPUTime(); + try { + module = moduleLoader.preloadModule(id); + } finally { + subtract += Metrics.getCurrentCPUTime() - pauseStart; + } + } catch (ModuleLoadException ex) { + if (moduleDependency.isOptional()) { + continue; + } else { + throw ex; + } + } + if (module == null) { + if (!moduleDependency.isOptional()) { + throw new ModuleNotFoundException(id.toString()); + } + continue; + } + + final PathFilter importFilter = dependency.getImportFilter(); + filterStack.add(importFilter); + subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited); + filterStack.remove(importFilter); + } else if (dependency instanceof ModuleClassLoaderDependency) { + final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; + final LocalLoader localLoader = classLoaderDependency.getLocalLoader(); + final PathFilter importFilter = classLoaderDependency.getImportFilter(); + final Set paths = classLoaderDependency.getPaths(); + for (String path : paths) { + if (importFilter.accept(path)) { + List list = map.get(path); + if (list == null) { + map.put(path, list = new ArrayList()); + list.add(localLoader); + } else if (! list.contains(localLoader)) { + list.add(localLoader); + } + } + } + } else if (dependency instanceof LocalDependency) { + final LocalDependency localDependency = (LocalDependency) dependency; + final LocalLoader localLoader = localDependency.getLocalLoader(); + final PathFilter importFilter = localDependency.getImportFilter(); + final Set paths = localDependency.getPaths(); + for (String path : paths) { + if (importFilter.accept(path)) { + List list = map.get(path); + if (list == null) { + map.put(path, list = new ArrayList()); + list.add(localLoader); + } else if (! list.contains(localLoader)) { + list.add(localLoader); + } + } + } + } + // else unknown dep type so just skip + } + return subtract; + } + + long addExportedPaths(Dependency[] dependencies, Map> map, FastCopyHashSet filterStack, Set visited) throws ModuleLoadException { + if (!visited.add(new Visited(this, filterStack))) { + return 0L; + } + long subtract = 0L; + moduleLoader.incScanCount(); + for (Dependency dependency : dependencies) { + final PathFilter exportFilter = dependency.getExportFilter(); + // skip non-exported dependencies altogether + if (exportFilter != PathFilters.rejectAll()) { + if (dependency instanceof ModuleDependency) { + final ModuleDependency moduleDependency = (ModuleDependency) dependency; + final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); + final ModuleIdentifier id = moduleDependency.getIdentifier(); + final Module module; + + try { + long pauseStart = Metrics.getCurrentCPUTime(); + try { + module = moduleLoader.preloadModule(id); + } finally { + subtract += Metrics.getCurrentCPUTime() - pauseStart; + } + } catch (ModuleLoadException ex) { + if (moduleDependency.isOptional()) { + continue; + } else { + throw ex; + } + } + if (module == null) { + if (!moduleDependency.isOptional()) { + throw new ModuleNotFoundException(id.toString()); + } + continue; + } + + final PathFilter importFilter = dependency.getImportFilter(); + if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) { + subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited); + } else { + final FastCopyHashSet clone = filterStack.clone(); + clone.add(importFilter); + clone.add(exportFilter); + subtract += module.addExportedPaths(module.getDependencies(), map, clone, visited); + } + } else if (dependency instanceof ModuleClassLoaderDependency) { + final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; + final LocalLoader localLoader = classLoaderDependency.getLocalLoader(); + final Set paths = classLoaderDependency.getPaths(); + for (String path : paths) { + boolean accept = true; + for (Object filter : filterStack.getRawArray()) { + if (filter != null && ! ((PathFilter)filter).accept(path)) { + accept = false; break; + } + } + if (accept && classLoaderDependency.getImportFilter().accept(path) && classLoaderDependency.getExportFilter().accept(path)) { + List list = map.get(path); + if (list == null) { + map.put(path, list = new ArrayList(1)); + list.add(localLoader); + } else if (! list.contains(localLoader)) { + list.add(localLoader); + } + } + } + } else if (dependency instanceof LocalDependency) { + final LocalDependency localDependency = (LocalDependency) dependency; + final LocalLoader localLoader = localDependency.getLocalLoader(); + final Set paths = localDependency.getPaths(); + for (String path : paths) { + boolean accept = true; + for (Object filter : filterStack.getRawArray()) { + if (filter != null && ! ((PathFilter)filter).accept(path)) { + accept = false; break; + } + } + if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) { + List list = map.get(path); + if (list == null) { + map.put(path, list = new ArrayList(1)); + list.add(localLoader); + } else if (! list.contains(localLoader)) { + list.add(localLoader); + } + } + } + } + // else unknown dep type so just skip + } + } + return subtract; + } + + Map> getPaths(final boolean exports) throws ModuleLoadException { + Linkage linkage = this.linkage; + Linkage.State state = linkage.getState(); + if (state.compareTo(exports ? LINKED_EXPORTS : LINKED) >= 0) { + return linkage.getPaths(exports); + } + // slow path loop + boolean intr = false; + try { + for (;;) { + synchronized (this) { + linkage = this.linkage; + state = linkage.getState(); + while (state == (exports ? LINKING_EXPORTS : LINKING) || state == NEW) try { + wait(); + linkage = this.linkage; + state = linkage.getState(); + } catch (InterruptedException e) { + intr = true; + } + if (state == (exports ? LINKED_EXPORTS : LINKED)) { + return linkage.getPaths(exports); + } + this.linkage = linkage = new Linkage(linkage.getSourceList(), exports ? LINKING_EXPORTS : LINKING); + // fall out and link + } + if (exports) { + linkExports(linkage); + } else { + link(linkage); + } + } + } finally { + if (intr) { + Thread.currentThread().interrupt(); + } + } + } + + Map> getPathsUnchecked(final boolean export) { + try { + return getPaths(export); + } catch (ModuleLoadException e) { + throw e.toError(); + } + } + + boolean link(final Linkage linkage) throws ModuleLoadException { + final HashMap> importsMap = new HashMap>(); + final Dependency[] dependencies = linkage.getSourceList(); + final long start = Metrics.getCurrentCPUTime(); + long subtractTime = 0L; + try { + final Set visited = new FastCopyHashSet(16); + final FastCopyHashSet filterStack = new FastCopyHashSet(8); + subtractTime += addPaths(dependencies, importsMap, filterStack, visited); + synchronized (this) { + if (this.linkage == linkage) { + this.linkage = new Linkage(linkage.getSourceList(), LINKED, importsMap, null); + notifyAll(); + return true; + } + // else all our efforts were just wasted since someone changed the deps in the meantime + return false; + } + } finally { + moduleLoader.addLinkTime(Metrics.getCurrentCPUTime() - start - subtractTime); + } + } + + boolean linkExports(final Linkage linkage) throws ModuleLoadException { + final HashMap> exportsMap = new HashMap>(); + final Dependency[] dependencies = linkage.getSourceList(); + final long start = Metrics.getCurrentCPUTime(); + long subtractTime = 0L; + try { + final Set visited = new FastCopyHashSet(16); + final FastCopyHashSet filterStack = new FastCopyHashSet(8); + subtractTime += addExportedPaths(dependencies, exportsMap, filterStack, visited); + synchronized (this) { + if (this.linkage == linkage) { + this.linkage = new Linkage(linkage.getSourceList(), LINKED_EXPORTS, linkage.getAllPaths(), exportsMap); + notifyAll(); + return true; + } + // else all our efforts were just wasted since someone changed the deps in the meantime + return false; + } + } finally { + moduleLoader.addLinkTime(Metrics.getCurrentCPUTime() - start - subtractTime); + } + } + + void linkIfNecessary() throws ModuleLoadException { + Linkage linkage = this.linkage; + if (linkage.getState().compareTo(LINKING) >= 0) { + return; + } + synchronized (this) { + linkage = this.linkage; + if (linkage.getState().compareTo(LINKING) >= 0) { + return; + } + this.linkage = linkage = new Linkage(linkage.getSourceList(), LINKING); + } + link(linkage); + } + + void relink() throws ModuleLoadException { + link(linkage); + } + + void setDependencies(final List dependencySpecs) throws ModuleLoadException { + synchronized (this) { + linkage = new Linkage(calculateDependencies(dependencySpecs), Linkage.State.UNLINKED, null, null); + notifyAll(); + } + } + + private Dependency[] calculateDependencies(final List dependencySpecs) { + final Dependency[] dependencies = new Dependency[dependencySpecs.size()]; + int i = 0; + for (DependencySpec spec : dependencySpecs) { + final Dependency dependency = spec.getDependency(this); + dependencies[i++] = dependency; + } + return dependencies; + } + + String getMainClass() { + return mainClassName; + } + + Package getPackage(final String name) { + List loaders = getPathsUnchecked(false).get(name.replace('.', '/')); + if (loaders != null) for (LocalLoader localLoader : loaders) { + Package pkg = localLoader.loadPackageLocal(name); + if (pkg != null) return pkg; + } + return null; + } + + Package[] getPackages() { + final ArrayList packages = new ArrayList(); + final Map> allPaths = getPathsUnchecked(false); + next: for (String path : allPaths.keySet()) { + String packageName = path.replace('/', '.'); + for (LocalLoader loader : allPaths.get(path)) { + Package pkg = loader.loadPackageLocal(packageName); + if (pkg != null) { + packages.add(pkg); + } + continue next; + } + } + return packages.toArray(new Package[packages.size()]); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.jboss.modules.Module.getPathsUnchecked` indirectly writes to field `table.[_]` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Map Module.getPathsUnchecked(boolean) + +### Procedure Id: +org.jboss.modules.Module.getPathsUnchecked(boolean):java.util.Map.a68fa709a7df307dde5deb99ccabce21 + +### File: +src/main/java/org/jboss/modules/Module.java + +### Key: +Module.java|getPathsUnchecked|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +8e7b43c818fa0ce3cdf75d51236f63de + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9734/instruction.md b/inferredbugs-9734/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ea64ecf2a49f218ac584015bf2cbd96c2ad78353 --- /dev/null +++ b/inferredbugs-9734/instruction.md @@ -0,0 +1,1179 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jboss-modules +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * JBoss, Home of Professional Open Source. + * Copyright 2010, Red Hat, Inc., and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This 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 software 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 software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.jboss.modules; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.net.URL; +import java.net.URLConnection; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.ServiceLoader; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; + +import org.jboss.modules.filter.PathFilter; +import org.jboss.modules.filter.PathFilters; +import org.jboss.modules.log.ModuleLogger; +import org.jboss.modules.log.NoopModuleLogger; + +import __redirected.__JAXPRedirected; + +import static org.jboss.modules.Linkage.State.*; + +/** + * A module is a unit of classes and other resources, along with the specification of what is imported and exported + * by this module from and to other modules. Modules are created by {@link ModuleLoader}s which build modules from + * various configuration information and resource roots. + * + * @author David M. Lloyd + * @author John Bailey + * @author Flavia Rainone + * @author Jason T. Greene + * @author thomas.diesler@jboss.com + * + * @apiviz.landmark +*/ +public final class Module { + + private static final AtomicReference BOOT_MODULE_LOADER = new AtomicReference(); + + static { + AccessController.doPrivileged(new PrivilegedAction() { + public Void run() { + try { + URL.setURLStreamHandlerFactory(new ModularURLStreamHandlerFactory()); + } catch (Throwable t) { + // todo log a warning or something + } + try { + URLConnection.setContentHandlerFactory(new ModularContentHandlerFactory()); + } catch (Throwable t) { + // todo log a warning or something + } + + __JAXPRedirected.initAll(); + + return null; + } + }); + + final String pkgsString = AccessController.doPrivileged(new PropertyReadAction("jboss.modules.system.pkgs")); + final List list = new ArrayList(); + list.add("java."); + list.add("sun.reflect."); + list.add("__redirected."); + if (pkgsString != null) { + int i; + int nc = -1; + do { + i = nc + 1; + nc = pkgsString.indexOf(',', i); + String part; + if (nc == -1) { + part = pkgsString.substring(i).trim(); + } else { + part = pkgsString.substring(i, nc).trim(); + } + if (part.length() > 0) { + list.add((part + ".").intern()); + } + } while (nc != -1); + } + systemPackages = list.toArray(list.toArray(new String[list.size()])); + final ListIterator iterator = list.listIterator(); + // http://youtrack.jetbrains.net/issue/IDEA-72097 + //noinspection WhileLoopReplaceableByForEach + while (iterator.hasNext()) { + iterator.set(iterator.next().replace('.', '/')); + } + systemPaths = list.toArray(list.toArray(new String[list.size()])); + } + + // static properties + + static final String[] systemPackages; + static final String[] systemPaths; + + /** + * The system-wide module logger, which may be changed via {@link #setModuleLogger(org.jboss.modules.log.ModuleLogger)}. + */ + static volatile ModuleLogger log = NoopModuleLogger.getInstance(); + + // immutable properties + + /** + * The identifier of this module. + */ + private final ModuleIdentifier identifier; + /** + * The name of the main class, if any (may be {@code null}). + */ + private final String mainClassName; + /** + * The module class loader for this module. + */ + private final ModuleClassLoader moduleClassLoader; + /** + * The module loader which created this module. + */ + private final ModuleLoader moduleLoader; + /** + * This reference exists solely to prevent the {@code FutureModule} from getting GC'd prematurely. + */ + @SuppressWarnings({ "unused" }) + private final Object myKey; + /** + * The fallback local loader, if any is defined. + */ + private final LocalLoader fallbackLoader; + + // mutable properties + + /** + * The linkage state. + */ + private volatile Linkage linkage = Linkage.NONE; + + // private constants + + private static final RuntimePermission GET_CLASS_LOADER = new RuntimePermission("getClassLoader"); + private static final RuntimePermission GET_BOOT_MODULE_LOADER = new RuntimePermission("getBootModuleLoader"); + private static final RuntimePermission ACCESS_MODULE_LOGGER = new RuntimePermission("accessModuleLogger"); + private static final RuntimePermission ADD_CONTENT_HANDLER_FACTORY = new RuntimePermission("addContentHandlerFactory"); + private static final RuntimePermission ADD_URL_STREAM_HANDLER_FACTORY = new RuntimePermission("addURLStreamHandlerFactory"); + + /** + * Construct a new instance from a module specification. + * + * @param spec the module specification + * @param moduleLoader the module loader + * @param myKey the key to keep a strong reference to + */ + Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) { + this.moduleLoader = moduleLoader; + this.myKey = myKey; + + // Initialize state from the spec. + identifier = spec.getModuleIdentifier(); + mainClassName = spec.getMainClass(); + fallbackLoader = spec.getFallbackLoader(); + //noinspection ThisEscapedInObjectConstruction + final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); + final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); + ModuleClassLoader moduleClassLoader = null; + if (factory != null) moduleClassLoader = factory.create(configuration); + if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); + this.moduleClassLoader = moduleClassLoader; + } + + LocalLoader getFallbackLoader() { + return fallbackLoader; + } + + Dependency[] getDependencies() { + return linkage.getSourceList(); + } + + ModuleClassLoader getClassLoaderPrivate() { + return moduleClassLoader; + } + + /** + * Get an exported resource from a specific root in this module. + * + * @param rootPath the module root to search + * @param resourcePath the path of the resource + * @return the resource + */ + public Resource getExportedResource(final String rootPath, final String resourcePath) { + return moduleClassLoader.loadResourceLocal(rootPath, resourcePath); + } + + /** + * Run a module's main class, if any. + * + * @param args the arguments to pass + * @throws NoSuchMethodException if there is no main method + * @throws InvocationTargetException if the main method failed + * @throws ClassNotFoundException if the main class is not found + */ + public void run(final String[] args) throws NoSuchMethodException, InvocationTargetException, ClassNotFoundException { + try { + if (mainClassName == null) { + throw new NoSuchMethodException("No main class defined for " + this); + } + final Class mainClass = moduleClassLoader.loadClass(mainClassName); + final Method mainMethod = mainClass.getMethod("main", String[].class); + final int modifiers = mainMethod.getModifiers(); + if (! Modifier.isStatic(modifiers)) { + throw new NoSuchMethodException("Main method is not static for " + this); + } + final ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(moduleClassLoader); + // ignore the return value + mainMethod.invoke(null, new Object[] {args}); + } finally { + Thread.currentThread().setContextClassLoader(previousClassLoader); + } + } catch (IllegalAccessException e) { + // unexpected; should be public + throw new IllegalAccessError(e.getMessage()); + } + } + + /** + * Get this module's identifier. + * + * @return the identifier + */ + public ModuleIdentifier getIdentifier() { + return identifier; + } + + /** + * Get the module loader which created this module. + * + * @return the module loader of this module + */ + public ModuleLoader getModuleLoader() { + return moduleLoader; + } + + /** + * Load a service loader from this module. + * + * @param serviceType the service type class + * @param the service type + * @return the service loader + */ + public ServiceLoader loadService(Class serviceType) { + return ServiceLoader.load(serviceType, moduleClassLoader); + } + + /** + * Load a service loader from a module in the caller's module loader. The caller's + * module loader refers to the loader of the module of the class that calls this method. + * Note that {@link #loadService(Class)} is more efficient since it does not need to crawl + * the stack. + * + * @param the the service type + * @param identifier the module identifier containing the service loader + * @param serviceType the service type class + * @return the loaded service from the caller's module + * @throws ModuleLoadException if the named module failed to load + */ + public static ServiceLoader loadServiceFromCallerModuleLoader(ModuleIdentifier identifier, Class serviceType) throws ModuleLoadException { + return getCallerModuleLoader().loadModule(identifier).loadService(serviceType); + } + + /** + * Get the class loader for a module. The class loader can be used to access non-exported classes and + * resources of the module. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("getClassLoader") permission to verify access to the class loader. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @return the module class loader + */ + public ModuleClassLoader getClassLoader() { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(GET_CLASS_LOADER); + } + return moduleClassLoader; + } + + /** + * Get all the paths exported by this module. + * + * @return the paths that are exported by this module + */ + public Set getExportedPaths() { + return Collections.unmodifiableSet(getPathsUnchecked(true).keySet()); + } + + /** + * Get the module for a loaded class, or {@code null} if the class did not come from any module. + * + * @param clazz the class + * @return the module it came from + */ + public static Module forClass(Class clazz) { + final ClassLoader cl = clazz.getClassLoader(); + return forClassLoader(cl, false); + } + + /** + * Get the module for a class loader, or {@code null} if the class loader is not associated with any module. If + * the class loader is unknown, it is possible to check the parent class loader up the chain, and so on until a module is found. + * + * @param cl the class loader + * @param search {@code true} to search up the delegation chain + * @return the associated module + */ + public static Module forClassLoader(ClassLoader cl, boolean search) { + if (cl instanceof ModuleClassLoader) { + return ((ModuleClassLoader) cl).getModule(); + } else if (search) { + return forClassLoader(cl.getParent(), true); + } else { + return null; + } + } + + /** + * Gets the boot module loader. The boot module loader is the + * initial loader that is established by the module framework. It typically + * is based off of the environmental module path unless it is overridden by + * specifying a different class name for the {@code boot.module.loader} system + * property. + * + * @return the boot module loader + */ + public static ModuleLoader getBootModuleLoader() { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(GET_BOOT_MODULE_LOADER); + } + ModuleLoader loader; + while ((loader = BOOT_MODULE_LOADER.get()) == null) { + loader = DefaultBootModuleLoaderHolder.INSTANCE; + if (BOOT_MODULE_LOADER.compareAndSet(null, loader)) { + break; + } + // get it again + } + return loader; + } + + static void initBootModuleLoader(ModuleLoader loader) { + BOOT_MODULE_LOADER.set(loader); + } + + /** + * Gets the current module loader. The current module loader is the + * loader of the module from the calling class. Note that this method + * must crawl the stack to determine this, so other mechanisms are more + * efficient. + * + * @return the current module loader, or {@code null} if this method is called outside of a module + */ + public static ModuleLoader getCallerModuleLoader() { + Module callerModule = getCallerModule(); + return callerModule == null ? null : callerModule.getModuleLoader(); + } + + /** + * Get the current thread's context module loader. This loader is the one which defined the module + * whose class loader is, or is a parent of, the thread's current context class loader. If there is none, + * then {@code null} is returned. + * + * @return the module loader, or {@code null} if none is set + */ + public static ModuleLoader getContextModuleLoader() { + return Module.forClassLoader(Thread.currentThread().getContextClassLoader(), true).getModuleLoader(); + } + + /** + * Get a module from the current module loader. Note that this must crawl the + * stack to determine this, so other mechanisms are more efficient. + * @see #getCallerModuleLoader() + * + * @param identifier the module identifier + * @return the module + * @throws ModuleLoadException if the module could not be loaded + */ + public static Module getModuleFromCallerModuleLoader(final ModuleIdentifier identifier) throws ModuleLoadException { + return getCallerModuleLoader().loadModule(identifier); + } + + /** + * Get the caller's module. The caller's module is the module containing the method that calls this + * method. Note that this method crawls the stack so other ways of obtaining the + * module are more efficient. + * + * @return the current module + */ + public static Module getCallerModule() { + return forClass(CallerContext.getCallingClass()); + } + + /** + * Get the module with the given identifier from the module loader used by this module. + * + * @param identifier the module identifier + * @return the module + * @throws ModuleLoadException if an error occurs + */ + public Module getModule(final ModuleIdentifier identifier) throws ModuleLoadException { + return moduleLoader.loadModule(identifier); + } + + /** + * Load a class from a module in the system module loader. + * + * @see #getBootModuleLoader() + * + * @param moduleIdentifier the identifier of the module from which the class + * should be loaded + * @param className the class name to load + * @return the class + * @throws ModuleLoadException if the module could not be loaded + * @throws ClassNotFoundException if the class could not be loaded + */ + public static Class loadClassFromBootModuleLoader(final ModuleIdentifier moduleIdentifier, final String className) + throws ModuleLoadException, ClassNotFoundException { + return Class.forName(className, true, getBootModuleLoader().loadModule(moduleIdentifier).getClassLoader()); + } + + /** + * Load a class from a module in the caller's module loader. + * + * @see #getCallerModuleLoader() + * + * @param moduleIdentifier the identifier of the module from which the class + * should be loaded + * @param className the class name to load + * @return the class + * @throws ModuleLoadException if the module could not be loaded + * @throws ClassNotFoundException if the class could not be loaded + */ + public static Class loadClassFromCallerModuleLoader(final ModuleIdentifier moduleIdentifier, final String className) + throws ModuleLoadException, ClassNotFoundException { + return Class.forName(className, true, getModuleFromCallerModuleLoader(moduleIdentifier).getClassLoader()); + } + + /** + * Load a class from a local loader. + * + * @param className the class name + * @param exportsOnly {@code true} to only load if the class is exported, {@code false} to load any class + * @param resolve {@code true} to resolve the class after definition + * @return the class + */ + Class loadModuleClass(final String className, final boolean exportsOnly, final boolean resolve) { + for (String s : systemPackages) { + if (className.startsWith(s)) { + try { + return moduleClassLoader.loadClass(className, resolve); + } catch (ClassNotFoundException e) { + return null; + } + } + } + final String path = pathOfClass(className); + final Map> paths = getPathsUnchecked(exportsOnly); + final List loaders = paths.get(path); + if (loaders != null) { + Class clazz; + for (LocalLoader loader : loaders) { + clazz = loader.loadClassLocal(className, resolve); + if (clazz != null) { + return clazz; + } + } + } + final LocalLoader fallbackLoader = this.fallbackLoader; + if (fallbackLoader != null) { + return fallbackLoader.loadClassLocal(className, resolve); + } + return null; + } + + /** + * Load a resource from a local loader. + * + * @param name the resource name + * @param exportsOnly {@code true} to only consider exported resources + * @return the resource URL, or {@code null} if not found + */ + URL getResource(final String name, final boolean exportsOnly) { + final String canonPath = PathUtils.canonicalize(name); + for (String s : Module.systemPaths) { + if (canonPath.startsWith(s)) { + return moduleClassLoader.getResource(canonPath); + } + } + log.trace("Attempting to find resource %s in %s", canonPath, this); + final String path = pathOf(canonPath); + final Map> paths = getPathsUnchecked(exportsOnly); + final List loaders = paths.get(path); + if (loaders != null) { + for (LocalLoader loader : loaders) { + final List resourceList = loader.loadResourceLocal(canonPath); + for (Resource resource : resourceList) { + return resource.getURL(); + } + } + } + final LocalLoader fallbackLoader = this.fallbackLoader; + if (fallbackLoader != null) { + final List resourceList = fallbackLoader.loadResourceLocal(canonPath); + for (Resource resource : resourceList) { + return resource.getURL(); + } + } + return null; + } + + /** + * Load all resources of a given name from a local loader. + * + * @param name the resource name + * @param exportsOnly {@code true} to only consider exported resources + * @return the enumeration of all the matching resource URLs (may be empty) + */ + Enumeration getResources(final String name, final boolean exportsOnly) { + final String canonPath = PathUtils.canonicalize(name); + for (String s : Module.systemPaths) { + if (canonPath.startsWith(s)) { + try { + return moduleClassLoader.getResources(canonPath); + } catch (IOException e) { + return ConcurrentClassLoader.EMPTY_ENUMERATION; + } + } + } + log.trace("Attempting to find all resources %s in %s", canonPath, this); + final String path = pathOf(canonPath); + final Map> paths = getPathsUnchecked(exportsOnly); + final List loaders = paths.get(path); + + final List list = new ArrayList(); + if (loaders != null) { + for (LocalLoader loader : loaders) { + final List resourceList = loader.loadResourceLocal(canonPath); + for (Resource resource : resourceList) { + list.add(resource.getURL()); + } + } + } + final LocalLoader fallbackLoader = this.fallbackLoader; + if (fallbackLoader != null) { + final List resourceList = fallbackLoader.loadResourceLocal(canonPath); + for (Resource resource : resourceList) { + list.add(resource.getURL()); + } + } + + return list.size() == 0 ? ConcurrentClassLoader.EMPTY_ENUMERATION : Collections.enumeration(list); + } + + /** + * Get an exported resource URL. + * + * @param name the resource name + * @return the resource, or {@code null} if it was not found + */ + public URL getExportedResource(final String name) { + return getResource(name, true); + } + + /** + * Get all exported resource URLs for a resource name. + * + * @param name the resource name + * @return the resource URLs + */ + public Enumeration getExportedResources(final String name) { + return getResources(name, true); + } + + /** + * Get the path name of a class. + * + * @param className the binary name of the class + * @return the parent path + */ + static String pathOfClass(final String className) { + final String resourceName = className.replace('.', '/'); + final String path; + final int idx = resourceName.lastIndexOf('/'); + if (idx > -1) { + path = resourceName.substring(0, idx); + } else { + path = ""; + } + return path; + } + + /** + * Get the path name of a resource. + * + * @param resourceName the resource name + * @return the parent path + */ + static String pathOf(final String resourceName) { + final String path; + if (resourceName.indexOf('/') == 0) { + return pathOf(resourceName.substring(1)); + } + final int idx = resourceName.lastIndexOf('/'); + if (idx > -1) { + path = resourceName.substring(0, idx); + } else { + path = ""; + } + return path; + } + + /** + * Get the file name of a class. + * + * @param className the class name + * @return the name of the corresponding class file + */ + static String fileNameOfClass(final String className) { + return className.replace('.', '/') + ".class"; + } + + /** + * Get the string representation of this module. + * + * @return the string representation + */ + @Override + public String toString() { + return "Module \"" + identifier + "\"" + " from " + moduleLoader.toString(); + } + + /** + * Get the logger used by the module system. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("accessModuleLogger") permission to verify access to the module logger. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @return the module logger + */ + public static ModuleLogger getModuleLogger() { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(ACCESS_MODULE_LOGGER); + } + return log; + } + + /** + * Change the logger used by the module system. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("accessModuleLogger") permission to verify access to the module logger. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @param logger the new logger, must not be {@code null} + */ + public static void setModuleLogger(final ModuleLogger logger) { + if (logger == null) { + throw new IllegalArgumentException("logger is null"); + } + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(ACCESS_MODULE_LOGGER); + } + logger.greeting(); + log = logger; + } + + /** + * Return the start time in millis when Module.class was loaded. + * + * @return start time of Module.class load + */ + public static long getStartTime() { + return StartTimeHolder.START_TIME; + } + + /** + * Register an additional module which contains content handlers. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("addContentHandlerFactory") permission to verify access. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @param module the module to add + */ + public static void registerContentHandlerFactoryModule(Module module) { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(ADD_CONTENT_HANDLER_FACTORY); + } + ModularContentHandlerFactory.addHandlerModule(module); + } + + /** + * Register an additional module which contains URL handlers. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("addURLStreamHandlerFactory") permission to verify access. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @param module the module to add + */ + public static void registerURLStreamHandlerFactoryModule(Module module) { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(ADD_URL_STREAM_HANDLER_FACTORY); + } + ModularURLStreamHandlerFactory.addHandlerModule(module); + } + + // Linking and resolution + + static final class Visited { + private final Module module; + private final FastCopyHashSet filters; + private final int hashCode; + + Visited(final Module module, final FastCopyHashSet filters) { + this.module = module; + this.filters = filters; + hashCode = filters.hashCode() * 13 + module.hashCode(); + } + + public int hashCode() { + return hashCode; + } + + public boolean equals(Object other) { + return other instanceof Visited && equals((Visited)other); + } + + public boolean equals(Visited other) { + return this == other || other != null && module == other.module && filters.equals(other.filters); + } + } + + long addPaths(Dependency[] dependencies, Map> map, FastCopyHashSet filterStack, Set visited) throws ModuleLoadException { + long subtract = 0L; + moduleLoader.incScanCount(); + for (Dependency dependency : dependencies) { + if (dependency instanceof ModuleDependency) { + final ModuleDependency moduleDependency = (ModuleDependency) dependency; + final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); + final ModuleIdentifier id = moduleDependency.getIdentifier(); + final Module module; + + try { + long pauseStart = Metrics.getCurrentCPUTime(); + try { + module = moduleLoader.preloadModule(id); + } finally { + subtract += Metrics.getCurrentCPUTime() - pauseStart; + } + } catch (ModuleLoadException ex) { + if (moduleDependency.isOptional()) { + continue; + } else { + throw ex; + } + } + if (module == null) { + if (!moduleDependency.isOptional()) { + throw new ModuleNotFoundException(id.toString()); + } + continue; + } + + final PathFilter importFilter = dependency.getImportFilter(); + filterStack.add(importFilter); + subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited); + filterStack.remove(importFilter); + } else if (dependency instanceof ModuleClassLoaderDependency) { + final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; + final LocalLoader localLoader = classLoaderDependency.getLocalLoader(); + final PathFilter importFilter = classLoaderDependency.getImportFilter(); + final Set paths = classLoaderDependency.getPaths(); + for (String path : paths) { + if (importFilter.accept(path)) { + List list = map.get(path); + if (list == null) { + map.put(path, list = new ArrayList()); + list.add(localLoader); + } else if (! list.contains(localLoader)) { + list.add(localLoader); + } + } + } + } else if (dependency instanceof LocalDependency) { + final LocalDependency localDependency = (LocalDependency) dependency; + final LocalLoader localLoader = localDependency.getLocalLoader(); + final PathFilter importFilter = localDependency.getImportFilter(); + final Set paths = localDependency.getPaths(); + for (String path : paths) { + if (importFilter.accept(path)) { + List list = map.get(path); + if (list == null) { + map.put(path, list = new ArrayList()); + list.add(localLoader); + } else if (! list.contains(localLoader)) { + list.add(localLoader); + } + } + } + } + // else unknown dep type so just skip + } + return subtract; + } + + long addExportedPaths(Dependency[] dependencies, Map> map, FastCopyHashSet filterStack, Set visited) throws ModuleLoadException { + if (!visited.add(new Visited(this, filterStack))) { + return 0L; + } + long subtract = 0L; + moduleLoader.incScanCount(); + for (Dependency dependency : dependencies) { + final PathFilter exportFilter = dependency.getExportFilter(); + // skip non-exported dependencies altogether + if (exportFilter != PathFilters.rejectAll()) { + if (dependency instanceof ModuleDependency) { + final ModuleDependency moduleDependency = (ModuleDependency) dependency; + final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); + final ModuleIdentifier id = moduleDependency.getIdentifier(); + final Module module; + + try { + long pauseStart = Metrics.getCurrentCPUTime(); + try { + module = moduleLoader.preloadModule(id); + } finally { + subtract += Metrics.getCurrentCPUTime() - pauseStart; + } + } catch (ModuleLoadException ex) { + if (moduleDependency.isOptional()) { + continue; + } else { + throw ex; + } + } + if (module == null) { + if (!moduleDependency.isOptional()) { + throw new ModuleNotFoundException(id.toString()); + } + continue; + } + + final PathFilter importFilter = dependency.getImportFilter(); + if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) { + subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited); + } else { + final FastCopyHashSet clone = filterStack.clone(); + clone.add(importFilter); + clone.add(exportFilter); + subtract += module.addExportedPaths(module.getDependencies(), map, clone, visited); + } + } else if (dependency instanceof ModuleClassLoaderDependency) { + final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; + final LocalLoader localLoader = classLoaderDependency.getLocalLoader(); + final Set paths = classLoaderDependency.getPaths(); + for (String path : paths) { + boolean accept = true; + for (Object filter : filterStack.getRawArray()) { + if (filter != null && ! ((PathFilter)filter).accept(path)) { + accept = false; break; + } + } + if (accept && classLoaderDependency.getImportFilter().accept(path) && classLoaderDependency.getExportFilter().accept(path)) { + List list = map.get(path); + if (list == null) { + map.put(path, list = new ArrayList(1)); + list.add(localLoader); + } else if (! list.contains(localLoader)) { + list.add(localLoader); + } + } + } + } else if (dependency instanceof LocalDependency) { + final LocalDependency localDependency = (LocalDependency) dependency; + final LocalLoader localLoader = localDependency.getLocalLoader(); + final Set paths = localDependency.getPaths(); + for (String path : paths) { + boolean accept = true; + for (Object filter : filterStack.getRawArray()) { + if (filter != null && ! ((PathFilter)filter).accept(path)) { + accept = false; break; + } + } + if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) { + List list = map.get(path); + if (list == null) { + map.put(path, list = new ArrayList(1)); + list.add(localLoader); + } else if (! list.contains(localLoader)) { + list.add(localLoader); + } + } + } + } + // else unknown dep type so just skip + } + } + return subtract; + } + + Map> getPaths(final boolean exports) throws ModuleLoadException { + Linkage linkage = this.linkage; + Linkage.State state = linkage.getState(); + if (state.compareTo(exports ? LINKED_EXPORTS : LINKED) >= 0) { + return linkage.getPaths(exports); + } + // slow path loop + boolean intr = false; + try { + for (;;) { + synchronized (this) { + linkage = this.linkage; + state = linkage.getState(); + while (state == (exports ? LINKING_EXPORTS : LINKING) || state == NEW) try { + wait(); + linkage = this.linkage; + state = linkage.getState(); + } catch (InterruptedException e) { + intr = true; + } + if (state == (exports ? LINKED_EXPORTS : LINKED)) { + return linkage.getPaths(exports); + } + this.linkage = linkage = new Linkage(linkage.getSourceList(), exports ? LINKING_EXPORTS : LINKING); + // fall out and link + } + if (exports) { + linkExports(linkage); + } else { + link(linkage); + } + } + } finally { + if (intr) { + Thread.currentThread().interrupt(); + } + } + } + + Map> getPathsUnchecked(final boolean export) { + try { + return getPaths(export); + } catch (ModuleLoadException e) { + throw e.toError(); + } + } + + boolean link(final Linkage linkage) throws ModuleLoadException { + final HashMap> importsMap = new HashMap>(); + final Dependency[] dependencies = linkage.getSourceList(); + final long start = Metrics.getCurrentCPUTime(); + long subtractTime = 0L; + try { + final Set visited = new FastCopyHashSet(16); + final FastCopyHashSet filterStack = new FastCopyHashSet(8); + subtractTime += addPaths(dependencies, importsMap, filterStack, visited); + synchronized (this) { + if (this.linkage == linkage) { + this.linkage = new Linkage(linkage.getSourceList(), LINKED, importsMap, null); + notifyAll(); + return true; + } + // else all our efforts were just wasted since someone changed the deps in the meantime + return false; + } + } finally { + moduleLoader.addLinkTime(Metrics.getCurrentCPUTime() - start - subtractTime); + } + } + + boolean linkExports(final Linkage linkage) throws ModuleLoadException { + final HashMap> exportsMap = new HashMap>(); + final Dependency[] dependencies = linkage.getSourceList(); + final long start = Metrics.getCurrentCPUTime(); + long subtractTime = 0L; + try { + final Set visited = new FastCopyHashSet(16); + final FastCopyHashSet filterStack = new FastCopyHashSet(8); + subtractTime += addExportedPaths(dependencies, exportsMap, filterStack, visited); + synchronized (this) { + if (this.linkage == linkage) { + this.linkage = new Linkage(linkage.getSourceList(), LINKED_EXPORTS, linkage.getAllPaths(), exportsMap); + notifyAll(); + return true; + } + // else all our efforts were just wasted since someone changed the deps in the meantime + return false; + } + } finally { + moduleLoader.addLinkTime(Metrics.getCurrentCPUTime() - start - subtractTime); + } + } + + void linkIfNecessary() throws ModuleLoadException { + Linkage linkage = this.linkage; + if (linkage.getState().compareTo(LINKING) >= 0) { + return; + } + synchronized (this) { + linkage = this.linkage; + if (linkage.getState().compareTo(LINKING) >= 0) { + return; + } + this.linkage = linkage = new Linkage(linkage.getSourceList(), LINKING); + } + link(linkage); + } + + void relink() throws ModuleLoadException { + link(linkage); + } + + void setDependencies(final List dependencySpecs) throws ModuleLoadException { + synchronized (this) { + linkage = new Linkage(calculateDependencies(dependencySpecs), Linkage.State.UNLINKED, null, null); + notifyAll(); + } + } + + private Dependency[] calculateDependencies(final List dependencySpecs) { + final Dependency[] dependencies = new Dependency[dependencySpecs.size()]; + int i = 0; + for (DependencySpec spec : dependencySpecs) { + final Dependency dependency = spec.getDependency(this); + dependencies[i++] = dependency; + } + return dependencies; + } + + String getMainClass() { + return mainClassName; + } + + Package getPackage(final String name) { + List loaders = getPathsUnchecked(false).get(name.replace('.', '/')); + if (loaders != null) for (LocalLoader localLoader : loaders) { + Package pkg = localLoader.loadPackageLocal(name); + if (pkg != null) return pkg; + } + return null; + } + + Package[] getPackages() { + final ArrayList packages = new ArrayList(); + final Map> allPaths = getPathsUnchecked(false); + next: for (String path : allPaths.keySet()) { + String packageName = path.replace('/', '.'); + for (LocalLoader loader : allPaths.get(path)) { + Package pkg = loader.loadPackageLocal(packageName); + if (pkg != null) { + packages.add(pkg); + } + continue next; + } + } + return packages.toArray(new Package[packages.size()]); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.jboss.modules.Module.addPaths` indirectly reads without synchronization from `table.[_]`. Potentially races with write in method `Module.link(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +long Module.addPaths(org.jboss.modules.Dependency[],Map,FastCopyHashSet,Set) + +### Procedure Id: +org.jboss.modules.Module.addPaths(org.jboss.modules.Dependency[],java.util.Map,org.jboss.modules.Fas.deb18ac3d22626a1199a4d784109363b + +### File: +src/main/java/org/jboss/modules/Module.java + +### Key: +Module.java|addPaths|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +63eff89e392053255f82d0315e3e22e0 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9814/instruction.md b/inferredbugs-9814/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..54a06c2f988dbfcf6e61a01e1401759879ef89df --- /dev/null +++ b/inferredbugs-9814/instruction.md @@ -0,0 +1,434 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** pippo +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2014 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ro.fortsoft.pippo.core; + +import ro.fortsoft.pippo.core.controller.Controller; +import ro.fortsoft.pippo.core.controller.ControllerHandler; +import ro.fortsoft.pippo.core.controller.ControllerInitializationListenerList; +import ro.fortsoft.pippo.core.controller.ControllerInstantiationListenerList; +import ro.fortsoft.pippo.core.controller.ControllerInvokeListenerList; +import ro.fortsoft.pippo.core.route.ClasspathResourceHandler; +import ro.fortsoft.pippo.core.route.DefaultRouteMatcher; +import ro.fortsoft.pippo.core.route.DefaultRouteNotFoundHandler; +import ro.fortsoft.pippo.core.route.Route; +import ro.fortsoft.pippo.core.route.RouteHandler; +import ro.fortsoft.pippo.core.route.RouteMatcher; +import ro.fortsoft.pippo.core.route.RouteNotFoundHandler; +import ro.fortsoft.pippo.core.route.UrlBuilder; +import ro.fortsoft.pippo.core.util.HttpCacheToolkit; +import ro.fortsoft.pippo.core.util.MimeTypes; +import ro.fortsoft.pippo.core.util.ServiceLocator; + +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Decebal Suiu + */ +public class Application { + + private static final Logger log = LoggerFactory.getLogger(Application.class); + + private PippoSettings pippoSettings; + private Languages languages; + private Messages messages; + private MimeTypes mimeTypes; + private HttpCacheToolkit httpCacheToolkit; + private TemplateEngine templateEngine; + private JsonEngine jsonEngine; + private XmlEngine xmlEngine; + private RouteMatcher routeMatcher; + private UrlBuilder urlBuilder; + private ExceptionHandler exceptionHandler; + private RouteNotFoundHandler routeNotFoundHandler; + + private String uploadLocation = System.getProperty("java.io.tmpdir"); + private long maximumUploadSize = -1L; + + private ControllerInstantiationListenerList controllerInstantiationListeners; + private ControllerInitializationListenerList controllerInitializationListeners; + private ControllerInvokeListenerList controllerInvokeListeners; + + private Map locals; + + /** + * Get Application for current thread. + * + * @return The current thread's Application + */ + public static Application get() { + Application application = ThreadContext.getApplication(); + if (application == null) { + throw new PippoRuntimeException("There is no application attached to current thread '{}'", + Thread.currentThread().getName()); + } + + return application; + } + + public Application() { + this(new PippoSettings(RuntimeMode.getCurrent())); + } + + public Application(PippoSettings settings) { + this.pippoSettings = settings; + this.languages = new Languages(settings); + this.messages = new Messages(languages); + this.mimeTypes = new MimeTypes(settings); + this.httpCacheToolkit = new HttpCacheToolkit(settings); + } + + public void init() { + } + + public void destroy() { + } + + /** + * The runtime mode. Must currently be either DEV, TEST, or PROD. + */ + public RuntimeMode getRuntimeMode() { + return pippoSettings.getRuntimeMode(); + } + + public PippoSettings getPippoSettings() { + return pippoSettings; + } + + public String getApplicationName() { + return pippoSettings.getString(PippoConstants.SETTING_APPLICATION_NAME, ""); + } + + public String getApplicationVersion() { + return pippoSettings.getString(PippoConstants.SETTING_APPLICATION_VERSION, ""); + } + + public Languages getLanguages() { + return languages; + } + + public Messages getMessages() { + return messages; + } + + public MimeTypes getMimeTypes() { + return mimeTypes; + } + + public HttpCacheToolkit getHttpCacheToolkit() { + return httpCacheToolkit; + } + + public TemplateEngine getTemplateEngine() { + if (templateEngine == null) { + TemplateEngine engine = ServiceLocator.locate(TemplateEngine.class); + setTemplateEngine(engine); + } + + return templateEngine; + } + + public void setTemplateEngine(TemplateEngine templateEngine) { + // initialize the engine first + templateEngine.init(this); + + this.templateEngine = templateEngine; + } + + public JsonEngine getJsonEngine() { + if (jsonEngine == null) { + jsonEngine = ServiceLocator.locate(JsonEngine.class); + } + + return jsonEngine; + } + + public void setJsonEngine(JsonEngine jsonEngine) { + this.jsonEngine = jsonEngine; + } + + public XmlEngine getXmlEngine() { + if (xmlEngine == null) { + xmlEngine = ServiceLocator.locate(XmlEngine.class); + } + + return xmlEngine; + } + + public void setXmlEngine(XmlEngine xmlEngine) { + this.xmlEngine = xmlEngine; + } + + public RouteMatcher getRouteMatcher() { + if (routeMatcher == null) { + routeMatcher = new DefaultRouteMatcher(); + } + + return routeMatcher; + } + + public void setRouteMatcher(RouteMatcher routeMatcher) { + this.routeMatcher = routeMatcher; + } + + void setContextPath(String contextPath) { + getUrlBuilder().setContextPath(contextPath); + } + + public void GET(ClasspathResourceHandler resourceHandler) { + if (getUrlBuilder().urlPatternFor(resourceHandler.getClass()) != null) { + throw new PippoRuntimeException("You may only register one route for {}", + resourceHandler.getClass().getSimpleName()); + } + resourceHandler.setMimeTypes(mimeTypes); + resourceHandler.setHttpCacheToolkit(httpCacheToolkit); + addRoute(resourceHandler.getUrlPattern(), HttpConstants.Method.GET, resourceHandler); + } + + public void GET(String urlPattern, RouteHandler routeHandler) { + addRoute(urlPattern, HttpConstants.Method.GET, routeHandler); + } + + public void GET(String urlPattern, Class controllerClass, String methodName) { + addRoute(urlPattern, HttpConstants.Method.GET, new ControllerHandler(controllerClass, methodName)); + } + + public void POST(String urlPattern, RouteHandler routeHandler) { + addRoute(urlPattern, HttpConstants.Method.POST, routeHandler); + } + + public void POST(String urlPattern, Class controllerClass, String methodName) { + addRoute(urlPattern, HttpConstants.Method.POST, new ControllerHandler(controllerClass, methodName)); + } + + public void DELETE(String urlPattern, RouteHandler routeHandler) { + addRoute(urlPattern, HttpConstants.Method.DELETE, routeHandler); + } + + public void DELETE(String urlPattern, Class controllerClass, String methodName) { + addRoute(urlPattern, HttpConstants.Method.DELETE, new ControllerHandler(controllerClass, methodName)); + } + + public void HEAD(String urlPattern, RouteHandler routeHandler) { + addRoute(urlPattern, HttpConstants.Method.HEAD, routeHandler); + } + + public void HEAD(String urlPattern, Class controllerClass, String methodName) { + addRoute(urlPattern, HttpConstants.Method.HEAD, new ControllerHandler(controllerClass, methodName)); + } + + public void PUT(String urlPattern, RouteHandler routeHandler) { + addRoute(urlPattern, HttpConstants.Method.PUT, routeHandler); + } + + public void PUT(String urlPattern, Class controllerClass, String methodName) { + addRoute(urlPattern, HttpConstants.Method.PUT, new ControllerHandler(controllerClass, methodName)); + } + + public void PATCH(String urlPattern, RouteHandler routeHandler) { + addRoute(urlPattern, HttpConstants.Method.PATCH, routeHandler); + } + + public void PATCH(String urlPattern, Class controllerClass, String methodName) { + addRoute(urlPattern, HttpConstants.Method.PATCH, new ControllerHandler(controllerClass, methodName)); + } + + public void addRoute(String urlPattern, String requestMethod, RouteHandler routeHandler) { + Route route = new Route(urlPattern, requestMethod, routeHandler); + try { + getRouteMatcher().addRoute(route); + } catch (Exception e) { + log.error("Cannot add route '{}'", route, e); + } + } + + public ExceptionHandler getExceptionHandler() { + if (exceptionHandler == null) { + exceptionHandler = new DefaultExceptionHandler(this); + } + + return exceptionHandler; + } + + public void setExceptionHandler(ExceptionHandler exceptionHandler) { + this.exceptionHandler = exceptionHandler; + } + + public RouteNotFoundHandler getRouteNotFoundHandler() { + if (routeNotFoundHandler == null) { + routeNotFoundHandler = new DefaultRouteNotFoundHandler(this); + } + + return routeNotFoundHandler; + } + + public void setRouteNotFoundHandler(RouteNotFoundHandler routeNotFoundHandler) { + this.routeNotFoundHandler = routeNotFoundHandler; + } + + /** + * The directory location where files will be stored. + * + * @return + */ + public String getUploadLocation() { + return uploadLocation; + } + + public void setUploadLocation(String uploadLocation) { + this.uploadLocation = uploadLocation; + } + + /** + * Gets the maximum size allowed for uploaded files. + * + * @return + */ + public long getMaximumUploadSize() { + return maximumUploadSize; + } + + public void setMaximumUploadSize(long maximumUploadSize) { + this.maximumUploadSize = maximumUploadSize; + } + + public ControllerInstantiationListenerList getControllerInstantiationListeners() { + if (controllerInstantiationListeners == null) { + controllerInstantiationListeners = new ControllerInstantiationListenerList(); + } + + return controllerInstantiationListeners; + } + + public ControllerInitializationListenerList getControllerInitializationListeners() { + if (controllerInitializationListeners == null) { + controllerInitializationListeners = new ControllerInitializationListenerList(); + } + + return controllerInitializationListeners; + } + + public ControllerInvokeListenerList getControllerInvokeListeners() { + if (controllerInvokeListeners == null) { + controllerInvokeListeners = new ControllerInvokeListenerList(); + } + + return controllerInvokeListeners; + } + + public Map getLocals() { + if (locals == null) { + locals = new HashMap<>(); + } + + return locals; + } + + public UrlBuilder getUrlBuilder() { + if (urlBuilder == null) { + urlBuilder = new UrlBuilder(getRouteMatcher()); + } + return urlBuilder; + } + + @Override + public String toString() { + String toString = (getApplicationName() + " " + getApplicationVersion()).trim(); + if (toString.isEmpty()) { + super.toString(); + } + + return toString; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `engine` last assigned on line 140 could be null and is dereferenced by call to `setTemplateEngine(...)` at line 141. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +TemplateEngine Application.getTemplateEngine() + +### Procedure Id: +ro.fortsoft.pippo.core.Application.getTemplateEngine():ro.fortsoft.pippo.core.TemplateEngine.aaa513372b934a6267b17002d0e34332 + +### File: +pippo-core/src/main/java/ro/fortsoft/pippo/core/Application.java + +### Key: +Application.java|getTemplateEngine|NULL_DEREFERENCE + +### Node Key: +c2c6d13a2c84d986d78a05ce39beab70 + +### Hash: +dd284b286ff0021f279e6e59e7faf4fa + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9815/instruction.md b/inferredbugs-9815/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e1fe6e4d041685b043a50b952e4a830f807340c6 --- /dev/null +++ b/inferredbugs-9815/instruction.md @@ -0,0 +1,139 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** pippo +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ro.pippo.core.route; + +import org.junit.Test; + +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static org.junit.Assert.*; + +public class PathTraversalResourceHandlerTest { + + @Test + public void classpathResourceHandlerTest() throws URISyntaxException { + ClasspathResourceHandler handler = new ClasspathResourceHandler("/", "/public"); + + URL resourceUrl = handler.getResourceUrl("VISIBLE"); + assertNotNull(resourceUrl); + Path visibleFile = Paths.get(resourceUrl.toURI()); + assertNotNull(visibleFile); + Path basePath = visibleFile.getParent(); + URL url = handler.getResourceUrl("../HIDDEN"); + assertNotNull(url); + assertTrue("Path traversal security issue", Paths.get(url.toURI()).startsWith(basePath)); + } + + @Test + public void webjarResourceHandlerTest() { + WebjarsResourceHandler handler = new WebjarsResourceHandler(); + + URL url = handler.getResourceUrl("../../../HIDDEN"); + assertNull(url); + } + + @Test + public void publicResourceHandlerTest() throws URISyntaxException { + PublicResourceHandler handler = new PublicResourceHandler(); + + URL resourceUrl = handler.getResourceUrl("VISIBLE"); + assertNotNull(resourceUrl); + Path visibleFile = Paths.get(resourceUrl.toURI()); + assertNotNull(visibleFile); + Path basePath = visibleFile.getParent(); + URL url = handler.getResourceUrl("../HIDDEN"); + assertNotNull(url); + assertTrue("Path traversal security issue", Paths.get(url.toURI()).startsWith(basePath)); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `url` last assigned on line 60 could be null and is dereferenced at line 62. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PathTraversalResourceHandlerTest.publicResourceHandlerTest() + +### Procedure Id: +ro.pippo.core.route.PathTraversalResourceHandlerTest.publicResourceHandlerTest():void.5070c82934057969bb82a51e21c74c76 + +### File: +pippo-core/src/test/java/ro/pippo/core/route/PathTraversalResourceHandlerTest.java + +### Key: +PathTraversalResourceHandlerTest.java|publicResourceHandlerTest|NULL_DEREFERENCE + +### Node Key: +24ae6f170d625e18d33bb0779a6f88fd + +### Hash: +626d3300bce9bf72fb17a221bcb71559 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9822/instruction.md b/inferredbugs-9822/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d2eed20b1122ef1c3f6cdac65f58277769078c8b --- /dev/null +++ b/inferredbugs-9822/instruction.md @@ -0,0 +1,243 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riak-java-client +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * This file is part of riak-java-pb-client + * + * Copyright (c) 2010 by Trifork + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ + +package com.basho.riak.pbc; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.util.Timer; +import java.util.TimerTask; + +import com.basho.riak.pbc.RPB.RpbErrorResp; +import com.google.protobuf.MessageLite; + +/** + * Wraps the {@link Socket} used to send/receive data to Riak's protocol buffers interface. + * + * See Basho Wiki for more details. + */ +class RiakConnection { + + static final int DEFAULT_RIAK_PB_PORT = 8087; + + private Socket sock; + private DataOutputStream dout; + private DataInputStream din; + + public RiakConnection(InetAddress addr, int port, int bufferSizeKb) throws IOException { + sock = new Socket(addr, port); + + sock.setSendBufferSize(1024 * bufferSizeKb); + + dout = new DataOutputStream(new BufferedOutputStream(sock + .getOutputStream(), 1024 * bufferSizeKb)); + din = new DataInputStream( + new BufferedInputStream(sock.getInputStream(), 1024 * bufferSizeKb)); + } + + /////////////////////// + + void send(int code, MessageLite req) throws IOException { + int len = req.getSerializedSize(); + dout.writeInt(len + 1); + dout.write(code); + req.writeTo(dout); + dout.flush(); + } + + void send(int code) throws IOException { + dout.writeInt(1); + dout.write(code); + dout.flush(); + } + + byte[] receive(int code) throws IOException { + int len = din.readInt(); + int get_code = din.read(); + + byte[] data = null; + if (len > 1) { + data = new byte[len - 1]; + din.readFully(data); + } + + if (get_code == RiakClient.MSG_ErrorResp) { + RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(data); + throw new RiakError(err); + } + + if (code != get_code) { + throw new IOException("bad message code. Expected: " + code + " actual: " + get_code); + } + + return data; + } + + void receive_code(int code) throws IOException, RiakError { + int len = din.readInt(); + int get_code = din.read(); + if (code == RiakClient.MSG_ErrorResp) { + RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(din); + throw new RiakError(err); + } + if (len != 1 || code != get_code) { + throw new IOException("bad message code"); + } + } + + static Timer TIMER = new Timer("riak-client-timeout-thread", true); + TimerTask idle_timeout; + + public void beginIdle() { + idle_timeout = new TimerTask() { + + @Override + public void run() { + RiakConnection.this.timer_fired(this); + } + }; + + TIMER.schedule(idle_timeout, 1000); + } + + synchronized void timer_fired(TimerTask fired_timer) { + if (idle_timeout != fired_timer) { + // if it is not our current timer, then ignore + return; + } + + close(); + } + + void close() { + if (isClosed()) + return; + + try { + sock.close(); + din = null; + dout = null; + sock = null; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + synchronized boolean endIdleAndCheckValid() { + TimerTask tt = idle_timeout; + if (tt != null) { tt.cancel(); } + idle_timeout = null; + + if (isClosed()) { + return false; + } else { + return true; + } + } + + public DataOutputStream getOutputStream() { + return dout; + } + + public boolean isClosed() { + return sock == null || sock.isClosed(); + } + + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.basho.riak.pbc.RiakConnection.send` reads without synchronization from `this.com.basho.riak.pbc.RiakConnection.dout`. Potentially races with write in method `RiakConnection.timer_fired(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RiakConnection.send(int) + +### Procedure Id: +com.basho.riak.pbc.RiakConnection.send(int):void.dff7e9c85b864ebb8243a7f15fb03cb6 + +### File: +src/main/java/com/basho/riak/pbc/RiakConnection.java + +### Key: +RiakConnection.java|send|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +a0f4c2e1fbd329d8107d884dd4ace56c + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9823/instruction.md b/inferredbugs-9823/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d50c1320ee1ac9e4e16b330f8ffc6d1f4b974dda --- /dev/null +++ b/inferredbugs-9823/instruction.md @@ -0,0 +1,243 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riak-java-client +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * This file is part of riak-java-pb-client + * + * Copyright (c) 2010 by Trifork + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ + +package com.basho.riak.pbc; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.util.Timer; +import java.util.TimerTask; + +import com.basho.riak.pbc.RPB.RpbErrorResp; +import com.google.protobuf.MessageLite; + +/** + * Wraps the {@link Socket} used to send/receive data to Riak's protocol buffers interface. + * + * See Basho Wiki for more details. + */ +class RiakConnection { + + static final int DEFAULT_RIAK_PB_PORT = 8087; + + private Socket sock; + private DataOutputStream dout; + private DataInputStream din; + + public RiakConnection(InetAddress addr, int port, int bufferSizeKb) throws IOException { + sock = new Socket(addr, port); + + sock.setSendBufferSize(1024 * bufferSizeKb); + + dout = new DataOutputStream(new BufferedOutputStream(sock + .getOutputStream(), 1024 * bufferSizeKb)); + din = new DataInputStream( + new BufferedInputStream(sock.getInputStream(), 1024 * bufferSizeKb)); + } + + /////////////////////// + + void send(int code, MessageLite req) throws IOException { + int len = req.getSerializedSize(); + dout.writeInt(len + 1); + dout.write(code); + req.writeTo(dout); + dout.flush(); + } + + void send(int code) throws IOException { + dout.writeInt(1); + dout.write(code); + dout.flush(); + } + + byte[] receive(int code) throws IOException { + int len = din.readInt(); + int get_code = din.read(); + + byte[] data = null; + if (len > 1) { + data = new byte[len - 1]; + din.readFully(data); + } + + if (get_code == RiakClient.MSG_ErrorResp) { + RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(data); + throw new RiakError(err); + } + + if (code != get_code) { + throw new IOException("bad message code. Expected: " + code + " actual: " + get_code); + } + + return data; + } + + void receive_code(int code) throws IOException, RiakError { + int len = din.readInt(); + int get_code = din.read(); + if (code == RiakClient.MSG_ErrorResp) { + RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(din); + throw new RiakError(err); + } + if (len != 1 || code != get_code) { + throw new IOException("bad message code"); + } + } + + static Timer TIMER = new Timer("riak-client-timeout-thread", true); + TimerTask idle_timeout; + + public void beginIdle() { + idle_timeout = new TimerTask() { + + @Override + public void run() { + RiakConnection.this.timer_fired(this); + } + }; + + TIMER.schedule(idle_timeout, 1000); + } + + synchronized void timer_fired(TimerTask fired_timer) { + if (idle_timeout != fired_timer) { + // if it is not our current timer, then ignore + return; + } + + close(); + } + + void close() { + if (isClosed()) + return; + + try { + sock.close(); + din = null; + dout = null; + sock = null; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + synchronized boolean endIdleAndCheckValid() { + TimerTask tt = idle_timeout; + if (tt != null) { tt.cancel(); } + idle_timeout = null; + + if (isClosed()) { + return false; + } else { + return true; + } + } + + public DataOutputStream getOutputStream() { + return dout; + } + + public boolean isClosed() { + return sock == null || sock.isClosed(); + } + + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.basho.riak.pbc.RiakConnection.receive_code` reads without synchronization from `this.com.basho.riak.pbc.RiakConnection.din`. Potentially races with write in method `RiakConnection.timer_fired(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RiakConnection.receive_code(int) + +### Procedure Id: +com.basho.riak.pbc.RiakConnection.receive_code(int):void.9a55d8a4cd6ccb1831c284d58bc3f0da + +### File: +src/main/java/com/basho/riak/pbc/RiakConnection.java + +### Key: +RiakConnection.java|receive_code|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +1cc4504571794b04eb0de7d7e4abe542 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9824/instruction.md b/inferredbugs-9824/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ea9ea5d9c5d7d742dddff4c5cfbfd1018634c929 --- /dev/null +++ b/inferredbugs-9824/instruction.md @@ -0,0 +1,659 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riak-java-client +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * This file is part of riak-java-pb-client + * + * Copyright (c) 2010 by Trifork + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ + +package com.basho.riak.pbc; + +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.prefs.BackingStoreException; +import java.util.prefs.Preferences; +import org.apache.commons.codec.binary.Base64; + +import org.json.JSONObject; + +import com.basho.riak.client.http.util.Constants; +import com.basho.riak.client.util.CharsetUtils; +import com.basho.riak.pbc.RPB.RpbDelReq; +import com.basho.riak.pbc.RPB.RpbGetClientIdResp; +import com.basho.riak.pbc.RPB.RpbGetReq; +import com.basho.riak.pbc.RPB.RpbGetResp; +import com.basho.riak.pbc.RPB.RpbGetServerInfoResp; +import com.basho.riak.pbc.RPB.RpbListBucketsResp; +import com.basho.riak.pbc.RPB.RpbMapRedReq; +import com.basho.riak.pbc.RPB.RpbPutReq; +import com.basho.riak.pbc.RPB.RpbPutResp; +import com.basho.riak.pbc.RPB.RpbSetClientIdReq; +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +//import com.trifork.riak.RPB.RpbListKeysResp; +//import com.trifork.riak.RPB.RpbMapRedResp; + +/** + * Low level protocol buffers client. + */ +public class RiakClient implements RiakMessageCodes { + + private static final int BUFFER_SIZE_KB; + + static { + BUFFER_SIZE_KB = Integer.parseInt(System.getProperty("com.basho.riak.client.pbc,buffer", "16")); + } + + private static final RiakObject[] NO_RIAK_OBJECTS = new RiakObject[0]; + private static final ByteString[] NO_BYTE_STRINGS = new ByteString[0]; + //private static final String[] NO_STRINGS = new String[0]; + //private static final MapReduceResponse[] NO_MAP_REDUCE_RESPONSES = new MapReduceResponse[0]; + + private String node; + private String serverVersion; + private InetAddress addr; + private int port; + private int bufferSizeKb; + + /** + * if this has been set (or gotten) then it will be applied to new + * connections + */ + private volatile ByteString clientID; + + public RiakClient(String host) throws IOException { + this(host, RiakConnection.DEFAULT_RIAK_PB_PORT); + } + + public RiakClient(String host, int port) throws IOException { + this(InetAddress.getByName(host), port); + } + + public RiakClient(InetAddress addr, int port) throws IOException { + this.addr = addr; + this.port = port; + this.bufferSizeKb = BUFFER_SIZE_KB; + } + + public RiakClient(String host, int port, int bufferSizeKb) throws IOException { + this.addr = InetAddress.getByName(host); + this.port = port; + this.bufferSizeKb = bufferSizeKb; + } + + private ThreadLocal connections = new ThreadLocal(); + + RiakConnection getConnection() throws IOException { + return getConnection(true); + } + + RiakConnection getConnection(boolean setClientId) throws IOException { + RiakConnection c = connections.get(); + if (c == null || !c.endIdleAndCheckValid()) { + c = new RiakConnection(addr, port, bufferSizeKb); + + if (this.clientID != null && setClientId) { + connections.set(c); + setClientID(clientID); + } + } + connections.set(null); + return c; + } + + void release(RiakConnection c) { + RiakConnection cc = connections.get(); + if (cc == null) { + c.beginIdle(); + connections.set(c); + } else { + c.close(); + } + } + + /** + * helper method to use a reasonable default client id + * beware, it caches the client id. If you call it multiple times on the same client + * you get the *same* id (not good for reusing a client with different ids) + * + * @throws IOException + */ + public void prepareClientID() throws IOException { + Preferences prefs = Preferences.userNodeForPackage(RiakClient.class); + + String clid = prefs.get("client_id", null); + if (clid == null) { + SecureRandom sr; + try { + sr = SecureRandom.getInstance("SHA1PRNG"); + // Not totally secure, but doesn't need to be + // and 100% less prone to 30 second hangs on linux jdk5 + sr.setSeed(UUID.randomUUID().getLeastSignificantBits() + new Date().getTime()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + byte[] data = new byte[6]; + sr.nextBytes(data); + clid = CharsetUtils.asString(Base64.encodeBase64Chunked(data), CharsetUtils.ISO_8859_1); + prefs.put("client_id", clid); + try { + prefs.flush(); + } catch (BackingStoreException e) { + throw new IOException(e.toString()); + } + } + + setClientID(clid); + } + + public void ping() throws IOException { + RiakConnection c = getConnection(); + try { + c.send(MSG_PingReq); + c.receive_code(MSG_PingResp); + } finally { + release(c); + } + } + + /** + * Warning: the riak client id is 4 bytes. This method silently truncates anymore bytes than that. + * Be aware that if you have two client Ids, "boris1" and "boris2" this method will leave you with 1 client id, "bori". + * Use {@link RiakClient#prepareClientID()} to generate a reasonably unique Id. + * @see RiakClient#prepareClientID() + * @param id + * @throws IOException + */ + public void setClientID(String id) throws IOException { + if(id == null || id.length() < Constants.RIAK_CLIENT_ID_LENGTH) { + throw new IllegalArgumentException("Client ID must be at least " + Constants.RIAK_CLIENT_ID_LENGTH + " bytes long"); + } + setClientID(ByteString.copyFrom(CharsetUtils.utf8StringToBytes(id), 0, Constants.RIAK_CLIENT_ID_LENGTH)); + } + + // ///////////////////// + + public void setClientID(ByteString id) throws IOException { + if(id.size() > Constants.RIAK_CLIENT_ID_LENGTH) { + id = ByteString.copyFrom(id.toByteArray(), 0, Constants.RIAK_CLIENT_ID_LENGTH); + } + RpbSetClientIdReq req = RPB.RpbSetClientIdReq.newBuilder().setClientId( + id).build(); + RiakConnection c = getConnection(false); + try { + c.send(MSG_SetClientIdReq, req); + c.receive_code(MSG_SetClientIdResp); + } finally { + release(c); + } + + this.clientID = id; + } + + public String getClientID() throws IOException { + RiakConnection c = getConnection(); + try { + c.send(MSG_GetClientIdReq); + byte[] data = c.receive(MSG_GetClientIdResp); + if (data == null) + return null; + RpbGetClientIdResp res = RPB.RpbGetClientIdResp.parseFrom(data); + clientID = res.getClientId(); + return clientID.toStringUtf8(); + } finally { + release(c); + } + } + + public Map getServerInfo() throws IOException { + RiakConnection c = getConnection(); + try { + c.send(MSG_GetServerInfoReq); + byte[] data = c.receive(MSG_GetServerInfoResp); + if (data == null) + return Collections.emptyMap(); + + RpbGetServerInfoResp res = RPB.RpbGetServerInfoResp.parseFrom(data); + if (res.hasNode()) { + this.node = res.getNode().toStringUtf8(); + } + if (res.hasServerVersion()) { + this.serverVersion = res.getServerVersion().toStringUtf8(); + } + Map result = new HashMap(); + result.put("node", node); + result.put("server_version", serverVersion); + return result; + } finally { + release(c); + } + } + + // ///////////////////// + + public RiakObject[] fetch(String bucket, String key, int readQuorum) + throws IOException { + return fetch(ByteString.copyFromUtf8(bucket), ByteString + .copyFromUtf8(key), readQuorum); + } + + public RiakObject[] fetch(ByteString bucket, ByteString key, int readQuorum) + throws IOException { + RpbGetReq req = RPB.RpbGetReq.newBuilder().setBucket(bucket) + .setKey(key).setR(readQuorum).build(); + + RiakConnection c = getConnection(); + try { + c.send(MSG_GetReq, req); + return process_fetch_reply(c, bucket, key); + } finally { + release(c); + } + + } + + public RiakObject[] fetch(String bucket, String key) throws IOException { + return fetch(ByteString.copyFromUtf8(bucket), ByteString + .copyFromUtf8(key)); + } + + public RiakObject[] fetch(ByteString bucket, ByteString key) + throws IOException { + RpbGetReq req = RPB.RpbGetReq.newBuilder().setBucket(bucket) + .setKey(key).build(); + + RiakConnection c = getConnection(); + try { + c.send(MSG_GetReq, req); + return process_fetch_reply(c, bucket, key); + } finally { + release(c); + } + } + + private RiakObject[] process_fetch_reply(RiakConnection c, + ByteString bucket, ByteString key) throws IOException, + InvalidProtocolBufferException { + byte[] rep = c.receive(MSG_GetResp); + + if (rep == null) { + return NO_RIAK_OBJECTS; + } + + RpbGetResp resp = RPB.RpbGetResp.parseFrom(rep); + int count = resp.getContentCount(); + RiakObject[] out = new RiakObject[count]; + ByteString vclock = resp.getVclock(); + for (int i = 0; i < count; i++) { + out[i] = new RiakObject(vclock, bucket, key, resp.getContent(i)); + } + return out; + } + + // ///////////////////// + + public ByteString[] store(RiakObject[] values, RequestMeta meta) + throws IOException { + + RiakConnection c = getConnection(); + try { + BulkReader reader = new BulkReader(c, values.length); + Thread worker = new Thread(reader); + worker.start(); + + DataOutputStream dout = c.getOutputStream(); + + for (int i = 0; i < values.length; i++) { + RiakObject value = values[i]; + + RPB.RpbPutReq.Builder builder = RPB.RpbPutReq.newBuilder() + .setBucket(value.getBucketBS()) + .setKey(value.getKeyBS()).setContent( + value.buildContent()); + + if (value.getVclock() != null) { + builder.setVclock(value.getVclock()); + } + + builder.setReturnBody(true); + + if (meta != null) { + + if (meta.writeQuorum != null) { + builder.setW(meta.writeQuorum.intValue()); + } + + if (meta.durableWriteQuorum != null) { + builder.setDw(meta.durableWriteQuorum.intValue()); + } + } + + RpbPutReq req = builder.build(); + + int len = req.getSerializedSize(); + dout.writeInt(len + 1); + dout.write(MSG_PutReq); + req.writeTo(dout); + } + + dout.flush(); + + try { + worker.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return reader.vclocks; + } finally { + release(c); + } + } + + class BulkReader implements Runnable { + + private ByteString[] vclocks; + private final RiakConnection c; + + public BulkReader(RiakConnection c, int count) { + this.c = c; + this.vclocks = new ByteString[count]; + } + + public void run() { + + try { + for (int i = 0; i < vclocks.length; i++) { + byte[] data = c.receive(MSG_PutResp); + if (data != null) { + RpbPutResp resp = RPB.RpbPutResp.parseFrom(data); + if (resp.hasVclock()) { + vclocks[i] = resp.getVclock(); + } + } + } + } catch (IOException e) { + // TODO + e.printStackTrace(); + } + + } + + } + + public void store(RiakObject value) throws IOException { + store(value, null); + } + + public RiakObject[] store(RiakObject value, IRequestMeta meta) + throws IOException { + + RPB.RpbPutReq.Builder builder = RPB.RpbPutReq.newBuilder().setBucket( + value.getBucketBS()).setKey(value.getKeyBS()).setContent( + value.buildContent()); + + if (value.getVclock() != null) { + builder.setVclock(value.getVclock()); + } + + if (meta != null) { + meta.preparePut(builder); + } + + RiakConnection c = getConnection(); + try { + c.send(MSG_PutReq, builder.build()); + byte[] r = c.receive(MSG_PutResp); + + if (r == null) { + return NO_RIAK_OBJECTS; + } + + RpbPutResp resp = RPB.RpbPutResp.parseFrom(r); + + RiakObject[] res = new RiakObject[resp.getContentsCount()]; + ByteString vclock = resp.getVclock(); + + for (int i = 0; i < res.length; i++) { + res[i] = new RiakObject(vclock, value.getBucketBS(), value + .getKeyBS(), resp.getContents(i)); + } + + return res; + } finally { + release(c); + } + } + + // ///////////////////// + + public void delete(String bucket, String key, int rw) throws IOException { + delete(ByteString.copyFromUtf8(bucket), ByteString.copyFromUtf8(key), + rw); + } + + public void delete(ByteString bucket, ByteString key, int rw) + throws IOException { + RpbDelReq req = RPB.RpbDelReq.newBuilder().setBucket(bucket) + .setKey(key).setRw(rw).build(); + + RiakConnection c = getConnection(); + try { + c.send(MSG_DelReq, req); + c.receive_code(MSG_DelResp); + } finally { + release(c); + } + + } + + public void delete(String bucket, String key) throws IOException { + delete(ByteString.copyFromUtf8(bucket), ByteString.copyFromUtf8(key)); + } + + public void delete(ByteString bucket, ByteString key) throws IOException { + RpbDelReq req = RPB.RpbDelReq.newBuilder().setBucket(bucket) + .setKey(key).build(); + + RiakConnection c = getConnection(); + try { + c.send(MSG_DelReq, req); + c.receive_code(MSG_DelResp); + } finally { + release(c); + } + } + + public ByteString[] listBuckets() throws IOException { + + byte[] data; + RiakConnection c = getConnection(); + try { + c.send(MSG_ListBucketsReq); + + data = c.receive(MSG_ListBucketsResp); + if (data == null) { + return NO_BYTE_STRINGS; + } + } finally { + release(c); + } + + RpbListBucketsResp resp = RPB.RpbListBucketsResp.parseFrom(data); + ByteString[] out = new ByteString[resp.getBucketsCount()]; + for (int i = 0; i < out.length; i++) { + out[i] = resp.getBuckets(i); + } + return out; + } + + public BucketProperties getBucketProperties(ByteString bucket) + throws IOException { + + RiakConnection c = getConnection(); + try { + c.send(MSG_GetBucketReq, RPB.RpbGetBucketReq.newBuilder() + .setBucket(bucket).build()); + + byte[] data = c.receive(MSG_GetBucketResp); + BucketProperties bp = new BucketProperties(); + if (data == null) { + return bp; + } + + bp.init(RPB.RpbGetBucketResp.parseFrom(data)); + return bp; + } finally { + release(c); + } + + } + + public void setBucketProperties(ByteString bucket, BucketProperties props) + throws IOException { + + RPB.RpbSetBucketReq req = RPB.RpbSetBucketReq.newBuilder().setBucket( + bucket).setProps(props.build()).build(); + + RiakConnection c = getConnection(); + try { + c.send(MSG_SetBucketReq, req); + c.receive_code(MSG_SetBucketResp); + } finally { + release(c); + } + } + + // ///////////////////// + + public KeySource listKeys(ByteString bucket) throws IOException { + + RiakConnection c = getConnection(); + c.send(MSG_ListKeysReq, RPB.RpbListKeysReq.newBuilder().setBucket( + bucket).build()); + + return new KeySource(this, c); + } + + // ///////////////////// + + public MapReduceResponseSource mapReduce(JSONObject obj) throws IOException { + return mapReduce(ByteString.copyFromUtf8(obj.toString()), + new RequestMeta().contentType("application/json")); + } + + public MapReduceResponseSource mapReduce(String request, + IRequestMeta meta) throws IOException { + return mapReduce(ByteString.copyFromUtf8(request), meta); + } + + public MapReduceResponseSource mapReduce(ByteString request, + IRequestMeta meta) throws IOException { + RiakConnection c = getConnection(); + + ByteString contentType = meta.getContentType(); + if (contentType == null) { + throw new IllegalArgumentException("no content type"); + } + RpbMapRedReq req = RPB.RpbMapRedReq.newBuilder().setRequest(request) + .setContentType(meta.getContentType()).build(); + + c.send(MSG_MapRedReq, req); + + return new MapReduceResponseSource(this, c, contentType); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.DataInputStream` acquired by call to `getConnection(...)` at line 200 is not released after line 205. +**Note**: potential exception at line 202 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RiakClient.setClientID(ByteString) + +### Procedure Id: +com.basho.riak.pbc.RiakClient.setClientID(com.google.protobuf.ByteString):void.af17e007bae664a35426613318902e69 + +### File: +src/main/java/com/basho/riak/pbc/RiakClient.java + +### Key: +RiakClient.java|setClientID|RESOURCE_LEAK + +### Node Key: +3458a9665feccaa41f237cf73dddd8f0 + +### Hash: +832d89cc0b292271fb35f69e339cc37f + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9840/instruction.md b/inferredbugs-9840/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d7a80cc2e92794045242391665bf43173e7a36f6 --- /dev/null +++ b/inferredbugs-9840/instruction.md @@ -0,0 +1,243 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riak-java-client +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * This file is part of riak-java-pb-client + * + * Copyright (c) 2010 by Trifork + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ + +package com.basho.riak.pbc; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.util.Timer; +import java.util.TimerTask; + +import com.basho.riak.pbc.RPB.RpbErrorResp; +import com.google.protobuf.MessageLite; + +/** + * Wraps the {@link Socket} used to send/receive data to Riak's protocol buffers interface. + * + * See Basho Wiki for more details. + */ +class RiakConnection { + + static final int DEFAULT_RIAK_PB_PORT = 8087; + + private Socket sock; + private DataOutputStream dout; + private DataInputStream din; + + public RiakConnection(InetAddress addr, int port, int bufferSizeKb) throws IOException { + sock = new Socket(addr, port); + + sock.setSendBufferSize(1024 * bufferSizeKb); + + dout = new DataOutputStream(new BufferedOutputStream(sock + .getOutputStream(), 1024 * bufferSizeKb)); + din = new DataInputStream( + new BufferedInputStream(sock.getInputStream(), 1024 * bufferSizeKb)); + } + + /////////////////////// + + void send(int code, MessageLite req) throws IOException { + int len = req.getSerializedSize(); + dout.writeInt(len + 1); + dout.write(code); + req.writeTo(dout); + dout.flush(); + } + + void send(int code) throws IOException { + dout.writeInt(1); + dout.write(code); + dout.flush(); + } + + byte[] receive(int code) throws IOException { + int len = din.readInt(); + int get_code = din.read(); + + byte[] data = null; + if (len > 1) { + data = new byte[len - 1]; + din.readFully(data); + } + + if (get_code == RiakClient.MSG_ErrorResp) { + RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(data); + throw new RiakError(err); + } + + if (code != get_code) { + throw new IOException("bad message code. Expected: " + code + " actual: " + get_code); + } + + return data; + } + + void receive_code(int code) throws IOException, RiakError { + int len = din.readInt(); + int get_code = din.read(); + if (code == RiakClient.MSG_ErrorResp) { + RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(din); + throw new RiakError(err); + } + if (len != 1 || code != get_code) { + throw new IOException("bad message code"); + } + } + + static Timer TIMER = new Timer("riak-client-timeout-thread", true); + TimerTask idle_timeout; + + public void beginIdle() { + idle_timeout = new TimerTask() { + + @Override + public void run() { + RiakConnection.this.timer_fired(this); + } + }; + + TIMER.schedule(idle_timeout, 1000); + } + + synchronized void timer_fired(TimerTask fired_timer) { + if (idle_timeout != fired_timer) { + // if it is not our current timer, then ignore + return; + } + + close(); + } + + void close() { + if (isClosed()) + return; + + try { + sock.close(); + din = null; + dout = null; + sock = null; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + synchronized boolean endIdleAndCheckValid() { + TimerTask tt = idle_timeout; + if (tt != null) { tt.cancel(); } + idle_timeout = null; + + if (isClosed()) { + return false; + } else { + return true; + } + } + + public DataOutputStream getOutputStream() { + return dout; + } + + public boolean isClosed() { + return sock == null || sock.isClosed(); + } + + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.basho.riak.pbc.RiakConnection.close` writes to field `this.com.basho.riak.pbc.RiakConnection.din` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RiakConnection.close() + +### Procedure Id: +com.basho.riak.pbc.RiakConnection.close():void.a946b834a56d1390933ecb12ed4186fc + +### File: +src/main/java/com/basho/riak/pbc/RiakConnection.java + +### Key: +RiakConnection.java|close|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +7b03b9e8783461cd1e05e52327302748 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9847/instruction.md b/inferredbugs-9847/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..84adbbd8f741c70d2c4ecceb6f113750aa5307eb --- /dev/null +++ b/inferredbugs-9847/instruction.md @@ -0,0 +1,1049 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** android-maven-plugin +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2009 Jayway AB + * Copyright (C) 2007-2008 JVending Masa + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.jayway.maven.plugins.android.phase01generatesources; + +import com.android.manifmerger.ManifestMerger; +import com.android.manifmerger.MergerLog; +import com.android.utils.StdLogger; +import com.jayway.maven.plugins.android.AbstractAndroidMojo; +import com.jayway.maven.plugins.android.CommandExecutor; +import com.jayway.maven.plugins.android.ExecutionException; +import com.jayway.maven.plugins.android.common.ZipExtractor; +import com.jayway.maven.plugins.android.configuration.BuildConfigConstant; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.codehaus.plexus.archiver.ArchiverException; +import org.codehaus.plexus.archiver.UnArchiver; +import org.codehaus.plexus.archiver.zip.ZipUnArchiver; +import org.codehaus.plexus.logging.Logger; +import org.codehaus.plexus.logging.console.ConsoleLogger; +import org.w3c.dom.Document; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +import static com.jayway.maven.plugins.android.common.AndroidExtension.AAR; +import static com.jayway.maven.plugins.android.common.AndroidExtension.APK; +import static com.jayway.maven.plugins.android.common.AndroidExtension.APKLIB; +import static com.jayway.maven.plugins.android.common.AndroidExtension.APKSOURCES; + +/** + * Generates R.java based on resources specified by the resources configuration parameter. + * Generates java files based on aidl files. + * + * @author hugo.josefson@jayway.com + * @author Manfred Moser + * @author William Ferguson + * @author Malachi de AElfweald malachid@gmail.com + * + * @goal generate-sources + * @phase generate-sources + * @requiresProject true + * @requiresDependencyResolution compile + */ +public class GenerateSourcesMojo extends AbstractAndroidMojo +{ + + /** + *

    + * Override default merging. You must have SDK Tools r20+ + *

    + * + *

    + * IMPORTANT: The resource plugin needs to be disabled for the + * process-resources phase, so the "default-resources" + * execution must be added. Without this the non-merged manifest will get + * re-copied to the build directory. + *

    + * + *

    + * The androidManifestFile should also be configured to pull + * from the build directory so that later phases will pull the merged + * manifest file. + *

    + *

    + * Example POM Setup: + *

    + * + *
    +     * <build>
    +     *     ...
    +     *     <plugins>
    +     *         ...
    +     *         <plugin>
    +     *             <artifactId>maven-resources-plugin</artifactId>
    +     *             <version>2.6</version>
    +     *             <executions>
    +     *                 <execution>
    +     *                     <phase>initialize</phase>
    +     *                     <goals>
    +     *                         <goal>resources</goal>
    +     *                     </goals>
    +     *                 </execution>
    +     *                 <execution>
    +     *                     <id>default-resources</id>
    +     *                     <phase>DISABLED</phase>
    +     *                 </execution>
    +     *             </executions>
    +     *         </plugin>
    +     *         <plugin>
    +     *             <groupId>com.jayway.maven.plugins.android.generation2</groupId>
    +     *             <artifactId>android-maven-plugin</artifactId>
    +     *             <configuration>
    +     *                 <androidManifestFile>
    +     *                     ${project.build.directory}/AndroidManifest.xml
    +     *                 </androidManifestFile>
    +     *                 <mergeManifests>true</mergeManifests>
    +     *             </configuration>
    +     *             <extensions>true</extensions>
    +     *         </plugin>
    +     *         ...
    +     *     </plugins>
    +     *     ...
    +     * </build>
    +     * 
    + *

    + * You can filter the pre-merged APK manifest. One important note about Eclipse, Eclipse will + * replace the merged manifest with a filtered pre-merged version when the project is refreshed. + * If you want to review the filtered merged version then you will need to open it outside Eclipse + * without refreshing the project in Eclipse. + *

    + *
    +     * <resources>
    +     *     <resource>
    +     *         <targetPath>${project.build.directory}</targetPath>
    +     *         <filtering>true</filtering>
    +     *         <directory>${basedir}</directory>
    +     *         <includes>
    +     *             <include>AndroidManifest.xml</include>
    +     *         </includes>
    +     *     </resource>
    +     * </resources>
    +     * 
    + * + * @parameter expression="${android.mergeManifests}" default-value="false" + */ + protected boolean mergeManifests; + + /** + * Override default generated folder containing R.java + * + * @parameter expression="${android.genDirectory}" default-value="${project.build.directory}/generated-sources/r" + */ + protected File genDirectory; + + /** + * Override default generated folder containing aidl classes + * + * @parameter expression="${android.genDirectoryAidl}" + * default-value="${project.build.directory}/generated-sources/aidl" + */ + protected File genDirectoryAidl; + + /** + *

    Parameter designed to generate custom BuildConfig constants + * + * @parameter expression="${android.buildConfigConstants}" + * @readonly + */ + protected BuildConfigConstant[] buildConfigConstants; + + /** + * Generates the source. + * + * @throws MojoExecutionException if it fails. + * @throws MojoFailureException if it fails. + */ + public void execute() throws MojoExecutionException, MojoFailureException + { + + // If the current POM isn't an Android-related POM, then don't do + // anything. This helps work with multi-module projects. + if ( ! isCurrentProjectAndroid() ) + { + return; + } + + try + { + targetDirectory.mkdirs(); + copyManifest(); + // TODO Do we really want to continue supporting APKSOURCES? How long has it been deprecated + extractSourceDependencies(); + + // Extract the apklib and aar dependencies into unpacked-libs so that they can be referenced in the build. + extractLibraryDependencies(); + + // Copy project assets to combinedAssets so that aapt has a single assets folder to load. + copyFolder( assetsDirectory, combinedAssets ); + + final String[] relativeAidlFileNames1 = findRelativeAidlFileNames( sourceDirectory ); + final String[] relativeAidlFileNames2 = findRelativeAidlFileNames( extractedDependenciesJavaSources ); + final Map relativeApklibAidlFileNames = new HashMap(); + + for ( Artifact artifact : getTransitiveDependencyArtifacts( APKLIB ) ) + { + final File libSourceFolder = getUnpackedApkLibSourceFolder( artifact ); + final String[] apklibAidlFiles = findRelativeAidlFileNames( libSourceFolder ); + relativeApklibAidlFileNames.put( artifact.getId(), apklibAidlFiles ); + } + + mergeManifests(); + generateR(); + generateBuildConfig(); + + // When compiling AIDL for this project, + // make sure we compile AIDL for dependencies as well. + // This is so project A, which depends on project B, can + // use AIDL info from project B in its own AIDL + Map files = new HashMap(); + files.put( sourceDirectory, relativeAidlFileNames1 ); + files.put( extractedDependenciesJavaSources, relativeAidlFileNames2 ); + for ( Artifact artifact : getTransitiveDependencyArtifacts( APKLIB ) ) + { + final File unpackedLibSourceFolder = getUnpackedApkLibSourceFolder( artifact ); + files.put( unpackedLibSourceFolder, relativeApklibAidlFileNames.get( artifact.getId() ) ); + } + generateAidlFiles( files ); + } + catch ( MojoExecutionException e ) + { + getLog().error( "Error when generating sources.", e ); + throw e; + } + } + + /** + * Copy the AndroidManifest.xml from sourceManifestFile to androidManifestFile + * + * @throws MojoExecutionException + */ + protected void copyManifest() throws MojoExecutionException + { + getLog().debug( "copyManifest: " + sourceManifestFile + " -> " + androidManifestFile ); + if ( sourceManifestFile == null ) + { + getLog().info( "Manifest copying disabled. Using default manifest only" ); + return; + } + + try + { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse( sourceManifestFile ); + Source source = new DOMSource( doc ); + + TransformerFactory xfactory = TransformerFactory.newInstance(); + Transformer xformer = xfactory.newTransformer(); + xformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); + + FileWriter writer = null; + try + { + androidManifestFile.getParentFile().mkdirs(); + + writer = new FileWriter( androidManifestFile, false ); + if ( doc.getXmlEncoding() != null && doc.getXmlVersion() != null ) + { + String xmldecl = String.format( "%n", + doc.getXmlVersion(), doc.getXmlEncoding() ); + + writer.write( xmldecl ); + } + Result result = new StreamResult( writer ); + xformer.transform( source, result ); + getLog().info( "Manifest copied from " + sourceManifestFile + " to " + androidManifestFile ); + } + finally + { + IOUtils.closeQuietly( writer ); + } + } + catch ( Exception e ) + { + getLog().error( "Error during copyManifest" ); + throw new MojoExecutionException( "Error during copyManifest", e ); + } + } + + /** + * Extract the source dependencies. + * + * @throws MojoExecutionException if it fails. + */ + protected void extractSourceDependencies() throws MojoExecutionException + { + for ( Artifact artifact : getDirectDependencyArtifacts() ) + { + String type = artifact.getType(); + if ( type.equals( APKSOURCES ) ) + { + getLog().debug( "Detected apksources dependency " + artifact + " with file " + artifact.getFile() + + ". Will resolve and extract..." ); + + final File apksourcesFile = resolveArtifactToFile( artifact ); + getLog().debug( "Extracting " + apksourcesFile + "..." ); + extractApksources( apksourcesFile ); + } + } + + if ( extractedDependenciesJavaResources.exists() ) + { + projectHelper.addResource( project, extractedDependenciesJavaResources.getAbsolutePath(), null, null ); + project.addCompileSourceRoot( extractedDependenciesJavaSources.getAbsolutePath() ); + } + } + + private void extractApksources( File apksourcesFile ) throws MojoExecutionException + { + if ( apksourcesFile.isDirectory() ) + { + getLog().warn( "The apksources artifact points to '" + apksourcesFile + + "' which is a directory; skipping unpacking it." ); + return; + } + final UnArchiver unArchiver = new ZipUnArchiver( apksourcesFile ) + { + @Override + protected Logger getLogger() + { + return new ConsoleLogger( Logger.LEVEL_DEBUG, "dependencies-unarchiver" ); + } + }; + extractedDependenciesDirectory.mkdirs(); + unArchiver.setDestDirectory( extractedDependenciesDirectory ); + try + { + unArchiver.extract(); + } + catch ( ArchiverException e ) + { + throw new MojoExecutionException( "ArchiverException while extracting " + apksourcesFile.getAbsolutePath() + + ". Message: " + e.getLocalizedMessage(), e ); + } + } + + private void extractLibraryDependencies() throws MojoExecutionException + { + final Collection artifacts = getTransitiveDependencyArtifacts(); + getLog().info( "Extracting libs" ); + + for ( Artifact artifact : artifacts ) + { + final String type = artifact.getType(); + if ( type.equals( APKLIB ) ) + { + getLog().info( "Extracting apklib " + artifact.getArtifactId() + "..." ); + extractApklib( artifact ); + } + else if ( type.equals( AAR ) ) + { + getLog().info( "Extracting aar " + artifact.getArtifactId() + "..." ); + extractAarLib( artifact ); + } + else if ( type.equals( APK ) ) + { + getLog().info( "Extracting apk " + artifact.getArtifactId() + "..." ); + extractApkClassesJar( artifact ); + } + else + { + getLog().debug( "Not extracting " + artifact.getArtifactId() + "..." ); + } + } + } + + /** + * Extracts ApkLib and adds the assets and apklib sources and resources to the build. + */ + private void extractApklib( Artifact apklibArtifact ) throws MojoExecutionException + { + getUnpackedLibHelper().extractApklib( apklibArtifact ); + + // Copy the assets to the the combinedAssets folder. + // Add the apklib source and resource to the compile. + // NB apklib sources are added to compileSourceRoot because we may need to compile against them. + // This means the apklib classes will be compiled into target/classes and packaged with this build. + copyFolder( getUnpackedLibAssetsFolder( apklibArtifact ), combinedAssets ); + + final File apklibSourceFolder = getUnpackedApkLibSourceFolder( apklibArtifact ); + final List resourceExclusions = Arrays.asList( "**/*.java", "**/*.aidl" ); + projectHelper.addResource( project, apklibSourceFolder.getAbsolutePath(), null, resourceExclusions ); + project.addCompileSourceRoot( apklibSourceFolder.getAbsolutePath() ); + } + + /** + * Extracts AarLib and if this is an APK build then adds the assets and resources to the build. + */ + private void extractAarLib( Artifact aarArtifact ) throws MojoExecutionException + { + getUnpackedLibHelper().extractAarLib( aarArtifact ); + + // Copy the assets to the the combinedAssets folder, but only if an APK build. + // Ie we only want to package assets that we own. + // Assets should only live within their owners or the final APK. + if ( isAPKBuild() ) + { + copyFolder( getUnpackedLibAssetsFolder( aarArtifact ), combinedAssets ); + } + + // Aar lib resources should only be included if we are building an apk. + // So we need to extract them into a folder that we then add to the resource classpath. + if ( isAPKBuild() ) + { + // Extract the resources from the AAR classes and add them as a resource path to the project. + final File aarClassesJar = getUnpackedAarClassesJar( aarArtifact ); + final ZipExtractor extractor = new ZipExtractor( getLog() ); + final File javaResourcesFolder = getUnpackedAarJavaResourcesFolder( aarArtifact ); + extractor.extract( aarClassesJar, javaResourcesFolder, ".class" ); + projectHelper.addResource( project, javaResourcesFolder.getAbsolutePath(), null, null ); + getLog().debug( "Added AAR resources to resource classpath : " + javaResourcesFolder ); + } + } + + /** + * Copies a dependent APK jar over the top of the placeholder created for it in AarMavenLifeCycleParticipant. + * + * This is necessary because we need the classes of the APK added to the compile classpath. + * NB APK dependencies are uncommon as they should really only be used in a project that tests an apk. + * + * @param artifact APK dependency for this project whose classes will be copied over. + */ + private void extractApkClassesJar( Artifact artifact ) throws MojoExecutionException + { + final File apkClassesJar = getUnpackedLibHelper().getJarFileForApk( artifact ); + final File unpackedClassesJar = getUnpackedLibHelper().getUnpackedClassesJar( artifact ); + try + { + FileUtils.copyFile( apkClassesJar, unpackedClassesJar ); + } + catch ( IOException e ) + { + throw new MojoExecutionException( + "Could not copy APK classes jar " + apkClassesJar + " to " + unpackedClassesJar, e ); + } + getLog().debug( "Copied APK classes jar into compile classpath : " + unpackedClassesJar ); + + } + + private void generateR() throws MojoExecutionException + { + getLog().info( "Generating R file for " + project.getArtifact() ); + + genDirectory.mkdirs(); + + final File[] overlayDirectories = getResourceOverlayDirectories(); + getLog().debug( "Resource overlay folders : " + Arrays.asList( overlayDirectories ) ); + + final CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); + executor.setLogger( this.getLog() ); + + final List commands = new ArrayList(); + commands.add( "package" ); + + commands.add( "-f" ); + commands.add( "--no-crunch" ); + + // inputs + commands.add( "-I" ); + commands.add( getAndroidSdk().getAndroidJar().getAbsolutePath() ); + + commands.add( "-M" ); + commands.add( androidManifestFile.getAbsolutePath() ); + + // NB AndroidBuilder only adds a single folder - presumably it contains a merge of all resources. + for ( File resOverlayDir : overlayDirectories ) + { + if ( resOverlayDir != null && resOverlayDir.exists() ) + { + getLog().debug( "Adding resource overlay folder : " + resOverlayDir ); + commands.add( "-S" ); + commands.add( resOverlayDir.getAbsolutePath() ); + } + } + if ( resourceDirectory.exists() ) + { + getLog().debug( "Adding resource folder : " + resourceDirectory ); + commands.add( "-S" ); + commands.add( resourceDirectory.getAbsolutePath() ); + } + + // Need to include any AAR or APKLIB dependencies when generating R because if any local + // resources directly reference dependent resources then R generation will crash. + addLibraryResourceFolders( commands ); + + // NB aapt only accepts a single assets parameter - combinedAssets is a merge of all assets + if ( combinedAssets.exists() ) + { + getLog().debug( "Adding assets folder : " + combinedAssets ); + commands.add( "-A" ); + commands.add( combinedAssets.getAbsolutePath() ); + } + + // outputs + commands.add( "-m" ); + commands.add( "-J" ); + commands.add( genDirectory.getAbsolutePath() ); + + // Write the output to an optional location + // Used by AndroidBuilder but not by us. + // final File optionalOutputLocation = some file; + // getLog().debug( "Using default package : " + optionalOutputLocation ); + // commands.add( "-F" ); + // commands.add( optionalOutputLocation.getAbsolutePath() ); + + // If a proguard file is defined then output Proguard options to it. + if ( proguardFile != null ) + { + final File parentFolder = proguardFile.getParentFile(); + if ( parentFolder != null ) + { + parentFolder.mkdirs(); + } + getLog().debug( "Adding proguard file : " + proguardFile ); + commands.add( "-G" ); + commands.add( proguardFile.getAbsolutePath() ); + } + + if ( StringUtils.isNotBlank( customPackage ) ) + { + getLog().debug( "Adding custom-package : " + customPackage ); + commands.add( "--custom-package" ); + commands.add( customPackage ); + } + + if ( AAR.equals( project.getArtifact().getType() ) ) + { + getLog().debug( "Adding non-constant-id" ); + commands.add( "--non-constant-id" ); + } + + for ( String aaptExtraArg : aaptExtraArgs ) + { + getLog().debug( "Adding aapt arg : " + aaptExtraArg ); + commands.add( aaptExtraArg ); + } + + if ( StringUtils.isNotBlank( configurations ) ) + { + // Should be comma separated list of locales etc. + getLog().debug( "Adding resource configurations : " + configurations ); + commands.add( "-c" ); + commands.add( configurations ); + } + + // We need to generate R.txt for all projects as it needs to be consumed when generating R class. + // It also needs to be consumed when packaging aar. + commands.add( "--output-text-symbols" ); + commands.add( targetDirectory.getAbsolutePath() ); + + // Allows us to supply multiple -S arguments. + commands.add( "--auto-add-overlay" ); + + getLog().debug( getAndroidSdk().getAaptPath() + " " + commands.toString() ); + try + { + targetDirectory.mkdirs(); + executor.executeCommand( getAndroidSdk().getAaptPath(), commands, project.getBasedir(), false ); + } + catch ( ExecutionException e ) + { + throw new MojoExecutionException( "", e ); + } + + // Generate R.java for apklibs + // Compatibility with Apklib which isn't present in AndroidBuilder + generateApkLibRs(); + + // Generate error corrected R.java for APKLIB dependencies, but only if this is an APK build. + final Set apklibDependencies = getTransitiveDependencyArtifacts( APKLIB ); + if ( !apklibDependencies.isEmpty() && APK.equals( project.getArtifact().getType() ) ) + { + // Generate R.java for each APKLIB based on R.txt + getLog().debug( "Generating R file for APKLIB dependencies" ); + generateRJavaFromRTxt( apklibDependencies, "apklib" ); + } + + // Generate error corrected R.java for AAR dependencies. + final Set aarLibraries = getTransitiveDependencyArtifacts( AAR ); + if ( !aarLibraries.isEmpty() ) + { + // Generate R.java for each AAR based on R.txt + getLog().debug( "Generating R file for AAR dependencies" ); + generateRJavaFromRTxt( aarLibraries, "aar" ); + } + + getLog().info( "Adding R gen folder to compile classpath: " + genDirectory ); + project.addCompileSourceRoot( genDirectory.getAbsolutePath() ); + } + + private void generateRJavaFromRTxt( Set librariesToGenerateR, String type ) throws MojoExecutionException + { + new ResourceClassGenerator( + this, librariesToGenerateR, targetDirectory, genDirectory, getLog(), type + ).generateLibraryRs(); + } + + private void generateApkLibRs() throws MojoExecutionException + { + getLog().debug( "Generating Rs for apklib deps of project " + project.getArtifact() ); + for ( final Artifact artifact : getTransitiveDependencyArtifacts( APKLIB ) ) + { + getLog().debug( "Generating apklib R.java for " + artifact.getArtifactId() + "..." ); + generateRForApkLibDependency( artifact ); + } + } + + private void addLibraryResourceFolders( List commands ) + { + for ( Artifact artifact : getTransitiveDependencyArtifacts() ) + { + getLog().debug( "Considering dep artifact : " + artifact ); + if ( artifact.getType().equals( APKLIB ) || artifact.getType().equals( AAR ) ) + { + final File apklibResDirectory = getUnpackedLibResourceFolder( artifact ); + if ( apklibResDirectory.exists() ) + { + getLog().debug( "Adding apklib or aar resource folder : " + apklibResDirectory ); + commands.add( "-S" ); + commands.add( apklibResDirectory.getAbsolutePath() ); + } + } + } + } + /** + * Executes aapt to generate the R class for the given apklib. + * + * @param apklibArtifact apklib for which to generate the R class. + * @throws MojoExecutionException if it fails. + */ + private void generateRForApkLibDependency( Artifact apklibArtifact ) throws MojoExecutionException + { + final File unpackDir = getUnpackedLibFolder( apklibArtifact ); + getLog().info( "Generating R file for apklibrary: " + apklibArtifact.getGroupId() + + ":" + apklibArtifact.getArtifactId() ); + final File apklibManifest = new File( unpackDir, "AndroidManifest.xml" ); + final File apklibResDir = new File( unpackDir, "res" ); + + final CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); + executor.setLogger( getLog() ); + + List commands = new ArrayList(); + commands.add( "package" ); + commands.add( "--non-constant-id" ); + commands.add( "-m" ); + commands.add( "-J" ); + commands.add( genDirectory.getAbsolutePath() ); + commands.add( "--custom-package" ); + commands.add( extractPackageNameFromAndroidManifest( apklibManifest ) ); + commands.add( "-M" ); + commands.add( apklibManifest.getAbsolutePath() ); + + if ( apklibResDir.exists() ) + { + // Add the APKLIB resources first so they overlay any of it's dependencies. + commands.add( "-S" ); + commands.add( apklibResDir.getAbsolutePath() ); + } + + final Set apklibDeps = getDependencyResolver().getLibraryDependenciesFor( project, apklibArtifact ); + getLog().debug( "apklib dependencies = " + apklibDeps ); + for ( Artifact dependency : apklibDeps ) + { + // Add in the resources that are dependencies of the apklib. + final String extension = dependency.getType(); + final File dependencyResDir = getUnpackedLibResourceFolder( dependency ); + if ( ( extension.equals( APKLIB ) || extension.equals( AAR ) ) && dependencyResDir.exists() ) + { + commands.add( "-S" ); + commands.add( dependencyResDir.getAbsolutePath() ); + } + } + + commands.add( "--auto-add-overlay" ); + + // Create combinedAssets for this apklib dependency - can't have multiple -A args + final File apklibCombAssets = new File( getUnpackedLibFolder( apklibArtifact ), "combined-assets" ); + for ( Artifact dependency : apklibDeps ) + { + // Accumulate assets for dependencies of the apklib (if they exist). + final String extension = dependency.getType(); + final File dependencyAssetsDir = getUnpackedLibAssetsFolder( dependency ); + if ( ( extension.equals( APKLIB ) || extension.equals( AAR ) ) ) + { + copyFolder( dependencyAssetsDir, apklibCombAssets ); + } + } + // Overlay the apklib dependency assets (if they exist) + final File apkLibAssetsDir = getUnpackedLibAssetsFolder( apklibArtifact ); + copyFolder( apkLibAssetsDir, apklibCombAssets ); + + // If there are any combined assets for the apklib dependency then provide them to aapt. + if ( apklibCombAssets.exists() ) + { + commands.add( "-A" ); + commands.add( apklibCombAssets.getAbsolutePath() ); + } + + commands.add( "-I" ); + commands.add( getAndroidSdk().getAndroidJar().getAbsolutePath() ); + if ( StringUtils.isNotBlank( configurations ) ) + { + commands.add( "-c" ); + commands.add( configurations ); + } + + for ( String aaptExtraArg : aaptExtraArgs ) + { + commands.add( aaptExtraArg ); + } + + // We need to generate R.txt for all projects as it needs to be consumed when generating R class. + // It also needs to be consumed when packaging aar. + commands.add( "--output-text-symbols" ); + commands.add( unpackDir.getAbsolutePath() ); + + getLog().debug( getAndroidSdk().getAaptPath() + " " + commands.toString() ); + try + { + executor.executeCommand( getAndroidSdk().getAaptPath(), commands, project.getBasedir(), false ); + } + catch ( ExecutionException e ) + { + throw new MojoExecutionException( "", e ); + } + } + + private void mergeManifests() throws MojoExecutionException + { + getLog().debug( "mergeManifests: " + mergeManifests ); + + if ( !mergeManifests ) + { + getLog().info( "Manifest merging disabled. Using project manifest only" ); + return; + } + + getLog().info( "Getting manifests of dependent apklibs" ); + List libManifests = new ArrayList(); + for ( Artifact artifact : getTransitiveDependencyArtifacts( APKLIB, AAR ) ) + { + final File libManifest = new File( getUnpackedLibFolder( artifact ), "AndroidManifest.xml" ); + if ( !libManifest.exists() ) + { + throw new MojoExecutionException( artifact.getArtifactId() + " is missing AndroidManifest.xml" ); + } + + libManifests.add( libManifest ); + } + + if ( !libManifests.isEmpty() ) + { + final File mergedManifest = new File( androidManifestFile.getParent(), "AndroidManifest-merged.xml" ); + final StdLogger stdLogger = new StdLogger( StdLogger.Level.VERBOSE ); + final ManifestMerger merger = new ManifestMerger( MergerLog.wrapSdkLog( stdLogger ), null ); + + getLog().info( "Merging manifests of dependent apklibs" ); + + final boolean mergeSuccess = merger.process( mergedManifest, androidManifestFile, + libManifests.toArray( new File[libManifests.size()] ), null, null ); + + if ( mergeSuccess ) + { + // Replace the original manifest file with the merged one so that + // the rest of the build will pick it up. + androidManifestFile.delete(); + mergedManifest.renameTo( androidManifestFile ); + getLog().info( "Done Merging Manifests of APKLIBs" ); + } + else + { + getLog().error( "Manifests were not merged!" ); + throw new MojoExecutionException( "Manifests were not merged!" ); + } + } + else + { + getLog().info( "No APKLIB manifests found. Using project manifest only." ); + } + } + + private void generateBuildConfig() throws MojoExecutionException + { + getLog().debug( "Generating BuildConfig file" ); + + // Create the BuildConfig for our package. + String packageName = extractPackageNameFromAndroidManifest( androidManifestFile ); + if ( StringUtils.isNotBlank( customPackage ) ) + { + packageName = customPackage; + } + generateBuildConfigForPackage( packageName ); + + try + { + // Generate the BuildConfig for any APKLIB and AAR dependencies. + // Need to generate for AAR, because some old AARs like ActionBarSherlock do not have BuildConfig (or R) + for ( Artifact artifact : getTransitiveDependencyArtifacts( APKLIB, AAR ) ) + { + final File manifest = new File( getUnpackedLibFolder( artifact ), "AndroidManifest.xml" ); + final String depPackageName = extractPackageNameFromAndroidManifest( manifest ); + + if ( artifact.getType().equals( AAR ) ) + { + final JarFile jar = new JarFile( getUnpackedAarClassesJar( artifact ) ); + final JarEntry entry = jar.getJarEntry( depPackageName.replace( '.', '/' ) + "/BuildConfig.class" ); + + if ( entry != null ) + { + getLog().info( "Skip BuildConfig.java generation for " + + artifact.getGroupId() + " " + artifact.getArtifactId() ); + continue; + } + } + + generateBuildConfigForPackage( depPackageName ); + } + } + catch ( IOException e ) + { + getLog().error( "Error generating BuildConfig ", e ); + throw new MojoExecutionException( "Error generating BuildConfig", e ); + } + } + + private void generateBuildConfigForPackage( String packageName ) throws MojoExecutionException + { + File outputFolder = new File( genDirectory, packageName.replace( ".", File.separator ) ); + outputFolder.mkdirs(); + + StringBuilder buildConfig = new StringBuilder(); + buildConfig.append( "package " ).append( packageName ).append( ";\n\n" ); + buildConfig.append( "public final class BuildConfig {\n" ); + buildConfig.append( " public static final boolean DEBUG = " ).append( !release ).append( ";\n" ); + for ( BuildConfigConstant constant : buildConfigConstants ) + { + String value = constant.getValue(); + if ( "String".equals( constant.getType() ) ) + { + value = "\"" + value + "\""; + } + + buildConfig.append( " public static final " ) + .append( constant.getType() ) + .append( " " ) + .append( constant.getName() ) + .append( " = " ) + .append( value ) + .append( ";\n" ); + } + buildConfig.append( "}\n" ); + + + File outputFile = new File( outputFolder, "BuildConfig.java" ); + try + { + FileUtils.writeStringToFile( outputFile, buildConfig.toString() ); + } + catch ( IOException e ) + { + getLog().error( "Error generating BuildConfig ", e ); + throw new MojoExecutionException( "Error generating BuildConfig", e ); + } + } + + /** + * Given a map of source directories to list of AIDL (relative) filenames within each, + * runs the AIDL compiler for each, such that all source directories are available to + * the AIDL compiler. + * + * @param files Map of source directory File instances to the relative paths to all AIDL files within + * @throws MojoExecutionException If the AIDL compiler fails + */ + private void generateAidlFiles( Map files ) + throws MojoExecutionException + { + List protoCommands = new ArrayList(); + protoCommands.add( "-p" + getAndroidSdk().getPathForFrameworkAidl() ); + + genDirectoryAidl.mkdirs(); + getLog().warn( "Adding AIDL gen folder to compile classpath: " + genDirectoryAidl ); + project.addCompileSourceRoot( genDirectoryAidl.getPath() ); + Set sourceDirs = files.keySet(); + for ( File sourceDir : sourceDirs ) + { + protoCommands.add( "-I" + sourceDir ); + } + for ( File sourceDir : sourceDirs ) + { + for ( String relativeAidlFileName : files.get( sourceDir ) ) + { + File targetDirectory = new File( genDirectoryAidl, new File( relativeAidlFileName ).getParent() ); + targetDirectory.mkdirs(); + + final String shortAidlFileName = new File( relativeAidlFileName ).getName(); + final String shortJavaFileName = shortAidlFileName.substring( 0, shortAidlFileName.lastIndexOf( "." ) ) + + ".java"; + final File aidlFileInSourceDirectory = new File( sourceDir, relativeAidlFileName ); + + List commands = new ArrayList( protoCommands ); + commands.add( aidlFileInSourceDirectory.getAbsolutePath() ); + commands.add( new File( targetDirectory, shortJavaFileName ).getAbsolutePath() ); + try + { + CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); + executor.setLogger( this.getLog() ); + + executor.executeCommand( getAndroidSdk().getAidlPath(), commands, project.getBasedir(), + false ); + } + catch ( ExecutionException e ) + { + throw new MojoExecutionException( "", e ); + } + } + } + } + + private String[] findRelativeAidlFileNames( File sourceDirectory ) + { + final String[] relativeAidlFileNames = findFilesInDirectory( sourceDirectory, "**/*.aidl" ); + if ( relativeAidlFileNames.length == 0 ) + { + getLog().debug( "ANDROID-904-002: Found aidl files: Count = " + relativeAidlFileNames.length ); + } + else + { + getLog().info( "ANDROID-904-002: Found aidl files: Count = " + relativeAidlFileNames.length ); + } + return relativeAidlFileNames; + } + + /** + * @return true if the pom type is APK, APKLIB, or APKSOURCES + */ + private boolean isCurrentProjectAndroid() + { + Set androidArtifacts = new HashSet() + { + { + addAll( Arrays.asList( APK, APKLIB, APKSOURCES, AAR ) ); + } + }; + return androidArtifacts.contains( project.getArtifact().getType() ); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.util.jar.JarFile` acquired to `jar` by call to `JarFile(...)` at line 833 is not released after line 834. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GenerateSourcesMojo.generateBuildConfig() + +### Procedure Id: +com.jayway.maven.plugins.android.phase01generatesources.GenerateSourcesMojo.generateBuildConfig():vo.48d774a7e7ecc8f5bcf92c21c4b5c53b + +### File: +src/main/java/com/jayway/maven/plugins/android/phase01generatesources/GenerateSourcesMojo.java + +### Key: +GenerateSourcesMojo.java|generateBuildConfig|RESOURCE_LEAK + +### Node Key: +7e9fc31bc469440d6384630f8b346526 + +### Hash: +63f03828ac5c4cf93e372d925c9d5bdd + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9849/instruction.md b/inferredbugs-9849/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d45f4190760fc12f03516d041703fbc1856f8e98 --- /dev/null +++ b/inferredbugs-9849/instruction.md @@ -0,0 +1,580 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** android-maven-plugin +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.jayway.maven.plugins.android.phase05compile; + +import com.jayway.maven.plugins.android.common.AetherHelper; +import com.jayway.maven.plugins.android.common.AndroidExtension; +import com.jayway.maven.plugins.android.common.JarHelper; +import com.jayway.maven.plugins.android.common.NativeHelper; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.filefilter.TrueFileFilter; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.DefaultArtifact; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.logging.Log; +import org.sonatype.aether.RepositorySystem; +import org.sonatype.aether.RepositorySystemSession; +import org.sonatype.aether.repository.RemoteRepository; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +/** + * Various helper methods for dealing with Android Native makefiles. + * + * @author Johan Lindquist + */ +public class MakefileHelper +{ + public static final String MAKEFILE_CAPTURE_FILE = "ANDROID_MAVEN_PLUGIN_LOCAL_C_INCLUDES_FILE"; + + public static final boolean IS_WINDOWS = System.getProperty( "os.name" ).toLowerCase().indexOf( "windows" ) >= 0; + public static final String WINDOWS_DRIVE_ROOT_REGEX = "[a-zA-Z]:\\\\"; + + /** + * Holder for the result of creating a makefile. This in particular keep tracks of all directories created + * for extracted header files. + */ + public static class MakefileHolder + { + String makeFile; + List includeDirectories; + + public MakefileHolder( List includeDirectories, String makeFile ) + { + this.includeDirectories = includeDirectories; + this.makeFile = makeFile; + } + + public List getIncludeDirectories() + { + return includeDirectories; + } + + public String getMakeFile() + { + return makeFile; + } + } + + private Log log; + private final RepositorySystem repoSystem; + private final RepositorySystemSession repoSession; + private final List projectRepos; + private final File unpackedApkLibsDirectory; + + /** + * Initialize the MakefileHelper by storing the supplied parameters to local variables. + * @param log + * @param repoSystem + * @param repoSession + * @param projectRepos + * @param unpackedApkLibsDirectory + */ + public MakefileHelper( Log log, + RepositorySystem repoSystem, RepositorySystemSession repoSession, + List projectRepos, + File unpackedApkLibsDirectory ) + { + this.log = log; + this.repoSystem = repoSystem; + this.repoSession = repoSession; + this.projectRepos = projectRepos; + this.unpackedApkLibsDirectory = unpackedApkLibsDirectory; + } + + /** + * Cleans up all include directories created in the temp directory during the build. + * + * @param makefileHolder The holder produced by the + * {@link MakefileHelper#createMakefileFromArtifacts(java.io.File, java.util.Set, + * boolean, org.sonatype.aether.RepositorySystemSession, java.util.List, org.sonatype.aether.RepositorySystem)} + */ + public static void cleanupAfterBuild( MakefileHolder makefileHolder ) + { + + if ( makefileHolder.getIncludeDirectories() != null ) + { + for ( File file : makefileHolder.getIncludeDirectories() ) + { + try + { + FileUtils.deleteDirectory( file ); + } + catch ( IOException e ) + { + e.printStackTrace(); + } + } + } + + } + + /** + * Creates an Android Makefile based on the specified set of static library dependency artifacts. + * + * @param outputDir Directory to resolve artifact locations relative to. Makefiles contain relative paths + * @param artifacts The list of (static library) dependency artifacts to create the Makefile from + * @param useHeaderArchives If true, the Makefile should include a LOCAL_EXPORT_C_INCLUDES statement, pointing to + * the location where the header archive was expanded + * @param repoSession + * @param projectRepos + * @param repoSystem + * @return The created Makefile + */ + public MakefileHolder createMakefileFromArtifacts( File outputDir, Set artifacts, + String ndkArchitecture, + boolean useHeaderArchives ) + throws IOException, MojoExecutionException + { + + final StringBuilder makeFile = new StringBuilder( "# Generated by Android Maven Plugin\n" ); + final List includeDirectories = new ArrayList(); + + // Add now output - allows us to somewhat intelligently determine the include paths to use for the header + // archive + makeFile.append( "$(shell echo \"LOCAL_C_INCLUDES=$(LOCAL_C_INCLUDES)\" > $(" + MAKEFILE_CAPTURE_FILE + "))" ); + makeFile.append( '\n' ); + makeFile.append( "$(shell echo \"LOCAL_PATH=$(LOCAL_PATH)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); + makeFile.append( '\n' ); + makeFile.append( "$(shell echo \"LOCAL_MODULE_FILENAME=$(LOCAL_MODULE_FILENAME)\" >> $(" + + MAKEFILE_CAPTURE_FILE + "))" ); + makeFile.append( '\n' ); + makeFile.append( "$(shell echo \"LOCAL_MODULE=$(LOCAL_MODULE)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); + makeFile.append( '\n' ); + makeFile.append( "$(shell echo \"LOCAL_CFLAGS=$(LOCAL_CFLAGS)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); + makeFile.append( '\n' ); + + if ( ! artifacts.isEmpty() ) + { + for ( Artifact artifact : artifacts ) + { + boolean apklibStatic = false; + + makeFile.append( "#\n" ); + makeFile.append( "# Group ID: " ); + makeFile.append( artifact.getGroupId() ); + makeFile.append( '\n' ); + makeFile.append( "# Artifact ID: " ); + makeFile.append( artifact.getArtifactId() ); + makeFile.append( '\n' ); + makeFile.append( "# Artifact Type: " ); + makeFile.append( artifact.getType() ); + makeFile.append( '\n' ); + makeFile.append( "# Version: " ); + makeFile.append( artifact.getVersion() ); + makeFile.append( '\n' ); + makeFile.append( "include $(CLEAR_VARS)" ); + makeFile.append( '\n' ); + makeFile.append( "LOCAL_MODULE := " ); + makeFile.append( artifact.getArtifactId() ); + makeFile.append( '\n' ); + apklibStatic = addLibraryDetails( makeFile, outputDir, artifact, ndkArchitecture ); + if ( useHeaderArchives ) + { + try + { + Artifact harArtifact = new DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(), + artifact.getVersion(), artifact.getScope(), "har", artifact.getClassifier(), + artifact.getArtifactHandler() ); + final Artifact resolvedHarArtifact = AetherHelper + .resolveArtifact( harArtifact, repoSystem, repoSession, projectRepos ); + + File includeDir = new File( System.getProperty( "java.io.tmpdir" ), + "android_maven_plugin_native_includes" + System.currentTimeMillis() + "_" + + resolvedHarArtifact.getArtifactId() ); + includeDir.deleteOnExit(); + includeDirectories.add( includeDir ); + + JarHelper.unjar( new JarFile( resolvedHarArtifact.getFile() ), includeDir, + new JarHelper.UnjarListener() + { + @Override + public boolean include( JarEntry jarEntry ) + { + return ! jarEntry.getName().startsWith( "META-INF" ); + } + } ); + + makeFile.append( "LOCAL_EXPORT_C_INCLUDES := " ); + final String str = includeDir.getAbsolutePath(); + makeFile.append( str ); + makeFile.append( '\n' ); + + if ( log.isDebugEnabled() ) + { + Collection includes = FileUtils.listFiles( includeDir, + TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE ); + log.debug( "Listing LOCAL_EXPORT_C_INCLUDES for " + artifact.getId() + ": " + includes ); + } + } + catch ( Exception e ) + { + throw new MojoExecutionException( + "Error while resolving header archive file for: " + artifact.getArtifactId(), e ); + } + } + if ( "a".equals( artifact.getType() ) || apklibStatic ) + { + makeFile.append( "include $(PREBUILT_STATIC_LIBRARY)\n" ); + } + else + { + makeFile.append( "include $(PREBUILT_SHARED_LIBRARY)\n" ); + } + } + } + + return new MakefileHolder( includeDirectories, makeFile.toString() ); + } + + private boolean addLibraryDetails( StringBuilder makeFile, File outputDir, + Artifact artifact, String ndkArchitecture ) throws IOException + { + boolean apklibStatic = false; + if ( AndroidExtension.APKLIB.equals( artifact.getType() ) ) + { + String classifier = artifact.getClassifier(); + String architecture = ( classifier != null ) ? classifier : ndkArchitecture; + // + // We assume that APKLIB contains a single static OR shared library + // that we should link against. The follow code identifies that file. + // + File[] staticLibs = NativeHelper.listNativeFiles( artifact, unpackedApkLibsDirectory, + architecture, true ); + if ( staticLibs != null && staticLibs.length > 0 ) + { + int libIdx = findApklibNativeLibrary( staticLibs, artifact.getArtifactId() ); + apklibStatic = true; + addLibraryDetails( makeFile, outputDir, staticLibs[libIdx], "" ); + } + else + { + File[] sharedLibs = NativeHelper.listNativeFiles( artifact, unpackedApkLibsDirectory, + architecture, false ); + if ( sharedLibs == null ) + { + throw new IOException( "Failed to find any library file in APKLIB" ); + } + int libIdx = findApklibNativeLibrary( sharedLibs, artifact.getArtifactId() ); + addLibraryDetails( makeFile, outputDir, sharedLibs[libIdx], "" ); + } + } + else + { + addLibraryDetails( makeFile, outputDir, artifact.getFile(), artifact.getArtifactId() ); + } + + return apklibStatic; + } + + private void addLibraryDetails( StringBuilder makeFile, File outputDir, File libFile, String outputName ) + throws IOException + { + String localPath = resolveRelativePath( outputDir, libFile ); + localPath = localPath.substring( 0, localPath.indexOf( libFile.getName() ) - 1 ); + + makeFile.append( "LOCAL_PATH := " ); + makeFile.append( localPath ); + makeFile.append( '\n' ); + makeFile.append( "LOCAL_SRC_FILES := " ); + makeFile.append( libFile.getName() ); + makeFile.append( '\n' ); + makeFile.append( "LOCAL_MODULE_FILENAME := " ); + if ( "".equals( outputName ) ) + { + makeFile.append( FilenameUtils.removeExtension( libFile.getName() ) ); + } + else + { + makeFile.append( outputName ); + } + makeFile.append( '\n' ); + } + + /** + * @param libs the array of possible library files. Must not be null. + * @return the index in the array of the library to use + * @throws IOException if a library cannot be identified + */ + private int findApklibNativeLibrary( File[] libs, String artifactName ) throws IOException + { + int libIdx = -1; + + if ( libs.length == 1 ) + + { + libIdx = 0; + } + else + { + log.info( "Found multiple library files, looking for name match with artifact" ); + StringBuilder sb = new StringBuilder(); + for ( int i = 0; i < libs.length; i++ ) + { + if ( sb.length() != 0 ) + { + sb.append( ", " ); + } + sb.append( libs[i].getName() ); + if ( libs[i].getName().startsWith( "lib" + artifactName ) ) + { + if ( libIdx != -1 ) + { + // We have multiple matches, tell the user we can't handle this ... + throw new IOException( "Found multiple libraries matching artifact name " + artifactName + + ". Please use unique artifact/library names." ); + + } + libIdx = i; + } + } + if ( libIdx < 0 ) + { + throw new IOException( "Unable to determine main library from " + sb.toString() + + " APKLIB should contain only 1 library or a library matching the artifact name" ); + } + } + return libIdx; + } + + /** + * Resolves the relative path of the specified artifact + * + * @param outputDirectory typically the parent directory of the directory containing the makefile + * @param file + * @return + */ + protected static String resolveRelativePath( File outputDirectory, File file ) throws IOException + { + String resolvedPath = file.getCanonicalPath(); + + String strOutputDirectoryPath = outputDirectory.getCanonicalPath(); + String strFilePath = file.getCanonicalPath(); + //System.out.println( "Resolving " + strFilePath + " against " + strOutputDirectoryPath ); + + if ( strFilePath.startsWith( strOutputDirectoryPath ) ) + { + // Simple case where file is in a subdirectory of outputDirectory + resolvedPath = strFilePath.substring( strOutputDirectoryPath.length() + 1 ); + } + else + { + // Look for commonality in paths + List outputDirectoryPathParts = splitPath( outputDirectory.getCanonicalFile() ); + List filePathParts = splitPath( file.getCanonicalFile() ); + int commonDepth = 0; + int maxCommonDepth = Math.min( outputDirectoryPathParts.size(), filePathParts.size() ); + for ( int i = 0; + ( i < maxCommonDepth ) + && outputDirectoryPathParts.get( i ).equals( filePathParts.get( i ) ); + i++ ) + { + commonDepth++; + } + // If there is a common root build a relative path between the common roots + if ( commonDepth > 0 ) + { + final StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append( ".." ); + for ( int i = 0; i < outputDirectoryPathParts.size() - commonDepth - 1; i++ ) + { + stringBuilder.append( File.separator ); + stringBuilder.append( ".." ); + } + for ( int i = commonDepth; i < filePathParts.size(); i++ ) + { + stringBuilder.append( File.separator ); + stringBuilder.append( filePathParts.get( i ) ); + } + resolvedPath = stringBuilder.toString(); + } + else + { + if ( IS_WINDOWS ) + { + // Windows has no common root directory, cannot resolve a path + // across drives so ... + throw new IOException( "Unable to resolve relative path across windows drives" ); + } + + // no intersection between paths so calculate a path via the root directory + final StringBuilder stringBuilder = new StringBuilder(); + + File depthCheck = outputDirectory.getParentFile(); + while ( depthCheck != null ) + { + if ( stringBuilder.length() > 0 ) + { + stringBuilder.append( File.separator ); + } + stringBuilder.append( ".." ); + depthCheck = depthCheck.getParentFile(); + } + + resolvedPath = stringBuilder.toString() + strFilePath; + } + } + + //System.out.println( "resolvedPath = " + resolvedPath ); + return resolvedPath; + } + + /** + * Method to split the path components of a file into a List + * @param f the file to split + * @return a new list containing the components of the path as strings + */ + protected static List splitPath( File f ) + { + List result; + File parent = f.getParentFile(); + if ( parent == null ) + { + result = new ArrayList(); + if ( f.getName().length() > 0 ) + { + // We're at the root but have a name so we have a relative path + // for which we need to add the first component to the list + result.add( f.getName() ); + } + else if ( IS_WINDOWS ) + { + String strF = f.toString(); + if ( strF.matches( WINDOWS_DRIVE_ROOT_REGEX ) ) + { + // We're on windows and the path is :\ so we + // add the : to the list + result.add( strF.substring( 0, strF.length() - 1 ).toUpperCase() ); + } + } + } + else + { + result = splitPath( parent ); + result.add( f.getName() ); + } + return result; + } + + /** + * Creates a list of artifacts suitable for use in the LOCAL_STATIC_LIBRARIES or LOCAL_SHARED_LIBRARIES + * variable in an Android makefile + * + * @param resolvedLibraryList + * @param staticLibrary + * @return a list of Ids for artifacts that include static or shared libraries + */ + public String createLibraryList( Set resolvedLibraryList, + String ndkArchitecture, + boolean staticLibrary ) + { + StringBuilder sb = new StringBuilder(); + + for ( Artifact a : resolvedLibraryList ) + { + if ( staticLibrary && "a".equals( a.getType() ) ) + { + sb.append( a.getArtifactId() ); + } + if ( ! staticLibrary && "so".equals( a.getType() ) ) + { + sb.append( a.getArtifactId() ); + } + if ( AndroidExtension.APKLIB.equals( a.getType() ) ) + { + File[] libFiles = NativeHelper.listNativeFiles( a, unpackedApkLibsDirectory, + ndkArchitecture, staticLibrary ); + if ( libFiles != null && libFiles.length > 0 ) + { + sb.append( a.getArtifactId() ); + } + + } + sb.append( " " ); + } + + return sb.toString(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.util.jar.JarFile` acquired by call to `JarFile(...)` at line 195 is not released after line 195. +**Note**: potential exception at line 195 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +MakefileHelper$MakefileHolder MakefileHelper.createMakefileFromArtifacts(File,Set,String,boolean) + +### Procedure Id: +com.jayway.maven.plugins.android.phase05compile.MakefileHelper.createMakefileFromArtifacts(java.io.F.9c01dea32c860ab0e4cbf203f0e4833f + +### File: +src/main/java/com/jayway/maven/plugins/android/phase05compile/MakefileHelper.java + +### Key: +MakefileHelper.java|createMakefileFromArtifacts|RESOURCE_LEAK + +### Node Key: +3cc09a942e4229549bed859de33fc95d + +### Hash: +345f301c82ec83157f4fa79e42e864bc + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9871/instruction.md b/inferredbugs-9871/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2c7ede3c4c78193d48f6a8f08bd70d603be08a6d --- /dev/null +++ b/inferredbugs-9871/instruction.md @@ -0,0 +1,138 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-apns +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.notnoop.apns.internal; + +import static com.notnoop.apns.internal.MockingUtils.*; + +import java.io.ByteArrayOutputStream; + +import javax.net.SocketFactory; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.Ignore; + +import com.notnoop.apns.SimpleApnsNotification; + + +public class ApnsConnectionTest { + SimpleApnsNotification msg = new SimpleApnsNotification ("a87d8878d878a79", "{\"aps\":{}}"); + + @Test + public void simpleSocket() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + SocketFactory factory = mockSocketFactory(baos, null); + packetSentRegardless(factory, baos); + } + + @Test + @Ignore + public void closedSocket() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + SocketFactory factory = mockClosedThenOpenSocket(baos, null, true, 1); + packetSentRegardless(factory, baos); + } + + @Test + public void errorOnce() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + SocketFactory factory = mockClosedThenOpenSocket(baos, null, false, 1); + packetSentRegardless(factory, baos); + } + + @Test + public void errorTwice() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + SocketFactory factory = mockClosedThenOpenSocket(baos, null, false, 2); + packetSentRegardless(factory, baos); + } + + /** + * Connection fails after three retries + */ + @Test(expected = Exception.class) + public void errorThrice() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + SocketFactory factory = mockClosedThenOpenSocket(baos, null, false, 3); + packetSentRegardless(factory, baos); + } + + private void packetSentRegardless(SocketFactory sf, ByteArrayOutputStream baos) { + ApnsConnectionImpl connection = new ApnsConnectionImpl(sf, "localhost", 80); + connection.DELAY_IN_MS = 0; + connection.sendMessage(msg); + Assert.assertArrayEquals(msg.marshall(), baos.toByteArray()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.notnoop.apns.internal.ApnsConnectionImpl` acquired to `connection` by call to `ApnsConnectionImpl(...)` at line 59 is not released after line 61. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ApnsConnectionTest.packetSentRegardless(SocketFactory,ByteArrayOutputStream) + +### Procedure Id: +com.notnoop.apns.internal.ApnsConnectionTest.packetSentRegardless(javax.net.SocketFactory,java.io.By.0c0a357a6d832fe3eaa9bd32a218aa84 + +### File: +src/test/java/com/notnoop/apns/internal/ApnsConnectionTest.java + +### Key: +ApnsConnectionTest.java|packetSentRegardless|RESOURCE_LEAK + +### Node Key: +141d12c688da63d404fcff6ee9c41043 + +### Hash: +1fc59002d596500cb3bc40b397ff51c9 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9876/instruction.md b/inferredbugs-9876/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..101ea898d897eaae65fd7fc9656641039ec2e6db --- /dev/null +++ b/inferredbugs-9876/instruction.md @@ -0,0 +1,387 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** frontend-maven-plugin +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.eirslett.maven.plugins.frontend.lib; + +import org.apache.commons.io.FileUtils; +import org.codehaus.jackson.map.ObjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; + +public class NodeAndNPMInstaller { + + private static final String INSTALL_PATH = "node"; + private static final String VERSION = "version"; + + public static final String DEFAULT_NODEJS_DOWNLOAD_ROOT = "https://nodejs.org/dist/"; + public static final String DEFAULT_NPM_DOWNLOAD_ROOT = "http://registry.npmjs.org/npm/-/"; + + private String nodeVersion, npmVersion, nodeDownloadRoot, npmDownloadRoot, userName, password; + + private static final Object lock = new Object(); + + private final Logger logger; + private final InstallConfig config; + private final ArchiveExtractor archiveExtractor; + private final FileDownloader fileDownloader; + + NodeAndNPMInstaller(InstallConfig config, ArchiveExtractor archiveExtractor, FileDownloader fileDownloader) { + this.logger = LoggerFactory.getLogger(getClass()); + this.config = config; + this.archiveExtractor = archiveExtractor; + this.fileDownloader = fileDownloader; + } + + public NodeAndNPMInstaller setNodeVersion (String nodeVersion) { + this.nodeVersion = nodeVersion; + return this; + } + + public NodeAndNPMInstaller setNodeDownloadRoot (String nodeDownloadRoot) { + this.nodeDownloadRoot = nodeDownloadRoot; + return this; + } + + public NodeAndNPMInstaller setNpmVersion (String npmVersion) { + this.npmVersion = npmVersion; + return this; + } + + public NodeAndNPMInstaller setNpmDownloadRoot (String npmDownloadRoot) { + this.npmDownloadRoot = npmDownloadRoot; + return this; + } + + public NodeAndNPMInstaller setUserName (String userName) { + this.userName = userName; + return this; + } + + public NodeAndNPMInstaller setPassword (String password) { + this.password = password; + return this; + } + + public void install() throws InstallationException { + if(nodeDownloadRoot == null || nodeDownloadRoot.isEmpty()){ + nodeDownloadRoot = DEFAULT_NODEJS_DOWNLOAD_ROOT; + } + if(npmDownloadRoot == null || npmDownloadRoot.isEmpty()){ + npmDownloadRoot = DEFAULT_NPM_DOWNLOAD_ROOT; + } + synchronized (lock) { + if (!nodeIsAlreadyInstalled()) { + logger.info("Installing node version {}", nodeVersion); + if (!nodeVersion.startsWith("v")) { + logger.warn("Node version does not start with naming convention 'v'."); + } + if (config.getPlatform().isWindows()) { + installNodeForWindows(); + } else { + installNodeDefault(); + } + } + if (!npmIsAlreadyInstalled()) { + installNpm(); + } + } + } + + private boolean nodeIsAlreadyInstalled() { + try { + NodeExecutorConfig executorConfig = new InstallNodeExecutorConfig(config); + File nodeFile = executorConfig.getNodePath(); + if(nodeFile.exists()){ + final String version = new NodeExecutor(executorConfig, Arrays.asList("--version"), null).executeAndGetResult(); + + if(version.equals(nodeVersion)){ + logger.info("Node {} is already installed.", version); + return true; + } else { + logger.info("Node {} was installed, but we need version {}", version, nodeVersion); + return false; + } + } else { + return false; + } + } catch (ProcessExecutionException e) { + return false; + } + } + + private boolean npmIsAlreadyInstalled(){ + try { + final File npmPackageJson = new File(config.getInstallDirectory() + Utils.normalize("/node/node_modules/npm/package.json")); + if(npmPackageJson.exists()){ + HashMap data = new ObjectMapper().readValue(npmPackageJson, HashMap.class); + if(data.containsKey(VERSION)){ + final String foundNpmVersion = data.get(VERSION).toString(); + if(foundNpmVersion.equals(npmVersion)) { + logger.info("NPM {} is already installed.", foundNpmVersion); + return true; + } else { + logger.info("NPM {} was installed, but we need version {}", foundNpmVersion, npmVersion); + return false; + } + } else { + logger.info("Could not read NPM version from package.json"); + return false; + } + } else { + return false; + } + } catch (IOException ex){ + throw new RuntimeException("Could not read package.json", ex); + } + } + + private void installNpm() throws InstallationException { + try { + logger.info("Installing npm version {}", npmVersion); + final String downloadUrl = npmDownloadRoot +"npm-"+npmVersion+".tgz"; + + CacheDescriptor cacheDescriptor = new CacheDescriptor("npm", npmVersion, "tar.gz"); + + File archive = config.getCacheResolver().resolve(cacheDescriptor); + + downloadFileIfMissing(downloadUrl, archive, userName, password); + + File installDirectory = getInstallDirectory(); + File nodeModulesDirectory = new File(installDirectory, "node_modules"); + + // We need to delete the existing npm directory first so we clean out any old files, and + // so we can rename the package directory below. + File oldNpmDirectory = new File(installDirectory, "npm"); + File npmDirectory = new File(nodeModulesDirectory, "npm"); + try { + if (oldNpmDirectory.isDirectory()) { + FileUtils.deleteDirectory(oldNpmDirectory); + } + FileUtils.deleteDirectory(npmDirectory); + } catch (IOException e) { + logger.warn("Failed to delete existing NPM installation."); + } + + extractFile(archive, nodeModulesDirectory); + + // handles difference between old and new download root (nodejs.org/dist/npm and registry.npmjs.org) + // see https://github.com/eirslett/frontend-maven-plugin/issues/65#issuecomment-52024254 + File packageDirectory = new File(nodeModulesDirectory, "package"); + if (packageDirectory.exists() && !npmDirectory.exists()) { + if (! packageDirectory.renameTo(npmDirectory)) { + logger.warn("Cannot rename NPM directory, making a copy."); + FileUtils.copyDirectory(packageDirectory, npmDirectory); + } + } + + // create a copy of the npm scripts next to the node executable + for (String script : Arrays.asList("npm", "npm.cmd")) { + File scriptFile = new File(npmDirectory, "bin"+File.separator+script); + if (scriptFile.exists()) { + File copy = new File(installDirectory, script); + FileUtils.copyFile(scriptFile, copy); + copy.setExecutable(true); + } + } + + logger.info("Installed npm locally."); + } catch (DownloadException e) { + throw new InstallationException("Could not download npm", e); + } catch (ArchiveExtractionException e) { + throw new InstallationException("Could not extract the npm archive", e); + } catch (IOException e) { + throw new InstallationException("Could not copy npm", e); + } + } + + private void installNodeDefault() throws InstallationException { + try { + final String longNodeFilename = config.getPlatform().getLongNodeFilename(nodeVersion); + String downloadUrl = nodeDownloadRoot + config.getPlatform().getNodeDownloadFilename(nodeVersion); + String classifier = config.getPlatform().getNodeClassifier(); + + File tmpDirectory = getTempDirectory(); + + CacheDescriptor cacheDescriptor = new CacheDescriptor("node", nodeVersion, classifier, "tar.gz"); + + File archive = config.getCacheResolver().resolve(cacheDescriptor); + + downloadFileIfMissing(downloadUrl, archive, userName, password); + + extractFile(archive, tmpDirectory); + + // Search for the node binary + File nodeBinary = new File(tmpDirectory,longNodeFilename + File.separator + "bin" + File.separator + "node"); + if(!nodeBinary.exists()){ + throw new FileNotFoundException("Could not find the downloaded Node.js binary in "+nodeBinary); + } else { + File destinationDirectory = getInstallDirectory(); + + File destination = new File(destinationDirectory, "node"); + logger.info("Copying node binary from {} to {}", nodeBinary, destination); + if(!nodeBinary.renameTo(destination)){ + throw new InstallationException("Could not install Node: Was not allowed to rename "+nodeBinary+" to "+destination); + } + + if(!destination.setExecutable(true, false)){ + throw new InstallationException("Could not install Node: Was not allowed to make "+destination+" executable."); + } + + deleteTempDirectory(tmpDirectory); + + logger.info("Installed node locally."); + } + } catch (IOException e) { + throw new InstallationException("Could not install Node", e); + } catch (DownloadException e) { + throw new InstallationException("Could not download Node.js", e); + } catch (ArchiveExtractionException e) { + throw new InstallationException("Could not extract the Node archive", e); + } + } + + private void installNodeForWindows() throws InstallationException { + final String downloadUrl = nodeDownloadRoot + config.getPlatform().getNodeDownloadFilename(nodeVersion); + try { + File destinationDirectory = getInstallDirectory(); + + File destination = new File(destinationDirectory, "node.exe"); + + String classifier = config.getPlatform().getNodeClassifier(); + + CacheDescriptor cacheDescriptor = new CacheDescriptor("node", nodeVersion, classifier, "exe"); + + File binary = config.getCacheResolver().resolve(cacheDescriptor); + + downloadFileIfMissing(downloadUrl, binary, userName, password); + + logger.info("Copying node binary from {} to {}", binary, destination); + FileUtils.copyFile(binary, destination); + + logger.info("Installed node locally."); + } catch (DownloadException e) { + throw new InstallationException("Could not download Node.js from: " + downloadUrl, e); + } catch (IOException e) { + throw new InstallationException("Could not install Node.js", e); + } + } + + private File getTempDirectory() { + File tmpDirectory = new File(getInstallDirectory(), "tmp"); + if (!tmpDirectory.exists()) { + logger.debug("Creating temporary directory {}", tmpDirectory); + tmpDirectory.mkdirs(); + } + return tmpDirectory; + } + + private File getInstallDirectory() { + File installDirectory = new File(config.getInstallDirectory(), INSTALL_PATH); + if (!installDirectory.exists()) { + logger.debug("Creating install directory {}", installDirectory); + installDirectory.mkdirs(); + } + return installDirectory; + } + + private void deleteTempDirectory(File tmpDirectory) throws IOException { + if (tmpDirectory != null && tmpDirectory.exists()) { + logger.debug("Deleting temporary directory {}", tmpDirectory); + FileUtils.deleteDirectory(tmpDirectory); + } + } + + private void extractFile(File archive, File destinationDirectory) throws ArchiveExtractionException { + logger.info("Unpacking {} into {}", archive, destinationDirectory); + archiveExtractor.extract(archive.getPath(), destinationDirectory.getPath()); + } + + private void downloadFileIfMissing(String downloadUrl, File destination, String userName, String password) throws DownloadException { + if (!destination.exists()) { + downloadFile(downloadUrl, destination, userName, password); + } + } + + private void downloadFile(String downloadUrl, File destination, String userName, String password) throws DownloadException { + logger.info("Downloading {} to {}", downloadUrl, destination); + fileDownloader.download(downloadUrl, destination.getPath(), userName, password); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.github.eirslett.maven.plugins.frontend.lib.NodeAndNPMInstaller.install` indirectly reads with synchronization from `this.com.github.eirslett.maven.plugins.frontend.lib.NodeAndNPMInstaller.npmDownloadRoot`. Potentially races with unsynchronized write in method `NodeAndNPMInstaller.install()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NodeAndNPMInstaller.install() + +### Procedure Id: +com.github.eirslett.maven.plugins.frontend.lib.NodeAndNPMInstaller.install():void.25620d4d1dced0926246685de6d199e0 + +### File: +frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/NodeAndNPMInstaller.java + +### Key: +NodeAndNPMInstaller.java|install|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +45ba4195082d63090213c5b6e9706cbc + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9878/instruction.md b/inferredbugs-9878/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..470901b46a458c2970c12cb700f1f001820295da --- /dev/null +++ b/inferredbugs-9878/instruction.md @@ -0,0 +1,387 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** frontend-maven-plugin +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.eirslett.maven.plugins.frontend.lib; + +import org.apache.commons.io.FileUtils; +import org.codehaus.jackson.map.ObjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; + +public class NodeAndNPMInstaller { + + private static final String INSTALL_PATH = "node"; + private static final String VERSION = "version"; + + public static final String DEFAULT_NODEJS_DOWNLOAD_ROOT = "https://nodejs.org/dist/"; + public static final String DEFAULT_NPM_DOWNLOAD_ROOT = "http://registry.npmjs.org/npm/-/"; + + private String nodeVersion, npmVersion, nodeDownloadRoot, npmDownloadRoot, userName, password; + + private static final Object lock = new Object(); + + private final Logger logger; + private final InstallConfig config; + private final ArchiveExtractor archiveExtractor; + private final FileDownloader fileDownloader; + + NodeAndNPMInstaller(InstallConfig config, ArchiveExtractor archiveExtractor, FileDownloader fileDownloader) { + this.logger = LoggerFactory.getLogger(getClass()); + this.config = config; + this.archiveExtractor = archiveExtractor; + this.fileDownloader = fileDownloader; + } + + public NodeAndNPMInstaller setNodeVersion (String nodeVersion) { + this.nodeVersion = nodeVersion; + return this; + } + + public NodeAndNPMInstaller setNodeDownloadRoot (String nodeDownloadRoot) { + this.nodeDownloadRoot = nodeDownloadRoot; + return this; + } + + public NodeAndNPMInstaller setNpmVersion (String npmVersion) { + this.npmVersion = npmVersion; + return this; + } + + public NodeAndNPMInstaller setNpmDownloadRoot (String npmDownloadRoot) { + this.npmDownloadRoot = npmDownloadRoot; + return this; + } + + public NodeAndNPMInstaller setUserName (String userName) { + this.userName = userName; + return this; + } + + public NodeAndNPMInstaller setPassword (String password) { + this.password = password; + return this; + } + + public void install() throws InstallationException { + if(nodeDownloadRoot == null || nodeDownloadRoot.isEmpty()){ + nodeDownloadRoot = DEFAULT_NODEJS_DOWNLOAD_ROOT; + } + if(npmDownloadRoot == null || npmDownloadRoot.isEmpty()){ + npmDownloadRoot = DEFAULT_NPM_DOWNLOAD_ROOT; + } + synchronized (lock) { + if (!nodeIsAlreadyInstalled()) { + logger.info("Installing node version {}", nodeVersion); + if (!nodeVersion.startsWith("v")) { + logger.warn("Node version does not start with naming convention 'v'."); + } + if (config.getPlatform().isWindows()) { + installNodeForWindows(); + } else { + installNodeDefault(); + } + } + if (!npmIsAlreadyInstalled()) { + installNpm(); + } + } + } + + private boolean nodeIsAlreadyInstalled() { + try { + NodeExecutorConfig executorConfig = new InstallNodeExecutorConfig(config); + File nodeFile = executorConfig.getNodePath(); + if(nodeFile.exists()){ + final String version = new NodeExecutor(executorConfig, Arrays.asList("--version"), null).executeAndGetResult(); + + if(version.equals(nodeVersion)){ + logger.info("Node {} is already installed.", version); + return true; + } else { + logger.info("Node {} was installed, but we need version {}", version, nodeVersion); + return false; + } + } else { + return false; + } + } catch (ProcessExecutionException e) { + return false; + } + } + + private boolean npmIsAlreadyInstalled(){ + try { + final File npmPackageJson = new File(config.getInstallDirectory() + Utils.normalize("/node/node_modules/npm/package.json")); + if(npmPackageJson.exists()){ + HashMap data = new ObjectMapper().readValue(npmPackageJson, HashMap.class); + if(data.containsKey(VERSION)){ + final String foundNpmVersion = data.get(VERSION).toString(); + if(foundNpmVersion.equals(npmVersion)) { + logger.info("NPM {} is already installed.", foundNpmVersion); + return true; + } else { + logger.info("NPM {} was installed, but we need version {}", foundNpmVersion, npmVersion); + return false; + } + } else { + logger.info("Could not read NPM version from package.json"); + return false; + } + } else { + return false; + } + } catch (IOException ex){ + throw new RuntimeException("Could not read package.json", ex); + } + } + + private void installNpm() throws InstallationException { + try { + logger.info("Installing npm version {}", npmVersion); + final String downloadUrl = npmDownloadRoot +"npm-"+npmVersion+".tgz"; + + CacheDescriptor cacheDescriptor = new CacheDescriptor("npm", npmVersion, "tar.gz"); + + File archive = config.getCacheResolver().resolve(cacheDescriptor); + + downloadFileIfMissing(downloadUrl, archive, userName, password); + + File installDirectory = getInstallDirectory(); + File nodeModulesDirectory = new File(installDirectory, "node_modules"); + + // We need to delete the existing npm directory first so we clean out any old files, and + // so we can rename the package directory below. + File oldNpmDirectory = new File(installDirectory, "npm"); + File npmDirectory = new File(nodeModulesDirectory, "npm"); + try { + if (oldNpmDirectory.isDirectory()) { + FileUtils.deleteDirectory(oldNpmDirectory); + } + FileUtils.deleteDirectory(npmDirectory); + } catch (IOException e) { + logger.warn("Failed to delete existing NPM installation."); + } + + extractFile(archive, nodeModulesDirectory); + + // handles difference between old and new download root (nodejs.org/dist/npm and registry.npmjs.org) + // see https://github.com/eirslett/frontend-maven-plugin/issues/65#issuecomment-52024254 + File packageDirectory = new File(nodeModulesDirectory, "package"); + if (packageDirectory.exists() && !npmDirectory.exists()) { + if (! packageDirectory.renameTo(npmDirectory)) { + logger.warn("Cannot rename NPM directory, making a copy."); + FileUtils.copyDirectory(packageDirectory, npmDirectory); + } + } + + // create a copy of the npm scripts next to the node executable + for (String script : Arrays.asList("npm", "npm.cmd")) { + File scriptFile = new File(npmDirectory, "bin"+File.separator+script); + if (scriptFile.exists()) { + File copy = new File(installDirectory, script); + FileUtils.copyFile(scriptFile, copy); + copy.setExecutable(true); + } + } + + logger.info("Installed npm locally."); + } catch (DownloadException e) { + throw new InstallationException("Could not download npm", e); + } catch (ArchiveExtractionException e) { + throw new InstallationException("Could not extract the npm archive", e); + } catch (IOException e) { + throw new InstallationException("Could not copy npm", e); + } + } + + private void installNodeDefault() throws InstallationException { + try { + final String longNodeFilename = config.getPlatform().getLongNodeFilename(nodeVersion); + String downloadUrl = nodeDownloadRoot + config.getPlatform().getNodeDownloadFilename(nodeVersion); + String classifier = config.getPlatform().getNodeClassifier(); + + File tmpDirectory = getTempDirectory(); + + CacheDescriptor cacheDescriptor = new CacheDescriptor("node", nodeVersion, classifier, "tar.gz"); + + File archive = config.getCacheResolver().resolve(cacheDescriptor); + + downloadFileIfMissing(downloadUrl, archive, userName, password); + + extractFile(archive, tmpDirectory); + + // Search for the node binary + File nodeBinary = new File(tmpDirectory,longNodeFilename + File.separator + "bin" + File.separator + "node"); + if(!nodeBinary.exists()){ + throw new FileNotFoundException("Could not find the downloaded Node.js binary in "+nodeBinary); + } else { + File destinationDirectory = getInstallDirectory(); + + File destination = new File(destinationDirectory, "node"); + logger.info("Copying node binary from {} to {}", nodeBinary, destination); + if(!nodeBinary.renameTo(destination)){ + throw new InstallationException("Could not install Node: Was not allowed to rename "+nodeBinary+" to "+destination); + } + + if(!destination.setExecutable(true, false)){ + throw new InstallationException("Could not install Node: Was not allowed to make "+destination+" executable."); + } + + deleteTempDirectory(tmpDirectory); + + logger.info("Installed node locally."); + } + } catch (IOException e) { + throw new InstallationException("Could not install Node", e); + } catch (DownloadException e) { + throw new InstallationException("Could not download Node.js", e); + } catch (ArchiveExtractionException e) { + throw new InstallationException("Could not extract the Node archive", e); + } + } + + private void installNodeForWindows() throws InstallationException { + final String downloadUrl = nodeDownloadRoot + config.getPlatform().getNodeDownloadFilename(nodeVersion); + try { + File destinationDirectory = getInstallDirectory(); + + File destination = new File(destinationDirectory, "node.exe"); + + String classifier = config.getPlatform().getNodeClassifier(); + + CacheDescriptor cacheDescriptor = new CacheDescriptor("node", nodeVersion, classifier, "exe"); + + File binary = config.getCacheResolver().resolve(cacheDescriptor); + + downloadFileIfMissing(downloadUrl, binary, userName, password); + + logger.info("Copying node binary from {} to {}", binary, destination); + FileUtils.copyFile(binary, destination); + + logger.info("Installed node locally."); + } catch (DownloadException e) { + throw new InstallationException("Could not download Node.js from: " + downloadUrl, e); + } catch (IOException e) { + throw new InstallationException("Could not install Node.js", e); + } + } + + private File getTempDirectory() { + File tmpDirectory = new File(getInstallDirectory(), "tmp"); + if (!tmpDirectory.exists()) { + logger.debug("Creating temporary directory {}", tmpDirectory); + tmpDirectory.mkdirs(); + } + return tmpDirectory; + } + + private File getInstallDirectory() { + File installDirectory = new File(config.getInstallDirectory(), INSTALL_PATH); + if (!installDirectory.exists()) { + logger.debug("Creating install directory {}", installDirectory); + installDirectory.mkdirs(); + } + return installDirectory; + } + + private void deleteTempDirectory(File tmpDirectory) throws IOException { + if (tmpDirectory != null && tmpDirectory.exists()) { + logger.debug("Deleting temporary directory {}", tmpDirectory); + FileUtils.deleteDirectory(tmpDirectory); + } + } + + private void extractFile(File archive, File destinationDirectory) throws ArchiveExtractionException { + logger.info("Unpacking {} into {}", archive, destinationDirectory); + archiveExtractor.extract(archive.getPath(), destinationDirectory.getPath()); + } + + private void downloadFileIfMissing(String downloadUrl, File destination, String userName, String password) throws DownloadException { + if (!destination.exists()) { + downloadFile(downloadUrl, destination, userName, password); + } + } + + private void downloadFile(String downloadUrl, File destination, String userName, String password) throws DownloadException { + logger.info("Downloading {} to {}", downloadUrl, destination); + fileDownloader.download(downloadUrl, destination.getPath(), userName, password); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.github.eirslett.maven.plugins.frontend.lib.NodeAndNPMInstaller.install` writes to field `this.com.github.eirslett.maven.plugins.frontend.lib.NodeAndNPMInstaller.npmDownloadRoot` outside of synchronization. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NodeAndNPMInstaller.install() + +### Procedure Id: +com.github.eirslett.maven.plugins.frontend.lib.NodeAndNPMInstaller.install():void.25620d4d1dced0926246685de6d199e0 + +### File: +frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/NodeAndNPMInstaller.java + +### Key: +NodeAndNPMInstaller.java|install|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +b4e4047316f70a227d37bd5959da4d32 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9882/instruction.md b/inferredbugs-9882/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7bd3a00aa996aded4f209d1bf685af2a1dec622e --- /dev/null +++ b/inferredbugs-9882/instruction.md @@ -0,0 +1,449 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** zemberek-nlp +**Bug ID:** 34 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package zemberek.embedding.fasttext; + +import zemberek.core.collections.IntVector; + +import java.util.*; + +public class Model { + + static class Node { + int parent; + int left; + int right; + long count; // TODO: this can be an int. + boolean binary; + } + + static class Pair implements Comparable { + + final float first; + final int second; + + Pair(float first, int second) { + this.first = first; + this.second = second; + } + + @Override + public int compareTo(Pair o) { + // descending. + return Float.compare(o.first, first); + } + } + + private Matrix wi_; + private Matrix wo_; + private Args args_; + private Vector hidden_; + private Vector output_; + private Vector grad_; + private int hsz_; + private int isz_; + private int osz_; + private float loss_; + private long nexamples_; + private static float[] t_sigmoid; + private static float[] t_log; + // used for negative sampling: + private int[] negatives; + private int negpos; + // used for hierarchical softmax: + private List paths = new ArrayList<>(); + private List codes = new ArrayList<>(); + private Node[] tree; + + private static final int NEGATIVE_TABLE_SIZE = 10000000; + + private static final int SIGMOID_TABLE_SIZE = 512; + private static final int MAX_SIGMOID = 8; + private static final int LOG_TABLE_SIZE = 512; + + Random random; + + static { + initLog(); + initSigmoid(); + } + + Model(Matrix wi, + Matrix wo, + Args args, + int seed) { + hidden_ = new Vector(args.dim); + output_ = new Vector(wo.m_); + grad_ = new Vector(args.dim); + random = new Random(seed); + wi_ = wi; + wo_ = wo; + args_ = args; + isz_ = wi.m_; + osz_ = wo.m_; + hsz_ = args.dim; + negpos = 0; + loss_ = 0.0f; + nexamples_ = 1; + } + + private float binaryLogistic(int target, boolean label, float lr) { + float score = sigmoid(wo_.dotRow(hidden_, target)); + float alpha = lr * ((label ? 1f : 0f) - score); + grad_.addRow(wo_, target, alpha); + synchronized (this) { + wo_.addRow(hidden_, target, alpha); + } + if (label) { + return -log(score); + } else { + return -log(1.0f - score); + } + } + + private float negativeSampling(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + for (int n = 0; n <= args_.neg; n++) { + if (n == 0) { + loss += binaryLogistic(target, true, lr); + } else { + loss += binaryLogistic(getNegative(target), false, lr); + } + } + return loss; + } + + + private float hierarchicalSoftmax(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + IntVector binaryCode = codes.get(target); + IntVector pathToRoot = paths.get(target); + for (int i = 0; i < pathToRoot.size(); i++) { + loss += binaryLogistic(pathToRoot.get(i), binaryCode.get(i) == 1, lr); + } + return loss; + } + + private void computeOutputSoftmax(Vector hidden, Vector output) { + output.mul(wo_, hidden); + float max = output.data_[0], z = 0.0f; + for (int i = 0; i < osz_; i++) { + max = Math.max(output.data_[i], max); + } + for (int i = 0; i < osz_; i++) { + output.data_[i] = (float) Math.exp(output.data_[i] - max); + z += output.data_[i]; + } + for (int i = 0; i < osz_; i++) { + output.data_[i] /= z; + } + } + + private void computeOutputSoftmax() { + computeOutputSoftmax(hidden_, output_); + } + + private float softmax(int target, float lr) { + grad_.zero(); + computeOutputSoftmax(); + for (int i = 0; i < osz_; i++) { + float label = (i == target) ? 1.0f : 0.0f; + float alpha = lr * (label - output_.data_[i]); + grad_.addRow(wo_, i, alpha); + synchronized (this) { + wo_.addRow(hidden_, i, alpha); + } + } + return -log(output_.data_[target]); + } + + private void computeHidden(int[] input, Vector hidden) { + assert (hidden.size() == hsz_); + hidden.zero(); + for (int i : input) { + hidden.addRow(wi_, i); + } + hidden.mul(1.0f / input.length); + } + + + private static final Comparator PAIR_COMPARATOR = + (l, r) -> l.first > r.first ? 1 : 0; + + List predict(int[] input, + int k, + Vector hidden, + Vector output) { + assert (k > 0); + computeHidden(input, hidden); + PriorityQueue heap = new PriorityQueue<>(k+1, PAIR_COMPARATOR); + if (args_.loss == Args.loss_name.hs) { + dfs(k, 2 * osz_ - 2, 0.0f, heap, hidden); + } else { + findKBest(k, heap, hidden, output); + } + List result = new ArrayList<>(heap); + Collections.sort(result); + return result; + } + + List predict(int[] input, int k) { + return predict(input, k, hidden_, output_); + } + + private void findKBest(int k, + PriorityQueue heap, + Vector hidden, + Vector output) { + computeOutputSoftmax(hidden, output); + for (int i = 0; i < osz_; i++) { + if (heap.size() == k && log(output.data_[i]) < heap.peek().first) { + continue; + } + heap.add(new Pair(output.data_[i], i)); + if (heap.size() > k) { + heap.remove(); + } + } + } + + //todo: check here. + private void dfs(int k, + int node, + float score, + PriorityQueue heap, + Vector hidden) { + if (heap.size() == k && score < heap.peek().first) { + return; + } + + if (tree[node].left == -1 && tree[node].right == -1) { + heap.add(new Pair(score, node)); + if (heap.size() > k) { + heap.remove(); + } + return; + } + + float f = sigmoid(wo_.dotRow(hidden, node - osz_)); + dfs(k, tree[node].left, score + log(1.0f - f), heap, hidden); + dfs(k, tree[node].right, score + log(f), heap, hidden); + } + + + void update(int[] input, int target, float lr) { + assert (target >= 0); + assert (target < osz_); + if (input.length == 0) return; + computeHidden(input, hidden_); + if (args_.loss == Args.loss_name.ns) { + loss_ += negativeSampling(target, lr); + } else if (args_.loss == Args.loss_name.hs) { + loss_ += hierarchicalSoftmax(target, lr); + } else { + loss_ += softmax(target, lr); + } + nexamples_ += 1; + + if (args_.model == Args.model_name.sup) { + grad_.mul(1.0f / input.length); + } + synchronized (this) { + for (int i : input) { + wi_.addRow(grad_, i, 1.0f); + } + } + } + + void setTargetCounts(long[] counts) { + assert (counts.length == osz_); + if (args_.loss == Args.loss_name.ns) { + initTableNegatives(counts); + } + if (args_.loss == Args.loss_name.hs) { + buildTree(counts); + } + } + + private void initTableNegatives(long[] counts) { + IntVector vec = new IntVector(counts.length*10); + float z = 0.0f; + for (long count : counts) { + z += (float) Math.pow(count, 0.5); + } + for (int i = 0; i < counts.length; i++) { + float c = (float) Math.pow(counts[i], 0.5); + for (int j = 0; j < c * NEGATIVE_TABLE_SIZE / z; j++) { + vec.add(i); + } + } + vec.shuffle(random); + negatives = vec.copyOf(); + } + + private int getNegative(int target) { + int negative; + do { + negative = negatives[negpos]; + negpos = (negpos + 1) % negatives.length; + } while (target == negative); + return negative; + } + + private void buildTree(long[] counts) { + tree = new Node[2 * osz_ - 1]; + for (int i = 0; i < 2 * osz_ - 1; i++) { + tree[i].parent = -1; + tree[i].left = -1; + tree[i].right = -1; + tree[i].count = (long) 1e15; + tree[i].binary = false; + } + for (int i = 0; i < osz_; i++) { + tree[i].count = counts[i]; + } + int leaf = osz_ - 1; + int node = osz_; + for (int i = osz_; i < 2 * osz_ - 1; i++) { + int[] mini = new int[2]; + for (int j = 0; j < 2; j++) { + if (leaf >= 0 && tree[leaf].count < tree[node].count) { + mini[j] = leaf--; + } else { + mini[j] = node++; + } + } + tree[i].left = mini[0]; + tree[i].right = mini[1]; + tree[i].count = tree[mini[0]].count + tree[mini[1]].count; + tree[mini[0]].parent = i; + tree[mini[1]].parent = i; + tree[mini[1]].binary = true; + } + for (int i = 0; i < osz_; i++) { + IntVector path = new IntVector(); + IntVector code = new IntVector(); + int j = i; + while (tree[j].parent != -1) { + path.add(tree[j].parent - osz_); + code.add(tree[j].binary ? 1 : 0); + j = tree[j].parent; + } + paths.add(path); + codes.add(code); + } + } + + float getLoss() { + return loss_ / nexamples_; + } + + private static void initSigmoid() { + t_sigmoid = new float[SIGMOID_TABLE_SIZE + 1]; + for (int i = 0; i < SIGMOID_TABLE_SIZE + 1; i++) { + float x = i * 2f * MAX_SIGMOID / SIGMOID_TABLE_SIZE - MAX_SIGMOID; + t_sigmoid[i] = 1.0f / (1.0f + (float) Math.exp(-x)); + } + } + + private static void initLog() { + t_log = new float[LOG_TABLE_SIZE + 1]; + for (int i = 0; i < LOG_TABLE_SIZE + 1; i++) { + float x = (i + 1e-5f) / LOG_TABLE_SIZE; + t_log[i] = (float) Math.log(x); + } + } + + private float log(float x) { + if (x > 1.0f) { + return 0.0f; + } + int i = (int) (x * LOG_TABLE_SIZE); + return t_log[i]; + } + + private float sigmoid(float x) { + if (x < -MAX_SIGMOID) { + return 0.0f; + } else if (x > MAX_SIGMOID) { + return 1.0f; + } else { + int i = (int) ((x + MAX_SIGMOID) * SIGMOID_TABLE_SIZE / MAX_SIGMOID / 2); + return t_sigmoid[i]; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `zemberek.embedding.fasttext.Model.update` indirectly writes to field `this.zemberek.embedding.fasttext.Model.grad_.zemberek.embedding.fasttext.Vector.data_.[_]` outside of synchronization. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Model.update(int[],int,float) + +### Procedure Id: +zemberek.embedding.fasttext.Model.update(int[],int,float):void.49e2c20141a9f555936abeccf294c2e6 + +### File: +experiment/src/main/java/zemberek/embedding/fasttext/Model.java + +### Key: +Model.java|update|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +fac7bcfb8ac1794c3ef91e8c37f057a4 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9885/instruction.md b/inferredbugs-9885/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1c925e801f906601aa72a5d4464affda699e7ef4 --- /dev/null +++ b/inferredbugs-9885/instruction.md @@ -0,0 +1,442 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** zemberek-nlp +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package zemberek.embedding.fasttext; + +import zemberek.core.collections.IntVector; + +import java.util.*; + +public class Model { + + static class Node { + int parent; + int left; + int right; + long count; // TODO: this can be an int. + boolean binary; + } + + static class Pair implements Comparable { + + final float first; + final int second; + + Pair(float first, int second) { + this.first = first; + this.second = second; + } + + @Override + public int compareTo(Pair o) { + //TODO: check below + return Float.compare(this.first, o.first); + } + } + + private Matrix wi_; + private Matrix wo_; + private Args args_; + private Vector hidden_; + private Vector output_; + private Vector grad_; + private int hsz_; + private int isz_; + private int osz_; + private float loss_; + private long nexamples_; + private static float[] t_sigmoid; + private static float[] t_log; + // used for negative sampling: + private int[] negatives; + private int negpos; + // used for hierarchical softmax: + private List paths = new ArrayList<>(); + private List codes = new ArrayList<>(); + private Node[] tree; + + private static final int NEGATIVE_TABLE_SIZE = 10000000; + + private static final int SIGMOID_TABLE_SIZE = 512; + private static final int MAX_SIGMOID = 8; + private static final int LOG_TABLE_SIZE = 512; + + Random random; + + static { + initLog(); + initSigmoid(); + } + + Model(Matrix wi, + Matrix wo, + Args args, + int seed) { + hidden_ = new Vector(args.dim); + output_ = new Vector(wo.m_); + grad_ = new Vector(args.dim); + random = new Random(seed); + wi_ = wi; + wo_ = wo; + args_ = args; + isz_ = wi.m_; + osz_ = wo.m_; + hsz_ = args.dim; + negpos = 0; + loss_ = 0.0f; + nexamples_ = 1; + } + + float binaryLogistic(int target, boolean label, float lr) { + float score = sigmoid(wo_.dotRow(hidden_, target)); + float alpha = lr * (label ? 1f : 0f - score); + grad_.addRow(wo_, target, alpha); + synchronized (this) { + wo_.addRow(hidden_, target, alpha); + } + if (label) { + return -log(score); + } else { + return -log(1.0f - score); + } + } + + float negativeSampling(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + for (int n = 0; n <= args_.neg; n++) { + if (n == 0) { + loss += binaryLogistic(target, true, lr); + } else { + loss += binaryLogistic(getNegative(target), false, lr); + } + } + return loss; + } + + + float hierarchicalSoftmax(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + IntVector binaryCode = codes.get(target); + IntVector pathToRoot = paths.get(target); + for (int i = 0; i < pathToRoot.size(); i++) { + loss += binaryLogistic(pathToRoot.get(i), binaryCode.get(i) == 1, lr); + } + return loss; + } + + void computeOutputSoftmax(Vector hidden, Vector output) { + output.mul(wo_, hidden); + float max = output.data_[0], z = 0.0f; + for (int i = 0; i < osz_; i++) { + max = Math.max(output.data_[i], max); + } + for (int i = 0; i < osz_; i++) { + output.data_[i] = (float) Math.exp(output.data_[i] - max); + z += output.data_[i]; + } + for (int i = 0; i < osz_; i++) { + output.data_[i] /= z; + } + } + + void computeOutputSoftmax() { + computeOutputSoftmax(hidden_, output_); + } + + float softmax(int target, float lr) { + grad_.zero(); + computeOutputSoftmax(); + for (int i = 0; i < osz_; i++) { + float label = (i == target) ? 1.0f : 0.0f; + float alpha = lr * (label - output_.data_[i]); + grad_.addRow(wo_, i, alpha); + synchronized (this) { + wo_.addRow(hidden_, i, alpha); + } + } + return -log(output_.data_[target]); + } + + void computeHidden(int[] input, Vector hidden) { + assert (hidden.size() == hsz_); + hidden.zero(); + for (int i : input) { + hidden.addRow(wi_, i); + } + hidden.mul(1.0f / input.length); + } + + + void predict(int[] input, int k, + PriorityQueue heap, + Vector hidden, Vector output) { + assert (k > 0); + //heap.reserve(k + 1); + computeHidden(input, hidden); + if (args_.loss == Args.loss_name.hs) { + dfs(k, 2 * osz_ - 2, 0.0f, heap, hidden); + } else { + findKBest(k, heap, hidden, output); + } + // TODO: write below if necessary. + //std::sort_heap(heap.begin(), heap.end(), comparePairs); + } + + void predict(int[] input, int k, + PriorityQueue heap) { + predict(input, k, heap, hidden_, output_); + } + + void findKBest(int k, PriorityQueue heap, + Vector hidden, Vector output) { + computeOutputSoftmax(hidden, output); + for (int i = 0; i < osz_; i++) { + if (heap.size() == k && log(output.data_[i]) < heap.peek().first) { + continue; + } + heap.add(new Pair(output.data_[i], i)); + if (heap.size() > k) { + heap.remove(); + } + } + } + + //todo: check here. + void dfs(int k, int node, float score, + PriorityQueue heap, + Vector hidden) { + if (heap.size() == k && score < heap.peek().first) { + return; + } + + if (tree[node].left == -1 && tree[node].right == -1) { + heap.add(new Pair(score, node)); + if (heap.size() > k) { + heap.remove(); + } + return; + } + + float f = sigmoid(wo_.dotRow(hidden, node - osz_)); + dfs(k, tree[node].left, score + log(1.0f - f), heap, hidden); + dfs(k, tree[node].right, score + log(f), heap, hidden); + } + + + void update(int[] input, int target, float lr) { + assert (target >= 0); + assert (target < osz_); + if (input.length == 0) return; + computeHidden(input, hidden_); + if (args_.loss == Args.loss_name.ns) { + loss_ += negativeSampling(target, lr); + } else if (args_.loss == Args.loss_name.hs) { + loss_ += hierarchicalSoftmax(target, lr); + } else { + loss_ += softmax(target, lr); + } + nexamples_ += 1; + + if (args_.model == Args.model_name.sup) { + grad_.mul(1.0f / input.length); + } + synchronized (this) { + for (int i : input) { + wi_.addRow(grad_, i, 1.0f); + } + } + } + + void setTargetCounts(long[] counts) { + assert (counts.length == osz_); + if (args_.loss == Args.loss_name.ns) { + initTableNegatives(counts); + } + if (args_.loss == Args.loss_name.hs) { + buildTree(counts); + } + } + + + void initTableNegatives(long[] counts) { + IntVector vec = new IntVector(counts.length*10); + float z = 0.0f; + for (long count : counts) { + z += (float) Math.pow(count, 0.5); + } + for (int i = 0; i < counts.length; i++) { + float c = (float) Math.pow(counts[i], 0.5); + for (int j = 0; j < c * NEGATIVE_TABLE_SIZE / z; j++) { + vec.add(i); + } + } + vec.shuffle(random); + negatives = vec.copyOf(); + } + + int getNegative(int target) { + int negative; + do { + negative = negatives[negpos]; + negpos = (negpos + 1) % negatives.length; + } while (target == negative); + return negative; + } + + void buildTree(long[] counts) { + tree = new Node[2 * osz_ - 1]; + for (int i = 0; i < 2 * osz_ - 1; i++) { + tree[i].parent = -1; + tree[i].left = -1; + tree[i].right = -1; + tree[i].count = (long) 1e15; + tree[i].binary = false; + } + for (int i = 0; i < osz_; i++) { + tree[i].count = counts[i]; + } + int leaf = osz_ - 1; + int node = osz_; + for (int i = osz_; i < 2 * osz_ - 1; i++) { + int[] mini = new int[2]; + for (int j = 0; j < 2; j++) { + if (leaf >= 0 && tree[leaf].count < tree[node].count) { + mini[j] = leaf--; + } else { + mini[j] = node++; + } + } + tree[i].left = mini[0]; + tree[i].right = mini[1]; + tree[i].count = tree[mini[0]].count + tree[mini[1]].count; + tree[mini[0]].parent = i; + tree[mini[1]].parent = i; + tree[mini[1]].binary = true; + } + for (int i = 0; i < osz_; i++) { + IntVector path = new IntVector(); + IntVector code = new IntVector(); + int j = i; + while (tree[j].parent != -1) { + path.add(tree[j].parent - osz_); + code.add(tree[j].binary ? 1 : 0); + j = tree[j].parent; + } + paths.add(path); + codes.add(code); + } + } + + float getLoss() { + return loss_ / nexamples_; + } + + static void initSigmoid() { + t_sigmoid = new float[SIGMOID_TABLE_SIZE + 1]; + for (int i = 0; i < SIGMOID_TABLE_SIZE + 1; i++) { + float x = i * 2f * MAX_SIGMOID / SIGMOID_TABLE_SIZE - MAX_SIGMOID; + t_sigmoid[i] = 1.0f / (1.0f + (float) Math.exp(-x)); + } + } + + static void initLog() { + t_log = new float[LOG_TABLE_SIZE + 1]; + for (int i = 0; i < LOG_TABLE_SIZE + 1; i++) { + float x = (i + 1e-5f) / LOG_TABLE_SIZE; + t_log[i] = (float) Math.log(x); + } + } + + float log(float x) { + if (x > 1.0f) { + return 0.0f; + } + int i = (int) (x * LOG_TABLE_SIZE); + return t_log[i]; + } + + float sigmoid(float x) { + if (x < -MAX_SIGMOID) { + return 0.0f; + } else if (x > MAX_SIGMOID) { + return 1.0f; + } else { + int i = (int) ((x + MAX_SIGMOID) * SIGMOID_TABLE_SIZE / MAX_SIGMOID / 2); + return t_sigmoid[i]; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `zemberek.embedding.fasttext.Model.softmax` indirectly reads with synchronization from `this.zemberek.embedding.fasttext.Model.hidden_.zemberek.embedding.fasttext.Vector.data_.[_]`. Potentially races with unsynchronized write in method `Model.update(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +float Model.softmax(int,float) + +### Procedure Id: +zemberek.embedding.fasttext.Model.softmax(int,float):float.9b5d27486e0baa33be6326b35ed6f8ec + +### File: +experiment/src/main/java/zemberek/embedding/fasttext/Model.java + +### Key: +Model.java|softmax|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +7a9d51eacbba1d716d344dcf1ac27480 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9959/instruction.md b/inferredbugs-9959/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09eef6f0ea1e996dedcee99107255d6f434b372e --- /dev/null +++ b/inferredbugs-9959/instruction.md @@ -0,0 +1,213 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** javaparser +**Bug ID:** 54 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2015-2016 Federico Tomassetti + * Copyright (C) 2017-2019 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) 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. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser 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. + */ + +package com.github.javaparser.symbolsolver.resolution; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseStart; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.StreamProvider; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.FieldAccessExpr; +import com.github.javaparser.symbolsolver.JavaSymbolSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class InternalClassInInterfaceTest { + + @Test + void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedSamePackage() throws IOException { + File src = new File("src/test/resources/internalClassInInterface"); + File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + + File.separator + "AClass.java"); + + CombinedTypeSolver localCts = new CombinedTypeSolver(); + localCts.add(new ReflectionTypeSolver()); + localCts.add(new JavaParserTypeSolver(src)); + + ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); + JavaParser parser = new JavaParser(parserConfiguration); + StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); + + CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); + Optional fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 4); + + assertTrue(fae.isPresent()); + + assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); + assertEquals("ADDITION", fae.get().resolve().getName()); + } + + @Test + void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedSamePackage() throws IOException { + File src = new File("src/test/resources/internalClassInInterface"); + File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + + File.separator + "AClass.java"); + + CombinedTypeSolver localCts = new CombinedTypeSolver(); + localCts.add(new ReflectionTypeSolver()); + localCts.add(new JavaParserTypeSolver(src)); + + ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); + JavaParser parser = new JavaParser(parserConfiguration); + StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); + + CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); + Optional fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 5); + + assertTrue(fae.isPresent()); + + assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); + assertEquals("ADDITION", fae.get().resolve().getName()); + } + + @Test + void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedDifferentPackage() throws IOException { + File src = new File("src/test/resources/internalClassInInterface"); + File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + + File.separator + "differentpackage" + File.separator + "AClass2.java"); + + CombinedTypeSolver localCts = new CombinedTypeSolver(); + localCts.add(new ReflectionTypeSolver()); + localCts.add(new JavaParserTypeSolver(src)); + + ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); + JavaParser parser = new JavaParser(parserConfiguration); + StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); + + CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); + Optional fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 6); + + assertTrue(fae.isPresent()); + + assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); + assertEquals("ADDITION", fae.get().resolve().getName()); + } + + @Test + void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedDifferentPackage() throws IOException { + File src = new File("src/test/resources/internalClassInInterface"); + File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + + File.separator + "differentpackage" + File.separator + "AClass2.java"); + + CombinedTypeSolver localCts = new CombinedTypeSolver(); + localCts.add(new ReflectionTypeSolver()); + localCts.add(new JavaParserTypeSolver(src)); + + ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); + JavaParser parser = new JavaParser(parserConfiguration); + StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); + + CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); + + Optional fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 7); + + assertTrue(fae.isPresent()); + + assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); + assertEquals("ADDITION", fae.get().resolve().getName()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired by call to `FileInputStream(...)` at line 59 is not released after line 59. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void InternalClassInInterfaceTest.resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedSamePackage() + +### Procedure Id: +com.github.javaparser.symbolsolver.resolution.InternalClassInInterfaceTest.resolveFieldOfEnumAsInter.fbb1052e934ddc391d68deb54dd163ed + +### File: +javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/InternalClassInInterfaceTest.java + +### Key: +InternalClassInInterfaceTest.java|resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedSamePackage|RESOURCE_LEAK + +### Node Key: +f35d0a16b6796ff33e585cc4a3fd24ab + +### Hash: +983ddc3c7bab7cc1964e01bc9592c541 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9961/instruction.md b/inferredbugs-9961/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a9596d86cc1a1db1970f01c262018d2f9ed04610 --- /dev/null +++ b/inferredbugs-9961/instruction.md @@ -0,0 +1,340 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** javaparser +**Bug ID:** 30 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2016 Federico Tomassetti + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.github.javaparser.symbolsolver.resolution; + +import com.github.javaparser.SlowTest; +import com.github.javaparser.symbolsolver.AbstractSymbolResolutionTest; +import com.github.javaparser.symbolsolver.SourceFileInfoExtractor; +import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade; +import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; +import com.github.javaparser.symbolsolver.utils.LeanParserConfiguration; +import org.junit.jupiter.api.Test; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@SlowTest +class AnalyseJavaParserTest extends AbstractSymbolResolutionTest { + + private static final Path root = adaptPath("src/test/test_sourcecode/javaparser_src"); + private static final Path properSrc = root.resolve("proper_source"); + + private SourceFileInfoExtractor getSourceFileInfoExtractor() { + CombinedTypeSolver combinedTypeSolver = new CombinedTypeSolver(); + combinedTypeSolver.add(new ReflectionTypeSolver()); + combinedTypeSolver.add(new JavaParserTypeSolver(properSrc, new LeanParserConfiguration())); + combinedTypeSolver.add(new JavaParserTypeSolver(root.resolve("generated"), new LeanParserConfiguration())); + SourceFileInfoExtractor sourceFileInfoExtractor = new SourceFileInfoExtractor(); + sourceFileInfoExtractor.setTypeSolver(combinedTypeSolver); + sourceFileInfoExtractor.setPrintFileName(false); + return sourceFileInfoExtractor; + } + + private static String readFile(Path file) + throws IOException { + byte[] encoded = Files.readAllBytes(file); + return new String(encoded, StandardCharsets.UTF_8); + } + + private static final boolean DEBUG = true; + + private void parse(String fileName) throws IOException { + Path sourceFile = properSrc.resolve( fileName + ".java"); + SourceFileInfoExtractor sourceFileInfoExtractor = getSourceFileInfoExtractor(); + OutputStream outErrStream = new ByteArrayOutputStream(); + PrintStream outErr = new PrintStream(outErrStream); + + sourceFileInfoExtractor.setOut(outErr); + sourceFileInfoExtractor.setErr(outErr); + sourceFileInfoExtractor.solve(sourceFile); + String output = outErrStream.toString(); + + String path = "expected_output/" + fileName.replaceAll("/", "_") + ".txt"; + Path dstFile = adaptPath(root.resolve(path)); + + if (DEBUG && (sourceFileInfoExtractor.getKo() != 0 || sourceFileInfoExtractor.getUnsupported() != 0)) { + System.err.println(output); + } + + assertEquals(0, sourceFileInfoExtractor.getKo(), "No failures expected when analyzing " + path); + assertEquals(0, sourceFileInfoExtractor.getUnsupported(), "No UnsupportedOperationException expected when analyzing " + path); + + String expected = readFile(dstFile); + + String[] outputLines = output.split("\n"); + String[] expectedLines = expected.split("\n"); + + for (int i = 0; i < Math.min(outputLines.length, expectedLines.length); i++) { + assertEquals(expectedLines[i].trim(), outputLines[i].trim(), "Line " + (i + 1) + " of " + path + " is different from what is expected"); + } + + assertEquals(expectedLines.length, outputLines.length); + + JavaParserFacade.clearInstances(); + + // If we need to update the file uncomment these lines + //PrintWriter writer = new PrintWriter(dstFile.getAbsoluteFile(), "UTF-8"); + //writer.print(output); + //writer.close(); + } + + @Test + void parsePositionUtils() throws IOException { + parse("com/github/javaparser/PositionUtils"); + } + + @Test + void parseJavaParser() throws IOException { + parse("com/github/javaparser/JavaParser"); + } + + @Test + void parseStatement() throws IOException { + parse("com/github/javaparser/ast/stmt/Statement"); + } + + @Test + void parseCatchClause() throws IOException { + parse("com/github/javaparser/ast/stmt/CatchClause"); + } + + @Test + void parseStatements() throws IOException { + parse("com/github/javaparser/ast/stmt/LabeledStmt"); + parse("com/github/javaparser/ast/stmt/BreakStmt"); + parse("com/github/javaparser/ast/stmt/ReturnStmt"); + parse("com/github/javaparser/ast/stmt/DoStmt"); + parse("com/github/javaparser/ast/stmt/AssertStmt"); + parse("com/github/javaparser/ast/stmt/ContinueStmt"); + parse("com/github/javaparser/ast/stmt/BlockStmt"); + parse("com/github/javaparser/ast/stmt/ExplicitConstructorInvocationStmt"); + parse("com/github/javaparser/ast/stmt/ExpressionStmt"); + parse("com/github/javaparser/ast/stmt/EmptyStmt"); + parse("com/github/javaparser/ast/stmt/SwitchStmt"); + parse("com/github/javaparser/ast/stmt/IfStmt"); + parse("com/github/javaparser/ast/stmt/SwitchEntryStmt"); + parse("com/github/javaparser/ast/stmt/SynchronizedStmt"); + parse("com/github/javaparser/ast/stmt/ForeachStmt"); + parse("com/github/javaparser/ast/stmt/ForStmt"); + parse("com/github/javaparser/ast/stmt/WhileStmt"); + parse("com/github/javaparser/ast/stmt/ThrowStmt"); + parse("com/github/javaparser/ast/stmt/TryStmt"); + parse("com/github/javaparser/ast/stmt/TypeDeclarationStmt"); + } + + @Test + void parseExpressions() throws IOException { + parse("com/github/javaparser/ast/expr/NameExpr"); + parse("com/github/javaparser/ast/expr/FieldAccessExpr"); + parse("com/github/javaparser/ast/expr/CharLiteralExpr"); + parse("com/github/javaparser/ast/expr/IntegerLiteralMinValueExpr"); + parse("com/github/javaparser/ast/expr/IntegerLiteralExpr"); + parse("com/github/javaparser/ast/expr/ArrayCreationExpr"); + parse("com/github/javaparser/ast/expr/VariableDeclarationExpr"); + parse("com/github/javaparser/ast/expr/SuperExpr"); + parse("com/github/javaparser/ast/expr/ArrayInitializerExpr"); + parse("com/github/javaparser/ast/expr/EnclosedExpr"); + parse("com/github/javaparser/ast/expr/Expression"); + parse("com/github/javaparser/ast/expr/SingleMemberAnnotationExpr"); + parse("com/github/javaparser/ast/expr/MethodReferenceExpr"); + parse("com/github/javaparser/ast/expr/ThisExpr"); + parse("com/github/javaparser/ast/expr/LiteralExpr"); + parse("com/github/javaparser/ast/expr/AnnotationExpr"); + parse("com/github/javaparser/ast/expr/InstanceOfExpr"); + parse("com/github/javaparser/ast/expr/LongLiteralExpr"); + parse("com/github/javaparser/ast/expr/StringLiteralExpr"); + parse("com/github/javaparser/ast/expr/NullLiteralExpr"); + parse("com/github/javaparser/ast/expr/ObjectCreationExpr"); + parse("com/github/javaparser/ast/expr/TypeExpr"); + parse("com/github/javaparser/ast/expr/DoubleLiteralExpr"); + parse("com/github/javaparser/ast/expr/LongLiteralMinValueExpr"); + parse("com/github/javaparser/ast/expr/MarkerAnnotationExpr"); + parse("com/github/javaparser/ast/expr/LambdaExpr"); + parse("com/github/javaparser/ast/expr/AssignExpr"); + parse("com/github/javaparser/ast/expr/NormalAnnotationExpr"); + parse("com/github/javaparser/ast/expr/QualifiedNameExpr"); + parse("com/github/javaparser/ast/expr/MemberValuePair"); + parse("com/github/javaparser/ast/expr/ArrayAccessExpr"); + parse("com/github/javaparser/ast/expr/ClassExpr"); + parse("com/github/javaparser/ast/expr/MethodCallExpr"); + parse("com/github/javaparser/ast/expr/ConditionalExpr"); + parse("com/github/javaparser/ast/expr/CastExpr"); + parse("com/github/javaparser/ast/expr/BooleanLiteralExpr"); + parse("com/github/javaparser/ast/expr/BinaryExpr"); + parse("com/github/javaparser/ast/expr/UnaryExpr"); + } + + @Test + void parseTypes() throws IOException { + parse("com/github/javaparser/ast/type/ClassOrInterfaceType"); + parse("com/github/javaparser/ast/type/PrimitiveType"); + parse("com/github/javaparser/ast/type/WildcardType"); + parse("com/github/javaparser/ast/type/UnknownType"); + parse("com/github/javaparser/ast/type/ReferenceType"); + parse("com/github/javaparser/ast/type/VoidType"); + parse("com/github/javaparser/ast/type/Type"); + } + + @Test + void parseVisitors() throws IOException { + parse("com/github/javaparser/ast/visitor/EqualsVisitor"); + parse("com/github/javaparser/ast/visitor/ModifierVisitorAdapter"); + parse("com/github/javaparser/ast/visitor/DumpVisitor"); + parse("com/github/javaparser/ast/visitor/VoidVisitor"); + parse("com/github/javaparser/ast/visitor/GenericVisitor"); + parse("com/github/javaparser/ast/visitor/VoidVisitorAdapter"); + parse("com/github/javaparser/ast/visitor/GenericVisitorAdapter"); + } + + @Test + void parseCloneVisitor() throws IOException { + parse("com/github/javaparser/ast/visitor/CloneVisitor"); + } + + @Test + void parseSourcesHelper() throws IOException { + parse("com/github/javaparser/SourcesHelper"); + } + + @Test + void parseComments() throws IOException { + parse("com/github/javaparser/ast/comments/LineComment"); + parse("com/github/javaparser/ast/comments/Comment"); + parse("com/github/javaparser/ast/comments/CommentsParser"); + parse("com/github/javaparser/ast/comments/JavadocComment"); + parse("com/github/javaparser/ast/comments/BlockComment"); + parse("com/github/javaparser/ast/comments/CommentsCollection"); + } + + @Test + void parseTheRest() throws IOException { + parse("com/github/javaparser/ast/internal/Utils"); + parse("com/github/javaparser/ast/body/AnnotationMemberDeclaration"); + parse("com/github/javaparser/ast/body/EnumDeclaration"); + parse("com/github/javaparser/ast/body/Parameter"); + parse("com/github/javaparser/ast/body/EnumConstantDeclaration"); + parse("com/github/javaparser/ast/body/VariableDeclarator"); + parse("com/github/javaparser/ast/body/TypeDeclaration"); + parse("com/github/javaparser/ast/body/EmptyMemberDeclaration"); + parse("com/github/javaparser/ast/body/ModifierSet"); + parse("com/github/javaparser/ast/body/VariableDeclaratorId"); + parse("com/github/javaparser/ast/body/BaseParameter"); + parse("com/github/javaparser/ast/body/AnnotableNode"); + parse("com/github/javaparser/ast/body/AnnotationDeclaration"); + parse("com/github/javaparser/ast/body/MethodDeclaration"); + parse("com/github/javaparser/ast/body/EmptyTypeDeclaration"); + parse("com/github/javaparser/ast/body/InitializerDeclaration"); + parse("com/github/javaparser/ast/body/BodyDeclaration"); + parse("com/github/javaparser/ast/body/FieldDeclaration"); + parse("com/github/javaparser/ast/body/ConstructorDeclaration"); + parse("com/github/javaparser/ast/body/WithDeclaration"); + parse("com/github/javaparser/ast/body/MultiTypeParameter"); + parse("com/github/javaparser/ast/body/ClassOrInterfaceDeclaration"); + parse("com/github/javaparser/ast/TreeVisitor"); + parse("com/github/javaparser/ast/PackageDeclaration"); + parse("com/github/javaparser/ast/DocumentableNode"); + parse("com/github/javaparser/ast/NamedNode"); + parse("com/github/javaparser/ast/Node"); + parse("com/github/javaparser/ast/AccessSpecifier"); + parse("com/github/javaparser/ast/CompilationUnit"); + parse("com/github/javaparser/ast/TypeParameter"); + parse("com/github/javaparser/ast/ImportDeclaration"); + parse("com/github/javaparser/Position"); + parse("com/github/javaparser/ASTHelper"); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PrintStream` acquired by call to `new()` at line 65 is not released after line 80. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AnalyseJavaParserTest.parse(String) + +### Procedure Id: +com.github.javaparser.symbolsolver.resolution.AnalyseJavaParserTest.parse(java.lang.String):void.95b04767c2e46c44ce608c17cda1a084 + +### File: +javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/AnalyseJavaParserTest.java + +### Key: +AnalyseJavaParserTest.java|parse|RESOURCE_LEAK + +### Node Key: +14442cc3be013c833ab63ae2401ac83a + +### Hash: +7e17745bc02c65d6a68220e6df5b146d + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9966/instruction.md b/inferredbugs-9966/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0a4560c28e67353f8fa85143b09792ebbb0a0de8 --- /dev/null +++ b/inferredbugs-9966/instruction.md @@ -0,0 +1,212 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** javaparser +**Bug ID:** 46 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2015-2016 Federico Tomassetti + * Copyright (C) 2017-2019 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) 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. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser 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. + */ + +package com.github.javaparser.symbolsolver.resolution; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseStart; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.StreamProvider; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.FieldAccessExpr; +import com.github.javaparser.symbolsolver.JavaSymbolSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class InternalClassInInterfaceTest { + + @Test + void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedSamePackage() throws IOException { + File src = new File("src/test/resources/internalClassInInterface"); + File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + + File.separator + "AClass.java"); + + CombinedTypeSolver localCts = new CombinedTypeSolver(); + localCts.add(new ReflectionTypeSolver()); + localCts.add(new JavaParserTypeSolver(src)); + + ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); + JavaParser parser = new JavaParser(parserConfiguration); + StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); + + CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); + Optional fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 4); + + assertTrue(fae.isPresent()); + + assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); + assertEquals("ADDITION", fae.get().resolve().getName()); + } + + @Test + void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedSamePackage() throws IOException { + File src = new File("src/test/resources/internalClassInInterface"); + File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + + File.separator + "AClass.java"); + + CombinedTypeSolver localCts = new CombinedTypeSolver(); + localCts.add(new ReflectionTypeSolver()); + localCts.add(new JavaParserTypeSolver(src)); + + ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); + JavaParser parser = new JavaParser(parserConfiguration); + StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); + + CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); + Optional fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 5); + + assertTrue(fae.isPresent()); + + assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); + assertEquals("ADDITION", fae.get().resolve().getName()); + } + + @Test + void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedDifferentPackage() throws IOException { + File src = new File("src/test/resources/internalClassInInterface"); + File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + + File.separator + "differentpackage" + File.separator + "AClass2.java"); + + CombinedTypeSolver localCts = new CombinedTypeSolver(); + localCts.add(new ReflectionTypeSolver()); + localCts.add(new JavaParserTypeSolver(src)); + + ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); + JavaParser parser = new JavaParser(parserConfiguration); + StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); + + CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); + Optional fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 6); + + assertTrue(fae.isPresent()); + + assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); + assertEquals("ADDITION", fae.get().resolve().getName()); + } + + @Test + void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedDifferentPackage() throws IOException { + File src = new File("src/test/resources/internalClassInInterface"); + File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + + File.separator + "differentpackage" + File.separator + "AClass2.java"); + + CombinedTypeSolver localCts = new CombinedTypeSolver(); + localCts.add(new ReflectionTypeSolver()); + localCts.add(new JavaParserTypeSolver(src)); + + ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); + JavaParser parser = new JavaParser(parserConfiguration); + StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); + + CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); + + Optional fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 7); + + assertTrue(fae.isPresent()); + + assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); + assertEquals("ADDITION", fae.get().resolve().getName()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `StreamProvider(...)` at line 58 is not released after line 60. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void InternalClassInInterfaceTest.resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedSamePackage() + +### Procedure Id: +com.github.javaparser.symbolsolver.resolution.InternalClassInInterfaceTest.resolveFieldOfEnumAsInter.fbb1052e934ddc391d68deb54dd163ed + +### File: +javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/InternalClassInInterfaceTest.java + +### Key: +InternalClassInInterfaceTest.java|resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedSamePackage|RESOURCE_LEAK + +### Node Key: +1e55ee1d1b05fb51bff8a15cb2c0a884 + +### Hash: +761de001e6fad71ecf01d047f67d3a25 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9992/instruction.md b/inferredbugs-9992/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..05d377270349f30d30c82fbf3c66ae5758fa48cb --- /dev/null +++ b/inferredbugs-9992/instruction.md @@ -0,0 +1,231 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** heimdall +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/*- + * =========================LICENSE_START================================== + * heimdall-gateway + * ======================================================================== + * Copyright (C) 2018 Conductor Tecnologia SA + * ======================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==========================LICENSE_END=================================== + */ +package br.com.conductor.heimdall.gateway.filter; + +import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.exception.ExceptionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Component; +import org.springframework.util.StreamUtils; + +import com.netflix.zuul.ZuulFilter; +import com.netflix.zuul.context.RequestContext; + +import br.com.conductor.heimdall.core.util.Constants; +import br.com.conductor.heimdall.core.util.ContentTypeUtils; +import br.com.conductor.heimdall.core.util.UrlUtil; +import br.com.conductor.heimdall.gateway.trace.FilterDetail; +import br.com.conductor.heimdall.gateway.trace.RequestResponseParser; +import br.com.conductor.heimdall.gateway.trace.StackTraceImpl; +import br.com.conductor.heimdall.gateway.trace.TraceContextHolder; +import br.com.conductor.heimdall.middleware.spec.Helper; +import br.com.twsoftware.alfred.object.Objeto; +import lombok.Cleanup; + +/** + * Logs the response to the trace + * + * @author Marcelo Aguiar Rodrigues + */ +@Component +public class LogResponseFilter extends ZuulFilter { + + private FilterDetail detail = new FilterDetail(); + @Autowired + private Helper helper; + + @Override + public int filterOrder() { + + return 102; + } + + @Override + public String filterType() { + + return POST_TYPE; + } + + @Override + public boolean shouldFilter() { + + return true; + } + + @Override + public Object run() { + long startTime = System.currentTimeMillis(); + try { + execute(); + detail.setStatus(Constants.SUCCESS); + } catch (Throwable e) { + detail.setStatus(Constants.FAILED); + TraceContextHolder.getInstance().getActualTrace().setStackTrace(new StackTraceImpl(e.getClass().getName(), e.getMessage(), ExceptionUtils.getStackTrace(e))); + } finally { + long endTime = System.currentTimeMillis(); + + long duration = (endTime - startTime); + + detail.setName(this.getClass().getSimpleName()); + detail.setTimeInMillisRun(duration); + TraceContextHolder.getInstance().getActualTrace().addFilter(detail); + } + return null; + } + + private void execute() throws Throwable { + RequestContext ctx = RequestContext.getCurrentContext(); + + + RequestResponseParser r = new RequestResponseParser(); + r.setUri(UrlUtil.getCurrentUrl(ctx.getRequest())); + + Map headers = getResponseHeaders(ctx); + r.setHeaders(headers); + + String content = headers.get(HttpHeaders.CONTENT_TYPE); + + // if the content type is not defined by api server then permit to read the body. Prevent NPE + if (Objeto.isBlank(content)) content = ""; + + String[] types = content.split(";"); + + if (!ContentTypeUtils.belongsToBlackList(types)) { + @Cleanup + InputStream stream = ctx.getResponseDataStream(); + String body; + + body = StreamUtils.copyToString(stream, StandardCharsets.UTF_8); + + if (body.isEmpty() && helper.call().response().getBody() != null) { + + body = helper.call().response().getBody(); + } + + if (Objects.nonNull(body) && !body.isEmpty()) { + + r.setBody(body); + } + ctx.setResponseDataStream(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8))); + } + TraceContextHolder.getInstance().getActualTrace().setResponse(r); + } + + private Map getResponseHeaders(RequestContext context) { + Map headers = new HashMap<>(); + + final HttpServletResponse response = context.getResponse(); + + context.getZuulResponseHeaders().stream().forEach(pair -> headers.put(pair.first(), pair.second())); + + final Collection headerNames = response.getHeaderNames(); + + headerNames.forEach(s -> headers.putIfAbsent(s, response.getHeader(s))); + + return headers; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `content` last assigned on line 115 could be null and is dereferenced at line 120. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void LogResponseFilter.execute() + +### Procedure Id: +br.com.conductor.heimdall.gateway.filter.LogResponseFilter.execute():void.cff648ce18188cde7f76f946df5ba610 + +### File: +heimdall-gateway/src/main/java/br/com/conductor/heimdall/gateway/filter/LogResponseFilter.java + +### Key: +LogResponseFilter.java|execute|NULL_DEREFERENCE + +### Node Key: +4fcfc07e7017949c61249af151219375 + +### Hash: +5c1cc028612e67d5cf694c939e4a5a2a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9995/instruction.md b/inferredbugs-9995/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d64e2fba506e0c8f78aa3b68298c0742bc728996 --- /dev/null +++ b/inferredbugs-9995/instruction.md @@ -0,0 +1,392 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** heimdall +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java + +package br.com.conductor.heimdall.core.service; + +/*- + * =========================LICENSE_START================================== + * heimdall-core + * ======================================================================== + * Copyright (C) 2018 Conductor Tecnologia SA + * ======================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==========================LICENSE_END=================================== + */ + +import static br.com.conductor.heimdall.core.exception.ExceptionMessage.GLOBAL_RESOURCE_NOT_FOUND; +import static br.com.conductor.heimdall.core.exception.ExceptionMessage.MIDDLEWARE_INVALID_FILE; +import static br.com.conductor.heimdall.core.exception.ExceptionMessage.MIDDLEWARE_UNSUPPORTED_TYPE; +import static br.com.conductor.heimdall.core.exception.ExceptionMessage.ONLY_ONE_MIDDLEWARE_PER_VERSION_AND_API; +import static br.com.twsoftware.alfred.object.Objeto.isBlank; +import static br.com.twsoftware.alfred.object.Objeto.notBlank; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.io.FilenameUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.ExampleMatcher; +import org.springframework.data.domain.ExampleMatcher.StringMatcher; +import org.springframework.data.domain.Page; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import br.com.conductor.heimdall.core.converter.GenericConverter; +import br.com.conductor.heimdall.core.dto.MiddlewareDTO; +import br.com.conductor.heimdall.core.dto.PageDTO; +import br.com.conductor.heimdall.core.dto.PageableDTO; +import br.com.conductor.heimdall.core.dto.page.MiddlewarePage; +import br.com.conductor.heimdall.core.entity.Api; +import br.com.conductor.heimdall.core.entity.Interceptor; +import br.com.conductor.heimdall.core.entity.Middleware; +import br.com.conductor.heimdall.core.enums.Status; +import br.com.conductor.heimdall.core.enums.TypeInterceptor; +import br.com.conductor.heimdall.core.environment.Property; +import br.com.conductor.heimdall.core.exception.ExceptionMessage; +import br.com.conductor.heimdall.core.exception.HeimdallException; +import br.com.conductor.heimdall.core.repository.ApiRepository; +import br.com.conductor.heimdall.core.repository.InterceptorRepository; +import br.com.conductor.heimdall.core.repository.MiddlewareRepository; +import br.com.conductor.heimdall.core.service.amqp.AMQPMiddlewareService; +import br.com.conductor.heimdall.core.util.Pageable; +import br.com.twsoftware.alfred.object.Objeto; +import lombok.extern.slf4j.Slf4j; + +/** + * This class provides methods to create, read, update and delete the {@link Middleware} resource. + * + * @author Filipe Germano + * + */ +@Service +@Slf4j +public class MiddlewareService { + + @Autowired + private MiddlewareRepository middlewareRepository; + + @Autowired + private ApiRepository apiRepository; + + @Autowired + private InterceptorRepository interceptorRepository; + + @Autowired + private Property property; + + @Value("${zuul.filter.root}") + private String root; + + @Autowired + private AMQPMiddlewareService amqpMiddlewareService; + + /** + * Finds a {@link Middleware} by its Id and {@link Api} Id. + * + * @param apiId The {@link Api} Id + * @param middlewareId The {@link Middleware} Id + * @return The {@link Middleware} associated with the {@link Api} + * @throws NotFoundException Resource not found + */ + @Transactional(readOnly = true) + public Middleware find(Long apiId, Long middlewareId) { + + Middleware middleware = middlewareRepository.findByApiIdAndId(apiId, middlewareId); + HeimdallException.checkThrow(isBlank(middleware), GLOBAL_RESOURCE_NOT_FOUND); + + return middleware; + } + + /** + * Generates a paged list of the {@link Middleware} associated with a {@link Api}. + * + * @param apiId The ID of the {@link Api} + * @param middlewareDTO The {@link MiddlewareDTO} + * @param pageableDTO The {@link PageableDTO} + * @return A paged {@link Middleware} list as a {@link MiddlewarePage} object + * @throws NotFoundException Resource not found + */ + @Transactional(readOnly = true) + public MiddlewarePage list(Long apiId, MiddlewareDTO middlewareDTO, PageableDTO pageableDTO) { + + Api api = apiRepository.findOne(apiId); + HeimdallException.checkThrow(isBlank(api), GLOBAL_RESOURCE_NOT_FOUND); + + Middleware middleware = GenericConverter.mapper(middlewareDTO, Middleware.class); + Api apiFind = new Api(); + apiFind.setId(apiId); + middleware.setApi(apiFind); + + Example example = Example.of(middleware, ExampleMatcher.matching().withIgnoreCase().withStringMatcher(StringMatcher.CONTAINING)); + + Pageable pageable = Pageable.setPageable(pageableDTO.getOffset(), pageableDTO.getLimit()); + Page page = middlewareRepository.findAll(example, pageable); + + MiddlewarePage middlewarePage = new MiddlewarePage(PageDTO.build(page)); + + return middlewarePage; + } + + /** + * Generates a list of the {@link Middleware} associated with a {@link Api}. + * + * @param apiId The ID of the API + * @param middlewareDTO The middleware DTO + * @return The list of {@link Middleware} + * @throws NotFoundException Resource not found + */ + @Transactional(readOnly = true) + public List list(Long apiId, MiddlewareDTO middlewareDTO) { + + Api api = apiRepository.findOne(apiId); + HeimdallException.checkThrow(isBlank(api), GLOBAL_RESOURCE_NOT_FOUND); + + Middleware middleware = GenericConverter.mapper(middlewareDTO, Middleware.class); + Api apiFind = new Api(); + apiFind.setId(apiId); + middleware.setApi(apiFind); + + Example example = Example.of(middleware, ExampleMatcher.matching().withIgnoreCase().withStringMatcher(StringMatcher.CONTAINING)); + + List middlewares = middlewareRepository.findAll(example); + + return middlewares; + } + + /** + * Save a new {@link Middleware} for a {@link Api}. + * + * @param apiId The {@link Api} Id + * @param middlewareDTO The {@link MiddlewareDTO} + * @param file The packaged {@link Middleware} file + * @return The new {@link Middleware} created + * @throws NotFoundException Resource not found + * @throws BadRequestException Only one middleware per version and api + * @throws BadRequestException File type differs from .jar not supported + * @throws BadRequestException Invalid middleware file + */ + @Transactional + public Middleware save(Long apiId, MiddlewareDTO middlewareDTO, MultipartFile file) { + + List middlewares = updateMiddlewaresStatus(middlewareRepository.findByApiId(apiId)); + + if (Objeto.notBlank(middlewares)) + middlewareRepository.save(middlewares); + + Api api = apiRepository.findOne(apiId); + HeimdallException.checkThrow(isBlank(api), GLOBAL_RESOURCE_NOT_FOUND); + + Middleware resData = middlewareRepository.findByApiIdAndVersion(apiId, middlewareDTO.getVersion()); + HeimdallException.checkThrow(notBlank(resData) && (resData.getApi().getId() == api.getId()), ONLY_ONE_MIDDLEWARE_PER_VERSION_AND_API); + + String type = FilenameUtils.getExtension(file.getOriginalFilename()); + HeimdallException.checkThrow(!("jar".equalsIgnoreCase(type)), MIDDLEWARE_UNSUPPORTED_TYPE); + + Middleware middleware = GenericConverter.mapper(middlewareDTO, Middleware.class); + middleware.setApi(api); + middleware.setPath(root + "/api/" + apiId + "/middleware"); + middleware.setType(type); + try { + + middleware.setFile(file.getBytes()); + } catch (Exception e) { + + log.error(e.getMessage(), e); + HeimdallException.checkThrow(isBlank(api), MIDDLEWARE_INVALID_FILE); + } + + List interceptors = interceptorRepository.findByTypeAndOperationResourceApiId(TypeInterceptor.MIDDLEWARE, middleware.getApi().getId()); + middleware.setInterceptors(interceptors); + middleware = middlewareRepository.save(middleware); + + amqpMiddlewareService.dispatchCreateMiddlewares(middleware.getId()); + + return middleware; + } + + /** + * Updates a middleware by Middleware ID and API ID. + * + * @param apiId The ID of the API + * @param middlewareId The middleware ID + * @param middlewareDTO The middleware DTO + * @return The middleware that was updated + * @throws NotFoundException Resource not found + * @throws BadRequestException Only one middleware per version and api + */ + @Transactional + public Middleware update(Long apiId, Long middlewareId, MiddlewareDTO middlewareDTO) { + + Middleware middleware = middlewareRepository.findByApiIdAndId(apiId, middlewareId); + HeimdallException.checkThrow(isBlank(middleware), GLOBAL_RESOURCE_NOT_FOUND); + + Middleware resData = middlewareRepository.findByApiIdAndVersion(apiId, middlewareDTO.getVersion()); + HeimdallException.checkThrow(notBlank(resData) && (resData.getApi().getId() == middleware.getApi().getId()) && (resData.getId() != middleware.getId()), ONLY_ONE_MIDDLEWARE_PER_VERSION_AND_API); + + middleware = GenericConverter.mapper(middlewareDTO, middleware); + + Boolean deleteDeprecated = property.getMiddlewares().getDeleteDeprecated(); + + if (middleware.getStatus().equals(Status.DEPRECATED)) + if (Objeto.notBlank(deleteDeprecated) && deleteDeprecated) + middleware.setFile(null); + + middleware = middlewareRepository.save(middleware); + + amqpMiddlewareService.dispatchCreateMiddlewares(middlewareId); + + return middleware; + } + + /** + * Deletes a middleware by API ID and middleware ID + * + * @param apiId The ID of the API + * @param middlewareId The middleware ID + * @throws NotFoundException Resource not found + * @throws BadRequestException Middleware still contains interceptors associated + */ + @Transactional + public void delete(Long apiId, Long middlewareId) { + + Middleware middleware = middlewareRepository.findByApiIdAndId(apiId, middlewareId); + HeimdallException.checkThrow(isBlank(middleware), GLOBAL_RESOURCE_NOT_FOUND); + HeimdallException.checkThrow((Objeto.notBlank(middleware.getInterceptors()) && middleware.getInterceptors().size() > 0), ExceptionMessage.MIDDLEWARE_CONTAINS_INTERCEOPTORS); + + amqpMiddlewareService.dispatchRemoveMiddlewares(middleware.getPath()); + middlewareRepository.delete(middleware.getId()); + + } + + /* + * Updates the status of current middleware repository based on the Property settings. + * + * ACTIVE -> changes status to INACTIVE + * + * INACTIVE -> deprecated if number exceeds property allowInactive, + * if deleteDeprecated is true, deletes the middleware file from database + * + * DEPRECATED -> do not change status + */ + private List updateMiddlewaresStatus(List list) { + + if (Objeto.notBlank(list)) { + Map> middlewareMap = list.stream() + .collect(Collectors.groupingBy(Middleware::getStatus)); + + Integer allowInactive = property.getMiddlewares().getAllowInactive(); + Boolean deleteDeprecated = property.getMiddlewares().getDeleteDeprecated(); + + if (Objeto.notBlank(allowInactive) && allowInactive != 0) { + + List active = middlewareMap.get(Status.ACTIVE); + List inactive = middlewareMap.get(Status.INACTIVE); + + active.forEach(m -> m.setStatus(Status.INACTIVE)); + inactive.addAll(active); + inactive.sort((m1, m2) -> m2.getCreationDate().compareTo(m1.getCreationDate())); + + inactive.stream().skip(allowInactive).forEach(m -> { + m.setStatus(Status.DEPRECATED); + if (Objeto.notBlank(deleteDeprecated) && deleteDeprecated) + m.setFile(null); + }); + + } else { + middlewareMap.get(Status.ACTIVE).forEach(m -> m.setStatus(Status.INACTIVE)); + } + + return list; + } + + return null; + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `build(page)` could be null and is dereferenced by call to `MiddlewarePage(...)` at line 137. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +MiddlewarePage MiddlewareService.list(Long,MiddlewareDTO,PageableDTO) + +### Procedure Id: +br.com.conductor.heimdall.core.service.MiddlewareService.list(java.lang.Long,br.com.conductor.heimda.2aa0256b42ba507ea270290eca0d8494 + +### File: +heimdall-core/src/main/java/br/com/conductor/heimdall/core/service/MiddlewareService.java + +### Key: +MiddlewareService.java|list|NULL_DEREFERENCE + +### Node Key: +542279f0032e3bd5e5ff74cff086db2a + +### Hash: +37c8a2d283f5b423683378d02c74daa0 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed.